date_picker.dart 12.3 KB
Newer Older
1 2 3 4 5 6
// 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';

7 8
import 'package:intl/date_symbols.dart';
import 'package:intl/intl.dart';
9
import 'package:sky/material.dart';
10
import 'package:sky/services.dart';
11 12 13 14 15 16
import 'package:sky/src/widgets/basic.dart';
import 'package:sky/src/widgets/framework.dart';
import 'package:sky/src/widgets/gesture_detector.dart';
import 'package:sky/src/widgets/ink_well.dart';
import 'package:sky/src/widgets/scrollable.dart';
import 'package:sky/src/widgets/theme.dart';
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

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

  DateTime selectedDate;
  DatePickerValueChanged onChanged;
  DateTime firstDate;
  DateTime lastDate;

  void syncConstructorArguments(DatePicker source) {
    selectedDate = source.selectedDate;
    onChanged = source.onChanged;
    firstDate = source.firstDate;
    lastDate = source.lastDate;
  }

  DatePickerMode _mode = DatePickerMode.day;

  void _handleModeChanged(DatePickerMode mode) {
51
    userFeedback.performHapticFeedback(HapticFeedbackType_VIRTUAL_KEY);
52 53 54 55 56 57
    setState(() {
      _mode = mode;
    });
  }

  void _handleYearChanged(DateTime dateTime) {
58
    userFeedback.performHapticFeedback(HapticFeedbackType_VIRTUAL_KEY);
59 60 61 62 63 64 65
    setState(() {
      _mode = DatePickerMode.day;
    });
    if (onChanged != null)
      onChanged(dateTime);
  }

66 67 68 69 70 71
  void _handleDayChanged(DateTime dateTime) {
    userFeedback.performHapticFeedback(HapticFeedbackType_VIRTUAL_KEY);
    if (onChanged != null)
      onChanged(dateTime);
  }

72 73 74 75 76 77 78 79 80 81 82 83 84
  static const double _calendarHeight = 210.0;

  Widget build() {
    Widget header = new DatePickerHeader(
      selectedDate: selectedDate,
      mode: _mode,
      onModeChanged: _handleModeChanged
    );
    Widget picker;
    switch (_mode) {
      case DatePickerMode.day:
        picker = new MonthPicker(
          selectedDate: selectedDate,
85
          onChanged: _handleDayChanged,
86 87 88 89 90 91 92 93 94 95 96 97 98 99
          firstDate: firstDate,
          lastDate: lastDate,
          itemExtent: _calendarHeight
        );
        break;
      case DatePickerMode.year:
        picker = new YearPicker(
          selectedDate: selectedDate,
          onChanged: _handleYearChanged,
          firstDate: firstDate,
          lastDate: lastDate
        );
        break;
    }
100 101 102 103 104 105 106
    return new Column([
      header,
      new Container(
        height: _calendarHeight,
        child: picker
      )
    ], alignItems: FlexAlignItems.stretch);
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
  }

}

// Shows the selected date in large font and toggles between year and day mode
class DatePickerHeader extends Component {
  DatePickerHeader({ this.selectedDate, this.mode, this.onModeChanged }) {
    assert(selectedDate != null);
    assert(mode != null);
  }

  DateTime selectedDate;
  DatePickerMode mode;
  DatePickerModeChanged onModeChanged;

  EventDisposition _handleChangeMode(DatePickerMode value) {
    if (value == mode)
      return EventDisposition.ignored;
    onModeChanged(value);
    return EventDisposition.processed;
  }

  Widget build() {
    ThemeData theme = Theme.of(this);
131
    TextTheme headerTheme;
132 133 134 135
    Color dayColor;
    Color yearColor;
    switch(theme.primaryColorBrightness) {
      case ThemeBrightness.light:
136 137 138
        headerTheme = Typography.black;
        dayColor = mode == DatePickerMode.day ? Colors.black87 : Colors.black54;
        yearColor = mode == DatePickerMode.year ? Colors.black87 : Colors.black54;
139 140
        break;
      case ThemeBrightness.dark:
141 142 143
        headerTheme = Typography.white;
        dayColor = mode == DatePickerMode.day ? Colors.white87 : Colors.white54;
        yearColor = mode == DatePickerMode.year ? Colors.white87 : Colors.white54;
144 145 146 147 148 149 150
        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(
151 152 153 154 155 156
      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)
157
        ),
158 159 160
        new GestureDetector(
          onTap: () => _handleChangeMode(DatePickerMode.day),
          child: new Text(new DateFormat("d").format(selectedDate), style: dayStyle)
161
        ),
162 163 164
        new GestureDetector(
          onTap: () => _handleChangeMode(DatePickerMode.year),
          child: new Text(new DateFormat("yyyy").format(selectedDate), style: yearStyle)
165
        )
166
      ])
167 168 169 170 171 172 173 174 175 176 177 178 179 180
    );
  }
}

// Fixed height component shows a single month and allows choosing a day
class DayPicker extends Component {
  DayPicker({
    this.selectedDate,
    this.currentDate,
    this.onChanged,
    this.displayedMonth
  }) {
    assert(selectedDate != null);
    assert(currentDate != null);
181
    assert(onChanged != null);
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 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 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
    assert(displayedMonth != null);
  }

  final DateTime selectedDate;
  final DateTime currentDate;
  final DatePickerValueChanged onChanged;
  final DateTime displayedMonth;

  Widget build() {
    ThemeData theme = Theme.of(this);
    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);

251 252
        item = new GestureDetector(
          onTap: () {
253
            DateTime result = new DateTime(year, month, day);
254
            onChanged(result);
255 256 257 258 259 260 261 262 263 264 265 266 267 268
          },
          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;
269 270
      rows.add(new Row(
        labels.sublist(startIndex, startIndex + days.length)
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
      ));
    }

    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);
288
    assert(onChanged != null);
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    assert(lastDate.isAfter(firstDate));
  }

  DateTime selectedDate;
  DatePickerValueChanged onChanged;
  DateTime firstDate;
  DateTime lastDate;

  void syncConstructorArguments(MonthPicker source) {
    selectedDate = source.selectedDate;
    onChanged = source.onChanged;
    firstDate = source.firstDate;
    lastDate = source.lastDate;
    super.syncConstructorArguments(source);
  }

  void initState() {
    _updateCurrentDate();
    super.initState();
  }

  DateTime _currentDate;
311 312
  Timer _timer;

313 314 315 316 317
  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
318 319 320
    if (_timer != null)
      _timer.cancel();
    _timer = new Timer(timeUntilTomorrow, () {
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
      setState(() {
        _updateCurrentDate();
      });
    });
  }

  int get itemCount => (lastDate.year - firstDate.year) * 12 + lastDate.month - firstDate.month + 1;

  List<Widget> buildItems(int start, int count) {
    List<Widget> result = new List<Widget>();
    DateTime startDate = new DateTime(firstDate.year + start ~/ 12, 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,
        key: new ObjectKey(displayedMonth),
        child: new DayPicker(
          selectedDate: selectedDate,
          currentDate: _currentDate,
          onChanged: onChanged,
          displayedMonth: displayedMonth
        )
      );
      result.add(item);
    }
    return result;
  }
348 349 350 351 352 353 354

  void didUnmount() {
    super.didUnmount();
    if (_timer != null) {
      _timer.cancel();
    }
  }
355 356 357 358 359 360 361 362 363 364 365
}

// 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);
366
    assert(onChanged != null);
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
    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);
  }

  int get itemCount => lastDate.year - firstDate.year + 1;

  List<Widget> buildItems(int start, int count) {
385
    TextStyle style = Theme.of(this).text.body1.copyWith(color: Colors.black54);
386 387 388 389
    List<Widget> items = new List<Widget>();
    for(int i = start; i < start + count; i++) {
      int year = firstDate.year + i;
      String label = year.toString();
390
      Widget item = new GestureDetector(
391
        key: new Key(label),
392
        onTap: () {
393
          DateTime result = new DateTime(year, selectedDate.month, selectedDate.day);
394
          onChanged(result);
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
        },
        child: new InkWell(
          child: new Container(
            height: itemExtent,
            decoration: year == selectedDate.year ? new BoxDecoration(
              backgroundColor: Theme.of(this).primarySwatch[100],
              shape: Shape.circle
            ) : null,
            child: new Center(
              child: new Text(label, style: style)
            )
          )
        )
      );
      items.add(item);
    }
    return items;
  }
}