time_picker.dart 13.4 KB
Newer Older
1 2 3 4
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
import 'dart:math' as math;

Adam Barth's avatar
Adam Barth committed
7
import 'package:flutter/animation.dart';
8 9
import 'package:flutter/painting.dart';
import 'package:flutter/rendering.dart';
10 11 12 13 14 15
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';

import 'colors.dart';
import 'theme.dart';
import 'typography.dart';
Adam Barth's avatar
Adam Barth committed
16
import 'constants.dart';
17

Adam Barth's avatar
Adam Barth committed
18 19 20 21 22 23 24 25 26 27 28 29
const Duration _kDialAnimateDuration = const Duration(milliseconds: 200);
const double _kTwoPi = 2 * math.PI;
const int _kHoursPerDay = 24;
const int _kHoursPerPeriod = 12;
const int _kMinutesPerHour = 60;

enum DayPeriod {
  am,
  pm,
}

/// A value representing a time during the day
30 31 32
class TimeOfDay {
  const TimeOfDay({ this.hour, this.minute });

Adam Barth's avatar
Adam Barth committed
33
  /// Returns a new TimeOfDay with the hour and/or minute replaced.
34
  TimeOfDay replacing({ int hour, int minute }) {
Adam Barth's avatar
Adam Barth committed
35 36
    assert(hour == null || (hour >= 0 && hour < _kHoursPerDay));
    assert(minute == null || (minute >= 0 && minute < _kMinutesPerHour));
37 38 39
    return new TimeOfDay(hour: hour ?? this.hour, minute: minute ?? this.minute);
  }

40 41 42 43 44
  /// The selected hour, in 24 hour time from 0..23
  final int hour;

  /// The selected minute.
  final int minute;
45

Adam Barth's avatar
Adam Barth committed
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
  /// Whether this time of day is before or after noon.
  DayPeriod get period => hour < _kHoursPerPeriod ? DayPeriod.am : DayPeriod.pm;

  /// Which hour of the current period (e.g., am or pm) this time is.
  int get hourOfPeriod => hour - periodOffset;

  String _addLeadingZeroIfNeeded(int value) {
    if (value < 10)
      return '0$value';
    return value.toString();
  }

  /// A string representing the hour, in 24 hour time (e.g., '04' or '18').
  String get hourLabel => _addLeadingZeroIfNeeded(hour);

  /// A string representing the minute (e.g., '07').
  String get minuteLabel => _addLeadingZeroIfNeeded(minute);

  /// A string representing the hour of the current period (e.g., '4' or '6').
  String get hourOfPeriodLabel {
    // TODO(ianh): Localize.
    final int hourOfPeriod = this.hourOfPeriod;
    if (hourOfPeriod == 0)
      return '12';
    return hourOfPeriod.toString();
  }

  /// A string representing the current period (e.g., 'a.m.').
  String get periodLabel => period == DayPeriod.am ? 'a.m.' : 'p.m.'; // TODO(ianh): Localize.

  /// The hour at which the current period starts.
  int get periodOffset => period == DayPeriod.am ? 0 : _kHoursPerPeriod;

79 80 81 82 83 84 85 86
  bool operator ==(dynamic other) {
    if (other is! TimeOfDay)
      return false;
    final TimeOfDay typedOther = other;
    return typedOther.hour == hour
        && typedOther.minute == minute;
  }

87
  int get hashCode => hashValues(hour, minute);
88

Adam Barth's avatar
Adam Barth committed
89 90
  // TODO(ianh): Localize.
  String toString() => '$hourOfPeriodLabel:$minuteLabel $periodLabel';
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
}

enum _TimePickerMode { hour, minute }

class TimePicker extends StatefulComponent {
  TimePicker({
    this.selectedTime,
    this.onChanged
  }) {
    assert(selectedTime != null);
  }

  final TimeOfDay selectedTime;
  final ValueChanged<TimeOfDay> onChanged;

  _TimePickerState createState() => new _TimePickerState();
}

class _TimePickerState extends State<TimePicker> {
  _TimePickerMode _mode = _TimePickerMode.hour;

  void _handleModeChanged(_TimePickerMode mode) {
113
    userFeedback.performHapticFeedback(HapticFeedbackType.virtualKey);
114 115 116 117 118 119 120 121 122
    setState(() {
      _mode = mode;
    });
  }

  Widget build(BuildContext context) {
    Widget header = new _TimePickerHeader(
      selectedTime: config.selectedTime,
      mode: _mode,
Adam Barth's avatar
Adam Barth committed
123 124
      onModeChanged: _handleModeChanged,
      onChanged: config.onChanged
125
    );
126 127 128 129 130 131 132 133 134 135 136 137
    return new Column(
      children: <Widget>[
        header,
        new AspectRatio(
          aspectRatio: 1.0,
          child: new Container(
            margin: const EdgeDims.all(12.0),
            child: new _Dial(
              mode: _mode,
              selectedTime: config.selectedTime,
              onChanged: config.onChanged
            )
138 139
          )
        )
140 141 142
      ],
      alignItems: FlexAlignItems.stretch
    );
143 144 145
  }
}

Adam Barth's avatar
Adam Barth committed
146
// TODO(ianh): Localize!
147
class _TimePickerHeader extends StatelessComponent {
Adam Barth's avatar
Adam Barth committed
148 149 150 151 152 153
  _TimePickerHeader({
    this.selectedTime,
    this.mode,
    this.onModeChanged,
    this.onChanged
  }) {
154 155 156 157
    assert(selectedTime != null);
    assert(mode != null);
  }

158 159 160
  final TimeOfDay selectedTime;
  final _TimePickerMode mode;
  final ValueChanged<_TimePickerMode> onModeChanged;
Adam Barth's avatar
Adam Barth committed
161
  final ValueChanged<TimeOfDay> onChanged;
162 163 164 165 166 167

  void _handleChangeMode(_TimePickerMode value) {
    if (value != mode)
      onModeChanged(value);
  }

Adam Barth's avatar
Adam Barth committed
168 169 170 171 172
  void _handleChangeDayPeriod() {
    int newHour = (selectedTime.hour + _kHoursPerPeriod) % _kHoursPerDay;
    onChanged(selectedTime.replacing(hour: newHour));
  }

173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
  Widget build(BuildContext context) {
    ThemeData theme = Theme.of(context);
    TextTheme headerTheme = theme.primaryTextTheme;

    Color activeColor;
    Color inactiveColor;
    switch(theme.primaryColorBrightness) {
      case ThemeBrightness.light:
        activeColor = Colors.black87;
        inactiveColor = Colors.black54;
        break;
      case ThemeBrightness.dark:
        activeColor = Colors.white;
        inactiveColor = Colors.white70;
        break;
    }
189 190
    TextStyle activeStyle = headerTheme.display3.copyWith(color: activeColor);
    TextStyle inactiveStyle = headerTheme.display3.copyWith(color: inactiveColor);
191 192 193 194

    TextStyle hourStyle = mode == _TimePickerMode.hour ? activeStyle : inactiveStyle;
    TextStyle minuteStyle = mode == _TimePickerMode.minute ? activeStyle : inactiveStyle;

Adam Barth's avatar
Adam Barth committed
195 196 197 198 199 200 201
    TextStyle amStyle = headerTheme.subhead.copyWith(
      color: selectedTime.period == DayPeriod.am ? activeColor: inactiveColor
    );
    TextStyle pmStyle = headerTheme.subhead.copyWith(
      color: selectedTime.period == DayPeriod.pm ? activeColor: inactiveColor
    );

202
    return new Container(
Adam Barth's avatar
Adam Barth committed
203
      padding: kDialogHeadingPadding,
204
      decoration: new BoxDecoration(backgroundColor: theme.primaryColor),
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
      child: new Row(
        children: <Widget>[
          new GestureDetector(
            onTap: () => _handleChangeMode(_TimePickerMode.hour),
            child: new Text(selectedTime.hourOfPeriodLabel, style: hourStyle)
          ),
          new Text(':', style: inactiveStyle),
          new GestureDetector(
            onTap: () => _handleChangeMode(_TimePickerMode.minute),
            child: new Text(selectedTime.minuteLabel, style: minuteStyle)
          ),
          new GestureDetector(
            onTap: _handleChangeDayPeriod,
            behavior: HitTestBehavior.opaque,
            child: new Container(
              padding: const EdgeDims.only(left: 16.0, right: 24.0),
              child: new Column(
                children: <Widget>[
                  new Text('AM', style: amStyle),
                  new Container(
                    padding: const EdgeDims.only(top: 4.0),
                    child: new Text('PM', style: pmStyle)
                  ),
                ],
                justifyContent: FlexJustifyContent.end
              )
            )
Adam Barth's avatar
Adam Barth committed
232
          )
233 234 235
        ],
        justifyContent: FlexJustifyContent.end
      )
236 237 238
    );
  }
}
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302

List<TextPainter> _initPainters(List<String> labels) {
  TextStyle style = Typography.black.subhead.copyWith(height: 1.0);
  List<TextPainter> painters = new List<TextPainter>(labels.length);
  for (int i = 0; i < painters.length; ++i) {
    String label = labels[i];
    TextPainter painter = new TextPainter(
      new StyledTextSpan(style, [
        new PlainTextSpan(label)
      ])
    );
    painter
      ..maxWidth = double.INFINITY
      ..maxHeight = double.INFINITY
      ..layout()
      ..maxWidth = painter.maxIntrinsicWidth
      ..layout();
    painters[i] = painter;
  }
  return painters;
}

List<TextPainter> _initHours() {
  return _initPainters(['12', '1', '2', '3', '4', '5',
                        '6', '7', '8', '9', '10', '11']);
}

List<TextPainter> _initMinutes() {
  return _initPainters(['00', '05', '10', '15', '20', '25',
                        '30', '35', '40', '45', '50', '55']);
}

class _DialPainter extends CustomPainter {
  const _DialPainter({
    this.labels,
    this.primaryColor,
    this.theta
  });

  final List<TextPainter> labels;
  final Color primaryColor;
  final double theta;

  void paint(Canvas canvas, Size size) {
    double radius = size.shortestSide / 2.0;
    Offset center = new Offset(size.width / 2.0, size.height / 2.0);
    Point centerPoint = center.toPoint();
    canvas.drawCircle(centerPoint, radius, new Paint()..color = Colors.grey[200]);

    const double labelPadding = 24.0;
    double labelRadius = radius - labelPadding;
    Offset getOffsetForTheta(double theta) {
      return center + new Offset(labelRadius * math.cos(theta),
                                 -labelRadius * math.sin(theta));
    }

    Paint primaryPaint = new Paint()
      ..color = primaryColor;
    Point currentPoint = getOffsetForTheta(theta).toPoint();
    canvas.drawCircle(centerPoint, 4.0, primaryPaint);
    canvas.drawCircle(currentPoint, labelPadding - 4.0, primaryPaint);
    primaryPaint.strokeWidth = 2.0;
    canvas.drawLine(centerPoint, currentPoint, primaryPaint);

Adam Barth's avatar
Adam Barth committed
303
    double labelThetaIncrement = -_kTwoPi / labels.length;
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
    double labelTheta = math.PI / 2.0;

    for (TextPainter label in labels) {
      Offset labelOffset = new Offset(-label.width / 2.0, -label.height / 2.0);
      label.paint(canvas, getOffsetForTheta(labelTheta) + labelOffset);
      labelTheta += labelThetaIncrement;
    }
  }

  bool shouldRepaint(_DialPainter oldPainter) {
    return oldPainter.labels != labels
        || oldPainter.primaryColor != primaryColor
        || oldPainter.theta != theta;
  }
}

class _Dial extends StatefulComponent {
  _Dial({
    this.selectedTime,
    this.mode,
    this.onChanged
  }) {
    assert(selectedTime != null);
  }

  final TimeOfDay selectedTime;
  final _TimePickerMode mode;
  final ValueChanged<TimeOfDay> onChanged;

  _DialState createState() => new _DialState();
}

class _DialState extends State<_Dial> {
  void initState() {
    super.initState();
339 340 341 342 343 344
    _thetaController = new AnimationController(duration: _kDialAnimateDuration);
    _thetaTween = new Tween<double>(begin: _getThetaForTime(config.selectedTime));
    _theta = _thetaTween.animate(new CurvedAnimation(
      parent: _thetaController,
      curve: Curves.ease
    ))..addListener(() => setState(() { }));
345 346 347
  }

  void didUpdateConfig(_Dial oldConfig) {
Adam Barth's avatar
Adam Barth committed
348 349 350 351
    if (config.mode != oldConfig.mode && !_dragging)
      _animateTo(_getThetaForTime(config.selectedTime));
  }

352
  Tween<double> _thetaTween;
353
  Animation<double> _theta;
354
  AnimationController _thetaController;
Adam Barth's avatar
Adam Barth committed
355 356 357 358 359 360 361 362 363 364
  bool _dragging = false;

  static double _nearest(double target, double a, double b) {
    return ((target - a).abs() < (target - b).abs()) ? a : b;
  }

  void _animateTo(double targetTheta) {
    double currentTheta = _theta.value;
    double beginTheta = _nearest(targetTheta, currentTheta, currentTheta + _kTwoPi);
    beginTheta = _nearest(targetTheta, beginTheta, currentTheta - _kTwoPi);
365 366 367 368 369 370
    _thetaTween
      ..begin = beginTheta
      ..end = targetTheta;
    _thetaController
      ..value = 0.0
      ..forward();
371 372 373 374
  }

  double _getThetaForTime(TimeOfDay time) {
    double fraction = (config.mode == _TimePickerMode.hour) ?
Adam Barth's avatar
Adam Barth committed
375 376 377
        (time.hour / _kHoursPerPeriod) % _kHoursPerPeriod :
        (time.minute / _kMinutesPerHour) % _kMinutesPerHour;
    return (math.PI / 2.0 - fraction * _kTwoPi) % _kTwoPi;
378 379 380
  }

  TimeOfDay _getTimeForTheta(double theta) {
Adam Barth's avatar
Adam Barth committed
381
    double fraction = (0.25 - (theta % _kTwoPi) / _kTwoPi) % 1.0;
382
    if (config.mode == _TimePickerMode.hour) {
Adam Barth's avatar
Adam Barth committed
383
      int hourOfPeriod = (fraction * _kHoursPerPeriod).round() % _kHoursPerPeriod;
384
      return config.selectedTime.replacing(
Adam Barth's avatar
Adam Barth committed
385
        hour: hourOfPeriod + config.selectedTime.periodOffset
386 387 388
      );
    } else {
      return config.selectedTime.replacing(
Adam Barth's avatar
Adam Barth committed
389
        minute: (fraction * _kMinutesPerHour).round() % _kMinutesPerHour
390 391 392 393 394 395 396
      );
    }
  }

  void _notifyOnChangedIfNeeded() {
    if (config.onChanged == null)
      return;
Adam Barth's avatar
Adam Barth committed
397
    TimeOfDay current = _getTimeForTheta(_theta.value);
398 399 400 401 402 403 404
    if (current != config.selectedTime)
      config.onChanged(current);
  }

  void _updateThetaForPan() {
    setState(() {
      Offset offset = _position - _center;
405 406 407
      _thetaTween
        ..begin = (math.atan2(offset.dx, offset.dy) - math.PI / 2.0) % _kTwoPi
        ..end = null;
408 409 410 411 412 413 414
    });
  }

  Point _position;
  Point _center;

  void _handlePanStart(Point globalPosition) {
Adam Barth's avatar
Adam Barth committed
415 416
    assert(!_dragging);
    _dragging = true;
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
    RenderBox box = context.findRenderObject();
    _position = box.globalToLocal(globalPosition);
    double radius = box.size.shortestSide / 2.0;
    _center = new Point(radius, radius);
    _updateThetaForPan();
    _notifyOnChangedIfNeeded();
  }

  void _handlePanUpdate(Offset delta) {
    _position += delta;
    _updateThetaForPan();
    _notifyOnChangedIfNeeded();
  }

  void _handlePanEnd(Offset velocity) {
Adam Barth's avatar
Adam Barth committed
432 433
    assert(_dragging);
    _dragging = false;
434 435
    _position = null;
    _center = null;
Adam Barth's avatar
Adam Barth committed
436
    _animateTo(_getThetaForTime(config.selectedTime));
437 438
  }

Adam Barth's avatar
Adam Barth committed
439 440 441
  final List<TextPainter> _hours = _initHours();
  final List<TextPainter> _minutes = _initMinutes();

442 443 444 445 446 447 448
  Widget build(BuildContext context) {
    return new GestureDetector(
      onPanStart: _handlePanStart,
      onPanUpdate: _handlePanUpdate,
      onPanEnd: _handlePanEnd,
      child: new CustomPaint(
        painter: new _DialPainter(
Adam Barth's avatar
Adam Barth committed
449
          labels: config.mode == _TimePickerMode.hour ? _hours : _minutes,
450
          primaryColor: Theme.of(context).primaryColor,
Adam Barth's avatar
Adam Barth committed
451
          theta: _theta.value
452 453 454 455 456
        )
      )
    );
  }
}