From 45c906d2ad7aa827cb274b209567633663bc2d6d Mon Sep 17 00:00:00 2001 From: Adam Barth Date: Thu, 1 Oct 2015 09:35:27 -0700 Subject: [PATCH] Make fn3 the default widget framework --- examples/address_book/lib/main.dart | 2 +- examples/demo_launcher/lib/main.dart | 2 +- examples/fitness/lib/main.dart | 2 +- examples/game/example_effect_line.dart | 2 +- examples/game/lib/main.dart | 2 +- examples/game/test_drawatlas.dart | 2 +- examples/game/test_performance.dart | 2 +- examples/hello_world/lib/main.dart | 2 +- examples/mine_digger/lib/main.dart | 2 +- examples/stocks/lib/main.dart | 2 +- examples/widgets/big_switch.dart | 2 +- examples/widgets/card_collection.dart | 2 +- examples/widgets/container.dart | 2 +- examples/widgets/date_picker.dart | 2 +- examples/widgets/drag_and_drop.dart | 2 +- examples/widgets/horizontal_scrolling.dart | 2 +- examples/widgets/navigation.dart | 2 +- examples/widgets/pageable_list.dart | 2 +- examples/widgets/piano.dart | 2 +- examples/widgets/progress_indicator.dart | 2 +- examples/widgets/scale.dart | 2 +- examples/widgets/styled_text.dart | 2 +- examples/widgets/tabs.dart | 2 +- packages/flutter/lib/src/fn3.dart | 54 - .../lib/src/fn3/animated_component.dart | 50 - packages/flutter/lib/src/fn3/basic.dart | 913 ------- packages/flutter/lib/src/fn3/card.dart | 31 - packages/flutter/lib/src/fn3/checkbox.dart | 182 -- packages/flutter/lib/src/fn3/date_picker.dart | 401 --- packages/flutter/lib/src/fn3/dialog.dart | 170 -- packages/flutter/lib/src/fn3/dismissable.dart | 266 -- packages/flutter/lib/src/fn3/drag_target.dart | 217 -- packages/flutter/lib/src/fn3/drawer.dart | 149 -- .../flutter/lib/src/fn3/drawer_divider.dart | 25 - .../flutter/lib/src/fn3/drawer_header.dart | 44 - packages/flutter/lib/src/fn3/drawer_item.dart | 90 - .../flutter/lib/src/fn3/editable_text.dart | 269 -- packages/flutter/lib/src/fn3/flat_button.dart | 38 - .../lib/src/fn3/floating_action_button.dart | 67 - packages/flutter/lib/src/fn3/focus.dart | 224 -- packages/flutter/lib/src/fn3/framework.dart | 1333 ---------- .../flutter/lib/src/fn3/gesture_detector.dart | 230 -- .../lib/src/fn3/homogeneous_viewport.dart | 178 -- packages/flutter/lib/src/fn3/icon.dart | 102 - packages/flutter/lib/src/fn3/icon_button.dart | 35 - packages/flutter/lib/src/fn3/ink_well.dart | 131 - packages/flutter/lib/src/fn3/input.dart | 164 -- packages/flutter/lib/src/fn3/material.dart | 78 - .../flutter/lib/src/fn3/material_button.dart | 55 - packages/flutter/lib/src/fn3/mimic.dart | 87 - .../flutter/lib/src/fn3/mixed_viewport.dart | 592 ----- packages/flutter/lib/src/fn3/navigator.dart | 297 --- packages/flutter/lib/src/fn3/popup_menu.dart | 210 -- .../flutter/lib/src/fn3/popup_menu_item.dart | 37 - .../lib/src/fn3/progress_indicator.dart | 164 -- packages/flutter/lib/src/fn3/radio.dart | 72 - .../flutter/lib/src/fn3/raised_button.dart | 50 - packages/flutter/lib/src/fn3/scaffold.dart | 252 -- packages/flutter/lib/src/fn3/scrollable.dart | 745 ------ packages/flutter/lib/src/fn3/snack_bar.dart | 111 - packages/flutter/lib/src/fn3/switch.dart | 150 -- packages/flutter/lib/src/fn3/tabs.dart | 619 ----- packages/flutter/lib/src/fn3/theme.dart | 30 - packages/flutter/lib/src/fn3/title.dart | 19 - packages/flutter/lib/src/fn3/tool_bar.dart | 89 - packages/flutter/lib/src/fn3/transitions.dart | 171 -- .../lib/src/widgets/animated_component.dart | 55 +- .../lib/src/widgets/animated_container.dart | 232 -- .../flutter/lib/src/{fn3 => widgets}/app.dart | 12 +- packages/flutter/lib/src/widgets/basic.dart | 552 ++--- .../lib/src/{fn3 => widgets}/binding.dart | 2 +- .../flutter/lib/src/widgets/button_base.dart | 46 - .../src/{fn3 => widgets}/button_state.dart | 4 +- packages/flutter/lib/src/widgets/card.dart | 6 +- .../flutter/lib/src/widgets/checkbox.dart | 88 +- .../flutter/lib/src/widgets/date_picker.dart | 130 +- .../lib/src/widgets/default_text_style.dart | 29 - packages/flutter/lib/src/widgets/dialog.dart | 28 +- .../flutter/lib/src/widgets/dismissable.dart | 55 +- .../flutter/lib/src/widgets/drag_target.dart | 189 +- packages/flutter/lib/src/widgets/drawer.dart | 59 +- .../lib/src/widgets/drawer_divider.dart | 8 +- .../lib/src/widgets/drawer_header.dart | 13 +- .../flutter/lib/src/widgets/drawer_item.dart | 48 +- .../lib/src/widgets/editable_text.dart | 149 +- .../flutter/lib/src/widgets/flat_button.dart | 11 +- .../src/widgets/floating_action_button.dart | 34 +- packages/flutter/lib/src/widgets/focus.dart | 122 +- .../flutter/lib/src/widgets/framework.dart | 2178 +++++++---------- .../lib/src/widgets/gesture_detector.dart | 121 +- .../lib/src/widgets/global_key_watcher.dart | 83 - .../lib/src/widgets/homogeneous_viewport.dart | 202 +- packages/flutter/lib/src/widgets/icon.dart | 19 +- .../flutter/lib/src/widgets/icon_button.dart | 8 +- .../flutter/lib/src/widgets/ink_well.dart | 19 +- packages/flutter/lib/src/widgets/input.dart | 131 +- .../flutter/lib/src/widgets/material.dart | 35 +- .../lib/src/widgets/material_button.dart | 37 +- packages/flutter/lib/src/widgets/mimic.dart | 106 +- .../lib/src/widgets/mixed_viewport.dart | 813 +++--- .../flutter/lib/src/widgets/navigator.dart | 405 +-- .../flutter/lib/src/widgets/popup_menu.dart | 109 +- .../lib/src/widgets/popup_menu_item.dart | 45 +- .../lib/src/widgets/progress_indicator.dart | 78 +- packages/flutter/lib/src/widgets/radio.dart | 35 +- .../lib/src/widgets/raised_button.dart | 21 +- .../flutter/lib/src/widgets/scaffold.dart | 95 +- .../flutter/lib/src/widgets/scrollable.dart | 480 ++-- .../flutter/lib/src/widgets/snack_bar.dart | 80 +- packages/flutter/lib/src/widgets/switch.dart | 43 +- packages/flutter/lib/src/widgets/tabs.dart | 130 +- packages/flutter/lib/src/widgets/theme.dart | 10 +- packages/flutter/lib/src/widgets/title.dart | 8 +- .../flutter/lib/src/widgets/tool_bar.dart | 12 +- .../flutter/lib/src/widgets/transitions.dart | 174 +- .../{fn3 => widgets}/unique_component.dart | 2 +- packages/flutter/lib/widgets.dart | 92 +- packages/flutter/lib/widgets_next.dart | 8 - packages/flutter_sprites/lib/skysprites.dart | 2 +- packages/unit/test/widget/align_test.dart | 2 +- packages/unit/test/widget/block_test.dart | 2 +- .../unit/test/widget/box_decoration_test.dart | 2 +- .../unit/test/widget/build_scope_test.dart | 2 +- packages/unit/test/widget/center_test.dart | 2 +- .../unit/test/widget/coordinates_test.dart | 2 +- .../unit/test/widget/date_picker_test.dart | 2 +- .../unit/test/widget/dismissable_test.dart | 2 +- packages/unit/test/widget/draggable_test.dart | 2 +- .../unit/test/widget/duplicate_key_test.dart | 2 +- packages/unit/test/widget/flex_test.dart | 2 +- .../test/widget/gesture_detector_test.dart | 2 +- .../widget/homogeneous_viewport_test.dart | 2 +- packages/unit/test/widget/input_test.dart | 2 +- packages/unit/test/widget/listener_test.dart | 2 +- .../unit/test/widget/mixed_viewport_test.dart | 2 +- .../unit/test/widget/multichild_test.dart | 2 +- packages/unit/test/widget/navigator_test.dart | 2 +- .../unit/test/widget/pageable_list_test.dart | 2 +- .../unit/test/widget/parent_data_test.dart | 2 +- .../test/widget/progress_indicator_test.dart | 2 +- .../widget/render_object_widget_test.dart | 2 +- .../scrollable_list_hit_testing_test.dart | 2 +- .../scrollable_list_horizontal_test.dart | 2 +- .../widget/scrollable_list_vertical_test.dart | 2 +- .../unit/test/widget/set_state_3_test.dart | 2 +- packages/unit/test/widget/set_state_test.dart | 2 +- .../unit/test/widget/snap_scrolling_test.dart | 2 +- packages/unit/test/widget/stack_test.dart | 2 +- .../test/widget/stateful_component_test.dart | 2 +- .../test/widget/stateful_components_test.dart | 2 +- packages/unit/test/widget/syncing_test.dart | 2 +- packages/unit/test/widget/test_widgets.dart | 2 +- packages/unit/test/widget/transform_test.dart | 2 +- packages/unit/test/widget/widget_tester.dart | 2 +- 154 files changed, 3554 insertions(+), 13206 deletions(-) delete mode 100644 packages/flutter/lib/src/fn3.dart delete mode 100644 packages/flutter/lib/src/fn3/animated_component.dart delete mode 100644 packages/flutter/lib/src/fn3/basic.dart delete mode 100644 packages/flutter/lib/src/fn3/card.dart delete mode 100644 packages/flutter/lib/src/fn3/checkbox.dart delete mode 100644 packages/flutter/lib/src/fn3/date_picker.dart delete mode 100644 packages/flutter/lib/src/fn3/dialog.dart delete mode 100644 packages/flutter/lib/src/fn3/dismissable.dart delete mode 100644 packages/flutter/lib/src/fn3/drag_target.dart delete mode 100644 packages/flutter/lib/src/fn3/drawer.dart delete mode 100644 packages/flutter/lib/src/fn3/drawer_divider.dart delete mode 100644 packages/flutter/lib/src/fn3/drawer_header.dart delete mode 100644 packages/flutter/lib/src/fn3/drawer_item.dart delete mode 100644 packages/flutter/lib/src/fn3/editable_text.dart delete mode 100644 packages/flutter/lib/src/fn3/flat_button.dart delete mode 100644 packages/flutter/lib/src/fn3/floating_action_button.dart delete mode 100644 packages/flutter/lib/src/fn3/focus.dart delete mode 100644 packages/flutter/lib/src/fn3/framework.dart delete mode 100644 packages/flutter/lib/src/fn3/gesture_detector.dart delete mode 100644 packages/flutter/lib/src/fn3/homogeneous_viewport.dart delete mode 100644 packages/flutter/lib/src/fn3/icon.dart delete mode 100644 packages/flutter/lib/src/fn3/icon_button.dart delete mode 100644 packages/flutter/lib/src/fn3/ink_well.dart delete mode 100644 packages/flutter/lib/src/fn3/input.dart delete mode 100644 packages/flutter/lib/src/fn3/material.dart delete mode 100644 packages/flutter/lib/src/fn3/material_button.dart delete mode 100644 packages/flutter/lib/src/fn3/mimic.dart delete mode 100644 packages/flutter/lib/src/fn3/mixed_viewport.dart delete mode 100644 packages/flutter/lib/src/fn3/navigator.dart delete mode 100644 packages/flutter/lib/src/fn3/popup_menu.dart delete mode 100644 packages/flutter/lib/src/fn3/popup_menu_item.dart delete mode 100644 packages/flutter/lib/src/fn3/progress_indicator.dart delete mode 100644 packages/flutter/lib/src/fn3/radio.dart delete mode 100644 packages/flutter/lib/src/fn3/raised_button.dart delete mode 100644 packages/flutter/lib/src/fn3/scaffold.dart delete mode 100644 packages/flutter/lib/src/fn3/scrollable.dart delete mode 100644 packages/flutter/lib/src/fn3/snack_bar.dart delete mode 100644 packages/flutter/lib/src/fn3/switch.dart delete mode 100644 packages/flutter/lib/src/fn3/tabs.dart delete mode 100644 packages/flutter/lib/src/fn3/theme.dart delete mode 100644 packages/flutter/lib/src/fn3/title.dart delete mode 100644 packages/flutter/lib/src/fn3/tool_bar.dart delete mode 100644 packages/flutter/lib/src/fn3/transitions.dart delete mode 100644 packages/flutter/lib/src/widgets/animated_container.dart rename packages/flutter/lib/src/{fn3 => widgets}/app.dart (87%) rename packages/flutter/lib/src/{fn3 => widgets}/binding.dart (99%) delete mode 100644 packages/flutter/lib/src/widgets/button_base.dart rename packages/flutter/lib/src/{fn3 => widgets}/button_state.dart (89%) delete mode 100644 packages/flutter/lib/src/widgets/default_text_style.dart delete mode 100644 packages/flutter/lib/src/widgets/global_key_watcher.dart rename packages/flutter/lib/src/{fn3 => widgets}/unique_component.dart (92%) delete mode 100644 packages/flutter/lib/widgets_next.dart diff --git a/examples/address_book/lib/main.dart b/examples/address_book/lib/main.dart index b46dffdc40..636df80513 100644 --- a/examples/address_book/lib/main.dart +++ b/examples/address_book/lib/main.dart @@ -3,7 +3,7 @@ // found in the LICENSE file. import 'package:sky/material.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; class Field extends StatelessComponent { Field({ diff --git a/examples/demo_launcher/lib/main.dart b/examples/demo_launcher/lib/main.dart index 76a3d3dd1e..3a80555ccc 100644 --- a/examples/demo_launcher/lib/main.dart +++ b/examples/demo_launcher/lib/main.dart @@ -5,7 +5,7 @@ import 'package:sky/material.dart'; import 'package:sky/painting.dart'; import 'package:sky/services.dart'; -import 'package:sky/widgets_next.dart'; +import 'package:sky/widgets.dart'; AssetBundle _initBundle() { if (rootBundle != null) diff --git a/examples/fitness/lib/main.dart b/examples/fitness/lib/main.dart index 43e7790885..1f12e111a5 100644 --- a/examples/fitness/lib/main.dart +++ b/examples/fitness/lib/main.dart @@ -8,7 +8,7 @@ import 'package:playfair/playfair.dart' as playfair; import 'package:sky/animation.dart'; import 'package:sky/material.dart'; import 'package:sky/painting.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'user_data.dart'; import 'date_utils.dart'; diff --git a/examples/game/example_effect_line.dart b/examples/game/example_effect_line.dart index fb1bfeea5e..4a6e7cc150 100644 --- a/examples/game/example_effect_line.dart +++ b/examples/game/example_effect_line.dart @@ -1,7 +1,7 @@ import 'package:sky/material.dart'; import 'package:sky/rendering.dart'; import 'package:sky/services.dart'; -import 'package:sky/widgets_next.dart'; +import 'package:sky/widgets.dart'; import 'package:skysprites/skysprites.dart'; AssetBundle _initBundle() { diff --git a/examples/game/lib/main.dart b/examples/game/lib/main.dart index 528e3a1547..a93038d44d 100644 --- a/examples/game/lib/main.dart +++ b/examples/game/lib/main.dart @@ -8,7 +8,7 @@ import 'package:sky/material.dart'; import 'package:sky/painting.dart'; import 'package:sky/rendering.dart'; import 'package:sky/services.dart'; -import 'package:sky/widgets_next.dart'; +import 'package:sky/widgets.dart'; import 'package:skysprites/skysprites.dart'; import 'game_demo.dart'; diff --git a/examples/game/test_drawatlas.dart b/examples/game/test_drawatlas.dart index 85b3bf6cdf..135334eccc 100644 --- a/examples/game/test_drawatlas.dart +++ b/examples/game/test_drawatlas.dart @@ -3,7 +3,7 @@ import 'dart:sky'; import 'package:sky/material.dart'; import 'package:sky/rendering.dart'; import 'package:sky/services.dart'; -import 'package:sky/widgets_next.dart'; +import 'package:sky/widgets.dart'; import 'package:skysprites/skysprites.dart'; AssetBundle _initBundle() { diff --git a/examples/game/test_performance.dart b/examples/game/test_performance.dart index 2d9744df16..5ceab235d4 100644 --- a/examples/game/test_performance.dart +++ b/examples/game/test_performance.dart @@ -4,7 +4,7 @@ import 'dart:math' as math; import 'package:sky/material.dart'; import 'package:sky/rendering.dart'; import 'package:sky/services.dart'; -import 'package:sky/widgets_next.dart'; +import 'package:sky/widgets.dart'; import 'package:skysprites/skysprites.dart'; AssetBundle _initBundle() { diff --git a/examples/hello_world/lib/main.dart b/examples/hello_world/lib/main.dart index 092c8b8095..c3a23d1f76 100644 --- a/examples/hello_world/lib/main.dart +++ b/examples/hello_world/lib/main.dart @@ -2,6 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; void main() => runApp(new Center(child: new Text('Hello, world!'))); diff --git a/examples/mine_digger/lib/main.dart b/examples/mine_digger/lib/main.dart index 91498eb405..8c823d8c50 100644 --- a/examples/mine_digger/lib/main.dart +++ b/examples/mine_digger/lib/main.dart @@ -8,7 +8,7 @@ import 'package:sky/material.dart'; import 'package:sky/painting.dart'; import 'package:sky/rendering.dart'; import 'package:sky/services.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; // Classic minesweeper-inspired game. The mouse controls are standard // except for left + right combo which is not implemented. For touch, diff --git a/examples/stocks/lib/main.dart b/examples/stocks/lib/main.dart index 361c5966de..4b2c1e89c3 100644 --- a/examples/stocks/lib/main.dart +++ b/examples/stocks/lib/main.dart @@ -12,7 +12,7 @@ import 'package:sky/animation.dart'; import 'package:sky/gestures.dart'; import 'package:sky/material.dart'; import 'package:sky/painting.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'stock_data.dart'; diff --git a/examples/widgets/big_switch.dart b/examples/widgets/big_switch.dart index c335b7705a..991ab70b5f 100644 --- a/examples/widgets/big_switch.dart +++ b/examples/widgets/big_switch.dart @@ -3,7 +3,7 @@ // found in the LICENSE file. import 'package:sky/material.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; class BigSwitch extends StatefulComponent { BigSwitch({ this.scale }); diff --git a/examples/widgets/card_collection.dart b/examples/widgets/card_collection.dart index bb84246435..8a69ab8321 100644 --- a/examples/widgets/card_collection.dart +++ b/examples/widgets/card_collection.dart @@ -5,7 +5,7 @@ import 'package:sky/animation.dart'; import 'package:sky/material.dart'; import 'package:sky/painting.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; class CardModel { CardModel(this.value, this.height, this.color); diff --git a/examples/widgets/container.dart b/examples/widgets/container.dart index 02537dc0e0..fbcd0e16ce 100644 --- a/examples/widgets/container.dart +++ b/examples/widgets/container.dart @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; class ContainerApp extends StatelessComponent { Widget build(BuildContext context) { diff --git a/examples/widgets/date_picker.dart b/examples/widgets/date_picker.dart index 42688c409a..5e64a4a87b 100644 --- a/examples/widgets/date_picker.dart +++ b/examples/widgets/date_picker.dart @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:sky/material.dart'; void main() => runApp(new DatePickerDemo()); diff --git a/examples/widgets/drag_and_drop.dart b/examples/widgets/drag_and_drop.dart index a819da298a..02d21e548d 100644 --- a/examples/widgets/drag_and_drop.dart +++ b/examples/widgets/drag_and_drop.dart @@ -5,7 +5,7 @@ import 'package:sky/material.dart'; import 'package:sky/painting.dart'; import 'package:sky/rendering.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; class DragData { DragData(this.text); diff --git a/examples/widgets/horizontal_scrolling.dart b/examples/widgets/horizontal_scrolling.dart index 06a580a3e7..52fae2a1d0 100644 --- a/examples/widgets/horizontal_scrolling.dart +++ b/examples/widgets/horizontal_scrolling.dart @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; class Circle extends StatelessComponent { Circle({ this.margin: EdgeDims.zero }); diff --git a/examples/widgets/navigation.dart b/examples/widgets/navigation.dart index e26d629936..c9dd69b161 100644 --- a/examples/widgets/navigation.dart +++ b/examples/widgets/navigation.dart @@ -3,7 +3,7 @@ // found in the LICENSE file. import 'package:sky/material.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; final Map routes = { '/': (NavigatorState navigator, Route route) => new Container( diff --git a/examples/widgets/pageable_list.dart b/examples/widgets/pageable_list.dart index 2dd6fe6c8c..e9c079cffe 100644 --- a/examples/widgets/pageable_list.dart +++ b/examples/widgets/pageable_list.dart @@ -5,7 +5,7 @@ import 'package:sky/animation.dart'; import 'package:sky/material.dart'; import 'package:sky/painting.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; class CardModel { CardModel(this.value, this.size, this.color); diff --git a/examples/widgets/piano.dart b/examples/widgets/piano.dart index c1d711e54a..98a942c258 100644 --- a/examples/widgets/piano.dart +++ b/examples/widgets/piano.dart @@ -7,7 +7,7 @@ import 'package:sky_services/media/media.mojom.dart'; import 'package:sky/material.dart'; import 'package:sky/rendering.dart'; import 'package:sky/services.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; // All of these sounds are marked as public domain at soundbible. const String chimes = "http://soundbible.com/grab.php?id=2030&type=wav"; diff --git a/examples/widgets/progress_indicator.dart b/examples/widgets/progress_indicator.dart index f62c9e2ef7..1024d37138 100644 --- a/examples/widgets/progress_indicator.dart +++ b/examples/widgets/progress_indicator.dart @@ -4,7 +4,7 @@ import 'package:sky/animation.dart'; import 'package:sky/material.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; class ProgressIndicatorApp extends StatefulComponent { ProgressIndicatorAppState createState() => new ProgressIndicatorAppState(); diff --git a/examples/widgets/scale.dart b/examples/widgets/scale.dart index 64255400b1..679de951e4 100644 --- a/examples/widgets/scale.dart +++ b/examples/widgets/scale.dart @@ -4,7 +4,7 @@ import 'package:sky/material.dart'; import 'package:sky/rendering.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; class ScaleApp extends StatefulComponent { ScaleAppState createState() => new ScaleAppState(); diff --git a/examples/widgets/styled_text.dart b/examples/widgets/styled_text.dart index 6d3b9790bf..94197cb6a1 100644 --- a/examples/widgets/styled_text.dart +++ b/examples/widgets/styled_text.dart @@ -4,7 +4,7 @@ import 'package:sky/material.dart'; import 'package:sky/rendering.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; class StyledTextApp extends StatefulComponent { StyledTextAppState createState() => new StyledTextAppState(); diff --git a/examples/widgets/tabs.dart b/examples/widgets/tabs.dart index a6efa2eabb..0b36e8ae39 100644 --- a/examples/widgets/tabs.dart +++ b/examples/widgets/tabs.dart @@ -4,7 +4,7 @@ import 'package:sky/material.dart'; import 'package:sky/painting.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; class TabbedNavigatorApp extends StatefulComponent { TabbedNavigatorAppState createState() => new TabbedNavigatorAppState(); diff --git a/packages/flutter/lib/src/fn3.dart b/packages/flutter/lib/src/fn3.dart deleted file mode 100644 index ba78185144..0000000000 --- a/packages/flutter/lib/src/fn3.dart +++ /dev/null @@ -1,54 +0,0 @@ -// 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. - -library fn3; - -export 'fn3/animated_component.dart'; -export 'fn3/app.dart'; -export 'fn3/basic.dart'; -export 'fn3/binding.dart'; -export 'fn3/button_state.dart'; -export 'fn3/card.dart'; -export 'fn3/checkbox.dart'; -export 'fn3/date_picker.dart'; -export 'fn3/dialog.dart'; -export 'fn3/dismissable.dart'; -export 'fn3/drag_target.dart'; -export 'fn3/drawer.dart'; -export 'fn3/drawer_divider.dart'; -export 'fn3/drawer_header.dart'; -export 'fn3/drawer_item.dart'; -export 'fn3/editable_text.dart'; -export 'fn3/flat_button.dart'; -export 'fn3/floating_action_button.dart'; -export 'fn3/focus.dart'; -export 'fn3/framework.dart'; -export 'fn3/gesture_detector.dart'; -export 'fn3/homogeneous_viewport.dart'; -export 'fn3/icon.dart'; -export 'fn3/icon_button.dart'; -export 'fn3/ink_well.dart'; -export 'fn3/input.dart'; -export 'fn3/material.dart'; -export 'fn3/material_button.dart'; -export 'fn3/mimic.dart'; -export 'fn3/mixed_viewport.dart'; -export 'fn3/navigator.dart'; -export 'fn3/popup_menu.dart'; -export 'fn3/popup_menu_item.dart'; -export 'fn3/progress_indicator.dart'; -export 'fn3/radio.dart'; -export 'fn3/raised_button.dart'; -export 'fn3/scaffold.dart'; -export 'fn3/scrollable.dart'; -export 'fn3/snack_bar.dart'; -export 'fn3/switch.dart'; -export 'fn3/tabs.dart'; -export 'fn3/theme.dart'; -export 'fn3/title.dart'; -export 'fn3/tool_bar.dart'; -export 'fn3/transitions.dart'; -export 'fn3/unique_component.dart'; - -export 'package:vector_math/vector_math.dart' show Matrix4; diff --git a/packages/flutter/lib/src/fn3/animated_component.dart b/packages/flutter/lib/src/fn3/animated_component.dart deleted file mode 100644 index a795d2c0fe..0000000000 --- a/packages/flutter/lib/src/fn3/animated_component.dart +++ /dev/null @@ -1,50 +0,0 @@ -// 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. - -import 'package:sky/animation.dart'; -import 'package:sky/src/fn3/framework.dart'; - -abstract class AnimatedComponent extends StatefulComponent { - const AnimatedComponent({ Key key, this.direction, this.duration }) : super(key: key); - - final Duration duration; - final Direction direction; -} - -abstract class AnimatedState extends State { - void initState() { - super.initState(); - _performance = new AnimationPerformance(duration: config.duration); - performance.addStatusListener(_handleAnimationStatusChanged); - if (buildDependsOnPerformance) { - performance.addListener(() { - setState(() { - // We don't actually have any state to change, per se, - // we just know that we have in fact changed state. - }); - }); - } - performance.play(config.direction); - } - - void didUpdateConfig(T oldConfig) { - performance.duration = config.duration; - if (config.duration != oldConfig.duration || config.direction != oldConfig.direction) - performance.play(config.direction); - } - - AnimationPerformance get performance => _performance; - AnimationPerformance _performance; - - void _handleAnimationStatusChanged(AnimationStatus status) { - if (status == AnimationStatus.completed) - handleCompleted(); - else if (status == AnimationStatus.dismissed) - handleDismissed(); - } - - bool get buildDependsOnPerformance => false; - void handleCompleted() { } - void handleDismissed() { } -} diff --git a/packages/flutter/lib/src/fn3/basic.dart b/packages/flutter/lib/src/fn3/basic.dart deleted file mode 100644 index 13bd235842..0000000000 --- a/packages/flutter/lib/src/fn3/basic.dart +++ /dev/null @@ -1,913 +0,0 @@ -// 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. - -import 'dart:sky' as sky; - -import 'package:sky/rendering.dart'; -import 'package:sky/services.dart'; -import 'package:sky/src/fn3/framework.dart'; - -export 'package:sky/rendering.dart' show - BackgroundImage, - BlockDirection, - Border, - BorderSide, - BoxConstraints, - BoxDecoration, - BoxDecorationPosition, - BoxShadow, - Color, - EdgeDims, - FlexAlignItems, - FlexDirection, - FlexJustifyContent, - Offset, - Paint, - Path, - Point, - Rect, - ScrollDirection, - Shape, - ShrinkWrap, - Size, - ValueChanged; - - -// PAINTING NODES - -class Opacity extends OneChildRenderObjectWidget { - Opacity({ Key key, this.opacity, Widget child }) - : super(key: key, child: child) { - assert(opacity >= 0.0 && opacity <= 1.0); - } - - final double opacity; - - RenderOpacity createRenderObject() => new RenderOpacity(opacity: opacity); - - void updateRenderObject(RenderOpacity renderObject, Opacity oldWidget) { - renderObject.opacity = opacity; - } -} - -class ColorFilter extends OneChildRenderObjectWidget { - ColorFilter({ Key key, this.color, this.transferMode, Widget child }) - : super(key: key, child: child) { - assert(color != null); - assert(transferMode != null); - } - - final Color color; - final sky.TransferMode transferMode; - - RenderColorFilter createRenderObject() => new RenderColorFilter(color: color, transferMode: transferMode); - - void updateRenderObject(RenderColorFilter renderObject, ColorFilter oldWidget) { - renderObject.color = color; - renderObject.transferMode = transferMode; - } -} - -class DecoratedBox extends OneChildRenderObjectWidget { - DecoratedBox({ - Key key, - this.decoration, - this.position: BoxDecorationPosition.background, - Widget child - }) : super(key: key, child: child) { - assert(decoration != null); - assert(position != null); - } - - final BoxDecoration decoration; - final BoxDecorationPosition position; - - RenderObject createRenderObject() => new RenderDecoratedBox(decoration: decoration, position: position); - - void updateRenderObject(RenderDecoratedBox renderObject, DecoratedBox oldWidget) { - renderObject.decoration = decoration; - renderObject.position = position; - } -} - -class CustomPaint extends OneChildRenderObjectWidget { - CustomPaint({ Key key, this.callback, this.token, Widget child }) - : super(key: key, child: child) { - assert(callback != null); - } - - final CustomPaintCallback callback; - final Object token; // set this to be repainted automatically when the token changes - - RenderCustomPaint createRenderObject() => new RenderCustomPaint(callback: callback); - - void updateRenderObject(RenderCustomPaint renderObject, CustomPaint oldWidget) { - if (oldWidget != null && oldWidget.token != token) - renderObject.markNeedsPaint(); - renderObject.callback = callback; - } - - void didUnmountRenderObject(RenderCustomPaint renderObject) { - renderObject.callback = null; - } -} - -class ClipRect extends OneChildRenderObjectWidget { - ClipRect({ Key key, Widget child }) : super(key: key, child: child); - RenderClipRect createRenderObject() => new RenderClipRect(); -} - -class ClipRRect extends OneChildRenderObjectWidget { - ClipRRect({ Key key, this.xRadius, this.yRadius, Widget child }) - : super(key: key, child: child); - - final double xRadius; - final double yRadius; - - RenderClipRRect createRenderObject() => new RenderClipRRect(xRadius: xRadius, yRadius: yRadius); - - void updateRenderObject(RenderClipRRect renderObject, ClipRRect oldWidget) { - renderObject.xRadius = xRadius; - renderObject.yRadius = yRadius; - } -} - -class ClipOval extends OneChildRenderObjectWidget { - ClipOval({ Key key, Widget child }) : super(key: key, child: child); - RenderClipOval createRenderObject() => new RenderClipOval(); -} - - -// POSITIONING AND SIZING NODES - -class Transform extends OneChildRenderObjectWidget { - Transform({ Key key, this.transform, this.origin, Widget child }) - : super(key: key, child: child) { - assert(transform != null); - } - - final Matrix4 transform; - final Offset origin; - - RenderTransform createRenderObject() => new RenderTransform(transform: transform, origin: origin); - - void updateRenderObject(RenderTransform renderObject, Transform oldWidget) { - renderObject.transform = transform; - renderObject.origin = origin; - } -} - -class Padding extends OneChildRenderObjectWidget { - Padding({ Key key, this.padding, Widget child }) - : super(key: key, child: child) { - assert(padding != null); - } - - final EdgeDims padding; - - RenderPadding createRenderObject() => new RenderPadding(padding: padding); - - void updateRenderObject(RenderPadding renderObject, Padding oldWidget) { - renderObject.padding = padding; - } -} - -class Align extends OneChildRenderObjectWidget { - Align({ - Key key, - this.horizontal: 0.5, - this.vertical: 0.5, - this.shrinkWrap: ShrinkWrap.none, - Widget child - }) : super(key: key, child: child) { - assert(horizontal != null); - assert(vertical != null); - assert(shrinkWrap != null); - } - - final double horizontal; - final double vertical; - final ShrinkWrap shrinkWrap; - - RenderPositionedBox createRenderObject() => new RenderPositionedBox(horizontal: horizontal, vertical: vertical, shrinkWrap: shrinkWrap); - - void updateRenderObject(RenderPositionedBox renderObject, Align oldWidget) { - renderObject.horizontal = horizontal; - renderObject.vertical = vertical; - renderObject.shrinkWrap = shrinkWrap; - } -} - -class Center extends Align { - Center({ Key key, ShrinkWrap shrinkWrap: ShrinkWrap.none, Widget child }) - : super(key: key, shrinkWrap: shrinkWrap, child: child); -} - -class SizedBox extends OneChildRenderObjectWidget { - SizedBox({ Key key, this.width, this.height, Widget child }) - : super(key: key, child: child); - - final double width; - final double height; - - RenderConstrainedBox createRenderObject() => new RenderConstrainedBox( - additionalConstraints: _additionalConstraints - ); - - BoxConstraints get _additionalConstraints { - BoxConstraints result = const BoxConstraints(); - if (width != null) - result = result.tightenWidth(width); - if (height != null) - result = result.tightenHeight(height); - return result; - } - - void updateRenderObject(RenderConstrainedBox renderObject, SizedBox oldWidget) { - renderObject.additionalConstraints = _additionalConstraints; - } -} - -class ConstrainedBox extends OneChildRenderObjectWidget { - ConstrainedBox({ Key key, this.constraints, Widget child }) - : super(key: key, child: child) { - assert(constraints != null); - } - - final BoxConstraints constraints; - - RenderConstrainedBox createRenderObject() => new RenderConstrainedBox(additionalConstraints: constraints); - - void updateRenderObject(RenderConstrainedBox renderObject, ConstrainedBox oldWidget) { - renderObject.additionalConstraints = constraints; - } -} - -class OverflowBox extends OneChildRenderObjectWidget { - OverflowBox({ Key key, this.minWidth, this.maxWidth, this.minHeight, this.maxHeight, Widget child }) - : super(key: key, child: child); - - final double minWidth; - final double maxWidth; - final double minHeight; - final double maxHeight; - - RenderOverflowBox createRenderObject() => new RenderOverflowBox( - minWidth: minWidth, - maxWidth: maxWidth, - minHeight: minHeight, - maxHeight: maxHeight - ); - - void updateRenderObject(RenderOverflowBox renderObject, OverflowBox oldWidget) { - renderObject.minWidth = minWidth; - renderObject.maxWidth = maxWidth; - renderObject.minHeight = minHeight; - renderObject.maxHeight = maxHeight; - } -} - -class AspectRatio extends OneChildRenderObjectWidget { - AspectRatio({ Key key, this.aspectRatio, Widget child }) - : super(key: key, child: child) { - assert(aspectRatio != null); - } - - final double aspectRatio; - - RenderAspectRatio createRenderObject() => new RenderAspectRatio(aspectRatio: aspectRatio); - - void updateRenderObject(RenderAspectRatio renderObject, AspectRatio oldWidget) { - renderObject.aspectRatio = aspectRatio; - } -} - -class IntrinsicWidth extends OneChildRenderObjectWidget { - IntrinsicWidth({ Key key, this.stepWidth, this.stepHeight, Widget child }) - : super(key: key, child: child); - - final double stepWidth; - final double stepHeight; - - RenderIntrinsicWidth createRenderObject() => new RenderIntrinsicWidth(stepWidth: stepWidth, stepHeight: stepHeight); - - void updateRenderObject(RenderIntrinsicWidth renderObject, IntrinsicWidth oldWidget) { - renderObject.stepWidth = stepWidth; - renderObject.stepHeight = stepHeight; - } -} - -class IntrinsicHeight extends OneChildRenderObjectWidget { - IntrinsicHeight({ Key key, Widget child }) : super(key: key, child: child); - RenderIntrinsicHeight createRenderObject() => new RenderIntrinsicHeight(); -} - -class Baseline extends OneChildRenderObjectWidget { - Baseline({ Key key, this.baseline, this.baselineType: TextBaseline.alphabetic, Widget child }) - : super(key: key, child: child) { - assert(baseline != null); - assert(baselineType != null); - } - - final double baseline; // in pixels - final TextBaseline baselineType; - - RenderBaseline createRenderObject() => new RenderBaseline(baseline: baseline, baselineType: baselineType); - - void updateRenderObject(RenderBaseline renderObject, Baseline oldWidget) { - renderObject.baseline = baseline; - renderObject.baselineType = baselineType; - } -} - -class Viewport extends OneChildRenderObjectWidget { - Viewport({ - Key key, - this.scrollDirection: ScrollDirection.vertical, - this.scrollOffset: Offset.zero, - Widget child - }) : super(key: key, child: child) { - assert(scrollDirection != null); - assert(scrollOffset != null); - } - - final ScrollDirection scrollDirection; - final Offset scrollOffset; - - RenderViewport createRenderObject() => new RenderViewport(scrollDirection: scrollDirection, scrollOffset: scrollOffset); - - void updateRenderObject(RenderViewport renderObject, Viewport oldWidget) { - // Order dependency: RenderViewport validates scrollOffset based on scrollDirection. - renderObject.scrollDirection = scrollDirection; - renderObject.scrollOffset = scrollOffset; - } -} - -class SizeObserver extends OneChildRenderObjectWidget { - SizeObserver({ Key key, this.callback, Widget child }) - : super(key: key, child: child) { - assert(callback != null); - } - - final SizeChangedCallback callback; - - RenderSizeObserver createRenderObject() => new RenderSizeObserver(callback: callback); - - void updateRenderObject(RenderSizeObserver renderObject, SizeObserver oldWidget) { - renderObject.callback = callback; - } - - void didUnmountRenderObject(RenderSizeObserver renderObject) { - renderObject.callback = null; - } -} - - -// CONVENIENCE CLASS TO COMBINE COMMON PAINTING, POSITIONING, AND SIZING NODES - -class Container extends StatelessComponent { - - Container({ - Key key, - this.child, - this.constraints, - this.decoration, - this.foregroundDecoration, - this.width, - this.height, - this.margin, - this.padding, - this.transform - }) : super(key: key) { - assert(margin == null || margin.isNonNegative); - assert(padding == null || padding.isNonNegative); - } - - final Widget child; - final BoxConstraints constraints; - final BoxDecoration decoration; - final BoxDecoration foregroundDecoration; - final EdgeDims margin; - final EdgeDims padding; - final Matrix4 transform; - final double width; - final double height; - - EdgeDims get _paddingIncludingBorder { - if (decoration == null || decoration.border == null) - return padding; - EdgeDims borderPadding = decoration.border.dimensions; - if (padding == null) - return borderPadding; - return padding + borderPadding; - } - - Widget build(BuildContext context) { - Widget current = child; - - if (child == null && (width == null || height == null)) - current = new ConstrainedBox(constraints: const BoxConstraints.expand()); - - EdgeDims effectivePadding = _paddingIncludingBorder; - if (effectivePadding != null) - current = new Padding(padding: effectivePadding, child: current); - - if (decoration != null) - current = new DecoratedBox(decoration: decoration, child: current); - - if (foregroundDecoration != null) { - current = new DecoratedBox( - decoration: foregroundDecoration, - position: BoxDecorationPosition.foreground, - child: current - ); - } - - if (width != null || height != null) { - current = new SizedBox( - width: width, - height: height, - child: current - ); - } - - if (constraints != null) - current = new ConstrainedBox(constraints: constraints, child: current); - - if (margin != null) - current = new Padding(padding: margin, child: current); - - if (transform != null) - current = new Transform(transform: transform, child: current); - - return current; - } - -} - - -// LAYOUT NODES - -class BlockBody extends MultiChildRenderObjectWidget { - BlockBody(List children, { - Key key, - this.direction: BlockDirection.vertical - }) : super(key: key, children: children) { - assert(direction != null); - } - - final BlockDirection direction; - - RenderBlock createRenderObject() => new RenderBlock(direction: direction); - - void updateRenderObject(RenderBlock renderObject, BlockBody oldWidget) { - renderObject.direction = direction; - } -} - -class Stack extends MultiChildRenderObjectWidget { - Stack(List children, { Key key }) : super(key: key, children: children); - RenderStack createRenderObject() => new RenderStack(); -} - -class Positioned extends ParentDataWidget { - Positioned({ - Key key, - Widget child, - this.top, - this.right, - this.bottom, - this.left - }) : super(key: key, child: child); - - final double top; - final double right; - final double bottom; - final double left; - - void debugValidateAncestor(Widget ancestor) { - assert(() { - 'Positioned must placed inside a Stack'; - return ancestor is Stack; - }); - } - - void applyParentData(RenderObject renderObject) { - assert(renderObject.parentData is StackParentData); - final StackParentData parentData = renderObject.parentData; - bool needsLayout = false; - - if (parentData.top != top) { - parentData.top = top; - needsLayout = true; - } - - if (parentData.right != right) { - parentData.right = right; - needsLayout = true; - } - - if (parentData.bottom != bottom) { - parentData.bottom = bottom; - needsLayout = true; - } - - if (parentData.left != left) { - parentData.left = left; - needsLayout = true; - } - - if (needsLayout) - renderObject.markNeedsLayout(); - } -} - -class Grid extends MultiChildRenderObjectWidget { - Grid(List children, { Key key, this.maxChildExtent }) - : super(key: key, children: children) { - assert(maxChildExtent != null); - } - - final double maxChildExtent; - - RenderGrid createRenderObject() => new RenderGrid(maxChildExtent: maxChildExtent); - - void updateRenderObject(RenderGrid renderObject, Grid oldWidget) { - renderObject.maxChildExtent = maxChildExtent; - } -} - -class Flex extends MultiChildRenderObjectWidget { - Flex(List children, { - Key key, - this.direction: FlexDirection.horizontal, - this.justifyContent: FlexJustifyContent.start, - this.alignItems: FlexAlignItems.center, - this.textBaseline - }) : super(key: key, children: children) { - assert(direction != null); - assert(justifyContent != null); - assert(alignItems != null); - } - - final FlexDirection direction; - final FlexJustifyContent justifyContent; - final FlexAlignItems alignItems; - final TextBaseline textBaseline; - - RenderFlex createRenderObject() => new RenderFlex(direction: direction, justifyContent: justifyContent, alignItems: alignItems, textBaseline: textBaseline); - - void updateRenderObject(RenderFlex renderObject, Flex oldWidget) { - renderObject.direction = direction; - renderObject.justifyContent = justifyContent; - renderObject.alignItems = alignItems; - renderObject.textBaseline = textBaseline; - } -} - -class Row extends Flex { - Row(List children, { - Key key, - justifyContent: FlexJustifyContent.start, - alignItems: FlexAlignItems.center, - textBaseline - }) : super(children, key: key, direction: FlexDirection.horizontal, justifyContent: justifyContent, alignItems: alignItems, textBaseline: textBaseline); -} - -class Column extends Flex { - Column(List children, { - Key key, - justifyContent: FlexJustifyContent.start, - alignItems: FlexAlignItems.center, - textBaseline - }) : super(children, key: key, direction: FlexDirection.vertical, justifyContent: justifyContent, alignItems: alignItems, textBaseline: textBaseline); -} - -class Flexible extends ParentDataWidget { - Flexible({ Key key, this.flex: 1, Widget child }) - : super(key: key, child: child); - - final int flex; - - void debugValidateAncestor(Widget ancestor) { - assert(() { - 'Flexible must placed inside a Flex'; - return ancestor is Flex; - }); - } - - void applyParentData(RenderObject renderObject) { - assert(renderObject.parentData is FlexParentData); - final FlexParentData parentData = renderObject.parentData; - if (parentData.flex != flex) { - parentData.flex = flex; - renderObject.markNeedsLayout(); - } - } -} - -class Paragraph extends LeafRenderObjectWidget { - Paragraph({ Key key, this.text }) : super(key: key) { - assert(text != null); - } - - final TextSpan text; - - RenderParagraph createRenderObject() => new RenderParagraph(text); - - void updateRenderObject(RenderParagraph renderObject, Paragraph oldWidget) { - renderObject.text = text; - } -} - -class StyledText extends StatelessComponent { - // elements ::= "string" | [ *] - // Where "string" is text to display and text-style is an instance of - // TextStyle. The text-style applies to all of the elements that follow. - StyledText({ this.elements, Key key }) : super(key: key) { - assert(_toSpan(elements) != null); - } - - final dynamic elements; - - TextSpan _toSpan(dynamic element) { - if (element is String) - return new PlainTextSpan(element); - if (element is Iterable) { - dynamic first = element.first; - if (first is! TextStyle) - throw new ArgumentError("First element of Iterable is a ${first.runtimeType} not a TextStyle"); - return new StyledTextSpan(first, element.skip(1).map(_toSpan).toList()); - } - throw new ArgumentError("Element is ${element.runtimeType} not a String or an Iterable"); - } - - Widget build(BuildContext context) { - return new Paragraph(text: _toSpan(elements)); - } -} - -class DefaultTextStyle extends InheritedWidget { - DefaultTextStyle({ - Key key, - this.style, - Widget child - }) : super(key: key, child: child) { - assert(style != null); - assert(child != null); - } - - final TextStyle style; - - static TextStyle of(BuildContext context) { - DefaultTextStyle result = context.inheritedWidgetOfType(DefaultTextStyle); - return result?.style; - } - - bool updateShouldNotify(DefaultTextStyle old) => style != old.style; -} - -class Text extends StatelessComponent { - Text(this.data, { Key key, TextStyle this.style }) : super(key: key) { - assert(data != null); - } - - final String data; - final TextStyle style; - - Widget build(BuildContext context) { - TextSpan text = new PlainTextSpan(data); - TextStyle defaultStyle = DefaultTextStyle.of(context); - TextStyle combinedStyle; - if (defaultStyle != null) { - if (style != null) - combinedStyle = defaultStyle.merge(style); - else - combinedStyle = defaultStyle; - } else { - combinedStyle = style; - } - if (combinedStyle != null) - text = new StyledTextSpan(combinedStyle, [text]); - return new Paragraph(text: text); - } -} - -class Image extends LeafRenderObjectWidget { - Image({ - Key key, - this.image, - this.width, - this.height, - this.colorFilter, - this.fit: ImageFit.scaleDown, - this.repeat: ImageRepeat.noRepeat - }) : super(key: key); - - final sky.Image image; - final double width; - final double height; - final sky.ColorFilter colorFilter; - final ImageFit fit; - final ImageRepeat repeat; - - RenderImage createRenderObject() => new RenderImage( - image: image, - width: width, - height: height, - colorFilter: colorFilter, - fit: fit, - repeat: repeat); - - void updateRenderObject(RenderImage renderObject, Image oldWidget) { - renderObject.image = image; - renderObject.width = width; - renderObject.height = height; - renderObject.colorFilter = colorFilter; - renderObject.fit = fit; - renderObject.repeat = repeat; - } -} - -class ImageListener extends StatefulComponent { - ImageListener({ - Key key, - this.image, - this.width, - this.height, - this.colorFilter, - this.fit: ImageFit.scaleDown, - this.repeat: ImageRepeat.noRepeat - }) : super(key: key) { - assert(image != null); - } - - final ImageResource image; - final double width; - final double height; - final sky.ColorFilter colorFilter; - final ImageFit fit; - final ImageRepeat repeat; - - ImageListenerState createState() => new ImageListenerState(); -} - -class ImageListenerState extends State { - void initState() { - super.initState(); - config.image.addListener(_handleImageChanged); - } - - sky.Image _resolvedImage; - - void _handleImageChanged(sky.Image resolvedImage) { - setState(() { - _resolvedImage = resolvedImage; - }); - } - - void dispose() { - config.image.removeListener(_handleImageChanged); - super.dispose(); - } - - void didUpdateConfig(ImageListener oldConfig) { - if (config.image != oldConfig.image) { - oldConfig.image.removeListener(_handleImageChanged); - config.image.addListener(_handleImageChanged); - } - } - - Widget build(BuildContext context) { - return new Image( - image: _resolvedImage, - width: config.width, - height: config.height, - colorFilter: config.colorFilter, - fit: config.fit, - repeat: config.repeat - ); - } -} - -class NetworkImage extends StatelessComponent { - NetworkImage({ - Key key, - this.src, - this.width, - this.height, - this.colorFilter, - this.fit: ImageFit.scaleDown, - this.repeat: ImageRepeat.noRepeat - }) : super(key: key); - - final String src; - final double width; - final double height; - final sky.ColorFilter colorFilter; - final ImageFit fit; - final ImageRepeat repeat; - - Widget build(BuildContext context) { - return new ImageListener( - image: imageCache.load(src), - width: width, - height: height, - colorFilter: colorFilter, - fit: fit, - repeat: repeat - ); - } -} - -class AssetImage extends StatelessComponent { - AssetImage({ - Key key, - this.name, - this.bundle, - this.width, - this.height, - this.colorFilter, - this.fit: ImageFit.scaleDown, - this.repeat: ImageRepeat.noRepeat - }) : super(key: key); - - final String name; - final AssetBundle bundle; - final double width; - final double height; - final sky.ColorFilter colorFilter; - final ImageFit fit; - final ImageRepeat repeat; - - Widget build(BuildContext context) { - return new ImageListener( - image: bundle.loadImage(name), - width: width, - height: height, - colorFilter: colorFilter, - fit: fit, - repeat: repeat - ); - } -} - - -// EVENT HANDLING - -class Listener extends OneChildRenderObjectWidget { - Listener({ - Key key, - Widget child, - this.onPointerDown, - this.onPointerMove, - this.onPointerUp, - this.onPointerCancel - }): super(key: key, child: child); - - final PointerEventListener onPointerDown; - final PointerEventListener onPointerMove; - final PointerEventListener onPointerUp; - final PointerEventListener onPointerCancel; - - RenderPointerListener createRenderObject() => new RenderPointerListener( - onPointerDown: onPointerDown, - onPointerMove: onPointerMove, - onPointerUp: onPointerUp, - onPointerCancel: onPointerCancel - ); - - void updateRenderObject(RenderPointerListener renderObject, Listener oldWidget) { - renderObject.onPointerDown = onPointerDown; - renderObject.onPointerMove = onPointerMove; - renderObject.onPointerUp = onPointerUp; - renderObject.onPointerCancel = onPointerCancel; - } -} - -class IgnorePointer extends OneChildRenderObjectWidget { - IgnorePointer({ Key key, Widget child, this.ignoring: true }) - : super(key: key, child: child); - - final bool ignoring; - - RenderIgnorePointer createRenderObject() => new RenderIgnorePointer(ignoring: ignoring); - - void updateRenderObject(RenderIgnorePointer renderObject, IgnorePointer oldWidget) { - renderObject.ignoring = ignoring; - } -} - -class MetaData extends OneChildRenderObjectWidget { - MetaData({ Key key, Widget child, this.metaData }) - : super(key: key, child: child); - - final dynamic metaData; - - RenderMetaData createRenderObject() => new RenderMetaData(metaData: metaData); - - void updateRenderObject(RenderMetaData renderObject, MetaData oldWidget) { - renderObject.metaData = metaData; - } -} diff --git a/packages/flutter/lib/src/fn3/card.dart b/packages/flutter/lib/src/fn3/card.dart deleted file mode 100644 index a10e4e90e2..0000000000 --- a/packages/flutter/lib/src/fn3/card.dart +++ /dev/null @@ -1,31 +0,0 @@ -// 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. - -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/material.dart'; - -const EdgeDims _kCardMargins = const EdgeDims.all(4.0); - -/// A material design card -/// -/// -class Card extends StatelessComponent { - const Card({ Key key, this.child, this.color }) : super(key: key); - - final Widget child; - final Color color; - - Widget build(BuildContext context) { - return new Container( - margin: _kCardMargins, - child: new Material( - color: color, - type: MaterialType.card, - level: 2, - child: child - ) - ); - } -} diff --git a/packages/flutter/lib/src/fn3/checkbox.dart b/packages/flutter/lib/src/fn3/checkbox.dart deleted file mode 100644 index 361ef86700..0000000000 --- a/packages/flutter/lib/src/fn3/checkbox.dart +++ /dev/null @@ -1,182 +0,0 @@ -// 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. - -import 'dart:sky' as sky; - -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/theme.dart'; -import 'package:sky/src/rendering/object.dart'; -import 'package:sky/src/rendering/toggleable.dart'; - -export 'package:sky/src/rendering/toggleable.dart' show ValueChanged; - -const double _kMidpoint = 0.5; -const sky.Color _kLightUncheckedColor = const sky.Color(0x8A000000); -const sky.Color _kDarkUncheckedColor = const sky.Color(0xB2FFFFFF); -const double _kEdgeSize = 20.0; -const double _kEdgeRadius = 1.0; - -/// A material design checkbox -/// -/// The checkbox itself does not maintain any state. Instead, when the state of -/// the checkbox changes, the component calls the `onChange` callback. Most -/// components that use a checkbox will listen for the `onChange` callback and -/// rebuild the checkbox with a new `value` to update the visual appearance of -/// the checkbox. -/// -/// -class Checkbox extends StatelessComponent { - /// Constructs a checkbox - /// - /// * `value` determines whether the checkbox is checked. - /// * `onChanged` is called whenever the state of the checkbox should change. - const Checkbox({Key key, this.value, this.onChanged}) : super(key: key); - - final bool value; - final ValueChanged onChanged; - - Widget build(BuildContext context) { - ThemeData themeData = Theme.of(context); - Color uncheckedColor = themeData.brightness == ThemeBrightness.light - ? _kLightUncheckedColor - : _kDarkUncheckedColor; - return new _CheckboxWrapper( - value: value, - onChanged: onChanged, - uncheckedColor: uncheckedColor, - accentColor: themeData.accentColor - ); - } -} - -// This wrapper class exists only because Switch needs to be a Component in -// order to get an accent color from a Theme but Components do not know how to -// host RenderObjects. -class _CheckboxWrapper extends LeafRenderObjectWidget { - _CheckboxWrapper({ - Key key, - this.value, - this.onChanged, - this.uncheckedColor, - this.accentColor - }): super(key: key) { - assert(uncheckedColor != null); - assert(accentColor != null); - } - - final bool value; - final ValueChanged onChanged; - final Color uncheckedColor; - final Color accentColor; - - _RenderCheckbox createRenderObject() => new _RenderCheckbox( - value: value, - accentColor: accentColor, - uncheckedColor: uncheckedColor, - onChanged: onChanged - ); - - void updateRenderObject(_RenderCheckbox renderObject, _CheckboxWrapper oldWidget) { - renderObject.value = value; - renderObject.onChanged = onChanged; - renderObject.uncheckedColor = uncheckedColor; - renderObject.accentColor = accentColor; - } -} - -class _RenderCheckbox extends RenderToggleable { - _RenderCheckbox({ - bool value, - Color uncheckedColor, - Color accentColor, - ValueChanged onChanged - }): _uncheckedColor = uncheckedColor, - _accentColor = accentColor, - super( - value: value, - onChanged: onChanged, - size: new Size(_kEdgeSize, _kEdgeSize) - ) { - assert(uncheckedColor != null); - assert(accentColor != null); - } - - Color _uncheckedColor; - Color get uncheckedColor => _uncheckedColor; - - void set uncheckedColor(Color value) { - assert(value != null); - if (value == _uncheckedColor) - return; - _uncheckedColor = value; - markNeedsPaint(); - } - - Color _accentColor; - void set accentColor(Color value) { - assert(value != null); - if (value == _accentColor) - return; - _accentColor = value; - markNeedsPaint(); - } - - void paint(PaintingContext context, Offset offset) { - final PaintingCanvas canvas = context.canvas; - // Choose a color between grey and the theme color - sky.Paint paint = new sky.Paint() - ..strokeWidth = 2.0 - ..color = uncheckedColor; - - // The rrect contracts slightly during the animation - double inset = 2.0 - (position - _kMidpoint).abs() * 2.0; - sky.Rect rect = new sky.Rect.fromLTWH(offset.dx + inset, offset.dy + inset, - _kEdgeSize - inset, _kEdgeSize - inset); - sky.RRect rrect = new sky.RRect() - ..setRectXY(rect, _kEdgeRadius, _kEdgeRadius); - - // Outline of the empty rrect - paint.setStyle(sky.PaintingStyle.stroke); - canvas.drawRRect(rrect, paint); - - // Radial gradient that changes size - if (position > 0) { - paint.setStyle(sky.PaintingStyle.fill); - paint.setShader(new sky.Gradient.radial( - new Point(_kEdgeSize / 2.0, _kEdgeSize / 2.0), - _kEdgeSize * (_kMidpoint - position) * 8.0, [ - const sky.Color(0x00000000), - uncheckedColor - ])); - canvas.drawRRect(rrect, paint); - } - - if (position > _kMidpoint) { - double t = (position - _kMidpoint) / (1.0 - _kMidpoint); - - // Solid filled rrect - paint.setStyle(sky.PaintingStyle.strokeAndFill); - paint.color = new Color.fromARGB((t * 255).floor(), _accentColor.red, - _accentColor.green, _accentColor.blue); - canvas.drawRRect(rrect, paint); - - // White inner check - paint.color = const sky.Color(0xFFFFFFFF); - paint.setStyle(sky.PaintingStyle.stroke); - sky.Path path = new sky.Path(); - sky.Point start = new sky.Point(_kEdgeSize * 0.2, _kEdgeSize * 0.5); - sky.Point mid = new sky.Point(_kEdgeSize * 0.4, _kEdgeSize * 0.7); - sky.Point end = new sky.Point(_kEdgeSize * 0.8, _kEdgeSize * 0.3); - Point lerp(Point p1, Point p2, double t) => - new Point(p1.x * (1.0 - t) + p2.x * t, p1.y * (1.0 - t) + p2.y * t); - sky.Point drawStart = lerp(start, mid, 1.0 - t); - sky.Point drawEnd = lerp(mid, end, t); - path.moveTo(offset.dx + drawStart.x, offset.dy + drawStart.y); - path.lineTo(offset.dx + mid.x, offset.dy + mid.y); - path.lineTo(offset.dx + drawEnd.x, offset.dy + drawEnd.y); - canvas.drawPath(path, paint); - } - } -} diff --git a/packages/flutter/lib/src/fn3/date_picker.dart b/packages/flutter/lib/src/fn3/date_picker.dart deleted file mode 100644 index 4e431748c1..0000000000 --- a/packages/flutter/lib/src/fn3/date_picker.dart +++ /dev/null @@ -1,401 +0,0 @@ -// 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. - -import 'dart:async'; - -import 'package:intl/date_symbols.dart'; -import 'package:intl/intl.dart'; -import 'package:sky/material.dart'; -import 'package:sky/painting.dart'; -import 'package:sky/services.dart'; -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/gesture_detector.dart'; -import 'package:sky/src/fn3/ink_well.dart'; -import 'package:sky/src/fn3/scrollable.dart'; -import 'package:sky/src/fn3/theme.dart'; - -typedef void DatePickerValueChanged(DateTime dateTime); - -enum DatePickerMode { day, year } - -typedef void DatePickerModeChanged(DatePickerMode value); - -class DatePicker extends StatefulComponent { - DatePicker({ - this.selectedDate, - this.onChanged, - this.firstDate, - this.lastDate - }) { - assert(selectedDate != null); - assert(firstDate != null); - assert(lastDate != null); - } - - final DateTime selectedDate; - final DatePickerValueChanged onChanged; - final DateTime firstDate; - final DateTime lastDate; - - DatePickerState createState() => new DatePickerState(); -} - -class DatePickerState extends State { - DatePickerMode _mode = DatePickerMode.day; - - void _handleModeChanged(DatePickerMode mode) { - userFeedback.performHapticFeedback(HapticFeedbackType.VIRTUAL_KEY); - setState(() { - _mode = mode; - }); - } - - void _handleYearChanged(DateTime dateTime) { - userFeedback.performHapticFeedback(HapticFeedbackType.VIRTUAL_KEY); - setState(() { - _mode = DatePickerMode.day; - }); - if (config.onChanged != null) - config.onChanged(dateTime); - } - - void _handleDayChanged(DateTime dateTime) { - userFeedback.performHapticFeedback(HapticFeedbackType.VIRTUAL_KEY); - if (config.onChanged != null) - config.onChanged(dateTime); - } - - static const double _calendarHeight = 210.0; - - Widget build(BuildContext context) { - Widget header = new DatePickerHeader( - selectedDate: config.selectedDate, - mode: _mode, - onModeChanged: _handleModeChanged - ); - Widget picker; - switch (_mode) { - case DatePickerMode.day: - picker = new MonthPicker( - selectedDate: config.selectedDate, - onChanged: _handleDayChanged, - firstDate: config.firstDate, - lastDate: config.lastDate, - itemExtent: _calendarHeight - ); - break; - case DatePickerMode.year: - picker = new YearPicker( - selectedDate: config.selectedDate, - onChanged: _handleYearChanged, - firstDate: config.firstDate, - lastDate: config.lastDate - ); - break; - } - return new Column([ - header, - new Container( - height: _calendarHeight, - child: picker - ) - ], alignItems: FlexAlignItems.stretch); - } - -} - -// Shows the selected date in large font and toggles between year and day mode -class DatePickerHeader extends StatelessComponent { - DatePickerHeader({ this.selectedDate, this.mode, this.onModeChanged }) { - assert(selectedDate != null); - assert(mode != null); - } - - DateTime selectedDate; - DatePickerMode mode; - DatePickerModeChanged onModeChanged; - - void _handleChangeMode(DatePickerMode value) { - if (value != mode) - onModeChanged(value); - } - - Widget build(BuildContext context) { - ThemeData theme = Theme.of(context); - TextTheme headerTheme; - Color dayColor; - Color yearColor; - switch(theme.primaryColorBrightness) { - case ThemeBrightness.light: - headerTheme = Typography.black; - dayColor = mode == DatePickerMode.day ? Colors.black87 : Colors.black54; - yearColor = mode == DatePickerMode.year ? Colors.black87 : Colors.black54; - break; - case ThemeBrightness.dark: - headerTheme = Typography.white; - dayColor = mode == DatePickerMode.day ? Colors.white87 : Colors.white54; - yearColor = mode == DatePickerMode.year ? Colors.white87 : Colors.white54; - break; - } - TextStyle dayStyle = headerTheme.display3.copyWith(color: dayColor, height: 1.0, fontSize: 100.0); - TextStyle monthStyle = headerTheme.headline.copyWith(color: dayColor, height: 1.0); - TextStyle yearStyle = headerTheme.headline.copyWith(color: yearColor, height: 1.0); - - return new Container( - padding: new EdgeDims.all(10.0), - decoration: new BoxDecoration(backgroundColor: theme.primaryColor), - child: new Column([ - new GestureDetector( - onTap: () => _handleChangeMode(DatePickerMode.day), - child: new Text(new DateFormat("MMM").format(selectedDate).toUpperCase(), style: monthStyle) - ), - new GestureDetector( - onTap: () => _handleChangeMode(DatePickerMode.day), - child: new Text(new DateFormat("d").format(selectedDate), style: dayStyle) - ), - new GestureDetector( - onTap: () => _handleChangeMode(DatePickerMode.year), - child: new Text(new DateFormat("yyyy").format(selectedDate), style: yearStyle) - ) - ]) - ); - } -} - -// Fixed height component shows a single month and allows choosing a day -class DayPicker extends StatelessComponent { - DayPicker({ - this.selectedDate, - this.currentDate, - this.onChanged, - this.displayedMonth - }) { - assert(selectedDate != null); - assert(currentDate != null); - assert(onChanged != null); - assert(displayedMonth != null); - } - - final DateTime selectedDate; - final DateTime currentDate; - final DatePickerValueChanged onChanged; - final DateTime displayedMonth; - - Widget build(BuildContext context) { - ThemeData theme = Theme.of(context); - TextStyle headerStyle = theme.text.caption.copyWith(fontWeight: FontWeight.w700); - TextStyle monthStyle = headerStyle.copyWith(fontSize: 14.0, height: 24.0 / 14.0); - TextStyle dayStyle = headerStyle.copyWith(fontWeight: FontWeight.w500); - DateFormat dateFormat = new DateFormat(); - DateSymbols symbols = dateFormat.dateSymbols; - - List headers = []; - for (String weekDay in symbols.NARROWWEEKDAYS) { - headers.add(new Text(weekDay, style: headerStyle)); - } - List rows = [ - new Text(new DateFormat("MMMM y").format(displayedMonth), style: monthStyle), - new Flex( - headers, - justifyContent: FlexJustifyContent.spaceAround - ) - ]; - int year = displayedMonth.year; - int month = displayedMonth.month; - // Dart's Date time constructor is very forgiving and will understand - // month 13 as January of the next year. :) - int daysInMonth = new DateTime(year, month + 1).difference(new DateTime(year, month)).inDays; - int firstDay = new DateTime(year, month).day; - int weeksShown = 6; - List days = [ - DateTime.SUNDAY, - DateTime.MONDAY, - DateTime.TUESDAY, - DateTime.WEDNESDAY, - DateTime.THURSDAY, - DateTime.FRIDAY, - DateTime.SATURDAY - ]; - int daySlots = weeksShown * days.length; - List labels = []; - for (int i = 0; i < daySlots; i++) { - // This assumes a start day of SUNDAY, but could be changed. - int day = i - firstDay + 1; - Widget item; - if (day < 1 || day > daysInMonth) { - item = new Text(""); - } else { - // Put a light circle around the selected day - BoxDecoration decoration = null; - if (selectedDate.year == year && - selectedDate.month == month && - selectedDate.day == day) - decoration = new BoxDecoration( - backgroundColor: theme.primarySwatch[100], - shape: Shape.circle - ); - - // Use a different font color for the current day - TextStyle itemStyle = dayStyle; - if (currentDate.year == year && - currentDate.month == month && - currentDate.day == day) - itemStyle = itemStyle.copyWith(color: theme.primaryColor); - - item = new GestureDetector( - onTap: () { - DateTime result = new DateTime(year, month, day); - onChanged(result); - }, - child: new Container( - height: 30.0, - decoration: decoration, - child: new Center( - child: new Text(day.toString(), style: itemStyle) - ) - ) - ); - } - labels.add(new Flexible(child: item)); - } - for (int w = 0; w < weeksShown; w++) { - int startIndex = w * days.length; - rows.add(new Row( - labels.sublist(startIndex, startIndex + days.length) - )); - } - - return new Column(rows); - } -} - -// Scrollable list of DayPickers to allow choosing a month -class MonthPicker extends ScrollableWidgetList { - MonthPicker({ - this.selectedDate, - this.onChanged, - this.firstDate, - this.lastDate, - double itemExtent - }) : super(itemExtent: itemExtent) { - assert(selectedDate != null); - assert(onChanged != null); - assert(lastDate.isAfter(firstDate)); - } - - final DateTime selectedDate; - final DatePickerValueChanged onChanged; - final DateTime firstDate; - final DateTime lastDate; - - MonthPickerState createState() => new MonthPickerState(); -} - -class MonthPickerState extends ScrollableWidgetListState { - void initState() { - super.initState(); - _updateCurrentDate(); - } - - DateTime _currentDate; - Timer _timer; - - void _updateCurrentDate() { - _currentDate = new DateTime.now(); - DateTime tomorrow = new DateTime(_currentDate.year, _currentDate.month, _currentDate.day + 1); - Duration timeUntilTomorrow = tomorrow.difference(_currentDate); - timeUntilTomorrow += const Duration(seconds: 1); // so we don't miss it by rounding - if (_timer != null) - _timer.cancel(); - _timer = new Timer(timeUntilTomorrow, () { - setState(() { - _updateCurrentDate(); - }); - }); - } - - int get itemCount => (config.lastDate.year - config.firstDate.year) * 12 + config.lastDate.month - config.firstDate.month + 1; - - List buildItems(BuildContext context, int start, int count) { - List result = new List(); - DateTime startDate = new DateTime(config.firstDate.year + start ~/ 12, config.firstDate.month + start % 12); - for (int i = 0; i < count; ++i) { - DateTime displayedMonth = new DateTime(startDate.year + i ~/ 12, startDate.month + i % 12); - Widget item = new Container( - height: config.itemExtent, - key: new ObjectKey(displayedMonth), - child: new DayPicker( - selectedDate: config.selectedDate, - currentDate: _currentDate, - onChanged: config.onChanged, - displayedMonth: displayedMonth - ) - ); - result.add(item); - } - return result; - } - - void dispose() { - if (_timer != null) - _timer.cancel(); - super.dispose(); - } -} - -// Scrollable list of years to allow picking a year -class YearPicker extends ScrollableWidgetList { - YearPicker({ - this.selectedDate, - this.onChanged, - this.firstDate, - this.lastDate - }) : super(itemExtent: 50.0) { - assert(selectedDate != null); - assert(onChanged != null); - assert(lastDate.isAfter(firstDate)); - } - - final DateTime selectedDate; - final DatePickerValueChanged onChanged; - final DateTime firstDate; - final DateTime lastDate; - - YearPickerState createState() => new YearPickerState(); -} - -class YearPickerState extends ScrollableWidgetListState { - int get itemCount => config.lastDate.year - config.firstDate.year + 1; - - List buildItems(BuildContext context, int start, int count) { - TextStyle style = Theme.of(context).text.body1.copyWith(color: Colors.black54); - List items = new List(); - for(int i = start; i < start + count; i++) { - int year = config.firstDate.year + i; - String label = year.toString(); - Widget item = new GestureDetector( - key: new Key(label), - onTap: () { - DateTime result = new DateTime(year, config.selectedDate.month, config.selectedDate.day); - config.onChanged(result); - }, - child: new InkWell( - child: new Container( - height: config.itemExtent, - decoration: year == config.selectedDate.year ? new BoxDecoration( - backgroundColor: Theme.of(context).primarySwatch[100], - shape: Shape.circle - ) : null, - child: new Center( - child: new Text(label, style: style) - ) - ) - ) - ); - items.add(item); - } - return items; - } -} diff --git a/packages/flutter/lib/src/fn3/dialog.dart b/packages/flutter/lib/src/fn3/dialog.dart deleted file mode 100644 index 4a83b9b25f..0000000000 --- a/packages/flutter/lib/src/fn3/dialog.dart +++ /dev/null @@ -1,170 +0,0 @@ -// 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. - -import 'dart:async'; - -import 'package:sky/animation.dart'; -import 'package:sky/material.dart'; -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/focus.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/gesture_detector.dart'; -import 'package:sky/src/fn3/material.dart'; -import 'package:sky/src/fn3/navigator.dart'; -import 'package:sky/src/fn3/scrollable.dart'; -import 'package:sky/src/fn3/theme.dart'; -import 'package:sky/src/fn3/transitions.dart'; - -typedef Widget DialogBuilder(NavigatorState navigator); - -/// A material design dialog -/// -/// -class Dialog extends StatelessComponent { - Dialog({ - Key key, - this.title, - this.titlePadding, - this.content, - this.contentPadding, - this.actions, - this.onDismiss - }): super(key: key); - - /// The (optional) title of the dialog is displayed in a large font at the top - /// of the dialog. - final Widget title; - - // Padding around the title; uses material design default if none is supplied - // If there is no title, no padding will be provided - final EdgeDims titlePadding; - - /// The (optional) content of the dialog is displayed in the center of the - /// dialog in a lighter font. - final Widget content; - - // Padding around the content; uses material design default if none is supplied - final EdgeDims contentPadding; - - /// The (optional) set of actions that are displayed at the bottom of the - /// dialog. - final List actions; - - /// An (optional) callback that is called when the dialog is dismissed. - final Function onDismiss; - - Color _getColor(BuildContext context) { - switch (Theme.of(context).brightness) { - case ThemeBrightness.light: - return Colors.white; - case ThemeBrightness.dark: - return Colors.grey[800]; - } - } - - Widget build(BuildContext context) { - - List dialogBody = new List(); - - if (title != null) { - EdgeDims padding = titlePadding; - if (padding == null) - padding = new EdgeDims(24.0, 24.0, content == null ? 20.0 : 0.0, 24.0); - dialogBody.add(new Padding( - padding: padding, - child: new DefaultTextStyle( - style: Theme.of(context).text.title, - child: title - ) - )); - } - - if (content != null) { - EdgeDims padding = contentPadding; - if (padding == null) - padding = const EdgeDims(20.0, 24.0, 24.0, 24.0); - dialogBody.add(new Padding( - padding: padding, - child: new DefaultTextStyle( - style: Theme.of(context).text.subhead, - child: content - ) - )); - } - - if (actions != null) { - dialogBody.add(new Container( - child: new Row(actions, - justifyContent: FlexJustifyContent.end - ) - )); - } - - return new Stack([ - new GestureDetector( - onTap: onDismiss, - child: new Container( - decoration: const BoxDecoration( - backgroundColor: const Color(0x7F000000) - ) - ) - ), - new Center( - child: new Container( - margin: new EdgeDims.symmetric(horizontal: 40.0, vertical: 24.0), - child: new ConstrainedBox( - constraints: new BoxConstraints(minWidth: 280.0), - child: new Material( - level: 4, - color: _getColor(context), - child: new IntrinsicWidth( - child: new Block(dialogBody) - ) - ) - ) - ) - ) - ]); - - } -} - -const Duration _kTransitionDuration = const Duration(milliseconds: 150); - -class DialogRoute extends Route { - DialogRoute({ this.completer, this.builder }); - - final Completer completer; - final RouteBuilder builder; - - Duration get transitionDuration => _kTransitionDuration; - bool get opaque => false; - Widget build(Key key, NavigatorState navigator) { - return new FadeTransition( - performance: performance, - opacity: new AnimatedValue(0.0, end: 1.0, curve: easeOut), - child: builder(navigator, this) - ); - } - - void didPop([dynamic result]) { - completer.complete(result); - super.didPop(result); - } -} - -Future showDialog(NavigatorState navigator, DialogBuilder builder) { - Completer completer = new Completer(); - navigator.push(new DialogRoute( - completer: completer, - builder: (navigator, route) { - return new Focus( - key: new GlobalObjectKey(route), - autofocus: true, - child: builder(navigator) - ); - } - )); - return completer.future; -} diff --git a/packages/flutter/lib/src/fn3/dismissable.dart b/packages/flutter/lib/src/fn3/dismissable.dart deleted file mode 100644 index 8dc356e20a..0000000000 --- a/packages/flutter/lib/src/fn3/dismissable.dart +++ /dev/null @@ -1,266 +0,0 @@ -// 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. - -import 'dart:sky' as sky; - -import 'package:sky/animation.dart'; -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/transitions.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/gesture_detector.dart'; - -const Duration _kCardDismissFadeout = const Duration(milliseconds: 200); -const Duration _kCardDismissResize = const Duration(milliseconds: 300); -final Interval _kCardDismissResizeInterval = new Interval(0.4, 1.0); -const double _kMinFlingVelocity = 700.0; -const double _kMinFlingVelocityDelta = 400.0; -const double _kFlingVelocityScale = 1.0 / 300.0; -const double _kDismissCardThreshold = 0.4; - -enum DismissDirection { - vertical, - horizontal, - left, - right, - up, - down -} - -typedef void ResizedCallback(); -typedef void DismissedCallback(); - -class Dismissable extends StatefulComponent { - Dismissable({ - Key key, - this.child, - this.onResized, - this.onDismissed, - this.direction: DismissDirection.horizontal - }) : super(key: key); - - Widget child; - ResizedCallback onResized; - DismissedCallback onDismissed; - DismissDirection direction; - - DismissableState createState() => new DismissableState(); -} - -class DismissableState extends State { - void initState() { - super.initState(); - _fadePerformance = new AnimationPerformance(duration: _kCardDismissFadeout); - _fadePerformance.addStatusListener((AnimationStatus status) { - if (status == AnimationStatus.completed) - _handleFadeCompleted(); - }); - } - - AnimationPerformance _fadePerformance; - AnimationPerformance _resizePerformance; - - Size _size; - double _dragExtent = 0.0; - bool _dragUnderway = false; - - bool get _directionIsYAxis { - return - config.direction == DismissDirection.vertical || - config.direction == DismissDirection.up || - config.direction == DismissDirection.down; - } - - void _handleFadeCompleted() { - if (!_dragUnderway) - _startResizePerformance(); - } - - bool get _isActive { - return _size != null && (_dragUnderway || _fadePerformance.isAnimating); - } - - void _maybeCallOnResized() { - if (config.onResized != null) - config.onResized(); - } - - void _maybeCallOnDismissed() { - if (config.onDismissed != null) - config.onDismissed(); - } - - void _startResizePerformance() { - assert(_size != null); - assert(_fadePerformance != null); - assert(_fadePerformance.isCompleted); - assert(_resizePerformance == null); - - setState(() { - _resizePerformance = new AnimationPerformance() - ..duration = _kCardDismissResize - ..addListener(_handleResizeProgressChanged); - _resizePerformance.play(); - }); - // Our squash curve (ease) does not return v=0.0 for t=0.0, so we - // technically resize on the first frame. To make sure this doesn't confuse - // any other widgets (like MixedViewport, which checks for this kind of - // thing), we report a resize straight away. - _maybeCallOnResized(); - } - - void _handleResizeProgressChanged() { - if (_resizePerformance.isCompleted) - _maybeCallOnDismissed(); - else - _maybeCallOnResized(); - } - - void _handleDragStart() { - if (_fadePerformance.isAnimating) - return; - setState(() { - _dragUnderway = true; - _dragExtent = 0.0; - _fadePerformance.progress = 0.0; - }); - } - - void _handleDragUpdate(double delta) { - if (!_isActive || _fadePerformance.isAnimating) - return; - - double oldDragExtent = _dragExtent; - switch(config.direction) { - case DismissDirection.horizontal: - case DismissDirection.vertical: - _dragExtent += delta; - break; - - case DismissDirection.up: - case DismissDirection.left: - if (_dragExtent + delta < 0) - _dragExtent += delta; - break; - - case DismissDirection.down: - case DismissDirection.right: - if (_dragExtent + delta > 0) - _dragExtent += delta; - break; - } - - if (oldDragExtent.sign != _dragExtent.sign) { - setState(() { - // Rebuild to update the new drag endpoint. - // The sign of _dragExtent is part of our build state; - // the actual value is not, it's just used to configure - // the performances. - }); - } - if (!_fadePerformance.isAnimating) - _fadePerformance.progress = _dragExtent.abs() / (_size.width * _kDismissCardThreshold); - } - - bool _isFlingGesture(sky.Offset velocity) { - double vx = velocity.dx; - double vy = velocity.dy; - if (_directionIsYAxis) { - if (vy.abs() - vx.abs() < _kMinFlingVelocityDelta) - return false; - switch(config.direction) { - case DismissDirection.vertical: - return vy.abs() > _kMinFlingVelocity; - case DismissDirection.up: - return -vy > _kMinFlingVelocity; - default: - return vy > _kMinFlingVelocity; - } - } else { - if (vx.abs() - vy.abs() < _kMinFlingVelocityDelta) - return false; - switch(config.direction) { - case DismissDirection.horizontal: - return vx.abs() > _kMinFlingVelocity; - case DismissDirection.left: - return -vx > _kMinFlingVelocity; - default: - return vx > _kMinFlingVelocity; - } - } - return false; - } - - void _handleDragEnd(sky.Offset velocity) { - if (!_isActive || _fadePerformance.isAnimating) - return; - - setState(() { - _dragUnderway = false; - if (_fadePerformance.isCompleted) { - _startResizePerformance(); - } else if (_isFlingGesture(velocity)) { - double flingVelocity = _directionIsYAxis ? velocity.dy : velocity.dx; - _dragExtent = flingVelocity.sign; - _fadePerformance.fling(velocity: flingVelocity.abs() * _kFlingVelocityScale); - } else { - _fadePerformance.reverse(); - } - }); - } - - void _handleSizeChanged(Size newSize) { - setState(() { - _size = new Size.copy(newSize); - }); - } - - Point get _activeCardDragEndPoint { - if (!_isActive) - return Point.origin; - assert(_size != null); - double extent = _directionIsYAxis ? _size.height : _size.width; - return new Point(_dragExtent.sign * extent * _kDismissCardThreshold, 0.0); - } - - Widget build(BuildContext context) { - if (_resizePerformance != null) { - // make sure you remove this widget once it's been dismissed! - assert(_resizePerformance.status == AnimationStatus.forward); - - AnimatedValue squashAxisExtent = new AnimatedValue( - _directionIsYAxis ? _size.width : _size.height, - end: 0.0, - curve: ease, - interval: _kCardDismissResizeInterval - ); - - return new SquashTransition( - performance: _resizePerformance.view, - width: _directionIsYAxis ? squashAxisExtent : null, - height: !_directionIsYAxis ? squashAxisExtent : null - ); - } - - return new GestureDetector( - onHorizontalDragStart: _directionIsYAxis ? null : _handleDragStart, - onHorizontalDragUpdate: _directionIsYAxis ? null : _handleDragUpdate, - onHorizontalDragEnd: _directionIsYAxis ? null : _handleDragEnd, - onVerticalDragStart: _directionIsYAxis ? _handleDragStart : null, - onVerticalDragUpdate: _directionIsYAxis ? _handleDragUpdate : null, - onVerticalDragEnd: _directionIsYAxis ? _handleDragEnd : null, - child: new SizeObserver( - callback: _handleSizeChanged, - child: new FadeTransition( - performance: _fadePerformance.view, - opacity: new AnimatedValue(1.0, end: 0.0), - child: new SlideTransition( - performance: _fadePerformance.view, - position: new AnimatedValue(Point.origin, end: _activeCardDragEndPoint), - child: config.child - ) - ) - ) - ); - } -} diff --git a/packages/flutter/lib/src/fn3/drag_target.dart b/packages/flutter/lib/src/fn3/drag_target.dart deleted file mode 100644 index 6e18290c91..0000000000 --- a/packages/flutter/lib/src/fn3/drag_target.dart +++ /dev/null @@ -1,217 +0,0 @@ -// 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. - -import 'dart:collection'; -import 'dart:sky' as sky; - -import 'package:sky/rendering.dart'; -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/binding.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/navigator.dart'; - -typedef bool DragTargetWillAccept(T data); -typedef void DragTargetAccept(T data); -typedef Widget DragTargetBuilder(BuildContext context, List candidateData, List rejectedData); -typedef void DragFinishedNotification(); - -class Draggable extends StatefulComponent { - Draggable({ Key key, this.navigator, this.data, this.child, this.feedback }): super(key: key) { - assert(navigator != null); - } - - final NavigatorState navigator; - final dynamic data; - final Widget child; - final Widget feedback; - - DraggableState createState() => new DraggableState(); -} - -class DraggableState extends State { - DragRoute _route; - - void _startDrag(sky.PointerEvent event) { - if (_route != null) - return; // TODO(ianh): once we switch to using gestures, just hand the gesture to the route so it can do everything itself. then we can have multiple drags at the same time. - Point point = new Point(event.x, event.y); - RenderBox renderObject = context.findRenderObject(); - _route = new DragRoute( - data: config.data, - dragStartPoint: renderObject.globalToLocal(point), - feedback: config.feedback, - onDragFinished: () { - _route = null; - } - ); - _route.update(point); - config.navigator.push(_route); - } - - void _updateDrag(sky.PointerEvent event) { - if (_route != null) { - config.navigator.setState(() { - _route.update(new Point(event.x, event.y)); - }); - } - } - - void _cancelDrag(sky.PointerEvent event) { - if (_route != null) { - config.navigator.popRoute(_route, DragEndKind.canceled); - assert(_route == null); - } - } - - void _drop(sky.PointerEvent event) { - if (_route != null) { - _route.update(new Point(event.x, event.y)); - config.navigator.popRoute(_route, DragEndKind.dropped); - assert(_route == null); - } - } - - Widget build(BuildContext context) { - // TODO(abarth): We should be using a GestureDetector - return new Listener( - onPointerDown: _startDrag, - onPointerMove: _updateDrag, - onPointerCancel: _cancelDrag, - onPointerUp: _drop, - child: config.child - ); - } -} - - -class DragTarget extends StatefulComponent { - const DragTarget({ - Key key, - this.builder, - this.onWillAccept, - this.onAccept - }) : super(key: key); - - final DragTargetBuilder builder; - final DragTargetWillAccept onWillAccept; - final DragTargetAccept onAccept; - - DragTargetState createState() => new DragTargetState(); -} - -class DragTargetState extends State> { - final List _candidateData = new List(); - final List _rejectedData = new List(); - - bool didEnter(dynamic data) { - assert(!_candidateData.contains(data)); - assert(!_rejectedData.contains(data)); - if (data is T && (config.onWillAccept == null || config.onWillAccept(data))) { - setState(() { - _candidateData.add(data); - }); - return true; - } - _rejectedData.add(data); - return false; - } - - void didLeave(dynamic data) { - assert(_candidateData.contains(data) || _rejectedData.contains(data)); - setState(() { - _candidateData.remove(data); - _rejectedData.remove(data); - }); - } - - void didDrop(dynamic data) { - assert(_candidateData.contains(data)); - setState(() { - _candidateData.remove(data); - }); - if (config.onAccept != null) - config.onAccept(data); - } - - Widget build(BuildContext context) { - return new MetaData( - metaData: this, - child: config.builder(context, - new UnmodifiableListView(_candidateData), - new UnmodifiableListView(_rejectedData)) - ); - } -} - - -enum DragEndKind { dropped, canceled } - -class DragRoute extends Route { - DragRoute({ this.data, this.dragStartPoint: Point.origin, this.feedback, this.onDragFinished }); - - final dynamic data; - final Point dragStartPoint; - final Widget feedback; - final DragFinishedNotification onDragFinished; - - DragTargetState _activeTarget; - bool _activeTargetWillAcceptDrop = false; - Offset _lastOffset; - - void update(Point globalPosition) { - _lastOffset = globalPosition - dragStartPoint; - HitTestResult result = WidgetFlutterBinding.instance.hitTest(globalPosition); - DragTargetState target = _getDragTarget(result.path); - if (target == _activeTarget) - return; - if (_activeTarget != null) - _activeTarget.didLeave(data); - _activeTarget = target; - _activeTargetWillAcceptDrop = _activeTarget != null && _activeTarget.didEnter(data); - } - - DragTargetState _getDragTarget(List path) { - // TODO(abarth): Why do we reverse the path here? - for (HitTestEntry entry in path.reversed) { - if (entry.target is RenderMetaData) { - RenderMetaData renderMetaData = entry.target; - if (renderMetaData.metaData is DragTargetState) - return renderMetaData.metaData; - } - } - return null; - } - - void didPop([DragEndKind endKind]) { - if (_activeTarget != null) { - if (endKind == DragEndKind.dropped && _activeTargetWillAcceptDrop) - _activeTarget.didDrop(data); - else - _activeTarget.didLeave(data); - } - _activeTarget = null; - _activeTargetWillAcceptDrop = false; - if (onDragFinished != null) - onDragFinished(); - super.didPop(endKind); - } - - bool get ephemeral => true; - bool get modal => false; - - Duration get transitionDuration => const Duration(); - bool get opaque => false; - Widget build(Key key, NavigatorState navigator) { - return new Positioned( - left: _lastOffset.dx, - top: _lastOffset.dy, - child: new IgnorePointer( - child: new Opacity( - opacity: 0.5, - child: feedback - ) - ) - ); - } -} diff --git a/packages/flutter/lib/src/fn3/drawer.dart b/packages/flutter/lib/src/fn3/drawer.dart deleted file mode 100644 index e79187477a..0000000000 --- a/packages/flutter/lib/src/fn3/drawer.dart +++ /dev/null @@ -1,149 +0,0 @@ -// 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. - -import 'dart:async'; - -import 'package:sky/animation.dart'; -import 'package:sky/material.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/gesture_detector.dart'; -import 'package:sky/src/fn3/navigator.dart'; -import 'package:sky/src/fn3/scrollable.dart'; -import 'package:sky/src/fn3/theme.dart'; -import 'package:sky/src/fn3/transitions.dart'; - -// TODO(eseidel): Draw width should vary based on device size: -// http://www.google.com/design/spec/layout/structure.html#structure-side-nav - -// Mobile: -// Width = Screen width − 56 dp -// Maximum width: 320dp -// Maximum width applies only when using a left nav. When using a right nav, -// the panel can cover the full width of the screen. - -// Desktop/Tablet: -// Maximum width for a left nav is 400dp. -// The right nav can vary depending on content. - -const double _kWidth = 304.0; -const double _kMinFlingVelocity = 365.0; -const double _kFlingVelocityScale = 1.0 / 300.0; -const Duration _kBaseSettleDuration = const Duration(milliseconds: 246); -const Duration _kThemeChangeDuration = const Duration(milliseconds: 200); -const Point _kOpenPosition = Point.origin; -const Point _kClosedPosition = const Point(-_kWidth, 0.0); - -typedef void DrawerDismissedCallback(); - -class Drawer extends StatefulComponent { - Drawer({ - Key key, - this.children, - this.showing: false, - this.level: 0, - this.onDismissed, - this.navigator - }) : super(key: key); - - final List children; - final bool showing; - final int level; - final DrawerDismissedCallback onDismissed; - final NavigatorState navigator; - - DrawerState createState() => new DrawerState(); -} - -class DrawerState extends State { - void initState() { - super.initState(); - _performance = new AnimationPerformance(duration: _kBaseSettleDuration); - _performance.addStatusListener((AnimationStatus status) { - if (status == AnimationStatus.dismissed) - _handleDismissed(); - }); - // Use a spring force for animating the drawer. We can't use curves for - // this because we need a linear curve in order to track the user's finger - // while dragging. - _performance.attachedForce = kDefaultSpringForce; - if (config.navigator != null) { - // TODO(ianh): This is crazy. We should convert drawer to use a pattern like openDialog(). - // https://github.com/domokit/sky_engine/pull/1186 - scheduleMicrotask(() { - config.navigator.pushState(this, (_) => _performance.reverse()); - }); - } - _performance.play(_direction); - } - - AnimationPerformance _performance; - - Direction get _direction => config.showing ? Direction.forward : Direction.reverse; - - void didUpdateConfig(Drawer oldConfig) { - if (config.showing != oldConfig.showing) - _performance.play(_direction); - } - - Widget build(BuildContext context) { - var mask = new GestureDetector( - child: new ColorTransition( - performance: _performance.view, - color: new AnimatedColorValue(Colors.transparent, end: const Color(0x7F000000)), - child: new Container() - ), - onTap: () { - _performance.reverse(); - } - ); - - Widget content = new SlideTransition( - performance: _performance.view, - position: new AnimatedValue(_kClosedPosition, end: _kOpenPosition), - // TODO(abarth): Use AnimatedContainer - child: new Container( - // behavior: implicitlyAnimate(const Duration(milliseconds: 200)), - decoration: new BoxDecoration( - backgroundColor: Theme.of(context).canvasColor, - boxShadow: shadows[config.level]), - width: _kWidth, - child: new Block(config.children) - ) - ); - - return new GestureDetector( - onHorizontalDragStart: _performance.stop, - onHorizontalDragUpdate: _handleDragUpdate, - onHorizontalDragEnd: _handleDragEnd, - child: new Stack([ mask, content ]) - ); - } - - void _handleDismissed() { - if (config.navigator != null && - config.navigator.currentRoute is RouteState && - (config.navigator.currentRoute as RouteState).owner == this) // TODO(ianh): remove cast once analyzer is cleverer - config.navigator.pop(); - if (config.onDismissed != null) - config.onDismissed(); - } - - bool get _isMostlyClosed => _performance.progress < 0.5; - - void _settle() { _isMostlyClosed ? _performance.reverse() : _performance.play(); } - - void _handleDragUpdate(double delta) { - _performance.progress += delta / _kWidth; - } - - void _handleDragEnd(Offset velocity) { - if (velocity.dx.abs() >= _kMinFlingVelocity) { - _performance.fling(velocity: velocity.dx * _kFlingVelocityScale); - } else { - _settle(); - } - } - -} diff --git a/packages/flutter/lib/src/fn3/drawer_divider.dart b/packages/flutter/lib/src/fn3/drawer_divider.dart deleted file mode 100644 index 0c0291c0ea..0000000000 --- a/packages/flutter/lib/src/fn3/drawer_divider.dart +++ /dev/null @@ -1,25 +0,0 @@ -// 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. - -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/theme.dart'; - -class DrawerDivider extends StatelessComponent { - const DrawerDivider({ Key key }) : super(key: key); - - Widget build(BuildContext context) { - return new Container( - height: 0.0, - decoration: new BoxDecoration( - border: new Border( - bottom: new BorderSide( - color: Theme.of(context).dividerColor - ) - ) - ), - margin: const EdgeDims.symmetric(vertical: 8.0) - ); - } -} diff --git a/packages/flutter/lib/src/fn3/drawer_header.dart b/packages/flutter/lib/src/fn3/drawer_header.dart deleted file mode 100644 index b948dfca52..0000000000 --- a/packages/flutter/lib/src/fn3/drawer_header.dart +++ /dev/null @@ -1,44 +0,0 @@ -// 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. - -import 'package:sky/material.dart'; -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/theme.dart'; - -// TODO(jackson): This class should usually render the user's -// preferred banner image rather than a solid background - -class DrawerHeader extends StatelessComponent { - const DrawerHeader({ Key key, this.child }) : super(key: key); - - final Widget child; - - Widget build(BuildContext context) { - return new Container( - height: kStatusBarHeight + kMaterialDrawerHeight, - decoration: new BoxDecoration( - backgroundColor: Theme.of(context).cardColor, - border: const Border( - bottom: const BorderSide( - color: const Color(0xFFD1D9E1), - width: 1.0 - ) - ) - ), - padding: const EdgeDims.only(bottom: 7.0), - margin: const EdgeDims.only(bottom: 8.0), - child: new Column([ - new Flexible(child: new Container()), - new Container( - padding: const EdgeDims.symmetric(horizontal: 16.0), - child: new DefaultTextStyle( - style: Theme.of(context).text.body2, - child: child - ) - )] - ) - ); - } -} diff --git a/packages/flutter/lib/src/fn3/drawer_item.dart b/packages/flutter/lib/src/fn3/drawer_item.dart deleted file mode 100644 index fe8a87e14e..0000000000 --- a/packages/flutter/lib/src/fn3/drawer_item.dart +++ /dev/null @@ -1,90 +0,0 @@ -// 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. - -import 'dart:sky' as sky; - -import 'package:sky/gestures.dart'; -import 'package:sky/material.dart'; -import 'package:sky/painting.dart'; -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/button_state.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/gesture_detector.dart'; -import 'package:sky/src/fn3/icon.dart'; -import 'package:sky/src/fn3/ink_well.dart'; -import 'package:sky/src/fn3/theme.dart'; - -class DrawerItem extends StatefulComponent { - const DrawerItem({ Key key, this.icon, this.child, this.onPressed, this.selected: false }) - : super(key: key); - - final String icon; - final Widget child; - final GestureTapListener onPressed; - final bool selected; - - DrawerItemState createState() => new DrawerItemState(); -} - -class DrawerItemState extends ButtonState { - TextStyle _getTextStyle(ThemeData themeData) { - TextStyle result = themeData.text.body2; - if (config.selected) - result = result.copyWith(color: themeData.primaryColor); - return result; - } - - Color _getBackgroundColor(ThemeData themeData) { - if (highlight) - return themeData.highlightColor; - if (config.selected) - return themeData.selectedColor; - return Colors.transparent; - } - - sky.ColorFilter _getColorFilter(ThemeData themeData) { - if (config.selected) - return new sky.ColorFilter.mode(themeData.primaryColor, sky.TransferMode.srcATop); - return new sky.ColorFilter.mode(const Color(0x73000000), sky.TransferMode.dstIn); - } - - Widget buildContent(BuildContext context) { - ThemeData themeData = Theme.of(context); - - List flexChildren = new List(); - if (config.icon != null) { - flexChildren.add( - new Padding( - padding: const EdgeDims.symmetric(horizontal: 16.0), - child: new Icon( - type: config.icon, - size: 24, - colorFilter: _getColorFilter(themeData)) - ) - ); - } - flexChildren.add( - new Flexible( - child: new Padding( - padding: const EdgeDims.symmetric(horizontal: 16.0), - child: new DefaultTextStyle( - style: _getTextStyle(themeData), - child: config.child - ) - ) - ) - ); - - return new GestureDetector( - onTap: config.onPressed, - child: new Container( - height: 48.0, - decoration: new BoxDecoration(backgroundColor: _getBackgroundColor(themeData)), - child: new InkWell( - child: new Row(flexChildren) - ) - ) - ); - } -} diff --git a/packages/flutter/lib/src/fn3/editable_text.dart b/packages/flutter/lib/src/fn3/editable_text.dart deleted file mode 100644 index fd685b7feb..0000000000 --- a/packages/flutter/lib/src/fn3/editable_text.dart +++ /dev/null @@ -1,269 +0,0 @@ -// 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. - -import 'dart:async'; - -import 'package:mojo_services/keyboard/keyboard.mojom.dart'; -import 'package:sky/painting.dart'; -import 'package:sky/rendering.dart'; -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/framework.dart'; - -const _kCursorBlinkPeriod = 500; // milliseconds - -typedef void StringUpdated(); - -class TextRange { - final int start; - final int end; - - TextRange({this.start, this.end}); - TextRange.collapsed(int position) - : start = position, - end = position; - const TextRange.empty() - : start = -1, - end = -1; - - bool get isValid => start >= 0 && end >= 0; - bool get isCollapsed => start == end; -} - -class EditableString implements KeyboardClient { - String text; - TextRange composing = const TextRange.empty(); - TextRange selection = const TextRange.empty(); - - final StringUpdated onUpdated; - - KeyboardClientStub stub; - - EditableString({this.text: '', this.onUpdated}) { - stub = new KeyboardClientStub.unbound()..impl = this; - } - - String textBefore(TextRange range) { - return text.substring(0, range.start); - } - - String textAfter(TextRange range) { - return text.substring(range.end); - } - - String textInside(TextRange range) { - return text.substring(range.start, range.end); - } - - void _delete(TextRange range) { - if (range.isCollapsed || !range.isValid) return; - text = textBefore(range) + textAfter(range); - } - - TextRange _append(String newText) { - int start = text.length; - text += newText; - return new TextRange(start: start, end: start + newText.length); - } - - TextRange _replace(TextRange range, String newText) { - assert(range.isValid); - - String before = textBefore(range); - String after = textAfter(range); - - text = before + newText + after; - return new TextRange( - start: before.length, end: before.length + newText.length); - } - - TextRange _replaceOrAppend(TextRange range, String newText) { - if (!range.isValid) return _append(newText); - return _replace(range, newText); - } - - void commitCompletion(CompletionData completion) { - // TODO(abarth): Not implemented. - } - - void commitCorrection(CorrectionData correction) { - // TODO(abarth): Not implemented. - } - - void commitText(String text, int newCursorPosition) { - // TODO(abarth): Why is |newCursorPosition| always 1? - TextRange committedRange = _replaceOrAppend(composing, text); - selection = new TextRange.collapsed(committedRange.end); - composing = const TextRange.empty(); - onUpdated(); - } - - void deleteSurroundingText(int beforeLength, int afterLength) { - TextRange beforeRange = new TextRange( - start: selection.start - beforeLength, end: selection.start); - TextRange afterRange = - new TextRange(start: selection.end, end: selection.end + afterLength); - _delete(afterRange); - _delete(beforeRange); - selection = new TextRange( - start: selection.start - beforeLength, - end: selection.end - beforeLength); - onUpdated(); - } - - void setComposingRegion(int start, int end) { - composing = new TextRange(start: start, end: end); - onUpdated(); - } - - void setComposingText(String text, int newCursorPosition) { - // TODO(abarth): Why is |newCursorPosition| always 1? - composing = _replaceOrAppend(composing, text); - selection = new TextRange.collapsed(composing.end); - onUpdated(); - } - - void setSelection(int start, int end) { - selection = new TextRange(start: start, end: end); - onUpdated(); - } -} - -class EditableText extends StatefulComponent { - EditableText({ - Key key, - this.value, - this.focused: false, - this.style, - this.cursorColor, - this.onContentSizeChanged, - this.scrollOffset - }) : super(key: key); - - final EditableString value; - final bool focused; - final TextStyle style; - final Color cursorColor; - final SizeChangedCallback onContentSizeChanged; - final Offset scrollOffset; - - EditableTextState createState() => new EditableTextState(); -} - -class EditableTextState extends State { - Timer _cursorTimer; - bool _showCursor = false; - - /// Whether the blinking cursor is visible (exposed for testing). - bool get test_showCursor => _showCursor; - - /// The cursor blink interval (exposed for testing). - Duration get test_cursorBlinkPeriod => - new Duration(milliseconds: _kCursorBlinkPeriod); - - void _cursorTick(Timer timer) { - setState(() { - _showCursor = !_showCursor; - }); - } - - void _startCursorTimer() { - _showCursor = true; - _cursorTimer = new Timer.periodic( - new Duration(milliseconds: _kCursorBlinkPeriod), _cursorTick); - } - - void dispose() { - if (_cursorTimer != null) - _stopCursorTimer(); - super.dispose(); - } - - void _stopCursorTimer() { - _cursorTimer.cancel(); - _cursorTimer = null; - _showCursor = false; - } - - Widget build(BuildContext context) { - assert(config.style != null); - assert(config.focused != null); - assert(config.cursorColor != null); - - if (config.focused && _cursorTimer == null) - _startCursorTimer(); - else if (!config.focused && _cursorTimer != null) - _stopCursorTimer(); - - return new SizedBox( - width: double.INFINITY, - child: new _EditableTextWidget( - value: config.value, - style: config.style, - cursorColor: config.cursorColor, - showCursor: _showCursor, - onContentSizeChanged: config.onContentSizeChanged, - scrollOffset: config.scrollOffset - ) - ); - } -} - -class _EditableTextWidget extends LeafRenderObjectWidget { - _EditableTextWidget({ - Key key, - this.value, - this.style, - this.cursorColor, - this.showCursor, - this.onContentSizeChanged, - this.scrollOffset - }) : super(key: key); - - final EditableString value; - final TextStyle style; - final Color cursorColor; - final bool showCursor; - final SizeChangedCallback onContentSizeChanged; - final Offset scrollOffset; - - RenderEditableParagraph createRenderObject() { - return new RenderEditableParagraph( - text: _buildTextSpan(), - cursorColor: cursorColor, - showCursor: showCursor, - onContentSizeChanged: onContentSizeChanged, - scrollOffset: scrollOffset - ); - } - - void updateRenderObject(RenderEditableParagraph renderObject, - _EditableTextWidget oldWidget) { - renderObject.text = _buildTextSpan(); - renderObject.cursorColor = cursorColor; - renderObject.showCursor = showCursor; - renderObject.onContentSizeChanged = onContentSizeChanged; - renderObject.scrollOffset = scrollOffset; - } - - // Construct a TextSpan that renders the EditableString using the chosen style. - TextSpan _buildTextSpan() { - if (value.composing.isValid) { - TextStyle composingStyle = style.merge( - const TextStyle(decoration: underline) - ); - - return new StyledTextSpan(style, [ - new PlainTextSpan(value.textBefore(value.composing)), - new StyledTextSpan(composingStyle, [ - new PlainTextSpan(value.textInside(value.composing)) - ]), - new PlainTextSpan(value.textAfter(value.composing)) - ]); - } - - return new StyledTextSpan(style, [ - new PlainTextSpan(value.text) - ]); - } -} diff --git a/packages/flutter/lib/src/fn3/flat_button.dart b/packages/flutter/lib/src/fn3/flat_button.dart deleted file mode 100644 index 353ebb47b8..0000000000 --- a/packages/flutter/lib/src/fn3/flat_button.dart +++ /dev/null @@ -1,38 +0,0 @@ -// 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. - -import 'package:sky/material.dart'; -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/material_button.dart'; -import 'package:sky/src/fn3/theme.dart'; - -class FlatButton extends MaterialButton { - FlatButton({ - Key key, - Widget child, - bool enabled: true, - Function onPressed - }) : super(key: key, - child: child, - enabled: enabled, - onPressed: onPressed); - - FlatButtonState createState() => new FlatButtonState(); -} - -class FlatButtonState extends MaterialButtonState { - Color getColor(BuildContext context) { - if (!config.enabled || !highlight) - return null; - switch (Theme.of(context).brightness) { - case ThemeBrightness.light: - return Colors.grey[400]; - case ThemeBrightness.dark: - return Colors.grey[200]; - } - } - - int get level => 0; -} diff --git a/packages/flutter/lib/src/fn3/floating_action_button.dart b/packages/flutter/lib/src/fn3/floating_action_button.dart deleted file mode 100644 index f7ba07430f..0000000000 --- a/packages/flutter/lib/src/fn3/floating_action_button.dart +++ /dev/null @@ -1,67 +0,0 @@ -// 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. - -import 'package:sky/gestures.dart'; -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/button_state.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/gesture_detector.dart'; -import 'package:sky/src/fn3/icon.dart'; -import 'package:sky/src/fn3/ink_well.dart'; -import 'package:sky/src/fn3/material.dart'; -import 'package:sky/src/fn3/theme.dart'; - -// TODO(eseidel): This needs to change based on device size? -// http://www.google.com/design/spec/layout/metrics-keylines.html#metrics-keylines-keylines-spacing -const double _kSize = 56.0; - -class FloatingActionButton extends StatefulComponent { - const FloatingActionButton({ - Key key, - this.child, - this.backgroundColor, - this.onPressed - }) : super(key: key); - - final Widget child; - final Color backgroundColor; - final GestureTapListener onPressed; - - FloatingActionButtonState createState() => new FloatingActionButtonState(); -} - -class FloatingActionButtonState extends ButtonState { - Widget buildContent(BuildContext context) { - IconThemeColor iconThemeColor = IconThemeColor.white; - Color materialColor = config.backgroundColor; - if (materialColor == null) { - ThemeData themeData = Theme.of(context); - materialColor = themeData.accentColor; - iconThemeColor = themeData.accentColorBrightness == ThemeBrightness.dark ? IconThemeColor.white : IconThemeColor.black; - } - - return new Material( - color: materialColor, - type: MaterialType.circle, - level: highlight ? 3 : 2, - child: new ClipOval( - child: new GestureDetector( - onTap: config.onPressed, - child: new Container( - width: _kSize, - height: _kSize, - child: new InkWell( - child: new Center( - child: new IconTheme( - data: new IconThemeData(color: iconThemeColor), - child: config.child - ) - ) - ) - ) - ) - ) - ); - } -} diff --git a/packages/flutter/lib/src/fn3/focus.dart b/packages/flutter/lib/src/fn3/focus.dart deleted file mode 100644 index f74e5ad1f9..0000000000 --- a/packages/flutter/lib/src/fn3/focus.dart +++ /dev/null @@ -1,224 +0,0 @@ -// 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. - -import 'package:sky/src/fn3/framework.dart'; - -typedef void FocusChanged(GlobalKey key); - -// _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(); - -class _FocusScope extends InheritedWidget { - _FocusScope({ - Key key, - this.focusState, - this.scopeFocused: true, // are we focused in our ancestor scope? - this.focusedScope, // which of our descendant scopes is focused, if any? - this.focusedWidget, - Widget child - }) : super(key: key, child: child); - - final bool scopeFocused; - final FocusState focusState; - - // These are mutable because we implicitly change them when they're null in - // certain cases, basically pretending retroactively that we were constructed - // with the right keys. - GlobalKey focusedScope; - GlobalKey focusedWidget; - - // The ...IfUnset() methods don'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. - - void _setFocusedWidgetIfUnset(GlobalKey key) { - focusState._setFocusedWidgetIfUnset(key); - focusedWidget = focusState._focusedWidget; - focusedScope = focusState._focusedScope == _noFocusedScope ? null : focusState._focusedScope; - } - - void _setFocusedScopeIfUnset(GlobalKey key) { - focusState._setFocusedScopeIfUnset(key); - assert(focusedWidget == focusState._focusedWidget); - focusedScope = focusState._focusedScope == _noFocusedScope ? null : focusState._focusedScope; - } - - bool updateShouldNotify(_FocusScope oldWidget) { - if (scopeFocused != oldWidget.scopeFocused) - return true; - if (!scopeFocused) - return false; - if (focusedScope != oldWidget.focusedScope) - return true; - if (focusedScope != null) - return false; - if (focusedWidget != oldWidget.focusedWidget) - return true; - return false; - } - -} - -class Focus extends StatefulComponent { - Focus({ - GlobalKey key, // key is required if this is a nested Focus scope - this.autofocus: false, - this.child - }) : super(key: key) { - assert(!autofocus || key != null); - } - - final bool autofocus; - final Widget child; - - FocusState createState() => new FocusState(); -} - -class FocusState extends State { - GlobalKey _focusedWidget; // when null, the first component to ask if it's focused will get the focus - GlobalKey _currentlyRegisteredWidgetRemovalListenerKey; - - void _setFocusedWidget(GlobalKey key) { - setState(() { - _focusedWidget = key; - if (_focusedScope == null) - _focusedScope = _noFocusedScope; - }); - _updateWidgetRemovalListener(key); - } - - void _setFocusedWidgetIfUnset(GlobalKey key) { - if (_focusedWidget == null && (_focusedScope == null || _focusedScope == _noFocusedScope)) { - _focusedWidget = key; - _focusedScope = _noFocusedScope; - _updateWidgetRemovalListener(key); - } - } - - void _handleWidgetRemoved(GlobalKey key) { - assert(_focusedWidget == key); - _updateWidgetRemovalListener(null); - setState(() { - _focusedWidget = null; - }); - } - - void _updateWidgetRemovalListener(GlobalKey key) { - if (_currentlyRegisteredWidgetRemovalListenerKey != key) { - if (_currentlyRegisteredWidgetRemovalListenerKey != null) - GlobalKey.unregisterRemoveListener(_currentlyRegisteredWidgetRemovalListenerKey, _handleWidgetRemoved); - if (key != null) - GlobalKey.registerRemoveListener(key, _handleWidgetRemoved); - _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); - } - - void _setFocusedScopeIfUnset(GlobalKey key) { - if (_focusedScope == null) { - _focusedScope = key; - _updateScopeRemovalListener(key); - } - } - - void _scopeRemoved(GlobalKey key) { - assert(_focusedScope == key); - _currentlyRegisteredScopeRemovalListenerKey = null; - setState(() { - _focusedScope = null; - }); - } - - void _updateScopeRemovalListener(GlobalKey key) { - if (_currentlyRegisteredScopeRemovalListenerKey != key) { - if (_currentlyRegisteredScopeRemovalListenerKey != null) - GlobalKey.unregisterRemoveListener(_currentlyRegisteredScopeRemovalListenerKey, _scopeRemoved); - if (key != null) - GlobalKey.registerRemoveListener(key, _scopeRemoved); - _currentlyRegisteredScopeRemovalListenerKey = key; - } - } - - void initState() { - super.initState(); - if (config.autofocus) - FocusState._moveScopeTo(context, config); - _updateWidgetRemovalListener(_focusedWidget); - _updateScopeRemovalListener(_focusedScope); - } - - void dispose() { - _updateWidgetRemovalListener(null); - _updateScopeRemovalListener(null); - super.dispose(); - } - - Widget build(BuildContext context) { - return new _FocusScope( - focusState: this, - scopeFocused: FocusState._atScope(context, config), - focusedScope: _focusedScope == _noFocusedScope ? null : _focusedScope, - focusedWidget: _focusedWidget, - child: config.child - ); - } - - static bool at(BuildContext context, Widget widget, { bool autofocus: true }) { - assert(widget != null); - assert(widget.key is GlobalKey); - _FocusScope focusScope = context.inheritedWidgetOfType(_FocusScope); - if (focusScope != null) { - if (autofocus) - focusScope._setFocusedWidgetIfUnset(widget.key); - return focusScope.scopeFocused && - focusScope.focusedScope == null && - focusScope.focusedWidget == widget.key; - } - return true; - } - - static bool _atScope(BuildContext context, Widget widget, { bool autofocus: true }) { - assert(widget != null); - _FocusScope focusScope = context.inheritedWidgetOfType(_FocusScope); - if (focusScope != null) { - if (autofocus) - focusScope._setFocusedScopeIfUnset(widget.key); - assert(widget.key != null); - return focusScope.scopeFocused && - focusScope.focusedScope == widget.key; - } - return true; - } - - // Don't call moveTo() from your build() function, it's intended to be called - // from event listeners, e.g. in response to a finger tap or tab key. - - static void moveTo(BuildContext context, Widget widget) { - assert(widget != null); - assert(widget.key is GlobalKey); - _FocusScope focusScope = context.inheritedWidgetOfType(_FocusScope); - if (focusScope != null) - focusScope.focusState._setFocusedWidget(widget.key); - } - - static void _moveScopeTo(BuildContext context, Focus component) { - assert(component != null); - assert(component.key != null); - _FocusScope focusScope = context.inheritedWidgetOfType(_FocusScope); - if (focusScope != null) - focusScope.focusState._setFocusedScope(component.key); - } -} diff --git a/packages/flutter/lib/src/fn3/framework.dart b/packages/flutter/lib/src/fn3/framework.dart deleted file mode 100644 index 4514639492..0000000000 --- a/packages/flutter/lib/src/fn3/framework.dart +++ /dev/null @@ -1,1333 +0,0 @@ -// 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. - -import 'dart:collection'; - -import 'package:sky/rendering.dart'; - -/// A Key is an identifier for [Widget]s and [Element]s. A new Widget will only -/// be used to reconfigure an existing Element if its Key is the same as its -/// original Widget's Key. -/// -/// Keys must be unique amongst the Elements with the same parent. -abstract class Key { - /// Default constructor, used by subclasses. - const Key.constructor(); // so that subclasses can call us, since the Key() factory constructor shadows the implicit constructor - - /// Construct a ValueKey with the given String. - /// This is the simplest way to create keys. - factory Key(String value) => new ValueKey(value); -} - -/// A kind of [Key] that uses a value of a particular type to identify itself. -/// -/// For example, a ValueKey is equal to another ValueKey if -/// their values match. -class ValueKey extends Key { - const ValueKey(this.value) : super.constructor(); - final T value; - String toString() => '[\'${value}\']'; - bool operator==(other) => other is ValueKey && other.value == value; - int get hashCode => value.hashCode; -} - -/// A kind of [Key] that takes its identity from the object used as its value. -/// -/// Used to tie the identity of a Widget to the identity of an object used to -/// generate that Widget. -class ObjectKey extends Key { - const ObjectKey(this.value) : super.constructor(); - final Object value; - String toString() => '[${value.runtimeType}(${value.hashCode})]'; - bool operator==(other) => other is ObjectKey && identical(other.value, value); - int get hashCode => identityHashCode(value); -} - -typedef void GlobalKeyRemoveListener(GlobalKey key); - -/// A GlobalKey is one that must be unique across the entire application. It is -/// used by components that need to communicate with other components across the -/// application's element tree. -abstract class GlobalKey extends Key { - const GlobalKey.constructor() : super.constructor(); // so that subclasses can call us, since the Key() factory constructor shadows the implicit constructor - - /// Constructs a LabeledGlobalKey, which is a GlobalKey with a label used for debugging. - /// The label is not used for comparing the identity of the key. - factory GlobalKey({ String label }) => new LabeledGlobalKey(label); // the label is purely for debugging purposes and is otherwise ignored - - static final Map _registry = new Map(); - static final Map _debugDuplicates = new Map(); - static final Map> _removeListeners = new Map>(); - static final Set _removedKeys = new Set(); - - void _register(Element element) { - assert(() { - if (_registry.containsKey(this)) { - int oldCount = _debugDuplicates.putIfAbsent(this, () => 1); - assert(oldCount >= 1); - _debugDuplicates[this] = oldCount + 1; - } - return true; - }); - _registry[this] = element; - } - - void _unregister(Element element) { - assert(() { - if (_registry.containsKey(this) && _debugDuplicates.containsKey(this)) { - int oldCount = _debugDuplicates[this]; - assert(oldCount >= 2); - if (oldCount == 2) { - _debugDuplicates.remove(this); - } else { - _debugDuplicates[this] = oldCount - 1; - } - } - return true; - }); - if (_registry[this] == element) { - _registry.remove(this); - _removedKeys.add(this); - } - } - - Element get currentElement => _registry[this]; - Widget get currentWidget => currentElement?.widget; - State get currentState { - Element element = currentElement; - if (element is StatefulComponentElement) - return element.state; - return null; - } - - static void registerRemoveListener(GlobalKey key, GlobalKeyRemoveListener listener) { - assert(key != null); - Set listeners = - _removeListeners.putIfAbsent(key, () => new Set()); - bool added = listeners.add(listener); - assert(added); - } - - static void unregisterRemoveListener(GlobalKey key, GlobalKeyRemoveListener listener) { - assert(key != null); - assert(_removeListeners.containsKey(key)); - bool removed = _removeListeners[key].remove(listener); - if (_removeListeners[key].isEmpty) - _removeListeners.remove(key); - assert(removed); - } - - static void checkForDuplicatesAndNotifyListeners() { - assert(() { - String message = ''; - for (GlobalKey key in _debugDuplicates.keys) { - message += 'Duplicate GlobalKey found amongst mounted elements: $key (${_debugDuplicates[key]} instances)\n'; - message += 'Most recently registered instance is:\n${_registry[key]}\n'; - } - if (!_debugDuplicates.isEmpty) - throw message; - return true; - }); - if (_removedKeys.isEmpty) - return; - try { - for (GlobalKey key in _removedKeys) { - if (!_registry.containsKey(key) && _removeListeners.containsKey(key)) { - Set localListeners = new Set.from(_removeListeners[key]); - for (GlobalKeyRemoveListener listener in localListeners) - listener(key); - } - } - } finally { - _removedKeys.clear(); - } - } - -} - -/// Each LabeledGlobalKey instance is a unique key. -/// The optional label can be used for documentary purposes. It does not affect -/// the key's identity. -class LabeledGlobalKey extends GlobalKey { - const LabeledGlobalKey(this._label) : super.constructor(); - final String _label; - String toString() => '[GlobalKey ${_label != null ? _label : hashCode}]'; -} - -/// A kind of [GlobalKey] that takes its identity from the object used as its value. -/// -/// Used to tie the identity of a Widget to the identity of an object used to -/// generate that Widget. -class GlobalObjectKey extends GlobalKey { - const GlobalObjectKey(this.value) : super.constructor(); - final Object value; - String toString() => '[GlobalKey ${value.runtimeType}(${value.hashCode})]'; - bool operator==(other) => other is GlobalObjectKey && identical(other.value, value); - int get hashCode => identityHashCode(value); -} - - -/// A Widget object describes the configuration for an [Element]. -/// Widget subclasses should be immutable with const constructors. -/// Widgets form a tree that is then inflated into an Element tree. -abstract class Widget { - const Widget({ this.key }); - final Key key; - - /// Inflates this configuration to a concrete instance. - Element createElement(); - - String toString() => '$runtimeType'; -} - -/// RenderObjectWidgets provide the configuration for [RenderObjectElement]s, -/// which wrap [RenderObject]s, which provide the actual rendering of the -/// application. -abstract class RenderObjectWidget extends Widget { - const RenderObjectWidget({ Key key }) : super(key: key); - - /// RenderObjectWidgets always inflate to a RenderObjectElement subclass. - RenderObjectElement createElement(); - - /// Constructs an instance of the RenderObject class that this - /// RenderObjectWidget represents, using the configuration described by this - /// RenderObjectWidget. - RenderObject createRenderObject(); - - /// Copies the configuration described by this RenderObjectWidget to the given - /// RenderObject, which must be of the same type as returned by this class' - /// createRenderObject(). - void updateRenderObject(RenderObject renderObject, RenderObjectWidget oldWidget) { } - - void didUnmountRenderObject(RenderObject renderObject) { } -} - -/// A superclass for RenderObjectWidgets that configure RenderObject subclasses -/// that have no children. -abstract class LeafRenderObjectWidget extends RenderObjectWidget { - const LeafRenderObjectWidget({ Key key }) : super(key: key); - - LeafRenderObjectElement createElement() => new LeafRenderObjectElement(this); -} - -/// A superclass for RenderObjectWidgets that configure RenderObject subclasses -/// that have a single child slot. (This superclass only provides the storage -/// for that child, it doesn't actually provide the updating logic.) -abstract class OneChildRenderObjectWidget extends RenderObjectWidget { - const OneChildRenderObjectWidget({ Key key, Widget this.child }) : super(key: key); - - final Widget child; - - OneChildRenderObjectElement createElement() => new OneChildRenderObjectElement(this); -} - -/// A superclass for RenderObjectWidgets that configure RenderObject subclasses -/// that have a single list of children. (This superclass only provides the -/// storage for that child list, it doesn't actually provide the updating -/// logic.) -abstract class MultiChildRenderObjectWidget extends RenderObjectWidget { - const MultiChildRenderObjectWidget({ Key key, List this.children }) - : super(key: key); - - final List children; - - MultiChildRenderObjectElement createElement() => new MultiChildRenderObjectElement(this); -} - -/// StatelessComponents describe a way to compose other Widgets to form reusable -/// parts, which doesn't depend on anything other than the configuration -/// information in the object itself. (For compositions that can change -/// dynamically, e.g. due to having an internal clock-driven state, or depending -/// on some system state, use [StatefulComponent].) -abstract class StatelessComponent extends Widget { - const StatelessComponent({ Key key }) : super(key: key); - - /// StatelessComponents always use StatelessComponentElements to represent - /// themselves in the Element tree. - StatelessComponentElement createElement() => new StatelessComponentElement(this); - - /// Returns another Widget out of which this StatelessComponent is built. - /// Typically that Widget will have been configured with further children, - /// such that really this function returns a tree of configuration. - /// - /// The given build context object contains information about the location in - /// the tree at which this component is being built. For example, the context - /// provides the set of inherited widgets for this location in the tree. - Widget build(BuildContext context); -} - -/// StatefulComponents provide the configuration for -/// [StatefulComponentElement]s, which wrap [State]s, which hold mutable state -/// and can dynamically and spontaneously ask to be rebuilt. -abstract class StatefulComponent extends Widget { - const StatefulComponent({ Key key }) : super(key: key); - - /// StatefulComponents always use StatefulComponentElements to represent - /// themselves in the Element tree. - StatefulComponentElement createElement() => new StatefulComponentElement(this); - - /// Returns an instance of the state to which this StatefulComponent is - /// related, using this object as the configuration. Subclasses should - /// override this to return a new instance of the State class associated with - /// this StatefulComponent class, like this: - /// - /// MyState createState() => new MyState(this); - State createState(); -} - -enum _StateLifecycle { - created, - initialized, - ready, - defunct, -} - -/// The logic and internal state for a StatefulComponent. -abstract class State { - /// The current configuration (an instance of the corresponding - /// StatefulComponent class). - T get config => _config; - T _config; - - /// This is used to verify that State objects move through life in an orderly fashion. - _StateLifecycle _debugLifecycleState = _StateLifecycle.created; - - /// Pointer to the owner Element object - StatefulComponentElement _element; - - /// The context in which this object will be built - BuildContext get context => _element; - - bool get mounted => _element != null; - - /// Called when this object is inserted into the tree. Override this function - /// to perform initialization that depends on the location at which this - /// object was inserted into the tree or on the widget configuration object. - /// - /// If you override this, make sure your method starts with a call to - /// super.initState(). - void initState() { - assert(_debugLifecycleState == _StateLifecycle.created); - assert(() { _debugLifecycleState = _StateLifecycle.initialized; return true; }); - } - - /// Called whenever the configuration changes. Override this method to update - /// additional state when the config field's value is changed. - void didUpdateConfig(T oldConfig) { } - - /// Whenever you need to change internal state for a State object, make the - /// change in a function that you pass to setState(), as in: - /// - /// setState(() { myState = newValue }); - /// - /// If you just change the state directly without calling setState(), then the - /// component will not be scheduled for rebuilding, meaning that its rendering - /// will not be updated. - void setState(void fn()) { - assert(_debugLifecycleState != _StateLifecycle.defunct); - fn(); - _element.markNeedsBuild(); - } - - /// Called when this object is removed from the tree. Override this to clean - /// up any resources allocated by this object. - /// - /// If you override this, make sure to end your method with a call to - /// super.dispose(). - void dispose() { - assert(_debugLifecycleState == _StateLifecycle.ready); - assert(() { _debugLifecycleState = _StateLifecycle.defunct; return true; }); - } - - /// Returns another Widget out of which this StatefulComponent is built. - /// Typically that Widget will have been configured with further children, - /// such that really this function returns a tree of configuration. - /// - /// The given build context object contains information about the location in - /// the tree at which this component is being built. For example, the context - /// provides the set of inherited widgets for this location in the tree. - Widget build(BuildContext context); - - String toString() { - final List data = []; - debugFillDescription(data); - return '$runtimeType(${data.join("; ")})'; - } - - void debugFillDescription(List description) { - description.add('$hashCode'); - if (_debugLifecycleState != _StateLifecycle.ready) - description.add('$_debugLifecycleState'); - if (_config == null) - description.add('no config'); - if (_element == null) - description.add('not mounted'); - } -} - -abstract class ProxyWidget extends StatelessComponent { - const ProxyWidget({ Key key, Widget this.child }) : super(key: key); - - final Widget child; - - Widget build(BuildContext context) => child; -} - -abstract class ParentDataWidget extends ProxyWidget { - ParentDataWidget({ Key key, Widget child }) - : super(key: key, child: child); - - ParentDataElement createElement() => new ParentDataElement(this); - - /// Subclasses should override this function to ensure that they are placed - /// inside widgets that expect them. - /// - /// The given ancestor is the first RenderObjectWidget ancestor of this widget. - void debugValidateAncestor(RenderObjectWidget ancestor); - - void applyParentData(RenderObject renderObject); -} - -abstract class InheritedWidget extends ProxyWidget { - const InheritedWidget({ Key key, Widget child }) - : super(key: key, child: child); - - InheritedElement createElement() => new InheritedElement(this); - - bool updateShouldNotify(InheritedWidget oldWidget); -} - -bool _canUpdate(Widget oldWidget, Widget newWidget) { - return oldWidget.runtimeType == newWidget.runtimeType && - oldWidget.key == newWidget.key; -} - -enum _ElementLifecycle { - initial, - mounted, - defunct, -} - -typedef void ElementVisitor(Element element); - -abstract class BuildContext { - InheritedWidget inheritedWidgetOfType(Type targetType); - RenderObject findRenderObject(); - - void visitAncestorElements(bool visitor(Element element)); -} - -/// Elements are the instantiations of Widget configurations. -/// -/// Elements can, in principle, have children. Only subclasses of -/// RenderObjectElement are allowed to have more than one child. -abstract class Element implements BuildContext { - Element(T widget) : _widget = widget { - assert(widget != null); - } - - Element _parent; - - /// Information set by parent to define where this child fits in its parent's - /// child list. - /// - /// Subclasses of Element that only have one child should use null for - /// the slot for that child. - dynamic get slot => _slot; - dynamic _slot; - - /// An integer that is guaranteed to be greater than the parent's, if any. - /// The element at the root of the tree must have a depth greater than 0. - int get depth => _depth; - int _depth; - - /// The configuration for this element. - T get widget => _widget; - T _widget; - - RenderObject get renderObject { - RenderObject result; - void visit(Element element) { - assert(result == null); // this verifies that there's only one child - if (element is RenderObjectElement) - result = element.renderObject; - else - element.visitChildren(visit); - } - visit(this); - return result; - } - - /// This is used to verify that Element objects move through life in an orderly fashion. - _ElementLifecycle _debugLifecycleState = _ElementLifecycle.initial; - - /// Calls the argument for each child. Must be overridden by subclasses that support having children. - void visitChildren(ElementVisitor visitor) { } - - /// Calls the argument for each descendant, depth-first pre-order. - void visitDescendants(ElementVisitor visitor) { - void visit(Element element) { - visitor(element); - element.visitChildren(visit); - } - visitChildren(visit); - } - - /// This method is the core of the system. - /// - /// It is called each time we are to add, update, or remove a child based on - /// an updated configuration. - /// - /// If the child is null, and the newWidget is not null, then we have a new - /// child for which we need to create an Element, configured with newWidget. - /// - /// If the newWidget is null, and the child is not null, then we need to - /// remove it because it no longer has a configuration. - /// - /// If neither are null, then we need to update the child's configuration to - /// be the new configuration given by newWidget. If newWidget can be given to - /// the existing child, then it is so given. Otherwise, the old child needs - /// to be disposed and a new child created for the new configuration. - /// - /// If both are null, then we don't have a child and won't have a child, so - /// we do nothing. - /// - /// The updateChild() method returns the new child, if it had to create one, - /// or the child that was passed in, if it just had to update the child, or - /// null, if it removed the child and did not replace it. - Element updateChild(Element child, Widget newWidget, dynamic newSlot) { - if (newWidget == null) { - if (child != null) - _detachChild(child); - return null; - } - if (child != null) { - if (child.widget == newWidget) { - if (child.slot != newSlot) - updateSlotForChild(child, newSlot); - return child; - } - if (_canUpdate(child.widget, newWidget)) { - if (child.slot != newSlot) - updateSlotForChild(child, newSlot); - child.update(newWidget); - assert(child.widget == newWidget); - return child; - } - _detachChild(child); - assert(child._parent == null); - } - child = newWidget.createElement(); - child.mount(this, newSlot); - assert(child._debugLifecycleState == _ElementLifecycle.mounted); - return child; - } - - /// Called when an Element is given a new parent shortly after having been - /// created. Use this to initialize state that depends on having a parent. For - /// state that is independent of the position in the tree, it's better to just - /// initialize the Element in the constructor. - void mount(Element parent, dynamic newSlot) { - assert(_debugLifecycleState == _ElementLifecycle.initial); - assert(widget != null); - assert(_parent == null); - assert(parent == null || parent._debugLifecycleState == _ElementLifecycle.mounted); - assert(slot == null); - assert(depth == null); - _parent = parent; - _slot = newSlot; - _depth = _parent != null ? _parent.depth + 1 : 1; - if (widget.key is GlobalKey) { - final GlobalKey key = widget.key; - key._register(this); - } - assert(() { _debugLifecycleState = _ElementLifecycle.mounted; return true; }); - } - - /// Called when an Element receives a new configuration widget. - void update(T newWidget) { - assert(_debugLifecycleState == _ElementLifecycle.mounted); - assert(widget != null); - assert(newWidget != null); - assert(depth != null); - assert(_canUpdate(widget, newWidget)); - _widget = newWidget; - } - - /// Called by MultiChildRenderObjectElement, and other RenderObjectElement - /// subclasses that have multiple children, to update the slot of a particular - /// child when the child is moved in its child list. - void updateSlotForChild(Element child, dynamic newSlot) { - assert(_debugLifecycleState == _ElementLifecycle.mounted); - assert(child != null); - assert(child._parent == this); - void visit(Element element) { - element._updateSlot(newSlot); - if (element is! RenderObjectElement) - element.visitChildren(visit); - } - visit(child); - } - - void _updateSlot(dynamic newSlot) { - assert(_debugLifecycleState == _ElementLifecycle.mounted); - assert(widget != null); - assert(_parent != null); - assert(_parent._debugLifecycleState == _ElementLifecycle.mounted); - assert(depth != null); - _slot = newSlot; - } - - void _detachChild(Element child) { - assert(child != null); - assert(child._parent == this); - child._parent = null; - - bool haveDetachedRenderObject = false; - void detach(Element descendant) { - if (!haveDetachedRenderObject) { - descendant._slot = null; - if (descendant is RenderObjectElement) { - descendant.detachRenderObject(); - haveDetachedRenderObject = true; - } - } - descendant.unmount(); - assert(descendant._debugLifecycleState == _ElementLifecycle.defunct); - } - - detach(child); - child.visitDescendants(detach); - } - - /// Called when an Element is removed from the tree. - /// Currently, an Element removed from the tree never returns. - void unmount() { - assert(_debugLifecycleState == _ElementLifecycle.mounted); - assert(widget != null); - assert(depth != null); - if (widget.key is GlobalKey) { - final GlobalKey key = widget.key; - key._unregister(this); - } - assert(() { _debugLifecycleState = _ElementLifecycle.defunct; return true; }); - } - - Set _dependencies; - InheritedWidget inheritedWidgetOfType(Type targetType) { - if (_dependencies == null) - _dependencies = new Set(); - _dependencies.add(targetType); - Element ancestor = _parent; - while (ancestor != null && ancestor.widget.runtimeType != targetType) - ancestor = ancestor._parent; - return ancestor?.widget; - } - - RenderObject findRenderObject() => renderObject; - - void visitAncestorElements(bool visitor(Element element)) { - Element ancestor = _parent; - while (ancestor != null && visitor(ancestor)) - ancestor = ancestor._parent; - } - - void dependenciesChanged() { - assert(false); - } - - String toString() { - final List data = []; - debugFillDescription(data); - final String name = widget != null ? '$widget' : '[$runtimeType]'; - return '$name(${data.join("; ")})'; - } - - void debugFillDescription(List description) { - if (depth == null) - description.add('no depth'); - if (widget == null) - description.add('no widget'); - } - - String toStringDeep([String prefixLineOne = '', String prefixOtherLines = '']) { - String result = '${prefixLineOne}$this\n'; - List children = []; - visitChildren((Element child) { - children.add(child); - }); - if (children.length > 0) { - Element last = children.removeLast(); - for (Element child in children) - result += '${child.toStringDeep("$prefixOtherLines \u251C", "$prefixOtherLines \u2502")}'; - result += '${last.toStringDeep("$prefixOtherLines \u2514", "$prefixOtherLines ")}'; - } - return result; - } -} - -class ErrorWidget extends LeafRenderObjectWidget { - RenderBox createRenderObject() => new RenderErrorBox(); -} - -typedef Widget WidgetBuilder(BuildContext context); -typedef void BuildScheduler(BuildableElement element); - -/// Base class for the instantiation of StatelessComponent and StatefulComponent -/// widgets. -abstract class BuildableElement extends Element { - BuildableElement(T widget) : super(widget); - - WidgetBuilder _builder; - Element _child; - - /// Returns true if the element has been marked as needing rebuilding. - bool get dirty => _dirty; - bool _dirty = true; - - // We to let component authors call setState from initState, didUpdateConfig, - // and build even when state is locked because its convenient and a no-op - // anyway. This flag ensures that this convenience is only allowed on the - // element currently undergoing initState, didUpdateConfig, or build. - bool _debugAllowIgnoredCallsToMarkNeedsBuild = false; - bool _debugSetAllowIgnoredCallsToMarkNeedsBuild(bool value) { - assert(_debugAllowIgnoredCallsToMarkNeedsBuild == !value); - _debugAllowIgnoredCallsToMarkNeedsBuild = value; - return true; - } - - void mount(Element parent, dynamic newSlot) { - super.mount(parent, newSlot); - assert(_child == null); - rebuild(); - assert(_child != null); - } - - /// Reinvokes the build() method of the StatelessComponent object (for - /// stateless components) or the State object (for stateful components) and - /// then updates the widget tree. - /// - /// Called automatically during mount() to generate the first build, by the - /// binding when scheduleBuild() has been called to mark this element dirty, - /// and by update() when the Widget has changed. - void rebuild() { - assert(_debugLifecycleState != _ElementLifecycle.initial); - if (!dirty) - return; - assert(_debugLifecycleState == _ElementLifecycle.mounted); - assert(_debugStateLocked); - assert(_debugSetAllowIgnoredCallsToMarkNeedsBuild(true)); - Widget built; - try { - built = _builder(this); - assert(built != null); - } catch (e, stack) { - _debugReportException('building ${_widget}', e, stack); - built = new ErrorWidget(); - } finally { - // We delay marking the element as clean until after calling _builder so - // that attempts to markNeedsBuild() during build() will be ignored. - _dirty = false; - assert(_debugSetAllowIgnoredCallsToMarkNeedsBuild(false)); - } - - try { - _child = updateChild(_child, built, slot); - assert(_child != null); - } catch (e, stack) { - _debugReportException('building ${_widget}', e, stack); - built = new ErrorWidget(); - _child = updateChild(null, built, slot); - } - } - - static BuildScheduler scheduleBuildFor; - - static int _debugStateLockLevel = 0; - static bool get _debugStateLocked => _debugStateLockLevel > 0; - - /// Establishes a scope in which component build functions can run. - /// - /// Inside a build scope, component build functions are allowed to run, but - /// State.setState() is forbidden. This mechanism prevents build functions - /// from transitively requiring other build functions to run, potentially - /// causing infinite loops. - /// - /// After unwinding the last build scope on the stack, the framework verifies - /// that each global key is used at most once and notifies listeners about - /// changes to global keys. - static void lockState(void callback()) { - _debugStateLockLevel += 1; - try { - callback(); - } finally { - _debugStateLockLevel -= 1; - } - } - - /// Marks the element as dirty and adds it to the global list of widgets to - /// rebuild in the next frame. - /// - /// Since it is inefficient to build an element twice in one frame, - /// applications and components should be structured so as to only mark - /// components dirty during event handlers before the frame begins, not during - /// the build itself. - void markNeedsBuild() { - assert(_debugLifecycleState != _ElementLifecycle.defunct); - assert(!_debugStateLocked || (_debugAllowIgnoredCallsToMarkNeedsBuild && dirty)); - if (dirty) - return; - assert(_debugLifecycleState == _ElementLifecycle.mounted); - assert(!_debugStateLocked); - _dirty = true; - assert(scheduleBuildFor != null); - scheduleBuildFor(this); - } - - void visitChildren(ElementVisitor visitor) { - if (_child != null) - visitor(_child); - } - - void unmount() { - super.unmount(); - _dirty = false; // so that we don't get rebuilt even if we're already marked dirty - } - - void dependenciesChanged() { - markNeedsBuild(); - } - - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (dirty) - description.add('dirty'); - } -} - -/// Instantiation of StatelessComponent widgets. -class StatelessComponentElement extends BuildableElement { - StatelessComponentElement(StatelessComponent widget) : super(widget) { - _builder = widget.build; - } - - void update(StatelessComponent newWidget) { - super.update(newWidget); - assert(widget == newWidget); - _builder = widget.build; - _dirty = true; - rebuild(); - } -} - -/// Instantiation of StatefulComponent widgets. -class StatefulComponentElement extends BuildableElement { - StatefulComponentElement(StatefulComponent widget) - : _state = widget.createState(), super(widget) { - assert(_state._element == null); - _state._element = this; - assert(_builder == null); - _builder = _state.build; - assert(_state._config == null); - _state._config = widget; - assert(_state._debugLifecycleState == _StateLifecycle.created); - try { - _debugSetAllowIgnoredCallsToMarkNeedsBuild(true); - _state.initState(); - } finally { - _debugSetAllowIgnoredCallsToMarkNeedsBuild(false); - } - assert(() { - if (_state._debugLifecycleState == _StateLifecycle.initialized) - return true; - print('${_state.runtimeType}.initState failed to call super.initState'); - return false; - }); - assert(() { _state._debugLifecycleState = _StateLifecycle.ready; return true; }); - } - - State get state => _state; - State _state; - - void update(StatefulComponent newWidget) { - super.update(newWidget); - assert(widget == newWidget); - StatefulComponent oldConfig = _state._config; - // Notice that we mark ourselves as dirty before calling didUpdateConfig to - // let authors call setState from within didUpdateConfig without triggering - // asserts. - _dirty = true; - _state._config = widget; - try { - _debugSetAllowIgnoredCallsToMarkNeedsBuild(true); - _state.didUpdateConfig(oldConfig); - } finally { - _debugSetAllowIgnoredCallsToMarkNeedsBuild(false); - } - rebuild(); - } - - void unmount() { - super.unmount(); - _state.dispose(); - assert(() { - if (_state._debugLifecycleState == _StateLifecycle.defunct) - return true; - print('${_state.runtimeType}.dispose failed to call super.dispose'); - return false; - }); - assert(!dirty); // See BuildableElement.unmount for why this is important. - _state._element = null; - _state = null; - } - - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (state != null) - description.add('state: $state'); - } -} - -class ParentDataElement extends StatelessComponentElement { - ParentDataElement(ParentDataWidget widget) : super(widget); - - void mount(Element parent, dynamic slot) { - assert(() { - Element ancestor = parent; - while (ancestor is! RenderObjectElement) { - assert(ancestor != null); - assert(() { - 'You cannot nest parent data widgets inside one another.'; - return ancestor is! ParentDataElement; - }); - ancestor = ancestor._parent; - } - _widget.debugValidateAncestor(ancestor._widget); - return true; - }); - super.mount(parent, slot); - } - - void update(ParentDataWidget newWidget) { - ParentDataWidget oldWidget = widget; - super.update(newWidget); - assert(widget == newWidget); - if (widget != oldWidget) - _notifyDescendants(); - } - - void _notifyDescendants() { - void notifyChildren(Element child) { - if (child is RenderObjectElement) - child.updateParentData(widget); - else if (child is! ParentDataElement) - child.visitChildren(notifyChildren); - } - visitChildren(notifyChildren); - } -} - -class InheritedElement extends StatelessComponentElement { - InheritedElement(InheritedWidget widget) : super(widget); - - void update(StatelessComponent newWidget) { - InheritedWidget oldWidget = widget; - super.update(newWidget); - assert(widget == newWidget); - if (widget.updateShouldNotify(oldWidget)) - _notifyDescendants(); - } - - void _notifyDescendants() { - final Type ourRuntimeType = runtimeType; - void notifyChildren(Element child) { - if (child._dependencies != null && - child._dependencies.contains(ourRuntimeType)) - child.dependenciesChanged(); - if (child.runtimeType != ourRuntimeType) - child.visitChildren(notifyChildren); - } - visitChildren(notifyChildren); - } -} - -/// Base class for instantiations of RenderObjectWidget subclasses -abstract class RenderObjectElement extends Element { - RenderObjectElement(T widget) - : _renderObject = widget.createRenderObject(), super(widget); - - /// The underlying [RenderObject] for this element - RenderObject get renderObject => _renderObject; - final RenderObject _renderObject; - - RenderObjectElement _ancestorRenderObjectElement; - - RenderObjectElement _findAncestorRenderObjectElement() { - Element ancestor = _parent; - while (ancestor != null && ancestor is! RenderObjectElement) - ancestor = ancestor._parent; - return ancestor; - } - - ParentDataElement _findAncestorParentDataElement() { - Element ancestor = _parent; - while (ancestor != null && ancestor is! RenderObjectElement) { - if (ancestor is ParentDataElement) - return ancestor; - ancestor = ancestor._parent; - } - return null; - } - - void mount(Element parent, dynamic newSlot) { - super.mount(parent, newSlot); - assert(_ancestorRenderObjectElement == null); - _ancestorRenderObjectElement = _findAncestorRenderObjectElement(); - _ancestorRenderObjectElement?.insertChildRenderObject(renderObject, newSlot); - ParentDataElement parentDataElement = _findAncestorParentDataElement(); - if (parentDataElement != null) - updateParentData(parentDataElement.widget); - } - - void update(T newWidget) { - T oldWidget = widget; - super.update(newWidget); - assert(widget == newWidget); - widget.updateRenderObject(renderObject, oldWidget); - } - - /// Utility function for subclasses that have one or more lists of children. - /// Attempts to update the given old children list using the given new - /// widgets, removing obsolete elements and introducing new ones as necessary, - /// and then returns the new child list. - List updateChildren(List oldChildren, List newWidgets) { - assert(oldChildren != null); - assert(newWidgets != null); - - // This attempts to diff the new child list (this.children) with - // the old child list (old.children), and update our renderObject - // accordingly. - - // The cases it tries to optimise for are: - // - the old list is empty - // - the lists are identical - // - there is an insertion or removal of one or more widgets in - // only one place in the list - // If a widget with a key is in both lists, it will be synced. - // Widgets without keys might be synced but there is no guarantee. - - // The general approach is to sync the entire new list backwards, as follows: - // 1. Walk the lists from the top until you no longer have - // matching nodes. We don't sync these yet, but we now know to - // skip them below. We do this because at each sync we need to - // pass the pointer to the new next widget as the slot, which - // we can't do until we've synced the next child. - // 2. Walk the lists from the bottom, syncing nodes, until you no - // longer have matching nodes. - // At this point we narrowed the old and new lists to the point - // where the nodes no longer match. - // 3. Walk the narrowed part of the old list to get the list of - // keys and sync null with non-keyed items. - // 4. Walk the narrowed part of the new list backwards: - // * Sync unkeyed items with null - // * Sync keyed items with the source if it exists, else with null. - // 5. Walk the top list again but backwards, syncing the nodes. - // 6. Sync null with any items in the list of keys that are still - // mounted. - - final ContainerRenderObjectMixin renderObject = this.renderObject; // TODO(ianh): Remove this once the analyzer is cleverer - assert(renderObject is ContainerRenderObjectMixin); - - int childrenTop = 0; - int newChildrenBottom = newWidgets.length - 1; - int oldChildrenBottom = oldChildren.length - 1; - - // top of the lists - while ((childrenTop <= oldChildrenBottom) && (childrenTop <= newChildrenBottom)) { - Element oldChild = oldChildren[childrenTop]; - Widget newWidget = newWidgets[childrenTop]; - assert(oldChild._debugLifecycleState == _ElementLifecycle.mounted); - if (!_canUpdate(oldChild.widget, newWidget)) - break; - childrenTop += 1; - } - - List newChildren = oldChildren.length == newWidgets.length ? - oldChildren : new List(newWidgets.length); - - Element nextSibling; - - // bottom of the lists - while ((childrenTop <= oldChildrenBottom) && (childrenTop <= newChildrenBottom)) { - Element oldChild = oldChildren[oldChildrenBottom]; - Widget newWidget = newWidgets[newChildrenBottom]; - assert(oldChild._debugLifecycleState == _ElementLifecycle.mounted); - if (!_canUpdate(oldChild.widget, newWidget)) - break; - Element newChild = updateChild(oldChild, newWidget, nextSibling); - assert(newChild._debugLifecycleState == _ElementLifecycle.mounted); - newChildren[newChildrenBottom] = newChild; - nextSibling = newChild; - oldChildrenBottom -= 1; - newChildrenBottom -= 1; - } - - // middle of the lists - old list - bool haveOldNodes = childrenTop <= oldChildrenBottom; - Map oldKeyedChildren; - if (haveOldNodes) { - oldKeyedChildren = new Map(); - while (childrenTop <= oldChildrenBottom) { - Element oldChild = oldChildren[oldChildrenBottom]; - assert(oldChild._debugLifecycleState == _ElementLifecycle.mounted); - if (oldChild.widget.key != null) - oldKeyedChildren[oldChild.widget.key] = oldChild; - else - _detachChild(oldChild); - oldChildrenBottom -= 1; - } - } - - // middle of the lists - new list - while (childrenTop <= newChildrenBottom) { - Element oldChild; - Widget newWidget = newWidgets[newChildrenBottom]; - if (haveOldNodes) { - Key key = newWidget.key; - if (key != null) { - oldChild = oldKeyedChildren[newWidget.key]; - if (oldChild != null) { - if (_canUpdate(oldChild.widget, newWidget)) { - // we found a match! - // remove it from oldKeyedChildren so we don't unsync it later - oldKeyedChildren.remove(key); - } else { - // Not a match, let's pretend we didn't see it for now. - oldChild = null; - } - } - } - } - assert(oldChild == null || _canUpdate(oldChild.widget, newWidget)); - Element newChild = updateChild(oldChild, newWidget, nextSibling); - assert(newChild._debugLifecycleState == _ElementLifecycle.mounted); - assert(oldChild == newChild || oldChild == null || oldChild._debugLifecycleState != _ElementLifecycle.mounted); - newChildren[newChildrenBottom] = newChild; - nextSibling = newChild; - newChildrenBottom -= 1; - } - assert(oldChildrenBottom == newChildrenBottom); - assert(childrenTop == newChildrenBottom + 1); - - // now sync the top of the list - while (childrenTop > 0) { - childrenTop -= 1; - Element oldChild = oldChildren[childrenTop]; - assert(oldChild._debugLifecycleState == _ElementLifecycle.mounted); - Widget newWidget = newWidgets[childrenTop]; - assert(_canUpdate(oldChild.widget, newWidget)); - Element newChild = updateChild(oldChild, newWidget, nextSibling); - assert(newChild._debugLifecycleState == _ElementLifecycle.mounted); - assert(oldChild == newChild || oldChild == null || oldChild._debugLifecycleState != _ElementLifecycle.mounted); - newChildren[childrenTop] = newChild; - nextSibling = newChild; - } - - // clean up any of the remaining middle nodes from the old list - if (haveOldNodes && !oldKeyedChildren.isEmpty) { - for (Element oldChild in oldKeyedChildren.values) - _detachChild(oldChild); - } - - assert(renderObject == this.renderObject); // TODO(ianh): Remove this once the analyzer is cleverer - return newChildren; - } - - void unmount() { - super.unmount(); - assert(!renderObject.attached); - widget.didUnmountRenderObject(renderObject); - } - - void updateParentData(ParentDataWidget parentData) { - parentData.applyParentData(renderObject); - } - - void _updateSlot(dynamic newSlot) { - assert(slot != newSlot); - super._updateSlot(newSlot); - assert(slot == newSlot); - _ancestorRenderObjectElement.moveChildRenderObject(renderObject, slot); - } - - void detachRenderObject() { - if (_ancestorRenderObjectElement != null) { - _ancestorRenderObjectElement.removeChildRenderObject(renderObject); - _ancestorRenderObjectElement = null; - } - } - - void insertChildRenderObject(RenderObject child, dynamic slot); - void moveChildRenderObject(RenderObject child, dynamic slot); - void removeChildRenderObject(RenderObject child); - - void debugFillDescription(List description) { - super.debugFillDescription(description); - if (renderObject != null) - description.add('renderObject: $renderObject'); - } -} - -/// Instantiation of RenderObjectWidgets that have no children -class LeafRenderObjectElement extends RenderObjectElement { - LeafRenderObjectElement(T widget): super(widget); - - void insertChildRenderObject(RenderObject child, dynamic slot) { - assert(false); - } - - void moveChildRenderObject(RenderObject child, dynamic slot) { - assert(false); - } - - void removeChildRenderObject(RenderObject child) { - assert(false); - } -} - -/// Instantiation of RenderObjectWidgets that have up to one child -class OneChildRenderObjectElement extends RenderObjectElement { - OneChildRenderObjectElement(T widget) : super(widget); - - Element _child; - - void visitChildren(ElementVisitor visitor) { - if (_child != null) - visitor(_child); - } - - void mount(Element parent, dynamic newSlot) { - super.mount(parent, newSlot); - _child = updateChild(_child, widget.child, null); - } - - void update(T newWidget) { - super.update(newWidget); - assert(widget == newWidget); - _child = updateChild(_child, widget.child, null); - } - - void insertChildRenderObject(RenderObject child, dynamic slot) { - final renderObject = this.renderObject; // TODO(ianh): Remove this once the analyzer is cleverer - assert(renderObject is RenderObjectWithChildMixin); - assert(slot == null); - renderObject.child = child; - assert(renderObject == this.renderObject); // TODO(ianh): Remove this once the analyzer is cleverer - } - - void moveChildRenderObject(RenderObject child, dynamic slot) { - assert(false); - } - - void removeChildRenderObject(RenderObject child) { - final renderObject = this.renderObject; // TODO(ianh): Remove this once the analyzer is cleverer - assert(renderObject is RenderObjectWithChildMixin); - assert(renderObject.child == child); - renderObject.child = null; - assert(renderObject == this.renderObject); // TODO(ianh): Remove this once the analyzer is cleverer - } -} - -/// Instantiation of RenderObjectWidgets that can have a list of children -class MultiChildRenderObjectElement extends RenderObjectElement { - MultiChildRenderObjectElement(T widget) : super(widget) { - assert(!_debugHasDuplicateIds()); - } - - List _children; - - void insertChildRenderObject(RenderObject child, Element slot) { - final renderObject = this.renderObject; // TODO(ianh): Remove this once the analyzer is cleverer - RenderObject nextSibling = slot?.renderObject; - assert(renderObject is ContainerRenderObjectMixin); - renderObject.add(child, before: nextSibling); - assert(renderObject == this.renderObject); // TODO(ianh): Remove this once the analyzer is cleverer - } - - void moveChildRenderObject(RenderObject child, dynamic slot) { - final renderObject = this.renderObject; // TODO(ianh): Remove this once the analyzer is cleverer - RenderObject nextSibling = slot?.renderObject; - assert(renderObject is ContainerRenderObjectMixin); - renderObject.move(child, before: nextSibling); - assert(renderObject == this.renderObject); // TODO(ianh): Remove this once the analyzer is cleverer - } - - void removeChildRenderObject(RenderObject child) { - final renderObject = this.renderObject; // TODO(ianh): Remove this once the analyzer is cleverer - assert(renderObject is ContainerRenderObjectMixin); - assert(child.parent == renderObject); - renderObject.remove(child); - assert(renderObject == this.renderObject); // TODO(ianh): Remove this once the analyzer is cleverer - } - - bool _debugHasDuplicateIds() { - var idSet = new HashSet(); - for (Widget child in widget.children) { - assert(child != null); - if (child.key == null) - continue; // when these nodes are reordered, we just reassign the data - - if (!idSet.add(child.key)) { - throw 'If multiple keyed nodes exist as children of another node, they must have unique keys. $widget has multiple children with key "${child.key}".'; - } - } - return false; - } - - void visitChildren(ElementVisitor visitor) { - for (Element child in _children) - visitor(child); - } - - void mount(Element parent, dynamic newSlot) { - super.mount(parent, newSlot); - _children = new List(widget.children.length); - Element previousChild; - for (int i = _children.length - 1; i >= 0; --i) { - Element newChild = widget.children[i].createElement(); - newChild.mount(this, previousChild); - assert(newChild._debugLifecycleState == _ElementLifecycle.mounted); - _children[i] = newChild; - previousChild = newChild; - } - } - - void update(T newWidget) { - super.update(newWidget); - assert(widget == newWidget); - _children = updateChildren(_children, widget.children); - } -} - -typedef void WidgetsExceptionHandler(String context, dynamic exception, StackTrace stack); -/// This callback is invoked whenever an exception is caught by the widget -/// system. The 'context' argument is a description of what was happening when -/// the exception occurred, and may include additional details such as -/// descriptions of the objects involved. The 'exception' argument contains the -/// object that was thrown, and the 'stack' argument contains the stack trace. -/// If no callback is set, then a default behaviour consisting of dumping the -/// context, exception, and stack trace to the console is used instead. -WidgetsExceptionHandler debugWidgetsExceptionHandler; -void _debugReportException(String context, dynamic exception, StackTrace stack) { - if (debugWidgetsExceptionHandler != null) { - debugWidgetsExceptionHandler(context, exception, stack); - } else { - print('------------------------------------------------------------------------'); - 'Exception caught while $context'.split('\n').forEach(print); - print('$exception'); - print('Stack trace:'); - '$stack'.split('\n').forEach(print); - print('------------------------------------------------------------------------'); - } -} diff --git a/packages/flutter/lib/src/fn3/gesture_detector.dart b/packages/flutter/lib/src/fn3/gesture_detector.dart deleted file mode 100644 index ad3582d410..0000000000 --- a/packages/flutter/lib/src/fn3/gesture_detector.dart +++ /dev/null @@ -1,230 +0,0 @@ -// 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. - -import 'dart:sky' as sky; - -import 'package:sky/gestures.dart'; -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/rendering/binding.dart'; - -class GestureDetector extends StatefulComponent { - const GestureDetector({ - Key key, - this.child, - this.onTap, - this.onShowPress, - this.onLongPress, - this.onVerticalDragStart, - this.onVerticalDragUpdate, - this.onVerticalDragEnd, - this.onHorizontalDragStart, - this.onHorizontalDragUpdate, - this.onHorizontalDragEnd, - this.onPanStart, - this.onPanUpdate, - this.onPanEnd, - this.onScaleStart, - this.onScaleUpdate, - this.onScaleEnd - }) : super(key: key); - - final Widget child; - final GestureTapListener onTap; - final GestureShowPressListener onShowPress; - final GestureLongPressListener onLongPress; - - final GestureDragStartCallback onVerticalDragStart; - final GestureDragUpdateCallback onVerticalDragUpdate; - final GestureDragEndCallback onVerticalDragEnd; - - final GestureDragStartCallback onHorizontalDragStart; - final GestureDragUpdateCallback onHorizontalDragUpdate; - final GestureDragEndCallback onHorizontalDragEnd; - - final GesturePanStartCallback onPanStart; - final GesturePanUpdateCallback onPanUpdate; - final GesturePanEndCallback onPanEnd; - - final GestureScaleStartCallback onScaleStart; - final GestureScaleUpdateCallback onScaleUpdate; - final GestureScaleEndCallback onScaleEnd; - - GestureDetectorState createState() => new GestureDetectorState(); -} - -class GestureDetectorState extends State { - void initState() { - super.initState(); - didUpdateConfig(null); - } - - final PointerRouter _router = FlutterBinding.instance.pointerRouter; - - TapGestureRecognizer _tap; - TapGestureRecognizer _ensureTap() { - if (_tap == null) - _tap = new TapGestureRecognizer(router: _router); - return _tap; - } - - ShowPressGestureRecognizer _showPress; - ShowPressGestureRecognizer _ensureShowPress() { - if (_showPress == null) - _showPress = new ShowPressGestureRecognizer(router: _router); - return _showPress; - } - - LongPressGestureRecognizer _longPress; - LongPressGestureRecognizer _ensureLongPress() { - if (_longPress == null) - _longPress = new LongPressGestureRecognizer(router: _router); - return _longPress; - } - - VerticalDragGestureRecognizer _verticalDrag; - VerticalDragGestureRecognizer _ensureVerticalDrag() { - if (_verticalDrag == null) - _verticalDrag = new VerticalDragGestureRecognizer(router: _router); - return _verticalDrag; - } - - HorizontalDragGestureRecognizer _horizontalDrag; - HorizontalDragGestureRecognizer _ensureHorizontalDrag() { - if (_horizontalDrag == null) - _horizontalDrag = new HorizontalDragGestureRecognizer(router: _router); - return _horizontalDrag; - } - - PanGestureRecognizer _pan; - PanGestureRecognizer _ensurePan() { - assert(_scale == null); // Scale is a superset of pan; just use scale - if (_pan == null) - _pan = new PanGestureRecognizer(router: _router); - return _pan; - } - - ScaleGestureRecognizer _scale; - ScaleGestureRecognizer _ensureScale() { - assert(_pan == null); // Scale is a superset of pan; just use scale - if (_scale == null) - _scale = new ScaleGestureRecognizer(router: _router); - return _scale; - } - - void dispose() { - _tap = _ensureDisposed(_tap); - _showPress = _ensureDisposed(_showPress); - _longPress = _ensureDisposed(_longPress); - _verticalDrag = _ensureDisposed(_verticalDrag); - _horizontalDrag = _ensureDisposed(_horizontalDrag); - _pan = _ensureDisposed(_pan); - _scale = _ensureDisposed(_scale); - super.dispose(); - } - - void didUpdateConfig(GestureDetector oldConfig) { - _syncTap(); - _syncShowPress(); - _syncLongPress(); - _syncVerticalDrag(); - _syncHorizontalDrag(); - _syncPan(); - _syncScale(); - } - - void _syncTap() { - if (config.onTap == null) - _tap = _ensureDisposed(_tap); - else - _ensureTap().onTap = config.onTap; - } - - void _syncShowPress() { - if (config.onShowPress == null) - _showPress = _ensureDisposed(_showPress); - else - _ensureShowPress().onShowPress = config.onShowPress; - } - - void _syncLongPress() { - if (config.onLongPress == null) - _longPress = _ensureDisposed(_longPress); - else - _ensureLongPress().onLongPress = config.onLongPress; - } - - void _syncVerticalDrag() { - if (config.onVerticalDragStart == null && config.onVerticalDragUpdate == null && config.onVerticalDragEnd == null) { - _verticalDrag = _ensureDisposed(_verticalDrag); - } else { - _ensureVerticalDrag() - ..onStart = config.onVerticalDragStart - ..onUpdate = config.onVerticalDragUpdate - ..onEnd = config.onVerticalDragEnd; - } - } - - void _syncHorizontalDrag() { - if (config.onHorizontalDragStart == null && config.onHorizontalDragUpdate == null && config.onHorizontalDragEnd == null) { - _horizontalDrag = _ensureDisposed(_horizontalDrag); - } else { - _ensureHorizontalDrag() - ..onStart = config.onHorizontalDragStart - ..onUpdate = config.onHorizontalDragUpdate - ..onEnd = config.onHorizontalDragEnd; - } - } - - void _syncPan() { - if (config.onPanStart == null && config.onPanUpdate == null && config.onPanEnd == null) { - _pan = _ensureDisposed(_pan); - } else { - _ensurePan() - ..onStart = config.onPanStart - ..onUpdate = config.onPanUpdate - ..onEnd = config.onPanEnd; - } - } - - void _syncScale() { - if (config.onScaleStart == null && config.onScaleUpdate == null && config.onScaleEnd == null) { - _scale = _ensureDisposed(_pan); - } else { - _ensureScale() - ..onStart = config.onScaleStart - ..onUpdate = config.onScaleUpdate - ..onEnd = config.onScaleEnd; - } - } - - GestureRecognizer _ensureDisposed(GestureRecognizer recognizer) { - recognizer?.dispose(); - return null; - } - - void _handlePointerDown(sky.PointerEvent event) { - if (_tap != null) - _tap.addPointer(event); - if (_showPress != null) - _showPress.addPointer(event); - if (_longPress != null) - _longPress.addPointer(event); - if (_verticalDrag != null) - _verticalDrag.addPointer(event); - if (_horizontalDrag != null) - _horizontalDrag.addPointer(event); - if (_pan != null) - _pan.addPointer(event); - if (_scale != null) - _scale.addPointer(event); - } - - Widget build(BuildContext context) { - return new Listener( - onPointerDown: _handlePointerDown, - child: config.child - ); - } -} diff --git a/packages/flutter/lib/src/fn3/homogeneous_viewport.dart b/packages/flutter/lib/src/fn3/homogeneous_viewport.dart deleted file mode 100644 index f5a28b49c3..0000000000 --- a/packages/flutter/lib/src/fn3/homogeneous_viewport.dart +++ /dev/null @@ -1,178 +0,0 @@ -// 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. - -import 'dart:math' as math; - -import 'package:sky/rendering.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/basic.dart'; - -typedef List ListBuilder(BuildContext context, int startIndex, int count); - -class HomogeneousViewport extends RenderObjectWidget { - HomogeneousViewport({ - Key key, - this.builder, - this.itemsWrap: false, - this.itemExtent, // required - this.itemCount, // optional, but you cannot shrink-wrap this class or otherwise use its intrinsic dimensions if you don't specify it - this.direction: ScrollDirection.vertical, - this.startOffset: 0.0 - }) : super(key: key) { - assert(itemExtent != null); - } - - final ListBuilder builder; - final bool itemsWrap; - final double itemExtent; - final int itemCount; - final ScrollDirection direction; - final double startOffset; - - HomogeneousViewportElement createElement() => new HomogeneousViewportElement(this); - - // we don't pass constructor arguments to the RenderBlockViewport() because until - // we know our children, the constructor arguments we could give have no effect - RenderBlockViewport createRenderObject() => new RenderBlockViewport(); - - bool isLayoutDifferentThan(HomogeneousViewport oldWidget) { - return itemsWrap != oldWidget.itemsWrap || - itemsWrap != oldWidget.itemsWrap || - itemExtent != oldWidget.itemExtent || - itemCount != oldWidget.itemCount || - direction != oldWidget.direction || - startOffset != oldWidget.startOffset; - } - - // all the actual work is done in the element -} - -class HomogeneousViewportElement extends RenderObjectElement { - HomogeneousViewportElement(HomogeneousViewport widget) : super(widget); - - List _children = const []; - int _layoutFirstIndex; - int _layoutItemCount; - - RenderBlockViewport get renderObject => super.renderObject; - - void visitChildren(ElementVisitor visitor) { - if (_children == null) - return; - for (Element child in _children) - visitor(child); - } - - void mount(Element parent, dynamic newSlot) { - super.mount(parent, newSlot); - renderObject.callback = layout; - renderObject.totalExtentCallback = getTotalExtent; - renderObject.minCrossAxisExtentCallback = getMinCrossAxisExtent; - renderObject.maxCrossAxisExtentCallback = getMaxCrossAxisExtent; - } - - void unmount() { - renderObject.callback = null; - renderObject.totalExtentCallback = null; - renderObject.minCrossAxisExtentCallback = null; - renderObject.maxCrossAxisExtentCallback = null; - super.unmount(); - } - - void update(HomogeneousViewport newWidget) { - bool needLayout = newWidget.isLayoutDifferentThan(widget); - super.update(newWidget); - if (needLayout) - renderObject.markNeedsLayout(); - else - _updateChildren(); - } - - void layout(BoxConstraints constraints) { - // We enter a build scope (meaning that markNeedsBuild() is forbidden) - // because we are in the middle of layout and if we allowed people to set - // state, they'd expect to have that state reflected immediately, which, if - // we were to try to honour it, would potentially result in assertions - // because you can't normally mutate the render object tree during layout. - // (If there were a way to limit these writes to descendants of this, it'd - // be ok because we are exempt from that assert since we are still actively - // doing our own layout.) - BuildableElement.lockState(() { - double mainAxisExtent = widget.direction == ScrollDirection.vertical ? constraints.maxHeight : constraints.maxWidth; - double offset; - if (widget.startOffset <= 0.0 && !widget.itemsWrap) { - _layoutFirstIndex = 0; - offset = -widget.startOffset; - } else { - _layoutFirstIndex = (widget.startOffset / widget.itemExtent).floor(); - offset = -(widget.startOffset % widget.itemExtent); - } - if (mainAxisExtent < double.INFINITY) { - _layoutItemCount = ((mainAxisExtent - offset) / widget.itemExtent).ceil(); - if (widget.itemCount != null && !widget.itemsWrap) - _layoutItemCount = math.min(_layoutItemCount, widget.itemCount - _layoutFirstIndex); - } else { - assert(() { - 'This HomogeneousViewport has no specified number of items (meaning it has infinite items), ' + - 'and has been placed in an unconstrained environment where all items can be rendered. ' + - 'It is most likely that you have placed your HomogeneousViewport (which is an internal ' + - 'component of several scrollable widgets) inside either another scrolling box, a flexible ' + - 'box (Row, Column), or a Stack, without giving it a specific size.'; - return widget.itemCount != null; - }); - _layoutItemCount = widget.itemCount - _layoutFirstIndex; - } - _layoutItemCount = math.max(0, _layoutItemCount); - _updateChildren(); - // Update the renderObject configuration - renderObject.direction = widget.direction == ScrollDirection.vertical ? BlockDirection.vertical : BlockDirection.horizontal; - renderObject.itemExtent = widget.itemExtent; - renderObject.minExtent = getTotalExtent(null); - renderObject.startOffset = offset; - }); - } - - void _updateChildren() { - assert(_layoutFirstIndex != null); - assert(_layoutItemCount != null); - List newWidgets; - if (_layoutItemCount > 0) - newWidgets = widget.builder(this, _layoutFirstIndex, _layoutItemCount); - else - newWidgets = []; - _children = updateChildren(_children, newWidgets); - } - - double getTotalExtent(BoxConstraints constraints) { - // constraints is null when called by layout() above - return widget.itemCount != null ? widget.itemCount * widget.itemExtent : double.INFINITY; - } - - double getMinCrossAxisExtent(BoxConstraints constraints) { - return 0.0; - } - - double getMaxCrossAxisExtent(BoxConstraints constraints) { - if (widget.direction == ScrollDirection.vertical) - return constraints.maxWidth; - return constraints.maxHeight; - } - - void insertChildRenderObject(RenderObject child, Element slot) { - RenderObject nextSibling = slot?.renderObject; - renderObject.add(child, before: nextSibling); - } - - void moveChildRenderObject(RenderObject child, Element slot) { - assert(child.parent == renderObject); - RenderObject nextSibling = slot?.renderObject; - renderObject.move(child, before: nextSibling); - } - - void removeChildRenderObject(RenderObject child) { - assert(child.parent == renderObject); - renderObject.remove(child); - } - -} diff --git a/packages/flutter/lib/src/fn3/icon.dart b/packages/flutter/lib/src/fn3/icon.dart deleted file mode 100644 index 64945807ac..0000000000 --- a/packages/flutter/lib/src/fn3/icon.dart +++ /dev/null @@ -1,102 +0,0 @@ -// 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. - -import 'dart:sky' as sky; - -import 'package:sky/services.dart'; -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/theme.dart'; -import 'package:sky/src/fn3/framework.dart'; - -enum IconThemeColor { white, black } - -class IconThemeData { - const IconThemeData({ this.color }); - final IconThemeColor color; -} - -class IconTheme extends InheritedWidget { - - IconTheme({ - Key key, - this.data, - Widget child - }) : super(key: key, child: child) { - assert(data != null); - assert(child != null); - } - - final IconThemeData data; - - static IconThemeData of(BuildContext context) { - IconTheme result = context.inheritedWidgetOfType(IconTheme); - return result?.data; - } - - bool updateShouldNotify(IconTheme old) => data != old.data; - -} - -AssetBundle _initIconBundle() { - if (rootBundle != null) - return rootBundle; - const String _kAssetBase = '/packages/material_design_icons/icons/'; - return new NetworkAssetBundle(Uri.base.resolve(_kAssetBase)); -} - -final AssetBundle _iconBundle = _initIconBundle(); - -class Icon extends StatelessComponent { - Icon({ - Key key, - this.size, - this.type: '', - this.color, - this.colorFilter - }) : super(key: key); - - final int size; - final String type; - final IconThemeColor color; - final sky.ColorFilter colorFilter; - - String getColorSuffix(BuildContext context) { - IconThemeColor iconThemeColor = color; - if (iconThemeColor == null) { - IconThemeData iconThemeData = IconTheme.of(context); - iconThemeColor = iconThemeData == null ? null : iconThemeData.color; - } - if (iconThemeColor == null) { - ThemeBrightness themeBrightness = Theme.of(context).brightness; - iconThemeColor = themeBrightness == ThemeBrightness.dark ? IconThemeColor.white : IconThemeColor.black; - } - switch(iconThemeColor) { - case IconThemeColor.white: - return "white"; - case IconThemeColor.black: - return "black"; - } - } - - Widget build(BuildContext context) { - String category = ''; - String subtype = ''; - List parts = type.split('/'); - if (parts.length == 2) { - category = parts[0]; - subtype = parts[1]; - } - // TODO(eseidel): This clearly isn't correct. Not sure what would be. - // Should we use the ios images on ios? - String density = 'drawable-xxhdpi'; - String colorSuffix = getColorSuffix(context); - return new AssetImage( - bundle: _iconBundle, - name: '${category}/${density}/ic_${subtype}_${colorSuffix}_${size}dp.png', - width: size.toDouble(), - height: size.toDouble(), - colorFilter: colorFilter - ); - } -} diff --git a/packages/flutter/lib/src/fn3/icon_button.dart b/packages/flutter/lib/src/fn3/icon_button.dart deleted file mode 100644 index 15ce46f2ac..0000000000 --- a/packages/flutter/lib/src/fn3/icon_button.dart +++ /dev/null @@ -1,35 +0,0 @@ -// 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. - -import 'dart:sky' as sky; - -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/icon.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/gesture_detector.dart'; - -class IconButton extends StatelessComponent { - const IconButton({ Key key, this.icon, this.onPressed, this.color }) : super(key: key); - - final String icon; - final Function onPressed; - final Color color; - - Widget build(BuildContext context) { - Widget child = new Icon(type: icon, size: 24); - if (color != null) { - child = new ColorFilter( - color: color, - transferMode: sky.TransferMode.srcATop, - child: child - ); - } - return new GestureDetector( - onTap: onPressed, - child: new Padding( - child: child, - padding: const EdgeDims.all(8.0)) - ); - } -} diff --git a/packages/flutter/lib/src/fn3/ink_well.dart b/packages/flutter/lib/src/fn3/ink_well.dart deleted file mode 100644 index 531bb08cd5..0000000000 --- a/packages/flutter/lib/src/fn3/ink_well.dart +++ /dev/null @@ -1,131 +0,0 @@ -// 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. - -import 'dart:math' as math; -import 'dart:sky' as sky; - -import 'package:sky/animation.dart'; -import 'package:sky/rendering.dart'; -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/framework.dart'; - -const int _kSplashInitialOpacity = 0x30; -const double _kSplashCancelledVelocity = 0.7; -const double _kSplashConfirmedVelocity = 0.7; -const double _kSplashInitialSize = 0.0; -const double _kSplashUnconfirmedVelocity = 0.2; - -double _getSplashTargetSize(Size bounds, Point position) { - double d1 = (position - bounds.topLeft(Point.origin)).distance; - double d2 = (position - bounds.topRight(Point.origin)).distance; - double d3 = (position - bounds.bottomLeft(Point.origin)).distance; - double d4 = (position - bounds.bottomRight(Point.origin)).distance; - return math.max(math.max(d1, d2), math.max(d3, d4)).ceil().toDouble(); -} - -class InkSplash { - InkSplash(this.pointer, this.position, this.well) { - _targetRadius = _getSplashTargetSize(well.size, position); - _radius = new AnimatedValue( - _kSplashInitialSize, end: _targetRadius, curve: easeOut); - - _performance = new ValueAnimation( - variable: _radius, - duration: new Duration(milliseconds: (_targetRadius / _kSplashUnconfirmedVelocity).floor()) - )..addListener(_handleRadiusChange) - ..play(); - } - - final int pointer; - final Point position; - final RenderInkWell well; - - double _targetRadius; - double _pinnedRadius; - AnimatedValue _radius; - AnimationPerformance _performance; - - void _updateVelocity(double velocity) { - int duration = (_targetRadius / velocity).floor(); - _performance - ..duration = new Duration(milliseconds: duration) - ..play(); - } - - void confirm() { - _updateVelocity(_kSplashConfirmedVelocity); - } - - void cancel() { - _updateVelocity(_kSplashCancelledVelocity); - _pinnedRadius = _radius.value; - } - - void _handleRadiusChange() { - if (_radius.value == _targetRadius) - well._splashes.remove(this); - well.markNeedsPaint(); - } - - void paint(PaintingCanvas canvas) { - int opacity = (_kSplashInitialOpacity * (1.1 - (_radius.value / _targetRadius))).floor(); - sky.Paint paint = new sky.Paint()..color = new sky.Color(opacity << 24); - double radius = _pinnedRadius == null ? _radius.value : _pinnedRadius; - canvas.drawCircle(position, radius, paint); - } -} - -class RenderInkWell extends RenderProxyBox { - RenderInkWell({ RenderBox child }) : super(child); - - final List _splashes = new List(); - - void handleEvent(sky.Event event, BoxHitTestEntry entry) { - // TODO(abarth): We should trigger these effects based on gestures. - // https://github.com/flutter/engine/issues/1271 - if (event is sky.PointerEvent) { - switch (event.type) { - case 'pointerdown': - _startSplash(event.pointer, entry.localPosition); - break; - case 'pointerup': - _confirmSplash(event.pointer); - break; - } - } - } - - void _startSplash(int pointer, Point position) { - _splashes.add(new InkSplash(pointer, position, this)); - markNeedsPaint(); - } - - void _forEachSplash(int pointer, Function callback) { - _splashes.where((splash) => splash.pointer == pointer) - .forEach(callback); - } - - void _confirmSplash(int pointer) { - _forEachSplash(pointer, (splash) { splash.confirm(); }); - markNeedsPaint(); - } - - void paint(PaintingContext context, Offset offset) { - if (!_splashes.isEmpty) { - final PaintingCanvas canvas = context.canvas; - canvas.save(); - canvas.translate(offset.dx, offset.dy); - canvas.clipRect(Point.origin & size); - for (InkSplash splash in _splashes) - splash.paint(canvas); - canvas.restore(); - } - super.paint(context, offset); - } -} - -class InkWell extends OneChildRenderObjectWidget { - InkWell({ Key key, Widget child }) : super(key: key, child: child); - RenderInkWell createRenderObject() => new RenderInkWell(); -} diff --git a/packages/flutter/lib/src/fn3/input.dart b/packages/flutter/lib/src/fn3/input.dart deleted file mode 100644 index 2f9d9d470e..0000000000 --- a/packages/flutter/lib/src/fn3/input.dart +++ /dev/null @@ -1,164 +0,0 @@ -// 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. - -import 'package:sky/animation.dart'; -import 'package:sky/services.dart'; -import 'package:sky/painting.dart'; -import 'package:sky/rendering.dart'; -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/editable_text.dart'; -import 'package:sky/src/fn3/focus.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/scrollable.dart'; -import 'package:sky/src/fn3/theme.dart'; - -export 'package:sky/services.dart' show KeyboardType; - -typedef void StringValueChanged(String value); - -// TODO(eseidel): This isn't right, it's 16px on the bottom: -// http://www.google.com/design/spec/components/text-fields.html#text-fields-single-line-text-field -const EdgeDims _kTextfieldPadding = const EdgeDims.symmetric(vertical: 8.0); - -class Input extends Scrollable { - Input({ - GlobalKey key, - this.initialValue: '', - this.placeholder, - this.onChanged, - this.keyboardType: KeyboardType.TEXT - }): super( - key: key, - initialScrollOffset: 0.0, - scrollDirection: ScrollDirection.horizontal - ); - - final String initialValue; - final KeyboardType keyboardType; - final String placeholder; - final StringValueChanged onChanged; - - InputState createState() => new InputState(); -} - -class InputState extends ScrollableState { - String _value; - EditableString _editableValue; - KeyboardHandle _keyboardHandle = KeyboardHandle.unattached; - - double _contentWidth = 0.0; - double _containerWidth = 0.0; - - void initState() { - super.initState(); - _value = config.initialValue; - _editableValue = new EditableString( - text: _value, - onUpdated: _handleTextUpdated - ); - } - - void _handleTextUpdated() { - if (_value != _editableValue.text) { - setState(() { - _value = _editableValue.text; - }); - if (config.onChanged != null) - config.onChanged(_value); - } - } - - Widget buildContent(BuildContext context) { - ThemeData themeData = Theme.of(context); - bool focused = FocusState.at(context, config); - - if (focused && !_keyboardHandle.attached) { - _keyboardHandle = keyboard.show(_editableValue.stub, config.keyboardType); - } else if (!focused && _keyboardHandle.attached) { - _keyboardHandle.release(); - } - - TextStyle textStyle = themeData.text.subhead; - List textChildren = []; - - if (config.placeholder != null && _value.isEmpty) { - Widget child = new Opacity( - key: const ValueKey('placeholder'), - child: new Text(config.placeholder, style: textStyle), - opacity: themeData.hintOpacity - ); - textChildren.add(child); - } - - Color focusHighlightColor = themeData.accentColor; - Color cursorColor = themeData.accentColor; - if (themeData.primarySwatch != null) { - cursorColor = themeData.primarySwatch[200]; - focusHighlightColor = focused ? themeData.primarySwatch[400] : themeData.hintColor; - } - - textChildren.add(new EditableText( - value: _editableValue, - focused: focused, - style: textStyle, - cursorColor: cursorColor, - onContentSizeChanged: _handleContentSizeChanged, - scrollOffset: scrollOffsetVector - )); - - return new Listener( - child: new SizeObserver( - callback: _handleContainerSizeChanged, - child: new Container( - child: new Stack(textChildren), - padding: _kTextfieldPadding, - decoration: new BoxDecoration(border: new Border( - bottom: new BorderSide( - color: focusHighlightColor, - width: focused ? 2.0 : 1.0 - ) - )) - ) - ), - onPointerDown: (_) { - if (FocusState.at(context, config)) { - assert(_keyboardHandle.attached); - _keyboardHandle.showByRequest(); - } else { - FocusState.moveTo(context, config); - // we'll get told to rebuild and we'll take care of the keyboard then - } - } - ); - } - - void dispose() { - if (_keyboardHandle.attached) - _keyboardHandle.release(); - super.dispose(); - } - - ScrollBehavior createScrollBehavior() => new BoundedBehavior(); - BoundedBehavior get scrollBehavior => super.scrollBehavior; - - void _handleContainerSizeChanged(Size newSize) { - _containerWidth = newSize.width; - _updateScrollBehavior(); - } - - void _handleContentSizeChanged(Size newSize) { - _contentWidth = newSize.width; - _updateScrollBehavior(); - } - - void _updateScrollBehavior() { - // Set the scroll offset to match the content width so that the cursor - // (which is always at the end of the text) will be visible. - scrollTo(scrollBehavior.updateExtents( - contentExtent: _contentWidth, - containerExtent: _containerWidth, - scrollOffset: _contentWidth) - ); - } -} diff --git a/packages/flutter/lib/src/fn3/material.dart b/packages/flutter/lib/src/fn3/material.dart deleted file mode 100644 index f0cc146cdf..0000000000 --- a/packages/flutter/lib/src/fn3/material.dart +++ /dev/null @@ -1,78 +0,0 @@ -// 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. - -import 'package:sky/painting.dart'; -import 'package:sky/material.dart'; -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/theme.dart'; - -enum MaterialType { canvas, card, circle, button } - -const Map edges = const { - MaterialType.canvas: null, - MaterialType.card: 2.0, - MaterialType.circle: null, - MaterialType.button: 2.0, -}; - -class Material extends StatelessComponent { - Material({ - Key key, - this.child, - this.type: MaterialType.card, - this.level: 0, - this.color - }) : super(key: key) { - assert(level != null); - } - - final Widget child; - final MaterialType type; - final int level; - final Color color; - - Color getBackgroundColor(BuildContext context) { - if (color != null) - return color; - switch (type) { - case MaterialType.canvas: - return Theme.of(context).canvasColor; - case MaterialType.card: - return Theme.of(context).cardColor; - default: - return null; - } - } - - Widget build(BuildContext context) { - Widget contents = child; - if (child != null) { - contents = new DefaultTextStyle( - style: Theme.of(context).text.body1, - child: contents - ); - if (edges[type] != null) { - contents = new ClipRRect( - xRadius: edges[type], - yRadius: edges[type], - child: contents - ); - } - } - // TODO(abarth): This should use AnimatedContainer. - return new DefaultTextStyle( - style: Theme.of(context).text.body1, - child: new Container( - decoration: new BoxDecoration( - backgroundColor: getBackgroundColor(context), - borderRadius: edges[type], - boxShadow: level == 0 ? null : shadows[level], - shape: type == MaterialType.circle ? Shape.circle : Shape.rectangle - ), - child: contents - ) - ); - } -} diff --git a/packages/flutter/lib/src/fn3/material_button.dart b/packages/flutter/lib/src/fn3/material_button.dart deleted file mode 100644 index c2a647ba08..0000000000 --- a/packages/flutter/lib/src/fn3/material_button.dart +++ /dev/null @@ -1,55 +0,0 @@ -// 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. - -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/button_state.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/gesture_detector.dart'; -import 'package:sky/src/fn3/ink_well.dart'; -import 'package:sky/src/fn3/material.dart'; - -// Rather than using this class directly, please use FlatButton or RaisedButton. -abstract class MaterialButton extends StatefulComponent { - MaterialButton({ - Key key, - this.child, - this.enabled: true, - this.onPressed - }) : super(key: key) { - assert(enabled != null); - } - - final Widget child; - final bool enabled; - final Function onPressed; -} - -abstract class MaterialButtonState extends ButtonState { - Color getColor(BuildContext context); - int get level; - - Widget buildContent(BuildContext context) { - Widget contents = new Container( - padding: new EdgeDims.symmetric(horizontal: 8.0), - child: new Center( - shrinkWrap: ShrinkWrap.width, - child: config.child // TODO(ianh): figure out a way to compell the child to have gray text when disabled... - ) - ); - return new GestureDetector( - onTap: config.enabled ? config.onPressed : null, - child: new Container( - height: 36.0, - constraints: new BoxConstraints(minWidth: 88.0), - margin: new EdgeDims.all(8.0), - child: new Material( - type: MaterialType.button, - child: config.enabled ? new InkWell(child: contents) : contents, - level: level, - color: getColor(context) - ) - ) - ); - } -} diff --git a/packages/flutter/lib/src/fn3/mimic.dart b/packages/flutter/lib/src/fn3/mimic.dart deleted file mode 100644 index 2933be6cd8..0000000000 --- a/packages/flutter/lib/src/fn3/mimic.dart +++ /dev/null @@ -1,87 +0,0 @@ -// 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. - -import 'package:sky/rendering.dart'; -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/framework.dart'; - -class MimicableKey { - MimicableKey._(this._state); - - final MimicableState _state; - - Rect get globalBounds => _state._globalBounds; - - void stopMimic() { - _state._stopMimic(); - } -} - -class Mimic extends StatelessComponent { - Mimic({ Key key, this.original }) : super(key: key); - - final MimicableKey original; - - Widget build(BuildContext context) { - if (original != null && original._state._beingMimicked) - return original._state.config.child; - return new Container(); - } -} - -class Mimicable extends StatefulComponent { - Mimicable({ Key key, this.child }) : super(key: key); - - final Widget child; - - MimicableState createState() => new MimicableState(); -} - -class MimicableState extends State { - Size _size; - bool _beingMimicked = false; - - MimicableKey startMimic() { - assert(!_beingMimicked); - assert(_size != null); - setState(() { - _beingMimicked = true; - }); - return new MimicableKey._(this); - } - - void _stopMimic() { - assert(_beingMimicked); - if (!mounted) { - _beingMimicked = false; - return; - } - setState(() { - _beingMimicked = false; - }); - } - - Rect get _globalBounds { - RenderBox box = context.findRenderObject(); - return box.localToGlobal(Point.origin) & box.size; - } - - void _handleSizeChanged(Size size) { - setState(() { - _size = size; - }); - } - - Widget build(BuildContext context) { - if (_beingMimicked) { - return new ConstrainedBox( - constraints: new BoxConstraints.tight(_size) - ); - } - return new SizeObserver( - callback: _handleSizeChanged, - child: config.child - ); - } -} diff --git a/packages/flutter/lib/src/fn3/mixed_viewport.dart b/packages/flutter/lib/src/fn3/mixed_viewport.dart deleted file mode 100644 index b60679e618..0000000000 --- a/packages/flutter/lib/src/fn3/mixed_viewport.dart +++ /dev/null @@ -1,592 +0,0 @@ -// 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. - -import 'package:sky/rendering.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/basic.dart'; - -typedef Widget IndexedBuilder(BuildContext context, int index); // return null if index is greater than index of last entry -typedef void ExtentsUpdateCallback(double newExtents); -typedef void InvalidatorCallback(Iterable indices); -typedef void InvalidatorAvailableCallback(InvalidatorCallback invalidator); - -enum _ChangeDescription { none, scrolled, resized } - -class MixedViewport extends RenderObjectWidget { - MixedViewport({ - Key key, - this.startOffset, - this.direction: ScrollDirection.vertical, - this.builder, - this.token, - this.onExtentsUpdate, - this.onInvalidatorAvailable - }): super(key: key); - - final double startOffset; - final ScrollDirection direction; - final IndexedBuilder builder; - final Object token; - final ExtentsUpdateCallback onExtentsUpdate; - final InvalidatorAvailableCallback onInvalidatorAvailable; - - MixedViewportElement createElement() => new MixedViewportElement(this); - - // we don't pass constructor arguments to the RenderBlockViewport() because until - // we know our children, the constructor arguments we could give have no effect - RenderBlockViewport createRenderObject() => new RenderBlockViewport(); - - _ChangeDescription evaluateChangesFrom(MixedViewport oldWidget) { - if (direction != oldWidget.direction || - builder != oldWidget.builder || - token != oldWidget.token) - return _ChangeDescription.resized; - if (startOffset != oldWidget.startOffset) - return _ChangeDescription.scrolled; - return _ChangeDescription.none; - } - - // all the actual work is done in the element -} - -class _ChildKey { - const _ChildKey(this.type, this.key); - factory _ChildKey.fromWidget(Widget widget) => new _ChildKey(widget.runtimeType, widget.key); - final Type type; - final Key key; - bool operator ==(other) => other is _ChildKey && other.type == type && other.key == key; - int get hashCode => 373 * 37 * type.hashCode + key.hashCode; - String toString() => "_ChildKey(type: $type, key: $key)"; -} - -class MixedViewportElement extends RenderObjectElement { - MixedViewportElement(MixedViewport widget) : super(widget) { - if (widget.onInvalidatorAvailable != null) - widget.onInvalidatorAvailable(invalidate); - } - - /// _childExtents contains the extents of each child from the top of the list - /// up to the last one we've ever created. - final List _childExtents = []; - - /// _childOffsets contains the offsets of the top of each child from the top - /// of the list up to the last one we've ever created, and the offset of the - /// end of the last one. The first value is always 0.0. If there are no - /// children, that is the only value. The offset of the end of the last child - /// created (the actual last child, if didReachLastChild is true), is also the - /// distance from the top (left) of the first child to the bottom (right) of - /// the last child created. - final List _childOffsets = [0.0]; - - /// Whether childOffsets includes the offset of the last child. - bool _didReachLastChild = false; - - /// The index of the first child whose bottom edge is below the top of the - /// viewport. - int _firstVisibleChildIndex; - - /// The currently visibly children. - Map<_ChildKey, Element> _childrenByKey = new Map<_ChildKey, Element>(); - - /// The child offsets that we've been told are invalid. - final Set _invalidIndices = new Set(); - - /// Returns false if any of the previously-cached offsets have been marked as - /// invalid and need to be updated. - bool get isValid => _invalidIndices.length == 0; - - /// The constraints for which the current offsets are valid. - BoxConstraints _lastLayoutConstraints; - - /// The last value that was sent to onExtentsUpdate. - double _lastReportedExtents; - - RenderBlockViewport get renderObject => super.renderObject; - - /// Notify the BlockViewport that the children at indices have, or might have, - /// changed size. Call this whenever the dimensions of a particular child - /// change, so that the rendering will be updated accordingly. A pointer to - /// this method is provided via the onInvalidatorAvailable callback. - void invalidate(Iterable indices) { - assert(indices.length > 0); - _invalidIndices.addAll(indices); - renderObject.markNeedsLayout(); - } - - /// Forget all the known child offsets. - void _resetCache() { - _childExtents.clear(); - _childOffsets.clear(); - _childOffsets.add(0.0); - _didReachLastChild = false; - _invalidIndices.clear(); - } - - void visitChildren(ElementVisitor visitor) { - for (Element child in _childrenByKey.values) - visitor(child); - } - - void mount(Element parent, dynamic newSlot) { - super.mount(parent, newSlot); - renderObject.callback = layout; - renderObject.totalExtentCallback = _noIntrinsicExtent; - renderObject.maxCrossAxisExtentCallback = _noIntrinsicExtent; - renderObject.minCrossAxisExtentCallback = _noIntrinsicExtent; - } - - void unmount() { - renderObject.callback = null; - renderObject.totalExtentCallback = null; - renderObject.minCrossAxisExtentCallback = null; - renderObject.maxCrossAxisExtentCallback = null; - super.unmount(); - } - - double _noIntrinsicExtent(BoxConstraints constraints) { - assert(() { - 'MixedViewport does not support returning intrinsic dimensions. ' + - 'Calculating the intrinsic dimensions would require walking the entire child list, ' + - 'which defeats the entire point of having a lazily-built list of children.'; - return false; - }); - return null; - } - - static const Object _omit = const Object(); // used as a slot when it's not yet time to attach the child - - void update(MixedViewport newWidget) { - _ChangeDescription changes = newWidget.evaluateChangesFrom(widget); - super.update(newWidget); - if (changes == _ChangeDescription.resized) - _resetCache(); - if (changes != _ChangeDescription.none || !isValid) { - renderObject.markNeedsLayout(); - } else { - // we just need to redraw our existing widgets as-is - if (_childrenByKey.length > 0) { - assert(_firstVisibleChildIndex >= 0); - assert(renderObject != null); - final int startIndex = _firstVisibleChildIndex; - int lastIndex = startIndex + _childrenByKey.length - 1; - Element nextSibling = null; - for (int index = lastIndex; index > startIndex; index -= 1) { - final Widget newWidget = _buildWidgetAt(index); - final _ChildKey key = new _ChildKey.fromWidget(newWidget); - final Element oldElement = _childrenByKey[key]; - assert(oldElement != null); - final Element newElement = updateChild(oldElement, newWidget, nextSibling); - assert(newElement != null); - _childrenByKey[key] = newElement; - // Verify that it hasn't changed size. - // If this assertion fires, it means you didn't call "invalidate" - // before changing the size of one of your items. - assert(_debugIsSameSize(newElement, index, _lastLayoutConstraints)); - nextSibling = newElement; - } - } - } - } - - void layout(BoxConstraints constraints) { - if (constraints != _lastLayoutConstraints) { - _resetCache(); - _lastLayoutConstraints = constraints; - } - BuildableElement.lockState(() { - _doLayout(constraints); - }); - if (widget.onExtentsUpdate != null) { - final double newExtents = _didReachLastChild ? _childOffsets.last : null; - if (newExtents != _lastReportedExtents) { - _lastReportedExtents = newExtents; - widget.onExtentsUpdate(_lastReportedExtents); - } - } - } - - /// Binary search to find the index of the child responsible for rendering a given pixel - int _findIndexForOffsetBeforeOrAt(double offset) { - int left = 0; - int right = _childOffsets.length - 1; - while (right >= left) { - int middle = left + ((right - left) ~/ 2); - if (_childOffsets[middle] < offset) { - left = middle + 1; - } else if (_childOffsets[middle] > offset) { - right = middle - 1; - } else { - return middle; - } - } - return right; - } - - /// Calls the builder. This is for the case where you don't know if you have a child at this index. - Widget _maybeBuildWidgetAt(int index) { - if (widget.builder == null) - return null; - final Widget newWidget = widget.builder(this, index); - assert(newWidget == null || newWidget.key != null); // every widget in a list must have a list-unique key - return newWidget; - } - - /// Calls the builder. This is for the case where you know that you should have a child there. - Widget _buildWidgetAt(int index) { - final Widget newWidget = widget.builder(this, index); - assert(newWidget != null); - assert(newWidget.key != null); // every widget in a list must have a list-unique key - return newWidget; - } - - /// Given an element configuration, inflates the element, updating the existing one if there was one. - /// Returns the resulting element. - Element _inflateOrUpdateWidget(Widget newWidget) { - final _ChildKey key = new _ChildKey.fromWidget(newWidget); - final Element oldElement = _childrenByKey[key]; - final Element newElement = updateChild(oldElement, newWidget, _omit); - assert(newElement != null); - return newElement; - } - - // Build the widget at index. - Element _getElement(int index, BoxConstraints innerConstraints) { - assert(index <= _childOffsets.length - 1); - final Widget newWidget = _buildWidgetAt(index); - final Element newElement = _inflateOrUpdateWidget(newWidget); - return newElement; - } - - // Build the widget at index. - Element _maybeGetElement(int index, BoxConstraints innerConstraints) { - assert(index <= _childOffsets.length - 1); - final Widget newWidget = _maybeBuildWidgetAt(index); - if (newWidget == null) - return null; - final Element newElement = _inflateOrUpdateWidget(newWidget); - return newElement; - } - - // Build the widget at index, handling the case where there is no such widget. - // Update the offset for that widget. - Element _getElementAtLastKnownOffset(int index, BoxConstraints innerConstraints) { - - // Inflate the new widget; if there isn't one, abort early. - assert(index == _childOffsets.length - 1); - final Widget newWidget = _maybeBuildWidgetAt(index); - if (newWidget == null) - return null; - final Element newElement = _inflateOrUpdateWidget(newWidget); - - // Update the offsets based on the newElement's dimensions. - final double newExtent = _getElementExtent(newElement, innerConstraints); - _childExtents.add(newExtent); - _childOffsets.add(_childOffsets[index] + newExtent); - assert(_childExtents.length == _childOffsets.length - 1); - - return newElement; - } - - /// Returns the intrinsic size of the given element in the scroll direction - double _getElementExtent(Element element, BoxConstraints innerConstraints) { - final RenderBox childRenderObject = element.renderObject; - switch (widget.direction) { - case ScrollDirection.vertical: - return childRenderObject.getMaxIntrinsicHeight(innerConstraints); - case ScrollDirection.horizontal: - return childRenderObject.getMaxIntrinsicWidth(innerConstraints); - case ScrollDirection.both: - assert(false); // we don't support ScrollDirection.both, see issue 888 - return double.NAN; - } - } - - BoxConstraints _getInnerConstraints(BoxConstraints constraints) { - switch (widget.direction) { - case ScrollDirection.vertical: - return new BoxConstraints.tightFor(width: constraints.constrainWidth()); - case ScrollDirection.horizontal: - return new BoxConstraints.tightFor(height: constraints.constrainHeight()); - case ScrollDirection.both: - assert(false); // we don't support ScrollDirection.both, see issue 888 - return null; - } - } - - /// This compares the offsets we had for an element with its current - /// intrinsic dimensions. - bool _debugIsSameSize(Element element, int index, BoxConstraints constraints) { - assert(_invalidIndices.isEmpty); - BoxConstraints innerConstraints = _getInnerConstraints(constraints); - double newExtent = _getElementExtent(element, innerConstraints); - bool result = _childExtents[index] == newExtent; - if (!result) - print("Element $element at index $index was size ${_childExtents[index]} but is now size ${newExtent} yet no invalidate() was received to that effect"); - return result; - } - - /// This is the core lazy-build algorithm. It builds widgets incrementally - /// from index 0 until it has built enough widgets to cover itself, and - /// discards any widgets that are not displayed. - void _doLayout(BoxConstraints constraints) { - Map<_ChildKey, Element> newChildren = new Map<_ChildKey, Element>(); - Map builtChildren = new Map(); - - // Establish the start and end offsets based on our current constraints. - double extent; - switch (widget.direction) { - case ScrollDirection.vertical: - extent = constraints.maxHeight; - assert(extent < double.INFINITY && - 'There is no point putting a lazily-built vertical MixedViewport inside a box with infinite internal ' + - 'height (e.g. inside something else that scrolls vertically), because it would then just eagerly build ' + - 'all the children. You probably want to put the MixedViewport inside a Container with a fixed height.' is String); - break; - case ScrollDirection.horizontal: - extent = constraints.maxWidth; - assert(extent < double.INFINITY && - 'There is no point putting a lazily-built horizontal MixedViewport inside a box with infinite internal ' + - 'width (e.g. inside something else that scrolls horizontally), because it would then just eagerly build ' + - 'all the children. You probably want to put the MixedViewport inside a Container with a fixed width.' is String); - break; - case ScrollDirection.both: assert(false); // we don't support ScrollDirection.both, see issue 888 - } - final double endOffset = widget.startOffset + extent; - - // Create the constraints that we will use to measure the children. - final BoxConstraints innerConstraints = _getInnerConstraints(constraints); - - // Before doing the actual layout, fix the offsets for the widgets whose - // size has apparently changed. - if (!isValid) { - assert(_childOffsets.length > 0); - assert(_childOffsets.length == _childExtents.length + 1); - List invalidIndices = _invalidIndices.toList(); - invalidIndices.sort(); - for (int i = 0; i < invalidIndices.length; i += 1) { - - // Determine the indices for this pass. - final int widgetIndex = invalidIndices[i]; - if (widgetIndex >= _childExtents.length) - break; // we don't have that child, so there's nothing to invalidate - int endIndex; // the last index into _childOffsets that we want to update this round - if (i == invalidIndices.length - 1) { - // This is the last invalid index. Update all the remaining entries in _childOffsets. - endIndex = _childOffsets.length - 1; - } else { - endIndex = invalidIndices[i + 1]; - if (endIndex > _childOffsets.length - 1) - endIndex = _childOffsets.length - 1; // no point updating beyond the last offset we know of - } - assert(widgetIndex >= 0); - assert(endIndex < _childOffsets.length); - assert(widgetIndex < endIndex); - - // Inflate the widget or update the existing element, as necessary. - final Element newElement = _getElement(widgetIndex, innerConstraints); - - // Update the offsets based on the newElement's dimensions. - _childExtents[widgetIndex] = _getElementExtent(newElement, innerConstraints); - for (int j = widgetIndex + 1; j <= endIndex; j++) - _childOffsets[j] = _childOffsets[j - 1] + _childExtents[j - 1]; - assert(_childOffsets.length == _childExtents.length + 1); - - // Decide if it's visible. - final _ChildKey key = new _ChildKey.fromWidget(newElement.widget); - final bool isVisible = _childOffsets[widgetIndex] < endOffset && _childOffsets[widgetIndex + 1] >= widget.startOffset; - if (isVisible) { - // Keep it. - newChildren[key] = newElement; - builtChildren[widgetIndex] = newElement; - } else { - // Drop it. - _childrenByKey.remove(key); - updateChild(newElement, null, null); - } - - } - _invalidIndices.clear(); - } - - // Decide what the first child to render should be (startIndex), if any (haveChildren). - int startIndex; - bool haveChildren; - if (endOffset < 0.0) { - // We're so far scrolled up that nothing is visible. - haveChildren = false; - } else if (widget.startOffset <= 0.0) { - startIndex = 0; - // If we're scrolled up past the top, then our first visible widget, if - // any, is the first widget. - if (_childExtents.length > 0) { - haveChildren = true; - } else { - final Element element = _getElementAtLastKnownOffset(startIndex, innerConstraints); - if (element != null) { - newChildren[new _ChildKey.fromWidget(element.widget)] = element; - builtChildren[startIndex] = element; - haveChildren = true; - } else { - haveChildren = false; - _didReachLastChild = true; - } - } - } else { - // We're at some sane (not higher than the top) scroll offset. - // See if we can already find the offset in our cache. - startIndex = _findIndexForOffsetBeforeOrAt(widget.startOffset); - if (startIndex < _childExtents.length) { - // We already know of a child that would be visible at this offset. - haveChildren = true; - } else { - // We don't have an offset on the list that is beyond the start offset. - assert(_childOffsets.last <= widget.startOffset); - // Fill the list until this isn't true or until we know that the - // list is complete (and thus we are overscrolled). - while (true) { - // Get the next element and cache its offset. - final Element element = _getElementAtLastKnownOffset(startIndex, innerConstraints); - if (element == null) { - // Reached the end of the list. We are so far overscrolled, there's nothing to show. - _didReachLastChild = true; - haveChildren = false; - break; - } - final _ChildKey key = new _ChildKey.fromWidget(element.widget); - if (_childOffsets.last > widget.startOffset) { - // This element is visible! It must thus be our first visible child. - newChildren[key] = element; - builtChildren[startIndex] = element; - haveChildren = true; - break; - } - // This element is not visible. Drop the inflated element. - // (We've already cached its offset for later use.) - _childrenByKey.remove(key); - updateChild(element, null, null); - startIndex += 1; - assert(startIndex == _childExtents.length); - } - assert(haveChildren == _childOffsets.last > widget.startOffset); - assert(() { - if (haveChildren) { - // We found a child to render. It's the last one for which we have an - // offset in _childOffsets. - // If we're here, we have at least one child, so our list has - // at least two offsets, the top of the child and the bottom - // of the child. - assert(_childExtents.length >= 1); - assert(_childOffsets.length == _childExtents.length + 1); - assert(startIndex == _childExtents.length - 1); - } - return true; - }); - } - } - assert(haveChildren != null); - assert(haveChildren || _didReachLastChild || endOffset < 0.0); - assert(startIndex >= 0); - assert(startIndex < _childExtents.length); - - // Build the other widgets that are visible. - int index = startIndex; - if (haveChildren) { - // Update the renderObject configuration - switch (widget.direction) { - case ScrollDirection.vertical: - renderObject.direction = BlockDirection.vertical; - break; - case ScrollDirection.horizontal: - renderObject.direction = BlockDirection.horizontal; - break; - case ScrollDirection.both: assert(false); // we don't support ScrollDirection.both, see issue 888 - } - renderObject.startOffset = _childOffsets[index] - widget.startOffset; - // Build all the widgets we still need. - while (_childOffsets[index] < endOffset) { - if (!builtChildren.containsKey(index)) { - Element element = _maybeGetElement(index, innerConstraints); - if (element == null) { - _didReachLastChild = true; - break; - } - if (index == _childExtents.length) { - // Remember this element's offset. - final double newExtent = _getElementExtent(element, innerConstraints); - _childExtents.add(newExtent); - _childOffsets.add(_childOffsets[index] + newExtent); - assert(_childOffsets.length == _childExtents.length + 1); - } else { - // Verify that it hasn't changed size. - // If this assertion fires, it means you didn't call "invalidate" - // before changing the size of one of your items. - assert(_debugIsSameSize(element, index, constraints)); - } - // Remember the element for when we place the children. - final _ChildKey key = new _ChildKey.fromWidget(element.widget); - newChildren[key] = element; - builtChildren[index] = element; - } - assert(builtChildren[index] != null); - index += 1; - } - } - - // Remove any old children. - for (_ChildKey oldChildKey in _childrenByKey.keys) { - if (!newChildren.containsKey(oldChildKey)) - updateChild(_childrenByKey[oldChildKey], null, null); - } - - if (haveChildren) { - // Place all our children in our RenderObject. - // All the children we are placing are in builtChildren and newChildren. - // We will walk them backwards so we can set the slots at the same time. - Element nextSibling = null; - while (index > startIndex) { - index -= 1; - final Element element = builtChildren[index]; - if (element.slot != nextSibling) - updateSlotForChild(element, nextSibling); - nextSibling = element; - } - } - - // Update our internal state. - _childrenByKey = newChildren; - _firstVisibleChildIndex = startIndex; - } - - void updateSlotForChild(Element element, dynamic newSlot) { - assert(newSlot == null || newSlot == _omit || newSlot is Element); - super.updateSlotForChild(element, newSlot); - } - - void insertChildRenderObject(RenderObject child, dynamic slot) { - if (slot == _omit) - return; - assert(slot == null || slot is Element); - RenderObject nextSibling = slot?.renderObject; - renderObject.add(child, before: nextSibling); - } - - void moveChildRenderObject(RenderObject child, dynamic slot) { - if (slot == _omit) - return; - assert(slot == null || slot is Element); - RenderObject nextSibling = slot?.renderObject; - assert(nextSibling == null || nextSibling.parent == renderObject); - if (child.parent == renderObject) - renderObject.move(child, before: nextSibling); - else - renderObject.add(child, before: nextSibling); - } - - void removeChildRenderObject(RenderObject child) { - if (child.parent != renderObject) - return; // probably had slot == _omit when inserted - renderObject.remove(child); - } - -} diff --git a/packages/flutter/lib/src/fn3/navigator.dart b/packages/flutter/lib/src/fn3/navigator.dart deleted file mode 100644 index 6de2d6b1b7..0000000000 --- a/packages/flutter/lib/src/fn3/navigator.dart +++ /dev/null @@ -1,297 +0,0 @@ -// 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. - -import 'package:sky/animation.dart'; -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/focus.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/transitions.dart'; - -typedef Widget RouteBuilder(NavigatorState navigator, Route route); -typedef RouteBuilder RouteGenerator(String name); -typedef void RouteStateCallback(RouteState route); -typedef void NotificationCallback(); - -class Navigator extends StatefulComponent { - Navigator({ - Key key, - this.routes, - this.onGenerateRoute, // you need to implement this if you pushNamed() to names that might not be in routes. - this.onUnknownRoute // 404 generator. You only need to implement this if you have a way to navigate to arbitrary names. - }) : super(key: key) { - // To use a navigator, you must at a minimum define the route with the name '/'. - assert(routes.containsKey('/')); - } - - final Map routes; - final RouteGenerator onGenerateRoute; - final RouteBuilder onUnknownRoute; - - NavigatorState createState() => new NavigatorState(); -} - -class NavigatorState extends State { - - List _history = new List(); - int _currentPosition = 0; - - Route get currentRoute => _history[_currentPosition]; - bool get hasPreviousRoute => _history.length > 1; - - void initState() { - super.initState(); - PageRoute route = new PageRoute(config.routes['/']); - assert(route != null); - assert(!route.ephemeral); - _history.add(route); - } - - void pushState(State owner, Function callback) { - push(new RouteState( - route: currentRoute, - owner: owner, - callback: callback - )); - } - - void pushNamed(String name) { - RouteBuilder builder; - if (!config.routes.containsKey(name)) { - assert(config.onGenerateRoute != null); - builder = config.onGenerateRoute(name); - } else { - builder = config.routes[name]; - } - if (builder == null) - builder = config.onUnknownRoute; // 404! - assert(builder != null); // 404 getting your 404! - push(new PageRoute(builder)); - } - - void push(Route route) { - assert(!_debugCurrentlyHaveRoute(route)); - setState(() { - while (currentRoute.ephemeral) { - assert(currentRoute.ephemeral); - currentRoute.didPop(null); - _currentPosition -= 1; - } - _history.insert(_currentPosition + 1, route); - _currentPosition += 1; - }); - } - - void popRoute(Route route, [dynamic result]) { - assert(_debugCurrentlyHaveRoute(route)); - assert(_currentPosition > 0); - setState(() { - while (currentRoute != route) { - assert(currentRoute.ephemeral); - currentRoute.didPop(null); - _currentPosition -= 1; - } - assert(_currentPosition > 0); - currentRoute.didPop(result); - _currentPosition -= 1; - }); - assert(!_debugCurrentlyHaveRoute(route)); - } - - void pop([dynamic result]) { - setState(() { - while (currentRoute.ephemeral) { - currentRoute.didPop(null); - _currentPosition -= 1; - } - assert(_currentPosition > 0); - currentRoute.didPop(result); - _currentPosition -= 1; - }); - } - - bool _debugCurrentlyHaveRoute(Route route) { - int index = _history.indexOf(route); - return index >= 0 && index <= _currentPosition; - } - - Widget build(BuildContext context) { - List visibleRoutes = new List(); - bool alreadyInsertModalBarrier = false; - for (int i = _history.length-1; i >= 0; i -= 1) { - Route route = _history[i]; - if (!route.hasContent) { - assert(!route.modal); - continue; - } - route.ensurePerformance( - direction: (i <= _currentPosition) ? Direction.forward : Direction.reverse - ); - route._onDismissed = () { - setState(() { - assert(_history.contains(route)); - _history.remove(route); - }); - }; - Key key = new ObjectKey(route); - Widget widget = route.build(key, this); - visibleRoutes.add(widget); - if (route.isActuallyOpaque) - break; - assert(route.modal || route.ephemeral); - if (route.modal && i > 0 && !alreadyInsertModalBarrier) { - visibleRoutes.add(new Listener( - onPointerDown: (_) { pop(); }, - child: new Container() - )); - alreadyInsertModalBarrier = true; - } - } - return new Focus(child: new Stack(visibleRoutes.reversed.toList())); - } -} - - -abstract class Route { - - WatchableAnimationPerformance get performance => _performance?.view; - AnimationPerformance _performance; - NotificationCallback _onDismissed; - - AnimationPerformance createPerformance() { - Duration duration = transitionDuration; - if (duration > Duration.ZERO) { - return new AnimationPerformance(duration: duration) - ..addStatusListener((AnimationStatus status) { - if (status == AnimationStatus.dismissed && _onDismissed != null) - _onDismissed(); - }); - } - return null; - } - - void ensurePerformance({ Direction direction }) { - assert(direction != null); - if (_performance == null) - _performance = createPerformance(); - if (_performance != null) { - AnimationStatus desiredStatus = direction == Direction.forward ? AnimationStatus.forward : AnimationStatus.reverse; - if (_performance.status != desiredStatus) - _performance.play(direction); - } - } - - /// If hasContent is true, then the route represents some on-screen state. - /// - /// If hasContent is false, then no performance will be created, and the values of - /// ephemeral, modal, and opaque are ignored. This is useful if the route - /// represents some state handled by another widget. See - /// NavigatorState.pushState(). - /// - /// Set hasContent to false if you have nothing useful to return from build(). - /// - /// modal must be false if hasContent is false, since otherwise any - /// interaction with the system at all would imply that the current route is - /// popped, which would be pointless. - bool get hasContent => true; - - /// If ephemeral is true, then to explicitly pop the route you have to use - /// navigator.popRoute() with a reference to this route. navigator.pop() - /// automatically pops all ephemeral routes before popping the current - /// top-most non-ephemeral route. - /// - /// If ephemeral is false, then the route can be popped with navigator.pop(). - /// - /// Set ephemeral to true if you want to be automatically popped when another - /// route is pushed or popped. - /// - /// modal must be true if ephemeral is false. - bool get ephemeral => false; - - /// If modal is true, a hidden layer is inserted in the widget tree that - /// catches all touches to widgets created by routes below this one, even if - /// this one is transparent. - /// - /// If modal is false, then earlier routes can be interacted with, including - /// causing new routes to be pushed and/or this route (and maybe others) to be - /// popped. - /// - /// ephemeral must be true if modal is false. - /// hasContent must be true if modal is true. - bool get modal => true; - - /// If opaque is true, then routes below this one will not be built or painted - /// when the transition to this route is complete. - /// - /// If opaque is false, then the previous route will always be painted even if - /// this route's transition is complete. - /// - /// Set this to true if there's no reason to build and paint the route behind - /// you when your transition is finished, and set it to false if you do not - /// cover the entire application surface or are in any way semi-transparent. - bool get opaque => false; - - /// If this is set to a non-zero [Duration], then an [AnimationPerformance] - /// object, available via the performance field, will be created when the - /// route is first built, using the duration described here. - Duration get transitionDuration => Duration.ZERO; - - bool get isActuallyOpaque => (performance == null || _performance.isCompleted) && opaque; - - Widget build(Key key, NavigatorState navigator); - void didPop([dynamic result]) { - if (performance == null && _onDismissed != null) - _onDismissed(); - } - - String toString() => '$runtimeType()'; -} - -const Duration _kTransitionDuration = const Duration(milliseconds: 150); -const Point _kTransitionStartPoint = const Point(0.0, 75.0); - -class PageRoute extends Route { - PageRoute(this.builder); - - final RouteBuilder builder; - - bool get opaque => true; - - Duration get transitionDuration => _kTransitionDuration; - - Widget build(Key key, NavigatorState navigator) { - // TODO(jackson): Hit testing should ignore transform - // TODO(jackson): Block input unless content is interactive - return new SlideTransition( - key: key, - performance: performance, - position: new AnimatedValue(_kTransitionStartPoint, end: Point.origin, curve: easeOut), - child: new FadeTransition( - performance: performance, - opacity: new AnimatedValue(0.0, end: 1.0, curve: easeOut), - child: builder(navigator, this) - ) - ); - } -} - -class RouteState extends Route { - RouteState({ this.route, this.owner, this.callback }); - - Route route; - State owner; - RouteStateCallback callback; - - bool get hasContent => false; - bool get modal => false; - bool get opaque => false; - - void didPop([dynamic result]) { - assert(result == null); - if (callback != null) - callback(this); - super.didPop(result); - } - - Widget build(Key key, NavigatorState navigator) => null; -} diff --git a/packages/flutter/lib/src/fn3/popup_menu.dart b/packages/flutter/lib/src/fn3/popup_menu.dart deleted file mode 100644 index 1052068704..0000000000 --- a/packages/flutter/lib/src/fn3/popup_menu.dart +++ /dev/null @@ -1,210 +0,0 @@ -// 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. - -import 'dart:async'; -import 'dart:sky' as sky; - -import 'package:sky/animation.dart'; -import 'package:sky/material.dart'; -import 'package:sky/painting.dart'; -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/focus.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/gesture_detector.dart'; -import 'package:sky/src/fn3/navigator.dart'; -import 'package:sky/src/fn3/popup_menu_item.dart'; -import 'package:sky/src/fn3/scrollable.dart'; -import 'package:sky/src/fn3/theme.dart'; -import 'package:sky/src/fn3/transitions.dart'; - -const Duration _kMenuDuration = const Duration(milliseconds: 300); -const double _kMenuCloseIntervalEnd = 2.0 / 3.0; -const double _kMenuWidthStep = 56.0; -const double _kMenuMargin = 16.0; // 24.0 on tablet -const double _kMenuMinWidth = 2.0 * _kMenuWidthStep; -const double _kMenuMaxWidth = 5.0 * _kMenuWidthStep; -const double _kMenuHorizontalPadding = 16.0; -const double _kMenuVerticalPadding = 8.0; - -typedef List PopupMenuItemsBuilder(NavigatorState navigator); - -class PopupMenu extends StatefulComponent { - PopupMenu({ - Key key, - this.items, - this.level: 4, - this.navigator, - this.performance - }) : super(key: key) { - assert(items != null); - assert(performance != null); - } - - final List items; - final int level; - final NavigatorState navigator; - final WatchableAnimationPerformance performance; - - PopupMenuState createState() => new PopupMenuState(); -} - -class PopupMenuState extends State { - void initState() { - super.initState(); - config.performance.addListener(_performanceChanged); - } - - void didUpdateConfig(PopupMenu oldConfig) { - if (config.performance != oldConfig.performance) { - oldConfig.performance.removeListener(_performanceChanged); - config.performance.addListener(_performanceChanged); - } - } - - void dispose() { - config.performance.removeListener(_performanceChanged); - super.dispose(); - } - - void _performanceChanged() { - setState(() { - // the performance changed, and our state is tied up with the performance - }); - } - - BoxPainter _painter; - - void _updateBoxPainter(BoxDecoration decoration) { - if (_painter == null || _painter.decoration != decoration) - _painter = new BoxPainter(decoration); - } - - Widget build(BuildContext context) { - _updateBoxPainter(new BoxDecoration( - backgroundColor: Theme.of(context).canvasColor, - borderRadius: 2.0, - boxShadow: shadows[config.level] - )); - double unit = 1.0 / (config.items.length + 1.5); // 1.0 for the width and 0.5 for the last item's fade. - List children = []; - for (int i = 0; i < config.items.length; ++i) { - double start = (i + 1) * unit; - double end = (start + 1.5 * unit).clamp(0.0, 1.0); - children.add(new FadeTransition( - performance: config.performance, - opacity: new AnimatedValue(0.0, end: 1.0, interval: new Interval(start, end)), - child: new GestureDetector( - onTap: () { config.navigator.pop(config.items[i].value); }, - child: config.items[i] - )) - ); - } - final width = new AnimatedValue(0.0, end: 1.0, interval: new Interval(0.0, unit)); - final height = new AnimatedValue(0.0, end: 1.0, interval: new Interval(0.0, unit * config.items.length)); - return new FadeTransition( - performance: config.performance, - opacity: new AnimatedValue(0.0, end: 1.0, interval: new Interval(0.0, 1.0 / 3.0)), - child: new Container( - margin: new EdgeDims.all(_kMenuMargin), - child: new BuilderTransition( - performance: config.performance, - variables: [width, height], - builder: (BuildContext context) { - return new CustomPaint( - callback: (sky.Canvas canvas, Size size) { - double widthValue = width.value * size.width; - double heightValue = height.value * size.height; - _painter.paint(canvas, new Rect.fromLTWH(size.width - widthValue, 0.0, widthValue, heightValue)); - }, - child: new ConstrainedBox( - constraints: new BoxConstraints( - minWidth: _kMenuMinWidth, - maxWidth: _kMenuMaxWidth - ), - child: new IntrinsicWidth( - stepWidth: _kMenuWidthStep, - child: new ScrollableViewport( - child: new Container( - padding: const EdgeDims.symmetric( - horizontal: _kMenuHorizontalPadding, - vertical: _kMenuVerticalPadding - ), - child: new BlockBody(children) - ) - ) - ) - ) - ); - } - ) - ) - ); - } -} - -class MenuPosition { - const MenuPosition({ this.top, this.right, this.bottom, this.left }); - final double top; - final double right; - final double bottom; - final double left; -} - -class MenuRoute extends Route { - MenuRoute({ this.completer, this.position, this.builder, this.level }); - - final Completer completer; - final MenuPosition position; - final PopupMenuItemsBuilder builder; - final int level; - - AnimationPerformance createPerformance() { - AnimationPerformance result = super.createPerformance(); - AnimationTiming timing = new AnimationTiming(); - timing.reverseInterval = new Interval(0.0, _kMenuCloseIntervalEnd); - result.timing = timing; - return result; - } - - bool get ephemeral => false; // we could make this true, but then we'd have to use popRoute(), not pop(), in menus - bool get modal => true; - - Duration get transitionDuration => _kMenuDuration; - bool get opaque => false; - Widget build(Key key, NavigatorState navigator) { - return new Positioned( - top: position?.top, - right: position?.right, - bottom: position?.bottom, - left: position?.left, - child: new Focus( - key: new GlobalObjectKey(this), - autofocus: true, - child: new PopupMenu( - key: key, - items: builder != null ? builder(navigator) : const [], - level: level, - navigator: navigator, - performance: performance - ) - ) - ); - } - - void didPop([dynamic result]) { - completer.complete(result); - super.didPop(result); - } -} - -Future showMenu({ NavigatorState navigator, MenuPosition position, PopupMenuItemsBuilder builder, int level: 4 }) { - Completer completer = new Completer(); - navigator.push(new MenuRoute( - completer: completer, - position: position, - builder: builder, - level: level - )); - return completer.future; -} diff --git a/packages/flutter/lib/src/fn3/popup_menu_item.dart b/packages/flutter/lib/src/fn3/popup_menu_item.dart deleted file mode 100644 index 7a4e85c6f9..0000000000 --- a/packages/flutter/lib/src/fn3/popup_menu_item.dart +++ /dev/null @@ -1,37 +0,0 @@ -// 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. - -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/ink_well.dart'; -import 'package:sky/src/fn3/theme.dart'; - -const double _kMenuItemHeight = 48.0; -const double _kBaselineOffsetFromBottom = 20.0; - -class PopupMenuItem extends StatelessComponent { - PopupMenuItem({ - Key key, - this.value, - this.child - }) : super(key: key); - - final Widget child; - final dynamic value; - - Widget build(BuildContext context) { - return new InkWell( - child: new Container( - height: _kMenuItemHeight, - child: new DefaultTextStyle( - style: Theme.of(context).text.subhead, - child: new Baseline( - baseline: _kMenuItemHeight - _kBaselineOffsetFromBottom, - child: child - ) - ) - ) - ); - } -} diff --git a/packages/flutter/lib/src/fn3/progress_indicator.dart b/packages/flutter/lib/src/fn3/progress_indicator.dart deleted file mode 100644 index bbd2f8f3f9..0000000000 --- a/packages/flutter/lib/src/fn3/progress_indicator.dart +++ /dev/null @@ -1,164 +0,0 @@ -// 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. - -import 'dart:math' as math; -import 'dart:sky' as sky; - -import 'package:sky/animation.dart'; -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/theme.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/transitions.dart'; - -const double _kLinearProgressIndicatorHeight = 6.0; -const double _kMinCircularProgressIndicatorSize = 15.0; -const double _kCircularProgressIndicatorStrokeWidth = 3.0; - -abstract class ProgressIndicator extends StatefulComponent { - ProgressIndicator({ - Key key, - this.value, - this.bufferValue - }) : super(key: key); - - final double value; // Null for non-determinate progress indicator. - final double bufferValue; // TODO(hansmuller) implement the support for this. - - Color _getBackgroundColor(BuildContext context) => Theme.of(context).primarySwatch[200]; - Color _getValueColor(BuildContext context) => Theme.of(context).primaryColor; - Object _getCustomPaintToken(double performanceValue) => value != null ? value : performanceValue; - - Widget _buildIndicator(BuildContext context, double performanceValue); - - ProgressIndicatorState createState() => new ProgressIndicatorState(); -} - -class ProgressIndicatorState extends State { - - ValueAnimation _performance; - - void initState() { - super.initState(); - _performance = new ValueAnimation( - variable: new AnimatedValue(0.0, end: 1.0, curve: ease), - duration: const Duration(milliseconds: 1500) - ); - _performance.addStatusListener((AnimationStatus status) { - if (status == AnimationStatus.completed) - _restartAnimation(); - }); - _performance.play(); - } - - void _restartAnimation() { - _performance.progress = 0.0; - _performance.play(); - } - - Widget build(BuildContext context) { - if (config.value != null) - return config._buildIndicator(context, _performance.value); - - return new BuilderTransition( - variables: [_performance.variable], - performance: _performance.view, - builder: (BuildContext context) { - return config._buildIndicator(context, _performance.value); - } - ); - } -} - -class LinearProgressIndicator extends ProgressIndicator { - LinearProgressIndicator({ - Key key, - double value, - double bufferValue - }) : super(key: key, value: value, bufferValue: bufferValue); - - void _paint(BuildContext context, double performanceValue, sky.Canvas canvas, Size size) { - Paint paint = new Paint() - ..color = _getBackgroundColor(context) - ..setStyle(sky.PaintingStyle.fill); - canvas.drawRect(Point.origin & size, paint); - - paint.color = _getValueColor(context); - if (value != null) { - double width = value.clamp(0.0, 1.0) * size.width; - canvas.drawRect(Point.origin & new Size(width, size.height), paint); - } else { - double startX = size.width * (1.5 * performanceValue - 0.5); - double endX = startX + 0.5 * size.width; - double x = startX.clamp(0.0, size.width); - double width = endX.clamp(0.0, size.width) - x; - canvas.drawRect(new Point(x, 0.0) & new Size(width, size.height), paint); - } - } - - Widget _buildIndicator(BuildContext context, double performanceValue) { - return new Container( - constraints: new BoxConstraints.tightFor( - width: double.INFINITY, - height: _kLinearProgressIndicatorHeight - ), - child: new CustomPaint( - token: _getCustomPaintToken(performanceValue), - callback: (sky.Canvas canvas, Size size) { - _paint(context, performanceValue, canvas, size); - } - ) - ); - } -} - -class CircularProgressIndicator extends ProgressIndicator { - static const _kTwoPI = math.PI * 2.0; - static const _kEpsilon = .0000001; - // Canavs.drawArc(r, 0, 2*PI) doesn't draw anything, so just get close. - static const _kSweep = _kTwoPI - _kEpsilon; - static const _kStartAngle = -math.PI / 2.0; - - CircularProgressIndicator({ - Key key, - double value, - double bufferValue - }) : super(key: key, value: value, bufferValue: bufferValue); - - void _paint(BuildContext context, double performanceValue, sky.Canvas canvas, Size size) { - Paint paint = new Paint() - ..color = _getValueColor(context) - ..strokeWidth = _kCircularProgressIndicatorStrokeWidth - ..setStyle(sky.PaintingStyle.stroke); - - if (value != null) { - double angle = value.clamp(0.0, 1.0) * _kSweep; - sky.Path path = new sky.Path() - ..arcTo(Point.origin & size, _kStartAngle, angle, false); - canvas.drawPath(path, paint); - } else { - double startAngle = _kTwoPI * (1.75 * performanceValue - 0.75); - double endAngle = startAngle + _kTwoPI * 0.75; - double arcAngle = startAngle.clamp(0.0, _kTwoPI); - double arcSweep = endAngle.clamp(0.0, _kTwoPI) - arcAngle; - sky.Path path = new sky.Path() - ..arcTo(Point.origin & size, _kStartAngle + arcAngle, arcSweep, false); - canvas.drawPath(path, paint); - } - } - - Widget _buildIndicator(BuildContext context, double performanceValue) { - return new Container( - constraints: new BoxConstraints( - minWidth: _kMinCircularProgressIndicatorSize, - minHeight: _kMinCircularProgressIndicatorSize - ), - child: new CustomPaint( - token: _getCustomPaintToken(performanceValue), - callback: (sky.Canvas canvas, Size size) { - _paint(context, performanceValue, canvas, size); - } - ) - ); - } -} diff --git a/packages/flutter/lib/src/fn3/radio.dart b/packages/flutter/lib/src/fn3/radio.dart deleted file mode 100644 index 76493c1b32..0000000000 --- a/packages/flutter/lib/src/fn3/radio.dart +++ /dev/null @@ -1,72 +0,0 @@ -// 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. - -import 'dart:sky' as sky; - -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/gesture_detector.dart'; -import 'package:sky/src/fn3/theme.dart'; - -const sky.Color _kLightOffColor = const sky.Color(0x8A000000); -const sky.Color _kDarkOffColor = const sky.Color(0xB2FFFFFF); - -typedef RadioValueChanged(Object value); - -class Radio extends StatefulComponent { - Radio({ - Key key, - this.value, - this.groupValue, - this.onChanged - }) : super(key: key) { - assert(onChanged != null); - } - - final Object value; - final Object groupValue; - final RadioValueChanged onChanged; - - RadioState createState() => new RadioState(); -} - -class RadioState extends State { - Color _getColor(BuildContext context) { - ThemeData themeData = Theme.of(context); - if (config.value == config.groupValue) - return themeData.accentColor; - return themeData.brightness == ThemeBrightness.light ? _kLightOffColor : _kDarkOffColor; - } - - Widget build(BuildContext context) { - const double kDiameter = 16.0; - const double kOuterRadius = kDiameter / 2; - const double kInnerRadius = 5.0; - return new GestureDetector( - onTap: () => config.onChanged(config.value), - child: new Container( - margin: const EdgeDims.symmetric(horizontal: 5.0), - width: kDiameter, - height: kDiameter, - child: new CustomPaint( - callback: (sky.Canvas canvas, Size size) { - - Paint paint = new Paint()..color = _getColor(context); - - // Draw the outer circle - paint.setStyle(sky.PaintingStyle.stroke); - paint.strokeWidth = 2.0; - canvas.drawCircle(const Point(kOuterRadius, kOuterRadius), kOuterRadius, paint); - - // Draw the inner circle - if (config.value == config.groupValue) { - paint.setStyle(sky.PaintingStyle.fill); - canvas.drawCircle(const Point(kOuterRadius, kOuterRadius), kInnerRadius, paint); - } - } - ) - ) - ); - } -} diff --git a/packages/flutter/lib/src/fn3/raised_button.dart b/packages/flutter/lib/src/fn3/raised_button.dart deleted file mode 100644 index 99fe4f2900..0000000000 --- a/packages/flutter/lib/src/fn3/raised_button.dart +++ /dev/null @@ -1,50 +0,0 @@ -// 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. - -import 'package:sky/material.dart'; -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/material_button.dart'; -import 'package:sky/src/fn3/theme.dart'; - -class RaisedButton extends MaterialButton { - RaisedButton({ - Key key, - Widget child, - bool enabled: true, - Function onPressed - }) : super(key: key, - child: child, - enabled: enabled, - onPressed: onPressed) { - assert(enabled != null); - } - - RaisedButtonState createState() => new RaisedButtonState(); -} - -class RaisedButtonState extends MaterialButtonState { - Color getColor(BuildContext context) { - if (config.enabled) { - switch (Theme.of(context).brightness) { - case ThemeBrightness.light: - if (highlight) - return Colors.grey[350]; - else - return Colors.grey[300]; - break; - case ThemeBrightness.dark: - if (highlight) - return Theme.of(context).primarySwatch[700]; - else - return Theme.of(context).primarySwatch[600]; - break; - } - } else { - return Colors.grey[350]; - } - } - - int get level => config.enabled ? (highlight ? 2 : 1) : 0; -} diff --git a/packages/flutter/lib/src/fn3/scaffold.dart b/packages/flutter/lib/src/fn3/scaffold.dart deleted file mode 100644 index 77a72c4d22..0000000000 --- a/packages/flutter/lib/src/fn3/scaffold.dart +++ /dev/null @@ -1,252 +0,0 @@ -// 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. - -import 'dart:sky' as sky; - -import 'package:sky/material.dart'; -import 'package:sky/rendering.dart'; -import 'package:sky/src/fn3/framework.dart'; - -// Slots are painted in this order and hit tested in reverse of this order -enum ScaffoldSlots { - body, - statusBar, - toolbar, - snackBar, - floatingActionButton, - drawer -} - -class RenderScaffold extends RenderBox { - - RenderScaffold({ - RenderBox body, - RenderBox statusBar, - RenderBox toolbar, - RenderBox snackBar, - RenderBox floatingActionButton, - RenderBox drawer - }) { - this[ScaffoldSlots.body] = body; - this[ScaffoldSlots.statusBar] = statusBar; - this[ScaffoldSlots.toolbar] = toolbar; - this[ScaffoldSlots.snackBar] = snackBar; - this[ScaffoldSlots.floatingActionButton] = floatingActionButton; - this[ScaffoldSlots.drawer] = drawer; - } - - Map _slots = new Map(); - RenderBox operator[] (ScaffoldSlots slot) => _slots[slot]; - void operator[]= (ScaffoldSlots slot, RenderBox value) { - RenderBox old = _slots[slot]; - if (old == value) - return; - if (old != null) - dropChild(old); - if (value == null) { - _slots.remove(slot); - } else { - _slots[slot] = value; - adoptChild(value); - } - markNeedsLayout(); - } - - void attachChildren() { - for (ScaffoldSlots slot in ScaffoldSlots.values) { - RenderBox box = _slots[slot]; - if (box != null) - box.attach(); - } - } - - void detachChildren() { - for (ScaffoldSlots slot in ScaffoldSlots.values) { - RenderBox box = _slots[slot]; - if (box != null) - box.detach(); - } - } - - void visitChildren(RenderObjectVisitor visitor) { - for (ScaffoldSlots slot in ScaffoldSlots.values) { - RenderBox box = _slots[slot]; - if (box != null) - visitor(box); - } - } - - ScaffoldSlots remove(RenderBox child) { - assert(child != null); - for (ScaffoldSlots slot in ScaffoldSlots.values) { - if (_slots[slot] == child) { - this[slot] = null; - return slot; - } - } - return null; - } - - bool get sizedByParent => true; - void performResize() { - size = constraints.biggest; - assert(!size.isInfinite); - } - - // TODO(eseidel): These change based on device size! - // http://www.google.com/design/spec/layout/metrics-keylines.html#metrics-keylines-keylines-spacing - static const kButtonX = 16.0; // left from right edge of body - static const kButtonY = 16.0; // up from bottom edge of body - - void performLayout() { - double bodyHeight = size.height; - double bodyPosition = 0.0; - double fabOffset = 0.0; - if (_slots[ScaffoldSlots.statusBar] != null) { - RenderBox statusBar = _slots[ScaffoldSlots.statusBar]; - statusBar.layout(new BoxConstraints.tight(new Size(size.width, kStatusBarHeight))); - assert(statusBar.parentData is BoxParentData); - statusBar.parentData.position = new Point(0.0, size.height - kStatusBarHeight); - bodyHeight -= kStatusBarHeight; - } - if (_slots[ScaffoldSlots.toolbar] != null) { - RenderBox toolbar = _slots[ScaffoldSlots.toolbar]; - double toolbarHeight = kToolBarHeight + sky.view.paddingTop; - toolbar.layout(new BoxConstraints.tight(new Size(size.width, toolbarHeight))); - assert(toolbar.parentData is BoxParentData); - toolbar.parentData.position = Point.origin; - bodyPosition += toolbarHeight; - bodyHeight -= toolbarHeight; - } - if (_slots[ScaffoldSlots.body] != null) { - RenderBox body = _slots[ScaffoldSlots.body]; - body.layout(new BoxConstraints.tight(new Size(size.width, bodyHeight))); - assert(body.parentData is BoxParentData); - body.parentData.position = new Point(0.0, bodyPosition); - } - if (_slots[ScaffoldSlots.snackBar] != null) { - RenderBox snackBar = _slots[ScaffoldSlots.snackBar]; - // TODO(jackson): On tablet/desktop, minWidth = 288, maxWidth = 568 - snackBar.layout( - new BoxConstraints(minWidth: size.width, maxWidth: size.width, minHeight: 0.0, maxHeight: bodyHeight), - parentUsesSize: true - ); - assert(snackBar.parentData is BoxParentData); - snackBar.parentData.position = new Point(0.0, bodyPosition + bodyHeight - snackBar.size.height); - fabOffset += snackBar.size.height; - } - if (_slots[ScaffoldSlots.floatingActionButton] != null) { - RenderBox floatingActionButton = _slots[ScaffoldSlots.floatingActionButton]; - Size area = new Size(size.width - kButtonX, size.height - kButtonY); - floatingActionButton.layout(new BoxConstraints.loose(area), parentUsesSize: true); - assert(floatingActionButton.parentData is BoxParentData); - floatingActionButton.parentData.position = (area - floatingActionButton.size).toPoint() + new Offset(0.0, -fabOffset); - } - if (_slots[ScaffoldSlots.drawer] != null) { - RenderBox drawer = _slots[ScaffoldSlots.drawer]; - drawer.layout(new BoxConstraints(minWidth: 0.0, maxWidth: size.width, minHeight: size.height, maxHeight: size.height)); - assert(drawer.parentData is BoxParentData); - drawer.parentData.position = Point.origin; - } - } - - void paint(PaintingContext context, Offset offset) { - for (ScaffoldSlots slot in ScaffoldSlots.values) { - RenderBox box = _slots[slot]; - if (box != null) { - assert(box.parentData is BoxParentData); - context.paintChild(box, box.parentData.position + offset); - } - } - } - - void hitTestChildren(HitTestResult result, { Point position }) { - for (ScaffoldSlots slot in ScaffoldSlots.values.reversed) { - RenderBox box = _slots[slot]; - if (box != null) { - assert(box.parentData is BoxParentData); - if (box.hitTest(result, position: (position - box.parentData.position).toPoint())) - return; - } - } - } - - String debugDescribeChildren(String prefix) { - return _slots.keys.map((slot) => '${prefix}${slot}: ${_slots[slot].toStringDeep(prefix)}').join(); - } -} - -class Scaffold extends RenderObjectWidget { - Scaffold({ - Key key, - Widget body, - Widget statusBar, - Widget toolbar, - Widget snackBar, - Widget floatingActionButton, - Widget drawer - }) : super(key: key) { - _children[ScaffoldSlots.body] = body; - _children[ScaffoldSlots.statusBar] = statusBar; - _children[ScaffoldSlots.toolbar] = toolbar; - _children[ScaffoldSlots.snackBar] = snackBar; - _children[ScaffoldSlots.floatingActionButton] = floatingActionButton; - _children[ScaffoldSlots.drawer] = drawer; - } - - final Map _children = new Map(); - - RenderScaffold createRenderObject() => new RenderScaffold(); - - ScaffoldElement createElement() => new ScaffoldElement(this); -} - -class ScaffoldElement extends RenderObjectElement { - ScaffoldElement(Scaffold widget) : super(widget); - - Map _children; - - RenderScaffold get renderObject => super.renderObject; - - void visitChildren(ElementVisitor visitor) { - for (ScaffoldSlots slot in ScaffoldSlots.values) { - Element element = _children[slot]; - if (element != null) - visitor(element); - } - } - - void mount(Element parent, dynamic newSlot) { - super.mount(parent, newSlot); - _children = new Map(); - for (ScaffoldSlots slot in ScaffoldSlots.values) { - Element newChild = widget._children[slot]?.createElement(); - _children[slot] = newChild; - newChild?.mount(this, slot); - } - } - - void update(Scaffold newWidget) { - super.update(newWidget); - assert(widget == newWidget); - for (ScaffoldSlots slot in ScaffoldSlots.values) { - _children[slot] = updateChild(_children[slot], widget._children[slot], slot); - assert((_children[slot] == null) == (widget._children[slot] == null)); - } - } - - void insertChildRenderObject(RenderObject child, ScaffoldSlots slot) { - renderObject[slot] = child; - } - - void moveChildRenderObject(RenderObject child, dynamic slot) { - removeChildRenderObject(child); - insertChildRenderObject(child, slot); - } - - void removeChildRenderObject(RenderObject child) { - assert(renderObject == child.parent); - renderObject.remove(child); - } -} diff --git a/packages/flutter/lib/src/fn3/scrollable.dart b/packages/flutter/lib/src/fn3/scrollable.dart deleted file mode 100644 index 86b316b924..0000000000 --- a/packages/flutter/lib/src/fn3/scrollable.dart +++ /dev/null @@ -1,745 +0,0 @@ -// 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. - -import 'dart:async'; -import 'dart:math' as math; -import 'dart:sky' as sky; - -import 'package:newton/newton.dart'; -import 'package:sky/animation.dart'; -import 'package:sky/gestures.dart'; -import 'package:sky/rendering.dart'; -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/gesture_detector.dart'; -import 'package:sky/src/fn3/homogeneous_viewport.dart'; -import 'package:sky/src/fn3/mixed_viewport.dart'; - -// The gesture velocity properties are pixels/second, config min,max limits are pixels/ms -const double _kMillisecondsPerSecond = 1000.0; -const double _kMinFlingVelocity = -kMaxFlingVelocity * _kMillisecondsPerSecond; -const double _kMaxFlingVelocity = kMaxFlingVelocity * _kMillisecondsPerSecond; - -typedef void ScrollListener(double scrollOffset); -typedef double SnapOffsetCallback(double scrollOffset); - -/// A base class for scrollable widgets that reacts to user input and generates -/// a scrollOffset. -abstract class Scrollable extends StatefulComponent { - Scrollable({ - Key key, - this.initialScrollOffset, - this.scrollDirection: ScrollDirection.vertical, - this.onScroll, - this.snapOffsetCallback, - this.snapAlignmentOffset: 0.0 - }) : super(key: key) { - assert(scrollDirection == ScrollDirection.vertical || - scrollDirection == ScrollDirection.horizontal); - } - - final double initialScrollOffset; - final ScrollDirection scrollDirection; - final ScrollListener onScroll; - final SnapOffsetCallback snapOffsetCallback; - final double snapAlignmentOffset; -} - -abstract class ScrollableState extends State { - void initState() { - super.initState(); - if (config.initialScrollOffset is double) - _scrollOffset = config.initialScrollOffset; - _toEndAnimation = new AnimatedSimulation(_setScrollOffset); - _toOffsetAnimation = new ValueAnimation() - ..addListener(() { - AnimatedValue offset = _toOffsetAnimation.variable; - _setScrollOffset(offset.value); - }); - } - - AnimatedSimulation _toEndAnimation; // See _startToEndAnimation() - ValueAnimation _toOffsetAnimation; // Started by scrollTo() - - double _scrollOffset = 0.0; - double get scrollOffset => _scrollOffset; - - Offset get scrollOffsetVector { - if (config.scrollDirection == ScrollDirection.horizontal) - return new Offset(scrollOffset, 0.0); - return new Offset(0.0, scrollOffset); - } - - ScrollBehavior _scrollBehavior; - ScrollBehavior createScrollBehavior(); - ScrollBehavior get scrollBehavior { - if (_scrollBehavior == null) - _scrollBehavior = createScrollBehavior(); - return _scrollBehavior; - } - - GestureDragUpdateCallback _getDragUpdateHandler(ScrollDirection direction) { - if (config.scrollDirection != direction || !scrollBehavior.isScrollable) - return null; - return _handleDragUpdate; - } - - GestureDragEndCallback _getDragEndHandler(ScrollDirection direction) { - if (config.scrollDirection != direction || !scrollBehavior.isScrollable) - return null; - return _handleDragEnd; - } - - Widget build(BuildContext context) { - return new GestureDetector( - onVerticalDragUpdate: _getDragUpdateHandler(ScrollDirection.vertical), - onVerticalDragEnd: _getDragEndHandler(ScrollDirection.vertical), - onHorizontalDragUpdate: _getDragUpdateHandler(ScrollDirection.horizontal), - onHorizontalDragEnd: _getDragEndHandler(ScrollDirection.horizontal), - child: new Listener( - child: buildContent(context), - onPointerDown: _handlePointerDown - ) - ); - } - - Widget buildContent(BuildContext context); - - Future _startToOffsetAnimation(double newScrollOffset, Duration duration, Curve curve) { - _stopAnimations(); - _toOffsetAnimation - ..variable = new AnimatedValue(scrollOffset, - end: newScrollOffset, - curve: curve - ) - ..progress = 0.0 - ..duration = duration; - return _toOffsetAnimation.play(); - } - - void _stopAnimations() { - if (_toOffsetAnimation.isAnimating) - _toOffsetAnimation.stop(); - if (_toEndAnimation.isAnimating) - _toEndAnimation.stop(); - } - - bool _scrollOffsetIsInBounds(double offset) { - if (scrollBehavior is! ExtentScrollBehavior) - return false; - ExtentScrollBehavior behavior = scrollBehavior; - return offset >= behavior.minScrollOffset && offset < behavior.maxScrollOffset; - } - - Simulation _createFlingSimulation(double velocity) { - return scrollBehavior.createFlingScrollSimulation(scrollOffset, velocity); - } - - Simulation _createSnapSimulation(double velocity) { - if (velocity == null || config.snapOffsetCallback == null || !_scrollOffsetIsInBounds(scrollOffset)) - return null; - - Simulation simulation = _createFlingSimulation(velocity); - if (simulation == null) - return null; - - double endScrollOffset = simulation.x(double.INFINITY); - if (endScrollOffset.isNaN) - return null; - - double snappedScrollOffset = config.snapOffsetCallback(endScrollOffset + config.snapAlignmentOffset); - double alignedScrollOffset = snappedScrollOffset - config.snapAlignmentOffset; - if (!_scrollOffsetIsInBounds(alignedScrollOffset)) - return null; - - double snapVelocity = velocity.abs() * (alignedScrollOffset - scrollOffset).sign; - Simulation toSnapSimulation = - scrollBehavior.createSnapScrollSimulation(scrollOffset, alignedScrollOffset, snapVelocity); - if (toSnapSimulation == null) - return null; - - double offsetMin = math.min(scrollOffset, alignedScrollOffset); - double offsetMax = math.max(scrollOffset, alignedScrollOffset); - return new ClampedSimulation(toSnapSimulation, xMin: offsetMin, xMax: offsetMax); - } - - Future _startToEndAnimation({ double velocity }) { - _stopAnimations(); - Simulation simulation = - _createSnapSimulation(velocity) ?? _createFlingSimulation(velocity ?? 0.0); - if (simulation == null) - return new Future.value(); - return _toEndAnimation.start(simulation); - } - - void dispose() { - _stopAnimations(); - super.dispose(); - } - - void _setScrollOffset(double newScrollOffset) { - if (_scrollOffset == newScrollOffset) - return; - setState(() { - _scrollOffset = newScrollOffset; - }); - if (config.onScroll != null) - config.onScroll(_scrollOffset); - } - - Future scrollTo(double newScrollOffset, { Duration duration, Curve curve: ease }) { - if (newScrollOffset == _scrollOffset) - return new Future.value(); - - if (duration == null) { - _stopAnimations(); - _setScrollOffset(newScrollOffset); - return new Future.value(); - } - - return _startToOffsetAnimation(newScrollOffset, duration, curve); - } - - Future scrollBy(double scrollDelta, { Duration duration, Curve curve }) { - double newScrollOffset = scrollBehavior.applyCurve(_scrollOffset, scrollDelta); - return scrollTo(newScrollOffset, duration: duration, curve: curve); - } - - Future fling(Offset velocity) { - if (velocity != Offset.zero) - return _startToEndAnimation(velocity: _scrollVelocity(velocity)); - if (!_toEndAnimation.isAnimating && (_toOffsetAnimation == null || !_toOffsetAnimation.isAnimating)) - return settleScrollOffset(); - return new Future.value(); - } - - Future settleScrollOffset() { - return _startToEndAnimation(); - } - - double _scrollVelocity(sky.Offset velocity) { - double scrollVelocity = config.scrollDirection == ScrollDirection.horizontal - ? -velocity.dx - : -velocity.dy; - return scrollVelocity.clamp(_kMinFlingVelocity, _kMaxFlingVelocity) / _kMillisecondsPerSecond; - } - - void _handlePointerDown(_) { - _stopAnimations(); - } - - void _handleDragUpdate(double delta) { - // We negate the delta here because a positive scroll offset moves the - // the content up (or to the left) rather than down (or the right). - scrollBy(-delta); - } - - void _handleDragEnd(Offset velocity) { - fling(velocity); - } -} - -ScrollableState findScrollableAncestor(BuildContext context) { - ScrollableState result; - context.visitAncestorElements((Element element) { - if (element is StatefulComponentElement) { - if (element.state is ScrollableState) { - result = element.state; - return false; - } - } - return true; - }); - return result; -} - -Future ensureWidgetIsVisible(BuildContext context, { Duration duration, Curve curve }) { - assert(context.findRenderObject() is RenderBox); - // TODO(abarth): This function doesn't handle nested scrollable widgets. - - ScrollableState scrollable = findScrollableAncestor(context); - if (scrollable == null) - return new Future.value(); - - RenderBox targetBox = context.findRenderObject(); - assert(targetBox.attached); - Size targetSize = targetBox.size; - - RenderBox scrollableBox = scrollable.context.findRenderObject(); - assert(scrollableBox.attached); - Size scrollableSize = scrollableBox.size; - - double scrollOffsetDelta; - switch (scrollable.config.scrollDirection) { - case ScrollDirection.vertical: - Point targetCenter = targetBox.localToGlobal(new Point(0.0, targetSize.height / 2.0)); - Point scrollableCenter = scrollableBox.localToGlobal(new Point(0.0, scrollableSize.height / 2.0)); - scrollOffsetDelta = targetCenter.y - scrollableCenter.y; - break; - case ScrollDirection.horizontal: - Point targetCenter = targetBox.localToGlobal(new Point(targetSize.width / 2.0, 0.0)); - Point scrollableCenter = scrollableBox.localToGlobal(new Point(scrollableSize.width / 2.0, 0.0)); - scrollOffsetDelta = targetCenter.x - scrollableCenter.x; - break; - case ScrollDirection.both: - assert(false); // See https://github.com/flutter/engine/issues/888 - break; - } - - ExtentScrollBehavior scrollBehavior = scrollable.scrollBehavior; - double scrollOffset = (scrollable.scrollOffset + scrollOffsetDelta) - .clamp(scrollBehavior.minScrollOffset, scrollBehavior.maxScrollOffset); - - if (scrollOffset != scrollable.scrollOffset) - return scrollable.scrollTo(scrollOffset, duration: duration, curve: curve); - - return new Future.value(); -} - -/// A simple scrollable widget that has a single child. Use this component if -/// you are not worried about offscreen widgets consuming resources. -class ScrollableViewport extends Scrollable { - ScrollableViewport({ - Key key, - this.child, - double initialScrollOffset, - ScrollDirection scrollDirection: ScrollDirection.vertical, - ScrollListener onScroll - }) : super( - key: key, - scrollDirection: scrollDirection, - initialScrollOffset: initialScrollOffset, - onScroll: onScroll - ); - - final Widget child; - - ScrollableViewportState createState() => new ScrollableViewportState(); -} - -class ScrollableViewportState extends ScrollableState { - ScrollBehavior createScrollBehavior() => new OverscrollWhenScrollableBehavior(); - OverscrollWhenScrollableBehavior get scrollBehavior => super.scrollBehavior; - - double _viewportSize = 0.0; - double _childSize = 0.0; - void _handleViewportSizeChanged(Size newSize) { - _viewportSize = config.scrollDirection == ScrollDirection.vertical ? newSize.height : newSize.width; - setState(() { - _updateScrollBehaviour(); - }); - } - void _handleChildSizeChanged(Size newSize) { - _childSize = config.scrollDirection == ScrollDirection.vertical ? newSize.height : newSize.width; - setState(() { - _updateScrollBehaviour(); - }); - } - void _updateScrollBehaviour() { - // if you don't call this from build() or syncConstructorArguments(), you must call it from setState(). - scrollTo(scrollBehavior.updateExtents( - contentExtent: _childSize, - containerExtent: _viewportSize, - scrollOffset: scrollOffset - )); - } - - Widget buildContent(BuildContext context) { - return new SizeObserver( - callback: _handleViewportSizeChanged, - child: new Viewport( - scrollOffset: scrollOffsetVector, - scrollDirection: config.scrollDirection, - child: new SizeObserver( - callback: _handleChildSizeChanged, - child: config.child - ) - ) - ); - } -} - -/// A mashup of [ScrollableViewport] and [BlockBody]. Useful when you have a small, -/// fixed number of children that you wish to arrange in a block layout and that -/// might exceed the height of its container (and therefore need to scroll). -class Block extends StatelessComponent { - Block(this.children, { - Key key, - this.initialScrollOffset, - this.scrollDirection: ScrollDirection.vertical, - this.onScroll - }) : super(key: key); - - final List children; - final double initialScrollOffset; - final ScrollDirection scrollDirection; - final ScrollListener onScroll; - - BlockDirection get _direction { - if (scrollDirection == ScrollDirection.vertical) - return BlockDirection.vertical; - return BlockDirection.horizontal; - } - - Widget build(BuildContext context) { - return new ScrollableViewport( - initialScrollOffset: initialScrollOffset, - scrollDirection: scrollDirection, - onScroll: onScroll, - child: new BlockBody(children, direction: _direction) - ); - } -} - -/// An optimized scrollable widget for a large number of children that are all -/// the same size (extent) in the scrollDirection. For example for -/// ScrollDirection.vertical itemExtent is the height of each item. Use this -/// widget when you have a large number of children or when you are concerned -// about offscreen widgets consuming resources. -abstract class ScrollableWidgetList extends Scrollable { - ScrollableWidgetList({ - Key key, - double initialScrollOffset, - ScrollDirection scrollDirection: ScrollDirection.vertical, - ScrollListener onScroll, - SnapOffsetCallback snapOffsetCallback, - double snapAlignmentOffset: 0.0, - this.itemsWrap: false, - this.itemExtent, - this.padding - }) : super( - key: key, - initialScrollOffset: initialScrollOffset, - scrollDirection: scrollDirection, - onScroll: onScroll, - snapOffsetCallback: snapOffsetCallback, - snapAlignmentOffset: snapAlignmentOffset - ) { - assert(itemExtent != null); - } - - final bool itemsWrap; - final double itemExtent; - final EdgeDims padding; -} - -abstract class ScrollableWidgetListState extends ScrollableState { - /// Subclasses must implement `get itemCount` to tell ScrollableWidgetList - /// how many items there are in the list. - int get itemCount; - int _previousItemCount; - - Size _containerSize = Size.zero; - - void didUpdateConfig(T oldConfig) { - super.didUpdateConfig(oldConfig); - - bool scrollBehaviorUpdateNeeded = - config.padding != oldConfig.padding || - config.itemExtent != oldConfig.itemExtent || - config.scrollDirection != oldConfig.scrollDirection; - - if (config.itemsWrap != oldConfig.itemsWrap) { - _scrollBehavior = null; - scrollBehaviorUpdateNeeded = true; - } - - if (itemCount != _previousItemCount) { - scrollBehaviorUpdateNeeded = true; - _previousItemCount = itemCount; - } - - if (scrollBehaviorUpdateNeeded) - _updateScrollBehavior(); - } - - ScrollBehavior createScrollBehavior() => new OverscrollBehavior(); - ExtentScrollBehavior get scrollBehavior => super.scrollBehavior; - - double get _containerExtent { - return config.scrollDirection == ScrollDirection.vertical - ? _containerSize.height - : _containerSize.width; - } - - void _handleSizeChanged(Size newSize) { - setState(() { - _containerSize = newSize; - _updateScrollBehavior(); - }); - } - - double get _leadingPadding { - EdgeDims padding = config.padding; - if (config.scrollDirection == ScrollDirection.vertical) - return padding != null ? padding.top : 0.0; - return padding != null ? padding.left : -.0; - } - - double get _trailingPadding { - EdgeDims padding = config.padding; - if (config.scrollDirection == ScrollDirection.vertical) - return padding != null ? padding.bottom : 0.0; - return padding != null ? padding.right : 0.0; - } - - EdgeDims get _crossAxisPadding { - EdgeDims padding = config.padding; - if (padding == null) - return null; - if (config.scrollDirection == ScrollDirection.vertical) - return new EdgeDims.only(left: padding.left, right: padding.right); - return new EdgeDims.only(top: padding.top, bottom: padding.bottom); - } - - void _updateScrollBehavior() { - // if you don't call this from build(), you must call it from setState(). - double contentExtent = config.itemExtent * itemCount; - if (config.padding != null) - contentExtent += _leadingPadding + _trailingPadding; - scrollTo(scrollBehavior.updateExtents( - contentExtent: contentExtent, - containerExtent: _containerExtent, - scrollOffset: scrollOffset - )); - } - - Widget buildContent(BuildContext context) { - if (itemCount != _previousItemCount) { - _previousItemCount = itemCount; - _updateScrollBehavior(); - } - - return new SizeObserver( - callback: _handleSizeChanged, - child: new Container( - padding: _crossAxisPadding, - child: new HomogeneousViewport( - builder: _buildItems, - itemsWrap: config.itemsWrap, - itemExtent: config.itemExtent, - itemCount: itemCount, - direction: config.scrollDirection, - startOffset: scrollOffset - _leadingPadding - ) - ) - ); - } - - List _buildItems(BuildContext context, int start, int count) { - List result = buildItems(context, start, count); - assert(result.every((item) => item.key != null)); - return result; - } - - List buildItems(BuildContext context, int start, int count); - -} - -typedef Widget ItemBuilder(BuildContext context, T item); - -/// A wrapper around [ScrollableWidgetList] that helps you translate a list of -/// model objects into a scrollable list of widgets. Assumes all the widgets -/// have the same height. -class ScrollableList extends ScrollableWidgetList { - ScrollableList({ - Key key, - double initialScrollOffset, - ScrollDirection scrollDirection: ScrollDirection.vertical, - ScrollListener onScroll, - SnapOffsetCallback snapOffsetCallback, - double snapAlignmentOffset: 0.0, - this.items, - this.itemBuilder, - itemsWrap: false, - double itemExtent, - EdgeDims padding - }) : super( - key: key, - initialScrollOffset: initialScrollOffset, - scrollDirection: scrollDirection, - onScroll: onScroll, - snapOffsetCallback: snapOffsetCallback, - snapAlignmentOffset: snapAlignmentOffset, - itemsWrap: itemsWrap, - itemExtent: itemExtent, - padding: padding); - - final List items; - final ItemBuilder itemBuilder; - - ScrollableListState> createState() => new ScrollableListState>(); -} - -class ScrollableListState> extends ScrollableWidgetListState { - ScrollBehavior createScrollBehavior() { - return config.itemsWrap ? new UnboundedBehavior() : super.createScrollBehavior(); - } - - int get itemCount => config.items.length; - - List buildItems(BuildContext context, int start, int count) { - List result = new List(); - int begin = config.itemsWrap ? start : math.max(0, start); - int end = config.itemsWrap ? begin + count : math.min(begin + count, config.items.length); - for (int i = begin; i < end; ++i) - result.add(config.itemBuilder(context, config.items[i % itemCount])); - return result; - } -} - -typedef void PageChangedCallback(int newPage); - -class PageableList extends ScrollableList { - PageableList({ - Key key, - double initialScrollOffset, - ScrollDirection scrollDirection: ScrollDirection.horizontal, - ScrollListener onScroll, - List items, - ItemBuilder itemBuilder, - bool itemsWrap: false, - double itemExtent, - this.onPageChanged, - EdgeDims padding, - this.duration: const Duration(milliseconds: 200), - this.curve: ease - }) : super( - key: key, - initialScrollOffset: initialScrollOffset, - scrollDirection: scrollDirection, - onScroll: onScroll, - items: items, - itemBuilder: itemBuilder, - itemsWrap: itemsWrap, - itemExtent: itemExtent, - padding: padding - ); - - final Duration duration; - final Curve curve; - final PageChangedCallback onPageChanged; - - PageableListState createState() => new PageableListState(); -} - -class PageableListState extends ScrollableListState> { - double _snapScrollOffset(double newScrollOffset) { - double scaledScrollOffset = newScrollOffset / config.itemExtent; - double previousScrollOffset = scaledScrollOffset.floor() * config.itemExtent; - double nextScrollOffset = scaledScrollOffset.ceil() * config.itemExtent; - double delta = newScrollOffset - previousScrollOffset; - return (delta < config.itemExtent / 2.0 ? previousScrollOffset : nextScrollOffset) - .clamp(scrollBehavior.minScrollOffset, scrollBehavior.maxScrollOffset); - } - - Future fling(sky.Offset velocity) { - double scrollVelocity = _scrollVelocity(velocity); - double newScrollOffset = _snapScrollOffset(scrollOffset + scrollVelocity.sign * config.itemExtent) - .clamp(_snapScrollOffset(scrollOffset - config.itemExtent / 2.0), - _snapScrollOffset(scrollOffset + config.itemExtent / 2.0)); - return scrollTo(newScrollOffset, duration: config.duration, curve: config.curve).then(_notifyPageChanged); - } - - int get currentPage => (scrollOffset / config.itemExtent).floor() % itemCount; - - void _notifyPageChanged(_) { - if (config.onPageChanged != null) - config.onPageChanged(currentPage); - } - - Future settleScrollOffset() { - return scrollTo(_snapScrollOffset(scrollOffset), duration: config.duration, curve: config.curve).then(_notifyPageChanged); - } -} - -/// A general scrollable list for a large number of children that might not all -/// have the same height. Prefer [ScrollableWidgetList] when all the children -/// have the same height because it can use that property to be more efficient. -/// Prefer [ScrollableViewport] with a single child. -class ScrollableMixedWidgetList extends Scrollable { - ScrollableMixedWidgetList({ - Key key, - double initialScrollOffset, - ScrollListener onScroll, - SnapOffsetCallback snapOffsetCallback, - double snapAlignmentOffset: 0.0, - this.builder, - this.token, - this.onInvalidatorAvailable - }) : super( - key: key, - initialScrollOffset: initialScrollOffset, - onScroll: onScroll, - snapOffsetCallback: snapOffsetCallback, - snapAlignmentOffset: snapAlignmentOffset - ); - - final IndexedBuilder builder; - final Object token; - final InvalidatorAvailableCallback onInvalidatorAvailable; - - ScrollableMixedWidgetListState createState() => new ScrollableMixedWidgetListState(); -} - -class ScrollableMixedWidgetListState extends ScrollableState { - void initState() { - super.initState(); - scrollBehavior.updateExtents( - contentExtent: double.INFINITY - ); - } - - ScrollBehavior createScrollBehavior() => new OverscrollBehavior(); - OverscrollBehavior get scrollBehavior => super.scrollBehavior; - - void _handleSizeChanged(Size newSize) { - setState(() { - scrollBy(scrollBehavior.updateExtents( - containerExtent: newSize.height, - scrollOffset: scrollOffset - )); - }); - } - - bool _contentChanged = false; - - void didUpdateConfig(ScrollableMixedWidgetList oldConfig) { - super.didUpdateConfig(oldConfig); - if (config.token != oldConfig.token) { - // When the token changes the scrollable's contents may have changed. - // Remember as much so that after the new contents have been laid out we - // can adjust the scrollOffset so that the last page of content is still - // visible. - _contentChanged = true; - } - } - - void _handleExtentsUpdate(double newExtents) { - double newScrollOffset; - setState(() { - newScrollOffset = scrollBehavior.updateExtents( - contentExtent: newExtents ?? double.INFINITY, - scrollOffset: scrollOffset - ); - }); - if (_contentChanged) { - _contentChanged = false; - scrollTo(newScrollOffset); - } - } - - Widget buildContent(BuildContext context) { - return new SizeObserver( - callback: _handleSizeChanged, - child: new MixedViewport( - startOffset: scrollOffset, - builder: config.builder, - token: config.token, - onInvalidatorAvailable: config.onInvalidatorAvailable, - onExtentsUpdate: _handleExtentsUpdate - ) - ); - } -} diff --git a/packages/flutter/lib/src/fn3/snack_bar.dart b/packages/flutter/lib/src/fn3/snack_bar.dart deleted file mode 100644 index a094e2f136..0000000000 --- a/packages/flutter/lib/src/fn3/snack_bar.dart +++ /dev/null @@ -1,111 +0,0 @@ -// 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. - - -import 'package:sky/animation.dart'; -import 'package:sky/painting.dart'; -import 'package:sky/material.dart'; -import 'package:sky/src/fn3/animated_component.dart'; -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/gesture_detector.dart'; -import 'package:sky/src/fn3/material.dart'; -import 'package:sky/src/fn3/theme.dart'; -import 'package:sky/src/fn3/transitions.dart'; - -typedef void SnackBarDismissedCallback(); - -const Duration _kSlideInDuration = const Duration(milliseconds: 200); -const double kSnackHeight = 52.0; -const double kSideMargins = 24.0; -const double kVerticalPadding = 14.0; -const Color kSnackBackground = const Color(0xFF323232); - -class SnackBarAction extends StatelessComponent { - SnackBarAction({Key key, this.label, this.onPressed }) : super(key: key) { - assert(label != null); - } - - final String label; - final Function onPressed; - - Widget build(BuildContext) { - return new GestureDetector( - onTap: onPressed, - child: new Container( - margin: const EdgeDims.only(left: kSideMargins), - padding: const EdgeDims.symmetric(vertical: kVerticalPadding), - child: new Text(label) - ) - ); - } -} - -class SnackBar extends AnimatedComponent { - SnackBar({ - Key key, - this.content, - this.actions, - bool showing, - this.onDismissed - }) : super(key: key, direction: showing ? Direction.forward : Direction.reverse, duration: _kSlideInDuration) { - assert(content != null); - } - - final Widget content; - final List actions; - final SnackBarDismissedCallback onDismissed; - - SnackBarState createState() => new SnackBarState(); -} - -class SnackBarState extends AnimatedState { - void handleDismissed() { - if (config.onDismissed != null) - config.onDismissed(); - } - - Widget build(BuildContext context) { - List children = [ - new Flexible( - child: new Container( - margin: const EdgeDims.symmetric(vertical: kVerticalPadding), - child: new DefaultTextStyle( - style: Typography.white.subhead, - child: config.content - ) - ) - ) - ]; - if (config.actions != null) - children.addAll(config.actions); - return new SquashTransition( - performance: performance.view, - height: new AnimatedValue( - 0.0, - end: kSnackHeight, - curve: easeIn, - reverseCurve: easeOut - ), - child: new ClipRect( - child: new OverflowBox( - minHeight: kSnackHeight, - maxHeight: kSnackHeight, - child: new Material( - level: 2, - color: kSnackBackground, - type: MaterialType.canvas, - child: new Container( - margin: const EdgeDims.symmetric(horizontal: kSideMargins), - child: new DefaultTextStyle( - style: new TextStyle(color: Theme.of(context).accentColor), - child: new Row(children) - ) - ) - ) - ) - ) - ); - } -} diff --git a/packages/flutter/lib/src/fn3/switch.dart b/packages/flutter/lib/src/fn3/switch.dart deleted file mode 100644 index ae58b3849b..0000000000 --- a/packages/flutter/lib/src/fn3/switch.dart +++ /dev/null @@ -1,150 +0,0 @@ -// 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. - -import 'dart:async'; -import 'dart:sky' as sky; - -import 'package:sky/material.dart'; -import 'package:sky/painting.dart'; -import 'package:sky/rendering.dart'; -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/theme.dart'; -import 'package:sky/src/fn3/framework.dart'; - -export 'package:sky/rendering.dart' show ValueChanged; - -const sky.Color _kThumbOffColor = const sky.Color(0xFFFAFAFA); -const sky.Color _kTrackOffColor = const sky.Color(0x42000000); -const double _kSwitchWidth = 35.0; -const double _kThumbRadius = 10.0; -const double _kSwitchHeight = _kThumbRadius * 2.0; -const double _kTrackHeight = 14.0; -const double _kTrackRadius = _kTrackHeight / 2.0; -const double _kTrackWidth = - _kSwitchWidth - (_kThumbRadius - _kTrackRadius) * 2.0; -const Size _kSwitchSize = const Size(_kSwitchWidth + 2.0, _kSwitchHeight + 2.0); -const double _kReactionRadius = _kSwitchWidth / 2.0; - -class Switch extends StatelessComponent { - Switch({ Key key, this.value, this.onChanged }) - : super(key: key); - - final bool value; - final ValueChanged onChanged; - - Widget build(BuildContext context) { - return new _SwitchWrapper( - value: value, - thumbColor: Theme.of(context).accentColor, - onChanged: onChanged - ); - } -} - -class _SwitchWrapper extends LeafRenderObjectWidget { - _SwitchWrapper({ Key key, this.value, this.thumbColor, this.onChanged }) - : super(key: key); - - final bool value; - final Color thumbColor; - final ValueChanged onChanged; - - _RenderSwitch createRenderObject() => new _RenderSwitch( - value: value, - thumbColor: thumbColor, - onChanged: onChanged - ); - - void updateRenderObject(_RenderSwitch renderObject, _SwitchWrapper oldWidget) { - renderObject.value = value; - renderObject.thumbColor = thumbColor; - renderObject.onChanged = onChanged; - } -} - -class _RenderSwitch extends RenderToggleable { - _RenderSwitch({ - bool value, - Color thumbColor: _kThumbOffColor, - ValueChanged onChanged - }) : _thumbColor = thumbColor, - super(value: value, onChanged: onChanged, size: _kSwitchSize) {} - - Color _thumbColor; - Color get thumbColor => _thumbColor; - void set thumbColor(Color value) { - if (value == _thumbColor) return; - _thumbColor = value; - markNeedsPaint(); - } - - RadialReaction _radialReaction; - - void handleEvent(sky.Event event, BoxHitTestEntry entry) { - if (event is sky.PointerEvent) { - if (event.type == 'pointerdown') - _showRadialReaction(entry.localPosition); - else if (event.type == 'pointerup') - _hideRadialReaction(); - } - super.handleEvent(event, entry); - } - - void _showRadialReaction(Point startLocation) { - if (_radialReaction != null) - return; - _radialReaction = new RadialReaction( - center: new Point(_kSwitchSize.width / 2.0, _kSwitchSize.height / 2.0), - radius: _kReactionRadius, - startPosition: startLocation - )..addListener(markNeedsPaint) - ..show(); - } - - Future _hideRadialReaction() async { - if (_radialReaction == null) - return; - await _radialReaction.hide(); - _radialReaction = null; - } - - void paint(PaintingContext context, Offset offset) { - final PaintingCanvas canvas = context.canvas; - sky.Color thumbColor = _kThumbOffColor; - sky.Color trackColor = _kTrackOffColor; - if (value) { - thumbColor = _thumbColor; - trackColor = new sky.Color(_thumbColor.value & 0x80FFFFFF); - } - - // Draw the track rrect - sky.Paint paint = new sky.Paint() - ..color = trackColor - ..style = sky.PaintingStyle.fill; - sky.Rect rect = new sky.Rect.fromLTWH(offset.dx, - offset.dy + _kSwitchHeight / 2.0 - _kTrackHeight / 2.0, _kTrackWidth, - _kTrackHeight); - sky.RRect rrect = new sky.RRect() - ..setRectXY(rect, _kTrackRadius, _kTrackRadius); - canvas.drawRRect(rrect, paint); - - if (_radialReaction != null) - _radialReaction.paint(canvas, offset); - - // Draw the raised thumb with a shadow - paint.color = thumbColor; - ShadowDrawLooperBuilder builder = new ShadowDrawLooperBuilder(); - for (BoxShadow boxShadow in shadows[1]) - builder.addShadow(boxShadow.offset, boxShadow.color, boxShadow.blur); - paint.drawLooper = builder.build(); - - // The thumb contracts slightly during the animation - double inset = 2.0 - (position - 0.5).abs() * 2.0; - Point thumbPos = new Point(offset.dx + - _kTrackRadius + - position * (_kTrackWidth - _kTrackRadius * 2), - offset.dy + _kSwitchHeight / 2.0); - canvas.drawCircle(thumbPos, _kThumbRadius - inset, paint); - } -} diff --git a/packages/flutter/lib/src/fn3/tabs.dart b/packages/flutter/lib/src/fn3/tabs.dart deleted file mode 100644 index 1ef2905823..0000000000 --- a/packages/flutter/lib/src/fn3/tabs.dart +++ /dev/null @@ -1,619 +0,0 @@ -// 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. - -import 'dart:math' as math; -import 'dart:sky' as sky; - -import 'package:newton/newton.dart'; -import 'package:sky/animation.dart'; -import 'package:sky/painting.dart'; -import 'package:sky/rendering.dart'; -import 'package:sky/material.dart'; -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/gesture_detector.dart'; -import 'package:sky/src/fn3/icon.dart'; -import 'package:sky/src/fn3/ink_well.dart'; -import 'package:sky/src/fn3/scrollable.dart'; -import 'package:sky/src/fn3/theme.dart'; -import 'package:sky/src/fn3/transitions.dart'; - -typedef void SelectedIndexChanged(int selectedIndex); -typedef void LayoutChanged(Size size, List widths); - -// See https://www.google.com/design/spec/components/tabs.html#tabs-specs -const double _kTabHeight = 46.0; -const double _kTextAndIconTabHeight = 72.0; -const double _kTabIndicatorHeight = 2.0; -const double _kMinTabWidth = 72.0; -const double _kMaxTabWidth = 264.0; -const EdgeDims _kTabLabelPadding = const EdgeDims.symmetric(horizontal: 12.0); -const int _kTabIconSize = 24; -const double _kTabBarScrollDrag = 0.025; -const Duration _kTabBarScroll = const Duration(milliseconds: 200); - -class TabBarParentData extends BoxParentData with - ContainerParentDataMixin { } - -class RenderTabBar extends RenderBox with - ContainerRenderObjectMixin, - RenderBoxContainerDefaultsMixin { - - RenderTabBar(this.onLayoutChanged); - - int _selectedIndex; - int get selectedIndex => _selectedIndex; - void set selectedIndex(int value) { - if (_selectedIndex != value) { - _selectedIndex = value; - markNeedsPaint(); - } - } - - Color _backgroundColor; - Color get backgroundColor => _backgroundColor; - void set backgroundColor(Color value) { - if (_backgroundColor != value) { - _backgroundColor = value; - markNeedsPaint(); - } - } - - Color _indicatorColor; - Color get indicatorColor => _indicatorColor; - void set indicatorColor(Color value) { - if (_indicatorColor != value) { - _indicatorColor = value; - markNeedsPaint(); - } - } - - Rect _indicatorRect; - Rect get indicatorRect => _indicatorRect; - void set indicatorRect(Rect value) { - if (_indicatorRect != value) { - _indicatorRect = value; - markNeedsPaint(); - } - } - - bool _textAndIcons; - bool get textAndIcons => _textAndIcons; - void set textAndIcons(bool value) { - if (_textAndIcons != value) { - _textAndIcons = value; - markNeedsLayout(); - } - } - - bool _isScrollable; - bool get isScrollable => _isScrollable; - void set isScrollable(bool value) { - if (_isScrollable != value) { - _isScrollable = value; - markNeedsLayout(); - } - } - - void setupParentData(RenderBox child) { - if (child.parentData is! TabBarParentData) - child.parentData = new TabBarParentData(); - } - - double getMinIntrinsicWidth(BoxConstraints constraints) { - BoxConstraints widthConstraints = - new BoxConstraints(maxWidth: constraints.maxWidth, maxHeight: constraints.maxHeight); - - double maxWidth = 0.0; - RenderBox child = firstChild; - while (child != null) { - maxWidth = math.max(maxWidth, child.getMinIntrinsicWidth(widthConstraints)); - assert(child.parentData is TabBarParentData); - child = child.parentData.nextSibling; - } - double width = isScrollable ? maxWidth : maxWidth * childCount; - return constraints.constrainWidth(width); - } - - double getMaxIntrinsicWidth(BoxConstraints constraints) { - BoxConstraints widthConstraints = - new BoxConstraints(maxWidth: constraints.maxWidth, maxHeight: constraints.maxHeight); - - double maxWidth = 0.0; - RenderBox child = firstChild; - while (child != null) { - maxWidth = math.max(maxWidth, child.getMaxIntrinsicWidth(widthConstraints)); - assert(child.parentData is TabBarParentData); - child = child.parentData.nextSibling; - } - double width = isScrollable ? maxWidth : maxWidth * childCount; - return constraints.constrainWidth(width); - } - - double get _tabHeight => textAndIcons ? _kTextAndIconTabHeight : _kTabHeight; - double get _tabBarHeight => _tabHeight + _kTabIndicatorHeight; - - double _getIntrinsicHeight(BoxConstraints constraints) => constraints.constrainHeight(_tabBarHeight); - - double getMinIntrinsicHeight(BoxConstraints constraints) => _getIntrinsicHeight(constraints); - - double getMaxIntrinsicHeight(BoxConstraints constraints) => _getIntrinsicHeight(constraints); - - void layoutFixedWidthTabs() { - double tabWidth = size.width / childCount; - BoxConstraints tabConstraints = - new BoxConstraints.tightFor(width: tabWidth, height: _tabHeight); - double x = 0.0; - RenderBox child = firstChild; - while (child != null) { - child.layout(tabConstraints); - assert(child.parentData is TabBarParentData); - child.parentData.position = new Point(x, 0.0); - x += tabWidth; - child = child.parentData.nextSibling; - } - } - - double layoutScrollableTabs() { - BoxConstraints tabConstraints = new BoxConstraints( - minWidth: _kMinTabWidth, - maxWidth: _kMaxTabWidth, - minHeight: _tabHeight, - maxHeight: _tabHeight - ); - double x = 0.0; - RenderBox child = firstChild; - while (child != null) { - child.layout(tabConstraints, parentUsesSize: true); - assert(child.parentData is TabBarParentData); - child.parentData.position = new Point(x, 0.0); - x += child.size.width; - child = child.parentData.nextSibling; - } - return x; - } - - Size layoutSize; - List layoutWidths; - LayoutChanged onLayoutChanged; - - void reportLayoutChangedIfNeeded() { - assert(onLayoutChanged != null); - List widths = new List(childCount); - if (!isScrollable && childCount > 0) { - double tabWidth = size.width / childCount; - widths.fillRange(0, widths.length, tabWidth); - } else if (isScrollable) { - RenderBox child = firstChild; - int childIndex = 0; - while (child != null) { - widths[childIndex++] = child.size.width; - child = child.parentData.nextSibling; - } - assert(childIndex == widths.length); - } - if (size != layoutSize || widths != layoutWidths) { - layoutSize = size; - layoutWidths = widths; - onLayoutChanged(layoutSize, layoutWidths); - } - } - - void performLayout() { - assert(constraints is BoxConstraints); - if (childCount == 0) - return; - - if (isScrollable) { - double tabBarWidth = layoutScrollableTabs(); - size = constraints.constrain(new Size(tabBarWidth, _tabBarHeight)); - } else { - size = constraints.constrain(new Size(constraints.maxWidth, _tabBarHeight)); - layoutFixedWidthTabs(); - } - - if (onLayoutChanged != null) - reportLayoutChangedIfNeeded(); - } - - void hitTestChildren(HitTestResult result, { Point position }) { - defaultHitTestChildren(result, position: position); - } - - void _paintIndicator(PaintingCanvas canvas, RenderBox selectedTab, Offset offset) { - if (indicatorColor == null) - return; - - if (indicatorRect != null) { - canvas.drawRect(indicatorRect.shift(offset), new Paint()..color = indicatorColor); - return; - } - - var size = new Size(selectedTab.size.width, _kTabIndicatorHeight); - var point = new Point( - selectedTab.parentData.position.x, - _tabBarHeight - _kTabIndicatorHeight - ); - Rect rect = (point + offset) & size; - canvas.drawRect(rect, new Paint()..color = indicatorColor); - } - - void paint(PaintingContext context, Offset offset) { - if (backgroundColor != null) { - double width = layoutWidths != null - ? layoutWidths.reduce((sum, width) => sum + width) - : size.width; - Rect rect = offset & new Size(width, size.height); - context.canvas.drawRect(rect, new Paint()..color = backgroundColor); - } - int index = 0; - RenderBox child = firstChild; - while (child != null) { - assert(child.parentData is TabBarParentData); - context.paintChild(child, child.parentData.position + offset); - if (index++ == selectedIndex) - _paintIndicator(context.canvas, child, offset); - child = child.parentData.nextSibling; - } - } -} - -class _TabBarWrapper extends MultiChildRenderObjectWidget { - _TabBarWrapper({ - Key key, - List children, - this.selectedIndex, - this.backgroundColor, - this.indicatorColor, - this.indicatorRect, - this.textAndIcons, - this.isScrollable: false, - this.onLayoutChanged - }) : super(key: key, children: children); - - final int selectedIndex; - final Color backgroundColor; - final Color indicatorColor; - final Rect indicatorRect; - final bool textAndIcons; - final bool isScrollable; - final LayoutChanged onLayoutChanged; - - RenderTabBar createRenderObject() { - RenderTabBar result = new RenderTabBar(onLayoutChanged); - updateRenderObject(result, null); - return result; - } - - void updateRenderObject(RenderTabBar renderObject, _TabBarWrapper oldWidget) { - renderObject.selectedIndex = selectedIndex; - renderObject.backgroundColor = backgroundColor; - renderObject.indicatorColor = indicatorColor; - renderObject.indicatorRect = indicatorRect; - renderObject.textAndIcons = textAndIcons; - renderObject.isScrollable = isScrollable; - renderObject.onLayoutChanged = onLayoutChanged; - } -} - -class TabLabel { - const TabLabel({ this.text, this.icon }); - - final String text; - final String icon; -} - -class Tab extends StatelessComponent { - Tab({ - Key key, - this.label, - this.color, - this.selected: false, - this.selectedColor - }) : super(key: key) { - assert(label.text != null || label.icon != null); - } - - final TabLabel label; - final Color color; - final bool selected; - final Color selectedColor; - - Widget _buildLabelText() { - assert(label.text != null); - TextStyle style = new TextStyle(color: selected ? selectedColor : color); - return new Text(label.text, style: style); - } - - Widget _buildLabelIcon() { - assert(label.icon != null); - Color iconColor = selected ? selectedColor : color; - sky.ColorFilter filter = new sky.ColorFilter.mode(iconColor, sky.TransferMode.srcATop); - return new Icon(type: label.icon, size: _kTabIconSize, colorFilter: filter); - } - - Widget build(BuildContext context) { - Widget labelContent; - if (label.icon == null) { - labelContent = _buildLabelText(); - } else if (label.text == null) { - labelContent = _buildLabelIcon(); - } else { - labelContent = new Column( - [ - new Container( - child: _buildLabelIcon(), - margin: const EdgeDims.only(bottom: 10.0) - ), - _buildLabelText() - ], - justifyContent: FlexJustifyContent.center, - alignItems: FlexAlignItems.center - ); - } - - Container centeredLabel = new Container( - child: new Center(child: labelContent), - constraints: new BoxConstraints(minWidth: _kMinTabWidth), - padding: _kTabLabelPadding - ); - - return new InkWell(child: centeredLabel); - } -} - -class _TabsScrollBehavior extends BoundedBehavior { - _TabsScrollBehavior(); - - bool isScrollable = true; - - Simulation createFlingScrollSimulation(double position, double velocity) { - if (!isScrollable) - return null; - - double velocityPerSecond = velocity * 1000.0; - return new BoundedFrictionSimulation( - _kTabBarScrollDrag, position, velocityPerSecond, minScrollOffset, maxScrollOffset - ); - } - - double applyCurve(double scrollOffset, double scrollDelta) { - return (isScrollable) ? super.applyCurve(scrollOffset, scrollDelta) : 0.0; - } -} - -class TabBar extends Scrollable { - TabBar({ - Key key, - this.labels, - this.selectedIndex: 0, - this.onChanged, - this.isScrollable: false - }) : super(key: key, scrollDirection: ScrollDirection.horizontal); - - final Iterable labels; - final int selectedIndex; - final SelectedIndexChanged onChanged; - final bool isScrollable; - - TabBarState createState() => new TabBarState(); -} - -class TabBarState extends ScrollableState { - void initState() { - super.initState(); - _indicatorAnimation = new ValueAnimation() - ..duration = _kTabBarScroll - ..variable = new AnimatedRect(null, curve: ease); - scrollBehavior.isScrollable = config.isScrollable; - } - - Size _tabBarSize; - Size _viewportSize = Size.zero; - List _tabWidths; - ValueAnimation _indicatorAnimation; - - void didUpdateConfig(TabBar oldConfig) { - super.didUpdateConfig(oldConfig); - if (!config.isScrollable) - scrollTo(0.0); - } - - AnimatedRect get _indicatorRect => _indicatorAnimation.variable; - - void _startIndicatorAnimation(int fromTabIndex, int toTabIndex) { - _indicatorRect - ..begin = (_indicatorRect.value == null ? _tabIndicatorRect(fromTabIndex) : _indicatorRect.value) - ..end = _tabIndicatorRect(toTabIndex); - _indicatorAnimation - ..progress = 0.0 - ..play(); - } - - ScrollBehavior createScrollBehavior() => new _TabsScrollBehavior(); - _TabsScrollBehavior get scrollBehavior => super.scrollBehavior; - - Rect _tabRect(int tabIndex) { - assert(_tabBarSize != null); - assert(_tabWidths != null); - assert(tabIndex >= 0 && tabIndex < _tabWidths.length); - double tabLeft = 0.0; - if (tabIndex > 0) - tabLeft = _tabWidths.take(tabIndex).reduce((sum, width) => sum + width); - double tabTop = 0.0; - double tabBottom = _tabBarSize.height - _kTabIndicatorHeight; - double tabRight = tabLeft + _tabWidths[tabIndex]; - return new Rect.fromLTRB(tabLeft, tabTop, tabRight, tabBottom); - } - - Rect _tabIndicatorRect(int tabIndex) { - Rect r = _tabRect(tabIndex); - return new Rect.fromLTRB(r.left, r.bottom, r.right, r.bottom + _kTabIndicatorHeight); - } - - double _centeredTabScrollOffset(int tabIndex) { - double viewportWidth = scrollBehavior.containerExtent; - return (_tabRect(tabIndex).left + _tabWidths[tabIndex] / 2.0 - viewportWidth / 2.0) - .clamp(scrollBehavior.minScrollOffset, scrollBehavior.maxScrollOffset); - } - - void _handleTap(int tabIndex) { - if (tabIndex != config.selectedIndex) { - if (_tabWidths != null) { - if (config.isScrollable) - scrollTo(_centeredTabScrollOffset(tabIndex), duration: _kTabBarScroll); - _startIndicatorAnimation(config.selectedIndex, tabIndex); - } - if (config.onChanged != null) - config.onChanged(tabIndex); - } - } - - Widget _toTab(TabLabel label, int tabIndex, Color color, Color selectedColor) { - return new GestureDetector( - onTap: () => _handleTap(tabIndex), - child: new Tab( - label: label, - color: color, - selected: tabIndex == config.selectedIndex, - selectedColor: selectedColor - ) - ); - } - - void _updateScrollBehavior() { - scrollBehavior.updateExtents( - containerExtent: config.scrollDirection == ScrollDirection.vertical ? _viewportSize.height : _viewportSize.width, - contentExtent: _tabWidths.reduce((sum, width) => sum + width) - ); - } - - void _layoutChanged(Size tabBarSize, List tabWidths) { - setState(() { - _tabBarSize = tabBarSize; - _tabWidths = tabWidths; - _updateScrollBehavior(); - }); - } - - void _handleViewportSizeChanged(Size newSize) { - _viewportSize = newSize; - _updateScrollBehavior(); - } - - Widget buildContent(BuildContext context) { - assert(config.labels != null && config.labels.isNotEmpty); - - ThemeData themeData = Theme.of(context); - Color backgroundColor = themeData.primaryColor; - Color indicatorColor = themeData.accentColor; - if (indicatorColor == backgroundColor) { - indicatorColor = Colors.white; - } - - TextStyle textStyle; - IconThemeColor iconThemeColor; - switch (themeData.primaryColorBrightness) { - case ThemeBrightness.light: - textStyle = Typography.black.body1; - iconThemeColor = IconThemeColor.black; - break; - case ThemeBrightness.dark: - textStyle = Typography.white.body1; - iconThemeColor = IconThemeColor.white; - break; - } - - List tabs = []; - bool textAndIcons = false; - int tabIndex = 0; - for (TabLabel label in config.labels) { - tabs.add(_toTab(label, tabIndex++, textStyle.color, indicatorColor)); - if (label.text != null && label.icon != null) - textAndIcons = true; - } - - Widget tabBar = new IconTheme( - data: new IconThemeData(color: iconThemeColor), - child: new DefaultTextStyle( - style: textStyle, - child: new BuilderTransition( - variables: [_indicatorRect], - performance: _indicatorAnimation.view, - builder: (BuildContext context) { - return new _TabBarWrapper( - children: tabs, - selectedIndex: config.selectedIndex, - backgroundColor: backgroundColor, - indicatorColor: indicatorColor, - indicatorRect: _indicatorRect.value, - textAndIcons: textAndIcons, - isScrollable: config.isScrollable, - onLayoutChanged: _layoutChanged - ); - } - ) - ) - ); - - if (!config.isScrollable) - return tabBar; - - return new SizeObserver( - callback: _handleViewportSizeChanged, - child: new Viewport( - scrollDirection: ScrollDirection.horizontal, - scrollOffset: new Offset(scrollOffset, 0.0), - child: tabBar - ) - ); - } -} - -class TabNavigatorView { - TabNavigatorView({ this.label, this.builder }) { - assert(builder != null); - } - - // this uses a builder for the contents, rather than a raw Widget child, - // because there might be many, many tabs and some might be relatively - // expensive to create up front. This way, the view is only created lazily. - - final TabLabel label; - final WidgetBuilder builder; -} - -class TabNavigator extends StatelessComponent { - TabNavigator({ - Key key, - this.views, - this.selectedIndex: 0, - this.onChanged, - this.isScrollable: false - }) : super(key: key); - - final List views; - final int selectedIndex; - final SelectedIndexChanged onChanged; - final bool isScrollable; - - void _handleSelectedIndexChanged(int tabIndex) { - if (onChanged != null) - onChanged(tabIndex); - } - - Widget build(BuildContext context) { - assert(views != null && views.isNotEmpty); - assert(selectedIndex >= 0 && selectedIndex < views.length); - return new Column([ - new TabBar( - labels: views.map((view) => view.label), - onChanged: _handleSelectedIndexChanged, - selectedIndex: selectedIndex, - isScrollable: isScrollable - ), - new Flexible(child: views[selectedIndex].builder(context)) - ]); - } -} diff --git a/packages/flutter/lib/src/fn3/theme.dart b/packages/flutter/lib/src/fn3/theme.dart deleted file mode 100644 index 52203c3a5f..0000000000 --- a/packages/flutter/lib/src/fn3/theme.dart +++ /dev/null @@ -1,30 +0,0 @@ -// 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. - -import 'package:sky/material.dart'; -import 'package:sky/src/fn3/framework.dart'; - -export 'package:sky/material.dart' show ThemeData, ThemeBrightness; - -class Theme extends InheritedWidget { - Theme({ - Key key, - this.data, - Widget child - }) : super(key: key, child: child) { - assert(child != null); - assert(data != null); - } - - final ThemeData data; - - static final ThemeData _kFallbackTheme = new ThemeData.fallback(); - - static ThemeData of(BuildContext context) { - Theme theme = context.inheritedWidgetOfType(Theme); - return theme == null ? _kFallbackTheme : theme.data; - } - - bool updateShouldNotify(Theme old) => data != old.data; -} diff --git a/packages/flutter/lib/src/fn3/title.dart b/packages/flutter/lib/src/fn3/title.dart deleted file mode 100644 index ee5dcfcfa0..0000000000 --- a/packages/flutter/lib/src/fn3/title.dart +++ /dev/null @@ -1,19 +0,0 @@ -// 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. - -import 'package:sky/services.dart'; -import 'package:sky/src/fn3/theme.dart'; -import 'package:sky/src/fn3/framework.dart'; - -class Title extends StatelessComponent { - Title({ this.title, this.child }); - - final Widget child; - final String title; - - Widget build(BuildContext context) { - updateTaskDescription(title, Theme.of(context).primaryColor); - return child; - } -} diff --git a/packages/flutter/lib/src/fn3/tool_bar.dart b/packages/flutter/lib/src/fn3/tool_bar.dart deleted file mode 100644 index e0781a4bd0..0000000000 --- a/packages/flutter/lib/src/fn3/tool_bar.dart +++ /dev/null @@ -1,89 +0,0 @@ -// 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. - -import 'package:sky/material.dart'; -import 'package:sky/painting.dart'; -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/icon.dart'; -import 'package:sky/src/fn3/theme.dart'; -import 'package:sky/src/rendering/flex.dart'; - -class ToolBar extends StatelessComponent { - - ToolBar({ - Key key, - this.left, - this.center, - this.right, - this.backgroundColor - }) : super(key: key); - - final Widget left; - final Widget center; - final List right; - final Color backgroundColor; - - Widget build(BuildContext context) { - Color toolbarColor = backgroundColor; - IconThemeData iconThemeData; - TextStyle centerStyle = Typography.white.title; - TextStyle sideStyle = Typography.white.body1; - if (toolbarColor == null) { - ThemeData themeData = Theme.of(context); - toolbarColor = themeData.primaryColor; - if (themeData.primaryColorBrightness == ThemeBrightness.light) { - centerStyle = Typography.black.title; - sideStyle = Typography.black.body2; - iconThemeData = const IconThemeData(color: IconThemeColor.black); - } else { - iconThemeData = const IconThemeData(color: IconThemeColor.white); - } - } - - List children = new List(); - - // left children - if (left != null) - children.add(left); - - // center children (left-aligned, but takes all remaining space) - children.add( - new Flexible( - child: new Padding( - child: center != null ? new DefaultTextStyle(child: center, style: centerStyle) : null, - padding: new EdgeDims.only(left: 24.0) - ) - ) - ); - - // right children - if (right != null) - children.addAll(right); - - Widget content = new Container( - child: new DefaultTextStyle( - style: sideStyle, - child: new Column([ - new Container( - child: new Row(children), - height: kToolBarHeight - ), - ], - justifyContent: FlexJustifyContent.end - ) - ), - padding: new EdgeDims.symmetric(horizontal: 8.0), - decoration: new BoxDecoration( - backgroundColor: toolbarColor, - boxShadow: shadows[2] - ) - ); - - if (iconThemeData != null) - content = new IconTheme(data: iconThemeData, child: content); - return content; - } - -} diff --git a/packages/flutter/lib/src/fn3/transitions.dart b/packages/flutter/lib/src/fn3/transitions.dart deleted file mode 100644 index 87089c271c..0000000000 --- a/packages/flutter/lib/src/fn3/transitions.dart +++ /dev/null @@ -1,171 +0,0 @@ -// 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. - -import 'package:sky/animation.dart'; -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:vector_math/vector_math.dart'; - -export 'package:sky/animation.dart' show Direction; - -abstract class TransitionComponent extends StatefulComponent { - TransitionComponent({ - Key key, - this.performance - }) : super(key: key) { - assert(performance != null); - } - - final WatchableAnimationPerformance performance; - - Widget build(BuildContext context); - - TransitionState createState() => new TransitionState(); -} - -class TransitionState extends State { - void initState() { - super.initState(); - config.performance.addListener(_performanceChanged); - } - - void didUpdateConfig(TransitionComponent oldConfig) { - if (config.performance != oldConfig.performance) { - oldConfig.performance.removeListener(_performanceChanged); - config.performance.addListener(_performanceChanged); - } - } - - void dispose() { - config.performance.removeListener(_performanceChanged); - super.dispose(); - } - - void _performanceChanged() { - setState(() { - // The performance's state is our build state, and it changed already. - }); - } - - Widget build(BuildContext context) { - return config.build(context); - } -} - -abstract class TransitionWithChild extends TransitionComponent { - TransitionWithChild({ - Key key, - this.child, - WatchableAnimationPerformance performance - }) : super(key: key, performance: performance); - - final Widget child; - - Widget build(BuildContext context) => buildWithChild(context, child); - - Widget buildWithChild(BuildContext context, Widget child); -} - -class SlideTransition extends TransitionWithChild { - SlideTransition({ - Key key, - this.position, - WatchableAnimationPerformance performance, - Widget child - }) : super(key: key, - performance: performance, - child: child); - - final AnimatedValue position; - - Widget buildWithChild(BuildContext context, Widget child) { - performance.updateVariable(position); - Matrix4 transform = new Matrix4.identity() - ..translate(position.value.x, position.value.y); - return new Transform(transform: transform, child: child); - } -} - -class FadeTransition extends TransitionWithChild { - FadeTransition({ - Key key, - this.opacity, - WatchableAnimationPerformance performance, - Widget child - }) : super(key: key, - performance: performance, - child: child); - - final AnimatedValue opacity; - - Widget buildWithChild(BuildContext context, Widget child) { - performance.updateVariable(opacity); - return new Opacity(opacity: opacity.value, child: child); - } -} - -class ColorTransition extends TransitionWithChild { - ColorTransition({ - Key key, - this.color, - WatchableAnimationPerformance performance, - Widget child - }) : super(key: key, - performance: performance, - child: child); - - final AnimatedColorValue color; - - Widget buildWithChild(BuildContext context, Widget child) { - performance.updateVariable(color); - return new DecoratedBox( - decoration: new BoxDecoration(backgroundColor: color.value), - child: child - ); - } -} - -class SquashTransition extends TransitionWithChild { - SquashTransition({ - Key key, - this.width, - this.height, - WatchableAnimationPerformance performance, - Widget child - }) : super(key: key, - performance: performance, - child: child); - - final AnimatedValue width; - final AnimatedValue height; - - Widget buildWithChild(BuildContext context, Widget child) { - if (width != null) - performance.updateVariable(width); - if (height != null) - performance.updateVariable(height); - return new SizedBox(width: width?.value, height: height?.value, child: child); - } -} - -typedef Widget BuilderFunction(BuildContext context); - -class BuilderTransition extends TransitionComponent { - BuilderTransition({ - Key key, - this.variables, - this.builder, - WatchableAnimationPerformance performance - }) : super(key: key, - performance: performance); - - final List variables; - final BuilderFunction builder; - - Widget build(BuildContext context) { - for (int i = 0; i < variables.length; ++i) - performance.updateVariable(variables[i]); - return builder(context); - } -} diff --git a/packages/flutter/lib/src/widgets/animated_component.dart b/packages/flutter/lib/src/widgets/animated_component.dart index f44a50ec2e..d9b27490c9 100644 --- a/packages/flutter/lib/src/widgets/animated_component.dart +++ b/packages/flutter/lib/src/widgets/animated_component.dart @@ -6,37 +6,17 @@ import 'package:sky/animation.dart'; import 'package:sky/src/widgets/framework.dart'; abstract class AnimatedComponent extends StatefulComponent { + const AnimatedComponent({ Key key, this.direction, this.duration }) : super(key: key); - AnimatedComponent({ Key key, this.direction, this.duration }) : super(key: key); - - Duration duration; - Direction direction; - - void syncConstructorArguments(AnimatedComponent source) { - bool resumePerformance = false; - if (duration != source.duration) { - duration = source.duration; - resumePerformance = true; - } - if (direction != source.direction) { - direction = source.direction; - resumePerformance = true; - } - if (resumePerformance) - performance.play(direction); - } - - AnimationPerformance get performance => _performance; - AnimationPerformance _performance; + final Duration duration; + final Direction direction; +} +abstract class AnimatedState extends State { void initState() { - _performance = new AnimationPerformance(duration: duration); - performance.addStatusListener((AnimationStatus status) { - if (status == AnimationStatus.completed) - handleCompleted(); - else if (status == AnimationStatus.dismissed) - handleDismissed(); - }); + super.initState(); + _performance = new AnimationPerformance(duration: config.duration); + performance.addStatusListener(_handleAnimationStatusChanged); if (buildDependsOnPerformance) { performance.addListener(() { setState(() { @@ -45,11 +25,26 @@ abstract class AnimatedComponent extends StatefulComponent { }); }); } - performance.play(direction); + performance.play(config.direction); + } + + void didUpdateConfig(T oldConfig) { + performance.duration = config.duration; + if (config.duration != oldConfig.duration || config.direction != oldConfig.direction) + performance.play(config.direction); + } + + AnimationPerformance get performance => _performance; + AnimationPerformance _performance; + + void _handleAnimationStatusChanged(AnimationStatus status) { + if (status == AnimationStatus.completed) + handleCompleted(); + else if (status == AnimationStatus.dismissed) + handleDismissed(); } bool get buildDependsOnPerformance => false; void handleCompleted() { } void handleDismissed() { } - } diff --git a/packages/flutter/lib/src/widgets/animated_container.dart b/packages/flutter/lib/src/widgets/animated_container.dart deleted file mode 100644 index 9931e19c12..0000000000 --- a/packages/flutter/lib/src/widgets/animated_container.dart +++ /dev/null @@ -1,232 +0,0 @@ -// 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. - -import 'dart:sky' as sky; - -import 'package:vector_math/vector_math.dart'; -import 'package:sky/animation.dart'; -import 'package:sky/painting.dart'; -import 'package:sky/src/widgets/basic.dart'; -import 'package:sky/src/widgets/framework.dart'; - -class AnimatedBoxConstraintsValue extends AnimatedValue { - AnimatedBoxConstraintsValue(BoxConstraints begin, { BoxConstraints end, Curve curve: linear }) - : super(begin, end: end, curve: curve); - - // TODO(abarth): We should lerp the BoxConstraints. - BoxConstraints lerp(double t) => end; -} - -class AnimatedBoxDecorationValue extends AnimatedValue { - AnimatedBoxDecorationValue(BoxDecoration begin, { BoxDecoration end, Curve curve: linear }) - : super(begin, end: end, curve: curve); - - BoxDecoration lerp(double t) => BoxDecoration.lerp(begin, end, t); -} - -class AnimatedEdgeDimsValue extends AnimatedValue { - AnimatedEdgeDimsValue(EdgeDims begin, { EdgeDims end, Curve curve: linear }) - : super(begin, end: end, curve: curve); - - EdgeDims lerp(double t) { - return new EdgeDims( - sky.lerpDouble(begin.top, end.top, t), - sky.lerpDouble(begin.right, end.right, t), - sky.lerpDouble(begin.bottom, end.bottom, t), - sky.lerpDouble(begin.bottom, end.left, t) - ); - } -} - -class AnimatedMatrix4Value extends AnimatedValue { - AnimatedMatrix4Value(Matrix4 begin, { Matrix4 end, Curve curve: linear }) - : super(begin, end: end, curve: curve); - - Matrix4 lerp(double t) { - // TODO(mpcomplete): Animate the full matrix. Will animating the cells - // separately work? - Vector3 beginT = begin.getTranslation(); - Vector3 endT = end.getTranslation(); - Vector3 lerpT = beginT*(1.0-t) + endT*t; - return new Matrix4.identity()..translate(lerpT); - } -} - -abstract class AnimationBehavior { - void initFields(AnimatedContainer original); - void syncConstructorArguments(AnimatedContainer original, AnimatedContainer updated); -} - -class ImplicitlyAnimatedValue { - final AnimationPerformance performance = new AnimationPerformance(); - final AnimatedValue _variable; - - ImplicitlyAnimatedValue(this._variable, Duration duration) { - performance - ..variable = _variable - ..duration = duration; - } - - T get value => _variable.value; - void animateTo(T newValue) { - _variable.begin = _variable.value; - _variable.end = newValue; - if (_variable.value != _variable.end) { - performance - ..progress = 0.0 - ..play(); - } - } -} - -abstract class ImplicitlyAnimatedFieldBehavior extends AnimationBehavior { - ImplicitlyAnimatedFieldBehavior(this.duration); - - Duration duration; - ImplicitlyAnimatedValue field; - - // Overrides. - T getter(AnimatedContainer container); - void setter(AnimatedContainer container, T value); - AnimatedValue initField(T value); - - void initFields(AnimatedContainer original) { - _updateField(original, getter(original)); - } - - void syncConstructorArguments(AnimatedContainer original, AnimatedContainer updated) { - _updateField(original, getter(updated)); - } - - void _updateField(AnimatedContainer original, T newValue) { - if (field != null) { - // Animate to newValue (possibly null). - field.animateTo(newValue); - } else if (newValue != null) { - // Set the value and prepare it for future animations. - field = new ImplicitlyAnimatedValue(initField(newValue), duration); - field.performance.addListener(() { - original.setState(() { setter(original, field.value); }); - }); - } - } -} - -class ImplicitlyAnimatedConstraintsBehavior extends ImplicitlyAnimatedFieldBehavior { - ImplicitlyAnimatedConstraintsBehavior(Duration duration) : super(duration); - - BoxConstraints getter(AnimatedContainer container) => container.constraints; - void setter(AnimatedContainer container, BoxConstraints val) { container.constraints = val; } - AnimatedValue initField(BoxConstraints val) => new AnimatedBoxConstraintsValue(val); -} - -class ImplicitlyAnimatedDecorationBehavior extends ImplicitlyAnimatedFieldBehavior { - ImplicitlyAnimatedDecorationBehavior(Duration duration) : super(duration); - - BoxDecoration getter(AnimatedContainer container) => container.decoration; - void setter(AnimatedContainer container, BoxDecoration val) { container.decoration = val; } - AnimatedValue initField(BoxDecoration val) => new AnimatedBoxDecorationValue(val); -} - -class ImplicitlyAnimatedMarginBehavior extends ImplicitlyAnimatedFieldBehavior { - ImplicitlyAnimatedMarginBehavior(Duration duration) : super(duration); - - EdgeDims getter(AnimatedContainer container) => container.margin; - void setter(AnimatedContainer container, EdgeDims val) { container.margin = val; } - AnimatedValue initField(EdgeDims val) => new AnimatedEdgeDimsValue(val); -} - -class ImplicitlyAnimatedPaddingBehavior extends ImplicitlyAnimatedFieldBehavior { - ImplicitlyAnimatedPaddingBehavior(Duration duration) : super(duration); - - EdgeDims getter(AnimatedContainer container) => container.padding; - void setter(AnimatedContainer container, EdgeDims val) { container.padding = val; } - AnimatedValue initField(EdgeDims val) => new AnimatedEdgeDimsValue(val); -} - -class ImplicitlyAnimatedTransformBehavior extends ImplicitlyAnimatedFieldBehavior { - ImplicitlyAnimatedTransformBehavior(Duration duration) : super(duration); - - Matrix4 getter(AnimatedContainer container) => container.transform; - void setter(AnimatedContainer container, Matrix4 val) { container.transform = val; } - AnimatedValue initField(Matrix4 val) => new AnimatedMatrix4Value(val); -} - -class ImplicitlyAnimatedWidthBehavior extends ImplicitlyAnimatedFieldBehavior { - ImplicitlyAnimatedWidthBehavior(Duration duration) : super(duration); - - double getter(AnimatedContainer container) => container.width; - void setter(AnimatedContainer container, double val) { container.width = val; } - AnimatedValue initField(double val) => new AnimatedValue(val); -} - -class ImplicitlyAnimatedHeightBehavior extends ImplicitlyAnimatedFieldBehavior { - ImplicitlyAnimatedHeightBehavior(Duration duration) : super(duration); - - double getter(AnimatedContainer container) => container.height; - void setter(AnimatedContainer container, double val) { container.height = val; } - AnimatedValue initField(double val) => new AnimatedValue(val); -} - -List implicitlyAnimate(Duration duration) { - return [ - new ImplicitlyAnimatedConstraintsBehavior(duration), - new ImplicitlyAnimatedDecorationBehavior(duration), - new ImplicitlyAnimatedMarginBehavior(duration), - new ImplicitlyAnimatedPaddingBehavior(duration), - new ImplicitlyAnimatedTransformBehavior(duration), - new ImplicitlyAnimatedWidthBehavior(duration), - new ImplicitlyAnimatedHeightBehavior(duration) - ]; -} - -class AnimatedContainer extends StatefulComponent { - AnimatedContainer({ - Key key, - this.child, - this.behavior, - this.constraints, - this.decoration, - this.width, - this.height, - this.margin, - this.padding, - this.transform - }) : super(key: key); - - Widget child; - BoxConstraints constraints; - BoxDecoration decoration; - EdgeDims margin; - EdgeDims padding; - Matrix4 transform; - double width; - double height; - - List behavior; - - void initState() { - for (AnimationBehavior i in behavior) - i.initFields(this); - } - - void syncConstructorArguments(AnimatedContainer updated) { - child = updated.child; - for (AnimationBehavior i in behavior) - i.syncConstructorArguments(this, updated); - } - - Widget build() { - return new Container( - child: child, - constraints: constraints, - decoration: decoration, - margin: margin, - padding: padding, - transform: transform, - width: width, - height: height - ); - } -} diff --git a/packages/flutter/lib/src/fn3/app.dart b/packages/flutter/lib/src/widgets/app.dart similarity index 87% rename from packages/flutter/lib/src/fn3/app.dart rename to packages/flutter/lib/src/widgets/app.dart index b181d5c258..79f9bbab10 100644 --- a/packages/flutter/lib/src/fn3/app.dart +++ b/packages/flutter/lib/src/widgets/app.dart @@ -7,12 +7,12 @@ import 'dart:sky' as sky; import 'package:sky/material.dart'; import 'package:sky/painting.dart'; import 'package:sky/services.dart'; -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/binding.dart'; -import 'package:sky/src/fn3/framework.dart'; -import 'package:sky/src/fn3/navigator.dart'; -import 'package:sky/src/fn3/theme.dart'; -import 'package:sky/src/fn3/title.dart'; +import 'package:sky/src/widgets/basic.dart'; +import 'package:sky/src/widgets/binding.dart'; +import 'package:sky/src/widgets/framework.dart'; +import 'package:sky/src/widgets/navigator.dart'; +import 'package:sky/src/widgets/theme.dart'; +import 'package:sky/src/widgets/title.dart'; const TextStyle _errorTextStyle = const TextStyle( color: const Color(0xD0FF0000), diff --git a/packages/flutter/lib/src/widgets/basic.dart b/packages/flutter/lib/src/widgets/basic.dart index 7cd58710b5..de0a0a03fd 100644 --- a/packages/flutter/lib/src/widgets/basic.dart +++ b/packages/flutter/lib/src/widgets/basic.dart @@ -4,38 +4,39 @@ import 'dart:sky' as sky; -import 'package:vector_math/vector_math.dart'; - +import 'package:sky/rendering.dart'; import 'package:sky/services.dart'; -import 'package:sky/src/painting/text_painter.dart'; -import 'package:sky/src/painting/text_style.dart'; -import 'package:sky/src/rendering/block.dart'; -import 'package:sky/src/rendering/box.dart'; -import 'package:sky/src/rendering/flex.dart'; -import 'package:sky/src/rendering/grid.dart'; -import 'package:sky/src/rendering/image.dart'; -import 'package:sky/src/rendering/object.dart'; -import 'package:sky/src/rendering/paragraph.dart'; -import 'package:sky/src/rendering/proxy_box.dart'; -import 'package:sky/src/rendering/shifted_box.dart'; -import 'package:sky/src/rendering/stack.dart'; -import 'package:sky/src/rendering/viewport.dart'; -import 'package:sky/src/widgets/default_text_style.dart'; import 'package:sky/src/widgets/framework.dart'; -export 'package:sky/src/painting/text_style.dart'; -export 'package:sky/src/rendering/block.dart' show BlockDirection; -export 'package:sky/src/rendering/box.dart' show BoxConstraints; -export 'package:sky/src/rendering/flex.dart' show FlexJustifyContent, FlexAlignItems, FlexDirection; -export 'package:sky/src/rendering/object.dart' show Point, Offset, Size, Rect, Color, Paint, Path; -export 'package:sky/src/rendering/proxy_box.dart' show BackgroundImage, BoxDecoration, BoxDecorationPosition, BoxShadow, Border, BorderSide, EdgeDims, Shape; -export 'package:sky/src/rendering/shifted_box.dart' show ShrinkWrap; -export 'package:sky/src/rendering/toggleable.dart' show ValueChanged; -export 'package:sky/src/rendering/viewport.dart' show ScrollDirection; +export 'package:sky/rendering.dart' show + BackgroundImage, + BlockDirection, + Border, + BorderSide, + BoxConstraints, + BoxDecoration, + BoxDecorationPosition, + BoxShadow, + Color, + EdgeDims, + FlexAlignItems, + FlexDirection, + FlexJustifyContent, + Offset, + Paint, + Path, + Point, + Rect, + ScrollDirection, + Shape, + ShrinkWrap, + Size, + ValueChanged; + // PAINTING NODES -class Opacity extends OneChildRenderObjectWrapper { +class Opacity extends OneChildRenderObjectWidget { Opacity({ Key key, this.opacity, Widget child }) : super(key: key, child: child) { assert(opacity >= 0.0 && opacity <= 1.0); @@ -43,16 +44,14 @@ class Opacity extends OneChildRenderObjectWrapper { final double opacity; - RenderOpacity createNode() => new RenderOpacity(opacity: opacity); - RenderOpacity get renderObject => super.renderObject; + RenderOpacity createRenderObject() => new RenderOpacity(opacity: opacity); - void syncRenderObject(Opacity old) { - super.syncRenderObject(old); + void updateRenderObject(RenderOpacity renderObject, Opacity oldWidget) { renderObject.opacity = opacity; } } -class ColorFilter extends OneChildRenderObjectWrapper { +class ColorFilter extends OneChildRenderObjectWidget { ColorFilter({ Key key, this.color, this.transferMode, Widget child }) : super(key: key, child: child) { assert(color != null); @@ -62,17 +61,15 @@ class ColorFilter extends OneChildRenderObjectWrapper { final Color color; final sky.TransferMode transferMode; - RenderColorFilter createNode() => new RenderColorFilter(color: color, transferMode: transferMode); - RenderColorFilter get renderObject => super.renderObject; + RenderColorFilter createRenderObject() => new RenderColorFilter(color: color, transferMode: transferMode); - void syncRenderObject(ColorFilter old) { - super.syncRenderObject(old); + void updateRenderObject(RenderColorFilter renderObject, ColorFilter oldWidget) { renderObject.color = color; renderObject.transferMode = transferMode; } } -class DecoratedBox extends OneChildRenderObjectWrapper { +class DecoratedBox extends OneChildRenderObjectWidget { DecoratedBox({ Key key, this.decoration, @@ -86,82 +83,65 @@ class DecoratedBox extends OneChildRenderObjectWrapper { final BoxDecoration decoration; final BoxDecorationPosition position; - RenderDecoratedBox createNode() => new RenderDecoratedBox(decoration: decoration, position: position); - RenderDecoratedBox get renderObject => super.renderObject; + RenderObject createRenderObject() => new RenderDecoratedBox(decoration: decoration, position: position); - void syncRenderObject(DecoratedBox old) { - super.syncRenderObject(old); + void updateRenderObject(RenderDecoratedBox renderObject, DecoratedBox oldWidget) { renderObject.decoration = decoration; renderObject.position = position; } } -class CustomPaint extends OneChildRenderObjectWrapper { +class CustomPaint extends OneChildRenderObjectWidget { CustomPaint({ Key key, this.callback, this.token, Widget child }) : super(key: key, child: child) { assert(callback != null); } final CustomPaintCallback callback; - final dynamic token; // set this to be repainted automatically when the token changes + final Object token; // set this to be repainted automatically when the token changes - RenderCustomPaint createNode() => new RenderCustomPaint(callback: callback); - RenderCustomPaint get renderObject => super.renderObject; + RenderCustomPaint createRenderObject() => new RenderCustomPaint(callback: callback); - void syncRenderObject(CustomPaint old) { - super.syncRenderObject(old); - if (old != null && old.token != token) + void updateRenderObject(RenderCustomPaint renderObject, CustomPaint oldWidget) { + if (oldWidget != null && oldWidget.token != token) renderObject.markNeedsPaint(); renderObject.callback = callback; } - void remove() { + void didUnmountRenderObject(RenderCustomPaint renderObject) { renderObject.callback = null; - super.remove(); } } -class ClipRect extends OneChildRenderObjectWrapper { - ClipRect({ Key key, Widget child }) - : super(key: key, child: child); - - RenderClipRect createNode() => new RenderClipRect(); - RenderClipRect get renderObject => super.renderObject; - - // Nothing to sync, so we don't implement syncRenderObject() +class ClipRect extends OneChildRenderObjectWidget { + ClipRect({ Key key, Widget child }) : super(key: key, child: child); + RenderClipRect createRenderObject() => new RenderClipRect(); } -class ClipRRect extends OneChildRenderObjectWrapper { +class ClipRRect extends OneChildRenderObjectWidget { ClipRRect({ Key key, this.xRadius, this.yRadius, Widget child }) : super(key: key, child: child); final double xRadius; final double yRadius; - RenderClipRRect createNode() => new RenderClipRRect(xRadius: xRadius, yRadius: yRadius); - RenderClipRRect get renderObject => super.renderObject; + RenderClipRRect createRenderObject() => new RenderClipRRect(xRadius: xRadius, yRadius: yRadius); - void syncRenderObject(ClipRRect old) { - super.syncRenderObject(old); + void updateRenderObject(RenderClipRRect renderObject, ClipRRect oldWidget) { renderObject.xRadius = xRadius; renderObject.yRadius = yRadius; } } -class ClipOval extends OneChildRenderObjectWrapper { - ClipOval({ Key key, Widget child }) - : super(key: key, child: child); - - RenderClipOval createNode() => new RenderClipOval(); - RenderClipOval get renderObject => super.renderObject; - - // Nothing to sync, so we don't implement syncRenderObject() +class ClipOval extends OneChildRenderObjectWidget { + ClipOval({ Key key, Widget child }) : super(key: key, child: child); + RenderClipOval createRenderObject() => new RenderClipOval(); } // POSITIONING AND SIZING NODES -class Transform extends OneChildRenderObjectWrapper { +class Transform extends OneChildRenderObjectWidget { Transform({ Key key, this.transform, this.origin, Widget child }) : super(key: key, child: child) { assert(transform != null); @@ -170,17 +150,15 @@ class Transform extends OneChildRenderObjectWrapper { final Matrix4 transform; final Offset origin; - RenderTransform createNode() => new RenderTransform(transform: transform, origin: origin); - RenderTransform get renderObject => super.renderObject; + RenderTransform createRenderObject() => new RenderTransform(transform: transform, origin: origin); - void syncRenderObject(Transform old) { - super.syncRenderObject(old); + void updateRenderObject(RenderTransform renderObject, Transform oldWidget) { renderObject.transform = transform; renderObject.origin = origin; } } -class Padding extends OneChildRenderObjectWrapper { +class Padding extends OneChildRenderObjectWidget { Padding({ Key key, this.padding, Widget child }) : super(key: key, child: child) { assert(padding != null); @@ -188,16 +166,14 @@ class Padding extends OneChildRenderObjectWrapper { final EdgeDims padding; - RenderPadding createNode() => new RenderPadding(padding: padding); - RenderPadding get renderObject => super.renderObject; + RenderPadding createRenderObject() => new RenderPadding(padding: padding); - void syncRenderObject(Padding old) { - super.syncRenderObject(old); + void updateRenderObject(RenderPadding renderObject, Padding oldWidget) { renderObject.padding = padding; } } -class Align extends OneChildRenderObjectWrapper { +class Align extends OneChildRenderObjectWidget { Align({ Key key, this.horizontal: 0.5, @@ -214,11 +190,9 @@ class Align extends OneChildRenderObjectWrapper { final double vertical; final ShrinkWrap shrinkWrap; - RenderPositionedBox createNode() => new RenderPositionedBox(horizontal: horizontal, vertical: vertical, shrinkWrap: shrinkWrap); - RenderPositionedBox get renderObject => super.renderObject; + RenderPositionedBox createRenderObject() => new RenderPositionedBox(horizontal: horizontal, vertical: vertical, shrinkWrap: shrinkWrap); - void syncRenderObject(Align old) { - super.syncRenderObject(old); + void updateRenderObject(RenderPositionedBox renderObject, Align oldWidget) { renderObject.horizontal = horizontal; renderObject.vertical = vertical; renderObject.shrinkWrap = shrinkWrap; @@ -230,17 +204,18 @@ class Center extends Align { : super(key: key, shrinkWrap: shrinkWrap, child: child); } -class SizedBox extends OneChildRenderObjectWrapper { +class SizedBox extends OneChildRenderObjectWidget { SizedBox({ Key key, this.width, this.height, Widget child }) : super(key: key, child: child); final double width; final double height; - RenderConstrainedBox createNode() => new RenderConstrainedBox(additionalConstraints: _additionalConstraints()); - RenderConstrainedBox get renderObject => super.renderObject; + RenderConstrainedBox createRenderObject() => new RenderConstrainedBox( + additionalConstraints: _additionalConstraints + ); - BoxConstraints _additionalConstraints() { + BoxConstraints get _additionalConstraints { BoxConstraints result = const BoxConstraints(); if (width != null) result = result.tightenWidth(width); @@ -249,13 +224,12 @@ class SizedBox extends OneChildRenderObjectWrapper { return result; } - void syncRenderObject(SizedBox old) { - super.syncRenderObject(old); - renderObject.additionalConstraints = _additionalConstraints(); + void updateRenderObject(RenderConstrainedBox renderObject, SizedBox oldWidget) { + renderObject.additionalConstraints = _additionalConstraints; } } -class ConstrainedBox extends OneChildRenderObjectWrapper { +class ConstrainedBox extends OneChildRenderObjectWidget { ConstrainedBox({ Key key, this.constraints, Widget child }) : super(key: key, child: child) { assert(constraints != null); @@ -263,16 +237,38 @@ class ConstrainedBox extends OneChildRenderObjectWrapper { final BoxConstraints constraints; - RenderConstrainedBox createNode() => new RenderConstrainedBox(additionalConstraints: constraints); - RenderConstrainedBox get renderObject => super.renderObject; + RenderConstrainedBox createRenderObject() => new RenderConstrainedBox(additionalConstraints: constraints); - void syncRenderObject(ConstrainedBox old) { - super.syncRenderObject(old); + void updateRenderObject(RenderConstrainedBox renderObject, ConstrainedBox oldWidget) { renderObject.additionalConstraints = constraints; } } -class AspectRatio extends OneChildRenderObjectWrapper { +class OverflowBox extends OneChildRenderObjectWidget { + OverflowBox({ Key key, this.minWidth, this.maxWidth, this.minHeight, this.maxHeight, Widget child }) + : super(key: key, child: child); + + final double minWidth; + final double maxWidth; + final double minHeight; + final double maxHeight; + + RenderOverflowBox createRenderObject() => new RenderOverflowBox( + minWidth: minWidth, + maxWidth: maxWidth, + minHeight: minHeight, + maxHeight: maxHeight + ); + + void updateRenderObject(RenderOverflowBox renderObject, OverflowBox oldWidget) { + renderObject.minWidth = minWidth; + renderObject.maxWidth = maxWidth; + renderObject.minHeight = minHeight; + renderObject.maxHeight = maxHeight; + } +} + +class AspectRatio extends OneChildRenderObjectWidget { AspectRatio({ Key key, this.aspectRatio, Widget child }) : super(key: key, child: child) { assert(aspectRatio != null); @@ -280,43 +276,34 @@ class AspectRatio extends OneChildRenderObjectWrapper { final double aspectRatio; - RenderAspectRatio createNode() => new RenderAspectRatio(aspectRatio: aspectRatio); - RenderAspectRatio get renderObject => super.renderObject; + RenderAspectRatio createRenderObject() => new RenderAspectRatio(aspectRatio: aspectRatio); - void syncRenderObject(AspectRatio old) { - super.syncRenderObject(old); + void updateRenderObject(RenderAspectRatio renderObject, AspectRatio oldWidget) { renderObject.aspectRatio = aspectRatio; } } -class IntrinsicWidth extends OneChildRenderObjectWrapper { +class IntrinsicWidth extends OneChildRenderObjectWidget { IntrinsicWidth({ Key key, this.stepWidth, this.stepHeight, Widget child }) : super(key: key, child: child); final double stepWidth; final double stepHeight; - RenderIntrinsicWidth createNode() => new RenderIntrinsicWidth(stepWidth: stepWidth, stepHeight: stepHeight); - RenderIntrinsicWidth get renderObject => super.renderObject; + RenderIntrinsicWidth createRenderObject() => new RenderIntrinsicWidth(stepWidth: stepWidth, stepHeight: stepHeight); - void syncRenderObject(IntrinsicWidth old) { - super.syncRenderObject(old); + void updateRenderObject(RenderIntrinsicWidth renderObject, IntrinsicWidth oldWidget) { renderObject.stepWidth = stepWidth; renderObject.stepHeight = stepHeight; } } -class IntrinsicHeight extends OneChildRenderObjectWrapper { - IntrinsicHeight({ Key key, Widget child }) - : super(key: key, child: child); - - RenderIntrinsicHeight createNode() => new RenderIntrinsicHeight(); - RenderIntrinsicHeight get renderObject => super.renderObject; - - // Nothing to sync, so we don't implement syncRenderObject() +class IntrinsicHeight extends OneChildRenderObjectWidget { + IntrinsicHeight({ Key key, Widget child }) : super(key: key, child: child); + RenderIntrinsicHeight createRenderObject() => new RenderIntrinsicHeight(); } -class Baseline extends OneChildRenderObjectWrapper { +class Baseline extends OneChildRenderObjectWidget { Baseline({ Key key, this.baseline, this.baselineType: TextBaseline.alphabetic, Widget child }) : super(key: key, child: child) { assert(baseline != null); @@ -326,17 +313,15 @@ class Baseline extends OneChildRenderObjectWrapper { final double baseline; // in pixels final TextBaseline baselineType; - RenderBaseline createNode() => new RenderBaseline(baseline: baseline, baselineType: baselineType); - RenderBaseline get renderObject => super.renderObject; + RenderBaseline createRenderObject() => new RenderBaseline(baseline: baseline, baselineType: baselineType); - void syncRenderObject(Baseline old) { - super.syncRenderObject(old); + void updateRenderObject(RenderBaseline renderObject, Baseline oldWidget) { renderObject.baseline = baseline; renderObject.baselineType = baselineType; } } -class Viewport extends OneChildRenderObjectWrapper { +class Viewport extends OneChildRenderObjectWidget { Viewport({ Key key, this.scrollDirection: ScrollDirection.vertical, @@ -350,18 +335,16 @@ class Viewport extends OneChildRenderObjectWrapper { final ScrollDirection scrollDirection; final Offset scrollOffset; - RenderViewport createNode() => new RenderViewport(scrollDirection: scrollDirection, scrollOffset: scrollOffset); - RenderViewport get renderObject => super.renderObject; + RenderViewport createRenderObject() => new RenderViewport(scrollDirection: scrollDirection, scrollOffset: scrollOffset); - void syncRenderObject(Viewport old) { - super.syncRenderObject(old); + void updateRenderObject(RenderViewport renderObject, Viewport oldWidget) { // Order dependency: RenderViewport validates scrollOffset based on scrollDirection. renderObject.scrollDirection = scrollDirection; renderObject.scrollOffset = scrollOffset; } } -class SizeObserver extends OneChildRenderObjectWrapper { +class SizeObserver extends OneChildRenderObjectWidget { SizeObserver({ Key key, this.callback, Widget child }) : super(key: key, child: child) { assert(callback != null); @@ -369,24 +352,21 @@ class SizeObserver extends OneChildRenderObjectWrapper { final SizeChangedCallback callback; - RenderSizeObserver createNode() => new RenderSizeObserver(callback: callback); - RenderSizeObserver get renderObject => super.renderObject; + RenderSizeObserver createRenderObject() => new RenderSizeObserver(callback: callback); - void syncRenderObject(SizeObserver old) { - super.syncRenderObject(old); + void updateRenderObject(RenderSizeObserver renderObject, SizeObserver oldWidget) { renderObject.callback = callback; } - void remove() { + void didUnmountRenderObject(RenderSizeObserver renderObject) { renderObject.callback = null; - super.remove(); } } // CONVENIENCE CLASS TO COMBINE COMMON PAINTING, POSITIONING, AND SIZING NODES -class Container extends Component { +class Container extends StatelessComponent { Container({ Key key, @@ -423,7 +403,7 @@ class Container extends Component { return padding + borderPadding; } - Widget build() { + Widget build(BuildContext context) { Widget current = child; if (child == null && (width == null || height == null)) @@ -469,7 +449,7 @@ class Container extends Component { // LAYOUT NODES -class BlockBody extends MultiChildRenderObjectWrapper { +class BlockBody extends MultiChildRenderObjectWidget { BlockBody(List children, { Key key, this.direction: BlockDirection.vertical @@ -479,30 +459,45 @@ class BlockBody extends MultiChildRenderObjectWrapper { final BlockDirection direction; - RenderBlock createNode() => new RenderBlock(direction: direction); - RenderBlock get renderObject => super.renderObject; + RenderBlock createRenderObject() => new RenderBlock(direction: direction); - void syncRenderObject(Widget old) { - super.syncRenderObject(old); + void updateRenderObject(RenderBlock renderObject, BlockBody oldWidget) { renderObject.direction = direction; } } -class Stack extends MultiChildRenderObjectWrapper { - Stack(List children, { Key key }) - : super(key: key, children: children); +class Stack extends MultiChildRenderObjectWidget { + Stack(List children, { Key key }) : super(key: key, children: children); + RenderStack createRenderObject() => new RenderStack(); +} - RenderStack createNode() => new RenderStack(); - RenderStack get renderObject => super.renderObject; +class Positioned extends ParentDataWidget { + Positioned({ + Key key, + Widget child, + this.top, + this.right, + this.bottom, + this.left + }) : super(key: key, child: child); - void updateParentData(RenderObject child, Positioned positioned) { - _updateParentDataWithValues(child, positioned?.top, positioned?.right, positioned?.bottom, positioned?.left); + final double top; + final double right; + final double bottom; + final double left; + + void debugValidateAncestor(Widget ancestor) { + assert(() { + 'Positioned must placed inside a Stack'; + return ancestor is Stack; + }); } - void _updateParentDataWithValues(RenderObject child, double top, double right, double bottom, double left) { - assert(child.parentData is StackParentData); - final StackParentData parentData = child.parentData; + void applyParentData(RenderObject renderObject) { + assert(renderObject.parentData is StackParentData); + final StackParentData parentData = renderObject.parentData; bool needsLayout = false; + if (parentData.top != top) { parentData.top = top; needsLayout = true; @@ -528,30 +523,7 @@ class Stack extends MultiChildRenderObjectWrapper { } } -class Positioned extends ParentDataNode { - Positioned({ - Key key, - Widget child, - this.top, - this.right, - this.bottom, - this.left - }) : super(key: key, child: child); - - final double top; - final double right; - final double bottom; - final double left; - - void debugValidateAncestor(Widget ancestor) { - assert(() { - 'Positioned must placed directly inside a Stack'; - return ancestor is Stack; - }); - } -} - -class Grid extends MultiChildRenderObjectWrapper { +class Grid extends MultiChildRenderObjectWidget { Grid(List children, { Key key, this.maxChildExtent }) : super(key: key, children: children) { assert(maxChildExtent != null); @@ -559,16 +531,14 @@ class Grid extends MultiChildRenderObjectWrapper { final double maxChildExtent; - RenderGrid createNode() => new RenderGrid(maxChildExtent: maxChildExtent); - RenderGrid get renderObject => super.renderObject; + RenderGrid createRenderObject() => new RenderGrid(maxChildExtent: maxChildExtent); - void syncRenderObject(Widget old) { - super.syncRenderObject(old); + void updateRenderObject(RenderGrid renderObject, Grid oldWidget) { renderObject.maxChildExtent = maxChildExtent; } } -class Flex extends MultiChildRenderObjectWrapper { +class Flex extends MultiChildRenderObjectWidget { Flex(List children, { Key key, this.direction: FlexDirection.horizontal, @@ -586,29 +556,14 @@ class Flex extends MultiChildRenderObjectWrapper { final FlexAlignItems alignItems; final TextBaseline textBaseline; - RenderFlex createNode() => new RenderFlex(direction: direction); - RenderFlex get renderObject => super.renderObject; + RenderFlex createRenderObject() => new RenderFlex(direction: direction, justifyContent: justifyContent, alignItems: alignItems, textBaseline: textBaseline); - void syncRenderObject(Widget old) { - super.syncRenderObject(old); + void updateRenderObject(RenderFlex renderObject, Flex oldWidget) { renderObject.direction = direction; renderObject.justifyContent = justifyContent; renderObject.alignItems = alignItems; renderObject.textBaseline = textBaseline; } - - void updateParentData(RenderObject child, Flexible flexible) { - _updateParentDataWithValues(child, flexible?.flex); - } - - void _updateParentDataWithValues(RenderObject child, int flex) { - assert(child.parentData is FlexParentData); - final FlexParentData parentData = child.parentData; - if (parentData.flex != flex) { - parentData.flex = flex; - renderObject.markNeedsLayout(); - } - } } class Row extends Flex { @@ -629,7 +584,7 @@ class Column extends Flex { }) : super(children, key: key, direction: FlexDirection.vertical, justifyContent: justifyContent, alignItems: alignItems, textBaseline: textBaseline); } -class Flexible extends ParentDataNode { +class Flexible extends ParentDataWidget { Flexible({ Key key, this.flex: 1, Widget child }) : super(key: key, child: child); @@ -637,29 +592,36 @@ class Flexible extends ParentDataNode { void debugValidateAncestor(Widget ancestor) { assert(() { - 'Flexible must placed directly inside a Flex'; + 'Flexible must placed inside a Flex'; return ancestor is Flex; }); } + + void applyParentData(RenderObject renderObject) { + assert(renderObject.parentData is FlexParentData); + final FlexParentData parentData = renderObject.parentData; + if (parentData.flex != flex) { + parentData.flex = flex; + renderObject.markNeedsLayout(); + } + } } -class Paragraph extends LeafRenderObjectWrapper { +class Paragraph extends LeafRenderObjectWidget { Paragraph({ Key key, this.text }) : super(key: key) { assert(text != null); } final TextSpan text; - RenderParagraph createNode() => new RenderParagraph(text); - RenderParagraph get renderObject => super.renderObject; + RenderParagraph createRenderObject() => new RenderParagraph(text); - void syncRenderObject(Widget old) { - super.syncRenderObject(old); + void updateRenderObject(RenderParagraph renderObject, Paragraph oldWidget) { renderObject.text = text; } } -class StyledText extends Component { +class StyledText extends StatelessComponent { // elements ::= "string" | [ *] // Where "string" is text to display and text-style is an instance of // TextStyle. The text-style applies to all of the elements that follow. @@ -681,12 +643,32 @@ class StyledText extends Component { throw new ArgumentError("Element is ${element.runtimeType} not a String or an Iterable"); } - Widget build() { + Widget build(BuildContext context) { return new Paragraph(text: _toSpan(elements)); } } -class Text extends Component { +class DefaultTextStyle extends InheritedWidget { + DefaultTextStyle({ + Key key, + this.style, + Widget child + }) : super(key: key, child: child) { + assert(style != null); + assert(child != null); + } + + final TextStyle style; + + static TextStyle of(BuildContext context) { + DefaultTextStyle result = context.inheritedWidgetOfType(DefaultTextStyle); + return result?.style; + } + + bool updateShouldNotify(DefaultTextStyle old) => style != old.style; +} + +class Text extends StatelessComponent { Text(this.data, { Key key, TextStyle this.style }) : super(key: key) { assert(data != null); } @@ -694,9 +676,9 @@ class Text extends Component { final String data; final TextStyle style; - Widget build() { + Widget build(BuildContext context) { TextSpan text = new PlainTextSpan(data); - TextStyle defaultStyle = DefaultTextStyle.of(this); + TextStyle defaultStyle = DefaultTextStyle.of(context); TextStyle combinedStyle; if (defaultStyle != null) { if (style != null) @@ -712,7 +694,7 @@ class Text extends Component { } } -class Image extends LeafRenderObjectWrapper { +class Image extends LeafRenderObjectWidget { Image({ Key key, this.image, @@ -730,17 +712,15 @@ class Image extends LeafRenderObjectWrapper { final ImageFit fit; final ImageRepeat repeat; - RenderImage createNode() => new RenderImage( + RenderImage createRenderObject() => new RenderImage( image: image, width: width, height: height, colorFilter: colorFilter, fit: fit, repeat: repeat); - RenderImage get renderObject => super.renderObject; - void syncRenderObject(Widget old) { - super.syncRenderObject(old); + void updateRenderObject(RenderImage renderObject, Image oldWidget) { renderObject.image = image; renderObject.width = width; renderObject.height = height; @@ -763,59 +743,55 @@ class ImageListener extends StatefulComponent { assert(image != null); } - ImageResource image; - double width; - double height; - sky.ColorFilter colorFilter; - ImageFit fit; - ImageRepeat repeat; + final ImageResource image; + final double width; + final double height; + final sky.ColorFilter colorFilter; + final ImageFit fit; + final ImageRepeat repeat; + + ImageListenerState createState() => new ImageListenerState(); +} + +class ImageListenerState extends State { + void initState() { + super.initState(); + config.image.addListener(_handleImageChanged); + } sky.Image _resolvedImage; void _handleImageChanged(sky.Image resolvedImage) { - assert(mounted); setState(() { _resolvedImage = resolvedImage; }); } - void didMount() { - super.didMount(); - image.addListener(_handleImageChanged); + void dispose() { + config.image.removeListener(_handleImageChanged); + super.dispose(); } - void didUnmount() { - super.didUnmount(); - image.removeListener(_handleImageChanged); + void didUpdateConfig(ImageListener oldConfig) { + if (config.image != oldConfig.image) { + oldConfig.image.removeListener(_handleImageChanged); + config.image.addListener(_handleImageChanged); + } } - void syncConstructorArguments(ImageListener source) { - final bool needToUpdateListeners = (image != source.image) && mounted; - if (needToUpdateListeners) - image.removeListener(_handleImageChanged); - image = source.image; - width = source.width; - height = source.height; - colorFilter = source.colorFilter; - fit = source.fit; - repeat = source.repeat; - if (needToUpdateListeners) - image.addListener(_handleImageChanged); - } - - Widget build() { + Widget build(BuildContext context) { return new Image( image: _resolvedImage, - width: width, - height: height, - colorFilter: colorFilter, - fit: fit, - repeat: repeat + width: config.width, + height: config.height, + colorFilter: config.colorFilter, + fit: config.fit, + repeat: config.repeat ); } } -class NetworkImage extends Component { +class NetworkImage extends StatelessComponent { NetworkImage({ Key key, this.src, @@ -833,7 +809,7 @@ class NetworkImage extends Component { final ImageFit fit; final ImageRepeat repeat; - Widget build() { + Widget build(BuildContext context) { return new ImageListener( image: imageCache.load(src), width: width, @@ -845,7 +821,7 @@ class NetworkImage extends Component { } } -class AssetImage extends Component { +class AssetImage extends StatelessComponent { AssetImage({ Key key, this.name, @@ -865,7 +841,7 @@ class AssetImage extends Component { final ImageFit fit; final ImageRepeat repeat; - Widget build() { + Widget build(BuildContext context) { return new ImageListener( image: bundle.loadImage(name), width: width, @@ -877,47 +853,61 @@ class AssetImage extends Component { } } -class WidgetToRenderBoxAdapter extends LeafRenderObjectWrapper { - WidgetToRenderBoxAdapter(RenderBox renderBox) - : renderBox = renderBox, - super(key: new ObjectKey(renderBox)); - - final RenderBox renderBox; - - RenderBox createNode() => this.renderBox; - RenderBox get renderObject => super.renderObject; - - void syncRenderObject(Widget old) { - super.syncRenderObject(old); - if (old != null) { - assert(old is WidgetToRenderBoxAdapter); - assert(renderObject == old.renderObject); - } - } - - void remove() { - RenderObjectWrapper ancestor = findAncestorRenderObjectWrapper(); - assert(ancestor is RenderObjectWrapper); - assert(ancestor.renderObject == renderObject.parent); - ancestor.detachChildRenderObject(this); - super.remove(); - } -} - // EVENT HANDLING -class IgnorePointer extends OneChildRenderObjectWrapper { +class Listener extends OneChildRenderObjectWidget { + Listener({ + Key key, + Widget child, + this.onPointerDown, + this.onPointerMove, + this.onPointerUp, + this.onPointerCancel + }): super(key: key, child: child); + + final PointerEventListener onPointerDown; + final PointerEventListener onPointerMove; + final PointerEventListener onPointerUp; + final PointerEventListener onPointerCancel; + + RenderPointerListener createRenderObject() => new RenderPointerListener( + onPointerDown: onPointerDown, + onPointerMove: onPointerMove, + onPointerUp: onPointerUp, + onPointerCancel: onPointerCancel + ); + + void updateRenderObject(RenderPointerListener renderObject, Listener oldWidget) { + renderObject.onPointerDown = onPointerDown; + renderObject.onPointerMove = onPointerMove; + renderObject.onPointerUp = onPointerUp; + renderObject.onPointerCancel = onPointerCancel; + } +} + +class IgnorePointer extends OneChildRenderObjectWidget { IgnorePointer({ Key key, Widget child, this.ignoring: true }) : super(key: key, child: child); final bool ignoring; - RenderIgnorePointer createNode() => new RenderIgnorePointer(ignoring: ignoring); - RenderIgnorePointer get renderObject => super.renderObject; + RenderIgnorePointer createRenderObject() => new RenderIgnorePointer(ignoring: ignoring); - void syncRenderObject(Widget old) { - super.syncRenderObject(old); + void updateRenderObject(RenderIgnorePointer renderObject, IgnorePointer oldWidget) { renderObject.ignoring = ignoring; } } + +class MetaData extends OneChildRenderObjectWidget { + MetaData({ Key key, Widget child, this.metaData }) + : super(key: key, child: child); + + final dynamic metaData; + + RenderMetaData createRenderObject() => new RenderMetaData(metaData: metaData); + + void updateRenderObject(RenderMetaData renderObject, MetaData oldWidget) { + renderObject.metaData = metaData; + } +} diff --git a/packages/flutter/lib/src/fn3/binding.dart b/packages/flutter/lib/src/widgets/binding.dart similarity index 99% rename from packages/flutter/lib/src/fn3/binding.dart rename to packages/flutter/lib/src/widgets/binding.dart index 3ae867163d..1ad4b06262 100644 --- a/packages/flutter/lib/src/fn3/binding.dart +++ b/packages/flutter/lib/src/widgets/binding.dart @@ -6,7 +6,7 @@ import 'dart:async'; import 'package:sky/animation.dart'; import 'package:sky/rendering.dart'; -import 'package:sky/src/fn3/framework.dart'; +import 'package:sky/src/widgets/framework.dart'; class WidgetFlutterBinding extends FlutterBinding { diff --git a/packages/flutter/lib/src/widgets/button_base.dart b/packages/flutter/lib/src/widgets/button_base.dart deleted file mode 100644 index dd4cebb1a3..0000000000 --- a/packages/flutter/lib/src/widgets/button_base.dart +++ /dev/null @@ -1,46 +0,0 @@ -// 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. - -import 'package:sky/src/widgets/framework.dart'; - -abstract class ButtonBase extends StatefulComponent { - - ButtonBase({ Key key, this.highlight: false }) : super(key: key); - - bool highlight; - - void syncConstructorArguments(ButtonBase source) { - highlight = source.highlight; - } - - void _handlePointerDown(_) { - setState(() { - highlight = true; - }); - } - - void _handlePointerUp(_) { - setState(() { - highlight = false; - }); - } - - void _handlePointerCancel(_) { - setState(() { - highlight = false; - }); - } - - Widget build() { - return new Listener( - child: buildContent(), - onPointerDown: _handlePointerDown, - onPointerUp: _handlePointerUp, - onPointerCancel: _handlePointerCancel - ); - } - - Widget buildContent(); - -} diff --git a/packages/flutter/lib/src/fn3/button_state.dart b/packages/flutter/lib/src/widgets/button_state.dart similarity index 89% rename from packages/flutter/lib/src/fn3/button_state.dart rename to packages/flutter/lib/src/widgets/button_state.dart index f821be62a2..a9c5366cb3 100644 --- a/packages/flutter/lib/src/fn3/button_state.dart +++ b/packages/flutter/lib/src/widgets/button_state.dart @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:sky/src/fn3/basic.dart'; -import 'package:sky/src/fn3/framework.dart'; +import 'package:sky/src/widgets/basic.dart'; +import 'package:sky/src/widgets/framework.dart'; abstract class ButtonState extends State { bool highlight = false; diff --git a/packages/flutter/lib/src/widgets/card.dart b/packages/flutter/lib/src/widgets/card.dart index db059fb6e4..c9e0435805 100644 --- a/packages/flutter/lib/src/widgets/card.dart +++ b/packages/flutter/lib/src/widgets/card.dart @@ -11,13 +11,13 @@ const EdgeDims _kCardMargins = const EdgeDims.all(4.0); /// A material design card /// /// -class Card extends Component { - Card({ Key key, this.child, this.color }) : super(key: key); +class Card extends StatelessComponent { + const Card({ Key key, this.child, this.color }) : super(key: key); final Widget child; final Color color; - Widget build() { + Widget build(BuildContext context) { return new Container( margin: _kCardMargins, child: new Material( diff --git a/packages/flutter/lib/src/widgets/checkbox.dart b/packages/flutter/lib/src/widgets/checkbox.dart index f4dc443ce5..2f69665986 100644 --- a/packages/flutter/lib/src/widgets/checkbox.dart +++ b/packages/flutter/lib/src/widgets/checkbox.dart @@ -4,10 +4,10 @@ import 'dart:sky' as sky; -import 'package:sky/src/rendering/object.dart'; import 'package:sky/src/widgets/basic.dart'; -import 'package:sky/src/widgets/theme.dart'; import 'package:sky/src/widgets/framework.dart'; +import 'package:sky/src/widgets/theme.dart'; +import 'package:sky/src/rendering/object.dart'; import 'package:sky/src/rendering/toggleable.dart'; export 'package:sky/src/rendering/toggleable.dart' show ValueChanged; @@ -17,7 +17,6 @@ const sky.Color _kLightUncheckedColor = const sky.Color(0x8A000000); const sky.Color _kDarkUncheckedColor = const sky.Color(0xB2FFFFFF); const double _kEdgeSize = 20.0; const double _kEdgeRadius = 1.0; -const Duration _kCheckDuration = const Duration(milliseconds: 200); /// A material design checkbox /// @@ -28,48 +27,58 @@ const Duration _kCheckDuration = const Duration(milliseconds: 200); /// the checkbox. /// /// -class Checkbox extends Component { +class Checkbox extends StatelessComponent { /// Constructs a checkbox /// /// * `value` determines whether the checkbox is checked. /// * `onChanged` is called whenever the state of the checkbox should change. - Checkbox({Key key, this.value, this.onChanged}) : super(key: key); + const Checkbox({Key key, this.value, this.onChanged}) : super(key: key); final bool value; final ValueChanged onChanged; - Widget build() { - ThemeData themeData = Theme.of(this); + Widget build(BuildContext context) { + ThemeData themeData = Theme.of(context); Color uncheckedColor = themeData.brightness == ThemeBrightness.light ? _kLightUncheckedColor : _kDarkUncheckedColor; return new _CheckboxWrapper( - value: value, - onChanged: onChanged, - uncheckedColor: uncheckedColor, - accentColor: themeData.accentColor); + value: value, + onChanged: onChanged, + uncheckedColor: uncheckedColor, + accentColor: themeData.accentColor + ); } } // This wrapper class exists only because Switch needs to be a Component in // order to get an accent color from a Theme but Components do not know how to // host RenderObjects. -class _CheckboxWrapper extends LeafRenderObjectWrapper { - _CheckboxWrapper({Key key, this.value, this.onChanged, this.uncheckedColor, - this.accentColor}) - : super(key: key); +class _CheckboxWrapper extends LeafRenderObjectWidget { + _CheckboxWrapper({ + Key key, + this.value, + this.onChanged, + this.uncheckedColor, + this.accentColor + }): super(key: key) { + assert(uncheckedColor != null); + assert(accentColor != null); + } final bool value; final ValueChanged onChanged; final Color uncheckedColor; final Color accentColor; - _RenderCheckbox get renderObject => super.renderObject; - _RenderCheckbox createNode() => new _RenderCheckbox( - value: value, uncheckedColor: uncheckedColor, onChanged: onChanged); + _RenderCheckbox createRenderObject() => new _RenderCheckbox( + value: value, + accentColor: accentColor, + uncheckedColor: uncheckedColor, + onChanged: onChanged + ); - void syncRenderObject(_CheckboxWrapper old) { - super.syncRenderObject(old); + void updateRenderObject(_RenderCheckbox renderObject, _CheckboxWrapper oldWidget) { renderObject.value = value; renderObject.onChanged = onChanged; renderObject.uncheckedColor = uncheckedColor; @@ -78,25 +87,38 @@ class _CheckboxWrapper extends LeafRenderObjectWrapper { } class _RenderCheckbox extends RenderToggleable { - _RenderCheckbox({bool value, Color uncheckedColor, ValueChanged onChanged}) - : _uncheckedColor = uncheckedColor, - super( - value: value, - onChanged: onChanged, - size: new Size(_kEdgeSize, _kEdgeSize)) {} + _RenderCheckbox({ + bool value, + Color uncheckedColor, + Color accentColor, + ValueChanged onChanged + }): _uncheckedColor = uncheckedColor, + _accentColor = accentColor, + super( + value: value, + onChanged: onChanged, + size: new Size(_kEdgeSize, _kEdgeSize) + ) { + assert(uncheckedColor != null); + assert(accentColor != null); + } Color _uncheckedColor; Color get uncheckedColor => _uncheckedColor; void set uncheckedColor(Color value) { - if (value == _uncheckedColor) return; + assert(value != null); + if (value == _uncheckedColor) + return; _uncheckedColor = value; markNeedsPaint(); } Color _accentColor; void set accentColor(Color value) { - if (value == _accentColor) return; + assert(value != null); + if (value == _accentColor) + return; _accentColor = value; markNeedsPaint(); } @@ -109,7 +131,7 @@ class _RenderCheckbox extends RenderToggleable { ..color = uncheckedColor; // The rrect contracts slightly during the animation - double inset = 2.0 - (position.value - _kMidpoint).abs() * 2.0; + double inset = 2.0 - (position - _kMidpoint).abs() * 2.0; sky.Rect rect = new sky.Rect.fromLTWH(offset.dx + inset, offset.dy + inset, _kEdgeSize - inset, _kEdgeSize - inset); sky.RRect rrect = new sky.RRect() @@ -120,19 +142,19 @@ class _RenderCheckbox extends RenderToggleable { canvas.drawRRect(rrect, paint); // Radial gradient that changes size - if (position.value > 0) { + if (position > 0) { paint.setStyle(sky.PaintingStyle.fill); paint.setShader(new sky.Gradient.radial( new Point(_kEdgeSize / 2.0, _kEdgeSize / 2.0), - _kEdgeSize * (_kMidpoint - position.value) * 8.0, [ + _kEdgeSize * (_kMidpoint - position) * 8.0, [ const sky.Color(0x00000000), uncheckedColor ])); canvas.drawRRect(rrect, paint); } - if (position.value > _kMidpoint) { - double t = (position.value - _kMidpoint) / (1.0 - _kMidpoint); + if (position > _kMidpoint) { + double t = (position - _kMidpoint) / (1.0 - _kMidpoint); // Solid filled rrect paint.setStyle(sky.PaintingStyle.strokeAndFill); diff --git a/packages/flutter/lib/src/widgets/date_picker.dart b/packages/flutter/lib/src/widgets/date_picker.dart index b5f7c92ba8..ed3a91c8b7 100644 --- a/packages/flutter/lib/src/widgets/date_picker.dart +++ b/packages/flutter/lib/src/widgets/date_picker.dart @@ -7,6 +7,7 @@ import 'dart:async'; import 'package:intl/date_symbols.dart'; import 'package:intl/intl.dart'; import 'package:sky/material.dart'; +import 'package:sky/painting.dart'; import 'package:sky/services.dart'; import 'package:sky/src/widgets/basic.dart'; import 'package:sky/src/widgets/framework.dart'; @@ -33,18 +34,15 @@ class DatePicker extends StatefulComponent { assert(lastDate != null); } - DateTime selectedDate; - DatePickerValueChanged onChanged; - DateTime firstDate; - DateTime lastDate; + final DateTime selectedDate; + final DatePickerValueChanged onChanged; + final DateTime firstDate; + final DateTime lastDate; - void syncConstructorArguments(DatePicker source) { - selectedDate = source.selectedDate; - onChanged = source.onChanged; - firstDate = source.firstDate; - lastDate = source.lastDate; - } + DatePickerState createState() => new DatePickerState(); +} +class DatePickerState extends State { DatePickerMode _mode = DatePickerMode.day; void _handleModeChanged(DatePickerMode mode) { @@ -59,21 +57,21 @@ class DatePicker extends StatefulComponent { setState(() { _mode = DatePickerMode.day; }); - if (onChanged != null) - onChanged(dateTime); + if (config.onChanged != null) + config.onChanged(dateTime); } void _handleDayChanged(DateTime dateTime) { userFeedback.performHapticFeedback(HapticFeedbackType.VIRTUAL_KEY); - if (onChanged != null) - onChanged(dateTime); + if (config.onChanged != null) + config.onChanged(dateTime); } static const double _calendarHeight = 210.0; - Widget build() { + Widget build(BuildContext context) { Widget header = new DatePickerHeader( - selectedDate: selectedDate, + selectedDate: config.selectedDate, mode: _mode, onModeChanged: _handleModeChanged ); @@ -81,19 +79,19 @@ class DatePicker extends StatefulComponent { switch (_mode) { case DatePickerMode.day: picker = new MonthPicker( - selectedDate: selectedDate, + selectedDate: config.selectedDate, onChanged: _handleDayChanged, - firstDate: firstDate, - lastDate: lastDate, + firstDate: config.firstDate, + lastDate: config.lastDate, itemExtent: _calendarHeight ); break; case DatePickerMode.year: picker = new YearPicker( - selectedDate: selectedDate, + selectedDate: config.selectedDate, onChanged: _handleYearChanged, - firstDate: firstDate, - lastDate: lastDate + firstDate: config.firstDate, + lastDate: config.lastDate ); break; } @@ -109,7 +107,7 @@ class DatePicker extends StatefulComponent { } // Shows the selected date in large font and toggles between year and day mode -class DatePickerHeader extends Component { +class DatePickerHeader extends StatelessComponent { DatePickerHeader({ this.selectedDate, this.mode, this.onModeChanged }) { assert(selectedDate != null); assert(mode != null); @@ -124,8 +122,8 @@ class DatePickerHeader extends Component { onModeChanged(value); } - Widget build() { - ThemeData theme = Theme.of(this); + Widget build(BuildContext context) { + ThemeData theme = Theme.of(context); TextTheme headerTheme; Color dayColor; Color yearColor; @@ -167,7 +165,7 @@ class DatePickerHeader extends Component { } // Fixed height component shows a single month and allows choosing a day -class DayPicker extends Component { +class DayPicker extends StatelessComponent { DayPicker({ this.selectedDate, this.currentDate, @@ -185,8 +183,8 @@ class DayPicker extends Component { final DatePickerValueChanged onChanged; final DateTime displayedMonth; - Widget build() { - ThemeData theme = Theme.of(this); + Widget build(BuildContext context) { + ThemeData theme = Theme.of(context); TextStyle headerStyle = theme.text.caption.copyWith(fontWeight: FontWeight.w700); TextStyle monthStyle = headerStyle.copyWith(fontSize: 14.0, height: 24.0 / 14.0); TextStyle dayStyle = headerStyle.copyWith(fontWeight: FontWeight.w500); @@ -287,22 +285,18 @@ class MonthPicker extends ScrollableWidgetList { assert(lastDate.isAfter(firstDate)); } - DateTime selectedDate; - DatePickerValueChanged onChanged; - DateTime firstDate; - DateTime lastDate; + final DateTime selectedDate; + final DatePickerValueChanged onChanged; + final DateTime firstDate; + final DateTime lastDate; - void syncConstructorArguments(MonthPicker source) { - selectedDate = source.selectedDate; - onChanged = source.onChanged; - firstDate = source.firstDate; - lastDate = source.lastDate; - super.syncConstructorArguments(source); - } + MonthPickerState createState() => new MonthPickerState(); +} +class MonthPickerState extends ScrollableWidgetListState { void initState() { - _updateCurrentDate(); super.initState(); + _updateCurrentDate(); } DateTime _currentDate; @@ -322,20 +316,20 @@ class MonthPicker extends ScrollableWidgetList { }); } - int get itemCount => (lastDate.year - firstDate.year) * 12 + lastDate.month - firstDate.month + 1; + int get itemCount => (config.lastDate.year - config.firstDate.year) * 12 + config.lastDate.month - config.firstDate.month + 1; - List buildItems(int start, int count) { + List buildItems(BuildContext context, int start, int count) { List result = new List(); - DateTime startDate = new DateTime(firstDate.year + start ~/ 12, firstDate.month + start % 12); + DateTime startDate = new DateTime(config.firstDate.year + start ~/ 12, config.firstDate.month + start % 12); for (int i = 0; i < count; ++i) { DateTime displayedMonth = new DateTime(startDate.year + i ~/ 12, startDate.month + i % 12); Widget item = new Container( - height: itemExtent, + height: config.itemExtent, key: new ObjectKey(displayedMonth), child: new DayPicker( - selectedDate: selectedDate, + selectedDate: config.selectedDate, currentDate: _currentDate, - onChanged: onChanged, + onChanged: config.onChanged, displayedMonth: displayedMonth ) ); @@ -344,11 +338,10 @@ class MonthPicker extends ScrollableWidgetList { return result; } - void didUnmount() { - super.didUnmount(); - if (_timer != null) { + void dispose() { + if (_timer != null) _timer.cancel(); - } + super.dispose(); } } @@ -364,38 +357,35 @@ class YearPicker extends ScrollableWidgetList { assert(onChanged != null); assert(lastDate.isAfter(firstDate)); } - DateTime selectedDate; - DatePickerValueChanged onChanged; - DateTime firstDate; - DateTime lastDate; - void syncConstructorArguments(YearPicker source) { - selectedDate = source.selectedDate; - onChanged = source.onChanged; - firstDate = source.firstDate; - lastDate = source.lastDate; - super.syncConstructorArguments(source); - } + final DateTime selectedDate; + final DatePickerValueChanged onChanged; + final DateTime firstDate; + final DateTime lastDate; - int get itemCount => lastDate.year - firstDate.year + 1; + YearPickerState createState() => new YearPickerState(); +} - List buildItems(int start, int count) { - TextStyle style = Theme.of(this).text.body1.copyWith(color: Colors.black54); +class YearPickerState extends ScrollableWidgetListState { + int get itemCount => config.lastDate.year - config.firstDate.year + 1; + + List buildItems(BuildContext context, int start, int count) { + TextStyle style = Theme.of(context).text.body1.copyWith(color: Colors.black54); List items = new List(); for(int i = start; i < start + count; i++) { - int year = firstDate.year + i; + int year = config.firstDate.year + i; String label = year.toString(); Widget item = new GestureDetector( key: new Key(label), onTap: () { - DateTime result = new DateTime(year, selectedDate.month, selectedDate.day); - onChanged(result); + DateTime result = new DateTime(year, config.selectedDate.month, config.selectedDate.day); + config.onChanged(result); }, child: new InkWell( child: new Container( - height: itemExtent, - decoration: year == selectedDate.year ? new BoxDecoration( - backgroundColor: Theme.of(this).primarySwatch[100], + height: config.itemExtent, + decoration: year == config.selectedDate.year ? new BoxDecoration( + backgroundColor: Theme.of(context).primarySwatch[100], shape: Shape.circle ) : null, child: new Center( diff --git a/packages/flutter/lib/src/widgets/default_text_style.dart b/packages/flutter/lib/src/widgets/default_text_style.dart deleted file mode 100644 index eb5d9964b2..0000000000 --- a/packages/flutter/lib/src/widgets/default_text_style.dart +++ /dev/null @@ -1,29 +0,0 @@ -// 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. - -import 'package:sky/painting.dart'; -import 'package:sky/src/widgets/basic.dart'; -import 'package:sky/src/widgets/framework.dart'; - -class DefaultTextStyle extends Inherited { - - DefaultTextStyle({ - Key key, - this.style, - Widget child - }) : super(key: key, child: child) { - assert(style != null); - assert(child != null); - } - - final TextStyle style; - - static TextStyle of(Widget widget) { - DefaultTextStyle result = widget.inheritedOfType(DefaultTextStyle); - return result?.style; - } - - bool syncShouldNotify(DefaultTextStyle old) => style != old.style; - -} diff --git a/packages/flutter/lib/src/widgets/dialog.dart b/packages/flutter/lib/src/widgets/dialog.dart index 7be95f8f2b..2e83515ca0 100644 --- a/packages/flutter/lib/src/widgets/dialog.dart +++ b/packages/flutter/lib/src/widgets/dialog.dart @@ -7,7 +7,6 @@ import 'dart:async'; import 'package:sky/animation.dart'; import 'package:sky/material.dart'; import 'package:sky/src/widgets/basic.dart'; -import 'package:sky/src/widgets/default_text_style.dart'; import 'package:sky/src/widgets/focus.dart'; import 'package:sky/src/widgets/framework.dart'; import 'package:sky/src/widgets/gesture_detector.dart'; @@ -17,12 +16,12 @@ import 'package:sky/src/widgets/scrollable.dart'; import 'package:sky/src/widgets/theme.dart'; import 'package:sky/src/widgets/transitions.dart'; -typedef Widget DialogBuilder(Navigator navigator); +typedef Widget DialogBuilder(NavigatorState navigator); /// A material design dialog /// /// -class Dialog extends Component { +class Dialog extends StatelessComponent { Dialog({ Key key, this.title, @@ -55,8 +54,8 @@ class Dialog extends Component { /// An (optional) callback that is called when the dialog is dismissed. final Function onDismiss; - Color get _color { - switch (Theme.of(this).brightness) { + Color _getColor(BuildContext context) { + switch (Theme.of(context).brightness) { case ThemeBrightness.light: return Colors.white; case ThemeBrightness.dark: @@ -64,7 +63,7 @@ class Dialog extends Component { } } - Widget build() { + Widget build(BuildContext context) { List dialogBody = new List(); @@ -75,7 +74,7 @@ class Dialog extends Component { dialogBody.add(new Padding( padding: padding, child: new DefaultTextStyle( - style: Theme.of(this).text.title, + style: Theme.of(context).text.title, child: title ) )); @@ -88,7 +87,7 @@ class Dialog extends Component { dialogBody.add(new Padding( padding: padding, child: new DefaultTextStyle( - style: Theme.of(this).text.subhead, + style: Theme.of(context).text.subhead, child: content ) )); @@ -118,7 +117,7 @@ class Dialog extends Component { constraints: new BoxConstraints(minWidth: 280.0), child: new Material( level: 4, - color: _color, + color: _getColor(context), child: new IntrinsicWidth( child: new Block(dialogBody) ) @@ -133,15 +132,15 @@ class Dialog extends Component { const Duration _kTransitionDuration = const Duration(milliseconds: 150); -class DialogRoute extends RouteBase { +class DialogRoute extends Route { DialogRoute({ this.completer, this.builder }); final Completer completer; final RouteBuilder builder; Duration get transitionDuration => _kTransitionDuration; - bool get isOpaque => false; - Widget build(Key key, Navigator navigator, WatchableAnimationPerformance performance) { + bool get opaque => false; + Widget build(Key key, NavigatorState navigator) { return new FadeTransition( performance: performance, opacity: new AnimatedValue(0.0, end: 1.0, curve: easeOut), @@ -149,12 +148,13 @@ class DialogRoute extends RouteBase { ); } - void popState([dynamic result]) { + void didPop([dynamic result]) { completer.complete(result); + super.didPop(result); } } -Future showDialog(Navigator navigator, DialogBuilder builder) { +Future showDialog(NavigatorState navigator, DialogBuilder builder) { Completer completer = new Completer(); navigator.push(new DialogRoute( completer: completer, diff --git a/packages/flutter/lib/src/widgets/dismissable.dart b/packages/flutter/lib/src/widgets/dismissable.dart index e7a0edbe33..fe270ab390 100644 --- a/packages/flutter/lib/src/widgets/dismissable.dart +++ b/packages/flutter/lib/src/widgets/dismissable.dart @@ -31,7 +31,6 @@ typedef void ResizedCallback(); typedef void DismissedCallback(); class Dismissable extends StatefulComponent { - Dismissable({ Key key, this.child, @@ -45,14 +44,12 @@ class Dismissable extends StatefulComponent { DismissedCallback onDismissed; DismissDirection direction; - AnimationPerformance _fadePerformance; - AnimationPerformance _resizePerformance; - - Size _size; - double _dragExtent = 0.0; - bool _dragUnderway = false; + DismissableState createState() => new DismissableState(); +} +class DismissableState extends State { void initState() { + super.initState(); _fadePerformance = new AnimationPerformance(duration: _kCardDismissFadeout); _fadePerformance.addStatusListener((AnimationStatus status) { if (status == AnimationStatus.completed) @@ -60,18 +57,18 @@ class Dismissable extends StatefulComponent { }); } - void syncConstructorArguments(Dismissable source) { - child = source.child; - onResized = source.onResized; - onDismissed = source.onDismissed; - direction = source.direction; - } + AnimationPerformance _fadePerformance; + AnimationPerformance _resizePerformance; + + Size _size; + double _dragExtent = 0.0; + bool _dragUnderway = false; bool get _directionIsYAxis { return - direction == DismissDirection.vertical || - direction == DismissDirection.up || - direction == DismissDirection.down; + config.direction == DismissDirection.vertical || + config.direction == DismissDirection.up || + config.direction == DismissDirection.down; } void _handleFadeCompleted() { @@ -84,13 +81,13 @@ class Dismissable extends StatefulComponent { } void _maybeCallOnResized() { - if (onResized != null) - onResized(); + if (config.onResized != null) + config.onResized(); } void _maybeCallOnDismissed() { - if (onDismissed != null) - onDismissed(); + if (config.onDismissed != null) + config.onDismissed(); } void _startResizePerformance() { @@ -105,6 +102,11 @@ class Dismissable extends StatefulComponent { ..addListener(_handleResizeProgressChanged); _resizePerformance.play(); }); + // Our squash curve (ease) does not return v=0.0 for t=0.0, so we + // technically resize on the first frame. To make sure this doesn't confuse + // any other widgets (like MixedViewport, which checks for this kind of + // thing), we report a resize straight away. + _maybeCallOnResized(); } void _handleResizeProgressChanged() { @@ -129,7 +131,7 @@ class Dismissable extends StatefulComponent { return; double oldDragExtent = _dragExtent; - switch(direction) { + switch(config.direction) { case DismissDirection.horizontal: case DismissDirection.vertical: _dragExtent += delta; @@ -166,7 +168,7 @@ class Dismissable extends StatefulComponent { if (_directionIsYAxis) { if (vy.abs() - vx.abs() < _kMinFlingVelocityDelta) return false; - switch(direction) { + switch(config.direction) { case DismissDirection.vertical: return vy.abs() > _kMinFlingVelocity; case DismissDirection.up: @@ -177,7 +179,7 @@ class Dismissable extends StatefulComponent { } else { if (vx.abs() - vy.abs() < _kMinFlingVelocityDelta) return false; - switch(direction) { + switch(config.direction) { case DismissDirection.horizontal: return vx.abs() > _kMinFlingVelocity; case DismissDirection.left: @@ -221,8 +223,11 @@ class Dismissable extends StatefulComponent { return new Point(_dragExtent.sign * extent * _kDismissCardThreshold, 0.0); } - Widget build() { + Widget build(BuildContext context) { if (_resizePerformance != null) { + // make sure you remove this widget once it's been dismissed! + assert(_resizePerformance.status == AnimationStatus.forward); + AnimatedValue squashAxisExtent = new AnimatedValue( _directionIsYAxis ? _size.width : _size.height, end: 0.0, @@ -252,7 +257,7 @@ class Dismissable extends StatefulComponent { child: new SlideTransition( performance: _fadePerformance.view, position: new AnimatedValue(Point.origin, end: _activeCardDragEndPoint), - child: child + child: config.child ) ) ) diff --git a/packages/flutter/lib/src/widgets/drag_target.dart b/packages/flutter/lib/src/widgets/drag_target.dart index 245cabcc1f..fe600aeb8f 100644 --- a/packages/flutter/lib/src/widgets/drag_target.dart +++ b/packages/flutter/lib/src/widgets/drag_target.dart @@ -3,40 +3,111 @@ // found in the LICENSE file. import 'dart:collection'; +import 'dart:sky' as sky; import 'package:sky/rendering.dart'; import 'package:sky/src/widgets/basic.dart'; +import 'package:sky/src/widgets/binding.dart'; import 'package:sky/src/widgets/framework.dart'; +import 'package:sky/src/widgets/navigator.dart'; typedef bool DragTargetWillAccept(T data); typedef void DragTargetAccept(T data); -typedef Widget DragTargetBuilder(List candidateData, List rejectedData); +typedef Widget DragTargetBuilder(BuildContext context, List candidateData, List rejectedData); +typedef void DragFinishedNotification(); + +class Draggable extends StatefulComponent { + Draggable({ Key key, this.navigator, this.data, this.child, this.feedback }): super(key: key) { + assert(navigator != null); + } + + final NavigatorState navigator; + final dynamic data; + final Widget child; + final Widget feedback; + + DraggableState createState() => new DraggableState(); +} + +class DraggableState extends State { + DragRoute _route; + + void _startDrag(sky.PointerEvent event) { + if (_route != null) + return; // TODO(ianh): once we switch to using gestures, just hand the gesture to the route so it can do everything itself. then we can have multiple drags at the same time. + Point point = new Point(event.x, event.y); + RenderBox renderObject = context.findRenderObject(); + _route = new DragRoute( + data: config.data, + dragStartPoint: renderObject.globalToLocal(point), + feedback: config.feedback, + onDragFinished: () { + _route = null; + } + ); + _route.update(point); + config.navigator.push(_route); + } + + void _updateDrag(sky.PointerEvent event) { + if (_route != null) { + config.navigator.setState(() { + _route.update(new Point(event.x, event.y)); + }); + } + } + + void _cancelDrag(sky.PointerEvent event) { + if (_route != null) { + config.navigator.popRoute(_route, DragEndKind.canceled); + assert(_route == null); + } + } + + void _drop(sky.PointerEvent event) { + if (_route != null) { + _route.update(new Point(event.x, event.y)); + config.navigator.popRoute(_route, DragEndKind.dropped); + assert(_route == null); + } + } + + Widget build(BuildContext context) { + // TODO(abarth): We should be using a GestureDetector + return new Listener( + onPointerDown: _startDrag, + onPointerMove: _updateDrag, + onPointerCancel: _cancelDrag, + onPointerUp: _drop, + child: config.child + ); + } +} + class DragTarget extends StatefulComponent { - DragTarget({ + const DragTarget({ Key key, this.builder, this.onWillAccept, this.onAccept }) : super(key: key); - DragTargetBuilder builder; - DragTargetWillAccept onWillAccept; - DragTargetAccept onAccept; + final DragTargetBuilder builder; + final DragTargetWillAccept onWillAccept; + final DragTargetAccept onAccept; + DragTargetState createState() => new DragTargetState(); +} + +class DragTargetState extends State> { final List _candidateData = new List(); final List _rejectedData = new List(); - void syncConstructorArguments(DragTarget source) { - builder = source.builder; - onWillAccept = source.onWillAccept; - onAccept = source.onAccept; - } - bool didEnter(dynamic data) { assert(!_candidateData.contains(data)); assert(!_rejectedData.contains(data)); - if (data is T && (onWillAccept == null || onWillAccept(data))) { + if (data is T && (config.onWillAccept == null || config.onWillAccept(data))) { setState(() { _candidateData.add(data); }); @@ -59,39 +130,39 @@ class DragTarget extends StatefulComponent { setState(() { _candidateData.remove(data); }); - if (onAccept != null) - onAccept(data); + if (config.onAccept != null) + config.onAccept(data); } - Widget build() { - return builder(new UnmodifiableListView(_candidateData), - new UnmodifiableListView(_rejectedData)); + Widget build(BuildContext context) { + return new MetaData( + metaData: this, + child: config.builder(context, + new UnmodifiableListView(_candidateData), + new UnmodifiableListView(_rejectedData)) + ); } } -class DragController { - DragController(this.data); + +enum DragEndKind { dropped, canceled } + +class DragRoute extends Route { + DragRoute({ this.data, this.dragStartPoint: Point.origin, this.feedback, this.onDragFinished }); final dynamic data; + final Point dragStartPoint; + final Widget feedback; + final DragFinishedNotification onDragFinished; - DragTarget _activeTarget; + DragTargetState _activeTarget; bool _activeTargetWillAcceptDrop = false; - - DragTarget _getDragTarget(List path) { - for (HitTestEntry entry in path.reversed) { - if (entry.target is! RenderObject) - continue; - for (Widget widget in RenderObjectWrapper.getWidgetsForRenderObject(entry.target)) { - if (widget is DragTarget) - return widget; - } - } - return null; - } + Offset _lastOffset; void update(Point globalPosition) { - HitTestResult result = FlutterBinding.instance.hitTest(globalPosition); - DragTarget target = _getDragTarget(result.path); + _lastOffset = globalPosition - dragStartPoint; + HitTestResult result = WidgetFlutterBinding.instance.hitTest(globalPosition); + DragTargetState target = _getDragTarget(result.path); if (target == _activeTarget) return; if (_activeTarget != null) @@ -100,21 +171,47 @@ class DragController { _activeTargetWillAcceptDrop = _activeTarget != null && _activeTarget.didEnter(data); } - void cancel() { - if (_activeTarget != null) - _activeTarget.didLeave(data); - _activeTarget = null; - _activeTargetWillAcceptDrop = false; + DragTargetState _getDragTarget(List path) { + // TODO(abarth): Why do we reverse the path here? + for (HitTestEntry entry in path.reversed) { + if (entry.target is RenderMetaData) { + RenderMetaData renderMetaData = entry.target; + if (renderMetaData.metaData is DragTargetState) + return renderMetaData.metaData; + } + } + return null; } - void drop() { - if (_activeTarget == null) - return; - if (_activeTargetWillAcceptDrop) - _activeTarget.didDrop(data); - else - _activeTarget.didLeave(data); + void didPop([DragEndKind endKind]) { + if (_activeTarget != null) { + if (endKind == DragEndKind.dropped && _activeTargetWillAcceptDrop) + _activeTarget.didDrop(data); + else + _activeTarget.didLeave(data); + } _activeTarget = null; _activeTargetWillAcceptDrop = false; + if (onDragFinished != null) + onDragFinished(); + super.didPop(endKind); + } + + bool get ephemeral => true; + bool get modal => false; + + Duration get transitionDuration => const Duration(); + bool get opaque => false; + Widget build(Key key, NavigatorState navigator) { + return new Positioned( + left: _lastOffset.dx, + top: _lastOffset.dy, + child: new IgnorePointer( + child: new Opacity( + opacity: 0.5, + child: feedback + ) + ) + ); } } diff --git a/packages/flutter/lib/src/widgets/drawer.dart b/packages/flutter/lib/src/widgets/drawer.dart index 8801cd45f8..b6a567c9f3 100644 --- a/packages/flutter/lib/src/widgets/drawer.dart +++ b/packages/flutter/lib/src/widgets/drawer.dart @@ -6,7 +6,6 @@ import 'dart:async'; import 'package:sky/animation.dart'; import 'package:sky/material.dart'; -import 'package:sky/src/widgets/animated_container.dart'; import 'package:sky/src/widgets/framework.dart'; import 'package:sky/src/widgets/basic.dart'; import 'package:sky/src/widgets/gesture_detector.dart'; @@ -48,15 +47,18 @@ class Drawer extends StatefulComponent { this.navigator }) : super(key: key); - List children; - bool showing; - int level; - DrawerDismissedCallback onDismissed; - Navigator navigator; + final List children; + final bool showing; + final int level; + final DrawerDismissedCallback onDismissed; + final NavigatorState navigator; - AnimationPerformance _performance; + DrawerState createState() => new DrawerState(); +} +class DrawerState extends State { void initState() { + super.initState(); _performance = new AnimationPerformance(duration: _kBaseSettleDuration); _performance.addStatusListener((AnimationStatus status) { if (status == AnimationStatus.dismissed) @@ -66,30 +68,26 @@ class Drawer extends StatefulComponent { // this because we need a linear curve in order to track the user's finger // while dragging. _performance.attachedForce = kDefaultSpringForce; - if (navigator != null) { + if (config.navigator != null) { // TODO(ianh): This is crazy. We should convert drawer to use a pattern like openDialog(). // https://github.com/domokit/sky_engine/pull/1186 scheduleMicrotask(() { - navigator.pushState(this, (_) => _performance.reverse()); + config.navigator.pushState(this, (_) => _performance.reverse()); }); } _performance.play(_direction); } - Direction get _direction => showing ? Direction.forward : Direction.reverse; + AnimationPerformance _performance; - void syncConstructorArguments(Drawer source) { - children = source.children; - if (showing != source.showing) { - showing = source.showing; + Direction get _direction => config.showing ? Direction.forward : Direction.reverse; + + void didUpdateConfig(Drawer oldConfig) { + if (config.showing != oldConfig.showing) _performance.play(_direction); - } - level = source.level; - onDismissed = source.onDismissed; - navigator = source.navigator; } - Widget build() { + Widget build(BuildContext context) { var mask = new GestureDetector( child: new ColorTransition( performance: _performance.view, @@ -104,13 +102,14 @@ class Drawer extends StatefulComponent { Widget content = new SlideTransition( performance: _performance.view, position: new AnimatedValue(_kClosedPosition, end: _kOpenPosition), - child: new AnimatedContainer( - behavior: implicitlyAnimate(const Duration(milliseconds: 200)), + // TODO(abarth): Use AnimatedContainer + child: new Container( + // behavior: implicitlyAnimate(const Duration(milliseconds: 200)), decoration: new BoxDecoration( - backgroundColor: Theme.of(this).canvasColor, - boxShadow: shadows[level]), + backgroundColor: Theme.of(context).canvasColor, + boxShadow: shadows[config.level]), width: _kWidth, - child: new Block(children) + child: new Block(config.children) ) ); @@ -123,12 +122,12 @@ class Drawer extends StatefulComponent { } void _handleDismissed() { - if (navigator != null && - navigator.currentRoute is RouteState && - (navigator.currentRoute as RouteState).owner == this) // TODO(ianh): remove cast once analyzer is cleverer - navigator.pop(); - if (onDismissed != null) - onDismissed(); + if (config.navigator != null && + config.navigator.currentRoute is RouteState && + (config.navigator.currentRoute as RouteState).owner == this) // TODO(ianh): remove cast once analyzer is cleverer + config.navigator.pop(); + if (config.onDismissed != null) + config.onDismissed(); } bool get _isMostlyClosed => _performance.progress < 0.5; diff --git a/packages/flutter/lib/src/widgets/drawer_divider.dart b/packages/flutter/lib/src/widgets/drawer_divider.dart index a73fbdefe6..7841726153 100644 --- a/packages/flutter/lib/src/widgets/drawer_divider.dart +++ b/packages/flutter/lib/src/widgets/drawer_divider.dart @@ -6,16 +6,16 @@ import 'package:sky/src/widgets/basic.dart'; import 'package:sky/src/widgets/framework.dart'; import 'package:sky/src/widgets/theme.dart'; -class DrawerDivider extends Component { - DrawerDivider({ Key key }) : super(key: key); +class DrawerDivider extends StatelessComponent { + const DrawerDivider({ Key key }) : super(key: key); - Widget build() { + Widget build(BuildContext context) { return new Container( height: 0.0, decoration: new BoxDecoration( border: new Border( bottom: new BorderSide( - color: Theme.of(this).dividerColor + color: Theme.of(context).dividerColor ) ) ), diff --git a/packages/flutter/lib/src/widgets/drawer_header.dart b/packages/flutter/lib/src/widgets/drawer_header.dart index 8f0cd2b86d..be71d34d41 100644 --- a/packages/flutter/lib/src/widgets/drawer_header.dart +++ b/packages/flutter/lib/src/widgets/drawer_header.dart @@ -4,24 +4,22 @@ import 'package:sky/material.dart'; import 'package:sky/src/widgets/basic.dart'; -import 'package:sky/src/widgets/default_text_style.dart'; import 'package:sky/src/widgets/framework.dart'; import 'package:sky/src/widgets/theme.dart'; // TODO(jackson): This class should usually render the user's // preferred banner image rather than a solid background -class DrawerHeader extends Component { - - DrawerHeader({ Key key, this.child }) : super(key: key); +class DrawerHeader extends StatelessComponent { + const DrawerHeader({ Key key, this.child }) : super(key: key); final Widget child; - Widget build() { + Widget build(BuildContext context) { return new Container( height: kStatusBarHeight + kMaterialDrawerHeight, decoration: new BoxDecoration( - backgroundColor: Theme.of(this).cardColor, + backgroundColor: Theme.of(context).cardColor, border: const Border( bottom: const BorderSide( color: const Color(0xFFD1D9E1), @@ -36,12 +34,11 @@ class DrawerHeader extends Component { new Container( padding: const EdgeDims.symmetric(horizontal: 16.0), child: new DefaultTextStyle( - style: Theme.of(this).text.body2, + style: Theme.of(context).text.body2, child: child ) )] ) ); } - } diff --git a/packages/flutter/lib/src/widgets/drawer_item.dart b/packages/flutter/lib/src/widgets/drawer_item.dart index 8ad1a7d82b..cd670b5aef 100644 --- a/packages/flutter/lib/src/widgets/drawer_item.dart +++ b/packages/flutter/lib/src/widgets/drawer_item.dart @@ -4,39 +4,33 @@ import 'dart:sky' as sky; -import 'package:sky/painting.dart'; +import 'package:sky/gestures.dart'; import 'package:sky/material.dart'; +import 'package:sky/painting.dart'; import 'package:sky/src/widgets/basic.dart'; -import 'package:sky/src/widgets/button_base.dart'; -import 'package:sky/src/widgets/default_text_style.dart'; +import 'package:sky/src/widgets/button_state.dart'; import 'package:sky/src/widgets/framework.dart'; import 'package:sky/src/widgets/gesture_detector.dart'; import 'package:sky/src/widgets/icon.dart'; import 'package:sky/src/widgets/ink_well.dart'; import 'package:sky/src/widgets/theme.dart'; -typedef void OnPressedFunction(); - -class DrawerItem extends ButtonBase { - DrawerItem({ Key key, this.icon, this.child, this.onPressed, this.selected: false }) +class DrawerItem extends StatefulComponent { + const DrawerItem({ Key key, this.icon, this.child, this.onPressed, this.selected: false }) : super(key: key); - String icon; - Widget child; - OnPressedFunction onPressed; - bool selected; + final String icon; + final Widget child; + final GestureTapListener onPressed; + final bool selected; - void syncConstructorArguments(DrawerItem source) { - icon = source.icon; - child = source.child; - onPressed = source.onPressed; - selected = source.selected; - super.syncConstructorArguments(source); - } + DrawerItemState createState() => new DrawerItemState(); +} +class DrawerItemState extends ButtonState { TextStyle _getTextStyle(ThemeData themeData) { TextStyle result = themeData.text.body2; - if (selected) + if (config.selected) result = result.copyWith(color: themeData.primaryColor); return result; } @@ -44,27 +38,27 @@ class DrawerItem extends ButtonBase { Color _getBackgroundColor(ThemeData themeData) { if (highlight) return themeData.highlightColor; - if (selected) + if (config.selected) return themeData.selectedColor; return Colors.transparent; } sky.ColorFilter _getColorFilter(ThemeData themeData) { - if (selected) + if (config.selected) return new sky.ColorFilter.mode(themeData.primaryColor, sky.TransferMode.srcATop); return new sky.ColorFilter.mode(const Color(0x73000000), sky.TransferMode.dstIn); } - Widget buildContent() { - ThemeData themeData = Theme.of(this); + Widget buildContent(BuildContext context) { + ThemeData themeData = Theme.of(context); List flexChildren = new List(); - if (icon != null) { + if (config.icon != null) { flexChildren.add( new Padding( padding: const EdgeDims.symmetric(horizontal: 16.0), child: new Icon( - type: icon, + type: config.icon, size: 24, colorFilter: _getColorFilter(themeData)) ) @@ -76,14 +70,14 @@ class DrawerItem extends ButtonBase { padding: const EdgeDims.symmetric(horizontal: 16.0), child: new DefaultTextStyle( style: _getTextStyle(themeData), - child: child + child: config.child ) ) ) ); return new GestureDetector( - onTap: onPressed, + onTap: config.onPressed, child: new Container( height: 48.0, decoration: new BoxDecoration(backgroundColor: _getBackgroundColor(themeData)), diff --git a/packages/flutter/lib/src/widgets/editable_text.dart b/packages/flutter/lib/src/widgets/editable_text.dart index 8b3ff14e86..fee3793f93 100644 --- a/packages/flutter/lib/src/widgets/editable_text.dart +++ b/packages/flutter/lib/src/widgets/editable_text.dart @@ -3,17 +3,14 @@ // found in the LICENSE file. import 'dart:async'; -import 'dart:sky' as sky; import 'package:mojo_services/keyboard/keyboard.mojom.dart'; import 'package:sky/painting.dart'; +import 'package:sky/rendering.dart'; import 'package:sky/src/widgets/basic.dart'; import 'package:sky/src/widgets/framework.dart'; const _kCursorBlinkPeriod = 500; // milliseconds -const _kCursorGap = 1.0; -const _kCursorHeightOffset = 2.0; -const _kCursorWidth = 1.0; typedef void StringUpdated(); @@ -133,26 +130,27 @@ class EditableString implements KeyboardClient { } class EditableText extends StatefulComponent { - EditableText({ Key key, this.value, this.focused: false, this.style, - this.cursorColor}) : super(key: key); + this.cursorColor, + this.onContentSizeChanged, + this.scrollOffset + }) : super(key: key); - EditableString value; - bool focused; - TextStyle style; - Color cursorColor; + final EditableString value; + final bool focused; + final TextStyle style; + final Color cursorColor; + final SizeChangedCallback onContentSizeChanged; + final Offset scrollOffset; - void syncConstructorArguments(EditableText source) { - value = source.value; - focused = source.focused; - style = source.style; - cursorColor = source.cursorColor; - } + EditableTextState createState() => new EditableTextState(); +} +class EditableTextState extends State { Timer _cursorTimer; bool _showCursor = false; @@ -175,10 +173,10 @@ class EditableText extends StatefulComponent { new Duration(milliseconds: _kCursorBlinkPeriod), _cursorTick); } - void didUnmount() { + void dispose() { if (_cursorTimer != null) _stopCursorTimer(); - super.didUnmount(); + super.dispose(); } void _stopCursorTimer() { @@ -187,50 +185,85 @@ class EditableText extends StatefulComponent { _showCursor = false; } - void _paintCursor(sky.Canvas canvas, Size size) { - if (!_showCursor) - return; + Widget build(BuildContext context) { + assert(config.style != null); + assert(config.focused != null); + assert(config.cursorColor != null); - double cursorHeight = style.fontSize + 2.0 * _kCursorHeightOffset; - Rect cursorRect = new Rect.fromLTWH( - _kCursorGap, - (size.height - cursorHeight) / 2.0, - _kCursorWidth, - cursorHeight - ); - canvas.drawRect(cursorRect, new Paint()..color = cursorColor); - } - - Widget build() { - assert(style != null); - assert(focused != null); - assert(cursorColor != null); - - if (focused && _cursorTimer == null) + if (config.focused && _cursorTimer == null) _startCursorTimer(); - else if (!focused && _cursorTimer != null) + else if (!config.focused && _cursorTimer != null) _stopCursorTimer(); - Widget text; - if (value.composing.isValid) { - TextStyle composingStyle = style.merge(const TextStyle(decoration: underline)); - text = new StyledText(elements: [ - style, - value.textBefore(value.composing), - [composingStyle, value.textInside(value.composing)], - value.textAfter(value.composing) - ]); - } else { - // TODO(eseidel): This is the wrong height if empty! - text = new Text(value.text, style: style); - } - - Widget cursor = new Container( - height: style.fontSize * style.height, - width: _kCursorGap + _kCursorWidth, - child: new CustomPaint(callback: _paintCursor, token: _showCursor) + return new SizedBox( + width: double.INFINITY, + child: new _EditableTextWidget( + value: config.value, + style: config.style, + cursorColor: config.cursorColor, + showCursor: _showCursor, + onContentSizeChanged: config.onContentSizeChanged, + scrollOffset: config.scrollOffset + ) ); - - return new Row([text, cursor]); + } +} + +class _EditableTextWidget extends LeafRenderObjectWidget { + _EditableTextWidget({ + Key key, + this.value, + this.style, + this.cursorColor, + this.showCursor, + this.onContentSizeChanged, + this.scrollOffset + }) : super(key: key); + + final EditableString value; + final TextStyle style; + final Color cursorColor; + final bool showCursor; + final SizeChangedCallback onContentSizeChanged; + final Offset scrollOffset; + + RenderEditableParagraph createRenderObject() { + return new RenderEditableParagraph( + text: _buildTextSpan(), + cursorColor: cursorColor, + showCursor: showCursor, + onContentSizeChanged: onContentSizeChanged, + scrollOffset: scrollOffset + ); + } + + void updateRenderObject(RenderEditableParagraph renderObject, + _EditableTextWidget oldWidget) { + renderObject.text = _buildTextSpan(); + renderObject.cursorColor = cursorColor; + renderObject.showCursor = showCursor; + renderObject.onContentSizeChanged = onContentSizeChanged; + renderObject.scrollOffset = scrollOffset; + } + + // Construct a TextSpan that renders the EditableString using the chosen style. + TextSpan _buildTextSpan() { + if (value.composing.isValid) { + TextStyle composingStyle = style.merge( + const TextStyle(decoration: underline) + ); + + return new StyledTextSpan(style, [ + new PlainTextSpan(value.textBefore(value.composing)), + new StyledTextSpan(composingStyle, [ + new PlainTextSpan(value.textInside(value.composing)) + ]), + new PlainTextSpan(value.textAfter(value.composing)) + ]); + } + + return new StyledTextSpan(style, [ + new PlainTextSpan(value.text) + ]); } } diff --git a/packages/flutter/lib/src/widgets/flat_button.dart b/packages/flutter/lib/src/widgets/flat_button.dart index 037f58c62e..501799005c 100644 --- a/packages/flutter/lib/src/widgets/flat_button.dart +++ b/packages/flutter/lib/src/widgets/flat_button.dart @@ -3,6 +3,7 @@ // found in the LICENSE file. import 'package:sky/material.dart'; +import 'package:sky/src/widgets/basic.dart'; import 'package:sky/src/widgets/framework.dart'; import 'package:sky/src/widgets/material_button.dart'; import 'package:sky/src/widgets/theme.dart'; @@ -18,10 +19,14 @@ class FlatButton extends MaterialButton { enabled: enabled, onPressed: onPressed); - Color get color { - if (!enabled || !highlight) + FlatButtonState createState() => new FlatButtonState(); +} + +class FlatButtonState extends MaterialButtonState { + Color getColor(BuildContext context) { + if (!config.enabled || !highlight) return null; - switch (Theme.of(this).brightness) { + switch (Theme.of(context).brightness) { case ThemeBrightness.light: return Colors.grey[400]; case ThemeBrightness.dark: diff --git a/packages/flutter/lib/src/widgets/floating_action_button.dart b/packages/flutter/lib/src/widgets/floating_action_button.dart index ddc2eb0fed..b61993abe4 100644 --- a/packages/flutter/lib/src/widgets/floating_action_button.dart +++ b/packages/flutter/lib/src/widgets/floating_action_button.dart @@ -2,8 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'package:sky/gestures.dart'; import 'package:sky/src/widgets/basic.dart'; -import 'package:sky/src/widgets/button_base.dart'; +import 'package:sky/src/widgets/button_state.dart'; import 'package:sky/src/widgets/framework.dart'; import 'package:sky/src/widgets/gesture_detector.dart'; import 'package:sky/src/widgets/icon.dart'; @@ -15,31 +16,27 @@ import 'package:sky/src/widgets/theme.dart'; // http://www.google.com/design/spec/layout/metrics-keylines.html#metrics-keylines-keylines-spacing const double _kSize = 56.0; -class FloatingActionButton extends ButtonBase { - - FloatingActionButton({ +class FloatingActionButton extends StatefulComponent { + const FloatingActionButton({ Key key, this.child, this.backgroundColor, this.onPressed }) : super(key: key); - Widget child; - Color backgroundColor; - Function onPressed; + final Widget child; + final Color backgroundColor; + final GestureTapListener onPressed; - void syncConstructorArguments(FloatingActionButton source) { - super.syncConstructorArguments(source); - child = source.child; - backgroundColor = source.backgroundColor; - onPressed = source.onPressed; - } + FloatingActionButtonState createState() => new FloatingActionButtonState(); +} - Widget buildContent() { +class FloatingActionButtonState extends ButtonState { + Widget buildContent(BuildContext context) { IconThemeColor iconThemeColor = IconThemeColor.white; - Color materialColor = backgroundColor; + Color materialColor = config.backgroundColor; if (materialColor == null) { - ThemeData themeData = Theme.of(this); + ThemeData themeData = Theme.of(context); materialColor = themeData.accentColor; iconThemeColor = themeData.accentColorBrightness == ThemeBrightness.dark ? IconThemeColor.white : IconThemeColor.black; } @@ -50,7 +47,7 @@ class FloatingActionButton extends ButtonBase { level: highlight ? 3 : 2, child: new ClipOval( child: new GestureDetector( - onTap: onPressed, + onTap: config.onPressed, child: new Container( width: _kSize, height: _kSize, @@ -58,7 +55,7 @@ class FloatingActionButton extends ButtonBase { child: new Center( child: new IconTheme( data: new IconThemeData(color: iconThemeColor), - child: child + child: config.child ) ) ) @@ -67,5 +64,4 @@ class FloatingActionButton extends ButtonBase { ) ); } - } diff --git a/packages/flutter/lib/src/widgets/focus.dart b/packages/flutter/lib/src/widgets/focus.dart index 9aa339a182..478c77173e 100644 --- a/packages/flutter/lib/src/widgets/focus.dart +++ b/packages/flutter/lib/src/widgets/focus.dart @@ -12,10 +12,10 @@ typedef void FocusChanged(GlobalKey key); // is focused and whichever is the first scope to ask for focus will get it. final GlobalKey _noFocusedScope = new GlobalKey(); -class _FocusScope extends Inherited { - +class _FocusScope extends InheritedWidget { _FocusScope({ Key key, + this.focusState, this.scopeFocused: true, // are we focused in our ancestor scope? this.focusedScope, // which of our descendant scopes is focused, if any? this.focusedWidget, @@ -23,8 +23,9 @@ class _FocusScope extends Inherited { }) : super(key: key, child: child); final bool scopeFocused; + final FocusState focusState; - // These are mutable because we implicitly changed them when they're null in + // These are mutable because we implicitly change them when they're null in // certain cases, basically pretending retroactively that we were constructed // with the right keys. GlobalKey focusedScope; @@ -35,30 +36,27 @@ class _FocusScope extends Inherited { // our state is checked. void _setFocusedWidgetIfUnset(GlobalKey key) { - assert(parent is Focus); - (parent as Focus)._setFocusedWidgetIfUnset(key); // TODO(ianh): remove cast once analyzer is cleverer - focusedWidget = (parent as Focus)._focusedWidget; - focusedScope = (parent as Focus)._focusedScope == _noFocusedScope ? null : (parent as Focus)._focusedScope; + focusState._setFocusedWidgetIfUnset(key); + focusedWidget = focusState._focusedWidget; + focusedScope = focusState._focusedScope == _noFocusedScope ? null : focusState._focusedScope; } void _setFocusedScopeIfUnset(GlobalKey key) { - assert(parent is Focus); - (parent as Focus)._setFocusedScopeIfUnset(key); // TODO(ianh): remove cast once analyzer is cleverer - assert(focusedWidget == (parent as Focus)._focusedWidget); - focusedScope = (parent as Focus)._focusedScope == _noFocusedScope ? null : (parent as Focus)._focusedScope; + focusState._setFocusedScopeIfUnset(key); + assert(focusedWidget == focusState._focusedWidget); + focusedScope = focusState._focusedScope == _noFocusedScope ? null : focusState._focusedScope; } - bool syncShouldNotify(_FocusScope old) { - assert(parent is Focus); - if (scopeFocused != old.scopeFocused) + bool updateShouldNotify(_FocusScope oldWidget) { + if (scopeFocused != oldWidget.scopeFocused) return true; if (!scopeFocused) return false; - if (focusedScope != old.focusedScope) + if (focusedScope != oldWidget.focusedScope) return true; if (focusedScope != null) return false; - if (focusedWidget != old.focusedWidget) + if (focusedWidget != oldWidget.focusedWidget) return true; return false; } @@ -66,7 +64,6 @@ class _FocusScope extends Inherited { } class Focus extends StatefulComponent { - Focus({ GlobalKey key, // key is required if this is a nested Focus scope this.autofocus: false, @@ -75,15 +72,13 @@ class Focus extends StatefulComponent { assert(!autofocus || key != null); } - bool autofocus; - Widget child; - - void syncConstructorArguments(Focus source) { - autofocus = source.autofocus; - child = source.child; - } + final bool autofocus; + final Widget child; + FocusState createState() => new FocusState(); +} +class FocusState extends State { GlobalKey _focusedWidget; // when null, the first component to ask if it's focused will get the focus GlobalKey _currentlyRegisteredWidgetRemovalListenerKey; @@ -122,7 +117,6 @@ class Focus extends StatefulComponent { } } - GlobalKey _focusedScope; // when null, the first scope to ask if it's focused will get the focus GlobalKey _currentlyRegisteredScopeRemovalListenerKey; @@ -158,56 +152,53 @@ class Focus extends StatefulComponent { } } - - bool _didAutoFocus = false; - void didMount() { - if (autofocus && !_didAutoFocus) { - _didAutoFocus = true; - Focus._moveScopeTo(this); - } + void initState() { + super.initState(); + if (config.autofocus) + FocusState._moveScopeTo(context, config); _updateWidgetRemovalListener(_focusedWidget); _updateScopeRemovalListener(_focusedScope); - super.didMount(); } - void didUnmount() { + void dispose() { _updateWidgetRemovalListener(null); _updateScopeRemovalListener(null); - super.didUnmount(); + super.dispose(); } - Widget build() { + Widget build(BuildContext context) { return new _FocusScope( - scopeFocused: Focus._atScope(this), + focusState: this, + scopeFocused: FocusState._atScope(context, config), focusedScope: _focusedScope == _noFocusedScope ? null : _focusedScope, focusedWidget: _focusedWidget, - child: child + child: config.child ); } - static bool at(Component component, { bool autofocus: true }) { - assert(component != null); - assert(component.key is GlobalKey); - _FocusScope focusScope = component.inheritedOfType(_FocusScope); + static bool at(BuildContext context, Widget widget, { bool autofocus: true }) { + assert(widget != null); + assert(widget.key is GlobalKey); + _FocusScope focusScope = context.inheritedWidgetOfType(_FocusScope); if (focusScope != null) { if (autofocus) - focusScope._setFocusedWidgetIfUnset(component.key); + focusScope._setFocusedWidgetIfUnset(widget.key); return focusScope.scopeFocused && focusScope.focusedScope == null && - focusScope.focusedWidget == component.key; + focusScope.focusedWidget == widget.key; } return true; } - static bool _atScope(Focus component, { bool autofocus: true }) { - assert(component != null); - _FocusScope focusScope = component.inheritedOfType(_FocusScope); + static bool _atScope(BuildContext context, Widget widget, { bool autofocus: true }) { + assert(widget != null); + _FocusScope focusScope = context.inheritedWidgetOfType(_FocusScope); if (focusScope != null) { if (autofocus) - focusScope._setFocusedScopeIfUnset(component.key); - assert(component.key != null); + focusScope._setFocusedScopeIfUnset(widget.key); + assert(widget.key != null); return focusScope.scopeFocused && - focusScope.focusedScope == component.key; + focusScope.focusedScope == widget.key; } return true; } @@ -215,30 +206,19 @@ class Focus extends StatefulComponent { // Don't call moveTo() from your build() function, it's intended to be called // from event listeners, e.g. in response to a finger tap or tab key. - static void moveTo(Component component) { - assert(component != null); - assert(component.key is GlobalKey); - _FocusScope focusScope = component.inheritedOfType(_FocusScope); - if (focusScope != null) { - assert(focusScope.parent is Focus); - (focusScope.parent as Focus)._setFocusedWidget(component.key); // TODO(ianh): remove cast once analyzer is cleverer - } + static void moveTo(BuildContext context, Widget widget) { + assert(widget != null); + assert(widget.key is GlobalKey); + _FocusScope focusScope = context.inheritedWidgetOfType(_FocusScope); + if (focusScope != null) + focusScope.focusState._setFocusedWidget(widget.key); } - static void _moveScopeTo(Focus component) { + static void _moveScopeTo(BuildContext context, Focus component) { assert(component != null); assert(component.key != null); - _FocusScope focusScope = component.inheritedOfType(_FocusScope); - if (focusScope != null) { - assert(focusScope.parent is Focus); - (focusScope.parent as Focus)._setFocusedScope(component.key); // TODO(ianh): remove cast once analyzer is cleverer - } + _FocusScope focusScope = context.inheritedWidgetOfType(_FocusScope); + if (focusScope != null) + focusScope.focusState._setFocusedScope(component.key); } - - void debugAddDetails(List details) { - super.debugAddDetails(details); - details.add('focusedScope=$_focusedScope'); - details.add('focusedWidget=$_focusedWidget'); - } - } diff --git a/packages/flutter/lib/src/widgets/framework.dart b/packages/flutter/lib/src/widgets/framework.dart index 0fa3a3e631..4514639492 100644 --- a/packages/flutter/lib/src/widgets/framework.dart +++ b/packages/flutter/lib/src/widgets/framework.dart @@ -2,26 +2,28 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'dart:async'; import 'dart:collection'; -import 'dart:sky' as sky; -import 'package:sky/animation.dart'; -import 'package:sky/services.dart'; import 'package:sky/rendering.dart'; -export 'package:sky/rendering.dart' show BoxConstraints, BoxDecoration, Border, BorderSide, EdgeDims, Point, Offset, Size, Rect, Color, Paint, Path; - -final bool _shouldLogRenderDuration = false; // see also 'enableProfilingLoop' argument to runApp() - -typedef Widget Builder(); -typedef void WidgetTreeWalker(Widget widget); - +/// A Key is an identifier for [Widget]s and [Element]s. A new Widget will only +/// be used to reconfigure an existing Element if its Key is the same as its +/// original Widget's Key. +/// +/// Keys must be unique amongst the Elements with the same parent. abstract class Key { + /// Default constructor, used by subclasses. const Key.constructor(); // so that subclasses can call us, since the Key() factory constructor shadows the implicit constructor + + /// Construct a ValueKey with the given String. + /// This is the simplest way to create keys. factory Key(String value) => new ValueKey(value); } +/// A kind of [Key] that uses a value of a particular type to identify itself. +/// +/// For example, a ValueKey is equal to another ValueKey if +/// their values match. class ValueKey extends Key { const ValueKey(this.value) : super.constructor(); final T value; @@ -30,6 +32,10 @@ class ValueKey extends Key { int get hashCode => value.hashCode; } +/// A kind of [Key] that takes its identity from the object used as its value. +/// +/// Used to tie the identity of a Widget to the identity of an object used to +/// generate that Widget. class ObjectKey extends Key { const ObjectKey(this.value) : super.constructor(); final Object value; @@ -38,21 +44,24 @@ class ObjectKey extends Key { int get hashCode => identityHashCode(value); } -typedef void GlobalKeySyncListener(GlobalKey key, Widget widget); typedef void GlobalKeyRemoveListener(GlobalKey key); +/// A GlobalKey is one that must be unique across the entire application. It is +/// used by components that need to communicate with other components across the +/// application's element tree. abstract class GlobalKey extends Key { const GlobalKey.constructor() : super.constructor(); // so that subclasses can call us, since the Key() factory constructor shadows the implicit constructor + + /// Constructs a LabeledGlobalKey, which is a GlobalKey with a label used for debugging. + /// The label is not used for comparing the identity of the key. factory GlobalKey({ String label }) => new LabeledGlobalKey(label); // the label is purely for debugging purposes and is otherwise ignored - static final Map _registry = new Map(); + static final Map _registry = new Map(); static final Map _debugDuplicates = new Map(); - static final Map> _syncListeners = new Map>(); static final Map> _removeListeners = new Map>(); - static final Set _syncedKeys = new Set(); static final Set _removedKeys = new Set(); - void _register(Widget widget) { + void _register(Element element) { assert(() { if (_registry.containsKey(this)) { int oldCount = _debugDuplicates.putIfAbsent(this, () => 1); @@ -61,10 +70,10 @@ abstract class GlobalKey extends Key { } return true; }); - _registry[this] = widget; + _registry[this] = element; } - void _unregister(Widget widget) { + void _unregister(Element element) { assert(() { if (_registry.containsKey(this) && _debugDuplicates.containsKey(this)) { int oldCount = _debugDuplicates[this]; @@ -77,31 +86,19 @@ abstract class GlobalKey extends Key { } return true; }); - if (_registry[this] == widget) { + if (_registry[this] == element) { _registry.remove(this); _removedKeys.add(this); } } - void _didSync() { - _syncedKeys.add(this); - } - - static void registerSyncListener(GlobalKey key, GlobalKeySyncListener listener) { - assert(key != null); - Set listeners = - _syncListeners.putIfAbsent(key, () => new Set()); - bool added = listeners.add(listener); - assert(added); - } - - static void unregisterSyncListener(GlobalKey key, GlobalKeySyncListener listener) { - assert(key != null); - assert(_syncListeners.containsKey(key)); - bool removed = _syncListeners[key].remove(listener); - if (_syncListeners[key].isEmpty) - _syncListeners.remove(key); - assert(removed); + Element get currentElement => _registry[this]; + Widget get currentWidget => currentElement?.widget; + State get currentState { + Element element = currentElement; + if (element is StatefulComponentElement) + return element.state; + return null; } static void registerRemoveListener(GlobalKey key, GlobalKeyRemoveListener listener) { @@ -121,35 +118,20 @@ abstract class GlobalKey extends Key { assert(removed); } - static Widget getWidget(GlobalKey key) { - assert(key != null); - return _registry[key]; - } - - static void _notifyListeners() { - assert(!_inBuildDirtyComponents); - assert(!Widget._notifyingMountStatus); + static void checkForDuplicatesAndNotifyListeners() { assert(() { String message = ''; for (GlobalKey key in _debugDuplicates.keys) { - message += 'Duplicate GlobalKey found amongst mounted widgets: $key (${_debugDuplicates[key]} instances)\n'; + message += 'Duplicate GlobalKey found amongst mounted elements: $key (${_debugDuplicates[key]} instances)\n'; message += 'Most recently registered instance is:\n${_registry[key]}\n'; } if (!_debugDuplicates.isEmpty) throw message; return true; }); - if (_syncedKeys.isEmpty && _removedKeys.isEmpty) + if (_removedKeys.isEmpty) return; try { - for (GlobalKey key in _syncedKeys) { - Widget widget = _registry[key]; - if (widget != null && _syncListeners.containsKey(key)) { - Set localListeners = new Set.from(_syncListeners[key]); - for (GlobalKeySyncListener listener in localListeners) - listener(key, widget); - } - } for (GlobalKey key in _removedKeys) { if (!_registry.containsKey(key) && _removeListeners.containsKey(key)) { Set localListeners = new Set.from(_removeListeners[key]); @@ -159,19 +141,24 @@ abstract class GlobalKey extends Key { } } finally { _removedKeys.clear(); - _syncedKeys.clear(); } } } +/// Each LabeledGlobalKey instance is a unique key. +/// The optional label can be used for documentary purposes. It does not affect +/// the key's identity. class LabeledGlobalKey extends GlobalKey { - // the label is purely for documentary purposes and does not affect the key const LabeledGlobalKey(this._label) : super.constructor(); final String _label; String toString() => '[GlobalKey ${_label != null ? _label : hashCode}]'; } +/// A kind of [GlobalKey] that takes its identity from the object used as its value. +/// +/// Used to tie the identity of a Widget to the identity of an object used to +/// generate that Widget. class GlobalObjectKey extends GlobalKey { const GlobalObjectKey(this.value) : super.constructor(); final Object value; @@ -180,991 +167,843 @@ class GlobalObjectKey extends GlobalKey { int get hashCode => identityHashCode(value); } -/// A base class for elements of the widget tree + +/// A Widget object describes the configuration for an [Element]. +/// Widget subclasses should be immutable with const constructors. +/// Widgets form a tree that is then inflated into an Element tree. abstract class Widget { + const Widget({ this.key }); + final Key key; - Widget({ Key key }) : _key = key { - assert(_isConstructedDuringBuild()); - } + /// Inflates this configuration to a concrete instance. + Element createElement(); - // TODO(jackson): Remove this workaround for limitation of Dart mixins - Widget._withKey(Key key) : _key = key { - assert(_isConstructedDuringBuild()); - } + String toString() => '$runtimeType'; +} - // you should not build the UI tree ahead of time, build it only during build() - bool _isConstructedDuringBuild() => this is AbstractWidgetRoot || this is App || _inBuildDirtyComponents || _inLayoutCallbackBuilder > 0; +/// RenderObjectWidgets provide the configuration for [RenderObjectElement]s, +/// which wrap [RenderObject]s, which provide the actual rendering of the +/// application. +abstract class RenderObjectWidget extends Widget { + const RenderObjectWidget({ Key key }) : super(key: key); - Key _key; + /// RenderObjectWidgets always inflate to a RenderObjectElement subclass. + RenderObjectElement createElement(); - /// A semantic identifer for this widget + /// Constructs an instance of the RenderObject class that this + /// RenderObjectWidget represents, using the configuration described by this + /// RenderObjectWidget. + RenderObject createRenderObject(); + + /// Copies the configuration described by this RenderObjectWidget to the given + /// RenderObject, which must be of the same type as returned by this class' + /// createRenderObject(). + void updateRenderObject(RenderObject renderObject, RenderObjectWidget oldWidget) { } + + void didUnmountRenderObject(RenderObject renderObject) { } +} + +/// A superclass for RenderObjectWidgets that configure RenderObject subclasses +/// that have no children. +abstract class LeafRenderObjectWidget extends RenderObjectWidget { + const LeafRenderObjectWidget({ Key key }) : super(key: key); + + LeafRenderObjectElement createElement() => new LeafRenderObjectElement(this); +} + +/// A superclass for RenderObjectWidgets that configure RenderObject subclasses +/// that have a single child slot. (This superclass only provides the storage +/// for that child, it doesn't actually provide the updating logic.) +abstract class OneChildRenderObjectWidget extends RenderObjectWidget { + const OneChildRenderObjectWidget({ Key key, Widget this.child }) : super(key: key); + + final Widget child; + + OneChildRenderObjectElement createElement() => new OneChildRenderObjectElement(this); +} + +/// A superclass for RenderObjectWidgets that configure RenderObject subclasses +/// that have a single list of children. (This superclass only provides the +/// storage for that child list, it doesn't actually provide the updating +/// logic.) +abstract class MultiChildRenderObjectWidget extends RenderObjectWidget { + const MultiChildRenderObjectWidget({ Key key, List this.children }) + : super(key: key); + + final List children; + + MultiChildRenderObjectElement createElement() => new MultiChildRenderObjectElement(this); +} + +/// StatelessComponents describe a way to compose other Widgets to form reusable +/// parts, which doesn't depend on anything other than the configuration +/// information in the object itself. (For compositions that can change +/// dynamically, e.g. due to having an internal clock-driven state, or depending +/// on some system state, use [StatefulComponent].) +abstract class StatelessComponent extends Widget { + const StatelessComponent({ Key key }) : super(key: key); + + /// StatelessComponents always use StatelessComponentElements to represent + /// themselves in the Element tree. + StatelessComponentElement createElement() => new StatelessComponentElement(this); + + /// Returns another Widget out of which this StatelessComponent is built. + /// Typically that Widget will have been configured with further children, + /// such that really this function returns a tree of configuration. /// - /// Keys are used to find matches when synchronizing two widget trees, for - /// example after a [Component] rebuilds. Without keys, two widgets can match - /// if their runtimeType matches. With keys, the keys must match as well. - /// Assigning a key to a widget can improve performance by causing the - /// framework to sync widgets that share a lot of common structure and can - /// help match stateful components semantically rather than positionally. - Key get key => _key; + /// The given build context object contains information about the location in + /// the tree at which this component is being built. For example, the context + /// provides the set of inherited widgets for this location in the tree. + Widget build(BuildContext context); +} - Widget _parent; +/// StatefulComponents provide the configuration for +/// [StatefulComponentElement]s, which wrap [State]s, which hold mutable state +/// and can dynamically and spontaneously ask to be rebuilt. +abstract class StatefulComponent extends Widget { + const StatefulComponent({ Key key }) : super(key: key); - /// The parent of this widget in the widget tree. - Widget get parent => _parent; + /// StatefulComponents always use StatefulComponentElements to represent + /// themselves in the Element tree. + StatefulComponentElement createElement() => new StatefulComponentElement(this); - // The "generation" of a Widget is the frame in which it was last - // synced. We use this to tell if an instance of a Widget has moved - // to earlier in the tree so that when we come across where it used - // to be, we pretend it was never there. See syncChild(). - static int _currentGeneration = 1; - int _generation = 0; - bool get isFromOldGeneration => _generation < _currentGeneration; - void _markAsFromCurrentGeneration() { _generation = _currentGeneration; } - - bool get _hasState => false; - static bool _canSync(Widget a, Widget b) { - assert(a != null); - assert(b != null); - return (a == b) || - (a.runtimeType == b.runtimeType && - a.key == b.key && - (!a._hasState || !b._hasState)); - } - - bool _mounted = false; - bool _wasMounted = false; - bool get mounted => _mounted; - static bool _notifyingMountStatus = false; - static List _mountedChanged = new List(); - - /// Called during the synchronizing process to update the widget's parent. - void setParent(Widget newParent) { - assert(!_notifyingMountStatus); - if (_parent == newParent) - return; - _parent = newParent; - if (newParent == null) { - if (_mounted) { - _mounted = false; - _mountedChanged.add(this); - } - } else { - assert(newParent._mounted); - if (_parent._mounted != _mounted) { - _mounted = _parent._mounted; - _mountedChanged.add(this); - } - } - } - - /// Walks the immediate children of this widget. + /// Returns an instance of the state to which this StatefulComponent is + /// related, using this object as the configuration. Subclasses should + /// override this to return a new instance of the State class associated with + /// this StatefulComponent class, like this: /// - /// Override this if you have children and call walker on each child. - /// Note that you may be called before the child has had its parent - /// pointer set to point to you. Your walker, and any methods it - /// invokes on your descendants, should not rely on the ancestor - /// chain being correctly configured at this point. - void walkChildren(WidgetTreeWalker walker) { } + /// MyState createState() => new MyState(this); + State createState(); +} - /// If the object has a single child, return it. Override this if - /// you define a new child model with only one child. - Widget get singleChild => null; +enum _StateLifecycle { + created, + initialized, + ready, + defunct, +} - /// Detaches the single child of this object from this object, - /// without calling remove() on that child. - /// Only called when singleChild returns a non-null node. - /// Override this if you override singleChild to return non-null. - void takeChild() { - assert(singleChild != null); - throw '${runtimeType} does not define a "takeChild()" method'; +/// The logic and internal state for a StatefulComponent. +abstract class State { + /// The current configuration (an instance of the corresponding + /// StatefulComponent class). + T get config => _config; + T _config; + + /// This is used to verify that State objects move through life in an orderly fashion. + _StateLifecycle _debugLifecycleState = _StateLifecycle.created; + + /// Pointer to the owner Element object + StatefulComponentElement _element; + + /// The context in which this object will be built + BuildContext get context => _element; + + bool get mounted => _element != null; + + /// Called when this object is inserted into the tree. Override this function + /// to perform initialization that depends on the location at which this + /// object was inserted into the tree or on the widget configuration object. + /// + /// If you override this, make sure your method starts with a call to + /// super.initState(). + void initState() { + assert(_debugLifecycleState == _StateLifecycle.created); + assert(() { _debugLifecycleState = _StateLifecycle.initialized; return true; }); } - static void _notifyMountStatusChanged() { - try { - sky.tracing.begin('Widget._notifyMountStatusChanged'); - _notifyingMountStatus = true; - for (Widget node in _mountedChanged) { - if (node._wasMounted != node._mounted) { - if (node._mounted) - node.didMount(); - else - node.didUnmount(); - node._wasMounted = node._mounted; - } - } - _mountedChanged.clear(); - } finally { - _notifyingMountStatus = false; - sky.tracing.end('Widget._notifyMountStatusChanged'); - } - GlobalKey._notifyListeners(); + /// Called whenever the configuration changes. Override this method to update + /// additional state when the config field's value is changed. + void didUpdateConfig(T oldConfig) { } + + /// Whenever you need to change internal state for a State object, make the + /// change in a function that you pass to setState(), as in: + /// + /// setState(() { myState = newValue }); + /// + /// If you just change the state directly without calling setState(), then the + /// component will not be scheduled for rebuilding, meaning that its rendering + /// will not be updated. + void setState(void fn()) { + assert(_debugLifecycleState != _StateLifecycle.defunct); + fn(); + _element.markNeedsBuild(); } - /// Override this function to learn when this [Widget] enters the widget tree. - void didMount() { - if (key is GlobalKey) - (key as GlobalKey)._register(this); // TODO(ianh): remove cast when analyzer is cleverer + /// Called when this object is removed from the tree. Override this to clean + /// up any resources allocated by this object. + /// + /// If you override this, make sure to end your method with a call to + /// super.dispose(). + void dispose() { + assert(_debugLifecycleState == _StateLifecycle.ready); + assert(() { _debugLifecycleState = _StateLifecycle.defunct; return true; }); } - /// Override this function to learn when this [Widget] leaves the widget tree. - void didUnmount() { - if (key is GlobalKey) - (key as GlobalKey)._unregister(this); // TODO(ianh): remove cast when analyzer is cleverer - } - - RenderObject _renderObject; - - /// The underlying [RenderObject] associated with this [Widget]. - RenderObject get renderObject => _renderObject; - - // Subclasses which implements Nodes that become stateful may return true - // if the node has become stateful and should be retained. - // This is called immediately before _sync(). - // Component.retainStatefulNodeIfPossible() calls syncConstructorArguments(). - // This is only ever called on a node A with an argument B if _canSync(A, B) - // is true. It's ok if after calling retainStatefulNodeIfPossible(), the two - // nodes no longer return true from _canSync(). - bool retainStatefulNodeIfPossible(Widget newNode) => false; - - void _sync(Widget old, dynamic slot) { - // When this is called, old must be from an old generation. It's a violation - // of the _sync() contract to call _sync() with an old node that has already - // been synced this generation, as this means that that node is elsewhere in - // the tree by now. - // By the time we get here, though, syncChild() has already been called on - // our children (by the subclasses overriding this). This means 'old' may - // have been moved to somewhere else in the tree and might therefore already - // be from a new generation. - assert(isFromOldGeneration); - _markAsFromCurrentGeneration(); - if (old != null && old != this) - old._markAsFromCurrentGeneration(); - if (key is GlobalKey) - (key as GlobalKey)._didSync(); // TODO(ianh): Remove the cast once the analyzer is cleverer. - } - void updateSlot(dynamic newSlot); - // 'slot' is the identifier that the ancestor RenderObjectWrapper uses to know - // where to put this descendant. If you just defer to a child, then make sure - // to pass them the slot. - - Set _dependencies; - Inherited inheritedOfType(Type targetType) { - if (_dependencies == null) - _dependencies = new Set(); - _dependencies.add(targetType); - Widget ancestor = parent; - while (ancestor != null && ancestor.runtimeType != targetType) - ancestor = ancestor.parent; - return ancestor; - } - - void dependenciesChanged() { - // This is called if you've use inheritedOfType and the Inherited - // ancestor you were provided was changed. For a widget to use Inherited - // it needs an implementation of dependenciesChanged. If your widget extends - // Component or RenderObjectWrapper this is provided for you automatically. - // If you aren't able to extend one of those classes, you need to - // provide your own implementation of dependenciesChanged. - assert(false); - } - - void remove() { - walkChildren((Widget child) { - if (child.isFromOldGeneration || !isFromOldGeneration) { - assert(child.parent == this); - child.remove(); - } else { - // if it's from the current generation and we're not, it means it's been moved somewhere else in the tree already and isn't really our child anymore - assert(child.parent != this); - } - }); - _renderObject = null; - setParent(null); - } - - void detachRenderObject(); - - Widget _getCandidateSingleChildFrom(Widget oldChild) { - Widget candidate = oldChild.singleChild; - if (candidate != null && !candidate.isFromOldGeneration) - candidate = null; - assert(candidate == null || candidate.parent == oldChild); - return candidate; - } - - // Returns the child which should be retained as the child of this node. - Widget syncChild(Widget newNode, Widget oldNode, dynamic slot) { - String debugDetails; - assert(() { - // we save this information early because by the time the exception fires we might have changed everything around - debugDetails = ' old child: $oldNode\n new child: $newNode'; - return true; - }); - try { - - // At this point, oldNode might have been moved to a new part in the tree. - // If this has happened, it will already have been synced, in which case - // it will be from a new generation. Our contract with _sync() is that we - // will not pass an old child that has been moved to elsewhere in the - // tree, so it's important that we verify at each step here that we're not - // dealing with such a child. This is why this function keeps checking - // isFromOldGeneration on the candidate "old" children. - - if (newNode == oldNode) { - // If our child literally hasn't changed identity, short-circuit the - // work. That subtree hasn't changed. We still need to set the parent - // because _we_ might have changed identity, even if the child hasn't. - assert(newNode is! RenderObjectWrapper || - (newNode is RenderObjectWrapper && newNode._ancestor != null)); // if the child didn't change, it had better be configured - assert(newNode is! StatefulComponent || - (newNode is StatefulComponent && newNode._isStateInitialized)); // if the child didn't change, it had better be configured - // TODO(ianh): Simplify the two asserts above once the analyzer is cleverer - if (newNode != null) { - newNode.setParent(this); - newNode._markAsFromCurrentGeneration(); - } - return newNode; // Nothing to do. Subtrees must be identical. - } - - // if the old node isn't the same as the new node and has already been synced, then - // we must assume that it has been moved elsewhere in the tree and isn't really a - // match for the node we're trying to insert. - if (oldNode != null && !oldNode.isFromOldGeneration) - oldNode = null; - - if (newNode == null) { - // the child in this slot has gone away - // remove it if they old one is still here - if (oldNode != null) { - assert(oldNode != null); - assert(oldNode.isFromOldGeneration); - assert(oldNode.mounted); - oldNode.detachRenderObject(); - oldNode.remove(); - assert(!oldNode.mounted); - // we don't update the generation of oldNode, because there's - // still a chance it could be reused as-is later in the tree. - } - return null; - } - - if (oldNode != null) { - assert(newNode != null); - assert(newNode.isFromOldGeneration); - assert(oldNode.isFromOldGeneration); - if (!Widget._canSync(newNode, oldNode)) { - assert(oldNode.mounted); - // We want to handle the case where there is a removal of zero - // or more widgets. In this case, we should be able to sync - // ourselves with a Widget that is a descendant of the - // oldNode, skipping the nodes in between. Let's try that. - Widget deadNode = oldNode; - Widget candidate = _getCandidateSingleChildFrom(oldNode); - oldNode = null; - - while (candidate != null) { - if (Widget._canSync(newNode, candidate)) { - assert(candidate.parent != null); - assert(candidate.parent.singleChild == candidate); - if (candidate.renderObject != deadNode.renderObject) { - // TODO(ianh): Handle removal across RenderNode boundaries - } else { - candidate.parent.takeChild(); - oldNode = candidate; - } - break; - } - candidate = _getCandidateSingleChildFrom(candidate); - } - - // TODO(ianh): Handle insertion, too... - - if (oldNode == null) - deadNode.detachRenderObject(); - deadNode.remove(); - } - if (oldNode != null) { - assert(newNode.isFromOldGeneration); - assert(oldNode.isFromOldGeneration); - assert(Widget._canSync(newNode, oldNode)); - if (oldNode == newNode) { - newNode.setParent(this); - newNode._markAsFromCurrentGeneration(); - return newNode; - } else if (oldNode.retainStatefulNodeIfPossible(newNode)) { - assert(oldNode.mounted); - assert(!newNode.mounted); - oldNode.setParent(this); - oldNode._sync(newNode, slot); - assert(oldNode.renderObject is RenderObject); - return oldNode; - } else { - oldNode.setParent(null); - } - } - } - - assert(oldNode == null || (oldNode.mounted == false && oldNode.parent == null && newNode.mounted == false && oldNode.isFromOldGeneration && newNode.isFromOldGeneration)); - assert(oldNode != newNode); - newNode.setParent(this); - newNode._sync(oldNode, slot); - assert(newNode.renderObject is RenderObject); - return newNode; - - } catch (e, stack) { - _debugReportException('syncing children of $this\n$debugDetails', e, stack); - return null; - } - } - - // This function can be safely called when the layout is valid. - // For example Listener or SizeObserver callbacks can safely call - // globalToLocal(). - Point globalToLocal(Point point) { - assert(mounted); - assert(renderObject is RenderBox); - return (renderObject as RenderBox).globalToLocal(point); - } - - // See globalToLocal(). - Point localToGlobal(Point point) { - assert(mounted); - assert(renderObject is RenderBox); - return (renderObject as RenderBox).localToGlobal(point); - } + /// Returns another Widget out of which this StatefulComponent is built. + /// Typically that Widget will have been configured with further children, + /// such that really this function returns a tree of configuration. + /// + /// The given build context object contains information about the location in + /// the tree at which this component is being built. For example, the context + /// provides the set of inherited widgets for this location in the tree. + Widget build(BuildContext context); String toString() { - List details = []; - debugAddDetails(details); - String detailString = details.join('; '); - return '$runtimeType($detailString})'; + final List data = []; + debugFillDescription(data); + return '$runtimeType(${data.join("; ")})'; } - void debugAddDetails(List details) { - if (key != null) - details.add('$key'); - details.add('hashCode=$hashCode'); - details.add(mounted ? 'mounted' : 'not mounted'); - if (_generation != _currentGeneration) { - if (_generation == 0) { - details.add('never synced'); - } else { - int delta = _generation - _currentGeneration; - String sign = delta < 0 ? '' : '+'; - details.add('gen$sign$delta'); - } - } - } - String toStringDeep([String prefix = '', String startPrefix = '']) { - String childrenString = ''; - List children = new List(); - walkChildren(children.add); - if (children.length > 0) { - Widget lastChild = children.removeLast(); - String nextStartPrefix = prefix + ' +-'; - String nextPrefix = prefix + ' | '; - for (Widget child in children) - childrenString += child.toStringDeep(nextPrefix, _adjustPrefixWithParentCheck(child, nextStartPrefix)); - nextStartPrefix = prefix + ' \'-'; - nextPrefix = prefix + ' '; - childrenString += lastChild.toStringDeep(nextPrefix, _adjustPrefixWithParentCheck(lastChild, nextStartPrefix)); - } - return '$startPrefix$this\n$childrenString'; - } - String _adjustPrefixWithParentCheck(Widget child, String prefix) { - if (child.parent == this) - return prefix; - if (child.parent == null) - return '$prefix [[DISCONNECTED]] '; - return '$prefix [[PARENT IS ${child.parent}]] '; + + void debugFillDescription(List description) { + description.add('$hashCode'); + if (_debugLifecycleState != _StateLifecycle.ready) + description.add('$_debugLifecycleState'); + if (_config == null) + description.add('no config'); + if (_element == null) + description.add('not mounted'); } } +abstract class ProxyWidget extends StatelessComponent { + const ProxyWidget({ Key key, Widget this.child }) : super(key: key); -// Descendants of TagNode provide a way to tag RenderObjectWrapper and -// Component nodes with annotations, such as event listeners, -// stylistic information, etc. -abstract class TagNode extends Widget { - - TagNode({ Key key, Widget child }) - : child = child, super(key: key) { - assert(child != null); - } - - // TODO(jackson): Remove this workaround for limitation of Dart mixins - TagNode._withKey(Widget child, Key key) - : child = child, super._withKey(key); - - Widget child; - - void walkChildren(WidgetTreeWalker walker) { - if (child != null) - walker(child); - } - - Widget get singleChild => child; - - bool _debugChildTaken = false; - - void takeChild() { - assert(!_debugChildTaken); - assert(singleChild == child); - assert(child != null); - child = null; - _renderObject = null; - assert(() { _debugChildTaken = true; return true; }); - } - - void _sync(TagNode old, dynamic slot) { - assert(!_debugChildTaken); - child = syncChild(child, old?.child, slot); - if (child != null) { - assert(child.parent == this); - assert(child.renderObject != null); - _renderObject = child.renderObject; - assert(_renderObject == renderObject); // in case a subclass reintroduces it - } else { - _renderObject = null; - } - super._sync(old, slot); - } - - void updateSlot(dynamic newSlot) { - child.updateSlot(newSlot); - } - - void detachRenderObject() { - assert(!_debugChildTaken); - if (child != null) - child.detachRenderObject(); - } + final Widget child; + Widget build(BuildContext context) => child; } -abstract class ParentDataNode extends TagNode { - ParentDataNode({ Key key, Widget child }) +abstract class ParentDataWidget extends ProxyWidget { + ParentDataWidget({ Key key, Widget child }) : super(key: key, child: child); + ParentDataElement createElement() => new ParentDataElement(this); + /// Subclasses should override this function to ensure that they are placed /// inside widgets that expect them. /// - /// The given ancestor is the first non-component ancestor of this widget. - void debugValidateAncestor(Widget ancestor); + /// The given ancestor is the first RenderObjectWidget ancestor of this widget. + void debugValidateAncestor(RenderObjectWidget ancestor); + + void applyParentData(RenderObject renderObject); } -abstract class Inherited extends TagNode { +abstract class InheritedWidget extends ProxyWidget { + const InheritedWidget({ Key key, Widget child }) + : super(key: key, child: child); - Inherited({ Key key, Widget child }) : super._withKey(child, key); + InheritedElement createElement() => new InheritedElement(this); - void _sync(Widget old, dynamic slot) { - if (old != null) { - if (syncShouldNotify(old)) - notifyDescendants(); + bool updateShouldNotify(InheritedWidget oldWidget); +} + +bool _canUpdate(Widget oldWidget, Widget newWidget) { + return oldWidget.runtimeType == newWidget.runtimeType && + oldWidget.key == newWidget.key; +} + +enum _ElementLifecycle { + initial, + mounted, + defunct, +} + +typedef void ElementVisitor(Element element); + +abstract class BuildContext { + InheritedWidget inheritedWidgetOfType(Type targetType); + RenderObject findRenderObject(); + + void visitAncestorElements(bool visitor(Element element)); +} + +/// Elements are the instantiations of Widget configurations. +/// +/// Elements can, in principle, have children. Only subclasses of +/// RenderObjectElement are allowed to have more than one child. +abstract class Element implements BuildContext { + Element(T widget) : _widget = widget { + assert(widget != null); + } + + Element _parent; + + /// Information set by parent to define where this child fits in its parent's + /// child list. + /// + /// Subclasses of Element that only have one child should use null for + /// the slot for that child. + dynamic get slot => _slot; + dynamic _slot; + + /// An integer that is guaranteed to be greater than the parent's, if any. + /// The element at the root of the tree must have a depth greater than 0. + int get depth => _depth; + int _depth; + + /// The configuration for this element. + T get widget => _widget; + T _widget; + + RenderObject get renderObject { + RenderObject result; + void visit(Element element) { + assert(result == null); // this verifies that there's only one child + if (element is RenderObjectElement) + result = element.renderObject; + else + element.visitChildren(visit); } - super._sync(old, slot); + visit(this); + return result; } - void notifyDescendants() { - final Type ourRuntimeType = runtimeType; - void notifyChildren(Widget child) { - if (child._dependencies != null && - child._dependencies.contains(ourRuntimeType)) - child.dependenciesChanged(); - if (child.runtimeType != ourRuntimeType) - child.walkChildren(notifyChildren); + /// This is used to verify that Element objects move through life in an orderly fashion. + _ElementLifecycle _debugLifecycleState = _ElementLifecycle.initial; + + /// Calls the argument for each child. Must be overridden by subclasses that support having children. + void visitChildren(ElementVisitor visitor) { } + + /// Calls the argument for each descendant, depth-first pre-order. + void visitDescendants(ElementVisitor visitor) { + void visit(Element element) { + visitor(element); + element.visitChildren(visit); } - walkChildren(notifyChildren); + visitChildren(visit); } - bool syncShouldNotify(Inherited old); - -} - -class Listener extends TagNode { - Listener({ - Key key, - Widget child, - PointerEventListener this.onPointerDown, - PointerEventListener this.onPointerMove, - PointerEventListener this.onPointerUp, - PointerEventListener this.onPointerCancel - }) : super(key: key, child: child); - - final PointerEventListener onPointerDown; - final PointerEventListener onPointerMove; - final PointerEventListener onPointerUp; - final PointerEventListener onPointerCancel; - - void _handleEvent(sky.Event event) { - if (onPointerDown != null && event.type == 'pointerdown') - return onPointerDown(event); - if (onPointerMove != null && event.type == 'pointermove') - return onPointerMove(event); - if (onPointerUp != null && event.type == 'pointerup') - return onPointerUp(event); - if (onPointerCancel != null && event.type == 'pointercancel') - return onPointerCancel(event); - } -} - -abstract class Component extends Widget { - - Component({ Key key }) - : _order = _currentOrder + 1, - super._withKey(key); - - bool _debugIsBuilding = false; - static Queue _debugComponentBuildTree = new Queue(); - - bool _dirty = true; - Widget _child; - - void walkChildren(WidgetTreeWalker walker) { - if (_child != null) - walker(_child); + /// This method is the core of the system. + /// + /// It is called each time we are to add, update, or remove a child based on + /// an updated configuration. + /// + /// If the child is null, and the newWidget is not null, then we have a new + /// child for which we need to create an Element, configured with newWidget. + /// + /// If the newWidget is null, and the child is not null, then we need to + /// remove it because it no longer has a configuration. + /// + /// If neither are null, then we need to update the child's configuration to + /// be the new configuration given by newWidget. If newWidget can be given to + /// the existing child, then it is so given. Otherwise, the old child needs + /// to be disposed and a new child created for the new configuration. + /// + /// If both are null, then we don't have a child and won't have a child, so + /// we do nothing. + /// + /// The updateChild() method returns the new child, if it had to create one, + /// or the child that was passed in, if it just had to update the child, or + /// null, if it removed the child and did not replace it. + Element updateChild(Element child, Widget newWidget, dynamic newSlot) { + if (newWidget == null) { + if (child != null) + _detachChild(child); + return null; + } + if (child != null) { + if (child.widget == newWidget) { + if (child.slot != newSlot) + updateSlotForChild(child, newSlot); + return child; + } + if (_canUpdate(child.widget, newWidget)) { + if (child.slot != newSlot) + updateSlotForChild(child, newSlot); + child.update(newWidget); + assert(child.widget == newWidget); + return child; + } + _detachChild(child); + assert(child._parent == null); + } + child = newWidget.createElement(); + child.mount(this, newSlot); + assert(child._debugLifecycleState == _ElementLifecycle.mounted); + return child; } - Widget get singleChild => _child; - - bool _debugChildTaken = false; - - void takeChild() { - assert(!_debugChildTaken); - assert(singleChild == _child); - assert(_child != null); - _child = null; - _renderObject = null; - assert(() { _debugChildTaken = true; return true; }); + /// Called when an Element is given a new parent shortly after having been + /// created. Use this to initialize state that depends on having a parent. For + /// state that is independent of the position in the tree, it's better to just + /// initialize the Element in the constructor. + void mount(Element parent, dynamic newSlot) { + assert(_debugLifecycleState == _ElementLifecycle.initial); + assert(widget != null); + assert(_parent == null); + assert(parent == null || parent._debugLifecycleState == _ElementLifecycle.mounted); + assert(slot == null); + assert(depth == null); + _parent = parent; + _slot = newSlot; + _depth = _parent != null ? _parent.depth + 1 : 1; + if (widget.key is GlobalKey) { + final GlobalKey key = widget.key; + key._register(this); + } + assert(() { _debugLifecycleState = _ElementLifecycle.mounted; return true; }); } - void remove() { - assert(_debugChildTaken || (_child != null && _renderObject != null)); - super.remove(); - _child = null; - _renderObject = null; + /// Called when an Element receives a new configuration widget. + void update(T newWidget) { + assert(_debugLifecycleState == _ElementLifecycle.mounted); + assert(widget != null); + assert(newWidget != null); + assert(depth != null); + assert(_canUpdate(widget, newWidget)); + _widget = newWidget; } - void detachRenderObject() { - assert(!_debugChildTaken); - if (_child != null) - _child.detachRenderObject(); + /// Called by MultiChildRenderObjectElement, and other RenderObjectElement + /// subclasses that have multiple children, to update the slot of a particular + /// child when the child is moved in its child list. + void updateSlotForChild(Element child, dynamic newSlot) { + assert(_debugLifecycleState == _ElementLifecycle.mounted); + assert(child != null); + assert(child._parent == this); + void visit(Element element) { + element._updateSlot(newSlot); + if (element is! RenderObjectElement) + element.visitChildren(visit); + } + visit(child); + } + + void _updateSlot(dynamic newSlot) { + assert(_debugLifecycleState == _ElementLifecycle.mounted); + assert(widget != null); + assert(_parent != null); + assert(_parent._debugLifecycleState == _ElementLifecycle.mounted); + assert(depth != null); + _slot = newSlot; + } + + void _detachChild(Element child) { + assert(child != null); + assert(child._parent == this); + child._parent = null; + + bool haveDetachedRenderObject = false; + void detach(Element descendant) { + if (!haveDetachedRenderObject) { + descendant._slot = null; + if (descendant is RenderObjectElement) { + descendant.detachRenderObject(); + haveDetachedRenderObject = true; + } + } + descendant.unmount(); + assert(descendant._debugLifecycleState == _ElementLifecycle.defunct); + } + + detach(child); + child.visitDescendants(detach); + } + + /// Called when an Element is removed from the tree. + /// Currently, an Element removed from the tree never returns. + void unmount() { + assert(_debugLifecycleState == _ElementLifecycle.mounted); + assert(widget != null); + assert(depth != null); + if (widget.key is GlobalKey) { + final GlobalKey key = widget.key; + key._unregister(this); + } + assert(() { _debugLifecycleState = _ElementLifecycle.defunct; return true; }); + } + + Set _dependencies; + InheritedWidget inheritedWidgetOfType(Type targetType) { + if (_dependencies == null) + _dependencies = new Set(); + _dependencies.add(targetType); + Element ancestor = _parent; + while (ancestor != null && ancestor.widget.runtimeType != targetType) + ancestor = ancestor._parent; + return ancestor?.widget; + } + + RenderObject findRenderObject() => renderObject; + + void visitAncestorElements(bool visitor(Element element)) { + Element ancestor = _parent; + while (ancestor != null && visitor(ancestor)) + ancestor = ancestor._parent; } void dependenciesChanged() { - // called by Inherited.sync() - _scheduleBuild(); + assert(false); } - dynamic _slot; // cached slot from the last time we were synced - - void updateSlot(dynamic newSlot) { - _slot = newSlot; - if (_child != null) - _child.updateSlot(newSlot); + String toString() { + final List data = []; + debugFillDescription(data); + final String name = widget != null ? '$widget' : '[$runtimeType]'; + return '$name(${data.join("; ")})'; } - // order corresponds to _build_ order, not depth in the tree. - // All the Components built by a particular other Component will have the - // same order, regardless of whether one is subsequently inserted - // into another. The order is used to not tell a Component to - // rebuild if the Component that it built has itself been rebuilt. - final int _order; - static int _currentOrder = 0; + void debugFillDescription(List description) { + if (depth == null) + description.add('no depth'); + if (widget == null) + description.add('no widget'); + } - // There are three cases here: - // 1) Building for the first time: - // assert(_child == null && old == null) - // 2) Re-building (because a dirty flag got set): - // assert(_child != null && old == null) - // 3) Syncing against an old version (we are either new, or Stateful and pretending to be new) - // assert(_child == null && old != null) - void _sync(Component old, dynamic slot) { - assert(!_debugChildTaken); - assert(_child == null || old == null); - assert(old == null || old.isFromOldGeneration); + String toStringDeep([String prefixLineOne = '', String prefixOtherLines = '']) { + String result = '${prefixLineOne}$this\n'; + List children = []; + visitChildren((Element child) { + children.add(child); + }); + if (children.length > 0) { + Element last = children.removeLast(); + for (Element child in children) + result += '${child.toStringDeep("$prefixOtherLines \u251C", "$prefixOtherLines \u2502")}'; + result += '${last.toStringDeep("$prefixOtherLines \u2514", "$prefixOtherLines ")}'; + } + return result; + } +} - updateSlot(slot); +class ErrorWidget extends LeafRenderObjectWidget { + RenderBox createRenderObject() => new RenderErrorBox(); +} - Widget oldChild; - if (old == null) { - oldChild = _child; - _child = null; - } else { - oldChild = old._child; - old._child = null; - assert(_child == null); +typedef Widget WidgetBuilder(BuildContext context); +typedef void BuildScheduler(BuildableElement element); + +/// Base class for the instantiation of StatelessComponent and StatefulComponent +/// widgets. +abstract class BuildableElement extends Element { + BuildableElement(T widget) : super(widget); + + WidgetBuilder _builder; + Element _child; + + /// Returns true if the element has been marked as needing rebuilding. + bool get dirty => _dirty; + bool _dirty = true; + + // We to let component authors call setState from initState, didUpdateConfig, + // and build even when state is locked because its convenient and a no-op + // anyway. This flag ensures that this convenience is only allowed on the + // element currently undergoing initState, didUpdateConfig, or build. + bool _debugAllowIgnoredCallsToMarkNeedsBuild = false; + bool _debugSetAllowIgnoredCallsToMarkNeedsBuild(bool value) { + assert(_debugAllowIgnoredCallsToMarkNeedsBuild == !value); + _debugAllowIgnoredCallsToMarkNeedsBuild = value; + return true; + } + + void mount(Element parent, dynamic newSlot) { + super.mount(parent, newSlot); + assert(_child == null); + rebuild(); + assert(_child != null); + } + + /// Reinvokes the build() method of the StatelessComponent object (for + /// stateless components) or the State object (for stateful components) and + /// then updates the widget tree. + /// + /// Called automatically during mount() to generate the first build, by the + /// binding when scheduleBuild() has been called to mark this element dirty, + /// and by update() when the Widget has changed. + void rebuild() { + assert(_debugLifecycleState != _ElementLifecycle.initial); + if (!dirty) + return; + assert(_debugLifecycleState == _ElementLifecycle.mounted); + assert(_debugStateLocked); + assert(_debugSetAllowIgnoredCallsToMarkNeedsBuild(true)); + Widget built; + try { + built = _builder(this); + assert(built != null); + } catch (e, stack) { + _debugReportException('building ${_widget}', e, stack); + built = new ErrorWidget(); + } finally { + // We delay marking the element as clean until after calling _builder so + // that attempts to markNeedsBuild() during build() will be ignored. + _dirty = false; + assert(_debugSetAllowIgnoredCallsToMarkNeedsBuild(false)); } - assert(() { - _debugIsBuilding = true; - _debugComponentBuildTree.add(this); - return true; - }); - - int lastOrder = _currentOrder; - _currentOrder = _order; try { - _child = build(); + _child = updateChild(_child, built, slot); assert(_child != null); } catch (e, stack) { - _debugReportException('building $this', e, stack); + _debugReportException('building ${_widget}', e, stack); + built = new ErrorWidget(); + _child = updateChild(null, built, slot); } - _currentOrder = lastOrder; - assert(() { _debugChildTaken = false; return true; }); + } + + static BuildScheduler scheduleBuildFor; + + static int _debugStateLockLevel = 0; + static bool get _debugStateLocked => _debugStateLockLevel > 0; + + /// Establishes a scope in which component build functions can run. + /// + /// Inside a build scope, component build functions are allowed to run, but + /// State.setState() is forbidden. This mechanism prevents build functions + /// from transitively requiring other build functions to run, potentially + /// causing infinite loops. + /// + /// After unwinding the last build scope on the stack, the framework verifies + /// that each global key is used at most once and notifies listeners about + /// changes to global keys. + static void lockState(void callback()) { + _debugStateLockLevel += 1; try { - // even if build() failed (i.e. _child == null), we still call syncChild(), to remove the oldChild - _child = syncChild(_child, oldChild, slot); - assert(!_debugChildTaken); // we shouldn't be able to lose our child when we're syncing it! - assert(_child == null || _child.parent == this); - assert(_child == null || _child.renderObject != null); - } catch (e, stack) { - _debugReportException('syncing build output of $this\n old child: $oldChild\n new child: $_child', e, stack); - _child = null; + callback(); + } finally { + _debugStateLockLevel -= 1; + } + } + + /// Marks the element as dirty and adds it to the global list of widgets to + /// rebuild in the next frame. + /// + /// Since it is inefficient to build an element twice in one frame, + /// applications and components should be structured so as to only mark + /// components dirty during event handlers before the frame begins, not during + /// the build itself. + void markNeedsBuild() { + assert(_debugLifecycleState != _ElementLifecycle.defunct); + assert(!_debugStateLocked || (_debugAllowIgnoredCallsToMarkNeedsBuild && dirty)); + if (dirty) + return; + assert(_debugLifecycleState == _ElementLifecycle.mounted); + assert(!_debugStateLocked); + _dirty = true; + assert(scheduleBuildFor != null); + scheduleBuildFor(this); + } + + void visitChildren(ElementVisitor visitor) { + if (_child != null) + visitor(_child); + } + + void unmount() { + super.unmount(); + _dirty = false; // so that we don't get rebuilt even if we're already marked dirty + } + + void dependenciesChanged() { + markNeedsBuild(); + } + + void debugFillDescription(List description) { + super.debugFillDescription(description); + if (dirty) + description.add('dirty'); + } +} + +/// Instantiation of StatelessComponent widgets. +class StatelessComponentElement extends BuildableElement { + StatelessComponentElement(StatelessComponent widget) : super(widget) { + _builder = widget.build; + } + + void update(StatelessComponent newWidget) { + super.update(newWidget); + assert(widget == newWidget); + _builder = widget.build; + _dirty = true; + rebuild(); + } +} + +/// Instantiation of StatefulComponent widgets. +class StatefulComponentElement extends BuildableElement { + StatefulComponentElement(StatefulComponent widget) + : _state = widget.createState(), super(widget) { + assert(_state._element == null); + _state._element = this; + assert(_builder == null); + _builder = _state.build; + assert(_state._config == null); + _state._config = widget; + assert(_state._debugLifecycleState == _StateLifecycle.created); + try { + _debugSetAllowIgnoredCallsToMarkNeedsBuild(true); + _state.initState(); + } finally { + _debugSetAllowIgnoredCallsToMarkNeedsBuild(false); } assert(() { - if (_child == null) { - try { - _child = new ErrorWidget()..setParent(this).._sync(null, slot); - } catch (e) { - print('(application is now in an unstable state - ignore any subsequent exceptions)'); - } - } - _debugIsBuilding = false; - return identical(_debugComponentBuildTree.removeLast(), this); + if (_state._debugLifecycleState == _StateLifecycle.initialized) + return true; + print('${_state.runtimeType}.initState failed to call super.initState'); + return false; }); - - _dirty = false; - _renderObject = _child.renderObject; - assert(_renderObject == renderObject); // in case a subclass reintroduces it - super._sync(old, slot); + assert(() { _state._debugLifecycleState = _StateLifecycle.ready; return true; }); } - void _markAsFromCurrentGeneration() { - if (_dirty) - return; - super._markAsFromCurrentGeneration(); - } + State get state => _state; + State _state; - void _buildIfDirty() { - if (!_dirty || !_mounted) - return; - assert(isFromOldGeneration); - assert(renderObject != null); - _sync(null, _slot); - } - - void _scheduleBuild() { - assert(!_debugIsBuilding); - if (_dirty || !_mounted) - return; + void update(StatefulComponent newWidget) { + super.update(newWidget); + assert(widget == newWidget); + StatefulComponent oldConfig = _state._config; + // Notice that we mark ourselves as dirty before calling didUpdateConfig to + // let authors call setState from within didUpdateConfig without triggering + // asserts. _dirty = true; - _scheduleComponentForBuild(this); - } - - static void flushBuild() { - if (!_dirtyComponents.isEmpty) - _buildDirtyComponents(); - } - - Widget build(); - - void debugAddDetails(List details) { - super.debugAddDetails(details); - if (_dirty) - details.add('dirty'); - } -} - -abstract class StatefulComponent extends Component { - - StatefulComponent({ Key key }) : super(key: key); - - bool _isStateInitialized = false; - - bool get _hasState => _isStateInitialized; - - bool retainStatefulNodeIfPossible(StatefulComponent newNode) { - assert(newNode != null); - assert(!newNode._isStateInitialized); - assert(this != newNode); - assert(Widget._canSync(this, newNode)); - assert(_child != null); - - newNode._child = _child; - _child = null; - _dirty = true; - - return true; - } - - // because our retainStatefulNodeIfPossible() method returns true, - // when _sync is called, our 'old' is actually the new instance that - // we are to copy state from. - void _sync(StatefulComponent old, dynamic slot) { - if (old == null) { - if (!_isStateInitialized) { - assert(mounted); - assert(!_wasMounted); - initState(); - _isStateInitialized = true; - } - } else { - assert(_isStateInitialized); - assert(!old._isStateInitialized); - assert(old.isFromOldGeneration); - syncConstructorArguments(old); - } - super._sync(old, slot); - assert(_child != null); - } - - // Stateful components can override initState if they want - // to do non-trivial work to initialize state. This is - // always called before build(). - void initState() { } - - // This is called by _sync(). Derived classes should override this - // method to update `this` to account for the new values the parent - // passed to `source`. Make sure to call super.syncConstructorArguments(source) - // unless you are extending StatefulComponent directly. - // A given source can be used multiple times as a source. - // The source must not be mutated. - void syncConstructorArguments(Component source); - - // Calls function fn immediately and then schedules another build - // for this Component. - void setState(void fn()) { - assert(!_debugIsBuilding); - assert(_isStateInitialized); - fn(); - _scheduleBuild(); - } - - void debugAddDetails(List details) { - super.debugAddDetails(details); - details.add(_isStateInitialized ? 'stateful' : 'stateless'); - } -} - -Set _dirtyComponents = new Set(); -bool _buildScheduled = false; -bool _inBuildDirtyComponents = false; -int _inLayoutCallbackBuilder = 0; - -class LayoutCallbackBuilderHandle { bool _active = true; } -LayoutCallbackBuilderHandle enterLayoutCallbackBuilder() { - LayoutCallbackBuilderHandle result; - assert(() { - _inLayoutCallbackBuilder += 1; - result = new LayoutCallbackBuilderHandle(); - return true; - }); - return result; -} -void exitLayoutCallbackBuilder(LayoutCallbackBuilderHandle handle) { - assert(() { - assert(handle._active); - handle._active = false; - _inLayoutCallbackBuilder -= 1; - return true; - }); - _endSyncPhase(); -} - -List _debugFrameTimes = []; - -// TODO(ianh): Move this to Component -void _absorbDirtyComponents(List list) { - list.addAll(_dirtyComponents); - _dirtyComponents.clear(); - list.sort((Component a, Component b) => a._order - b._order); -} - -// TODO(ianh): Move this to Component -void _buildDirtyComponents() { - assert(!_dirtyComponents.isEmpty); - - Stopwatch sw; - if (_shouldLogRenderDuration) - sw = new Stopwatch()..start(); - - while (!_dirtyComponents.isEmpty) { - _inBuildDirtyComponents = true; + _state._config = widget; try { - sky.tracing.begin('Component.flushBuild'); - List sortedDirtyComponents = new List(); - _absorbDirtyComponents(sortedDirtyComponents); - int index = 0; - while (index < sortedDirtyComponents.length) { - Component component = sortedDirtyComponents[index]; - component._buildIfDirty(); - if (_dirtyComponents.length > 0) { - // the following assert verifies that we're not rebuilding anyone twice in one frame - assert(_dirtyComponents.every((Component component) => !sortedDirtyComponents.contains(component))); - _absorbDirtyComponents(sortedDirtyComponents); - index = 0; - } else { - index += 1; - } - } + _debugSetAllowIgnoredCallsToMarkNeedsBuild(true); + _state.didUpdateConfig(oldConfig); } finally { - _buildScheduled = false; - _inBuildDirtyComponents = false; - sky.tracing.end('Component.flushBuild'); + _debugSetAllowIgnoredCallsToMarkNeedsBuild(false); } - _endSyncPhase(); + rebuild(); } - if (_shouldLogRenderDuration) { - sw.stop(); - _debugFrameTimes.add(sw.elapsedMicroseconds); - if (_debugFrameTimes.length >= 1000) { - _debugFrameTimes.sort(); - const int i = 99; - print('Component.flushBuild: ${i+1}th fastest frame out of the last ${_debugFrameTimes.length}: ${_debugFrameTimes[i]} microseconds'); - _debugFrameTimes.clear(); - } + void unmount() { + super.unmount(); + _state.dispose(); + assert(() { + if (_state._debugLifecycleState == _StateLifecycle.defunct) + return true; + print('${_state.runtimeType}.dispose failed to call super.dispose'); + return false; + }); + assert(!dirty); // See BuildableElement.unmount for why this is important. + _state._element = null; + _state = null; } -} - -// TODO(ianh): Move this to Widget -void _endSyncPhase() { - try { - Widget._currentGeneration += 1; - Widget._notifyMountStatusChanged(); - } catch (e, stack) { - _debugReportException('sending post-sync notifications', e, stack); - return null; + void debugFillDescription(List description) { + super.debugFillDescription(description); + if (state != null) + description.add('state: $state'); } } -// TODO(ianh): Move this to Component -void _scheduleComponentForBuild(Component component) { - _dirtyComponents.add(component); - if (!_buildScheduled) { - _buildScheduled = true; - scheduler.ensureVisualUpdate(); +class ParentDataElement extends StatelessComponentElement { + ParentDataElement(ParentDataWidget widget) : super(widget); + + void mount(Element parent, dynamic slot) { + assert(() { + Element ancestor = parent; + while (ancestor is! RenderObjectElement) { + assert(ancestor != null); + assert(() { + 'You cannot nest parent data widgets inside one another.'; + return ancestor is! ParentDataElement; + }); + ancestor = ancestor._parent; + } + _widget.debugValidateAncestor(ancestor._widget); + return true; + }); + super.mount(parent, slot); + } + + void update(ParentDataWidget newWidget) { + ParentDataWidget oldWidget = widget; + super.update(newWidget); + assert(widget == newWidget); + if (widget != oldWidget) + _notifyDescendants(); + } + + void _notifyDescendants() { + void notifyChildren(Element child) { + if (child is RenderObjectElement) + child.updateParentData(widget); + else if (child is! ParentDataElement) + child.visitChildren(notifyChildren); + } + visitChildren(notifyChildren); } } -// RenderObjectWrappers correspond to a desired state of a -// RenderObject. They are fully immutable, except that a Widget which -// is a Component which lives within a RenderObjectWrapper's children -// list may be in-place replaced with the "old" instance if it has -// become stateful. -abstract class RenderObjectWrapper extends Widget { +class InheritedElement extends StatelessComponentElement { + InheritedElement(InheritedWidget widget) : super(widget); - RenderObjectWrapper({ Key key }) : super(key: key); + void update(StatelessComponent newWidget) { + InheritedWidget oldWidget = widget; + super.update(newWidget); + assert(widget == newWidget); + if (widget.updateShouldNotify(oldWidget)) + _notifyDescendants(); + } - RenderObject createNode(); - - static final Map _nodeMap = - new HashMap(); - static RenderObjectWrapper _getMounted(RenderObject node) => _nodeMap[node]; - - static Iterable getWidgetsForRenderObject(RenderObject renderObject) sync* { - Widget target = RenderObjectWrapper._getMounted(renderObject); - if (target == null) - return; - RenderObject targetRenderObject = target.renderObject; - while (target != null && target.renderObject == targetRenderObject) { - yield target; - target = target.parent; + void _notifyDescendants() { + final Type ourRuntimeType = runtimeType; + void notifyChildren(Element child) { + if (child._dependencies != null && + child._dependencies.contains(ourRuntimeType)) + child.dependenciesChanged(); + if (child.runtimeType != ourRuntimeType) + child.visitChildren(notifyChildren); } + visitChildren(notifyChildren); } +} - RenderObjectWrapper _ancestor; - void insertChildRenderObject(RenderObjectWrapper child, dynamic slot); - void detachChildRenderObject(RenderObjectWrapper child); +/// Base class for instantiations of RenderObjectWidget subclasses +abstract class RenderObjectElement extends Element { + RenderObjectElement(T widget) + : _renderObject = widget.createRenderObject(), super(widget); - bool get _hasState => _renderObject != null; + /// The underlying [RenderObject] for this element + RenderObject get renderObject => _renderObject; + final RenderObject _renderObject; - void retainStatefulRenderObjectWrapper(RenderObjectWrapper newNode) { - newNode._renderObject = _renderObject; - newNode._ancestor = _ancestor; - } + RenderObjectElement _ancestorRenderObjectElement; - RenderObjectWrapper findAncestorRenderObjectWrapper() { - Widget ancestor = parent; - while (ancestor != null && ancestor is! RenderObjectWrapper) - ancestor = ancestor.parent; + RenderObjectElement _findAncestorRenderObjectElement() { + Element ancestor = _parent; + while (ancestor != null && ancestor is! RenderObjectElement) + ancestor = ancestor._parent; return ancestor; } - void _sync(RenderObjectWrapper old, dynamic slot) { - // TODO(abarth): We should split RenderObjectWrapper into two pieces so that - // RenderViewObject doesn't need to inherit all this code it - // doesn't need. - assert(parent != null || this is RenderViewWrapper); - assert(old == null || old.isFromOldGeneration); - if (old == null) { - _renderObject = createNode(); - assert(_renderObject != null); - _ancestor = findAncestorRenderObjectWrapper(); - if (_ancestor != null) - _ancestor.insertChildRenderObject(this, slot); - } else { - _renderObject = old.renderObject; - _ancestor = old._ancestor; - assert(_renderObject != null); + ParentDataElement _findAncestorParentDataElement() { + Element ancestor = _parent; + while (ancestor != null && ancestor is! RenderObjectElement) { + if (ancestor is ParentDataElement) + return ancestor; + ancestor = ancestor._parent; } - assert(() { - _renderObject.debugExceptionContext = Component._debugComponentBuildTree.fold(' Widget build stack:', (String result, Component component) => result + '\n $component'); - return true; - }); - assert(_renderObject == renderObject); // in case a subclass reintroduces it - assert(renderObject != null); - assert(mounted); - _nodeMap[renderObject] = this; - syncRenderObject(old); - super._sync(old, slot); + return null; } - void updateSlot(dynamic newSlot) { - // We never use the slot except during sync(), in which - // case our parent is handing it to us anyway. - // We don't need to propagate this to our children, since - // we give them their own slots for them to fit into us. + void mount(Element parent, dynamic newSlot) { + super.mount(parent, newSlot); + assert(_ancestorRenderObjectElement == null); + _ancestorRenderObjectElement = _findAncestorRenderObjectElement(); + _ancestorRenderObjectElement?.insertChildRenderObject(renderObject, newSlot); + ParentDataElement parentDataElement = _findAncestorParentDataElement(); + if (parentDataElement != null) + updateParentData(parentDataElement.widget); } - /// Override this function if your RenderObjectWrapper uses a [ParentDataNode] - /// to program parent data into children. - void updateParentData(RenderObject child, ParentDataNode node) { } - - void syncRenderObject(RenderObjectWrapper old) { - assert(old == null || old.renderObject == renderObject); - ParentDataNode parentDataNode = null; - for (Widget current = parent; current != null; current = current.parent) { - assert(() { - if (current is ParentDataNode) { - Widget ancestor = current.parent; - while (ancestor is Component) - ancestor = ancestor.parent; - // ancestor might be null in two cases: - // - asking for the ancestor of a Widget that has no non-Component - // ancestors between itself and its AbstractWidgetRoot ancestor - // - if the node is just being synced to get its intrinsic - // dimensions, as e.g. MixedViewport does. - if (ancestor != null) - current.debugValidateAncestor(ancestor); - } - return true; - }); - if (current is ParentDataNode) { - assert(parentDataNode == null); - parentDataNode = current; - } else if (current is RenderObjectWrapper) { - current.updateParentData(renderObject, parentDataNode); - break; - } - } + void update(T newWidget) { + T oldWidget = widget; + super.update(newWidget); + assert(widget == newWidget); + widget.updateRenderObject(renderObject, oldWidget); } - // for use by subclasses that manage their children using lists - void syncChildren(List newChildren, List oldChildren) { - assert(newChildren != null); + /// Utility function for subclasses that have one or more lists of children. + /// Attempts to update the given old children list using the given new + /// widgets, removing obsolete elements and introducing new ones as necessary, + /// and then returns the new child list. + List updateChildren(List oldChildren, List newWidgets) { assert(oldChildren != null); - assert(!identical(newChildren, oldChildren)); + assert(newWidgets != null); // This attempts to diff the new child list (this.children) with // the old child list (old.children), and update our renderObject @@ -1201,41 +1040,33 @@ abstract class RenderObjectWrapper extends Widget { assert(renderObject is ContainerRenderObjectMixin); int childrenTop = 0; - int newChildrenBottom = newChildren.length-1; - int oldChildrenBottom = oldChildren.length-1; + int newChildrenBottom = newWidgets.length - 1; + int oldChildrenBottom = oldChildren.length - 1; // top of the lists while ((childrenTop <= oldChildrenBottom) && (childrenTop <= newChildrenBottom)) { - Widget oldChild = oldChildren[childrenTop]; - Widget newChild = newChildren[childrenTop]; - if (oldChild != newChild && !oldChild.isFromOldGeneration) { - // even if the two nodes could in theory be synced, they can't really because - // it would seem that the old node has already been synced elsewhere in the tree. - break; - } - assert(oldChild.mounted); - if (!Widget._canSync(oldChild, newChild)) + Element oldChild = oldChildren[childrenTop]; + Widget newWidget = newWidgets[childrenTop]; + assert(oldChild._debugLifecycleState == _ElementLifecycle.mounted); + if (!_canUpdate(oldChild.widget, newWidget)) break; childrenTop += 1; } - Widget nextSibling; + List newChildren = oldChildren.length == newWidgets.length ? + oldChildren : new List(newWidgets.length); + + Element nextSibling; // bottom of the lists while ((childrenTop <= oldChildrenBottom) && (childrenTop <= newChildrenBottom)) { - Widget oldChild = oldChildren[oldChildrenBottom]; - Widget newChild = newChildren[newChildrenBottom]; - if (oldChild != newChild && !oldChild.isFromOldGeneration) { - // even if the two nodes could in theory be synced, they can't really because - // it would seem that the old node has already been synced elsewhere in the tree. + Element oldChild = oldChildren[oldChildrenBottom]; + Widget newWidget = newWidgets[newChildrenBottom]; + assert(oldChild._debugLifecycleState == _ElementLifecycle.mounted); + if (!_canUpdate(oldChild.widget, newWidget)) break; - } - assert(oldChild.mounted); - if (!Widget._canSync(oldChild, newChild)) - break; - assert(oldChild == newChild || !newChild.mounted); - newChild = syncChild(newChild, oldChild, nextSibling); - assert(newChild.mounted); + Element newChild = updateChild(oldChild, newWidget, nextSibling); + assert(newChild._debugLifecycleState == _ElementLifecycle.mounted); newChildren[newChildrenBottom] = newChild; nextSibling = newChild; oldChildrenBottom -= 1; @@ -1244,395 +1075,239 @@ abstract class RenderObjectWrapper extends Widget { // middle of the lists - old list bool haveOldNodes = childrenTop <= oldChildrenBottom; - Map oldKeyedChildren; + Map oldKeyedChildren; if (haveOldNodes) { - oldKeyedChildren = new Map(); + oldKeyedChildren = new Map(); while (childrenTop <= oldChildrenBottom) { - Widget oldChild = oldChildren[oldChildrenBottom]; - assert(oldChild.mounted); - if (oldChild.key != null) { - oldKeyedChildren[oldChild.key] = oldChild; - } else { - // Let's give up trying to sync this node with a new node. If this - // child is from the old generation, then we'll remove it from our - // child list. It it's not, then that means it's already been synced - // elsewhere and we should leave it alone. - if (oldChild.isFromOldGeneration) - syncChild(null, oldChild, null); - } + Element oldChild = oldChildren[oldChildrenBottom]; + assert(oldChild._debugLifecycleState == _ElementLifecycle.mounted); + if (oldChild.widget.key != null) + oldKeyedChildren[oldChild.widget.key] = oldChild; + else + _detachChild(oldChild); oldChildrenBottom -= 1; } } // middle of the lists - new list while (childrenTop <= newChildrenBottom) { - Widget oldChild; - Widget newChild = newChildren[newChildrenBottom]; + Element oldChild; + Widget newWidget = newWidgets[newChildrenBottom]; if (haveOldNodes) { - Key key = newChild.key; + Key key = newWidget.key; if (key != null) { - oldChild = oldKeyedChildren[newChild.key]; + oldChild = oldKeyedChildren[newWidget.key]; if (oldChild != null) { - if ((Widget._canSync(oldChild, newChild)) && - (oldChild == newChild || oldChild.isFromOldGeneration)) { + if (_canUpdate(oldChild.widget, newWidget)) { // we found a match! // remove it from oldKeyedChildren so we don't unsync it later oldKeyedChildren.remove(key); } else { - // Either it wasn't a match, or it's already been synced elsewhere in the tree. - // In either case, let's pretend we didn't see it for now. + // Not a match, let's pretend we didn't see it for now. oldChild = null; } } } } - assert(oldChild == null || Widget._canSync(oldChild, newChild)); - assert(oldChild == newChild || !newChild.mounted); - newChild = syncChild(newChild, oldChild, nextSibling); - assert(newChild.mounted); - assert(oldChild == newChild || oldChild == null || !oldChild.mounted); + assert(oldChild == null || _canUpdate(oldChild.widget, newWidget)); + Element newChild = updateChild(oldChild, newWidget, nextSibling); + assert(newChild._debugLifecycleState == _ElementLifecycle.mounted); + assert(oldChild == newChild || oldChild == null || oldChild._debugLifecycleState != _ElementLifecycle.mounted); newChildren[newChildrenBottom] = newChild; nextSibling = newChild; newChildrenBottom -= 1; } assert(oldChildrenBottom == newChildrenBottom); - assert(childrenTop == newChildrenBottom+1); + assert(childrenTop == newChildrenBottom + 1); // now sync the top of the list while (childrenTop > 0) { childrenTop -= 1; - Widget oldChild = oldChildren[childrenTop]; - assert(oldChild.mounted); - Widget newChild = newChildren[childrenTop]; - assert(Widget._canSync(oldChild, newChild)); - newChild = syncChild(newChild, oldChild, nextSibling); - assert(newChild.mounted); - assert(oldChild == newChild || oldChild == null || !oldChild.mounted); + Element oldChild = oldChildren[childrenTop]; + assert(oldChild._debugLifecycleState == _ElementLifecycle.mounted); + Widget newWidget = newWidgets[childrenTop]; + assert(_canUpdate(oldChild.widget, newWidget)); + Element newChild = updateChild(oldChild, newWidget, nextSibling); + assert(newChild._debugLifecycleState == _ElementLifecycle.mounted); + assert(oldChild == newChild || oldChild == null || oldChild._debugLifecycleState != _ElementLifecycle.mounted); newChildren[childrenTop] = newChild; nextSibling = newChild; } // clean up any of the remaining middle nodes from the old list if (haveOldNodes && !oldKeyedChildren.isEmpty) { - for (Widget oldChild in oldKeyedChildren.values) - if (oldChild.isFromOldGeneration) - syncChild(null, oldChild, null); + for (Element oldChild in oldKeyedChildren.values) + _detachChild(oldChild); } assert(renderObject == this.renderObject); // TODO(ianh): Remove this once the analyzer is cleverer + return newChildren; } - void dependenciesChanged() { - // called by Inherited.sync() - syncRenderObject(this); + void unmount() { + super.unmount(); + assert(!renderObject.attached); + widget.didUnmountRenderObject(renderObject); } - void remove() { - assert(renderObject != null); - _nodeMap.remove(renderObject); - super.remove(); + void updateParentData(ParentDataWidget parentData) { + parentData.applyParentData(renderObject); + } + + void _updateSlot(dynamic newSlot) { + assert(slot != newSlot); + super._updateSlot(newSlot); + assert(slot == newSlot); + _ancestorRenderObjectElement.moveChildRenderObject(renderObject, slot); } void detachRenderObject() { - assert(renderObject != null); - assert(_ancestor != null); - assert(_ancestor.renderObject != null); - _ancestor.detachChildRenderObject(this); + if (_ancestorRenderObjectElement != null) { + _ancestorRenderObjectElement.removeChildRenderObject(renderObject); + _ancestorRenderObjectElement = null; + } } + void insertChildRenderObject(RenderObject child, dynamic slot); + void moveChildRenderObject(RenderObject child, dynamic slot); + void removeChildRenderObject(RenderObject child); + + void debugFillDescription(List description) { + super.debugFillDescription(description); + if (renderObject != null) + description.add('renderObject: $renderObject'); + } } -abstract class LeafRenderObjectWrapper extends RenderObjectWrapper { +/// Instantiation of RenderObjectWidgets that have no children +class LeafRenderObjectElement extends RenderObjectElement { + LeafRenderObjectElement(T widget): super(widget); - LeafRenderObjectWrapper({ Key key }) : super(key: key); - - void insertChildRenderObject(RenderObjectWrapper child, dynamic slot) { + void insertChildRenderObject(RenderObject child, dynamic slot) { assert(false); } - void detachChildRenderObject(RenderObjectWrapper child) { + void moveChildRenderObject(RenderObject child, dynamic slot) { assert(false); } + void removeChildRenderObject(RenderObject child) { + assert(false); + } } -abstract class OneChildRenderObjectWrapper extends RenderObjectWrapper { +/// Instantiation of RenderObjectWidgets that have up to one child +class OneChildRenderObjectElement extends RenderObjectElement { + OneChildRenderObjectElement(T widget) : super(widget); - OneChildRenderObjectWrapper({ Key key, Widget child }) - : _child = child, super(key: key); + Element _child; - Widget _child; - Widget get child => _child; - - void walkChildren(WidgetTreeWalker walker) { - if (child != null) - walker(child); + void visitChildren(ElementVisitor visitor) { + if (_child != null) + visitor(_child); } - Widget get singleChild => _child; - - bool _debugChildTaken = false; - - void takeChild() { - assert(!_debugChildTaken); - assert(singleChild == child); - assert(child != null); - _child = null; - assert(() { _debugChildTaken = true; return true; }); + void mount(Element parent, dynamic newSlot) { + super.mount(parent, newSlot); + _child = updateChild(_child, widget.child, null); } - void syncRenderObject(RenderObjectWrapper old) { - assert(!_debugChildTaken); - super.syncRenderObject(old); - Widget oldChild = (old as OneChildRenderObjectWrapper)?.child; - Widget newChild = child; - _child = syncChild(newChild, oldChild, null); - assert((newChild == null && child == null) || (newChild != null && child.parent == this)); - assert(oldChild == null || child == oldChild || oldChild.parent == null); + void update(T newWidget) { + super.update(newWidget); + assert(widget == newWidget); + _child = updateChild(_child, widget.child, null); } - void insertChildRenderObject(RenderObjectWrapper child, dynamic slot) { + void insertChildRenderObject(RenderObject child, dynamic slot) { final renderObject = this.renderObject; // TODO(ianh): Remove this once the analyzer is cleverer assert(renderObject is RenderObjectWithChildMixin); assert(slot == null); - renderObject.child = child.renderObject; + renderObject.child = child; assert(renderObject == this.renderObject); // TODO(ianh): Remove this once the analyzer is cleverer } - void detachChildRenderObject(RenderObjectWrapper child) { + void moveChildRenderObject(RenderObject child, dynamic slot) { + assert(false); + } + + void removeChildRenderObject(RenderObject child) { final renderObject = this.renderObject; // TODO(ianh): Remove this once the analyzer is cleverer assert(renderObject is RenderObjectWithChildMixin); - assert(renderObject.child == child.renderObject); + assert(renderObject.child == child); renderObject.child = null; assert(renderObject == this.renderObject); // TODO(ianh): Remove this once the analyzer is cleverer } } -abstract class MultiChildRenderObjectWrapper extends RenderObjectWrapper { - - // In MultiChildRenderObjectWrapper subclasses, slots are the Widget - // nodes whose RenderObjects are to be used as the "insert before" - // sibling in ContainerRenderObjectMixin.add() calls - - MultiChildRenderObjectWrapper({ Key key, List children }) - : this.children = children == null ? const [] : children, - super(key: key) { +/// Instantiation of RenderObjectWidgets that can have a list of children +class MultiChildRenderObjectElement extends RenderObjectElement { + MultiChildRenderObjectElement(T widget) : super(widget) { assert(!_debugHasDuplicateIds()); } - final List children; + List _children; - void walkChildren(WidgetTreeWalker walker) { - for (Widget child in children) - walker(child); - } - - void insertChildRenderObject(RenderObjectWrapper child, Widget slot) { + void insertChildRenderObject(RenderObject child, Element slot) { final renderObject = this.renderObject; // TODO(ianh): Remove this once the analyzer is cleverer RenderObject nextSibling = slot?.renderObject; - assert(nextSibling == null || nextSibling is RenderObject); assert(renderObject is ContainerRenderObjectMixin); - renderObject.add(child.renderObject, before: nextSibling); + renderObject.add(child, before: nextSibling); assert(renderObject == this.renderObject); // TODO(ianh): Remove this once the analyzer is cleverer } - void detachChildRenderObject(RenderObjectWrapper child) { + void moveChildRenderObject(RenderObject child, dynamic slot) { + final renderObject = this.renderObject; // TODO(ianh): Remove this once the analyzer is cleverer + RenderObject nextSibling = slot?.renderObject; + assert(renderObject is ContainerRenderObjectMixin); + renderObject.move(child, before: nextSibling); + assert(renderObject == this.renderObject); // TODO(ianh): Remove this once the analyzer is cleverer + } + + void removeChildRenderObject(RenderObject child) { final renderObject = this.renderObject; // TODO(ianh): Remove this once the analyzer is cleverer assert(renderObject is ContainerRenderObjectMixin); - assert(child.renderObject.parent == renderObject); - renderObject.remove(child.renderObject); + assert(child.parent == renderObject); + renderObject.remove(child); assert(renderObject == this.renderObject); // TODO(ianh): Remove this once the analyzer is cleverer } bool _debugHasDuplicateIds() { var idSet = new HashSet(); - for (var child in children) { + for (Widget child in widget.children) { assert(child != null); if (child.key == null) continue; // when these nodes are reordered, we just reassign the data if (!idSet.add(child.key)) { - throw 'If multiple keyed nodes exist as children of another node, they must have unique keys. $this has multiple children with key "${child.key}".'; + throw 'If multiple keyed nodes exist as children of another node, they must have unique keys. $widget has multiple children with key "${child.key}".'; } } return false; } - void syncRenderObject(MultiChildRenderObjectWrapper old) { - super.syncRenderObject(old); - List oldChildren = old == null ? const [] : old.children; - if (oldChildren == children) { - int index = children.length; - Widget nextSibling = null; - while (index > 0) { - index -= 1; - Widget child = children[index]; - nextSibling = syncChild(child, child, nextSibling); - children[index] = nextSibling; - } - } else { - syncChildren(children, oldChildren); + void visitChildren(ElementVisitor visitor) { + for (Element child in _children) + visitor(child); + } + + void mount(Element parent, dynamic newSlot) { + super.mount(parent, newSlot); + _children = new List(widget.children.length); + Element previousChild; + for (int i = _children.length - 1; i >= 0; --i) { + Element newChild = widget.children[i].createElement(); + newChild.mount(this, previousChild); + assert(newChild._debugLifecycleState == _ElementLifecycle.mounted); + _children[i] = newChild; + previousChild = newChild; } } -} - -class WidgetFlutterBinding extends FlutterBinding { - - WidgetFlutterBinding({ RenderView renderViewOverride: null }) - : super(renderViewOverride: renderViewOverride); - - static void initWidgetFlutterBinding({ RenderView renderViewOverride: null }) { - if (FlutterBinding.instance == null) - new WidgetFlutterBinding(renderViewOverride: renderViewOverride); - assert(FlutterBinding.instance is WidgetFlutterBinding); + void update(T newWidget) { + super.update(newWidget); + assert(widget == newWidget); + _children = updateChildren(_children, widget.children); } - - void handleEvent(sky.Event event, BindingHitTestEntry entry) { - for (HitTestEntry entry in entry.result.path) { - if (entry.target is! RenderObject) - continue; - for (Widget target in RenderObjectWrapper.getWidgetsForRenderObject(entry.target)) { - if (target is Listener) - target._handleEvent(event); - } - } - super.handleEvent(event, entry); - } - - void beginFrame(double timeStamp) { - Component.flushBuild(); - super.beginFrame(timeStamp); - } - -} - -abstract class App extends StatefulComponent { - - App({ Key key }) : super(key: key); - - void _handleEvent(sky.Event event) { - if (event.type == 'back') - onBack(); - } - - void didMount() { - super.didMount(); - FlutterBinding.instance.addEventListener(_handleEvent); - } - - void didUnmount() { - super.didUnmount(); - FlutterBinding.instance.removeEventListener(_handleEvent); - } - - void syncConstructorArguments(Component source) { } - - // Override this to handle back button behavior in your app - // Call super.onBack() to finish the activity - void onBack() { - activity.finishCurrentActivity(); - } -} - -abstract class AbstractWidgetRoot extends StatefulComponent { - - AbstractWidgetRoot() { - _mounted = true; - _scheduleComponentForBuild(this); - } - - void syncConstructorArguments(AbstractWidgetRoot source) { - assert(false); - // if we get here, it implies that we have a parent - } - - void _buildIfDirty() { - assert(_dirty); - assert(_mounted); - assert(parent == null); - _sync(null, null); - } - -} - -class RenderViewWrapper extends OneChildRenderObjectWrapper { - RenderViewWrapper({ Key key, Widget child }) : super(key: key, child: child); - RenderView get renderObject => super.renderObject; - RenderView createNode() => FlutterBinding.instance.renderView; -} - -class AppContainer extends AbstractWidgetRoot { - AppContainer(this.app) { - assert(FlutterBinding.instance is WidgetFlutterBinding); - } - final App app; - Widget build() => new RenderViewWrapper(child: app); -} - -AppContainer _container; -void runApp(App app, { RenderView renderViewOverride, bool enableProfilingLoop: false }) { - WidgetFlutterBinding.initWidgetFlutterBinding(renderViewOverride: renderViewOverride); - _container = new AppContainer(app); - if (enableProfilingLoop) { - new Timer.periodic(const Duration(milliseconds: 20), (_) { - app._scheduleBuild(); - }); - } -} - -/// Prints a textual representation of the entire widget tree -void debugDumpApp() { - if (_container != null) - _container.toStringDeep().split('\n').forEach(print); - else - print('runApp() not yet called'); -} - - -class RenderBoxToWidgetAdapter extends AbstractWidgetRoot { - - RenderBoxToWidgetAdapter( - RenderObjectWithChildMixin container, - this.builder - ) : _container = container, super() { - assert(builder != null); - } - - RenderObjectWithChildMixin _container; - RenderObjectWithChildMixin get container => _container; - void set container(RenderObjectWithChildMixin value) { - if (_container != value) { - assert(value.child == null); - if (renderObject != null) { - assert(_container.child == renderObject); - _container.child = null; - } - _container = value; - if (renderObject != null) { - _container.child = renderObject; - assert(_container.child == renderObject); - } - } - } - - final Builder builder; - - void _buildIfDirty() { - super._buildIfDirty(); - if (renderObject.parent == null) { - // we haven't attached it yet - assert(_container.child == null); - _container.child = renderObject; - } - assert(renderObject.parent == _container); - } - - Widget build() => builder(); -} - -class ErrorWidget extends LeafRenderObjectWrapper { - RenderBox createNode() => new RenderErrorBox(); } typedef void WidgetsExceptionHandler(String context, dynamic exception, StackTrace stack); @@ -1641,19 +1316,18 @@ typedef void WidgetsExceptionHandler(String context, dynamic exception, StackTra /// the exception occurred, and may include additional details such as /// descriptions of the objects involved. The 'exception' argument contains the /// object that was thrown, and the 'stack' argument contains the stack trace. -/// The callback is invoked after the information is printed to the console, and -/// could be used to print additional information, such as from -/// [debugDumpApp()]. +/// If no callback is set, then a default behaviour consisting of dumping the +/// context, exception, and stack trace to the console is used instead. WidgetsExceptionHandler debugWidgetsExceptionHandler; void _debugReportException(String context, dynamic exception, StackTrace stack) { - print('------------------------------------------------------------------------'); - 'Exception caught while $context'.split('\n').forEach(print); - print('$exception'); - print('Stack trace:'); - '$stack'.split('\n').forEach(print); - print('Build stack:'); - Component._debugComponentBuildTree.forEach((Component component) { print(' $component'); }); - if (debugWidgetsExceptionHandler != null) + if (debugWidgetsExceptionHandler != null) { debugWidgetsExceptionHandler(context, exception, stack); - print('------------------------------------------------------------------------'); + } else { + print('------------------------------------------------------------------------'); + 'Exception caught while $context'.split('\n').forEach(print); + print('$exception'); + print('Stack trace:'); + '$stack'.split('\n').forEach(print); + print('------------------------------------------------------------------------'); + } } diff --git a/packages/flutter/lib/src/widgets/gesture_detector.dart b/packages/flutter/lib/src/widgets/gesture_detector.dart index ffd393db32..88cacddbbf 100644 --- a/packages/flutter/lib/src/widgets/gesture_detector.dart +++ b/packages/flutter/lib/src/widgets/gesture_detector.dart @@ -5,11 +5,12 @@ import 'dart:sky' as sky; import 'package:sky/gestures.dart'; -import 'package:sky/src/rendering/binding.dart'; +import 'package:sky/src/widgets/basic.dart'; import 'package:sky/src/widgets/framework.dart'; +import 'package:sky/src/rendering/binding.dart'; class GestureDetector extends StatefulComponent { - GestureDetector({ + const GestureDetector({ Key key, this.child, this.onTap, @@ -29,45 +30,34 @@ class GestureDetector extends StatefulComponent { this.onScaleEnd }) : super(key: key); - Widget child; - GestureTapListener onTap; - GestureShowPressListener onShowPress; - GestureLongPressListener onLongPress; + final Widget child; + final GestureTapListener onTap; + final GestureShowPressListener onShowPress; + final GestureLongPressListener onLongPress; - GestureDragStartCallback onVerticalDragStart; - GestureDragUpdateCallback onVerticalDragUpdate; - GestureDragEndCallback onVerticalDragEnd; + final GestureDragStartCallback onVerticalDragStart; + final GestureDragUpdateCallback onVerticalDragUpdate; + final GestureDragEndCallback onVerticalDragEnd; - GestureDragStartCallback onHorizontalDragStart; - GestureDragUpdateCallback onHorizontalDragUpdate; - GestureDragEndCallback onHorizontalDragEnd; + final GestureDragStartCallback onHorizontalDragStart; + final GestureDragUpdateCallback onHorizontalDragUpdate; + final GestureDragEndCallback onHorizontalDragEnd; - GesturePanStartCallback onPanStart; - GesturePanUpdateCallback onPanUpdate; - GesturePanEndCallback onPanEnd; + final GesturePanStartCallback onPanStart; + final GesturePanUpdateCallback onPanUpdate; + final GesturePanEndCallback onPanEnd; - GestureScaleStartCallback onScaleStart; - GestureScaleUpdateCallback onScaleUpdate; - GestureScaleEndCallback onScaleEnd; + final GestureScaleStartCallback onScaleStart; + final GestureScaleUpdateCallback onScaleUpdate; + final GestureScaleEndCallback onScaleEnd; - void syncConstructorArguments(GestureDetector source) { - child = source.child; - onTap = source.onTap; - onShowPress = source.onShowPress; - onLongPress = source.onLongPress; - onVerticalDragStart = source.onVerticalDragStart; - onVerticalDragUpdate = source.onVerticalDragUpdate; - onVerticalDragEnd = source.onVerticalDragEnd; - onHorizontalDragStart = source.onHorizontalDragStart; - onHorizontalDragUpdate = source.onHorizontalDragUpdate; - onHorizontalDragEnd = source.onHorizontalDragEnd; - onPanStart = source.onPanStart; - onPanUpdate = source.onPanUpdate; - onPanEnd = source.onPanEnd; - onScaleStart = source.onScaleStart; - onScaleUpdate = source.onScaleUpdate; - onScaleEnd = source.onScaleEnd; - _syncGestureListeners(); + GestureDetectorState createState() => new GestureDetectorState(); +} + +class GestureDetectorState extends State { + void initState() { + super.initState(); + didUpdateConfig(null); } final PointerRouter _router = FlutterBinding.instance.pointerRouter; @@ -123,13 +113,7 @@ class GestureDetector extends StatefulComponent { return _scale; } - void didMount() { - super.didMount(); - _syncGestureListeners(); - } - - void didUnmount() { - super.didUnmount(); + void dispose() { _tap = _ensureDisposed(_tap); _showPress = _ensureDisposed(_showPress); _longPress = _ensureDisposed(_longPress); @@ -137,9 +121,10 @@ class GestureDetector extends StatefulComponent { _horizontalDrag = _ensureDisposed(_horizontalDrag); _pan = _ensureDisposed(_pan); _scale = _ensureDisposed(_scale); + super.dispose(); } - void _syncGestureListeners() { + void didUpdateConfig(GestureDetector oldConfig) { _syncTap(); _syncShowPress(); _syncLongPress(); @@ -150,67 +135,67 @@ class GestureDetector extends StatefulComponent { } void _syncTap() { - if (onTap == null) + if (config.onTap == null) _tap = _ensureDisposed(_tap); else - _ensureTap().onTap = onTap; + _ensureTap().onTap = config.onTap; } void _syncShowPress() { - if (onShowPress == null) + if (config.onShowPress == null) _showPress = _ensureDisposed(_showPress); else - _ensureShowPress().onShowPress = onShowPress; + _ensureShowPress().onShowPress = config.onShowPress; } void _syncLongPress() { - if (onLongPress == null) + if (config.onLongPress == null) _longPress = _ensureDisposed(_longPress); else - _ensureLongPress().onLongPress = onLongPress; + _ensureLongPress().onLongPress = config.onLongPress; } void _syncVerticalDrag() { - if (onVerticalDragStart == null && onVerticalDragUpdate == null && onVerticalDragEnd == null) { + if (config.onVerticalDragStart == null && config.onVerticalDragUpdate == null && config.onVerticalDragEnd == null) { _verticalDrag = _ensureDisposed(_verticalDrag); } else { _ensureVerticalDrag() - ..onStart = onVerticalDragStart - ..onUpdate = onVerticalDragUpdate - ..onEnd = onVerticalDragEnd; + ..onStart = config.onVerticalDragStart + ..onUpdate = config.onVerticalDragUpdate + ..onEnd = config.onVerticalDragEnd; } } void _syncHorizontalDrag() { - if (onHorizontalDragStart == null && onHorizontalDragUpdate == null && onHorizontalDragEnd == null) { + if (config.onHorizontalDragStart == null && config.onHorizontalDragUpdate == null && config.onHorizontalDragEnd == null) { _horizontalDrag = _ensureDisposed(_horizontalDrag); } else { _ensureHorizontalDrag() - ..onStart = onHorizontalDragStart - ..onUpdate = onHorizontalDragUpdate - ..onEnd = onHorizontalDragEnd; + ..onStart = config.onHorizontalDragStart + ..onUpdate = config.onHorizontalDragUpdate + ..onEnd = config.onHorizontalDragEnd; } } void _syncPan() { - if (onPanStart == null && onPanUpdate == null && onPanEnd == null) { + if (config.onPanStart == null && config.onPanUpdate == null && config.onPanEnd == null) { _pan = _ensureDisposed(_pan); } else { _ensurePan() - ..onStart = onPanStart - ..onUpdate = onPanUpdate - ..onEnd = onPanEnd; + ..onStart = config.onPanStart + ..onUpdate = config.onPanUpdate + ..onEnd = config.onPanEnd; } } void _syncScale() { - if (onScaleStart == null && onScaleUpdate == null && onScaleEnd == null) { + if (config.onScaleStart == null && config.onScaleUpdate == null && config.onScaleEnd == null) { _scale = _ensureDisposed(_pan); } else { _ensureScale() - ..onStart = onScaleStart - ..onUpdate = onScaleUpdate - ..onEnd = onScaleEnd; + ..onStart = config.onScaleStart + ..onUpdate = config.onScaleUpdate + ..onEnd = config.onScaleEnd; } } @@ -236,10 +221,10 @@ class GestureDetector extends StatefulComponent { _scale.addPointer(event); } - Widget build() { + Widget build(BuildContext context) { return new Listener( onPointerDown: _handlePointerDown, - child: child + child: config.child ); } } diff --git a/packages/flutter/lib/src/widgets/global_key_watcher.dart b/packages/flutter/lib/src/widgets/global_key_watcher.dart deleted file mode 100644 index 03c5403525..0000000000 --- a/packages/flutter/lib/src/widgets/global_key_watcher.dart +++ /dev/null @@ -1,83 +0,0 @@ -// 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. - -import 'package:sky/src/widgets/framework.dart'; - -abstract class GlobalKeyWatcher extends StatefulComponent { - GlobalKeyWatcher({ - Key key, - this.watchedKey - }); - - GlobalKey watchedKey; - - void syncConstructorArguments(GlobalKeyWatcher source) { - if (watchedKey != source.watchedKey) { - if (watchedKey != null) - _removeListeners(); - watchedKey = source.watchedKey; - if (mounted && watchedKey != null) { - _setWatchedWidget(GlobalKey.getWidget(watchedKey)); - _addListeners(); - } - } - } - - Widget get watchedWidget => _watchedWidget; - Widget _watchedWidget; - void _setWatchedWidget(Widget value) { - assert(mounted || value == null); - if (watchedWidget != value) { - if (watchedWidget != null) - stopWatching(); - assert(value == null || debugValidateWatchedWidget(value)); - setState(() { - _watchedWidget = value; - }); - if (watchedWidget != null) - startWatching(); - } - } - - bool debugValidateWatchedWidget(Widget candidate) => true; - - void didMount() { - super.didMount(); - if (watchedKey != null) { - _setWatchedWidget(GlobalKey.getWidget(watchedKey)); - _addListeners(); - } - } - - void didUnmount() { - super.didUnmount(); - if (watchedKey != null) - _removeListeners(); - _setWatchedWidget(null); - } - - void _addListeners() { - GlobalKey.registerSyncListener(watchedKey, didSyncWatchedKey); - GlobalKey.registerRemoveListener(watchedKey, didRemoveWatchedKey); - } - - void _removeListeners() { - GlobalKey.unregisterSyncListener(watchedKey, didSyncWatchedKey); - GlobalKey.unregisterRemoveListener(watchedKey, didRemoveWatchedKey); - } - - void didSyncWatchedKey(GlobalKey key, Widget widget) { - assert(key == watchedKey); - _setWatchedWidget(widget); - } - - void didRemoveWatchedKey(GlobalKey key) { - assert(key == watchedKey); - _setWatchedWidget(null); - } - - void stopWatching() { } - void startWatching() { } - -} diff --git a/packages/flutter/lib/src/widgets/homogeneous_viewport.dart b/packages/flutter/lib/src/widgets/homogeneous_viewport.dart index 3fc72207a1..19dade6689 100644 --- a/packages/flutter/lib/src/widgets/homogeneous_viewport.dart +++ b/packages/flutter/lib/src/widgets/homogeneous_viewport.dart @@ -4,15 +4,13 @@ import 'dart:math' as math; -import 'package:sky/src/rendering/block.dart'; -import 'package:sky/src/rendering/box.dart'; -import 'package:sky/src/rendering/object.dart'; +import 'package:sky/rendering.dart'; import 'package:sky/src/widgets/framework.dart'; import 'package:sky/src/widgets/basic.dart'; -typedef List ListBuilder(int startIndex, int count); +typedef List ListBuilder(BuildContext context, int startIndex, int count); -class HomogeneousViewport extends RenderObjectWrapper { +class HomogeneousViewport extends RenderObjectWidget { HomogeneousViewport({ Key key, this.builder, @@ -25,118 +23,95 @@ class HomogeneousViewport extends RenderObjectWrapper { assert(itemExtent != null); } - ListBuilder builder; - bool itemsWrap; - double itemExtent; - int itemCount; - ScrollDirection direction; - double startOffset; + final ListBuilder builder; + final bool itemsWrap; + final double itemExtent; + final int itemCount; + final ScrollDirection direction; + final double startOffset; - List _children; - bool _layoutDirty = true; + HomogeneousViewportElement createElement() => new HomogeneousViewportElement(this); + + // we don't pass constructor arguments to the RenderBlockViewport() because until + // we know our children, the constructor arguments we could give have no effect + RenderBlockViewport createRenderObject() => new RenderBlockViewport(); + + bool isLayoutDifferentThan(HomogeneousViewport oldWidget) { + return itemsWrap != oldWidget.itemsWrap || + itemsWrap != oldWidget.itemsWrap || + itemExtent != oldWidget.itemExtent || + itemCount != oldWidget.itemCount || + direction != oldWidget.direction || + startOffset != oldWidget.startOffset; + } + + // all the actual work is done in the element +} + +class HomogeneousViewportElement extends RenderObjectElement { + HomogeneousViewportElement(HomogeneousViewport widget) : super(widget); + + List _children = const []; int _layoutFirstIndex; int _layoutItemCount; RenderBlockViewport get renderObject => super.renderObject; - RenderBlockViewport createNode() { - // we don't pass constructor arguments to the RenderBlockViewport() because until - // we know our children, the constructor arguments we could give have no effect - RenderBlockViewport result = new RenderBlockViewport(); - result.callback = layout; - result.totalExtentCallback = getTotalExtent; - result.minCrossAxisExtentCallback = getMinCrossAxisExtent; - result.maxCrossAxisExtentCallback = getMaxCrossAxisExtent; - return result; + void visitChildren(ElementVisitor visitor) { + if (_children == null) + return; + for (Element child in _children) + visitor(child); } - void remove() { + void mount(Element parent, dynamic newSlot) { + super.mount(parent, newSlot); + renderObject.callback = layout; + renderObject.totalExtentCallback = getTotalExtent; + renderObject.minCrossAxisExtentCallback = getMinCrossAxisExtent; + renderObject.maxCrossAxisExtentCallback = getMaxCrossAxisExtent; + } + + void unmount() { renderObject.callback = null; renderObject.totalExtentCallback = null; renderObject.minCrossAxisExtentCallback = null; renderObject.maxCrossAxisExtentCallback = null; - super.remove(); - _children.clear(); - _layoutDirty = true; - assert(() { - _layoutFirstIndex = null; - _layoutItemCount = null; - return true; - }); + super.unmount(); } - void walkChildren(WidgetTreeWalker walker) { - if (_children == null) - return; - for (Widget child in _children) - walker(child); - } - - void insertChildRenderObject(RenderObjectWrapper child, Widget slot) { - RenderObject nextSibling = slot?.renderObject; - renderObject.add(child.renderObject, before: nextSibling); - } - - void detachChildRenderObject(RenderObjectWrapper child) { - renderObject.remove(child.renderObject); - } - - bool retainStatefulNodeIfPossible(HomogeneousViewport newNode) { - retainStatefulRenderObjectWrapper(newNode); - if (startOffset != newNode.startOffset) { - _layoutDirty = true; - startOffset = newNode.startOffset; - } - if (itemCount != newNode.itemCount) { - _layoutDirty = true; - itemCount = newNode.itemCount; - } - if (itemsWrap != newNode.itemsWrap) { - _layoutDirty = true; - itemsWrap = newNode.itemsWrap; - } - if (itemExtent != newNode.itemExtent) { - _layoutDirty = true; - itemExtent = newNode.itemExtent; - } - if (direction != newNode.direction) { - _layoutDirty = true; - direction = newNode.direction; - } - if (builder != newNode.builder) { - _layoutDirty = true; - builder = newNode.builder; - } - return true; - } - - // This is called during the regular component build - void syncRenderObject(HomogeneousViewport old) { - super.syncRenderObject(old); - if (_layoutDirty) { + void update(HomogeneousViewport newWidget) { + bool needLayout = newWidget.isLayoutDifferentThan(widget); + super.update(newWidget); + if (needLayout) renderObject.markNeedsLayout(); - } else { - assert(old != null); // if old was null, we'd be new, and therefore _layoutDirty would be true + else _updateChildren(); - } } void layout(BoxConstraints constraints) { - LayoutCallbackBuilderHandle handle = enterLayoutCallbackBuilder(); - try { - double mainAxisExtent = direction == ScrollDirection.vertical ? constraints.maxHeight : constraints.maxWidth; + // We enter a build scope (meaning that markNeedsBuild() is forbidden) + // because we are in the middle of layout and if we allowed people to set + // state, they'd expect to have that state reflected immediately, which, if + // we were to try to honour it, would potentially result in assertions + // because you can't normally mutate the render object tree during layout. + // (If there were a way to limit these writes to descendants of this, it'd + // be ok because we are exempt from that assert since we are still actively + // doing our own layout.) + BuildableElement.lockState(() { + double mainAxisExtent = widget.direction == ScrollDirection.vertical ? constraints.maxHeight : constraints.maxWidth; double offset; - if (startOffset <= 0.0 && !itemsWrap) { + if (widget.startOffset <= 0.0 && !widget.itemsWrap) { _layoutFirstIndex = 0; - offset = -startOffset; + offset = -widget.startOffset; } else { - _layoutFirstIndex = (startOffset / itemExtent).floor(); - offset = -(startOffset % itemExtent); + _layoutFirstIndex = (widget.startOffset / widget.itemExtent).floor(); + offset = -(widget.startOffset % widget.itemExtent); } if (mainAxisExtent < double.INFINITY) { - _layoutItemCount = ((mainAxisExtent - offset) / itemExtent).ceil(); - if (itemCount != null && !itemsWrap) - _layoutItemCount = math.min(_layoutItemCount, itemCount - _layoutFirstIndex); + _layoutItemCount = ((mainAxisExtent - offset) / widget.itemExtent).ceil(); + if (widget.itemCount != null && !widget.itemsWrap) + _layoutItemCount = math.min(_layoutItemCount, widget.itemCount - _layoutFirstIndex); } else { assert(() { 'This HomogeneousViewport has no specified number of items (meaning it has infinite items), ' + @@ -144,37 +119,34 @@ class HomogeneousViewport extends RenderObjectWrapper { 'It is most likely that you have placed your HomogeneousViewport (which is an internal ' + 'component of several scrollable widgets) inside either another scrolling box, a flexible ' + 'box (Row, Column), or a Stack, without giving it a specific size.'; - return itemCount != null; + return widget.itemCount != null; }); - _layoutItemCount = itemCount - _layoutFirstIndex; + _layoutItemCount = widget.itemCount - _layoutFirstIndex; } _layoutItemCount = math.max(0, _layoutItemCount); _updateChildren(); // Update the renderObject configuration - renderObject.direction = direction == ScrollDirection.vertical ? BlockDirection.vertical : BlockDirection.horizontal; - renderObject.itemExtent = itemExtent; + renderObject.direction = widget.direction == ScrollDirection.vertical ? BlockDirection.vertical : BlockDirection.horizontal; + renderObject.itemExtent = widget.itemExtent; renderObject.minExtent = getTotalExtent(null); renderObject.startOffset = offset; - } finally { - exitLayoutCallbackBuilder(handle); - } + }); } void _updateChildren() { assert(_layoutFirstIndex != null); assert(_layoutItemCount != null); - List newChildren; + List newWidgets; if (_layoutItemCount > 0) - newChildren = builder(_layoutFirstIndex, _layoutItemCount); + newWidgets = widget.builder(this, _layoutFirstIndex, _layoutItemCount); else - newChildren = []; - syncChildren(newChildren, _children == null ? [] : _children); - _children = newChildren; + newWidgets = []; + _children = updateChildren(_children, newWidgets); } double getTotalExtent(BoxConstraints constraints) { // constraints is null when called by layout() above - return itemCount != null ? itemCount * itemExtent : double.INFINITY; + return widget.itemCount != null ? widget.itemCount * widget.itemExtent : double.INFINITY; } double getMinCrossAxisExtent(BoxConstraints constraints) { @@ -182,9 +154,25 @@ class HomogeneousViewport extends RenderObjectWrapper { } double getMaxCrossAxisExtent(BoxConstraints constraints) { - if (direction == ScrollDirection.vertical) + if (widget.direction == ScrollDirection.vertical) return constraints.maxWidth; return constraints.maxHeight; } + void insertChildRenderObject(RenderObject child, Element slot) { + RenderObject nextSibling = slot?.renderObject; + renderObject.add(child, before: nextSibling); + } + + void moveChildRenderObject(RenderObject child, Element slot) { + assert(child.parent == renderObject); + RenderObject nextSibling = slot?.renderObject; + renderObject.move(child, before: nextSibling); + } + + void removeChildRenderObject(RenderObject child) { + assert(child.parent == renderObject); + renderObject.remove(child); + } + } diff --git a/packages/flutter/lib/src/widgets/icon.dart b/packages/flutter/lib/src/widgets/icon.dart index 2dfdff0c54..dc95312ba3 100644 --- a/packages/flutter/lib/src/widgets/icon.dart +++ b/packages/flutter/lib/src/widgets/icon.dart @@ -16,7 +16,7 @@ class IconThemeData { final IconThemeColor color; } -class IconTheme extends Inherited { +class IconTheme extends InheritedWidget { IconTheme({ Key key, @@ -29,12 +29,12 @@ class IconTheme extends Inherited { final IconThemeData data; - static IconThemeData of(Component component) { - IconTheme result = component.inheritedOfType(IconTheme); + static IconThemeData of(BuildContext context) { + IconTheme result = context.inheritedWidgetOfType(IconTheme); return result?.data; } - bool syncShouldNotify(IconTheme old) => data != old.data; + bool updateShouldNotify(IconTheme old) => data != old.data; } @@ -47,7 +47,7 @@ AssetBundle _initIconBundle() { final AssetBundle _iconBundle = _initIconBundle(); -class Icon extends Component { +class Icon extends StatelessComponent { Icon({ Key key, this.size, @@ -61,14 +61,14 @@ class Icon extends Component { final IconThemeColor color; final sky.ColorFilter colorFilter; - String get colorSuffix { + String getColorSuffix(BuildContext context) { IconThemeColor iconThemeColor = color; if (iconThemeColor == null) { - IconThemeData iconThemeData = IconTheme.of(this); + IconThemeData iconThemeData = IconTheme.of(context); iconThemeColor = iconThemeData == null ? null : iconThemeData.color; } if (iconThemeColor == null) { - ThemeBrightness themeBrightness = Theme.of(this).brightness; + ThemeBrightness themeBrightness = Theme.of(context).brightness; iconThemeColor = themeBrightness == ThemeBrightness.dark ? IconThemeColor.white : IconThemeColor.black; } switch(iconThemeColor) { @@ -79,7 +79,7 @@ class Icon extends Component { } } - Widget build() { + Widget build(BuildContext context) { String category = ''; String subtype = ''; List parts = type.split('/'); @@ -90,6 +90,7 @@ class Icon extends Component { // TODO(eseidel): This clearly isn't correct. Not sure what would be. // Should we use the ios images on ios? String density = 'drawable-xxhdpi'; + String colorSuffix = getColorSuffix(context); return new AssetImage( bundle: _iconBundle, name: '${category}/${density}/ic_${subtype}_${colorSuffix}_${size}dp.png', diff --git a/packages/flutter/lib/src/widgets/icon_button.dart b/packages/flutter/lib/src/widgets/icon_button.dart index 714f1ae70a..fcb42fd327 100644 --- a/packages/flutter/lib/src/widgets/icon_button.dart +++ b/packages/flutter/lib/src/widgets/icon_button.dart @@ -9,15 +9,14 @@ import 'package:sky/src/widgets/icon.dart'; import 'package:sky/src/widgets/framework.dart'; import 'package:sky/src/widgets/gesture_detector.dart'; -class IconButton extends Component { - - IconButton({ Key key, this.icon, this.onPressed, this.color }) : super(key: key); +class IconButton extends StatelessComponent { + const IconButton({ Key key, this.icon, this.onPressed, this.color }) : super(key: key); final String icon; final Function onPressed; final Color color; - Widget build() { + Widget build(BuildContext context) { Widget child = new Icon(type: icon, size: 24); if (color != null) { child = new ColorFilter( @@ -33,5 +32,4 @@ class IconButton extends Component { padding: const EdgeDims.all(8.0)) ); } - } diff --git a/packages/flutter/lib/src/widgets/ink_well.dart b/packages/flutter/lib/src/widgets/ink_well.dart index d4096d0952..7f2b2e0e13 100644 --- a/packages/flutter/lib/src/widgets/ink_well.dart +++ b/packages/flutter/lib/src/widgets/ink_well.dart @@ -30,11 +30,11 @@ class InkSplash { _radius = new AnimatedValue( _kSplashInitialSize, end: _targetRadius, curve: easeOut); - _performance = new AnimationPerformance() - ..variable = _radius - ..duration = new Duration(milliseconds: (_targetRadius / _kSplashUnconfirmedVelocity).floor()) - ..addListener(_handleRadiusChange) - ..play(); + _performance = new ValueAnimation( + variable: _radius, + duration: new Duration(milliseconds: (_targetRadius / _kSplashUnconfirmedVelocity).floor()) + )..addListener(_handleRadiusChange) + ..play(); } final int pointer; @@ -125,10 +125,7 @@ class RenderInkWell extends RenderProxyBox { } } -class InkWell extends OneChildRenderObjectWrapper { - InkWell({ Key key, Widget child }) - : super(key: key, child: child); - - RenderInkWell get renderObject => super.renderObject; - RenderInkWell createNode() => new RenderInkWell(); +class InkWell extends OneChildRenderObjectWidget { + InkWell({ Key key, Widget child }) : super(key: key, child: child); + RenderInkWell createRenderObject() => new RenderInkWell(); } diff --git a/packages/flutter/lib/src/widgets/input.dart b/packages/flutter/lib/src/widgets/input.dart index 67d4581d1a..b9bcfbaf92 100644 --- a/packages/flutter/lib/src/widgets/input.dart +++ b/packages/flutter/lib/src/widgets/input.dart @@ -2,12 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'package:sky/animation.dart'; import 'package:sky/services.dart'; import 'package:sky/painting.dart'; +import 'package:sky/rendering.dart'; import 'package:sky/src/widgets/basic.dart'; import 'package:sky/src/widgets/editable_text.dart'; import 'package:sky/src/widgets/focus.dart'; import 'package:sky/src/widgets/framework.dart'; +import 'package:sky/src/widgets/scrollable.dart'; import 'package:sky/src/widgets/theme.dart'; export 'package:sky/services.dart' show KeyboardType; @@ -18,36 +21,42 @@ typedef void StringValueChanged(String value); // http://www.google.com/design/spec/components/text-fields.html#text-fields-single-line-text-field const EdgeDims _kTextfieldPadding = const EdgeDims.symmetric(vertical: 8.0); -class Input extends StatefulComponent { - +class Input extends Scrollable { Input({ GlobalKey key, - String initialValue: '', + this.initialValue: '', this.placeholder, this.onChanged, - this.keyboardType : KeyboardType.TEXT - }): _value = initialValue, super(key: key); + this.keyboardType: KeyboardType.TEXT + }): super( + key: key, + initialScrollOffset: 0.0, + scrollDirection: ScrollDirection.horizontal + ); - KeyboardType keyboardType; - String placeholder; - StringValueChanged onChanged; + final String initialValue; + final KeyboardType keyboardType; + final String placeholder; + final StringValueChanged onChanged; + InputState createState() => new InputState(); +} + +class InputState extends ScrollableState { String _value; EditableString _editableValue; KeyboardHandle _keyboardHandle = KeyboardHandle.unattached; + double _contentWidth = 0.0; + double _containerWidth = 0.0; + void initState() { + super.initState(); + _value = config.initialValue; _editableValue = new EditableString( text: _value, onUpdated: _handleTextUpdated ); - super.initState(); - } - - void syncConstructorArguments(Input source) { - placeholder = source.placeholder; - onChanged = source.onChanged; - keyboardType = source.keyboardType; } void _handleTextUpdated() { @@ -55,17 +64,17 @@ class Input extends StatefulComponent { setState(() { _value = _editableValue.text; }); - if (onChanged != null) - onChanged(_value); + if (config.onChanged != null) + config.onChanged(_value); } } - Widget build() { - ThemeData themeData = Theme.of(this); - bool focused = Focus.at(this); + Widget buildContent(BuildContext context) { + ThemeData themeData = Theme.of(context); + bool focused = FocusState.at(context, config); if (focused && !_keyboardHandle.attached) { - _keyboardHandle = keyboard.show(_editableValue.stub, keyboardType); + _keyboardHandle = keyboard.show(_editableValue.stub, config.keyboardType); } else if (!focused && _keyboardHandle.attached) { _keyboardHandle.release(); } @@ -73,10 +82,10 @@ class Input extends StatefulComponent { TextStyle textStyle = themeData.text.subhead; List textChildren = []; - if (placeholder != null && _value.isEmpty) { + if (config.placeholder != null && _value.isEmpty) { Widget child = new Opacity( key: const ValueKey('placeholder'), - child: new Text(placeholder, style: textStyle), + child: new Text(config.placeholder, style: textStyle), opacity: themeData.hintOpacity ); textChildren.add(child); @@ -93,39 +102,63 @@ class Input extends StatefulComponent { value: _editableValue, focused: focused, style: textStyle, - cursorColor: cursorColor + cursorColor: cursorColor, + onContentSizeChanged: _handleContentSizeChanged, + scrollOffset: scrollOffsetVector )); - Border focusHighlight = new Border(bottom: new BorderSide( - color: focusHighlightColor, - width: focused ? 2.0 : 1.0 - )); - - Container input = new Container( - child: new Stack(textChildren), - padding: _kTextfieldPadding, - decoration: new BoxDecoration(border: focusHighlight) - ); - return new Listener( - child: input, - onPointerDown: focus + child: new SizeObserver( + callback: _handleContainerSizeChanged, + child: new Container( + child: new Stack(textChildren), + padding: _kTextfieldPadding, + decoration: new BoxDecoration(border: new Border( + bottom: new BorderSide( + color: focusHighlightColor, + width: focused ? 2.0 : 1.0 + ) + )) + ) + ), + onPointerDown: (_) { + if (FocusState.at(context, config)) { + assert(_keyboardHandle.attached); + _keyboardHandle.showByRequest(); + } else { + FocusState.moveTo(context, config); + // we'll get told to rebuild and we'll take care of the keyboard then + } + } ); } - void focus(_) { - if (Focus.at(this)) { - assert(_keyboardHandle.attached); - _keyboardHandle.showByRequest(); - } else { - Focus.moveTo(this); - // we'll get told to rebuild and we'll take care of the keyboard then - } - } - - void didUnmount() { + void dispose() { if (_keyboardHandle.attached) _keyboardHandle.release(); - super.didUnmount(); + super.dispose(); + } + + ScrollBehavior createScrollBehavior() => new BoundedBehavior(); + BoundedBehavior get scrollBehavior => super.scrollBehavior; + + void _handleContainerSizeChanged(Size newSize) { + _containerWidth = newSize.width; + _updateScrollBehavior(); + } + + void _handleContentSizeChanged(Size newSize) { + _contentWidth = newSize.width; + _updateScrollBehavior(); + } + + void _updateScrollBehavior() { + // Set the scroll offset to match the content width so that the cursor + // (which is always at the end of the text) will be visible. + scrollTo(scrollBehavior.updateExtents( + contentExtent: _contentWidth, + containerExtent: _containerWidth, + scrollOffset: _contentWidth) + ); } } diff --git a/packages/flutter/lib/src/widgets/material.dart b/packages/flutter/lib/src/widgets/material.dart index 95f3b869c6..02ea4ce80e 100644 --- a/packages/flutter/lib/src/widgets/material.dart +++ b/packages/flutter/lib/src/widgets/material.dart @@ -4,9 +4,7 @@ import 'package:sky/painting.dart'; import 'package:sky/material.dart'; -import 'package:sky/src/widgets/animated_container.dart'; import 'package:sky/src/widgets/basic.dart'; -import 'package:sky/src/widgets/default_text_style.dart'; import 'package:sky/src/widgets/framework.dart'; import 'package:sky/src/widgets/theme.dart'; @@ -19,7 +17,7 @@ const Map edges = const { MaterialType.button: 2.0, }; -class Material extends Component { +class Material extends StatelessComponent { Material({ Key key, this.child, @@ -35,24 +33,24 @@ class Material extends Component { final int level; final Color color; - Color get _backgroundColor { + Color getBackgroundColor(BuildContext context) { if (color != null) return color; switch (type) { case MaterialType.canvas: - return Theme.of(this).canvasColor; + return Theme.of(context).canvasColor; case MaterialType.card: - return Theme.of(this).cardColor; + return Theme.of(context).cardColor; default: return null; } } - Widget build() { + Widget build(BuildContext context) { Widget contents = child; if (child != null) { contents = new DefaultTextStyle( - style: Theme.of(this).text.body1, + style: Theme.of(context).text.body1, child: contents ); if (edges[type] != null) { @@ -63,15 +61,18 @@ class Material extends Component { ); } } - return new AnimatedContainer( - behavior: implicitlyAnimate(const Duration(milliseconds: 200)), - decoration: new BoxDecoration( - backgroundColor: _backgroundColor, - borderRadius: edges[type], - boxShadow: level == 0 ? null : shadows[level], - shape: type == MaterialType.circle ? Shape.circle : Shape.rectangle - ), - child: contents + // TODO(abarth): This should use AnimatedContainer. + return new DefaultTextStyle( + style: Theme.of(context).text.body1, + child: new Container( + decoration: new BoxDecoration( + backgroundColor: getBackgroundColor(context), + borderRadius: edges[type], + boxShadow: level == 0 ? null : shadows[level], + shape: type == MaterialType.circle ? Shape.circle : Shape.rectangle + ), + child: contents + ) ); } } diff --git a/packages/flutter/lib/src/widgets/material_button.dart b/packages/flutter/lib/src/widgets/material_button.dart index 11d2b02285..c5dfb0a7be 100644 --- a/packages/flutter/lib/src/widgets/material_button.dart +++ b/packages/flutter/lib/src/widgets/material_button.dart @@ -3,58 +3,53 @@ // found in the LICENSE file. import 'package:sky/src/widgets/basic.dart'; -import 'package:sky/src/widgets/button_base.dart'; +import 'package:sky/src/widgets/button_state.dart'; import 'package:sky/src/widgets/framework.dart'; import 'package:sky/src/widgets/gesture_detector.dart'; import 'package:sky/src/widgets/ink_well.dart'; import 'package:sky/src/widgets/material.dart'; // Rather than using this class directly, please use FlatButton or RaisedButton. -abstract class MaterialButton extends ButtonBase { - +abstract class MaterialButton extends StatefulComponent { MaterialButton({ Key key, this.child, this.enabled: true, this.onPressed - }) : super(key: key); - - Widget child; - bool enabled; - Function onPressed; - - void syncConstructorArguments(MaterialButton source) { - child = source.child; - enabled = source.enabled; - onPressed = source.onPressed; - super.syncConstructorArguments(source); + }) : super(key: key) { + assert(enabled != null); } - Color get color; + final Widget child; + final bool enabled; + final Function onPressed; +} + +abstract class MaterialButtonState extends ButtonState { + Color getColor(BuildContext context); int get level; - Widget buildContent() { + Widget buildContent(BuildContext context) { Widget contents = new Container( padding: new EdgeDims.symmetric(horizontal: 8.0), child: new Center( shrinkWrap: ShrinkWrap.width, - child: child // TODO(ianh): figure out a way to compell the child to have gray text when disabled... + child: config.child // TODO(ianh): figure out a way to compell the child to have gray text when disabled... ) ); return new GestureDetector( - onTap: enabled ? onPressed : null, + onTap: config.enabled ? config.onPressed : null, child: new Container( height: 36.0, constraints: new BoxConstraints(minWidth: 88.0), margin: new EdgeDims.all(8.0), child: new Material( type: MaterialType.button, - child: enabled ? new InkWell(child: contents) : contents, + child: config.enabled ? new InkWell(child: contents) : contents, level: level, - color: color + color: getColor(context) ) ) ); } - } diff --git a/packages/flutter/lib/src/widgets/mimic.dart b/packages/flutter/lib/src/widgets/mimic.dart index a8ed50d84b..961db37986 100644 --- a/packages/flutter/lib/src/widgets/mimic.dart +++ b/packages/flutter/lib/src/widgets/mimic.dart @@ -2,86 +2,69 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'package:sky/rendering.dart'; import 'package:sky/src/widgets/basic.dart'; import 'package:sky/src/widgets/framework.dart'; -import 'package:sky/src/widgets/global_key_watcher.dart'; -typedef MimicReadyCallback(); +class MimicableKey { + MimicableKey._(this._state); -class Mimic extends GlobalKeyWatcher { - Mimic({ - Key key, - GlobalKey original, - this.onMimicReady - }) : super(key: key, watchedKey: original); + final MimicableState _state; - MimicReadyCallback onMimicReady; + Rect get globalBounds => _state._globalBounds; - void syncConstructorArguments(Mimic source) { - onMimicReady = source.onMimicReady; - super.syncConstructorArguments(source); + void stopMimic() { + _state._stopMimic(); } +} - bool debugValidateWatchedWidget(Widget candidate) { - return candidate is Mimicable; - } +class Mimic extends StatelessComponent { + Mimic({ Key key, this.original }) : super(key: key); - Mimicable get _mimicable => watchedWidget; + final MimicableKey original; - void didSyncWatchedKey(GlobalKey key, Widget widget) { - super.didSyncWatchedKey(key, widget); // calls startWatching() - if (onMimicReady != null && _mimicable._didBuildPlaceholder) - onMimicReady(); - } - - void startWatching() { - _mimicable.startMimic(); - } - - void stopWatching() { - _mimicable.stopMimic(); - } - - Widget build() { - if (_mimicable == null || !_mimicable._didBuildPlaceholder) - return new Container(); - return _mimicable.child; + Widget build(BuildContext context) { + if (original != null && original._state._beingMimicked) + return original._state.config.child; + return new Container(); } } class Mimicable extends StatefulComponent { - Mimicable({ GlobalKey key, this.child }) : super(key: key); + Mimicable({ Key key, this.child }) : super(key: key); - Widget child; + final Widget child; + MimicableState createState() => new MimicableState(); +} + +class MimicableState extends State { Size _size; - Size get size => _size; + bool _beingMimicked = false; - void syncConstructorArguments(Mimicable source) { - child = source.child; - } - - bool _didBuildPlaceholder = false; - - Rect get globalBounds { - if (_size == null) - return null; - return localToGlobal(Point.origin) & _size; - } - - bool _mimicRequested = false; - void startMimic() { - assert(!_mimicRequested); + MimicableKey startMimic() { + assert(!_beingMimicked); + assert(_size != null); setState(() { - _mimicRequested = true; + _beingMimicked = true; + }); + return new MimicableKey._(this); + } + + void _stopMimic() { + assert(_beingMimicked); + if (!mounted) { + _beingMimicked = false; + return; + } + setState(() { + _beingMimicked = false; }); } - void stopMimic() { - assert(_mimicRequested); - setState(() { - _mimicRequested = false; - }); + Rect get _globalBounds { + RenderBox box = context.findRenderObject(); + return box.localToGlobal(Point.origin) & box.size; } void _handleSizeChanged(Size size) { @@ -90,16 +73,15 @@ class Mimicable extends StatefulComponent { }); } - Widget build() { - _didBuildPlaceholder = _mimicRequested && _size != null; - if (_didBuildPlaceholder) { + Widget build(BuildContext context) { + if (_beingMimicked) { return new ConstrainedBox( constraints: new BoxConstraints.tight(_size) ); } return new SizeObserver( callback: _handleSizeChanged, - child: child + child: config.child ); } } diff --git a/packages/flutter/lib/src/widgets/mixed_viewport.dart b/packages/flutter/lib/src/widgets/mixed_viewport.dart index c9b9dfc1db..723cde1fea 100644 --- a/packages/flutter/lib/src/widgets/mixed_viewport.dart +++ b/packages/flutter/lib/src/widgets/mixed_viewport.dart @@ -2,143 +2,146 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'dart:collection'; - -import 'package:sky/src/rendering/block.dart'; -import 'package:sky/src/rendering/box.dart'; -import 'package:sky/src/rendering/object.dart'; +import 'package:sky/rendering.dart'; import 'package:sky/src/widgets/framework.dart'; import 'package:sky/src/widgets/basic.dart'; -// return null if index is greater than index of last entry -typedef Widget IndexedBuilder(int index); +typedef Widget IndexedBuilder(BuildContext context, int index); // return null if index is greater than index of last entry +typedef void ExtentsUpdateCallback(double newExtents); +typedef void InvalidatorCallback(Iterable indices); +typedef void InvalidatorAvailableCallback(InvalidatorCallback invalidator); -class _Key { - const _Key(this.type, this.key); - factory _Key.fromWidget(Widget widget) => new _Key(widget.runtimeType, widget.key); +enum _ChangeDescription { none, scrolled, resized } + +class MixedViewport extends RenderObjectWidget { + MixedViewport({ + Key key, + this.startOffset, + this.direction: ScrollDirection.vertical, + this.builder, + this.token, + this.onExtentsUpdate, + this.onInvalidatorAvailable + }): super(key: key); + + final double startOffset; + final ScrollDirection direction; + final IndexedBuilder builder; + final Object token; + final ExtentsUpdateCallback onExtentsUpdate; + final InvalidatorAvailableCallback onInvalidatorAvailable; + + MixedViewportElement createElement() => new MixedViewportElement(this); + + // we don't pass constructor arguments to the RenderBlockViewport() because until + // we know our children, the constructor arguments we could give have no effect + RenderBlockViewport createRenderObject() => new RenderBlockViewport(); + + _ChangeDescription evaluateChangesFrom(MixedViewport oldWidget) { + if (direction != oldWidget.direction || + builder != oldWidget.builder || + token != oldWidget.token) + return _ChangeDescription.resized; + if (startOffset != oldWidget.startOffset) + return _ChangeDescription.scrolled; + return _ChangeDescription.none; + } + + // all the actual work is done in the element +} + +class _ChildKey { + const _ChildKey(this.type, this.key); + factory _ChildKey.fromWidget(Widget widget) => new _ChildKey(widget.runtimeType, widget.key); final Type type; final Key key; - bool operator ==(other) => other is _Key && other.type == type && other.key == key; + bool operator ==(other) => other is _ChildKey && other.type == type && other.key == key; int get hashCode => 373 * 37 * type.hashCode + key.hashCode; - String toString() => "_Key(type: $type, key: $key)"; + String toString() => "_ChildKey(type: $type, key: $key)"; } -typedef void LayoutChangedCallback(); - -class MixedViewportLayoutState { - MixedViewportLayoutState() - : _childOffsets = [0.0], - _firstVisibleChildIndex = 0, - _visibleChildCount = 0, - _didReachLastChild = false - { - _readOnlyChildOffsets = new UnmodifiableListView(_childOffsets); +class MixedViewportElement extends RenderObjectElement { + MixedViewportElement(MixedViewport widget) : super(widget) { + if (widget.onInvalidatorAvailable != null) + widget.onInvalidatorAvailable(invalidate); } - bool _dirty = true; + /// _childExtents contains the extents of each child from the top of the list + /// up to the last one we've ever created. + final List _childExtents = []; + /// _childOffsets contains the offsets of the top of each child from the top + /// of the list up to the last one we've ever created, and the offset of the + /// end of the last one. The first value is always 0.0. If there are no + /// children, that is the only value. The offset of the end of the last child + /// created (the actual last child, if didReachLastChild is true), is also the + /// distance from the top (left) of the first child to the bottom (right) of + /// the last child created. + final List _childOffsets = [0.0]; + + /// Whether childOffsets includes the offset of the last child. + bool _didReachLastChild = false; + + /// The index of the first child whose bottom edge is below the top of the + /// viewport. int _firstVisibleChildIndex; - int get firstVisibleChildIndex => _firstVisibleChildIndex; - int _visibleChildCount; - int get visibleChildCount => _visibleChildCount; + /// The currently visibly children. + Map<_ChildKey, Element> _childrenByKey = new Map<_ChildKey, Element>(); - // childOffsets contains the offsets of each child from the top of the - // list up to the last one we've ever created, and the offset of the - // end of the last one. If there are no children, then the only offset - // is 0.0. - List _childOffsets; - UnmodifiableListView _readOnlyChildOffsets; - UnmodifiableListView get childOffsets => _readOnlyChildOffsets; - double get contentsSize => _childOffsets.last; + /// The child offsets that we've been told are invalid. + final Set _invalidIndices = new Set(); - bool _didReachLastChild; - bool get didReachLastChild => _didReachLastChild; - - Set _invalidIndices = new Set(); + /// Returns false if any of the previously-cached offsets have been marked as + /// invalid and need to be updated. bool get isValid => _invalidIndices.length == 0; - // Notify the BlockViewport that the children at indices have either - // changed size and/or changed type. - void invalidate(Iterable indices) { - _invalidIndices.addAll(indices); - } - final List _listeners = new List(); - void addListener(Function listener) { - _listeners.add(listener); - } - void removeListener(Function listener) { - _listeners.remove(listener); - } - void _notifyListeners() { - List localListeners = new List.from(_listeners); - for (Function listener in localListeners) - listener(); - } -} + /// The constraints for which the current offsets are valid. + BoxConstraints _lastLayoutConstraints; -class MixedViewport extends RenderObjectWrapper { - MixedViewport({ this.startOffset, this.direction: ScrollDirection.vertical, this.builder, this.token, MixedViewportLayoutState layoutState }) - : layoutState = layoutState, super(key: new ObjectKey(layoutState)) { - // using the layout state as the key is important to prevent us from being synced with someone with a different layout state - assert(this.layoutState != null); - } - - double startOffset; - ScrollDirection direction; - IndexedBuilder builder; - Object token; - MixedViewportLayoutState layoutState; - - Map<_Key, Widget> _childrenByKey = new Map<_Key, Widget>(); + /// The last value that was sent to onExtentsUpdate. + double _lastReportedExtents; RenderBlockViewport get renderObject => super.renderObject; - RenderBlockViewport createNode() { - // we don't pass the direction or offset to the render object when we - // create it, because the render object is empty so it will not matter - RenderBlockViewport result = new RenderBlockViewport(); - result.callback = layout; - result.totalExtentCallback = _noIntrinsicExtent; - result.maxCrossAxisExtentCallback = _noIntrinsicExtent; - result.minCrossAxisExtentCallback = _noIntrinsicExtent; - return result; + /// Notify the BlockViewport that the children at indices have, or might have, + /// changed size. Call this whenever the dimensions of a particular child + /// change, so that the rendering will be updated accordingly. A pointer to + /// this method is provided via the onInvalidatorAvailable callback. + void invalidate(Iterable indices) { + assert(indices.length > 0); + _invalidIndices.addAll(indices); + renderObject.markNeedsLayout(); } - void remove() { + /// Forget all the known child offsets. + void _resetCache() { + _childExtents.clear(); + _childOffsets.clear(); + _childOffsets.add(0.0); + _didReachLastChild = false; + _invalidIndices.clear(); + } + + void visitChildren(ElementVisitor visitor) { + for (Element child in _childrenByKey.values) + visitor(child); + } + + void mount(Element parent, dynamic newSlot) { + super.mount(parent, newSlot); + renderObject.callback = layout; + renderObject.totalExtentCallback = _noIntrinsicExtent; + renderObject.maxCrossAxisExtentCallback = _noIntrinsicExtent; + renderObject.minCrossAxisExtentCallback = _noIntrinsicExtent; + } + + void unmount() { renderObject.callback = null; renderObject.totalExtentCallback = null; - renderObject.maxCrossAxisExtentCallback = null; renderObject.minCrossAxisExtentCallback = null; - super.remove(); - _childrenByKey.clear(); - layoutState._dirty = true; - } - - void walkChildren(WidgetTreeWalker walker) { - for (Widget child in _childrenByKey.values) - walker(child); - } - - static const _omit = const Object(); // used as a slot when it's not yet time to attach the child - - void insertChildRenderObject(RenderObjectWrapper child, dynamic slot) { - if (slot == _omit) - return; - final renderObject = this.renderObject; // TODO(ianh): Remove this once the analyzer is cleverer - assert(slot == null || slot is RenderObject); - assert(renderObject is ContainerRenderObjectMixin); - renderObject.add(child.renderObject, before: slot); - assert(renderObject == this.renderObject); // TODO(ianh): Remove this once the analyzer is cleverer - } - - void detachChildRenderObject(RenderObjectWrapper child) { - final renderObject = this.renderObject; // TODO(ianh): Remove this once the analyzer is cleverer - assert(renderObject is ContainerRenderObjectMixin); - if (child.renderObject.parent != renderObject) - return; // probably had slot == _omit when inserted - renderObject.remove(child.renderObject); - assert(renderObject == this.renderObject); // TODO(ianh): Remove this once the analyzer is cleverer + renderObject.maxCrossAxisExtentCallback = null; + super.unmount(); } double _noIntrinsicExtent(BoxConstraints constraints) { @@ -151,15 +154,67 @@ class MixedViewport extends RenderObjectWrapper { return null; } + static const Object _omit = const Object(); // used as a slot when it's not yet time to attach the child + + void update(MixedViewport newWidget) { + _ChangeDescription changes = newWidget.evaluateChangesFrom(widget); + super.update(newWidget); + if (changes == _ChangeDescription.resized) + _resetCache(); + if (changes != _ChangeDescription.none || !isValid) { + renderObject.markNeedsLayout(); + } else { + // we just need to redraw our existing widgets as-is + if (_childrenByKey.length > 0) { + assert(_firstVisibleChildIndex >= 0); + assert(renderObject != null); + final int startIndex = _firstVisibleChildIndex; + int lastIndex = startIndex + _childrenByKey.length - 1; + Element nextSibling = null; + for (int index = lastIndex; index > startIndex; index -= 1) { + final Widget newWidget = _buildWidgetAt(index); + final _ChildKey key = new _ChildKey.fromWidget(newWidget); + final Element oldElement = _childrenByKey[key]; + assert(oldElement != null); + final Element newElement = updateChild(oldElement, newWidget, nextSibling); + assert(newElement != null); + _childrenByKey[key] = newElement; + // Verify that it hasn't changed size. + // If this assertion fires, it means you didn't call "invalidate" + // before changing the size of one of your items. + assert(_debugIsSameSize(newElement, index, _lastLayoutConstraints)); + nextSibling = newElement; + } + } + } + } + + void layout(BoxConstraints constraints) { + if (constraints != _lastLayoutConstraints) { + _resetCache(); + _lastLayoutConstraints = constraints; + } + BuildableElement.lockState(() { + _doLayout(constraints); + }); + if (widget.onExtentsUpdate != null) { + final double newExtents = _didReachLastChild ? _childOffsets.last : null; + if (newExtents != _lastReportedExtents) { + _lastReportedExtents = newExtents; + widget.onExtentsUpdate(_lastReportedExtents); + } + } + } + + /// Binary search to find the index of the child responsible for rendering a given pixel int _findIndexForOffsetBeforeOrAt(double offset) { - final List offsets = layoutState._childOffsets; int left = 0; - int right = offsets.length - 1; + int right = _childOffsets.length - 1; while (right >= left) { int middle = left + ((right - left) ~/ 2); - if (offsets[middle] < offset) { + if (_childOffsets[middle] < offset) { left = middle + 1; - } else if (offsets[middle] > offset) { + } else if (_childOffsets[middle] > offset) { right = middle - 1; } else { return middle; @@ -168,284 +223,310 @@ class MixedViewport extends RenderObjectWrapper { return right; } - bool retainStatefulNodeIfPossible(MixedViewport newNode) { - assert(layoutState == newNode.layoutState); - retainStatefulRenderObjectWrapper(newNode); - if (startOffset != newNode.startOffset) { - layoutState._dirty = true; - startOffset = newNode.startOffset; - } - if (direction != newNode.direction || builder != newNode.builder || token != newNode.token) { - layoutState._dirty = true; - layoutState._didReachLastChild = false; - layoutState._childOffsets = [0.0]; - layoutState._invalidIndices = new Set(); - direction = newNode.direction; - builder = newNode.builder; - token = newNode.token; - } - return true; - } - - void syncRenderObject(MixedViewport old) { - super.syncRenderObject(old); - if (layoutState._dirty || !layoutState.isValid) { - renderObject.markNeedsLayout(); - } else { - if (layoutState._visibleChildCount > 0) { - assert(layoutState.firstVisibleChildIndex >= 0); - assert(builder != null); - assert(renderObject != null); - final int startIndex = layoutState._firstVisibleChildIndex; - int lastIndex = startIndex + layoutState._visibleChildCount - 1; - for (int index = startIndex; index <= lastIndex; index += 1) { - Widget widget = builder(index); - assert(widget != null); - assert(widget.key != null); - assert(widget.isFromOldGeneration); - _Key key = new _Key.fromWidget(widget); - Widget oldWidget = _childrenByKey[key]; - assert(oldWidget != null); - assert(() { - 'One of the nodes that was in this MixedViewport was placed in another part of the tree, without the MixedViewport\'s token or builder being changed ' + - 'and without the MixedViewport\'s MixedViewportLayoutState object being told about that any of the children were invalid.'; - return oldWidget.isFromOldGeneration; - }); - assert(oldWidget.renderObject.parent == renderObject); - widget = syncChild(widget, oldWidget, renderObject.childAfter(oldWidget.renderObject)); - assert(widget != null); - _childrenByKey[key] = widget; - } - } - } - } - - // Build the widget at index, and use its maxIntrinsicHeight to fix up - // the offsets from index+1 to endIndex. Return the newWidget. - Widget _getWidgetAndRecomputeOffsets(int index, int endIndex, BoxConstraints innerConstraints) { - final List offsets = layoutState._childOffsets; - // Create the newWidget at index. - assert(index >= 0); - assert(endIndex > index); - assert(endIndex < offsets.length); - assert(builder != null); - Widget newWidget = builder(index); - assert(newWidget != null); - assert(newWidget.key != null); - assert(newWidget.isFromOldGeneration); - final _Key key = new _Key.fromWidget(newWidget); - Widget oldWidget = _childrenByKey[key]; - if (oldWidget != null && !oldWidget.isFromOldGeneration) - oldWidget = null; - newWidget = syncChild(newWidget, oldWidget, _omit); - assert(newWidget != null); - // Update the offsets based on the newWidget's dimensions. - RenderBox widgetRoot = newWidget.renderObject; - assert(widgetRoot is RenderBox); - double newOffset; - if (direction == ScrollDirection.vertical) { - newOffset = widgetRoot.getMaxIntrinsicHeight(innerConstraints); - } else { - newOffset = widgetRoot.getMaxIntrinsicWidth(innerConstraints); - } - double oldOffset = offsets[index + 1] - offsets[index]; - double offsetDelta = newOffset - oldOffset; - for (int i = index + 1; i <= endIndex; i++) - offsets[i] += offsetDelta; + /// Calls the builder. This is for the case where you don't know if you have a child at this index. + Widget _maybeBuildWidgetAt(int index) { + if (widget.builder == null) + return null; + final Widget newWidget = widget.builder(this, index); + assert(newWidget == null || newWidget.key != null); // every widget in a list must have a list-unique key return newWidget; } - Widget _getWidget(int index, BoxConstraints innerConstraints) { - final List offsets = layoutState._childOffsets; - assert(index >= 0); - Widget widget = builder == null ? null : builder(index); - if (widget == null) + /// Calls the builder. This is for the case where you know that you should have a child there. + Widget _buildWidgetAt(int index) { + final Widget newWidget = widget.builder(this, index); + assert(newWidget != null); + assert(newWidget.key != null); // every widget in a list must have a list-unique key + return newWidget; + } + + /// Given an element configuration, inflates the element, updating the existing one if there was one. + /// Returns the resulting element. + Element _inflateOrUpdateWidget(Widget newWidget) { + final _ChildKey key = new _ChildKey.fromWidget(newWidget); + final Element oldElement = _childrenByKey[key]; + final Element newElement = updateChild(oldElement, newWidget, _omit); + assert(newElement != null); + return newElement; + } + + // Build the widget at index. + Element _getElement(int index, BoxConstraints innerConstraints) { + assert(index <= _childOffsets.length - 1); + final Widget newWidget = _buildWidgetAt(index); + final Element newElement = _inflateOrUpdateWidget(newWidget); + return newElement; + } + + // Build the widget at index. + Element _maybeGetElement(int index, BoxConstraints innerConstraints) { + assert(index <= _childOffsets.length - 1); + final Widget newWidget = _maybeBuildWidgetAt(index); + if (newWidget == null) return null; - assert(widget.key != null); // items in lists must have keys - final _Key key = new _Key.fromWidget(widget); - Widget oldWidget = _childrenByKey[key]; - if (oldWidget != null && !oldWidget.isFromOldGeneration) - oldWidget = null; - widget = syncChild(widget, oldWidget, _omit); - if (index >= offsets.length - 1) { - assert(index == offsets.length - 1); - final double widgetStartOffset = offsets[index]; - RenderBox widgetRoot = widget.renderObject; - assert(widgetRoot is RenderBox); - double widgetEndOffset; - if (direction == ScrollDirection.vertical) { - widgetEndOffset = widgetStartOffset + widgetRoot.getMaxIntrinsicHeight(innerConstraints); - } else { - widgetEndOffset = widgetStartOffset + widgetRoot.getMaxIntrinsicWidth(innerConstraints); - } - offsets.add(widgetEndOffset); + final Element newElement = _inflateOrUpdateWidget(newWidget); + return newElement; + } + + // Build the widget at index, handling the case where there is no such widget. + // Update the offset for that widget. + Element _getElementAtLastKnownOffset(int index, BoxConstraints innerConstraints) { + + // Inflate the new widget; if there isn't one, abort early. + assert(index == _childOffsets.length - 1); + final Widget newWidget = _maybeBuildWidgetAt(index); + if (newWidget == null) + return null; + final Element newElement = _inflateOrUpdateWidget(newWidget); + + // Update the offsets based on the newElement's dimensions. + final double newExtent = _getElementExtent(newElement, innerConstraints); + _childExtents.add(newExtent); + _childOffsets.add(_childOffsets[index] + newExtent); + assert(_childExtents.length == _childOffsets.length - 1); + + return newElement; + } + + /// Returns the intrinsic size of the given element in the scroll direction + double _getElementExtent(Element element, BoxConstraints innerConstraints) { + final RenderBox childRenderObject = element.renderObject; + switch (widget.direction) { + case ScrollDirection.vertical: + return childRenderObject.getMaxIntrinsicHeight(innerConstraints); + case ScrollDirection.horizontal: + return childRenderObject.getMaxIntrinsicWidth(innerConstraints); + case ScrollDirection.both: + assert(false); // we don't support ScrollDirection.both, see issue 888 + return double.NAN; } - return widget; } - void layout(BoxConstraints constraints) { - if (!layoutState._dirty && layoutState.isValid) - return; - layoutState._dirty = false; - - LayoutCallbackBuilderHandle handle = enterLayoutCallbackBuilder(); - try { - _doLayout(constraints); - } finally { - exitLayoutCallbackBuilder(handle); + BoxConstraints _getInnerConstraints(BoxConstraints constraints) { + switch (widget.direction) { + case ScrollDirection.vertical: + return new BoxConstraints.tightFor(width: constraints.constrainWidth()); + case ScrollDirection.horizontal: + return new BoxConstraints.tightFor(height: constraints.constrainHeight()); + case ScrollDirection.both: + assert(false); // we don't support ScrollDirection.both, see issue 888 + return null; } - - layoutState._notifyListeners(); } - void _unsyncChild(Widget widget) { - assert(!widget.isFromOldGeneration); - // The following two lines are the equivalent of "syncChild(null, - // widget, null)", but actually doing that wouldn't work because - // widget is now from the new generation and so syncChild() would - // assume that that means someone else has already sync()ed with it - // and that it's wanted. But it's not wanted! We want to get rid of - // it. So we do it manually. - widget.detachRenderObject(); - widget.remove(); + /// This compares the offsets we had for an element with its current + /// intrinsic dimensions. + bool _debugIsSameSize(Element element, int index, BoxConstraints constraints) { + assert(_invalidIndices.isEmpty); + BoxConstraints innerConstraints = _getInnerConstraints(constraints); + double newExtent = _getElementExtent(element, innerConstraints); + bool result = _childExtents[index] == newExtent; + if (!result) + print("Element $element at index $index was size ${_childExtents[index]} but is now size ${newExtent} yet no invalidate() was received to that effect"); + return result; } + /// This is the core lazy-build algorithm. It builds widgets incrementally + /// from index 0 until it has built enough widgets to cover itself, and + /// discards any widgets that are not displayed. void _doLayout(BoxConstraints constraints) { - Map<_Key, Widget> newChildren = new Map<_Key, Widget>(); - Map builtChildren = new Map(); + Map<_ChildKey, Element> newChildren = new Map<_ChildKey, Element>(); + Map builtChildren = new Map(); - final List offsets = layoutState._childOffsets; - final Map<_Key, Widget> childrenByKey = _childrenByKey; + // Establish the start and end offsets based on our current constraints. double extent; - if (direction == ScrollDirection.vertical) { - extent = constraints.maxHeight; - assert(extent < double.INFINITY && - 'There is no point putting a lazily-built vertical MixedViewport inside a box with infinite internal ' + - 'height (e.g. inside something else that scrolls vertically), because it would then just eagerly build ' + - 'all the children. You probably want to put the MixedViewport inside a Container with a fixed height.' is String); - } else { - extent = constraints.maxWidth; - assert(extent < double.INFINITY && - 'There is no point putting a lazily-built horizontal MixedViewport inside a box with infinite internal ' + - 'width (e.g. inside something else that scrolls horizontally), because it would then just eagerly build ' + - 'all the children. You probably want to put the MixedViewport inside a Container with a fixed width.' is String); + switch (widget.direction) { + case ScrollDirection.vertical: + extent = constraints.maxHeight; + assert(extent < double.INFINITY && + 'There is no point putting a lazily-built vertical MixedViewport inside a box with infinite internal ' + + 'height (e.g. inside something else that scrolls vertically), because it would then just eagerly build ' + + 'all the children. You probably want to put the MixedViewport inside a Container with a fixed height.' is String); + break; + case ScrollDirection.horizontal: + extent = constraints.maxWidth; + assert(extent < double.INFINITY && + 'There is no point putting a lazily-built horizontal MixedViewport inside a box with infinite internal ' + + 'width (e.g. inside something else that scrolls horizontally), because it would then just eagerly build ' + + 'all the children. You probably want to put the MixedViewport inside a Container with a fixed width.' is String); + break; + case ScrollDirection.both: assert(false); // we don't support ScrollDirection.both, see issue 888 } - final double endOffset = startOffset + extent; + final double endOffset = widget.startOffset + extent; - BoxConstraints innerConstraints; - if (direction == ScrollDirection.vertical) { - innerConstraints = new BoxConstraints.tightFor(width: constraints.constrainWidth()); - } else { - innerConstraints = new BoxConstraints.tightFor(height: constraints.constrainHeight()); - } + // Create the constraints that we will use to measure the children. + final BoxConstraints innerConstraints = _getInnerConstraints(constraints); - // Before doing the actual layout, fix the offsets for the widgets - // whose size or type has changed. - if (!layoutState.isValid && offsets.length > 0) { - List invalidIndices = layoutState._invalidIndices.toList(); + // Before doing the actual layout, fix the offsets for the widgets whose + // size has apparently changed. + if (!isValid) { + assert(_childOffsets.length > 0); + assert(_childOffsets.length == _childExtents.length + 1); + List invalidIndices = _invalidIndices.toList(); invalidIndices.sort(); - // Ensure all of the offsets after invalidIndices[0] are updated. - if (invalidIndices.last < offsets.length - 1) - invalidIndices.add(offsets.length - 1); - for (int i = 0; i < invalidIndices.length - 1; i += 1) { - int index = invalidIndices[i]; - int endIndex = invalidIndices[i + 1]; - Widget widget = _getWidgetAndRecomputeOffsets(index, endIndex, innerConstraints); - _Key widgetKey = new _Key.fromWidget(widget); - bool isVisible = offsets[index] < endOffset && offsets[index + 1] >= startOffset; - if (isVisible) { - newChildren[widgetKey] = widget; - builtChildren[index] = widget; - } else { - childrenByKey.remove(widgetKey); - _unsyncChild(widget); - } - } - } - layoutState._invalidIndices.clear(); + for (int i = 0; i < invalidIndices.length; i += 1) { + // Determine the indices for this pass. + final int widgetIndex = invalidIndices[i]; + if (widgetIndex >= _childExtents.length) + break; // we don't have that child, so there's nothing to invalidate + int endIndex; // the last index into _childOffsets that we want to update this round + if (i == invalidIndices.length - 1) { + // This is the last invalid index. Update all the remaining entries in _childOffsets. + endIndex = _childOffsets.length - 1; + } else { + endIndex = invalidIndices[i + 1]; + if (endIndex > _childOffsets.length - 1) + endIndex = _childOffsets.length - 1; // no point updating beyond the last offset we know of + } + assert(widgetIndex >= 0); + assert(endIndex < _childOffsets.length); + assert(widgetIndex < endIndex); + + // Inflate the widget or update the existing element, as necessary. + final Element newElement = _getElement(widgetIndex, innerConstraints); + + // Update the offsets based on the newElement's dimensions. + _childExtents[widgetIndex] = _getElementExtent(newElement, innerConstraints); + for (int j = widgetIndex + 1; j <= endIndex; j++) + _childOffsets[j] = _childOffsets[j - 1] + _childExtents[j - 1]; + assert(_childOffsets.length == _childExtents.length + 1); + + // Decide if it's visible. + final _ChildKey key = new _ChildKey.fromWidget(newElement.widget); + final bool isVisible = _childOffsets[widgetIndex] < endOffset && _childOffsets[widgetIndex + 1] >= widget.startOffset; + if (isVisible) { + // Keep it. + newChildren[key] = newElement; + builtChildren[widgetIndex] = newElement; + } else { + // Drop it. + _childrenByKey.remove(key); + updateChild(newElement, null, null); + } + + } + _invalidIndices.clear(); + } + + // Decide what the first child to render should be (startIndex), if any (haveChildren). int startIndex; bool haveChildren; - if (startOffset <= 0.0) { + if (endOffset < 0.0) { + // We're so far scrolled up that nothing is visible. + haveChildren = false; + } else if (widget.startOffset <= 0.0) { startIndex = 0; - if (offsets.length > 1) { + // If we're scrolled up past the top, then our first visible widget, if + // any, is the first widget. + if (_childExtents.length > 0) { haveChildren = true; } else { - Widget widget = _getWidget(startIndex, innerConstraints); - if (widget != null) { - newChildren[new _Key.fromWidget(widget)] = widget; - builtChildren[startIndex] = widget; + final Element element = _getElementAtLastKnownOffset(startIndex, innerConstraints); + if (element != null) { + newChildren[new _ChildKey.fromWidget(element.widget)] = element; + builtChildren[startIndex] = element; haveChildren = true; } else { haveChildren = false; - layoutState._didReachLastChild = true; + _didReachLastChild = true; } } } else { - startIndex = _findIndexForOffsetBeforeOrAt(startOffset); - if (startIndex == offsets.length - 1) { + // We're at some sane (not higher than the top) scroll offset. + // See if we can already find the offset in our cache. + startIndex = _findIndexForOffsetBeforeOrAt(widget.startOffset); + if (startIndex < _childExtents.length) { + // We already know of a child that would be visible at this offset. + haveChildren = true; + } else { // We don't have an offset on the list that is beyond the start offset. - assert(offsets.last <= startOffset); + assert(_childOffsets.last <= widget.startOffset); // Fill the list until this isn't true or until we know that the // list is complete (and thus we are overscrolled). while (true) { - Widget widget = _getWidget(startIndex, innerConstraints); - if (widget == null) { - layoutState._didReachLastChild = true; + // Get the next element and cache its offset. + final Element element = _getElementAtLastKnownOffset(startIndex, innerConstraints); + if (element == null) { + // Reached the end of the list. We are so far overscrolled, there's nothing to show. + _didReachLastChild = true; + haveChildren = false; break; } - _Key widgetKey = new _Key.fromWidget(widget); - if (offsets.last > startOffset) { - // it's visible - newChildren[widgetKey] = widget; - builtChildren[startIndex] = widget; + final _ChildKey key = new _ChildKey.fromWidget(element.widget); + if (_childOffsets.last > widget.startOffset) { + // This element is visible! It must thus be our first visible child. + newChildren[key] = element; + builtChildren[startIndex] = element; + haveChildren = true; break; } - childrenByKey.remove(widgetKey); - _unsyncChild(widget); + // This element is not visible. Drop the inflated element. + // (We've already cached its offset for later use.) + _childrenByKey.remove(key); + updateChild(element, null, null); startIndex += 1; - assert(startIndex == offsets.length - 1); + assert(startIndex == _childExtents.length); } - if (offsets.last > startOffset) { - // If we're here, we have at least one child, so our list has - // at least two offsets, the top of the child and the bottom - // of the child. - assert(offsets.length >= 2); - assert(startIndex == offsets.length - 2); - haveChildren = true; - } else { - // If we're here, there are no children to show. - haveChildren = false; - } - } else { - haveChildren = true; + assert(haveChildren == _childOffsets.last > widget.startOffset); + assert(() { + if (haveChildren) { + // We found a child to render. It's the last one for which we have an + // offset in _childOffsets. + // If we're here, we have at least one child, so our list has + // at least two offsets, the top of the child and the bottom + // of the child. + assert(_childExtents.length >= 1); + assert(_childOffsets.length == _childExtents.length + 1); + assert(startIndex == _childExtents.length - 1); + } + return true; + }); } } assert(haveChildren != null); - assert(haveChildren || layoutState._didReachLastChild); - + assert(haveChildren || _didReachLastChild || endOffset < 0.0); assert(startIndex >= 0); - assert(startIndex < offsets.length); + assert(startIndex < _childExtents.length); + // Build the other widgets that are visible. int index = startIndex; if (haveChildren) { // Update the renderObject configuration - if (direction == ScrollDirection.vertical) { - renderObject.direction = BlockDirection.vertical; - } else { - renderObject.direction = BlockDirection.horizontal; + switch (widget.direction) { + case ScrollDirection.vertical: + renderObject.direction = BlockDirection.vertical; + break; + case ScrollDirection.horizontal: + renderObject.direction = BlockDirection.horizontal; + break; + case ScrollDirection.both: assert(false); // we don't support ScrollDirection.both, see issue 888 } - renderObject.startOffset = offsets[index] - startOffset; + renderObject.startOffset = _childOffsets[index] - widget.startOffset; // Build all the widgets we still need. - while (offsets[index] < endOffset) { + while (_childOffsets[index] < endOffset) { if (!builtChildren.containsKey(index)) { - Widget widget = _getWidget(index, innerConstraints); - if (widget == null) { - layoutState._didReachLastChild = true; + Element element = _maybeGetElement(index, innerConstraints); + if (element == null) { + _didReachLastChild = true; break; } - newChildren[new _Key.fromWidget(widget)] = widget; - builtChildren[index] = widget; + if (index == _childExtents.length) { + // Remember this element's offset. + final double newExtent = _getElementExtent(element, innerConstraints); + _childExtents.add(newExtent); + _childOffsets.add(_childOffsets[index] + newExtent); + assert(_childOffsets.length == _childExtents.length + 1); + } else { + // Verify that it hasn't changed size. + // If this assertion fires, it means you didn't call "invalidate" + // before changing the size of one of your items. + assert(_debugIsSameSize(element, index, constraints)); + } + // Remember the element for when we place the children. + final _ChildKey key = new _ChildKey.fromWidget(element.widget); + newChildren[key] = element; + builtChildren[index] = element; } assert(builtChildren[index] != null); index += 1; @@ -453,33 +534,59 @@ class MixedViewport extends RenderObjectWrapper { } // Remove any old children. - for (_Key oldChildKey in childrenByKey.keys) { + for (_ChildKey oldChildKey in _childrenByKey.keys) { if (!newChildren.containsKey(oldChildKey)) - syncChild(null, childrenByKey[oldChildKey], null); // calls detachChildRenderObject() + updateChild(_childrenByKey[oldChildKey], null, null); } if (haveChildren) { // Place all our children in our RenderObject. // All the children we are placing are in builtChildren and newChildren. - // We will walk them backwards so we can set the siblings at the same time. - RenderBox nextSibling = null; + // We will walk them backwards so we can set the slots at the same time. + Element nextSibling = null; while (index > startIndex) { index -= 1; - Widget widget = builtChildren[index]; - if (widget.renderObject.parent == renderObject) { - renderObject.move(widget.renderObject, before: nextSibling); - } else { - assert(widget.renderObject.parent == null); - renderObject.add(widget.renderObject, before: nextSibling); - } - widget.updateSlot(nextSibling); - nextSibling = widget.renderObject; + final Element element = builtChildren[index]; + if (element.slot != nextSibling) + updateSlotForChild(element, nextSibling); + nextSibling = element; } } + // Update our internal state. _childrenByKey = newChildren; - layoutState._firstVisibleChildIndex = startIndex; - layoutState._visibleChildCount = newChildren.length; + _firstVisibleChildIndex = startIndex; + } + + void updateSlotForChild(Element element, dynamic newSlot) { + assert(newSlot == null || newSlot == _omit || newSlot is Element); + super.updateSlotForChild(element, newSlot); + } + + void insertChildRenderObject(RenderObject child, dynamic slot) { + if (slot == _omit) + return; + assert(slot == null || slot is Element); + RenderObject nextSibling = slot?.renderObject; + renderObject.add(child, before: nextSibling); + } + + void moveChildRenderObject(RenderObject child, dynamic slot) { + if (slot == _omit) + return; + assert(slot == null || slot is Element); + RenderObject nextSibling = slot?.renderObject; + assert(nextSibling == null || nextSibling.parent == renderObject); + if (child.parent == renderObject) + renderObject.move(child, before: nextSibling); + else + renderObject.add(child, before: nextSibling); + } + + void removeChildRenderObject(RenderObject child) { + if (child.parent != renderObject) + return; // probably had slot == _omit when inserted + renderObject.remove(child); } } diff --git a/packages/flutter/lib/src/widgets/navigator.dart b/packages/flutter/lib/src/widgets/navigator.dart index c290569347..b22ef6c082 100644 --- a/packages/flutter/lib/src/widgets/navigator.dart +++ b/packages/flutter/lib/src/widgets/navigator.dart @@ -8,66 +8,258 @@ import 'package:sky/src/widgets/focus.dart'; import 'package:sky/src/widgets/framework.dart'; import 'package:sky/src/widgets/transitions.dart'; -typedef Widget RouteBuilder(Navigator navigator, RouteBase route); - +typedef Widget RouteBuilder(NavigatorState navigator, Route route); +typedef RouteBuilder RouteGenerator(String name); +typedef void RouteStateCallback(RouteState route); typedef void NotificationCallback(); -abstract class RouteBase { - AnimationPerformance _performance; - NotificationCallback onDismissed; - NotificationCallback onCompleted; - AnimationPerformance createPerformance() { - AnimationPerformance result = new AnimationPerformance(duration: transitionDuration); - result.addStatusListener((AnimationStatus status) { - switch (status) { - case AnimationStatus.dismissed: - if (onDismissed != null) - onDismissed(); - break; - case AnimationStatus.completed: - if (onCompleted != null) - onCompleted(); - break; - default: - ; - } - }); - return result; +class Navigator extends StatefulComponent { + Navigator({ + Key key, + this.routes, + this.onGenerateRoute, // you need to implement this if you pushNamed() to names that might not be in routes. + this.onUnknownRoute // 404 generator. You only need to implement this if you have a way to navigate to arbitrary names. + }) : super(key: key) { + // To use a navigator, you must at a minimum define the route with the name '/'. + assert(routes.containsKey('/')); } - WatchableAnimationPerformance ensurePerformance({ Direction direction }) { + + final Map routes; + final RouteGenerator onGenerateRoute; + final RouteBuilder onUnknownRoute; + + NavigatorState createState() => new NavigatorState(); +} + +class NavigatorState extends State { + + List _history = new List(); + int _currentPosition = 0; + + Route get currentRoute => _history[_currentPosition]; + bool get hasPreviousRoute => _history.length > 1; + + void initState() { + super.initState(); + PageRoute route = new PageRoute(config.routes['/']); + assert(route != null); + assert(!route.ephemeral); + _history.add(route); + } + + void pushState(State owner, Function callback) { + push(new RouteState( + route: currentRoute, + owner: owner, + callback: callback + )); + } + + void pushNamed(String name) { + RouteBuilder builder; + if (!config.routes.containsKey(name)) { + assert(config.onGenerateRoute != null); + builder = config.onGenerateRoute(name); + } else { + builder = config.routes[name]; + } + if (builder == null) + builder = config.onUnknownRoute; // 404! + assert(builder != null); // 404 getting your 404! + push(new PageRoute(builder)); + } + + void push(Route route) { + assert(!_debugCurrentlyHaveRoute(route)); + setState(() { + while (currentRoute.ephemeral) { + assert(currentRoute.ephemeral); + currentRoute.didPop(null); + _currentPosition -= 1; + } + _history.insert(_currentPosition + 1, route); + _currentPosition += 1; + }); + } + + void popRoute(Route route, [dynamic result]) { + assert(_debugCurrentlyHaveRoute(route)); + assert(_currentPosition > 0); + setState(() { + while (currentRoute != route) { + assert(currentRoute.ephemeral); + currentRoute.didPop(null); + _currentPosition -= 1; + } + assert(_currentPosition > 0); + currentRoute.didPop(result); + _currentPosition -= 1; + }); + assert(!_debugCurrentlyHaveRoute(route)); + } + + void pop([dynamic result]) { + setState(() { + while (currentRoute.ephemeral) { + currentRoute.didPop(null); + _currentPosition -= 1; + } + assert(_currentPosition > 0); + currentRoute.didPop(result); + _currentPosition -= 1; + }); + } + + bool _debugCurrentlyHaveRoute(Route route) { + int index = _history.indexOf(route); + return index >= 0 && index <= _currentPosition; + } + + Widget build(BuildContext context) { + List visibleRoutes = new List(); + bool alreadyInsertModalBarrier = false; + for (int i = _history.length-1; i >= 0; i -= 1) { + Route route = _history[i]; + if (!route.hasContent) { + assert(!route.modal); + continue; + } + route.ensurePerformance( + direction: (i <= _currentPosition) ? Direction.forward : Direction.reverse + ); + route._onDismissed = () { + setState(() { + assert(_history.contains(route)); + _history.remove(route); + }); + }; + Key key = new ObjectKey(route); + Widget widget = route.build(key, this); + visibleRoutes.add(widget); + if (route.isActuallyOpaque) + break; + assert(route.modal || route.ephemeral); + if (route.modal && i > 0 && !alreadyInsertModalBarrier) { + visibleRoutes.add(new Listener( + onPointerDown: (_) { pop(); }, + child: new Container() + )); + alreadyInsertModalBarrier = true; + } + } + return new Focus(child: new Stack(visibleRoutes.reversed.toList())); + } +} + + +abstract class Route { + + WatchableAnimationPerformance get performance => _performance?.view; + AnimationPerformance _performance; + NotificationCallback _onDismissed; + + AnimationPerformance createPerformance() { + Duration duration = transitionDuration; + if (duration > Duration.ZERO) { + return new AnimationPerformance(duration: duration) + ..addStatusListener((AnimationStatus status) { + if (status == AnimationStatus.dismissed && _onDismissed != null) + _onDismissed(); + }); + } + return null; + } + + void ensurePerformance({ Direction direction }) { assert(direction != null); if (_performance == null) _performance = createPerformance(); - AnimationStatus desiredStatus = direction == Direction.forward ? AnimationStatus.forward : AnimationStatus.reverse; - if (_performance.status != desiredStatus) - _performance.play(direction); - return _performance.view; + if (_performance != null) { + AnimationStatus desiredStatus = direction == Direction.forward ? AnimationStatus.forward : AnimationStatus.reverse; + if (_performance.status != desiredStatus) + _performance.play(direction); + } } - bool get isActuallyOpaque => _performance != null && _performance.isCompleted && isOpaque; - bool get hasContent => true; // set to false if you have nothing useful to return from build() + /// If hasContent is true, then the route represents some on-screen state. + /// + /// If hasContent is false, then no performance will be created, and the values of + /// ephemeral, modal, and opaque are ignored. This is useful if the route + /// represents some state handled by another widget. See + /// NavigatorState.pushState(). + /// + /// Set hasContent to false if you have nothing useful to return from build(). + /// + /// modal must be false if hasContent is false, since otherwise any + /// interaction with the system at all would imply that the current route is + /// popped, which would be pointless. + bool get hasContent => true; - Duration get transitionDuration; - bool get isOpaque; - Widget build(Key key, Navigator navigator, WatchableAnimationPerformance performance); - void popState([dynamic result]) { assert(result == null); } + /// If ephemeral is true, then to explicitly pop the route you have to use + /// navigator.popRoute() with a reference to this route. navigator.pop() + /// automatically pops all ephemeral routes before popping the current + /// top-most non-ephemeral route. + /// + /// If ephemeral is false, then the route can be popped with navigator.pop(). + /// + /// Set ephemeral to true if you want to be automatically popped when another + /// route is pushed or popped. + /// + /// modal must be true if ephemeral is false. + bool get ephemeral => false; + + /// If modal is true, a hidden layer is inserted in the widget tree that + /// catches all touches to widgets created by routes below this one, even if + /// this one is transparent. + /// + /// If modal is false, then earlier routes can be interacted with, including + /// causing new routes to be pushed and/or this route (and maybe others) to be + /// popped. + /// + /// ephemeral must be true if modal is false. + /// hasContent must be true if modal is true. + bool get modal => true; + + /// If opaque is true, then routes below this one will not be built or painted + /// when the transition to this route is complete. + /// + /// If opaque is false, then the previous route will always be painted even if + /// this route's transition is complete. + /// + /// Set this to true if there's no reason to build and paint the route behind + /// you when your transition is finished, and set it to false if you do not + /// cover the entire application surface or are in any way semi-transparent. + bool get opaque => false; + + /// If this is set to a non-zero [Duration], then an [AnimationPerformance] + /// object, available via the performance field, will be created when the + /// route is first built, using the duration described here. + Duration get transitionDuration => Duration.ZERO; + + bool get isActuallyOpaque => (performance == null || _performance.isCompleted) && opaque; + + Widget build(Key key, NavigatorState navigator); + void didPop([dynamic result]) { + if (performance == null && _onDismissed != null) + _onDismissed(); + } String toString() => '$runtimeType()'; } const Duration _kTransitionDuration = const Duration(milliseconds: 150); const Point _kTransitionStartPoint = const Point(0.0, 75.0); -class Route extends RouteBase { - Route({ this.name, this.builder }); - final String name; +class PageRoute extends Route { + PageRoute(this.builder); + final RouteBuilder builder; - bool get isOpaque => true; + bool get opaque => true; Duration get transitionDuration => _kTransitionDuration; - Widget build(Key key, Navigator navigator, WatchableAnimationPerformance performance) { + Widget build(Key key, NavigatorState navigator) { // TODO(jackson): Hit testing should ignore transform // TODO(jackson): Block input unless content is interactive return new SlideTransition( @@ -81,138 +273,25 @@ class Route extends RouteBase { ) ); } - - String toString() => '$runtimeType(name="$name")'; } -class RouteState extends RouteBase { - RouteState({ this.callback, this.route, this.owner }); +class RouteState extends Route { + RouteState({ this.route, this.owner, this.callback }); - Function callback; - RouteBase route; - StatefulComponent owner; + Route route; + State owner; + RouteStateCallback callback; - bool get isOpaque => false; + bool get hasContent => false; + bool get modal => false; + bool get opaque => false; - void popState([dynamic result]) { + void didPop([dynamic result]) { assert(result == null); if (callback != null) callback(this); + super.didPop(result); } - bool get hasContent => false; - Duration get transitionDuration => const Duration(); - Widget build(Key key, Navigator navigator, WatchableAnimationPerformance performance) => null; -} - -class NavigationState { - - NavigationState(List routes) { - for (Route route in routes) { - if (route.name != null) - namedRoutes[route.name] = route; - } - history.add(routes[0]); - } - - List history = new List(); - int historyIndex = 0; - Map namedRoutes = new Map(); - - RouteBase get currentRoute => history[historyIndex]; - bool hasPrevious() => historyIndex > 0; - - void pushNamed(String name) { - Route route = namedRoutes[name]; - assert(route != null); - push(route); - } - - void push(RouteBase route) { - assert(!_debugCurrentlyHaveRoute(route)); - history.insert(historyIndex + 1, route); - historyIndex++; - } - - void pop([dynamic result]) { - if (historyIndex > 0) { - RouteBase route = history[historyIndex]; - route.popState(result); - historyIndex--; - } - } - - bool _debugCurrentlyHaveRoute(RouteBase route) { - return history.any((candidate) => candidate == route); - } -} - -class Navigator extends StatefulComponent { - - Navigator(this.state, { Key key }) : super(key: key); - - NavigationState state; - - void syncConstructorArguments(Navigator source) { - state = source.state; - } - - RouteBase get currentRoute => state.currentRoute; - - void pushState(StatefulComponent owner, Function callback) { - RouteBase route = new RouteState( - owner: owner, - callback: callback, - route: state.currentRoute - ); - push(route); - } - - void pushNamed(String name) { - setState(() { - state.pushNamed(name); - }); - } - - void push(RouteBase route) { - setState(() { - state.push(route); - }); - } - - void pop([dynamic result]) { - setState(() { - state.pop(result); - }); - } - - Widget build() { - List visibleRoutes = new List(); - for (int i = state.history.length-1; i >= 0; i -= 1) { - RouteBase route = state.history[i]; - if (!route.hasContent) - continue; - WatchableAnimationPerformance performance = route.ensurePerformance( - direction: (i <= state.historyIndex) ? Direction.forward : Direction.reverse - ); - route.onDismissed = () { - setState(() { - assert(state.history.contains(route)); - state.history.remove(route); - }); - }; - Key key = new ObjectKey(route); - Widget widget = route.build(key, this, performance); - visibleRoutes.add(widget); - if (route.isActuallyOpaque) - break; - } - if (visibleRoutes.length > 1) { - visibleRoutes.insert(1, new Listener( - onPointerDown: (_) { pop(); }, - child: new Container() - )); - } - return new Focus(child: new Stack(visibleRoutes.reversed.toList())); - } + Widget build(Key key, NavigatorState navigator) => null; } diff --git a/packages/flutter/lib/src/widgets/popup_menu.dart b/packages/flutter/lib/src/widgets/popup_menu.dart index 54fcc128b4..60e02929d5 100644 --- a/packages/flutter/lib/src/widgets/popup_menu.dart +++ b/packages/flutter/lib/src/widgets/popup_menu.dart @@ -6,14 +6,16 @@ import 'dart:async'; import 'dart:sky' as sky; import 'package:sky/animation.dart'; -import 'package:sky/painting.dart'; import 'package:sky/material.dart'; +import 'package:sky/painting.dart'; import 'package:sky/src/widgets/basic.dart'; import 'package:sky/src/widgets/focus.dart'; import 'package:sky/src/widgets/framework.dart'; +import 'package:sky/src/widgets/gesture_detector.dart'; import 'package:sky/src/widgets/navigator.dart'; import 'package:sky/src/widgets/popup_menu_item.dart'; import 'package:sky/src/widgets/scrollable.dart'; +import 'package:sky/src/widgets/theme.dart'; import 'package:sky/src/widgets/transitions.dart'; const Duration _kMenuDuration = const Duration(milliseconds: 300); @@ -25,8 +27,9 @@ const double _kMenuMaxWidth = 5.0 * _kMenuWidthStep; const double _kMenuHorizontalPadding = 16.0; const double _kMenuVerticalPadding = 8.0; -class PopupMenu extends StatefulComponent { +typedef List PopupMenuItemsBuilder(NavigatorState navigator); +class PopupMenu extends StatefulComponent { PopupMenu({ Key key, this.items, @@ -38,49 +41,30 @@ class PopupMenu extends StatefulComponent { assert(performance != null); } - List items; - int level; - Navigator navigator; - WatchableAnimationPerformance performance; + final List items; + final int level; + final NavigatorState navigator; + final WatchableAnimationPerformance performance; - BoxPainter _painter; + PopupMenuState createState() => new PopupMenuState(); +} +class PopupMenuState extends State { void initState() { - _updateBoxPainter(); + super.initState(); + config.performance.addListener(_performanceChanged); } - void _updateBoxPainter() { - _painter = new BoxPainter( - new BoxDecoration( - backgroundColor: Colors.grey[50], - borderRadius: 2.0, - boxShadow: shadows[level] - ) - ); - } - - void syncConstructorArguments(PopupMenu source) { - items = source.items; - if (level != source.level) { - level = source.level; - _updateBoxPainter(); + void didUpdateConfig(PopupMenu oldConfig) { + if (config.performance != oldConfig.performance) { + oldConfig.performance.removeListener(_performanceChanged); + config.performance.addListener(_performanceChanged); } - navigator = source.navigator; - if (mounted) - performance.removeListener(_performanceChanged); - performance = source.performance; - if (mounted) - performance.addListener(_performanceChanged); } - void didMount() { - performance.addListener(_performanceChanged); - super.didMount(); - } - - void didUnmount() { - performance.removeListener(_performanceChanged); - super.didMount(); + void dispose() { + config.performance.removeListener(_performanceChanged); + super.dispose(); } void _performanceChanged() { @@ -89,34 +73,44 @@ class PopupMenu extends StatefulComponent { }); } - void itemPressed(PopupMenuItem item) { - if (navigator != null) - navigator.pop(item.value); + BoxPainter _painter; + + void _updateBoxPainter(BoxDecoration decoration) { + if (_painter == null || _painter.decoration != decoration) + _painter = new BoxPainter(decoration); } - Widget build() { - double unit = 1.0 / (items.length + 1.5); // 1.0 for the width and 0.5 for the last item's fade. + Widget build(BuildContext context) { + _updateBoxPainter(new BoxDecoration( + backgroundColor: Theme.of(context).canvasColor, + borderRadius: 2.0, + boxShadow: shadows[config.level] + )); + double unit = 1.0 / (config.items.length + 1.5); // 1.0 for the width and 0.5 for the last item's fade. List children = []; - for (int i = 0; i < items.length; ++i) { + for (int i = 0; i < config.items.length; ++i) { double start = (i + 1) * unit; double end = (start + 1.5 * unit).clamp(0.0, 1.0); children.add(new FadeTransition( - performance: performance, + performance: config.performance, opacity: new AnimatedValue(0.0, end: 1.0, interval: new Interval(start, end)), - child: items[i]) + child: new GestureDetector( + onTap: () { config.navigator.pop(config.items[i].value); }, + child: config.items[i] + )) ); } final width = new AnimatedValue(0.0, end: 1.0, interval: new Interval(0.0, unit)); - final height = new AnimatedValue(0.0, end: 1.0, interval: new Interval(0.0, unit * items.length)); + final height = new AnimatedValue(0.0, end: 1.0, interval: new Interval(0.0, unit * config.items.length)); return new FadeTransition( - performance: performance, + performance: config.performance, opacity: new AnimatedValue(0.0, end: 1.0, interval: new Interval(0.0, 1.0 / 3.0)), child: new Container( margin: new EdgeDims.all(_kMenuMargin), child: new BuilderTransition( - performance: performance, + performance: config.performance, variables: [width, height], - builder: () { + builder: (BuildContext context) { return new CustomPaint( callback: (sky.Canvas canvas, Size size) { double widthValue = width.value * size.width; @@ -147,7 +141,6 @@ class PopupMenu extends StatefulComponent { ) ); } - } class MenuPosition { @@ -158,7 +151,7 @@ class MenuPosition { final double left; } -class MenuRoute extends RouteBase { +class MenuRoute extends Route { MenuRoute({ this.completer, this.position, this.builder, this.level }); final Completer completer; @@ -174,9 +167,12 @@ class MenuRoute extends RouteBase { return result; } + bool get ephemeral => false; // we could make this true, but then we'd have to use popRoute(), not pop(), in menus + bool get modal => true; + Duration get transitionDuration => _kMenuDuration; - bool get isOpaque => false; - Widget build(Key key, Navigator navigator, WatchableAnimationPerformance performance) { + bool get opaque => false; + Widget build(Key key, NavigatorState navigator) { return new Positioned( top: position?.top, right: position?.right, @@ -196,14 +192,13 @@ class MenuRoute extends RouteBase { ); } - void popState([dynamic result]) { + void didPop([dynamic result]) { completer.complete(result); + super.didPop(result); } } -typedef List PopupMenuItemsBuilder(Navigator navigator); - -Future showMenu({ Navigator navigator, MenuPosition position, PopupMenuItemsBuilder builder, int level: 4 }) { +Future showMenu({ NavigatorState navigator, MenuPosition position, PopupMenuItemsBuilder builder, int level: 4 }) { Completer completer = new Completer(); navigator.push(new MenuRoute( completer: completer, diff --git a/packages/flutter/lib/src/widgets/popup_menu_item.dart b/packages/flutter/lib/src/widgets/popup_menu_item.dart index f55cad2aaa..1e44c23c2d 100644 --- a/packages/flutter/lib/src/widgets/popup_menu_item.dart +++ b/packages/flutter/lib/src/widgets/popup_menu_item.dart @@ -2,58 +2,33 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:sky/painting.dart'; import 'package:sky/src/widgets/basic.dart'; -import 'package:sky/src/widgets/default_text_style.dart'; import 'package:sky/src/widgets/framework.dart'; -import 'package:sky/src/widgets/gesture_detector.dart'; import 'package:sky/src/widgets/ink_well.dart'; -import 'package:sky/src/widgets/popup_menu.dart'; import 'package:sky/src/widgets/theme.dart'; const double _kMenuItemHeight = 48.0; const double _kBaselineOffsetFromBottom = 20.0; -class PopupMenuItem extends Component { +class PopupMenuItem extends StatelessComponent { PopupMenuItem({ Key key, - this.onPressed, this.value, this.child }) : super(key: key); final Widget child; - final Function onPressed; final dynamic value; - TextStyle get textStyle => Theme.of(this).text.subhead; - - PopupMenu findAncestorPopupMenu() { - Widget ancestor = parent; - while (ancestor != null && ancestor is! PopupMenu) - ancestor = ancestor.parent; - return ancestor; - } - - void handlePressed() { - if (onPressed != null) - onPressed(); - PopupMenu menu = findAncestorPopupMenu(); - menu?.itemPressed(this); - } - - Widget build() { - return new GestureDetector( - onTap: handlePressed, - child: new InkWell( - child: new Container( - height: _kMenuItemHeight, - child: new DefaultTextStyle( - style: textStyle, - child: new Baseline( - baseline: _kMenuItemHeight - _kBaselineOffsetFromBottom, - child: child - ) + Widget build(BuildContext context) { + return new InkWell( + child: new Container( + height: _kMenuItemHeight, + child: new DefaultTextStyle( + style: Theme.of(context).text.subhead, + child: new Baseline( + baseline: _kMenuItemHeight - _kBaselineOffsetFromBottom, + child: child ) ) ) diff --git a/packages/flutter/lib/src/widgets/progress_indicator.dart b/packages/flutter/lib/src/widgets/progress_indicator.dart index 9b225ac15e..d6c86ef72f 100644 --- a/packages/flutter/lib/src/widgets/progress_indicator.dart +++ b/packages/flutter/lib/src/widgets/progress_indicator.dart @@ -22,19 +22,28 @@ abstract class ProgressIndicator extends StatefulComponent { this.bufferValue }) : super(key: key); - double value; // Null for non-determinate progress indicator. - double bufferValue; // TODO(hansmuller) implement the support for this. + final double value; // Null for non-determinate progress indicator. + final double bufferValue; // TODO(hansmuller) implement the support for this. - AnimationPerformance _performance; - double get _performanceValue => (_performance.variable as AnimatedValue).value; - Color get _backgroundColor => Theme.of(this).primarySwatch[200]; - Color get _valueColor => Theme.of(this).primaryColor; - Object get _customPaintToken => value != null ? value : _performanceValue; + Color _getBackgroundColor(BuildContext context) => Theme.of(context).primarySwatch[200]; + Color _getValueColor(BuildContext context) => Theme.of(context).primaryColor; + Object _getCustomPaintToken(double performanceValue) => value != null ? value : performanceValue; + + Widget _buildIndicator(BuildContext context, double performanceValue); + + ProgressIndicatorState createState() => new ProgressIndicatorState(); +} + +class ProgressIndicatorState extends State { + + ValueAnimation _performance; void initState() { - _performance = new AnimationPerformance() - ..duration = const Duration(milliseconds: 1500) - ..variable = new AnimatedValue(0.0, end: 1.0, curve: ease); + super.initState(); + _performance = new ValueAnimation( + variable: new AnimatedValue(0.0, end: 1.0, curve: ease), + duration: const Duration(milliseconds: 1500) + ); _performance.addStatusListener((AnimationStatus status) { if (status == AnimationStatus.completed) _restartAnimation(); @@ -42,28 +51,23 @@ abstract class ProgressIndicator extends StatefulComponent { _performance.play(); } - void syncConstructorArguments(ProgressIndicator source) { - value = source.value; - bufferValue = source.bufferValue; - } - void _restartAnimation() { _performance.progress = 0.0; _performance.play(); } - Widget build() { - if (value != null) - return _buildIndicator(); + Widget build(BuildContext context) { + if (config.value != null) + return config._buildIndicator(context, _performance.value); return new BuilderTransition( variables: [_performance.variable], performance: _performance.view, - builder: _buildIndicator + builder: (BuildContext context) { + return config._buildIndicator(context, _performance.value); + } ); } - - Widget _buildIndicator(); } class LinearProgressIndicator extends ProgressIndicator { @@ -73,18 +77,18 @@ class LinearProgressIndicator extends ProgressIndicator { double bufferValue }) : super(key: key, value: value, bufferValue: bufferValue); - void _paint(sky.Canvas canvas, Size size) { + void _paint(BuildContext context, double performanceValue, sky.Canvas canvas, Size size) { Paint paint = new Paint() - ..color = _backgroundColor + ..color = _getBackgroundColor(context) ..setStyle(sky.PaintingStyle.fill); canvas.drawRect(Point.origin & size, paint); - paint.color = _valueColor; + paint.color = _getValueColor(context); if (value != null) { double width = value.clamp(0.0, 1.0) * size.width; canvas.drawRect(Point.origin & new Size(width, size.height), paint); } else { - double startX = size.width * (1.5 * _performanceValue - 0.5); + double startX = size.width * (1.5 * performanceValue - 0.5); double endX = startX + 0.5 * size.width; double x = startX.clamp(0.0, size.width); double width = endX.clamp(0.0, size.width) - x; @@ -92,12 +96,17 @@ class LinearProgressIndicator extends ProgressIndicator { } } - Widget _buildIndicator() { + Widget _buildIndicator(BuildContext context, double performanceValue) { return new Container( - child: new CustomPaint(callback: _paint, token: _customPaintToken), constraints: new BoxConstraints.tightFor( width: double.INFINITY, height: _kLinearProgressIndicatorHeight + ), + child: new CustomPaint( + token: _getCustomPaintToken(performanceValue), + callback: (sky.Canvas canvas, Size size) { + _paint(context, performanceValue, canvas, size); + } ) ); } @@ -116,9 +125,9 @@ class CircularProgressIndicator extends ProgressIndicator { double bufferValue }) : super(key: key, value: value, bufferValue: bufferValue); - void _paint(sky.Canvas canvas, Size size) { + void _paint(BuildContext context, double performanceValue, sky.Canvas canvas, Size size) { Paint paint = new Paint() - ..color = _valueColor + ..color = _getValueColor(context) ..strokeWidth = _kCircularProgressIndicatorStrokeWidth ..setStyle(sky.PaintingStyle.stroke); @@ -128,7 +137,7 @@ class CircularProgressIndicator extends ProgressIndicator { ..arcTo(Point.origin & size, _kStartAngle, angle, false); canvas.drawPath(path, paint); } else { - double startAngle = _kTwoPI * (1.75 * _performanceValue - 0.75); + double startAngle = _kTwoPI * (1.75 * performanceValue - 0.75); double endAngle = startAngle + _kTwoPI * 0.75; double arcAngle = startAngle.clamp(0.0, _kTwoPI); double arcSweep = endAngle.clamp(0.0, _kTwoPI) - arcAngle; @@ -138,12 +147,17 @@ class CircularProgressIndicator extends ProgressIndicator { } } - Widget _buildIndicator() { + Widget _buildIndicator(BuildContext context, double performanceValue) { return new Container( - child: new CustomPaint(callback: _paint, token: _customPaintToken), constraints: new BoxConstraints( minWidth: _kMinCircularProgressIndicatorSize, minHeight: _kMinCircularProgressIndicatorSize + ), + child: new CustomPaint( + token: _getCustomPaintToken(performanceValue), + callback: (sky.Canvas canvas, Size size) { + _paint(context, performanceValue, canvas, size); + } ) ); } diff --git a/packages/flutter/lib/src/widgets/radio.dart b/packages/flutter/lib/src/widgets/radio.dart index 6592ee9b77..ab51bea716 100644 --- a/packages/flutter/lib/src/widgets/radio.dart +++ b/packages/flutter/lib/src/widgets/radio.dart @@ -4,9 +4,7 @@ import 'dart:sky' as sky; -import 'package:sky/src/rendering/object.dart'; import 'package:sky/src/widgets/basic.dart'; -import 'package:sky/src/widgets/button_base.dart'; import 'package:sky/src/widgets/framework.dart'; import 'package:sky/src/widgets/gesture_detector.dart'; import 'package:sky/src/widgets/theme.dart'; @@ -16,8 +14,7 @@ const sky.Color _kDarkOffColor = const sky.Color(0xB2FFFFFF); typedef RadioValueChanged(Object value); -class Radio extends ButtonBase { - +class Radio extends StatefulComponent { Radio({ Key key, this.value, @@ -27,30 +24,27 @@ class Radio extends ButtonBase { assert(onChanged != null); } - Object value; - Object groupValue; - RadioValueChanged onChanged; + final Object value; + final Object groupValue; + final RadioValueChanged onChanged; - void syncConstructorArguments(Radio source) { - value = source.value; - groupValue = source.groupValue; - onChanged = source.onChanged; - super.syncConstructorArguments(source); - } + RadioState createState() => new RadioState(); +} - Color get color { - ThemeData themeData = Theme.of(this); - if (value == groupValue) +class RadioState extends State { + Color _getColor(BuildContext context) { + ThemeData themeData = Theme.of(context); + if (config.value == config.groupValue) return themeData.accentColor; return themeData.brightness == ThemeBrightness.light ? _kLightOffColor : _kDarkOffColor; } - Widget buildContent() { + Widget build(BuildContext context) { const double kDiameter = 16.0; const double kOuterRadius = kDiameter / 2; const double kInnerRadius = 5.0; return new GestureDetector( - onTap: () => onChanged(value), + onTap: () => config.onChanged(config.value), child: new Container( margin: const EdgeDims.symmetric(horizontal: 5.0), width: kDiameter, @@ -58,7 +52,7 @@ class Radio extends ButtonBase { child: new CustomPaint( callback: (sky.Canvas canvas, Size size) { - Paint paint = new Paint()..color = color; + Paint paint = new Paint()..color = _getColor(context); // Draw the outer circle paint.setStyle(sky.PaintingStyle.stroke); @@ -66,7 +60,7 @@ class Radio extends ButtonBase { canvas.drawCircle(const Point(kOuterRadius, kOuterRadius), kOuterRadius, paint); // Draw the inner circle - if (value == groupValue) { + if (config.value == config.groupValue) { paint.setStyle(sky.PaintingStyle.fill); canvas.drawCircle(const Point(kOuterRadius, kOuterRadius), kInnerRadius, paint); } @@ -75,5 +69,4 @@ class Radio extends ButtonBase { ) ); } - } diff --git a/packages/flutter/lib/src/widgets/raised_button.dart b/packages/flutter/lib/src/widgets/raised_button.dart index 3bddca1534..bf666f2783 100644 --- a/packages/flutter/lib/src/widgets/raised_button.dart +++ b/packages/flutter/lib/src/widgets/raised_button.dart @@ -9,7 +9,6 @@ import 'package:sky/src/widgets/material_button.dart'; import 'package:sky/src/widgets/theme.dart'; class RaisedButton extends MaterialButton { - RaisedButton({ Key key, Widget child, @@ -18,11 +17,17 @@ class RaisedButton extends MaterialButton { }) : super(key: key, child: child, enabled: enabled, - onPressed: onPressed); + onPressed: onPressed) { + assert(enabled != null); + } - Color get color { - if (enabled) { - switch (Theme.of(this).brightness) { + RaisedButtonState createState() => new RaisedButtonState(); +} + +class RaisedButtonState extends MaterialButtonState { + Color getColor(BuildContext context) { + if (config.enabled) { + switch (Theme.of(context).brightness) { case ThemeBrightness.light: if (highlight) return Colors.grey[350]; @@ -31,9 +36,9 @@ class RaisedButton extends MaterialButton { break; case ThemeBrightness.dark: if (highlight) - return Theme.of(this).primarySwatch[700]; + return Theme.of(context).primarySwatch[700]; else - return Theme.of(this).primarySwatch[600]; + return Theme.of(context).primarySwatch[600]; break; } } else { @@ -41,5 +46,5 @@ class RaisedButton extends MaterialButton { } } - int get level => enabled ? (highlight ? 2 : 1) : 0; + int get level => config.enabled ? (highlight ? 2 : 1) : 0; } diff --git a/packages/flutter/lib/src/widgets/scaffold.dart b/packages/flutter/lib/src/widgets/scaffold.dart index 186fca98cd..9e4b1e1dd5 100644 --- a/packages/flutter/lib/src/widgets/scaffold.dart +++ b/packages/flutter/lib/src/widgets/scaffold.dart @@ -102,6 +102,7 @@ class RenderScaffold extends RenderBox { void performLayout() { double bodyHeight = size.height; double bodyPosition = 0.0; + double fabOffset = 0.0; if (_slots[ScaffoldSlots.statusBar] != null) { RenderBox statusBar = _slots[ScaffoldSlots.statusBar]; statusBar.layout(new BoxConstraints.tight(new Size(size.width, kStatusBarHeight))); @@ -127,18 +128,20 @@ class RenderScaffold extends RenderBox { if (_slots[ScaffoldSlots.snackBar] != null) { RenderBox snackBar = _slots[ScaffoldSlots.snackBar]; // TODO(jackson): On tablet/desktop, minWidth = 288, maxWidth = 568 - snackBar.layout(new BoxConstraints(minWidth: size.width, maxWidth: size.width, minHeight: 0.0, maxHeight: size.height), - parentUsesSize: true); + snackBar.layout( + new BoxConstraints(minWidth: size.width, maxWidth: size.width, minHeight: 0.0, maxHeight: bodyHeight), + parentUsesSize: true + ); assert(snackBar.parentData is BoxParentData); - // Position it off-screen. SnackBar slides in with an animation. - snackBar.parentData.position = new Point(0.0, size.height); + snackBar.parentData.position = new Point(0.0, bodyPosition + bodyHeight - snackBar.size.height); + fabOffset += snackBar.size.height; } if (_slots[ScaffoldSlots.floatingActionButton] != null) { RenderBox floatingActionButton = _slots[ScaffoldSlots.floatingActionButton]; Size area = new Size(size.width - kButtonX, size.height - kButtonY); floatingActionButton.layout(new BoxConstraints.loose(area), parentUsesSize: true); assert(floatingActionButton.parentData is BoxParentData); - floatingActionButton.parentData.position = (area - floatingActionButton.size).toPoint(); + floatingActionButton.parentData.position = (area - floatingActionButton.size).toPoint() + new Offset(0.0, -fabOffset); } if (_slots[ScaffoldSlots.drawer] != null) { RenderBox drawer = _slots[ScaffoldSlots.drawer]; @@ -174,8 +177,7 @@ class RenderScaffold extends RenderBox { } } -class Scaffold extends RenderObjectWrapper { - +class Scaffold extends RenderObjectWidget { Scaffold({ Key key, Widget body, @@ -185,47 +187,66 @@ class Scaffold extends RenderObjectWrapper { Widget floatingActionButton, Widget drawer }) : super(key: key) { - _slots[ScaffoldSlots.body] = body; - _slots[ScaffoldSlots.statusBar] = statusBar; - _slots[ScaffoldSlots.toolbar] = toolbar; - _slots[ScaffoldSlots.snackBar] = snackBar; - _slots[ScaffoldSlots.floatingActionButton] = floatingActionButton; - _slots[ScaffoldSlots.drawer] = drawer; + _children[ScaffoldSlots.body] = body; + _children[ScaffoldSlots.statusBar] = statusBar; + _children[ScaffoldSlots.toolbar] = toolbar; + _children[ScaffoldSlots.snackBar] = snackBar; + _children[ScaffoldSlots.floatingActionButton] = floatingActionButton; + _children[ScaffoldSlots.drawer] = drawer; } - Map _slots = new Map(); + final Map _children = new Map(); + + RenderScaffold createRenderObject() => new RenderScaffold(); + + ScaffoldElement createElement() => new ScaffoldElement(this); +} + +class ScaffoldElement extends RenderObjectElement { + ScaffoldElement(Scaffold widget) : super(widget); + + Map _children; RenderScaffold get renderObject => super.renderObject; - RenderScaffold createNode() => new RenderScaffold(); - void walkChildren(WidgetTreeWalker walker) { + void visitChildren(ElementVisitor visitor) { for (ScaffoldSlots slot in ScaffoldSlots.values) { - Widget widget = _slots[slot]; - if (widget != null) - walker(widget); + Element element = _children[slot]; + if (element != null) + visitor(element); } } - void insertChildRenderObject(RenderObjectWrapper child, ScaffoldSlots slot) { - renderObject[slot] = child?.renderObject; - } - - void detachChildRenderObject(RenderObjectWrapper child) { - final renderObject = this.renderObject; // TODO(ianh): Remove this once the analyzer is cleverer - assert(renderObject is RenderScaffold); - assert(renderObject == child.renderObject.parent); - renderObject.remove(child.renderObject); - assert(renderObject == this.renderObject); // TODO(ianh): Remove this once the analyzer is cleverer - } - - void syncRenderObject(Widget old) { - super.syncRenderObject(old); + void mount(Element parent, dynamic newSlot) { + super.mount(parent, newSlot); + _children = new Map(); for (ScaffoldSlots slot in ScaffoldSlots.values) { - Widget widget = _slots[slot]; - _slots[slot] = syncChild(widget, old is Scaffold ? old._slots[slot] : null, slot); - assert((_slots[slot] == null) == (widget == null)); - assert(_slots[slot] == null || _slots[slot].parent == this); + Element newChild = widget._children[slot]?.createElement(); + _children[slot] = newChild; + newChild?.mount(this, slot); } } + void update(Scaffold newWidget) { + super.update(newWidget); + assert(widget == newWidget); + for (ScaffoldSlots slot in ScaffoldSlots.values) { + _children[slot] = updateChild(_children[slot], widget._children[slot], slot); + assert((_children[slot] == null) == (widget._children[slot] == null)); + } + } + + void insertChildRenderObject(RenderObject child, ScaffoldSlots slot) { + renderObject[slot] = child; + } + + void moveChildRenderObject(RenderObject child, dynamic slot) { + removeChildRenderObject(child); + insertChildRenderObject(child, slot); + } + + void removeChildRenderObject(RenderObject child) { + assert(renderObject == child.parent); + renderObject.remove(child); + } } diff --git a/packages/flutter/lib/src/widgets/scrollable.dart b/packages/flutter/lib/src/widgets/scrollable.dart index 3f4a721ffd..f5ac199d25 100644 --- a/packages/flutter/lib/src/widgets/scrollable.dart +++ b/packages/flutter/lib/src/widgets/scrollable.dart @@ -9,45 +9,48 @@ import 'dart:sky' as sky; import 'package:newton/newton.dart'; import 'package:sky/animation.dart'; import 'package:sky/gestures.dart'; -import 'package:sky/src/rendering/box.dart'; -import 'package:sky/src/rendering/viewport.dart'; +import 'package:sky/rendering.dart'; import 'package:sky/src/widgets/basic.dart'; import 'package:sky/src/widgets/framework.dart'; import 'package:sky/src/widgets/gesture_detector.dart'; import 'package:sky/src/widgets/homogeneous_viewport.dart'; import 'package:sky/src/widgets/mixed_viewport.dart'; -export 'package:sky/src/widgets/mixed_viewport.dart' show MixedViewportLayoutState; - // The gesture velocity properties are pixels/second, config min,max limits are pixels/ms const double _kMillisecondsPerSecond = 1000.0; const double _kMinFlingVelocity = -kMaxFlingVelocity * _kMillisecondsPerSecond; const double _kMaxFlingVelocity = kMaxFlingVelocity * _kMillisecondsPerSecond; -typedef void ScrollListener(); +typedef void ScrollListener(double scrollOffset); +typedef double SnapOffsetCallback(double scrollOffset); /// A base class for scrollable widgets that reacts to user input and generates /// a scrollOffset. abstract class Scrollable extends StatefulComponent { - Scrollable({ Key key, this.initialScrollOffset, - this.scrollDirection: ScrollDirection.vertical + this.scrollDirection: ScrollDirection.vertical, + this.onScroll, + this.snapOffsetCallback, + this.snapAlignmentOffset: 0.0 }) : super(key: key) { assert(scrollDirection == ScrollDirection.vertical || scrollDirection == ScrollDirection.horizontal); } - double initialScrollOffset; - ScrollDirection scrollDirection; - - AnimatedSimulation _toEndAnimation; // See _startToEndAnimation() - ValueAnimation _toOffsetAnimation; // Started by scrollTo() + final double initialScrollOffset; + final ScrollDirection scrollDirection; + final ScrollListener onScroll; + final SnapOffsetCallback snapOffsetCallback; + final double snapAlignmentOffset; +} +abstract class ScrollableState extends State { void initState() { - if (initialScrollOffset is double) - _scrollOffset = initialScrollOffset; + super.initState(); + if (config.initialScrollOffset is double) + _scrollOffset = config.initialScrollOffset; _toEndAnimation = new AnimatedSimulation(_setScrollOffset); _toOffsetAnimation = new ValueAnimation() ..addListener(() { @@ -56,15 +59,14 @@ abstract class Scrollable extends StatefulComponent { }); } - void syncConstructorArguments(Scrollable source) { - scrollDirection = source.scrollDirection; - } + AnimatedSimulation _toEndAnimation; // See _startToEndAnimation() + ValueAnimation _toOffsetAnimation; // Started by scrollTo() double _scrollOffset = 0.0; double get scrollOffset => _scrollOffset; Offset get scrollOffsetVector { - if (scrollDirection == ScrollDirection.horizontal) + if (config.scrollDirection == ScrollDirection.horizontal) return new Offset(scrollOffset, 0.0); return new Offset(0.0, scrollOffset); } @@ -77,33 +79,33 @@ abstract class Scrollable extends StatefulComponent { return _scrollBehavior; } - Widget buildContent(); - GestureDragUpdateCallback _getDragUpdateHandler(ScrollDirection direction) { - if (scrollDirection != direction || !scrollBehavior.isScrollable) + if (config.scrollDirection != direction || !scrollBehavior.isScrollable) return null; return _handleDragUpdate; } GestureDragEndCallback _getDragEndHandler(ScrollDirection direction) { - if (scrollDirection != direction || !scrollBehavior.isScrollable) + if (config.scrollDirection != direction || !scrollBehavior.isScrollable) return null; return _handleDragEnd; } - Widget build() { + Widget build(BuildContext context) { return new GestureDetector( onVerticalDragUpdate: _getDragUpdateHandler(ScrollDirection.vertical), onVerticalDragEnd: _getDragEndHandler(ScrollDirection.vertical), onHorizontalDragUpdate: _getDragUpdateHandler(ScrollDirection.horizontal), onHorizontalDragEnd: _getDragEndHandler(ScrollDirection.horizontal), child: new Listener( - child: buildContent(), + child: buildContent(context), onPointerDown: _handlePointerDown ) ); } + Widget buildContent(BuildContext context); + Future _startToOffsetAnimation(double newScrollOffset, Duration duration, Curve curve) { _stopAnimations(); _toOffsetAnimation @@ -123,16 +125,57 @@ abstract class Scrollable extends StatefulComponent { _toEndAnimation.stop(); } - void _startToEndAnimation({ double velocity: 0.0 }) { - _stopAnimations(); - Simulation simulation = scrollBehavior.createFlingScrollSimulation(scrollOffset, velocity); - if (simulation != null) - _toEndAnimation.start(simulation); + bool _scrollOffsetIsInBounds(double offset) { + if (scrollBehavior is! ExtentScrollBehavior) + return false; + ExtentScrollBehavior behavior = scrollBehavior; + return offset >= behavior.minScrollOffset && offset < behavior.maxScrollOffset; } - void didUnmount() { + Simulation _createFlingSimulation(double velocity) { + return scrollBehavior.createFlingScrollSimulation(scrollOffset, velocity); + } + + Simulation _createSnapSimulation(double velocity) { + if (velocity == null || config.snapOffsetCallback == null || !_scrollOffsetIsInBounds(scrollOffset)) + return null; + + Simulation simulation = _createFlingSimulation(velocity); + if (simulation == null) + return null; + + double endScrollOffset = simulation.x(double.INFINITY); + if (endScrollOffset.isNaN) + return null; + + double snappedScrollOffset = config.snapOffsetCallback(endScrollOffset + config.snapAlignmentOffset); + double alignedScrollOffset = snappedScrollOffset - config.snapAlignmentOffset; + if (!_scrollOffsetIsInBounds(alignedScrollOffset)) + return null; + + double snapVelocity = velocity.abs() * (alignedScrollOffset - scrollOffset).sign; + Simulation toSnapSimulation = + scrollBehavior.createSnapScrollSimulation(scrollOffset, alignedScrollOffset, snapVelocity); + if (toSnapSimulation == null) + return null; + + double offsetMin = math.min(scrollOffset, alignedScrollOffset); + double offsetMax = math.max(scrollOffset, alignedScrollOffset); + return new ClampedSimulation(toSnapSimulation, xMin: offsetMin, xMax: offsetMax); + } + + Future _startToEndAnimation({ double velocity }) { _stopAnimations(); - super.didUnmount(); + Simulation simulation = + _createSnapSimulation(velocity) ?? _createFlingSimulation(velocity ?? 0.0); + if (simulation == null) + return new Future.value(); + return _toEndAnimation.start(simulation); + } + + void dispose() { + _stopAnimations(); + super.dispose(); } void _setScrollOffset(double newScrollOffset) { @@ -141,8 +184,8 @@ abstract class Scrollable extends StatefulComponent { setState(() { _scrollOffset = newScrollOffset; }); - if (_listeners.length > 0) - _notifyListeners(); + if (config.onScroll != null) + config.onScroll(_scrollOffset); } Future scrollTo(double newScrollOffset, { Duration duration, Curve curve: ease }) { @@ -163,20 +206,20 @@ abstract class Scrollable extends StatefulComponent { return scrollTo(newScrollOffset, duration: duration, curve: curve); } - void fling(Offset velocity) { - if (velocity != Offset.zero) { - _startToEndAnimation(velocity: _scrollVelocity(velocity)); - } else if (!_toEndAnimation.isAnimating && (_toOffsetAnimation == null || !_toOffsetAnimation.isAnimating)) { - settleScrollOffset(); - } + Future fling(Offset velocity) { + if (velocity != Offset.zero) + return _startToEndAnimation(velocity: _scrollVelocity(velocity)); + if (!_toEndAnimation.isAnimating && (_toOffsetAnimation == null || !_toOffsetAnimation.isAnimating)) + return settleScrollOffset(); + return new Future.value(); } - void settleScrollOffset() { - _startToEndAnimation(); + Future settleScrollOffset() { + return _startToEndAnimation(); } double _scrollVelocity(sky.Offset velocity) { - double scrollVelocity = scrollDirection == ScrollDirection.horizontal + double scrollVelocity = config.scrollDirection == ScrollDirection.horizontal ? -velocity.dx : -velocity.dy; return scrollVelocity.clamp(_kMinFlingVelocity, _kMaxFlingVelocity) / _kMillisecondsPerSecond; @@ -195,54 +238,55 @@ abstract class Scrollable extends StatefulComponent { void _handleDragEnd(Offset velocity) { fling(velocity); } - - final List _listeners = new List(); - void addListener(ScrollListener listener) { - _listeners.add(listener); - } - - void removeListener(ScrollListener listener) { - _listeners.remove(listener); - } - - void _notifyListeners() { - List localListeners = new List.from(_listeners); - for (ScrollListener listener in localListeners) - listener(); - } } -Scrollable findScrollableAncestor({ Widget target }) { - Widget ancestor = target; - while (ancestor != null && ancestor is! Scrollable) - ancestor = ancestor.parent; - return ancestor; +ScrollableState findScrollableAncestor(BuildContext context) { + ScrollableState result; + context.visitAncestorElements((Element element) { + if (element is StatefulComponentElement) { + if (element.state is ScrollableState) { + result = element.state; + return false; + } + } + return true; + }); + return result; } -Future ensureWidgetIsVisible(Widget target, { Duration duration, Curve curve }) { - assert(target.mounted); - assert(target.renderObject is RenderBox); +Future ensureWidgetIsVisible(BuildContext context, { Duration duration, Curve curve }) { + assert(context.findRenderObject() is RenderBox); + // TODO(abarth): This function doesn't handle nested scrollable widgets. - Scrollable scrollable = findScrollableAncestor(target: target); + ScrollableState scrollable = findScrollableAncestor(context); if (scrollable == null) return new Future.value(); - Size targetSize = (target.renderObject as RenderBox).size; - Point targetCenter = target.localToGlobal( - scrollable.scrollDirection == ScrollDirection.vertical - ? new Point(0.0, targetSize.height / 2.0) - : new Point(targetSize.width / 2.0, 0.0) - ); + RenderBox targetBox = context.findRenderObject(); + assert(targetBox.attached); + Size targetSize = targetBox.size; + + RenderBox scrollableBox = scrollable.context.findRenderObject(); + assert(scrollableBox.attached); + Size scrollableSize = scrollableBox.size; + + double scrollOffsetDelta; + switch (scrollable.config.scrollDirection) { + case ScrollDirection.vertical: + Point targetCenter = targetBox.localToGlobal(new Point(0.0, targetSize.height / 2.0)); + Point scrollableCenter = scrollableBox.localToGlobal(new Point(0.0, scrollableSize.height / 2.0)); + scrollOffsetDelta = targetCenter.y - scrollableCenter.y; + break; + case ScrollDirection.horizontal: + Point targetCenter = targetBox.localToGlobal(new Point(targetSize.width / 2.0, 0.0)); + Point scrollableCenter = scrollableBox.localToGlobal(new Point(scrollableSize.width / 2.0, 0.0)); + scrollOffsetDelta = targetCenter.x - scrollableCenter.x; + break; + case ScrollDirection.both: + assert(false); // See https://github.com/flutter/engine/issues/888 + break; + } - Size scrollableSize = (scrollable.renderObject as RenderBox).size; - Point scrollableCenter = scrollable.localToGlobal( - scrollable.scrollDirection == ScrollDirection.vertical - ? new Point(0.0, scrollableSize.height / 2.0) - : new Point(scrollableSize.width / 2.0, 0.0) - ); - double scrollOffsetDelta = scrollable.scrollDirection == ScrollDirection.vertical - ? targetCenter.y - scrollableCenter.y - : targetCenter.x - scrollableCenter.x; ExtentScrollBehavior scrollBehavior = scrollable.scrollBehavior; double scrollOffset = (scrollable.scrollOffset + scrollOffsetDelta) .clamp(scrollBehavior.minScrollOffset, scrollBehavior.maxScrollOffset); @@ -260,33 +304,34 @@ class ScrollableViewport extends Scrollable { Key key, this.child, double initialScrollOffset, - ScrollDirection scrollDirection: ScrollDirection.vertical + ScrollDirection scrollDirection: ScrollDirection.vertical, + ScrollListener onScroll }) : super( key: key, scrollDirection: scrollDirection, - initialScrollOffset: initialScrollOffset + initialScrollOffset: initialScrollOffset, + onScroll: onScroll ); - Widget child; + final Widget child; - void syncConstructorArguments(ScrollableViewport source) { - child = source.child; - super.syncConstructorArguments(source); - } + ScrollableViewportState createState() => new ScrollableViewportState(); +} +class ScrollableViewportState extends ScrollableState { ScrollBehavior createScrollBehavior() => new OverscrollWhenScrollableBehavior(); OverscrollWhenScrollableBehavior get scrollBehavior => super.scrollBehavior; double _viewportSize = 0.0; double _childSize = 0.0; void _handleViewportSizeChanged(Size newSize) { - _viewportSize = scrollDirection == ScrollDirection.vertical ? newSize.height : newSize.width; + _viewportSize = config.scrollDirection == ScrollDirection.vertical ? newSize.height : newSize.width; setState(() { _updateScrollBehaviour(); }); } void _handleChildSizeChanged(Size newSize) { - _childSize = scrollDirection == ScrollDirection.vertical ? newSize.height : newSize.width; + _childSize = config.scrollDirection == ScrollDirection.vertical ? newSize.height : newSize.width; setState(() { _updateScrollBehaviour(); }); @@ -300,15 +345,15 @@ class ScrollableViewport extends Scrollable { )); } - Widget buildContent() { + Widget buildContent(BuildContext context) { return new SizeObserver( callback: _handleViewportSizeChanged, child: new Viewport( scrollOffset: scrollOffsetVector, - scrollDirection: scrollDirection, + scrollDirection: config.scrollDirection, child: new SizeObserver( callback: _handleChildSizeChanged, - child: child + child: config.child ) ) ); @@ -318,16 +363,18 @@ class ScrollableViewport extends Scrollable { /// A mashup of [ScrollableViewport] and [BlockBody]. Useful when you have a small, /// fixed number of children that you wish to arrange in a block layout and that /// might exceed the height of its container (and therefore need to scroll). -class Block extends Component { +class Block extends StatelessComponent { Block(this.children, { Key key, this.initialScrollOffset, - this.scrollDirection: ScrollDirection.vertical + this.scrollDirection: ScrollDirection.vertical, + this.onScroll }) : super(key: key); final List children; final double initialScrollOffset; final ScrollDirection scrollDirection; + final ScrollListener onScroll; BlockDirection get _direction { if (scrollDirection == ScrollDirection.vertical) @@ -335,10 +382,11 @@ class Block extends Component { return BlockDirection.horizontal; } - Widget build() { + Widget build(BuildContext context) { return new ScrollableViewport( initialScrollOffset: initialScrollOffset, scrollDirection: scrollDirection, + onScroll: onScroll, child: new BlockBody(children, direction: _direction) ); } @@ -354,39 +402,49 @@ abstract class ScrollableWidgetList extends Scrollable { Key key, double initialScrollOffset, ScrollDirection scrollDirection: ScrollDirection.vertical, + ScrollListener onScroll, + SnapOffsetCallback snapOffsetCallback, + double snapAlignmentOffset: 0.0, this.itemsWrap: false, this.itemExtent, this.padding - }) : super(key: key, initialScrollOffset: initialScrollOffset, scrollDirection: scrollDirection) { + }) : super( + key: key, + initialScrollOffset: initialScrollOffset, + scrollDirection: scrollDirection, + onScroll: onScroll, + snapOffsetCallback: snapOffsetCallback, + snapAlignmentOffset: snapAlignmentOffset + ) { assert(itemExtent != null); } - EdgeDims padding; - bool itemsWrap; - double itemExtent; - Size containerSize = Size.zero; + final bool itemsWrap; + final double itemExtent; + final EdgeDims padding; +} +abstract class ScrollableWidgetListState extends ScrollableState { /// Subclasses must implement `get itemCount` to tell ScrollableWidgetList /// how many items there are in the list. int get itemCount; int _previousItemCount; - void syncConstructorArguments(ScrollableWidgetList source) { - bool scrollBehaviorUpdateNeeded = - padding != source.padding || - itemExtent != source.itemExtent || - scrollDirection != source.scrollDirection; + Size _containerSize = Size.zero; - if (itemsWrap != source.itemsWrap) { + void didUpdateConfig(T oldConfig) { + super.didUpdateConfig(oldConfig); + + bool scrollBehaviorUpdateNeeded = + config.padding != oldConfig.padding || + config.itemExtent != oldConfig.itemExtent || + config.scrollDirection != oldConfig.scrollDirection; + + if (config.itemsWrap != oldConfig.itemsWrap) { _scrollBehavior = null; scrollBehaviorUpdateNeeded = true; } - padding = source.padding; - itemsWrap = source.itemsWrap; - itemExtent = source.itemExtent; - super.syncConstructorArguments(source); // update scrollDirection - if (itemCount != _previousItemCount) { scrollBehaviorUpdateNeeded = true; _previousItemCount = itemCount; @@ -400,42 +458,45 @@ abstract class ScrollableWidgetList extends Scrollable { ExtentScrollBehavior get scrollBehavior => super.scrollBehavior; double get _containerExtent { - return scrollDirection == ScrollDirection.vertical - ? containerSize.height - : containerSize.width; + return config.scrollDirection == ScrollDirection.vertical + ? _containerSize.height + : _containerSize.width; } void _handleSizeChanged(Size newSize) { setState(() { - containerSize = newSize; + _containerSize = newSize; _updateScrollBehavior(); }); } double get _leadingPadding { - if (scrollDirection == ScrollDirection.vertical) + EdgeDims padding = config.padding; + if (config.scrollDirection == ScrollDirection.vertical) return padding != null ? padding.top : 0.0; return padding != null ? padding.left : -.0; } double get _trailingPadding { - if (scrollDirection == ScrollDirection.vertical) + EdgeDims padding = config.padding; + if (config.scrollDirection == ScrollDirection.vertical) return padding != null ? padding.bottom : 0.0; return padding != null ? padding.right : 0.0; } EdgeDims get _crossAxisPadding { + EdgeDims padding = config.padding; if (padding == null) return null; - if (scrollDirection == ScrollDirection.vertical) + if (config.scrollDirection == ScrollDirection.vertical) return new EdgeDims.only(left: padding.left, right: padding.right); return new EdgeDims.only(top: padding.top, bottom: padding.bottom); } void _updateScrollBehavior() { - // if you don't call this from build() or syncConstructorArguments(), you must call it from setState(). - double contentExtent = itemExtent * itemCount; - if (padding != null) + // if you don't call this from build(), you must call it from setState(). + double contentExtent = config.itemExtent * itemCount; + if (config.padding != null) contentExtent += _leadingPadding + _trailingPadding; scrollTo(scrollBehavior.updateExtents( contentExtent: contentExtent, @@ -444,7 +505,7 @@ abstract class ScrollableWidgetList extends Scrollable { )); } - Widget buildContent() { + Widget buildContent(BuildContext context) { if (itemCount != _previousItemCount) { _previousItemCount = itemCount; _updateScrollBehavior(); @@ -456,27 +517,27 @@ abstract class ScrollableWidgetList extends Scrollable { padding: _crossAxisPadding, child: new HomogeneousViewport( builder: _buildItems, - itemsWrap: itemsWrap, - itemExtent: itemExtent, + itemsWrap: config.itemsWrap, + itemExtent: config.itemExtent, itemCount: itemCount, - direction: scrollDirection, + direction: config.scrollDirection, startOffset: scrollOffset - _leadingPadding ) ) ); } - List _buildItems(int start, int count) { - List result = buildItems(start, count); + List _buildItems(BuildContext context, int start, int count) { + List result = buildItems(context, start, count); assert(result.every((item) => item.key != null)); return result; } - List buildItems(int start, int count); + List buildItems(BuildContext context, int start, int count); } -typedef Widget ItemBuilder(T item); +typedef Widget ItemBuilder(BuildContext context, T item); /// A wrapper around [ScrollableWidgetList] that helps you translate a list of /// model objects into a scrollable list of widgets. Assumes all the widgets @@ -486,6 +547,9 @@ class ScrollableList extends ScrollableWidgetList { Key key, double initialScrollOffset, ScrollDirection scrollDirection: ScrollDirection.vertical, + ScrollListener onScroll, + SnapOffsetCallback snapOffsetCallback, + double snapAlignmentOffset: 0.0, this.items, this.itemBuilder, itemsWrap: false, @@ -495,31 +559,32 @@ class ScrollableList extends ScrollableWidgetList { key: key, initialScrollOffset: initialScrollOffset, scrollDirection: scrollDirection, + onScroll: onScroll, + snapOffsetCallback: snapOffsetCallback, + snapAlignmentOffset: snapAlignmentOffset, itemsWrap: itemsWrap, itemExtent: itemExtent, padding: padding); - List items; - ItemBuilder itemBuilder; + final List items; + final ItemBuilder itemBuilder; - void syncConstructorArguments(ScrollableList source) { - items = source.items; - itemBuilder = source.itemBuilder; - super.syncConstructorArguments(source); - } + ScrollableListState> createState() => new ScrollableListState>(); +} +class ScrollableListState> extends ScrollableWidgetListState { ScrollBehavior createScrollBehavior() { - return itemsWrap ? new UnboundedBehavior() : super.createScrollBehavior(); + return config.itemsWrap ? new UnboundedBehavior() : super.createScrollBehavior(); } - int get itemCount => items.length; + int get itemCount => config.items.length; - List buildItems(int start, int count) { + List buildItems(BuildContext context, int start, int count) { List result = new List(); - int begin = itemsWrap ? start : math.max(0, start); - int end = itemsWrap ? begin + count : math.min(begin + count, items.length); + int begin = config.itemsWrap ? start : math.max(0, start); + int end = config.itemsWrap ? begin + count : math.min(begin + count, config.items.length); for (int i = begin; i < end; ++i) - result.add(itemBuilder(items[i % itemCount])); + result.add(config.itemBuilder(context, config.items[i % itemCount])); return result; } } @@ -531,11 +596,12 @@ class PageableList extends ScrollableList { Key key, double initialScrollOffset, ScrollDirection scrollDirection: ScrollDirection.horizontal, + ScrollListener onScroll, List items, ItemBuilder itemBuilder, bool itemsWrap: false, double itemExtent, - PageChangedCallback this.pageChanged, + this.onPageChanged, EdgeDims padding, this.duration: const Duration(milliseconds: 200), this.curve: ease @@ -543,6 +609,7 @@ class PageableList extends ScrollableList { key: key, initialScrollOffset: initialScrollOffset, scrollDirection: scrollDirection, + onScroll: onScroll, items: items, itemBuilder: itemBuilder, itemsWrap: itemsWrap, @@ -550,43 +617,40 @@ class PageableList extends ScrollableList { padding: padding ); - Duration duration; - Curve curve; - PageChangedCallback pageChanged; + final Duration duration; + final Curve curve; + final PageChangedCallback onPageChanged; - void syncConstructorArguments(PageableList source) { - duration = source.duration; - curve = source.curve; - pageChanged = source.pageChanged; - super.syncConstructorArguments(source); - } + PageableListState createState() => new PageableListState(); +} +class PageableListState extends ScrollableListState> { double _snapScrollOffset(double newScrollOffset) { - double scaledScrollOffset = newScrollOffset / itemExtent; - double previousScrollOffset = scaledScrollOffset.floor() * itemExtent; - double nextScrollOffset = scaledScrollOffset.ceil() * itemExtent; + double scaledScrollOffset = newScrollOffset / config.itemExtent; + double previousScrollOffset = scaledScrollOffset.floor() * config.itemExtent; + double nextScrollOffset = scaledScrollOffset.ceil() * config.itemExtent; double delta = newScrollOffset - previousScrollOffset; - return (delta < itemExtent / 2.0 ? previousScrollOffset : nextScrollOffset) + return (delta < config.itemExtent / 2.0 ? previousScrollOffset : nextScrollOffset) .clamp(scrollBehavior.minScrollOffset, scrollBehavior.maxScrollOffset); } - void fling(sky.Offset velocity) { + Future fling(sky.Offset velocity) { double scrollVelocity = _scrollVelocity(velocity); - double newScrollOffset = _snapScrollOffset(scrollOffset + scrollVelocity.sign * itemExtent) - .clamp(_snapScrollOffset(scrollOffset - itemExtent / 2.0), - _snapScrollOffset(scrollOffset + itemExtent / 2.0)); - scrollTo(newScrollOffset, duration: duration, curve: curve).then(_notifyPageChanged); + double newScrollOffset = _snapScrollOffset(scrollOffset + scrollVelocity.sign * config.itemExtent) + .clamp(_snapScrollOffset(scrollOffset - config.itemExtent / 2.0), + _snapScrollOffset(scrollOffset + config.itemExtent / 2.0)); + return scrollTo(newScrollOffset, duration: config.duration, curve: config.curve).then(_notifyPageChanged); } - int get currentPage => (scrollOffset / itemExtent).floor() % itemCount; + int get currentPage => (scrollOffset / config.itemExtent).floor() % itemCount; void _notifyPageChanged(_) { - if (pageChanged != null) - pageChanged(currentPage); + if (config.onPageChanged != null) + config.onPageChanged(currentPage); } - void settleScrollOffset() { - scrollTo(_snapScrollOffset(scrollOffset), duration: duration, curve: curve).then(_notifyPageChanged); + Future settleScrollOffset() { + return scrollTo(_snapScrollOffset(scrollOffset), duration: config.duration, curve: config.curve).then(_notifyPageChanged); } } @@ -598,49 +662,33 @@ class ScrollableMixedWidgetList extends Scrollable { ScrollableMixedWidgetList({ Key key, double initialScrollOffset, + ScrollListener onScroll, + SnapOffsetCallback snapOffsetCallback, + double snapAlignmentOffset: 0.0, this.builder, this.token, - this.layoutState - }) : super(key: key, initialScrollOffset: initialScrollOffset); + this.onInvalidatorAvailable + }) : super( + key: key, + initialScrollOffset: initialScrollOffset, + onScroll: onScroll, + snapOffsetCallback: snapOffsetCallback, + snapAlignmentOffset: snapAlignmentOffset + ); - IndexedBuilder builder; - Object token; - MixedViewportLayoutState layoutState; + final IndexedBuilder builder; + final Object token; + final InvalidatorAvailableCallback onInvalidatorAvailable; - // When the token changes the scrollable's contents may have - // changed. Remember as much so that after the new contents - // have been laid out we can adjust the scrollOffset so that - // the last page of content is still visible. - bool _contentChanged = true; + ScrollableMixedWidgetListState createState() => new ScrollableMixedWidgetListState(); +} +class ScrollableMixedWidgetListState extends ScrollableState { void initState() { - assert(layoutState != null); super.initState(); - } - - void didMount() { - layoutState.addListener(_handleLayoutChanged); - super.didMount(); - } - - void didUnmount() { - layoutState.removeListener(_handleLayoutChanged); - super.didUnmount(); - } - - void syncConstructorArguments(ScrollableMixedWidgetList source) { - builder = source.builder; - if (token != source.token) - _contentChanged = true; - token = source.token; - if (layoutState != source.layoutState) { - // Warning: this is unlikely to be what you intended. - assert(source.layoutState != null); - layoutState.removeListener(_handleLayoutChanged); - layoutState = source.layoutState; - layoutState.addListener(_handleLayoutChanged); - } - super.syncConstructorArguments(source); + scrollBehavior.updateExtents( + contentExtent: double.INFINITY + ); } ScrollBehavior createScrollBehavior() => new OverscrollBehavior(); @@ -655,11 +703,24 @@ class ScrollableMixedWidgetList extends Scrollable { }); } - void _handleLayoutChanged() { + bool _contentChanged = false; + + void didUpdateConfig(ScrollableMixedWidgetList oldConfig) { + super.didUpdateConfig(oldConfig); + if (config.token != oldConfig.token) { + // When the token changes the scrollable's contents may have changed. + // Remember as much so that after the new contents have been laid out we + // can adjust the scrollOffset so that the last page of content is still + // visible. + _contentChanged = true; + } + } + + void _handleExtentsUpdate(double newExtents) { double newScrollOffset; setState(() { newScrollOffset = scrollBehavior.updateExtents( - contentExtent: layoutState.didReachLastChild ? layoutState.contentsSize : double.INFINITY, + contentExtent: newExtents ?? double.INFINITY, scrollOffset: scrollOffset ); }); @@ -669,14 +730,15 @@ class ScrollableMixedWidgetList extends Scrollable { } } - Widget buildContent() { + Widget buildContent(BuildContext context) { return new SizeObserver( callback: _handleSizeChanged, child: new MixedViewport( - builder: builder, - layoutState: layoutState, startOffset: scrollOffset, - token: token + builder: config.builder, + token: config.token, + onInvalidatorAvailable: config.onInvalidatorAvailable, + onExtentsUpdate: _handleExtentsUpdate ) ); } diff --git a/packages/flutter/lib/src/widgets/snack_bar.dart b/packages/flutter/lib/src/widgets/snack_bar.dart index 361fdb3ee9..82ff38feb3 100644 --- a/packages/flutter/lib/src/widgets/snack_bar.dart +++ b/packages/flutter/lib/src/widgets/snack_bar.dart @@ -8,7 +8,6 @@ import 'package:sky/painting.dart'; import 'package:sky/material.dart'; import 'package:sky/src/widgets/animated_component.dart'; import 'package:sky/src/widgets/basic.dart'; -import 'package:sky/src/widgets/default_text_style.dart'; import 'package:sky/src/widgets/framework.dart'; import 'package:sky/src/widgets/gesture_detector.dart'; import 'package:sky/src/widgets/material.dart'; @@ -18,9 +17,12 @@ import 'package:sky/src/widgets/transitions.dart'; typedef void SnackBarDismissedCallback(); const Duration _kSlideInDuration = const Duration(milliseconds: 200); -// TODO(ianh): factor out some of the constants below +const double kSnackHeight = 52.0; +const double kSideMargins = 24.0; +const double kVerticalPadding = 14.0; +const Color kSnackBackground = const Color(0xFF323232); -class SnackBarAction extends Component { +class SnackBarAction extends StatelessComponent { SnackBarAction({Key key, this.label, this.onPressed }) : super(key: key) { assert(label != null); } @@ -28,12 +30,12 @@ class SnackBarAction extends Component { final String label; final Function onPressed; - Widget build() { + Widget build(BuildContext) { return new GestureDetector( onTap: onPressed, child: new Container( - margin: const EdgeDims.only(left: 24.0), - padding: const EdgeDims.only(top: 14.0, bottom: 14.0), + margin: const EdgeDims.only(left: kSideMargins), + padding: const EdgeDims.symmetric(vertical: kVerticalPadding), child: new Text(label) ) ); @@ -41,10 +43,8 @@ class SnackBarAction extends Component { } class SnackBar extends AnimatedComponent { - SnackBar({ Key key, - this.transitionKey, this.content, this.actions, bool showing, @@ -53,56 +53,56 @@ class SnackBar extends AnimatedComponent { assert(content != null); } - Key transitionKey; - Widget content; - List actions; - SnackBarDismissedCallback onDismissed; + final Widget content; + final List actions; + final SnackBarDismissedCallback onDismissed; - void syncConstructorArguments(SnackBar source) { - transitionKey = source.transitionKey; - content = source.content; - actions = source.actions; - onDismissed = source.onDismissed; - super.syncConstructorArguments(source); - } + SnackBarState createState() => new SnackBarState(); +} +class SnackBarState extends AnimatedState { void handleDismissed() { - if (onDismissed != null) - onDismissed(); + if (config.onDismissed != null) + config.onDismissed(); } - Widget build() { + Widget build(BuildContext context) { List children = [ new Flexible( child: new Container( - margin: const EdgeDims.symmetric(vertical: 14.0), + margin: const EdgeDims.symmetric(vertical: kVerticalPadding), child: new DefaultTextStyle( style: Typography.white.subhead, - child: content + child: config.content ) ) ) ]; - if (actions != null) - children.addAll(actions); - return new SlideTransition( - key: transitionKey, + if (config.actions != null) + children.addAll(config.actions); + return new SquashTransition( performance: performance.view, - position: new AnimatedValue( - Point.origin, - end: const Point(0.0, -52.0), + height: new AnimatedValue( + 0.0, + end: kSnackHeight, curve: easeIn, reverseCurve: easeOut ), - child: new Material( - level: 2, - color: const Color(0xFF323232), - type: MaterialType.canvas, - child: new Container( - margin: const EdgeDims.symmetric(horizontal: 24.0), - child: new DefaultTextStyle( - style: new TextStyle(color: Theme.of(this).accentColor), - child: new Row(children) + child: new ClipRect( + child: new OverflowBox( + minHeight: kSnackHeight, + maxHeight: kSnackHeight, + child: new Material( + level: 2, + color: kSnackBackground, + type: MaterialType.canvas, + child: new Container( + margin: const EdgeDims.symmetric(horizontal: kSideMargins), + child: new DefaultTextStyle( + style: new TextStyle(color: Theme.of(context).accentColor), + child: new Row(children) + ) + ) ) ) ) diff --git a/packages/flutter/lib/src/widgets/switch.dart b/packages/flutter/lib/src/widgets/switch.dart index 372b0a1b13..5452545529 100644 --- a/packages/flutter/lib/src/widgets/switch.dart +++ b/packages/flutter/lib/src/widgets/switch.dart @@ -11,9 +11,8 @@ import 'package:sky/rendering.dart'; import 'package:sky/src/widgets/basic.dart'; import 'package:sky/src/widgets/theme.dart'; import 'package:sky/src/widgets/framework.dart'; -import 'package:sky/src/rendering/toggleable.dart'; -export 'package:sky/src/rendering/toggleable.dart' show ValueChanged; +export 'package:sky/rendering.dart' show ValueChanged; const sky.Color _kThumbOffColor = const sky.Color(0xFFFAFAFA); const sky.Color _kTrackOffColor = const sky.Color(0x42000000); @@ -24,29 +23,43 @@ const double _kTrackHeight = 14.0; const double _kTrackRadius = _kTrackHeight / 2.0; const double _kTrackWidth = _kSwitchWidth - (_kThumbRadius - _kTrackRadius) * 2.0; -const Duration _kCheckDuration = const Duration(milliseconds: 200); const Size _kSwitchSize = const Size(_kSwitchWidth + 2.0, _kSwitchHeight + 2.0); const double _kReactionRadius = _kSwitchWidth / 2.0; -class Switch extends LeafRenderObjectWrapper { +class Switch extends StatelessComponent { Switch({ Key key, this.value, this.onChanged }) : super(key: key); final bool value; final ValueChanged onChanged; - _RenderSwitch get renderObject => super.renderObject; - _RenderSwitch createNode() => new _RenderSwitch( + Widget build(BuildContext context) { + return new _SwitchWrapper( + value: value, + thumbColor: Theme.of(context).accentColor, + onChanged: onChanged + ); + } +} + +class _SwitchWrapper extends LeafRenderObjectWidget { + _SwitchWrapper({ Key key, this.value, this.thumbColor, this.onChanged }) + : super(key: key); + + final bool value; + final Color thumbColor; + final ValueChanged onChanged; + + _RenderSwitch createRenderObject() => new _RenderSwitch( value: value, - thumbColor: null, + thumbColor: thumbColor, onChanged: onChanged ); - void syncRenderObject(Switch old) { - super.syncRenderObject(old); + void updateRenderObject(_RenderSwitch renderObject, _SwitchWrapper oldWidget) { renderObject.value = value; + renderObject.thumbColor = thumbColor; renderObject.onChanged = onChanged; - renderObject.thumbColor = Theme.of(this).accentColor; } } @@ -84,9 +97,9 @@ class _RenderSwitch extends RenderToggleable { _radialReaction = new RadialReaction( center: new Point(_kSwitchSize.width / 2.0, _kSwitchSize.height / 2.0), radius: _kReactionRadius, - startPosition: startLocation) - ..addListener(markNeedsPaint) - ..show(); + startPosition: startLocation + )..addListener(markNeedsPaint) + ..show(); } Future _hideRadialReaction() async { @@ -127,10 +140,10 @@ class _RenderSwitch extends RenderToggleable { paint.drawLooper = builder.build(); // The thumb contracts slightly during the animation - double inset = 2.0 - (position.value - 0.5).abs() * 2.0; + double inset = 2.0 - (position - 0.5).abs() * 2.0; Point thumbPos = new Point(offset.dx + _kTrackRadius + - position.value * (_kTrackWidth - _kTrackRadius * 2), + position * (_kTrackWidth - _kTrackRadius * 2), offset.dy + _kSwitchHeight / 2.0); canvas.drawCircle(thumbPos, _kThumbRadius - inset, paint); } diff --git a/packages/flutter/lib/src/widgets/tabs.dart b/packages/flutter/lib/src/widgets/tabs.dart index 10fc97e983..d65957c433 100644 --- a/packages/flutter/lib/src/widgets/tabs.dart +++ b/packages/flutter/lib/src/widgets/tabs.dart @@ -11,7 +11,6 @@ import 'package:sky/painting.dart'; import 'package:sky/rendering.dart'; import 'package:sky/material.dart'; import 'package:sky/src/widgets/basic.dart'; -import 'package:sky/src/widgets/default_text_style.dart'; import 'package:sky/src/widgets/framework.dart'; import 'package:sky/src/widgets/gesture_detector.dart'; import 'package:sky/src/widgets/icon.dart'; @@ -260,8 +259,8 @@ class RenderTabBar extends RenderBox with } } -class TabBarWrapper extends MultiChildRenderObjectWrapper { - TabBarWrapper({ +class _TabBarWrapper extends MultiChildRenderObjectWidget { + _TabBarWrapper({ Key key, List children, this.selectedIndex, @@ -281,11 +280,13 @@ class TabBarWrapper extends MultiChildRenderObjectWrapper { final bool isScrollable; final LayoutChanged onLayoutChanged; - RenderTabBar get renderObject => super.renderObject; - RenderTabBar createNode() => new RenderTabBar(onLayoutChanged); + RenderTabBar createRenderObject() { + RenderTabBar result = new RenderTabBar(onLayoutChanged); + updateRenderObject(result, null); + return result; + } - void syncRenderObject(Widget old) { - super.syncRenderObject(old); + void updateRenderObject(RenderTabBar renderObject, _TabBarWrapper oldWidget) { renderObject.selectedIndex = selectedIndex; renderObject.backgroundColor = backgroundColor; renderObject.indicatorColor = indicatorColor; @@ -303,7 +304,7 @@ class TabLabel { final String icon; } -class Tab extends Component { +class Tab extends StatelessComponent { Tab({ Key key, this.label, @@ -332,7 +333,7 @@ class Tab extends Component { return new Icon(type: label.icon, size: _kTabIconSize, colorFilter: filter); } - Widget build() { + Widget build(BuildContext context) { Widget labelContent; if (label.icon == null) { labelContent = _buildLabelText(); @@ -391,33 +392,32 @@ class TabBar extends Scrollable { this.isScrollable: false }) : super(key: key, scrollDirection: ScrollDirection.horizontal); - Iterable labels; - int selectedIndex; - SelectedIndexChanged onChanged; - bool isScrollable; + final Iterable labels; + final int selectedIndex; + final SelectedIndexChanged onChanged; + final bool isScrollable; + + TabBarState createState() => new TabBarState(); +} + +class TabBarState extends ScrollableState { + void initState() { + super.initState(); + _indicatorAnimation = new ValueAnimation() + ..duration = _kTabBarScroll + ..variable = new AnimatedRect(null, curve: ease); + scrollBehavior.isScrollable = config.isScrollable; + } Size _tabBarSize; Size _viewportSize = Size.zero; List _tabWidths; ValueAnimation _indicatorAnimation; - void initState() { - super.initState(); - _indicatorAnimation = new ValueAnimation() - ..duration = _kTabBarScroll - ..variable = new AnimatedRect(null, curve: ease); - scrollBehavior.isScrollable = isScrollable; - } - - void syncConstructorArguments(TabBar source) { - super.syncConstructorArguments(source); - labels = source.labels; - selectedIndex = source.selectedIndex; - onChanged = source.onChanged; - isScrollable = source.isScrollable; - if (!isScrollable) + void didUpdateConfig(TabBar oldConfig) { + super.didUpdateConfig(oldConfig); + if (!config.isScrollable) scrollTo(0.0); - scrollBehavior.isScrollable = source.isScrollable; } AnimatedRect get _indicatorRect => _indicatorAnimation.variable; @@ -459,14 +459,14 @@ class TabBar extends Scrollable { } void _handleTap(int tabIndex) { - if (tabIndex != selectedIndex) { + if (tabIndex != config.selectedIndex) { if (_tabWidths != null) { - if (isScrollable) + if (config.isScrollable) scrollTo(_centeredTabScrollOffset(tabIndex), duration: _kTabBarScroll); - _startIndicatorAnimation(selectedIndex, tabIndex); + _startIndicatorAnimation(config.selectedIndex, tabIndex); } - if (onChanged != null) - onChanged(tabIndex); + if (config.onChanged != null) + config.onChanged(tabIndex); } } @@ -476,7 +476,7 @@ class TabBar extends Scrollable { child: new Tab( label: label, color: color, - selected: tabIndex == selectedIndex, + selected: tabIndex == config.selectedIndex, selectedColor: selectedColor ) ); @@ -484,7 +484,7 @@ class TabBar extends Scrollable { void _updateScrollBehavior() { scrollBehavior.updateExtents( - containerExtent: scrollDirection == ScrollDirection.vertical ? _viewportSize.height : _viewportSize.width, + containerExtent: config.scrollDirection == ScrollDirection.vertical ? _viewportSize.height : _viewportSize.width, contentExtent: _tabWidths.reduce((sum, width) => sum + width) ); } @@ -502,10 +502,10 @@ class TabBar extends Scrollable { _updateScrollBehavior(); } - Widget buildContent() { - assert(labels != null && labels.isNotEmpty); + Widget buildContent(BuildContext context) { + assert(config.labels != null && config.labels.isNotEmpty); - ThemeData themeData = Theme.of(this); + ThemeData themeData = Theme.of(context); Color backgroundColor = themeData.primaryColor; Color indicatorColor = themeData.accentColor; if (indicatorColor == backgroundColor) { @@ -528,7 +528,7 @@ class TabBar extends Scrollable { List tabs = []; bool textAndIcons = false; int tabIndex = 0; - for (TabLabel label in labels) { + for (TabLabel label in config.labels) { tabs.add(_toTab(label, tabIndex++, textStyle.color, indicatorColor)); if (label.text != null && label.icon != null) textAndIcons = true; @@ -541,15 +541,15 @@ class TabBar extends Scrollable { child: new BuilderTransition( variables: [_indicatorRect], performance: _indicatorAnimation.view, - builder: () { - return new TabBarWrapper( + builder: (BuildContext context) { + return new _TabBarWrapper( children: tabs, - selectedIndex: selectedIndex, + selectedIndex: config.selectedIndex, backgroundColor: backgroundColor, indicatorColor: indicatorColor, indicatorRect: _indicatorRect.value, textAndIcons: textAndIcons, - isScrollable: isScrollable, + isScrollable: config.isScrollable, onLayoutChanged: _layoutChanged ); } @@ -557,7 +557,7 @@ class TabBar extends Scrollable { ) ); - if (!isScrollable) + if (!config.isScrollable) return tabBar; return new SizeObserver( @@ -572,20 +572,19 @@ class TabBar extends Scrollable { } class TabNavigatorView { - TabNavigatorView({ this.label, this.builder }); + TabNavigatorView({ this.label, this.builder }) { + assert(builder != null); + } + + // this uses a builder for the contents, rather than a raw Widget child, + // because there might be many, many tabs and some might be relatively + // expensive to create up front. This way, the view is only created lazily. final TabLabel label; - final Builder builder; - - Widget buildContent() { - assert(builder != null); - Widget content = builder(); - assert(content != null); - return content; - } + final WidgetBuilder builder; } -class TabNavigator extends Component { +class TabNavigator extends StatelessComponent { TabNavigator({ Key key, this.views, @@ -604,18 +603,17 @@ class TabNavigator extends Component { onChanged(tabIndex); } - Widget build() { + Widget build(BuildContext context) { assert(views != null && views.isNotEmpty); assert(selectedIndex >= 0 && selectedIndex < views.length); - - TabBar tabBar = new TabBar( - labels: views.map((view) => view.label), - onChanged: _handleSelectedIndexChanged, - selectedIndex: selectedIndex, - isScrollable: isScrollable - ); - - Widget content = views[selectedIndex].buildContent(); - return new Column([tabBar, new Flexible(child: content)]); + return new Column([ + new TabBar( + labels: views.map((view) => view.label), + onChanged: _handleSelectedIndexChanged, + selectedIndex: selectedIndex, + isScrollable: isScrollable + ), + new Flexible(child: views[selectedIndex].builder(context)) + ]); } } diff --git a/packages/flutter/lib/src/widgets/theme.dart b/packages/flutter/lib/src/widgets/theme.dart index 482325e8e1..c06978b2d7 100644 --- a/packages/flutter/lib/src/widgets/theme.dart +++ b/packages/flutter/lib/src/widgets/theme.dart @@ -7,8 +7,7 @@ import 'package:sky/src/widgets/framework.dart'; export 'package:sky/material.dart' show ThemeData, ThemeBrightness; -class Theme extends Inherited { - +class Theme extends InheritedWidget { Theme({ Key key, this.data, @@ -22,11 +21,10 @@ class Theme extends Inherited { static final ThemeData _kFallbackTheme = new ThemeData.fallback(); - static ThemeData of(Widget widget) { - Theme theme = widget.inheritedOfType(Theme); + static ThemeData of(BuildContext context) { + Theme theme = context.inheritedWidgetOfType(Theme); return theme == null ? _kFallbackTheme : theme.data; } - bool syncShouldNotify(Theme old) => data != old.data; - + bool updateShouldNotify(Theme old) => data != old.data; } diff --git a/packages/flutter/lib/src/widgets/title.dart b/packages/flutter/lib/src/widgets/title.dart index 79a6998543..f9f9ae5c4f 100644 --- a/packages/flutter/lib/src/widgets/title.dart +++ b/packages/flutter/lib/src/widgets/title.dart @@ -6,16 +6,14 @@ import 'package:sky/services.dart'; import 'package:sky/src/widgets/theme.dart'; import 'package:sky/src/widgets/framework.dart'; -class Title extends Component { - +class Title extends StatelessComponent { Title({ this.title, this.child }); final Widget child; final String title; - Widget build() { - updateTaskDescription(title, Theme.of(this).primaryColor); + Widget build(BuildContext context) { + updateTaskDescription(title, Theme.of(context).primaryColor); return child; } - } diff --git a/packages/flutter/lib/src/widgets/tool_bar.dart b/packages/flutter/lib/src/widgets/tool_bar.dart index f5b8bf33f4..543531ae63 100644 --- a/packages/flutter/lib/src/widgets/tool_bar.dart +++ b/packages/flutter/lib/src/widgets/tool_bar.dart @@ -2,17 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:sky/src/widgets/theme.dart'; - import 'package:sky/material.dart'; import 'package:sky/painting.dart'; -import 'package:sky/src/rendering/flex.dart'; import 'package:sky/src/widgets/basic.dart'; -import 'package:sky/src/widgets/default_text_style.dart'; import 'package:sky/src/widgets/framework.dart'; import 'package:sky/src/widgets/icon.dart'; +import 'package:sky/src/widgets/theme.dart'; +import 'package:sky/src/rendering/flex.dart'; -class ToolBar extends Component { +class ToolBar extends StatelessComponent { ToolBar({ Key key, @@ -27,13 +25,13 @@ class ToolBar extends Component { final List right; final Color backgroundColor; - Widget build() { + Widget build(BuildContext context) { Color toolbarColor = backgroundColor; IconThemeData iconThemeData; TextStyle centerStyle = Typography.white.title; TextStyle sideStyle = Typography.white.body1; if (toolbarColor == null) { - ThemeData themeData = Theme.of(this); + ThemeData themeData = Theme.of(context); toolbarColor = themeData.primaryColor; if (themeData.primaryColorBrightness == ThemeBrightness.light) { centerStyle = Typography.black.title; diff --git a/packages/flutter/lib/src/widgets/transitions.dart b/packages/flutter/lib/src/widgets/transitions.dart index 5570313380..85599fffc5 100644 --- a/packages/flutter/lib/src/widgets/transitions.dart +++ b/packages/flutter/lib/src/widgets/transitions.dart @@ -5,118 +5,69 @@ import 'package:sky/animation.dart'; import 'package:sky/src/widgets/basic.dart'; import 'package:sky/src/widgets/framework.dart'; -import 'package:sky/src/widgets/global_key_watcher.dart'; import 'package:vector_math/vector_math.dart'; export 'package:sky/animation.dart' show Direction; -class TransitionProxy extends GlobalKeyWatcher { - - TransitionProxy({ - Key key, - GlobalKey transitionKey, - this.child - }) : super(key: key, watchedKey: transitionKey); - - Widget child; - - void syncConstructorArguments(TransitionProxy source) { - child = source.child; - super.syncConstructorArguments(source); - } - - bool debugValidateWatchedWidget(Widget candidate) { - return candidate is TransitionBaseWithChild; - } - - TransitionBaseWithChild get transition => this.watchedWidget; - - void startWatching() { - transition.performance.addListener(_performanceChanged); - } - - void stopWatching() { - transition.performance.removeListener(_performanceChanged); - } - - void _performanceChanged() { - setState(() { - // The performance changed, so we probably need to ask the transition - // we're watching for a rebuild. - }); - } - - Widget build() { - if (transition != null) - return transition.buildWithChild(child); - return child; - } - -} - -abstract class TransitionBase extends StatefulComponent { - - TransitionBase({ +abstract class TransitionComponent extends StatefulComponent { + TransitionComponent({ Key key, this.performance }) : super(key: key) { assert(performance != null); } - WatchableAnimationPerformance performance; + final WatchableAnimationPerformance performance; - void syncConstructorArguments(TransitionBase source) { - if (performance != source.performance) { - if (mounted) - performance.removeListener(_performanceChanged); - performance = source.performance; - if (mounted) - performance.addListener(_performanceChanged); + Widget build(BuildContext context); + + TransitionState createState() => new TransitionState(); +} + +class TransitionState extends State { + void initState() { + super.initState(); + config.performance.addListener(_performanceChanged); + } + + void didUpdateConfig(TransitionComponent oldConfig) { + if (config.performance != oldConfig.performance) { + oldConfig.performance.removeListener(_performanceChanged); + config.performance.addListener(_performanceChanged); } } + void dispose() { + config.performance.removeListener(_performanceChanged); + super.dispose(); + } + void _performanceChanged() { setState(() { // The performance's state is our build state, and it changed already. }); } - void didMount() { - performance.addListener(_performanceChanged); - super.didMount(); + Widget build(BuildContext context) { + return config.build(context); } - - void didUnmount() { - performance.removeListener(_performanceChanged); - super.didUnmount(); - } - } -abstract class TransitionBaseWithChild extends TransitionBase { - - TransitionBaseWithChild({ +abstract class TransitionWithChild extends TransitionComponent { + TransitionWithChild({ Key key, this.child, WatchableAnimationPerformance performance }) : super(key: key, performance: performance); - Widget child; + final Widget child; - void syncConstructorArguments(TransitionBaseWithChild source) { - child = source.child; - super.syncConstructorArguments(source); - } - - Widget build() { - return buildWithChild(child); - } - - Widget buildWithChild(Widget child); + Widget build(BuildContext context) => buildWithChild(context, child); + Widget buildWithChild(BuildContext context, Widget child); } -class SlideTransition extends TransitionBaseWithChild { +class SlideTransition extends TransitionWithChild { SlideTransition({ Key key, this.position, @@ -126,14 +77,9 @@ class SlideTransition extends TransitionBaseWithChild { performance: performance, child: child); - AnimatedValue position; + final AnimatedValue position; - void syncConstructorArguments(SlideTransition source) { - position = source.position; - super.syncConstructorArguments(source); - } - - Widget buildWithChild(Widget child) { + Widget buildWithChild(BuildContext context, Widget child) { performance.updateVariable(position); Matrix4 transform = new Matrix4.identity() ..translate(position.value.x, position.value.y); @@ -141,7 +87,7 @@ class SlideTransition extends TransitionBaseWithChild { } } -class FadeTransition extends TransitionBaseWithChild { +class FadeTransition extends TransitionWithChild { FadeTransition({ Key key, this.opacity, @@ -151,20 +97,15 @@ class FadeTransition extends TransitionBaseWithChild { performance: performance, child: child); - AnimatedValue opacity; + final AnimatedValue opacity; - void syncConstructorArguments(FadeTransition source) { - opacity = source.opacity; - super.syncConstructorArguments(source); - } - - Widget buildWithChild(Widget child) { + Widget buildWithChild(BuildContext context, Widget child) { performance.updateVariable(opacity); return new Opacity(opacity: opacity.value, child: child); } } -class ColorTransition extends TransitionBaseWithChild { +class ColorTransition extends TransitionWithChild { ColorTransition({ Key key, this.color, @@ -174,14 +115,9 @@ class ColorTransition extends TransitionBaseWithChild { performance: performance, child: child); - AnimatedColorValue color; + final AnimatedColorValue color; - void syncConstructorArguments(ColorTransition source) { - color = source.color; - super.syncConstructorArguments(source); - } - - Widget buildWithChild(Widget child) { + Widget buildWithChild(BuildContext context, Widget child) { performance.updateVariable(color); return new DecoratedBox( decoration: new BoxDecoration(backgroundColor: color.value), @@ -190,7 +126,7 @@ class ColorTransition extends TransitionBaseWithChild { } } -class SquashTransition extends TransitionBaseWithChild { +class SquashTransition extends TransitionWithChild { SquashTransition({ Key key, this.width, @@ -201,16 +137,10 @@ class SquashTransition extends TransitionBaseWithChild { performance: performance, child: child); - AnimatedValue width; - AnimatedValue height; + final AnimatedValue width; + final AnimatedValue height; - void syncConstructorArguments(SquashTransition source) { - width = source.width; - height = source.height; - super.syncConstructorArguments(source); - } - - Widget buildWithChild(Widget child) { + Widget buildWithChild(BuildContext context, Widget child) { if (width != null) performance.updateVariable(width); if (height != null) @@ -219,9 +149,9 @@ class SquashTransition extends TransitionBaseWithChild { } } -typedef Widget BuilderFunction(); +typedef Widget BuilderFunction(BuildContext context); -class BuilderTransition extends TransitionBase { +class BuilderTransition extends TransitionComponent { BuilderTransition({ Key key, this.variables, @@ -230,18 +160,12 @@ class BuilderTransition extends TransitionBase { }) : super(key: key, performance: performance); - List variables; - BuilderFunction builder; + final List variables; + final BuilderFunction builder; - void syncConstructorArguments(BuilderTransition source) { - variables = source.variables; - builder = source.builder; - super.syncConstructorArguments(source); - } - - Widget build() { + Widget build(BuildContext context) { for (int i = 0; i < variables.length; ++i) performance.updateVariable(variables[i]); - return builder(); + return builder(context); } } diff --git a/packages/flutter/lib/src/fn3/unique_component.dart b/packages/flutter/lib/src/widgets/unique_component.dart similarity index 92% rename from packages/flutter/lib/src/fn3/unique_component.dart rename to packages/flutter/lib/src/widgets/unique_component.dart index 560d3b4477..065ee3b033 100644 --- a/packages/flutter/lib/src/fn3/unique_component.dart +++ b/packages/flutter/lib/src/widgets/unique_component.dart @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; abstract class UniqueComponent extends StatefulComponent { UniqueComponent({ GlobalKey key }) : super(key: key) { diff --git a/packages/flutter/lib/widgets.dart b/packages/flutter/lib/widgets.dart index 6df19bd41b..20b2134acb 100644 --- a/packages/flutter/lib/widgets.dart +++ b/packages/flutter/lib/widgets.dart @@ -5,51 +5,51 @@ /// The Flutter widget framework. library widgets; -export 'package:sky/src/widgets/animated_component.dart'; -export 'package:sky/src/widgets/animated_container.dart'; -export 'package:sky/src/widgets/basic.dart'; -export 'package:sky/src/widgets/button_base.dart'; -export 'package:sky/src/widgets/card.dart'; -export 'package:sky/src/widgets/checkbox.dart'; -export 'package:sky/src/widgets/date_picker.dart'; -export 'package:sky/src/widgets/default_text_style.dart'; -export 'package:sky/src/widgets/dialog.dart'; -export 'package:sky/src/widgets/dismissable.dart'; -export 'package:sky/src/widgets/drag_target.dart'; -export 'package:sky/src/widgets/drawer.dart'; -export 'package:sky/src/widgets/drawer_divider.dart'; -export 'package:sky/src/widgets/drawer_header.dart'; -export 'package:sky/src/widgets/drawer_item.dart'; -export 'package:sky/src/widgets/editable_text.dart'; -export 'package:sky/src/widgets/flat_button.dart'; -export 'package:sky/src/widgets/floating_action_button.dart'; -export 'package:sky/src/widgets/focus.dart'; -export 'package:sky/src/widgets/framework.dart'; -export 'package:sky/src/widgets/gesture_detector.dart'; -export 'package:sky/src/widgets/global_key_watcher.dart'; -export 'package:sky/src/widgets/homogeneous_viewport.dart'; -export 'package:sky/src/widgets/icon.dart'; -export 'package:sky/src/widgets/icon_button.dart'; -export 'package:sky/src/widgets/ink_well.dart'; -export 'package:sky/src/widgets/input.dart'; -export 'package:sky/src/widgets/material.dart'; -export 'package:sky/src/widgets/material_button.dart'; -export 'package:sky/src/widgets/mimic.dart'; -export 'package:sky/src/widgets/mixed_viewport.dart'; -export 'package:sky/src/widgets/navigator.dart'; -export 'package:sky/src/widgets/popup_menu.dart'; -export 'package:sky/src/widgets/popup_menu_item.dart'; -export 'package:sky/src/widgets/progress_indicator.dart'; -export 'package:sky/src/widgets/radio.dart'; -export 'package:sky/src/widgets/raised_button.dart'; -export 'package:sky/src/widgets/scaffold.dart'; -export 'package:sky/src/widgets/scrollable.dart'; -export 'package:sky/src/widgets/snack_bar.dart'; -export 'package:sky/src/widgets/switch.dart'; -export 'package:sky/src/widgets/tabs.dart'; -export 'package:sky/src/widgets/theme.dart'; -export 'package:sky/src/widgets/title.dart'; -export 'package:sky/src/widgets/tool_bar.dart'; -export 'package:sky/src/widgets/transitions.dart'; +export 'src/widgets/animated_component.dart'; +export 'src/widgets/app.dart'; +export 'src/widgets/basic.dart'; +export 'src/widgets/binding.dart'; +export 'src/widgets/button_state.dart'; +export 'src/widgets/card.dart'; +export 'src/widgets/checkbox.dart'; +export 'src/widgets/date_picker.dart'; +export 'src/widgets/dialog.dart'; +export 'src/widgets/dismissable.dart'; +export 'src/widgets/drag_target.dart'; +export 'src/widgets/drawer.dart'; +export 'src/widgets/drawer_divider.dart'; +export 'src/widgets/drawer_header.dart'; +export 'src/widgets/drawer_item.dart'; +export 'src/widgets/editable_text.dart'; +export 'src/widgets/flat_button.dart'; +export 'src/widgets/floating_action_button.dart'; +export 'src/widgets/focus.dart'; +export 'src/widgets/framework.dart'; +export 'src/widgets/gesture_detector.dart'; +export 'src/widgets/homogeneous_viewport.dart'; +export 'src/widgets/icon.dart'; +export 'src/widgets/icon_button.dart'; +export 'src/widgets/ink_well.dart'; +export 'src/widgets/input.dart'; +export 'src/widgets/material.dart'; +export 'src/widgets/material_button.dart'; +export 'src/widgets/mimic.dart'; +export 'src/widgets/mixed_viewport.dart'; +export 'src/widgets/navigator.dart'; +export 'src/widgets/popup_menu.dart'; +export 'src/widgets/popup_menu_item.dart'; +export 'src/widgets/progress_indicator.dart'; +export 'src/widgets/radio.dart'; +export 'src/widgets/raised_button.dart'; +export 'src/widgets/scaffold.dart'; +export 'src/widgets/scrollable.dart'; +export 'src/widgets/snack_bar.dart'; +export 'src/widgets/switch.dart'; +export 'src/widgets/tabs.dart'; +export 'src/widgets/theme.dart'; +export 'src/widgets/title.dart'; +export 'src/widgets/tool_bar.dart'; +export 'src/widgets/transitions.dart'; +export 'src/widgets/unique_component.dart'; export 'package:vector_math/vector_math.dart' show Matrix4; diff --git a/packages/flutter/lib/widgets_next.dart b/packages/flutter/lib/widgets_next.dart deleted file mode 100644 index bf7f11bb9f..0000000000 --- a/packages/flutter/lib/widgets_next.dart +++ /dev/null @@ -1,8 +0,0 @@ -// 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. - -/// The Flutter widget framework. -library widgets; - -export 'src/fn3.dart'; diff --git a/packages/flutter_sprites/lib/skysprites.dart b/packages/flutter_sprites/lib/skysprites.dart index 54fd5ece2a..8e94b3cb31 100644 --- a/packages/flutter_sprites/lib/skysprites.dart +++ b/packages/flutter_sprites/lib/skysprites.dart @@ -16,7 +16,7 @@ import 'package:sky/animation.dart'; import 'package:sky/painting.dart'; import 'package:sky/rendering.dart'; import 'package:sky/services.dart'; -import 'package:sky/widgets_next.dart'; +import 'package:sky/widgets.dart'; import 'package:vector_math/vector_math.dart'; part 'action.dart'; diff --git a/packages/unit/test/widget/align_test.dart b/packages/unit/test/widget/align_test.dart index 6b7d83bd12..2706c14d03 100644 --- a/packages/unit/test/widget/align_test.dart +++ b/packages/unit/test/widget/align_test.dart @@ -1,4 +1,4 @@ -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'widget_tester.dart'; diff --git a/packages/unit/test/widget/block_test.dart b/packages/unit/test/widget/block_test.dart index b449a4c6c1..fef6d818e4 100644 --- a/packages/unit/test/widget/block_test.dart +++ b/packages/unit/test/widget/block_test.dart @@ -1,4 +1,4 @@ -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import '../engine/mock_events.dart'; diff --git a/packages/unit/test/widget/box_decoration_test.dart b/packages/unit/test/widget/box_decoration_test.dart index 8247b542d4..7ad8b3ef2c 100644 --- a/packages/unit/test/widget/box_decoration_test.dart +++ b/packages/unit/test/widget/box_decoration_test.dart @@ -1,5 +1,5 @@ import 'package:sky/material.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'widget_tester.dart'; diff --git a/packages/unit/test/widget/build_scope_test.dart b/packages/unit/test/widget/build_scope_test.dart index 5400ad93f2..63e55ceb7a 100644 --- a/packages/unit/test/widget/build_scope_test.dart +++ b/packages/unit/test/widget/build_scope_test.dart @@ -1,4 +1,4 @@ -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'widget_tester.dart'; diff --git a/packages/unit/test/widget/center_test.dart b/packages/unit/test/widget/center_test.dart index d2949f4de3..c2b6f2cabe 100644 --- a/packages/unit/test/widget/center_test.dart +++ b/packages/unit/test/widget/center_test.dart @@ -1,4 +1,4 @@ -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'widget_tester.dart'; diff --git a/packages/unit/test/widget/coordinates_test.dart b/packages/unit/test/widget/coordinates_test.dart index 08a7649308..972356ecf2 100644 --- a/packages/unit/test/widget/coordinates_test.dart +++ b/packages/unit/test/widget/coordinates_test.dart @@ -1,5 +1,5 @@ import 'package:sky/rendering.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'widget_tester.dart'; diff --git a/packages/unit/test/widget/date_picker_test.dart b/packages/unit/test/widget/date_picker_test.dart index 802dc3d0be..c0281e8a09 100644 --- a/packages/unit/test/widget/date_picker_test.dart +++ b/packages/unit/test/widget/date_picker_test.dart @@ -1,4 +1,4 @@ -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'widget_tester.dart'; diff --git a/packages/unit/test/widget/dismissable_test.dart b/packages/unit/test/widget/dismissable_test.dart index 04b1b01c76..bcf11e92c1 100644 --- a/packages/unit/test/widget/dismissable_test.dart +++ b/packages/unit/test/widget/dismissable_test.dart @@ -1,5 +1,5 @@ import 'package:quiver/testing/async.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import '../engine/mock_events.dart'; diff --git a/packages/unit/test/widget/draggable_test.dart b/packages/unit/test/widget/draggable_test.dart index da17e9013e..6c92ab9277 100644 --- a/packages/unit/test/widget/draggable_test.dart +++ b/packages/unit/test/widget/draggable_test.dart @@ -1,4 +1,4 @@ -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import '../engine/mock_events.dart'; diff --git a/packages/unit/test/widget/duplicate_key_test.dart b/packages/unit/test/widget/duplicate_key_test.dart index 3fe60f1335..b0d497f343 100644 --- a/packages/unit/test/widget/duplicate_key_test.dart +++ b/packages/unit/test/widget/duplicate_key_test.dart @@ -1,4 +1,4 @@ -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'widget_tester.dart'; diff --git a/packages/unit/test/widget/flex_test.dart b/packages/unit/test/widget/flex_test.dart index 25471cbbc2..ea4a0335fb 100644 --- a/packages/unit/test/widget/flex_test.dart +++ b/packages/unit/test/widget/flex_test.dart @@ -1,4 +1,4 @@ -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'widget_tester.dart'; diff --git a/packages/unit/test/widget/gesture_detector_test.dart b/packages/unit/test/widget/gesture_detector_test.dart index 746ea37383..93d0c643c6 100644 --- a/packages/unit/test/widget/gesture_detector_test.dart +++ b/packages/unit/test/widget/gesture_detector_test.dart @@ -1,4 +1,4 @@ -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import '../engine/mock_events.dart'; diff --git a/packages/unit/test/widget/homogeneous_viewport_test.dart b/packages/unit/test/widget/homogeneous_viewport_test.dart index c2fa3b1507..5e90ca84bf 100644 --- a/packages/unit/test/widget/homogeneous_viewport_test.dart +++ b/packages/unit/test/widget/homogeneous_viewport_test.dart @@ -1,4 +1,4 @@ -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'widget_tester.dart'; diff --git a/packages/unit/test/widget/input_test.dart b/packages/unit/test/widget/input_test.dart index c816030e96..ce8776f0b8 100644 --- a/packages/unit/test/widget/input_test.dart +++ b/packages/unit/test/widget/input_test.dart @@ -2,7 +2,7 @@ import 'package:mojo_services/keyboard/keyboard.mojom.dart'; import 'package:quiver/testing/async.dart'; import 'package:sky/rendering.dart'; import 'package:sky/services.dart'; -import 'package:sky/widgets_next.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'widget_tester.dart'; diff --git a/packages/unit/test/widget/listener_test.dart b/packages/unit/test/widget/listener_test.dart index 19ad382984..c3e53916cc 100644 --- a/packages/unit/test/widget/listener_test.dart +++ b/packages/unit/test/widget/listener_test.dart @@ -1,4 +1,4 @@ -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'widget_tester.dart'; diff --git a/packages/unit/test/widget/mixed_viewport_test.dart b/packages/unit/test/widget/mixed_viewport_test.dart index 466b37f3cd..29ced2b786 100644 --- a/packages/unit/test/widget/mixed_viewport_test.dart +++ b/packages/unit/test/widget/mixed_viewport_test.dart @@ -1,4 +1,4 @@ -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'widget_tester.dart'; diff --git a/packages/unit/test/widget/multichild_test.dart b/packages/unit/test/widget/multichild_test.dart index 89b63e5dbd..6dfaef0695 100644 --- a/packages/unit/test/widget/multichild_test.dart +++ b/packages/unit/test/widget/multichild_test.dart @@ -1,5 +1,5 @@ import 'package:sky/rendering.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'test_widgets.dart'; diff --git a/packages/unit/test/widget/navigator_test.dart b/packages/unit/test/widget/navigator_test.dart index 03c5376553..1e3f06bda9 100644 --- a/packages/unit/test/widget/navigator_test.dart +++ b/packages/unit/test/widget/navigator_test.dart @@ -1,5 +1,5 @@ import 'package:sky/animation.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'widget_tester.dart'; diff --git a/packages/unit/test/widget/pageable_list_test.dart b/packages/unit/test/widget/pageable_list_test.dart index a255c63171..820eb3f64c 100644 --- a/packages/unit/test/widget/pageable_list_test.dart +++ b/packages/unit/test/widget/pageable_list_test.dart @@ -1,5 +1,5 @@ import 'package:quiver/testing/async.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'widget_tester.dart'; diff --git a/packages/unit/test/widget/parent_data_test.dart b/packages/unit/test/widget/parent_data_test.dart index 9ee52c3013..ba3394e4cf 100644 --- a/packages/unit/test/widget/parent_data_test.dart +++ b/packages/unit/test/widget/parent_data_test.dart @@ -1,5 +1,5 @@ import 'package:sky/rendering.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'test_widgets.dart'; diff --git a/packages/unit/test/widget/progress_indicator_test.dart b/packages/unit/test/widget/progress_indicator_test.dart index 9052644069..3d36feb78f 100644 --- a/packages/unit/test/widget/progress_indicator_test.dart +++ b/packages/unit/test/widget/progress_indicator_test.dart @@ -1,6 +1,6 @@ import 'package:sky/rendering.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'widget_tester.dart'; diff --git a/packages/unit/test/widget/render_object_widget_test.dart b/packages/unit/test/widget/render_object_widget_test.dart index 77ac14f2be..6fbc196cc7 100644 --- a/packages/unit/test/widget/render_object_widget_test.dart +++ b/packages/unit/test/widget/render_object_widget_test.dart @@ -1,5 +1,5 @@ import 'package:sky/rendering.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'widget_tester.dart'; diff --git a/packages/unit/test/widget/scrollable_list_hit_testing_test.dart b/packages/unit/test/widget/scrollable_list_hit_testing_test.dart index d2cbf5c4bf..b8c9a1a361 100644 --- a/packages/unit/test/widget/scrollable_list_hit_testing_test.dart +++ b/packages/unit/test/widget/scrollable_list_hit_testing_test.dart @@ -1,5 +1,5 @@ import 'package:sky/rendering.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'widget_tester.dart'; diff --git a/packages/unit/test/widget/scrollable_list_horizontal_test.dart b/packages/unit/test/widget/scrollable_list_horizontal_test.dart index 5197472ef5..b8ff44b37b 100644 --- a/packages/unit/test/widget/scrollable_list_horizontal_test.dart +++ b/packages/unit/test/widget/scrollable_list_horizontal_test.dart @@ -1,5 +1,5 @@ import 'package:sky/rendering.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'widget_tester.dart'; diff --git a/packages/unit/test/widget/scrollable_list_vertical_test.dart b/packages/unit/test/widget/scrollable_list_vertical_test.dart index ad966ef468..84282701b3 100644 --- a/packages/unit/test/widget/scrollable_list_vertical_test.dart +++ b/packages/unit/test/widget/scrollable_list_vertical_test.dart @@ -1,4 +1,4 @@ -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'widget_tester.dart'; diff --git a/packages/unit/test/widget/set_state_3_test.dart b/packages/unit/test/widget/set_state_3_test.dart index 7ce1c867b0..f4f0a8eb04 100644 --- a/packages/unit/test/widget/set_state_3_test.dart +++ b/packages/unit/test/widget/set_state_3_test.dart @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'widget_tester.dart'; diff --git a/packages/unit/test/widget/set_state_test.dart b/packages/unit/test/widget/set_state_test.dart index 0be59b1e4f..43bb81aa14 100644 --- a/packages/unit/test/widget/set_state_test.dart +++ b/packages/unit/test/widget/set_state_test.dart @@ -1,4 +1,4 @@ -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import '../engine/mock_events.dart'; diff --git a/packages/unit/test/widget/snap_scrolling_test.dart b/packages/unit/test/widget/snap_scrolling_test.dart index aa99926185..871473bedd 100644 --- a/packages/unit/test/widget/snap_scrolling_test.dart +++ b/packages/unit/test/widget/snap_scrolling_test.dart @@ -5,7 +5,7 @@ import 'dart:async'; import 'package:quiver/testing/async.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'widget_tester.dart'; diff --git a/packages/unit/test/widget/stack_test.dart b/packages/unit/test/widget/stack_test.dart index a494a81be9..405b398bb7 100644 --- a/packages/unit/test/widget/stack_test.dart +++ b/packages/unit/test/widget/stack_test.dart @@ -1,4 +1,4 @@ -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'widget_tester.dart'; diff --git a/packages/unit/test/widget/stateful_component_test.dart b/packages/unit/test/widget/stateful_component_test.dart index de48c069ed..b8bc8499b9 100644 --- a/packages/unit/test/widget/stateful_component_test.dart +++ b/packages/unit/test/widget/stateful_component_test.dart @@ -1,5 +1,5 @@ import 'package:sky/rendering.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'widget_tester.dart'; diff --git a/packages/unit/test/widget/stateful_components_test.dart b/packages/unit/test/widget/stateful_components_test.dart index a5c9ccf91e..f7d7a1f1fd 100644 --- a/packages/unit/test/widget/stateful_components_test.dart +++ b/packages/unit/test/widget/stateful_components_test.dart @@ -1,4 +1,4 @@ -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'widget_tester.dart'; diff --git a/packages/unit/test/widget/syncing_test.dart b/packages/unit/test/widget/syncing_test.dart index 92d5b92b89..e88d1fca72 100644 --- a/packages/unit/test/widget/syncing_test.dart +++ b/packages/unit/test/widget/syncing_test.dart @@ -1,4 +1,4 @@ -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'widget_tester.dart'; diff --git a/packages/unit/test/widget/test_widgets.dart b/packages/unit/test/widget/test_widgets.dart index 9133ca8d9b..62c2dd0135 100644 --- a/packages/unit/test/widget/test_widgets.dart +++ b/packages/unit/test/widget/test_widgets.dart @@ -1,4 +1,4 @@ -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'widget_tester.dart'; diff --git a/packages/unit/test/widget/transform_test.dart b/packages/unit/test/widget/transform_test.dart index 638c67c3d0..ba92424faf 100644 --- a/packages/unit/test/widget/transform_test.dart +++ b/packages/unit/test/widget/transform_test.dart @@ -1,4 +1,4 @@ -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import 'package:test/test.dart'; import 'widget_tester.dart'; diff --git a/packages/unit/test/widget/widget_tester.dart b/packages/unit/test/widget/widget_tester.dart index 3ceb9c0d97..0068a14719 100644 --- a/packages/unit/test/widget/widget_tester.dart +++ b/packages/unit/test/widget/widget_tester.dart @@ -2,7 +2,7 @@ import 'dart:sky' as sky; import 'package:sky/animation.dart'; import 'package:sky/rendering.dart'; -import 'package:sky/src/fn3.dart'; +import 'package:sky/widgets.dart'; import '../engine/mock_events.dart';