From 432bfb4729a69e03d5eb98a71c14a0f08ea43e2e Mon Sep 17 00:00:00 2001 From: Adam Barth Date: Sat, 23 Jan 2016 00:21:18 -0800 Subject: [PATCH 1/4] Add material design features to Input Properly support labels, hints, icons, and custom typography. --- examples/address_book/lib/main.dart | 100 +++------- examples/fitness/lib/meal.dart | 2 +- examples/fitness/lib/measurement.dart | 2 +- examples/fitness/lib/settings.dart | 2 +- examples/stocks/lib/stock_home.dart | 4 +- packages/flutter/lib/src/material/input.dart | 188 ++++++++++++++----- packages/flutter/test/widget/input_test.dart | 8 +- 7 files changed, 180 insertions(+), 126 deletions(-) diff --git a/examples/address_book/lib/main.dart b/examples/address_book/lib/main.dart index 03c35c5855..006f9f6374 100644 --- a/examples/address_book/lib/main.dart +++ b/examples/address_book/lib/main.dart @@ -4,79 +4,41 @@ import 'package:flutter/material.dart'; -class Field extends StatelessComponent { - Field({ - Key key, - this.inputKey, - this.icon, - this.placeholder - }) : super(key: key); - - final GlobalKey inputKey; - final String icon; - final String placeholder; - - Widget build(BuildContext context) { - return new Row( - children: [ - new Padding( - padding: const EdgeDims.symmetric(horizontal: 16.0), - child: new Icon(icon: icon) - ), - new Flexible( - child: new Input( - key: inputKey, - placeholder: placeholder - ) - ) - ] - ); - } -} +final GlobalKey _kNameKey = new GlobalKey(debugLabel: 'name field'); +final GlobalKey _kPhoneKey = new GlobalKey(debugLabel: 'phone field'); +final GlobalKey _kEmailKey = new GlobalKey(debugLabel: 'email field'); +final GlobalKey _kAddressKey = new GlobalKey(debugLabel: 'address field'); +final GlobalKey _kRingtoneKey = new GlobalKey(debugLabel: 'ringtone field'); +final GlobalKey _kNoteKey = new GlobalKey(debugLabel: 'note field'); class AddressBookHome extends StatelessComponent { - Widget buildToolBar(BuildContext context) { - return new ToolBar( - right: [new IconButton(icon: "navigation/check")] - ); - } - - Widget buildFloatingActionButton(BuildContext context) { - return new FloatingActionButton( - child: new Icon(icon: 'image/photo_camera'), - backgroundColor: Theme.of(context).accentColor - ); - } - - static final GlobalKey nameKey = new GlobalKey(debugLabel: 'name field'); - static final GlobalKey phoneKey = new GlobalKey(debugLabel: 'phone field'); - static final GlobalKey emailKey = new GlobalKey(debugLabel: 'email field'); - static final GlobalKey addressKey = new GlobalKey(debugLabel: 'address field'); - static final GlobalKey ringtoneKey = new GlobalKey(debugLabel: 'ringtone field'); - static final GlobalKey noteKey = new GlobalKey(debugLabel: 'note field'); - - Widget buildBody(BuildContext context) { - return new Block(children: [ - new AspectRatio( - aspectRatio: 16.0 / 9.0, - child: new Container( - decoration: new BoxDecoration(backgroundColor: Colors.purple[300]) - ) - ), - new Field(inputKey: nameKey, icon: "social/person", placeholder: "Name"), - new Field(inputKey: phoneKey, icon: "communication/phone", placeholder: "Phone"), - new Field(inputKey: emailKey, icon: "communication/email", placeholder: "Email"), - new Field(inputKey: addressKey, icon: "maps/place", placeholder: "Address"), - new Field(inputKey: ringtoneKey, icon: "av/volume_up", placeholder: "Ringtone"), - new Field(inputKey: noteKey, icon: "content/add", placeholder: "Add note"), - ]); - } - Widget build(BuildContext context) { return new Scaffold( - toolBar: buildToolBar(context), - body: buildBody(context), - floatingActionButton: buildFloatingActionButton(context) + toolBar: new ToolBar( + center: new Text('Edit contact'), + right: [ + new IconButton(icon: 'navigation/check') + ] + ), + body: new Block( + children: [ + new AspectRatio( + aspectRatio: 16.0 / 9.0, + child: new Container( + decoration: new BoxDecoration(backgroundColor: Colors.purple[300]) + ) + ), + new Input(key: _kNameKey, icon: 'social/person', labelText: 'Name', style: Typography.black.display1), + new Input(key: _kPhoneKey, icon: 'communication/phone', hintText: 'Phone'), + new Input(key: _kEmailKey, icon: 'communication/email', hintText: 'Email'), + new Input(key: _kAddressKey, icon: 'maps/place', hintText: 'Address'), + new Input(key: _kRingtoneKey, icon: 'av/volume_up', hintText: 'Ringtone'), + new Input(key: _kNoteKey, icon: 'content/add', hintText: 'Add note'), + ] + ), + floatingActionButton: new FloatingActionButton( + child: new Icon(icon: 'image/photo_camera') + ) ); } } diff --git a/examples/fitness/lib/meal.dart b/examples/fitness/lib/meal.dart index dbd1bdb2cb..25deb9fecf 100644 --- a/examples/fitness/lib/meal.dart +++ b/examples/fitness/lib/meal.dart @@ -90,7 +90,7 @@ class MealFragmentState extends State { new Input( key: descriptionKey, autofocus: true, - placeholder: 'Describe meal', + hintText: 'Describe meal', onChanged: _handleDescriptionChanged ), ], diff --git a/examples/fitness/lib/measurement.dart b/examples/fitness/lib/measurement.dart index 65694eceb5..cabce298aa 100644 --- a/examples/fitness/lib/measurement.dart +++ b/examples/fitness/lib/measurement.dart @@ -142,7 +142,7 @@ class MeasurementFragmentState extends State { new Input( key: weightKey, autofocus: true, - placeholder: 'Enter weight', + hintText: 'Enter weight', keyboardType: KeyboardType.number, onChanged: _handleWeightChanged ), diff --git a/examples/fitness/lib/settings.dart b/examples/fitness/lib/settings.dart index a99544d7b2..7d3e6bf712 100644 --- a/examples/fitness/lib/settings.dart +++ b/examples/fitness/lib/settings.dart @@ -63,7 +63,7 @@ class SettingsFragmentState extends State { content: new Input( key: weightGoalKey, autofocus: true, - placeholder: 'Goal weight in lbs', + hintText: 'Goal weight in lbs', keyboardType: KeyboardType.number, onChanged: _handleGoalWeightChanged ), diff --git a/examples/stocks/lib/stock_home.dart b/examples/stocks/lib/stock_home.dart index a8a971144c..62e4c7f1c1 100644 --- a/examples/stocks/lib/stock_home.dart +++ b/examples/stocks/lib/stock_home.dart @@ -237,7 +237,7 @@ class StockHomeState extends State { center: new Input( key: searchFieldKey, autofocus: true, - placeholder: 'Search stocks', + hintText: 'Search stocks', onChanged: _handleSearchQueryChanged ), backgroundColor: Theme.of(context).canvasColor @@ -254,7 +254,7 @@ class StockHomeState extends State { new Input( key: companyNameKey, autofocus: true, - placeholder: 'Company Name' + hintText: 'Company Name' ), ] ); diff --git a/packages/flutter/lib/src/material/input.dart b/packages/flutter/lib/src/material/input.dart index b55f74646c..52963a80f3 100644 --- a/packages/flutter/lib/src/material/input.dart +++ b/packages/flutter/lib/src/material/input.dart @@ -6,23 +6,29 @@ import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; +import 'colors.dart'; import 'debug.dart'; +import 'icon.dart'; import 'theme.dart'; export 'package:flutter/rendering.dart' show ValueChanged; export 'package:flutter/services.dart' show KeyboardType; -/// A material design text input widget. +/// A material design text input field. class Input extends Scrollable { Input({ GlobalKey key, this.initialValue: '', - this.placeholder, + this.keyboardType: KeyboardType.text, + this.icon, + this.labelText, + this.hintText, + this.errorText, + this.style, this.hideText: false, this.isDense: false, this.autofocus: false, this.onChanged, - this.keyboardType: KeyboardType.text, this.onSubmitted }) : super( key: key, @@ -32,28 +38,40 @@ class Input extends Scrollable { assert(key != null); } - /// Initial editable text for the widget. + /// Initial editable text for the input field. final String initialValue; /// The type of keyboard to use for editing the text. final KeyboardType keyboardType; - /// Hint text to show when the widget doesn't contain editable text. - final String placeholder; + /// An icon to show adjacent to the input field. + final String icon; + + /// Text to show above the input field. + final String labelText; + + /// Text to show inline in the input field when it would otherwise be empty. + final String hintText; + + /// Text to show when the input text is invalid. + final String errorText; + + /// The style to use for the text being edited. + final TextStyle style; /// Whether to hide the text being edited (e.g., for passwords). final bool hideText; - /// Whether the input widget is part of a dense form (i.e., uses less vertical space). + /// Whether the input field is part of a dense form (i.e., uses less vertical space). final bool isDense; - /// Whether this input widget should focus itself is nothing else is already focused. + /// Whether this input field should focus itself is nothing else is already focused. final bool autofocus; /// Called when the text being edited changes. final ValueChanged onChanged; - /// Called when the user indicates that they are done editing the text in the widget. + /// Called when the user indicates that they are done editing the text in the field. final ValueChanged onSubmitted; InputState createState() => new InputState(); @@ -95,6 +113,57 @@ class InputState extends ScrollableState { config.onSubmitted(_value); } + Widget _buildEditableField({ + ThemeData themeData, + bool focused, + Color focusHighlightColor, + TextStyle textStyle, + double topPadding + }) { + Color cursorColor = themeData.primarySwatch == null ? + themeData.accentColor : + themeData.primarySwatch[200]; + + EdgeDims margin = new EdgeDims.only(bottom: config.isDense ? 4.0 : 8.0); + EdgeDims padding = new EdgeDims.only(top: topPadding, bottom: 8.0); + Color borderColor = focusHighlightColor; + double borderWidth = focused ? 2.0 : 1.0; + + if (config.errorText != null) { + borderColor = Colors.red[700]; + borderWidth = 2.0; + if (!config.isDense) { + margin = const EdgeDims.only(bottom: 15.0); + padding = new EdgeDims.only(top: topPadding, bottom: 1.0); + } + } + + return new Container( + margin: margin, + padding: padding, + decoration: new BoxDecoration( + border: new Border( + bottom: new BorderSide( + color: borderColor, + width: borderWidth + ) + ) + ), + child: new SizeObserver( + onSizeChanged: _handleContainerSizeChanged, + child: new RawEditableLine( + value: _editableString, + focused: focused, + style: textStyle, + hideText: config.hideText, + cursorColor: cursorColor, + onContentSizeChanged: _handleContentSizeChanged, + scrollOffset: scrollOffsetVector + ) + ) + ); + } + Widget buildContent(BuildContext context) { assert(debugCheckHasMaterial(context)); ThemeData themeData = Theme.of(context); @@ -109,35 +178,72 @@ class InputState extends ScrollableState { _keyboardHandle.release(); } - TextStyle textStyle = themeData.text.subhead; - List textChildren = []; - - if (config.placeholder != null && _value.isEmpty) { - Widget child = new Opacity( - key: const ValueKey('placeholder'), - child: new Text(config.placeholder, style: textStyle), - opacity: themeData.hintOpacity - ); - textChildren.add(child); - } - + TextStyle textStyle = config.style ?? themeData.text.subhead; Color focusHighlightColor = themeData.accentColor; - Color cursorColor = themeData.accentColor; - if (themeData.primarySwatch != null) { - cursorColor = themeData.primarySwatch[200]; + if (themeData.primarySwatch != null) focusHighlightColor = focused ? themeData.primarySwatch[400] : themeData.hintColor; + double topPadding = config.isDense ? 12.0 : 16.0; + + List stackChildren = []; + + if (config.labelText != null) { + TextStyle labelStyle = themeData.text.caption.copyWith(color: focused ? focusHighlightColor : themeData.hintColor); + stackChildren.add(new Positioned( + left: 0.0, + top: topPadding, + child: new Text(config.labelText, style: labelStyle) + )); + topPadding += labelStyle.fontSize + (config.isDense ? 4.0 : 8.0); } - textChildren.add(new RawEditableLine( - value: _editableString, + if (config.hintText != null && _value.isEmpty) { + TextStyle hintStyle = textStyle.copyWith(color: themeData.hintColor); + stackChildren.add(new Positioned( + left: 0.0, + top: topPadding, + child: new Text(config.hintText, style: hintStyle) + )); + } + + stackChildren.add(_buildEditableField( + themeData: themeData, focused: focused, - style: textStyle, - hideText: config.hideText, - cursorColor: cursorColor, - onContentSizeChanged: _handleContentSizeChanged, - scrollOffset: scrollOffsetVector + focusHighlightColor: focusHighlightColor, + textStyle: textStyle, + topPadding: topPadding )); + if (config.errorText != null && !config.isDense) { + TextStyle errorStyle = themeData.text.caption.copyWith(color: Colors.red[700]); + stackChildren.add(new Positioned( + left: 0.0, + bottom: 0.0, + child: new Text(config.errorText, style: errorStyle) + )); + } + + Widget child = new Stack(children: stackChildren); + + if (config.icon != null) { + double iconSize = config.isDense ? 18.0 : 24.0; + double iconTop = topPadding + (textStyle.fontSize - iconSize) / 2.0; + child = new Row( + alignItems: FlexAlignItems.start, + children: [ + new Container( + margin: new EdgeDims.only(right: 16.0, top: iconTop), + width: config.isDense ? 40.0 : 48.0, + child: new Icon( + icon: config.icon, + color: focused ? focusHighlightColor : Colors.black45, + size: config.isDense ? IconSize.s18 : IconSize.s24 + ) + ), + new Flexible(child: child) + ] + ); + } + return new GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { @@ -149,23 +255,9 @@ class InputState extends ScrollableState { // we'll get told to rebuild and we'll take care of the keyboard then } }, - child: new SizeObserver( - onSizeChanged: _handleContainerSizeChanged, - child: new Container( - child: new Stack(children: textChildren), - margin: config.isDense ? - const EdgeDims.symmetric(vertical: 4.0) : - const EdgeDims.symmetric(vertical: 8.0), - padding: const EdgeDims.symmetric(vertical: 8.0), - decoration: new BoxDecoration( - border: new Border( - bottom: new BorderSide( - color: focusHighlightColor, - width: focused ? 2.0 : 1.0 - ) - ) - ) - ) + child: new Padding( + padding: const EdgeDims.symmetric(horizontal: 16.0), + child: child ) ); } diff --git a/packages/flutter/test/widget/input_test.dart b/packages/flutter/test/widget/input_test.dart index 8b125546ba..564c7138d0 100644 --- a/packages/flutter/test/widget/input_test.dart +++ b/packages/flutter/test/widget/input_test.dart @@ -41,7 +41,7 @@ void main() { child: new Material( child: new Input( key: inputKey, - placeholder: 'Placeholder', + hintText: 'Placeholder', onChanged: (String value) { inputValue = value; } ) ) @@ -81,7 +81,7 @@ void main() { child: new Material( child: new Input( key: inputKey, - placeholder: 'Placeholder' + hintText: 'Placeholder' ) ) ); @@ -123,7 +123,7 @@ void main() { child: new Material( child: new Input( key: inputKey, - placeholder: 'Placeholder' + hintText: 'Placeholder' ) ) ); @@ -159,7 +159,7 @@ void main() { child: new Input( key: inputKey, hideText: true, - placeholder: 'Placeholder' + hintText: 'Placeholder' ) ) ); From 61f82ee18c2fcbf02fd3e580b8284caf55834b86 Mon Sep 17 00:00:00 2001 From: Adam Barth Date: Sat, 23 Jan 2016 01:00:42 -0800 Subject: [PATCH 2/4] Improve the factoring between Input and RawEditableLine RawEditableLine is now responsible for the scrolling behavior, which removes the need for callbacks between RawEditableLine and Input. It also fixes a bug whereby the whole Input widget (including its icon) would scroll when the text got long. --- packages/flutter/lib/src/material/input.dart | 166 +++++++----------- .../lib/src/rendering/editable_line.dart | 25 +-- .../flutter/lib/src/widgets/editable.dart | 111 +++++++++--- packages/flutter/test/widget/input_test.dart | 2 +- 4 files changed, 162 insertions(+), 142 deletions(-) diff --git a/packages/flutter/lib/src/material/input.dart b/packages/flutter/lib/src/material/input.dart index 52963a80f3..35a540ff22 100644 --- a/packages/flutter/lib/src/material/input.dart +++ b/packages/flutter/lib/src/material/input.dart @@ -15,7 +15,7 @@ export 'package:flutter/rendering.dart' show ValueChanged; export 'package:flutter/services.dart' show KeyboardType; /// A material design text input field. -class Input extends Scrollable { +class Input extends StatefulComponent { Input({ GlobalKey key, this.initialValue: '', @@ -30,11 +30,7 @@ class Input extends Scrollable { this.autofocus: false, this.onChanged, this.onSubmitted - }) : super( - key: key, - initialScrollOffset: 0.0, - scrollDirection: Axis.horizontal - ) { + }) : super(key: key) { assert(key != null); } @@ -74,17 +70,15 @@ class Input extends Scrollable { /// Called when the user indicates that they are done editing the text in the field. final ValueChanged onSubmitted; - InputState createState() => new InputState(); + _InputState createState() => new _InputState(); } -class InputState extends ScrollableState { +class _InputState extends State { String _value; EditableString _editableString; KeyboardHandle _keyboardHandle = KeyboardHandle.unattached; - double _contentWidth = 0.0; - double _containerWidth = 0.0; - + // Used by tests. EditableString get editableValue => _editableString; void initState() { @@ -97,6 +91,23 @@ class InputState extends ScrollableState { ); } + void dispose() { + if (_keyboardHandle.attached) + _keyboardHandle.release(); + super.dispose(); + } + + void _attachOrDetachKeyboard(bool focused) { + if (focused && !_keyboardHandle.attached) { + _keyboardHandle = keyboard.show(_editableString.stub, config.keyboardType); + _keyboardHandle.setText(_editableString.text); + _keyboardHandle.setSelection(_editableString.selection.start, + _editableString.selection.end); + } else if (!focused && _keyboardHandle.attached) { + _keyboardHandle.release(); + } + } + void _handleTextUpdated() { if (_value != _editableString.text) { setState(() { @@ -113,70 +124,12 @@ class InputState extends ScrollableState { config.onSubmitted(_value); } - Widget _buildEditableField({ - ThemeData themeData, - bool focused, - Color focusHighlightColor, - TextStyle textStyle, - double topPadding - }) { - Color cursorColor = themeData.primarySwatch == null ? - themeData.accentColor : - themeData.primarySwatch[200]; - - EdgeDims margin = new EdgeDims.only(bottom: config.isDense ? 4.0 : 8.0); - EdgeDims padding = new EdgeDims.only(top: topPadding, bottom: 8.0); - Color borderColor = focusHighlightColor; - double borderWidth = focused ? 2.0 : 1.0; - - if (config.errorText != null) { - borderColor = Colors.red[700]; - borderWidth = 2.0; - if (!config.isDense) { - margin = const EdgeDims.only(bottom: 15.0); - padding = new EdgeDims.only(top: topPadding, bottom: 1.0); - } - } - - return new Container( - margin: margin, - padding: padding, - decoration: new BoxDecoration( - border: new Border( - bottom: new BorderSide( - color: borderColor, - width: borderWidth - ) - ) - ), - child: new SizeObserver( - onSizeChanged: _handleContainerSizeChanged, - child: new RawEditableLine( - value: _editableString, - focused: focused, - style: textStyle, - hideText: config.hideText, - cursorColor: cursorColor, - onContentSizeChanged: _handleContentSizeChanged, - scrollOffset: scrollOffsetVector - ) - ) - ); - } - - Widget buildContent(BuildContext context) { + Widget build(BuildContext context) { assert(debugCheckHasMaterial(context)); ThemeData themeData = Theme.of(context); bool focused = Focus.at(context, autofocus: config.autofocus); - if (focused && !_keyboardHandle.attached) { - _keyboardHandle = keyboard.show(_editableString.stub, config.keyboardType); - _keyboardHandle.setText(_editableString.text); - _keyboardHandle.setSelection(_editableString.selection.start, - _editableString.selection.end); - } else if (!focused && _keyboardHandle.attached) { - _keyboardHandle.release(); - } + _attachOrDetachKeyboard(focused); TextStyle textStyle = config.style ?? themeData.text.subhead; Color focusHighlightColor = themeData.accentColor; @@ -205,12 +158,42 @@ class InputState extends ScrollableState { )); } - stackChildren.add(_buildEditableField( - themeData: themeData, - focused: focused, - focusHighlightColor: focusHighlightColor, - textStyle: textStyle, - topPadding: topPadding + Color cursorColor = themeData.primarySwatch == null ? + themeData.accentColor : + themeData.primarySwatch[200]; + + EdgeDims margin = new EdgeDims.only(bottom: config.isDense ? 4.0 : 8.0); + EdgeDims padding = new EdgeDims.only(top: topPadding, bottom: 8.0); + Color borderColor = focusHighlightColor; + double borderWidth = focused ? 2.0 : 1.0; + + if (config.errorText != null) { + borderColor = Colors.red[700]; + borderWidth = 2.0; + if (!config.isDense) { + margin = const EdgeDims.only(bottom: 15.0); + padding = new EdgeDims.only(top: topPadding, bottom: 1.0); + } + } + + stackChildren.add(new Container( + margin: margin, + padding: padding, + decoration: new BoxDecoration( + border: new Border( + bottom: new BorderSide( + color: borderColor, + width: borderWidth + ) + ) + ), + child: new RawEditableLine( + value: _editableString, + focused: focused, + style: textStyle, + hideText: config.hideText, + cursorColor: cursorColor + ) )); if (config.errorText != null && !config.isDense) { @@ -261,33 +244,4 @@ class InputState extends ScrollableState { ) ); } - - void dispose() { - if (_keyboardHandle.attached) - _keyboardHandle.release(); - super.dispose(); - } - - ScrollBehavior createScrollBehavior() => new BoundedBehavior(); - BoundedBehavior get scrollBehavior => super.scrollBehavior; - - void _handleContainerSizeChanged(Size newSize) { - _containerWidth = newSize.width; - _updateScrollBehavior(); - } - - void _handleContentSizeChanged(Size newSize) { - _contentWidth = newSize.width; - _updateScrollBehavior(); - } - - void _updateScrollBehavior() { - // Set the scroll offset to match the content width so that the cursor - // (which is always at the end of the text) will be visible. - scrollTo(scrollBehavior.updateExtents( - contentExtent: _contentWidth, - containerExtent: _containerWidth, - scrollOffset: _contentWidth - )); - } } diff --git a/packages/flutter/lib/src/rendering/editable_line.dart b/packages/flutter/lib/src/rendering/editable_line.dart index 05baa34d9e..3e5cac156b 100644 --- a/packages/flutter/lib/src/rendering/editable_line.dart +++ b/packages/flutter/lib/src/rendering/editable_line.dart @@ -22,13 +22,14 @@ class RenderEditableLine extends RenderBox { RenderEditableLine({ StyledTextSpan text, Color cursorColor, - bool showCursor, - this.onContentSizeChanged, - Offset scrollOffset + bool showCursor: false, + Offset paintOffset: Offset.zero, + this.onContentSizeChanged }) : _textPainter = new TextPainter(text), _cursorColor = cursorColor, _showCursor = showCursor, - _scrollOffset = scrollOffset { + _paintOffset = paintOffset { + assert(!showCursor || cursorColor != null); // TODO(abarth): These min/max values should be the default for TextPainter. _textPainter ..minWidth = 0.0 @@ -71,12 +72,12 @@ class RenderEditableLine extends RenderBox { markNeedsPaint(); } - Offset get scrollOffset => _scrollOffset; - Offset _scrollOffset; - void set scrollOffset(Offset value) { - if (_scrollOffset == value) + Offset get paintOffset => _paintOffset; + Offset _paintOffset; + void set paintOffset(Offset value) { + if (_paintOffset == value) return; - _scrollOffset = value; + _paintOffset = value; markNeedsPaint(); } @@ -155,12 +156,12 @@ class RenderEditableLine extends RenderBox { } void _paintContents(PaintingContext context, Offset offset) { - _textPainter.paint(context.canvas, offset - _scrollOffset); + _textPainter.paint(context.canvas, offset + _paintOffset); if (_showCursor) { Rect cursorRect = new Rect.fromLTWH( - offset.dx + _contentSize.width - _kCursorWidth - _scrollOffset.dx, - offset.dy + _kCursorHeightOffset - _scrollOffset.dy, + offset.dx + _paintOffset.dx + _contentSize.width - _kCursorWidth, + offset.dy + _paintOffset.dy + _kCursorHeightOffset, _kCursorWidth, size.height - 2.0 * _kCursorHeightOffset ); diff --git a/packages/flutter/lib/src/widgets/editable.dart b/packages/flutter/lib/src/widgets/editable.dart index 40362b5c88..6debfe0904 100644 --- a/packages/flutter/lib/src/widgets/editable.dart +++ b/packages/flutter/lib/src/widgets/editable.dart @@ -11,26 +11,39 @@ import 'package:flutter/rendering.dart'; import 'basic.dart'; import 'framework.dart'; +import 'scrollable.dart'; +import 'scroll_behavior.dart'; const Duration _kCursorBlinkHalfPeriod = const Duration(milliseconds: 500); /// A range of characters in a string of tet. class TextRange { const TextRange({ this.start, this.end }); + + /// A text range that starts and ends at position. const TextRange.collapsed(int position) : start = position, end = position; + + /// A text range that contains nothing and is not in the text. const TextRange.empty() : start = -1, end = -1; + /// The index of the first character in the range. final int start; + + /// The next index after the characters in this range. final int end; + /// Whether this range represents a valid position in the text. bool get isValid => start >= 0 && end >= 0; + + /// Whether this range is empty (but still potentially placed inside the text). bool get isCollapsed => start == end; } +/// A string that can be manipulated by a keyboard. class EditableString implements KeyboardClient { EditableString({this.text: '', this.onUpdated, this.onSubmitted}) { assert(onUpdated != null); @@ -39,23 +52,35 @@ class EditableString implements KeyboardClient { selection = new TextRange(start: text.length, end: text.length); } + /// The current text being edited. String text; + + // The range of text that is still being composed. TextRange composing = const TextRange.empty(); + + /// The range of text that is currently selected. TextRange selection; + /// Called whenever the text changes. final VoidCallback onUpdated; + + /// Called whenever the user indicates they are done editing the string. final VoidCallback onSubmitted; + /// A keyboard client stub that can be attached to a keyboard service. KeyboardClientStub stub; + /// The text before the given range. String textBefore(TextRange range) { return text.substring(0, range.start); } + /// The text after the given range. String textAfter(TextRange range) { return text.substring(range.end); } + /// The text inside the given range. String textInside(TextRange range) { return text.substring(range.start, range.end); } @@ -141,35 +166,72 @@ class EditableString implements KeyboardClient { } } -class RawEditableLine extends StatefulComponent { +/// A basic single-line input control. +/// +/// This control is not intended to be used directly. Instead, consider using +/// [Input], which provides focus management and material design. +class RawEditableLine extends Scrollable { RawEditableLine({ Key key, this.value, this.focused: false, this.hideText: false, this.style, - this.cursorColor, - this.onContentSizeChanged, - this.scrollOffset - }) : super(key: key); + this.cursorColor + }) : super( + key: key, + initialScrollOffset: 0.0, + scrollDirection: Axis.horizontal + ); + /// The editable string being displayed in this widget. final EditableString value; + + /// Whether this widget is focused. final bool focused; + + /// Whether to hide the text being edited (e.g., for passwords). final bool hideText; + + /// The text style to use for the editable text. final TextStyle style; + + /// The color to use when painting the cursor. final Color cursorColor; - final SizeChangedCallback onContentSizeChanged; - final Offset scrollOffset; RawEditableTextState createState() => new RawEditableTextState(); } -class RawEditableTextState extends State { - // TODO(abarth): Move the cursor timer into RenderEditableLine so we can - // remove this extra widget. +class RawEditableTextState extends ScrollableState { Timer _cursorTimer; bool _showCursor = false; + double _contentWidth = 0.0; + double _containerWidth = 0.0; + + 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 + )); + } + /// Whether the blinking cursor is actually visible at this precise moment /// (it's hidden half the time, since it blinks). bool get cursorCurrentlyVisible => _showCursor; @@ -202,7 +264,7 @@ class RawEditableTextState extends State { _showCursor = false; } - Widget build(BuildContext context) { + Widget buildContent(BuildContext context) { assert(config.style != null); assert(config.focused != null); assert(config.cursorColor != null); @@ -212,14 +274,17 @@ class RawEditableTextState extends State { else if (!config.focused && _cursorTimer != null) _stopCursorTimer(); - return new _EditableLineWidget( - value: config.value, - style: config.style, - cursorColor: config.cursorColor, - showCursor: _showCursor, - hideText: config.hideText, - onContentSizeChanged: config.onContentSizeChanged, - scrollOffset: config.scrollOffset + return new SizeObserver( + onSizeChanged: _handleContainerSizeChanged, + child: new _EditableLineWidget( + value: config.value, + style: config.style, + cursorColor: config.cursorColor, + showCursor: _showCursor, + hideText: config.hideText, + onContentSizeChanged: _handleContentSizeChanged, + paintOffset: new Offset(-scrollOffset, 0.0) + ) ); } } @@ -233,7 +298,7 @@ class _EditableLineWidget extends LeafRenderObjectWidget { this.showCursor, this.hideText, this.onContentSizeChanged, - this.scrollOffset + this.paintOffset }) : super(key: key); final EditableString value; @@ -242,7 +307,7 @@ class _EditableLineWidget extends LeafRenderObjectWidget { final bool showCursor; final bool hideText; final SizeChangedCallback onContentSizeChanged; - final Offset scrollOffset; + final Offset paintOffset; RenderEditableLine createRenderObject() { return new RenderEditableLine( @@ -250,7 +315,7 @@ class _EditableLineWidget extends LeafRenderObjectWidget { cursorColor: cursorColor, showCursor: showCursor, onContentSizeChanged: onContentSizeChanged, - scrollOffset: scrollOffset + paintOffset: paintOffset ); } @@ -260,7 +325,7 @@ class _EditableLineWidget extends LeafRenderObjectWidget { renderObject.cursorColor = cursorColor; renderObject.showCursor = showCursor; renderObject.onContentSizeChanged = onContentSizeChanged; - renderObject.scrollOffset = scrollOffset; + renderObject.paintOffset = paintOffset; } StyledTextSpan get _styledTextSpan { diff --git a/packages/flutter/test/widget/input_test.dart b/packages/flutter/test/widget/input_test.dart index 564c7138d0..904025dde9 100644 --- a/packages/flutter/test/widget/input_test.dart +++ b/packages/flutter/test/widget/input_test.dart @@ -133,7 +133,7 @@ void main() { const String testValue = 'ABC'; mockKeyboard.client.commitText(testValue, testValue.length); - InputState input = tester.findStateOfType(InputState); + dynamic input = inputKey.currentState; // Delete characters and verify that the selection follows the length // of the text. From 7faee3e18ed3c1398f98800be91a55b4c22a4890 Mon Sep 17 00:00:00 2001 From: Adam Barth Date: Sat, 23 Jan 2016 12:22:15 -0800 Subject: [PATCH 3/4] Add implicit animations to Input Now the label animates from its inline position to above the text and the focus highlight grows into place. --- packages/flutter/lib/src/material/input.dart | 35 ++++++++++---- .../flutter/lib/src/painting/box_painter.dart | 47 ++++++++++++++++++- 2 files changed, 72 insertions(+), 10 deletions(-) diff --git a/packages/flutter/lib/src/material/input.dart b/packages/flutter/lib/src/material/input.dart index 35a540ff22..6b300b4d7b 100644 --- a/packages/flutter/lib/src/material/input.dart +++ b/packages/flutter/lib/src/material/input.dart @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'package:flutter/animation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; @@ -73,6 +74,9 @@ class Input extends StatefulComponent { _InputState createState() => new _InputState(); } +const Duration _kTransitionDuration = const Duration(milliseconds: 200); +const Curve _kTransitionCurve = Curves.ease; + class _InputState extends State { String _value; EditableString _editableString; @@ -139,21 +143,34 @@ class _InputState extends State { List stackChildren = []; + bool hasInlineLabel = config.labelText != null && !focused && !_value.isNotEmpty; + if (config.labelText != null) { - TextStyle labelStyle = themeData.text.caption.copyWith(color: focused ? focusHighlightColor : themeData.hintColor); - stackChildren.add(new Positioned( + TextStyle labelStyle = hasInlineLabel ? + themeData.text.subhead.copyWith(color: themeData.hintColor) : + themeData.text.caption.copyWith(color: focused ? focusHighlightColor : themeData.hintColor); + + double topPaddingIncrement = themeData.text.caption.fontSize + (config.isDense ? 4.0 : 8.0); + double top = topPadding; + if (hasInlineLabel) + top += topPaddingIncrement + textStyle.fontSize - labelStyle.fontSize; + + stackChildren.add(new AnimatedPositioned( left: 0.0, - top: topPadding, + top: top, + duration: _kTransitionDuration, + curve: _kTransitionCurve, child: new Text(config.labelText, style: labelStyle) )); - topPadding += labelStyle.fontSize + (config.isDense ? 4.0 : 8.0); + + topPadding += topPaddingIncrement; } - if (config.hintText != null && _value.isEmpty) { - TextStyle hintStyle = textStyle.copyWith(color: themeData.hintColor); + if (config.hintText != null && _value.isEmpty && !hasInlineLabel) { + TextStyle hintStyle = themeData.text.subhead.copyWith(color: themeData.hintColor); stackChildren.add(new Positioned( left: 0.0, - top: topPadding, + top: topPadding + textStyle.fontSize - hintStyle.fontSize, child: new Text(config.hintText, style: hintStyle) )); } @@ -176,9 +193,11 @@ class _InputState extends State { } } - stackChildren.add(new Container( + stackChildren.add(new AnimatedContainer( margin: margin, padding: padding, + duration: _kTransitionDuration, + curve: _kTransitionCurve, decoration: new BoxDecoration( border: new Border( bottom: new BorderSide( diff --git a/packages/flutter/lib/src/painting/box_painter.dart b/packages/flutter/lib/src/painting/box_painter.dart index d37e47c201..c43fbd803a 100644 --- a/packages/flutter/lib/src/painting/box_painter.dart +++ b/packages/flutter/lib/src/painting/box_painter.dart @@ -29,6 +29,25 @@ class BorderSide { /// A black border side of zero width. static const none = const BorderSide(width: 0.0); + BorderSide copyWith({ + Color color, + double width + }) { + return new BorderSide( + color: color ?? this.color, + width: width ?? this.width + ); + } + + static BorderSide lerp(BorderSide a, BorderSide b, double t) { + assert(a != null); + assert(b != null); + return new BorderSide( + color: Color.lerp(a.color, b.color, t), + width: ui.lerpDouble(a.width, b.width, t) + ); + } + bool operator ==(dynamic other) { if (identical(this, other)) return true; @@ -79,6 +98,30 @@ class Border { return new EdgeDims.TRBL(top.width, right.width, bottom.width, left.width); } + Border scale(double t) { + return new Border( + top: top.copyWith(width: t * top.width), + right: right.copyWith(width: t * right.width), + bottom: bottom.copyWith(width: t * bottom.width), + left: left.copyWith(width: t * left.width) + ); + } + + static Border lerp(Border a, Border b, double t) { + if (a == null && b == null) + return null; + if (a == null) + return b.scale(t); + if (b == null) + return a.scale(1.0 - t); + return new Border( + top: BorderSide.lerp(a.top, b.top, t), + right: BorderSide.lerp(a.right, b.right, t), + bottom: BorderSide.lerp(a.bottom, b.bottom, t), + left: BorderSide.lerp(a.left, b.left, t) + ); + } + bool operator ==(dynamic other) { if (identical(this, other)) return true; @@ -718,7 +761,7 @@ class BoxDecoration extends Decoration { return new BoxDecoration( backgroundColor: Color.lerp(null, backgroundColor, factor), backgroundImage: backgroundImage, - border: border, + border: Border.lerp(null, border, factor), borderRadius: ui.lerpDouble(null, borderRadius, factor), boxShadow: BoxShadow.lerpList(null, boxShadow, factor), gradient: gradient, @@ -740,7 +783,7 @@ class BoxDecoration extends Decoration { return new BoxDecoration( backgroundColor: Color.lerp(a.backgroundColor, b.backgroundColor, t), backgroundImage: b.backgroundImage, - border: b.border, + border: Border.lerp(a.border, b.border, t), borderRadius: ui.lerpDouble(a.borderRadius, b.borderRadius, t), boxShadow: BoxShadow.lerpList(a.boxShadow, b.boxShadow, t), gradient: b.gradient, From 5f3b2d48359a7ca6be9ad6392b8d51d072d2f344 Mon Sep 17 00:00:00 2001 From: Adam Barth Date: Sat, 23 Jan 2016 17:47:09 -0800 Subject: [PATCH 4/4] Add errorColor to ThemeData That way folks can customize it if they want (and it makes the code a bit more self-documenting). --- packages/flutter/lib/src/material/input.dart | 4 +-- .../flutter/lib/src/material/theme_data.dart | 25 ++++++++++++++----- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/packages/flutter/lib/src/material/input.dart b/packages/flutter/lib/src/material/input.dart index 6b300b4d7b..e26a2dec61 100644 --- a/packages/flutter/lib/src/material/input.dart +++ b/packages/flutter/lib/src/material/input.dart @@ -185,7 +185,7 @@ class _InputState extends State { double borderWidth = focused ? 2.0 : 1.0; if (config.errorText != null) { - borderColor = Colors.red[700]; + borderColor = themeData.errorColor; borderWidth = 2.0; if (!config.isDense) { margin = const EdgeDims.only(bottom: 15.0); @@ -216,7 +216,7 @@ class _InputState extends State { )); if (config.errorText != null && !config.isDense) { - TextStyle errorStyle = themeData.text.caption.copyWith(color: Colors.red[700]); + TextStyle errorStyle = themeData.text.caption.copyWith(color: themeData.errorColor); stackChildren.add(new Positioned( left: 0.0, bottom: 0.0, diff --git a/packages/flutter/lib/src/material/theme_data.dart b/packages/flutter/lib/src/material/theme_data.dart index 483929b2c1..a9f87d55f7 100644 --- a/packages/flutter/lib/src/material/theme_data.dart +++ b/packages/flutter/lib/src/material/theme_data.dart @@ -46,6 +46,7 @@ class ThemeData { this.indicatorColor, this.hintColor, this.hintOpacity, + this.errorColor, this.text, this.primaryTextTheme, this.primaryIconTheme @@ -66,6 +67,7 @@ class ThemeData { assert(indicatorColor != null); assert(hintColor != null); assert(hintOpacity != null); + assert(errorColor != null); assert(text != null); assert(primaryTextTheme != null); assert(primaryIconTheme != null); @@ -88,6 +90,7 @@ class ThemeData { Color indicatorColor, Color hintColor, double hintOpacity, + Color errorColor, TextTheme text, TextTheme primaryTextTheme, IconThemeData primaryIconTheme @@ -108,6 +111,7 @@ class ThemeData { indicatorColor ??= accentColor == primaryColor ? Colors.white : accentColor; hintColor ??= isDark ? const Color(0x42FFFFFF) : const Color(0x4C000000); hintOpacity ??= hintColor != null ? hintColor.alpha / 0xFF : isDark ? 0.26 : 0.30; + errorColor ??= Colors.red[700]; text ??= isDark ? Typography.white : Typography.black; primaryTextTheme ??= primaryColorBrightness == ThemeBrightness.dark ? Typography.white : Typography.black; primaryIconTheme ??= primaryColorBrightness == ThemeBrightness.dark ? const IconThemeData(color: IconThemeColor.white) : const IconThemeData(color: IconThemeColor.black); @@ -128,6 +132,7 @@ class ThemeData { indicatorColor: indicatorColor, hintColor: hintColor, hintOpacity: hintOpacity, + errorColor: errorColor, text: text, primaryTextTheme: primaryTextTheme, primaryIconTheme: primaryIconTheme @@ -182,6 +187,9 @@ class ThemeData { final Color hintColor; final double hintOpacity; + /// The color to use for input validation errors. + final Color errorColor; + /// Text with a color that contrasts with the card and canvas colors. final TextTheme text; @@ -217,6 +225,7 @@ class ThemeData { indicatorColor: Color.lerp(begin.indicatorColor, end.indicatorColor, t), hintColor: Color.lerp(begin.hintColor, end.hintColor, t), hintOpacity: lerpDouble(begin.hintOpacity, end.hintOpacity, t), + errorColor: Color.lerp(begin.errorColor, end.errorColor, t), text: TextTheme.lerp(begin.text, end.text, t), primaryTextTheme: TextTheme.lerp(begin.primaryTextTheme, end.primaryTextTheme, t), primaryIconTheme: IconThemeData.lerp(begin.primaryIconTheme, end.primaryIconTheme, t) @@ -243,6 +252,7 @@ class ThemeData { (otherData.indicatorColor == indicatorColor) && (otherData.hintColor == hintColor) && (otherData.hintOpacity == hintOpacity) && + (otherData.errorColor == errorColor) && (otherData.text == text) && (otherData.primaryTextTheme == primaryTextTheme) && (otherData.primaryIconTheme == primaryIconTheme); @@ -263,12 +273,15 @@ class ThemeData { disabledColor, accentColor, accentColorBrightness, - indicatorColor, - hintColor, - hintOpacity, - text, - primaryTextTheme, - primaryIconTheme + hashValues( // Too many values. + indicatorColor, + hintColor, + hintOpacity, + errorColor, + text, + primaryTextTheme, + primaryIconTheme + ) ); }