time_picker.dart 13.3 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;

7
import 'package:flutter/services.dart' show HapticFeedbackType, userFeedback;
8 9 10 11 12
import 'package:flutter/widgets.dart';

import 'colors.dart';
import 'theme.dart';
import 'typography.dart';
Adam Barth's avatar
Adam Barth committed
13
import 'constants.dart';
14

Adam Barth's avatar
Adam Barth committed
15 16 17 18 19 20 21 22 23 24 25 26
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
27 28 29
class TimeOfDay {
  const TimeOfDay({ this.hour, this.minute });

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

37 38 39 40 41
  /// The selected hour, in 24 hour time from 0..23
  final int hour;

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

Adam Barth's avatar
Adam Barth committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
  /// 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;

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

84
  int get hashCode => hashValues(hour, minute);
85

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

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) {
110
    userFeedback.performHapticFeedback(HapticFeedbackType.virtualKey);
111 112 113 114 115 116 117 118 119
    setState(() {
      _mode = mode;
    });
  }

  Widget build(BuildContext context) {
    Widget header = new _TimePickerHeader(
      selectedTime: config.selectedTime,
      mode: _mode,
Adam Barth's avatar
Adam Barth committed
120 121
      onModeChanged: _handleModeChanged,
      onChanged: config.onChanged
122
    );
123 124 125 126 127 128 129 130 131 132 133 134
    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
            )
135 136
          )
        )
137 138 139
      ],
      alignItems: FlexAlignItems.stretch
    );
140 141 142
  }
}

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

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

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

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

170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
  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;
    }
186 187
    TextStyle activeStyle = headerTheme.display3.copyWith(color: activeColor);
    TextStyle inactiveStyle = headerTheme.display3.copyWith(color: inactiveColor);
188 189 190 191

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

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

199
    return new Container(
Adam Barth's avatar
Adam Barth committed
200
      padding: kDialogHeadingPadding,
201
      decoration: new BoxDecoration(backgroundColor: theme.primaryColor),
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
      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
229
          )
230 231 232
        ],
        justifyContent: FlexJustifyContent.end
      )
233 234 235
    );
  }
}
236 237 238 239 240 241 242

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(
Adam Barth's avatar
Adam Barth committed
243
      new TextSpan(style: style, text: label)
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
    );
    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
298
    double labelThetaIncrement = -_kTwoPi / labels.length;
299 300 301 302 303 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
    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();
334 335 336 337 338 339
    _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(() { }));
340 341 342
  }

  void didUpdateConfig(_Dial oldConfig) {
Adam Barth's avatar
Adam Barth committed
343 344 345 346
    if (config.mode != oldConfig.mode && !_dragging)
      _animateTo(_getThetaForTime(config.selectedTime));
  }

347
  Tween<double> _thetaTween;
348
  Animation<double> _theta;
349
  AnimationController _thetaController;
Adam Barth's avatar
Adam Barth committed
350 351 352 353 354 355 356 357 358 359
  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);
360 361 362 363 364 365
    _thetaTween
      ..begin = beginTheta
      ..end = targetTheta;
    _thetaController
      ..value = 0.0
      ..forward();
366 367 368 369
  }

  double _getThetaForTime(TimeOfDay time) {
    double fraction = (config.mode == _TimePickerMode.hour) ?
Adam Barth's avatar
Adam Barth committed
370 371 372
        (time.hour / _kHoursPerPeriod) % _kHoursPerPeriod :
        (time.minute / _kMinutesPerHour) % _kMinutesPerHour;
    return (math.PI / 2.0 - fraction * _kTwoPi) % _kTwoPi;
373 374 375
  }

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

  void _notifyOnChangedIfNeeded() {
    if (config.onChanged == null)
      return;
Adam Barth's avatar
Adam Barth committed
392
    TimeOfDay current = _getTimeForTheta(_theta.value);
393 394 395 396 397 398 399
    if (current != config.selectedTime)
      config.onChanged(current);
  }

  void _updateThetaForPan() {
    setState(() {
      Offset offset = _position - _center;
400 401 402
      _thetaTween
        ..begin = (math.atan2(offset.dx, offset.dy) - math.PI / 2.0) % _kTwoPi
        ..end = null;
403 404 405 406 407 408 409
    });
  }

  Point _position;
  Point _center;

  void _handlePanStart(Point globalPosition) {
Adam Barth's avatar
Adam Barth committed
410 411
    assert(!_dragging);
    _dragging = true;
412 413 414 415 416 417 418 419 420 421 422 423 424 425
    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();
  }

426
  void _handlePanEnd(Velocity velocity) {
Adam Barth's avatar
Adam Barth committed
427 428
    assert(_dragging);
    _dragging = false;
429 430
    _position = null;
    _center = null;
Adam Barth's avatar
Adam Barth committed
431
    _animateTo(_getThetaForTime(config.selectedTime));
432 433
  }

Adam Barth's avatar
Adam Barth committed
434 435 436
  final List<TextPainter> _hours = _initHours();
  final List<TextPainter> _minutes = _initMinutes();

437 438 439 440 441 442 443
  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
444
          labels: config.mode == _TimePickerMode.hour ? _hours : _minutes,
445
          primaryColor: Theme.of(context).primaryColor,
Adam Barth's avatar
Adam Barth committed
446
          theta: _theta.value
447 448 449 450 451
        )
      )
    );
  }
}