Make fn3 the default widget framework

This commit is contained in:
Adam Barth
2015-10-01 09:35:27 -07:00
parent 9fe747e409
commit 45c906d2ad
154 changed files with 3554 additions and 13206 deletions

View File

@@ -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({

View File

@@ -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)

View File

@@ -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';

View File

@@ -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() {

View File

@@ -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';

View File

@@ -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() {

View File

@@ -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() {

View File

@@ -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!')));

View File

@@ -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,

View File

@@ -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';

View File

@@ -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 });

View File

@@ -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);

View File

@@ -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) {

View File

@@ -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());

View File

@@ -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);

View File

@@ -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 });

View File

@@ -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<String, RouteBuilder> routes = <String, RouteBuilder>{
'/': (NavigatorState navigator, Route route) => new Container(

View File

@@ -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);

View File

@@ -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";

View File

@@ -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();

View File

@@ -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();

View File

@@ -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();

View File

@@ -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();

View File

@@ -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;

View File

@@ -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<T extends AnimatedComponent> extends State<T> {
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() { }
}

View File

@@ -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<Widget> 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<Widget> 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<Widget> 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<Widget> 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<Widget> 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<Widget> 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" | [<text-style> <elements>*]
// 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<ImageListener> {
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;
}
}

View File

@@ -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
///
/// <https://www.google.com/design/spec/components/cards.html>
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
)
);
}
}

View File

@@ -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.
///
/// <https://www.google.com/design/spec/components/lists-controls.html#lists-controls-types-of-list-controls>
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);
}
}
}

View File

@@ -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<DatePicker> {
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<Text> headers = [];
for (String weekDay in symbols.NARROWWEEKDAYS) {
headers.add(new Text(weekDay, style: headerStyle));
}
List<Widget> 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<int> days = [
DateTime.SUNDAY,
DateTime.MONDAY,
DateTime.TUESDAY,
DateTime.WEDNESDAY,
DateTime.THURSDAY,
DateTime.FRIDAY,
DateTime.SATURDAY
];
int daySlots = weeksShown * days.length;
List<Widget> 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<MonthPicker> {
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<Widget> buildItems(BuildContext context, int start, int count) {
List<Widget> result = new List<Widget>();
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<YearPicker> {
int get itemCount => config.lastDate.year - config.firstDate.year + 1;
List<Widget> buildItems(BuildContext context, int start, int count) {
TextStyle style = Theme.of(context).text.body1.copyWith(color: Colors.black54);
List<Widget> items = new List<Widget>();
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;
}
}

View File

@@ -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
///
/// <https://www.google.com/design/spec/components/dialogs.html>
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<Widget> 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<Widget> dialogBody = new List<Widget>();
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<double>(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;
}

View File

@@ -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<Dismissable> {
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<double> squashAxisExtent = new AnimatedValue<double>(
_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<double>(1.0, end: 0.0),
child: new SlideTransition(
performance: _fadePerformance.view,
position: new AnimatedValue<Point>(Point.origin, end: _activeCardDragEndPoint),
child: config.child
)
)
)
);
}
}

View File

@@ -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>(T data);
typedef void DragTargetAccept<T>(T data);
typedef Widget DragTargetBuilder<T>(BuildContext context, List<T> candidateData, List<dynamic> 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<Draggable> {
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<T> extends StatefulComponent {
const DragTarget({
Key key,
this.builder,
this.onWillAccept,
this.onAccept
}) : super(key: key);
final DragTargetBuilder<T> builder;
final DragTargetWillAccept<T> onWillAccept;
final DragTargetAccept<T> onAccept;
DragTargetState<T> createState() => new DragTargetState<T>();
}
class DragTargetState<T> extends State<DragTarget<T>> {
final List<T> _candidateData = new List<T>();
final List<dynamic> _rejectedData = new List<dynamic>();
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<T>(_candidateData),
new UnmodifiableListView<dynamic>(_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<HitTestEntry> 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
)
)
);
}
}

View File

@@ -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<Widget> children;
final bool showing;
final int level;
final DrawerDismissedCallback onDismissed;
final NavigatorState navigator;
DrawerState createState() => new DrawerState();
}
class DrawerState extends State<Drawer> {
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<Point>(_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();
}
}
}

View File

@@ -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)
);
}
}

View File

@@ -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
)
)]
)
);
}
}

View File

@@ -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<DrawerItem> {
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<Widget> flexChildren = new List<Widget>();
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)
)
)
);
}
}

View File

@@ -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<EditableText> {
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)
]);
}
}

View File

@@ -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<FlatButton> {
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;
}

View File

@@ -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<FloatingActionButton> {
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
)
)
)
)
)
)
);
}
}

View File

@@ -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<Focus> {
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);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -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<GestureDetector> {
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
);
}
}

View File

@@ -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<Widget> 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<HomogeneousViewport> {
HomogeneousViewportElement(HomogeneousViewport widget) : super(widget);
List<Element> _children = const <Element>[];
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<Widget> newWidgets;
if (_layoutItemCount > 0)
newWidgets = widget.builder(this, _layoutFirstIndex, _layoutItemCount);
else
newWidgets = <Widget>[];
_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);
}
}

View File

@@ -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<String> 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
);
}
}

View File

@@ -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))
);
}
}

View File

@@ -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<double>(
_kSplashInitialSize, end: _targetRadius, curve: easeOut);
_performance = new ValueAnimation<double>(
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<double> _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<InkSplash> _splashes = new List<InkSplash>();
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();
}

View File

@@ -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<Input> {
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<Widget> textChildren = <Widget>[];
if (config.placeholder != null && _value.isEmpty) {
Widget child = new Opacity(
key: const ValueKey<String>('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)
);
}
}

View File

@@ -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<MaterialType, double> 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
)
);
}
}

View File

@@ -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<T extends MaterialButton> extends ButtonState<T> {
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)
)
)
);
}
}

View File

@@ -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<Mimicable> {
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
);
}
}

View File

@@ -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<int> 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<MixedViewport> {
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<double> _childExtents = <double>[];
/// _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<double> _childOffsets = <double>[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<int> _invalidIndices = new Set<int>();
/// 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<int> 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<int, Element> builtChildren = new Map<int, Element>();
// 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<int> 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);
}
}

View File

@@ -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<String, RouteBuilder> routes;
final RouteGenerator onGenerateRoute;
final RouteBuilder onUnknownRoute;
NavigatorState createState() => new NavigatorState();
}
class NavigatorState extends State<Navigator> {
List<Route> _history = new List<Route>();
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<Widget> visibleRoutes = new List<Widget>();
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<Point>(_kTransitionStartPoint, end: Point.origin, curve: easeOut),
child: new FadeTransition(
performance: performance,
opacity: new AnimatedValue<double>(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;
}

View File

@@ -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<PopupMenuItem> 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<PopupMenuItem> items;
final int level;
final NavigatorState navigator;
final WatchableAnimationPerformance performance;
PopupMenuState createState() => new PopupMenuState();
}
class PopupMenuState extends State<PopupMenu> {
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<Widget> 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<double>(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<double>(0.0, end: 1.0, interval: new Interval(0.0, unit));
final height = new AnimatedValue<double>(0.0, end: 1.0, interval: new Interval(0.0, unit * config.items.length));
return new FadeTransition(
performance: config.performance,
opacity: new AnimatedValue<double>(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 <PopupMenuItem>[],
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;
}

View File

@@ -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
)
)
)
);
}
}

View File

@@ -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<ProgressIndicator> {
ValueAnimation<double> _performance;
void initState() {
super.initState();
_performance = new ValueAnimation<double>(
variable: new AnimatedValue<double>(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);
}
)
);
}
}

View File

@@ -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<Radio> {
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);
}
}
)
)
);
}
}

View File

@@ -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<RaisedButton> {
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;
}

View File

@@ -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<ScaffoldSlots, RenderBox> _slots = new Map<ScaffoldSlots, RenderBox>();
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<ScaffoldSlots, Widget> _children = new Map<ScaffoldSlots, Widget>();
RenderScaffold createRenderObject() => new RenderScaffold();
ScaffoldElement createElement() => new ScaffoldElement(this);
}
class ScaffoldElement extends RenderObjectElement<Scaffold> {
ScaffoldElement(Scaffold widget) : super(widget);
Map<ScaffoldSlots, Element> _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<ScaffoldSlots, Element>();
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);
}
}

View File

@@ -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<T extends Scrollable> extends State<T> {
void initState() {
super.initState();
if (config.initialScrollOffset is double)
_scrollOffset = config.initialScrollOffset;
_toEndAnimation = new AnimatedSimulation(_setScrollOffset);
_toOffsetAnimation = new ValueAnimation<double>()
..addListener(() {
AnimatedValue<double> offset = _toOffsetAnimation.variable;
_setScrollOffset(offset.value);
});
}
AnimatedSimulation _toEndAnimation; // See _startToEndAnimation()
ValueAnimation<double> _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<double>(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<ScrollableViewport> {
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<Widget> 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<T extends ScrollableWidgetList> extends ScrollableState<T> {
/// 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<Widget> _buildItems(BuildContext context, int start, int count) {
List<Widget> result = buildItems(context, start, count);
assert(result.every((item) => item.key != null));
return result;
}
List<Widget> buildItems(BuildContext context, int start, int count);
}
typedef Widget ItemBuilder<T>(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<T> 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<T> items;
final ItemBuilder<T> itemBuilder;
ScrollableListState<T, ScrollableList<T>> createState() => new ScrollableListState<T, ScrollableList<T>>();
}
class ScrollableListState<T, Config extends ScrollableList<T>> extends ScrollableWidgetListState<Config> {
ScrollBehavior createScrollBehavior() {
return config.itemsWrap ? new UnboundedBehavior() : super.createScrollBehavior();
}
int get itemCount => config.items.length;
List<Widget> buildItems(BuildContext context, int start, int count) {
List<Widget> result = new List<Widget>();
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<T> extends ScrollableList<T> {
PageableList({
Key key,
double initialScrollOffset,
ScrollDirection scrollDirection: ScrollDirection.horizontal,
ScrollListener onScroll,
List<T> items,
ItemBuilder<T> 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<T> createState() => new PageableListState();
}
class PageableListState<T> extends ScrollableListState<T, PageableList<T>> {
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<ScrollableMixedWidgetList> {
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
)
);
}
}

View File

@@ -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<SnackBarAction> actions;
final SnackBarDismissedCallback onDismissed;
SnackBarState createState() => new SnackBarState();
}
class SnackBarState extends AnimatedState<SnackBar> {
void handleDismissed() {
if (config.onDismissed != null)
config.onDismissed();
}
Widget build(BuildContext context) {
List<Widget> 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<double>(
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)
)
)
)
)
)
);
}
}

View File

@@ -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);
}
}

View File

@@ -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<double> 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<RenderBox> { }
class RenderTabBar extends RenderBox with
ContainerRenderObjectMixin<RenderBox, TabBarParentData>,
RenderBoxContainerDefaultsMixin<RenderBox, TabBarParentData> {
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<double> layoutWidths;
LayoutChanged onLayoutChanged;
void reportLayoutChangedIfNeeded() {
assert(onLayoutChanged != null);
List<double> widths = new List<double>(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<Widget> 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(
<Widget>[
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<TabLabel> labels;
final int selectedIndex;
final SelectedIndexChanged onChanged;
final bool isScrollable;
TabBarState createState() => new TabBarState();
}
class TabBarState extends ScrollableState<TabBar> {
void initState() {
super.initState();
_indicatorAnimation = new ValueAnimation<Rect>()
..duration = _kTabBarScroll
..variable = new AnimatedRect(null, curve: ease);
scrollBehavior.isScrollable = config.isScrollable;
}
Size _tabBarSize;
Size _viewportSize = Size.zero;
List<double> _tabWidths;
ValueAnimation<Rect> _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<double> 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<Widget> tabs = <Widget>[];
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<TabNavigatorView> 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))
]);
}
}

View File

@@ -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;
}

View File

@@ -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;
}
}

View File

@@ -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<Widget> 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<Widget> children = new List<Widget>();
// 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;
}
}

View File

@@ -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<TransitionComponent> {
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<Point> 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<double> 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<double> width;
final AnimatedValue<double> 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<AnimatedValue> variables;
final BuilderFunction builder;
Widget build(BuildContext context) {
for (int i = 0; i < variables.length; ++i)
performance.updateVariable(variables[i]);
return builder(context);
}
}

View File

@@ -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<T extends AnimatedComponent> extends State<T> {
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() { }
}

View File

@@ -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<BoxConstraints> {
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<BoxDecoration> {
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<EdgeDims> {
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<Matrix4> {
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<T> {
final AnimationPerformance performance = new AnimationPerformance();
final AnimatedValue<T> _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<T> extends AnimationBehavior {
ImplicitlyAnimatedFieldBehavior(this.duration);
Duration duration;
ImplicitlyAnimatedValue<T> field;
// Overrides.
T getter(AnimatedContainer container);
void setter(AnimatedContainer container, T value);
AnimatedValue<T> 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<T>(initField(newValue), duration);
field.performance.addListener(() {
original.setState(() { setter(original, field.value); });
});
}
}
}
class ImplicitlyAnimatedConstraintsBehavior extends ImplicitlyAnimatedFieldBehavior<BoxConstraints> {
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<BoxDecoration> {
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<EdgeDims> {
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<EdgeDims> {
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<Matrix4> {
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<double> {
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<double>(val);
}
class ImplicitlyAnimatedHeightBehavior extends ImplicitlyAnimatedFieldBehavior<double> {
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<double>(val);
}
List<AnimationBehavior> 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<AnimationBehavior> 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
);
}
}

View File

@@ -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),

View File

@@ -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<Widget> 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<Widget> children, { Key key })
: super(key: key, children: children);
class Stack extends MultiChildRenderObjectWidget {
Stack(List<Widget> 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<Widget> 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<Widget> 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" | [<text-style> <elements>*]
// 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<ImageListener> {
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;
}
}

View File

@@ -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 {

View File

@@ -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();
}

View File

@@ -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<T extends StatefulComponent> extends State<T> {
bool highlight = false;

View File

@@ -11,13 +11,13 @@ const EdgeDims _kCardMargins = const EdgeDims.all(4.0);
/// A material design card
///
/// <https://www.google.com/design/spec/components/cards.html>
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(

View File

@@ -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.
///
/// <https://www.google.com/design/spec/components/lists-controls.html#lists-controls-types-of-list-controls>
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);

View File

@@ -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<DatePicker> {
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<MonthPicker> {
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<Widget> buildItems(int start, int count) {
List<Widget> buildItems(BuildContext context, int start, int count) {
List<Widget> result = new List<Widget>();
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<Widget> buildItems(int start, int count) {
TextStyle style = Theme.of(this).text.body1.copyWith(color: Colors.black54);
class YearPickerState extends ScrollableWidgetListState<YearPicker> {
int get itemCount => config.lastDate.year - config.firstDate.year + 1;
List<Widget> buildItems(BuildContext context, int start, int count) {
TextStyle style = Theme.of(context).text.body1.copyWith(color: Colors.black54);
List<Widget> items = new List<Widget>();
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(

View File

@@ -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;
}

View File

@@ -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
///
/// <https://www.google.com/design/spec/components/dialogs.html>
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<Widget> dialogBody = new List<Widget>();
@@ -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<double>(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,

View File

@@ -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<Dismissable> {
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<double> squashAxisExtent = new AnimatedValue<double>(
_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>(Point.origin, end: _activeCardDragEndPoint),
child: child
child: config.child
)
)
)

View File

@@ -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>(T data);
typedef void DragTargetAccept<T>(T data);
typedef Widget DragTargetBuilder<T>(List<T> candidateData, List<dynamic> rejectedData);
typedef Widget DragTargetBuilder<T>(BuildContext context, List<T> candidateData, List<dynamic> 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<Draggable> {
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<T> extends StatefulComponent {
DragTarget({
const DragTarget({
Key key,
this.builder,
this.onWillAccept,
this.onAccept
}) : super(key: key);
DragTargetBuilder<T> builder;
DragTargetWillAccept<T> onWillAccept;
DragTargetAccept<T> onAccept;
final DragTargetBuilder<T> builder;
final DragTargetWillAccept<T> onWillAccept;
final DragTargetAccept<T> onAccept;
DragTargetState<T> createState() => new DragTargetState<T>();
}
class DragTargetState<T> extends State<DragTarget<T>> {
final List<T> _candidateData = new List<T>();
final List<dynamic> _rejectedData = new List<dynamic>();
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<T> extends StatefulComponent {
setState(() {
_candidateData.remove(data);
});
if (onAccept != null)
onAccept(data);
if (config.onAccept != null)
config.onAccept(data);
}
Widget build() {
return builder(new UnmodifiableListView<T>(_candidateData),
new UnmodifiableListView<dynamic>(_rejectedData));
Widget build(BuildContext context) {
return new MetaData(
metaData: this,
child: config.builder(context,
new UnmodifiableListView<T>(_candidateData),
new UnmodifiableListView<dynamic>(_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<HitTestEntry> 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<HitTestEntry> 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
)
)
);
}
}

View File

@@ -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<Widget> children;
bool showing;
int level;
DrawerDismissedCallback onDismissed;
Navigator navigator;
final List<Widget> children;
final bool showing;
final int level;
final DrawerDismissedCallback onDismissed;
final NavigatorState navigator;
AnimationPerformance _performance;
DrawerState createState() => new DrawerState();
}
class DrawerState extends State<Drawer> {
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<Point>(_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;

View File

@@ -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
)
)
),

View File

@@ -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
)
)]
)
);
}
}

View File

@@ -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<DrawerItem> {
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<Widget> flexChildren = new List<Widget>();
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)),

View File

@@ -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<EditableText> {
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)
]);
}
}

View File

@@ -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<FlatButton> {
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:

View File

@@ -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<FloatingActionButton> {
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 {
)
);
}
}

View File

@@ -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<Focus> {
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<String> details) {
super.debugAddDetails(details);
details.add('focusedScope=$_focusedScope');
details.add('focusedWidget=$_focusedWidget');
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -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<GestureDetector> {
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
);
}
}

View File

@@ -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() { }
}

View File

@@ -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<Widget> ListBuilder(int startIndex, int count);
typedef List<Widget> 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<Widget> _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<HomogeneousViewport> {
HomogeneousViewportElement(HomogeneousViewport widget) : super(widget);
List<Element> _children = const <Element>[];
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<Widget> newChildren;
List<Widget> newWidgets;
if (_layoutItemCount > 0)
newChildren = builder(_layoutFirstIndex, _layoutItemCount);
newWidgets = widget.builder(this, _layoutFirstIndex, _layoutItemCount);
else
newChildren = <Widget>[];
syncChildren(newChildren, _children == null ? <Widget>[] : _children);
_children = newChildren;
newWidgets = <Widget>[];
_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);
}
}

View File

@@ -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<String> 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',

View File

@@ -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))
);
}
}

View File

@@ -30,11 +30,11 @@ class InkSplash {
_radius = new AnimatedValue<double>(
_kSplashInitialSize, end: _targetRadius, curve: easeOut);
_performance = new AnimationPerformance()
..variable = _radius
..duration = new Duration(milliseconds: (_targetRadius / _kSplashUnconfirmedVelocity).floor())
..addListener(_handleRadiusChange)
..play();
_performance = new ValueAnimation<double>(
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();
}

View File

@@ -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<Input> {
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<Widget> textChildren = <Widget>[];
if (placeholder != null && _value.isEmpty) {
if (config.placeholder != null && _value.isEmpty) {
Widget child = new Opacity(
key: const ValueKey<String>('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)
);
}
}

View File

@@ -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<MaterialType, double> 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
)
);
}
}

View File

@@ -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<T extends MaterialButton> extends ButtonState<T> {
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)
)
)
);
}
}

View File

@@ -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<Mimicable> {
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
);
}
}

View File

@@ -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<int> 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 = <double>[0.0],
_firstVisibleChildIndex = 0,
_visibleChildCount = 0,
_didReachLastChild = false
{
_readOnlyChildOffsets = new UnmodifiableListView<double>(_childOffsets);
class MixedViewportElement extends RenderObjectElement<MixedViewport> {
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<double> _childExtents = <double>[];
/// _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<double> _childOffsets = <double>[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<double> _childOffsets;
UnmodifiableListView<double> _readOnlyChildOffsets;
UnmodifiableListView<double> get childOffsets => _readOnlyChildOffsets;
double get contentsSize => _childOffsets.last;
/// The child offsets that we've been told are invalid.
final Set<int> _invalidIndices = new Set<int>();
bool _didReachLastChild;
bool get didReachLastChild => _didReachLastChild;
Set<int> _invalidIndices = new Set<int>();
/// 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<int> indices) {
_invalidIndices.addAll(indices);
}
final List<Function> _listeners = new List<Function>();
void addListener(Function listener) {
_listeners.add(listener);
}
void removeListener(Function listener) {
_listeners.remove(listener);
}
void _notifyListeners() {
List<Function> localListeners = new List<Function>.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<int> 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<double> 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 = <double>[0.0];
layoutState._invalidIndices = new Set<int>();
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<double> 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<double> 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<int, Widget> builtChildren = new Map<int, Widget>();
Map<_ChildKey, Element> newChildren = new Map<_ChildKey, Element>();
Map<int, Element> builtChildren = new Map<int, Element>();
final List<double> 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<int> 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<int> 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);
}
}

Some files were not shown because too many files have changed in this diff Show More