Debian Codegraph @

src/qml/CustomPickers/1.0/DatePicker.qml

raw
1 /*
2 * Copyright 2015 Canonical Ltd.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU Lesser General Public License as published by
6 * the Free Software Foundation; version 3.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16
17 import QtQuick 2.4
18 import Lomiri.Components 1.3
19
20 /*!
21 \qmltype DatePicker
22 \inqmlmodule Lomiri.Components.Pickers 1.0
23 \ingroup ubuntu-pickers
24 \brief DatePicker component provides date and time value picking functionality.
25
26 DatePicker combines up to three Picker elements providing different date or time
27 value selection possibilities. It can be used to select full date (year, month,
28 day), full time (hours, minutes, seconds) as well as to select a combination of
29 year and month, month and day, hours and minutes, minutes and seconds or individual
30 time units (i.e. year, month or day as well as hours, minutes or seconds). The
31 selected date as well as the initial one is provided by the \l date property.
32 For convenience the component provides also the \a year, \a month, \a day,
33 \a week, \a hours, \a minutes and \a seconds values as separate properties,
34 however these properties are not writable, and their initialization can happen
35 only through the \l date property.
36
37 \qml
38 import QtQuick 2.4
39 import Lomiri.Components 1.3
40 import Lomiri.Components.Pickers 1.0
41
42 Column {
43 Label {
44 text: "Selected date: W" + datePicker.week + " - " +
45 Qt.formatDate(datePicker.date, "dddd, dd-MMMM-yyyy")
46 }
47 DatePicker {
48 id: datePicker
49 }
50 }
51 \endqml
52
53 The \l mode property specifies what time units should be shown by the picker.
54 The property holds a string, combining \b Years, \b Months, \b Days, \b Hours,
55 \b Minutes and \b Seconds strings sepatared with '|' character. A DatePicker
56 which shows only year and month date units would look as follows:
57 \qml
58 import QtQuick 2.4
59 import Lomiri.Components 1.3
60 import Lomiri.Components.Pickers 1.0
61
62 Column {
63 Label {
64 text: "Selected month: " + Qt.formatDate(datePicker.date, "MMMM-yyyy")
65 }
66 DatePicker {
67 id: datePicker
68 mode: "Years|Months"
69 }
70 }
71 \endqml
72
73 The \b mode of the DatePicker is set to date picking. In case time picking
74 is needed, the model should be set to contain the time specific mode flags.
75 The following example demonstrates how to use DatePicker for time picking.
76 \qml
77 import QtQuick 2.4
78 import Lomiri.Components 1.3
79 import Lomiri.Components.Pickers 1.0
80
81 Column {
82 Label {
83 text: "Selected time: " + Qt.formatTime(datePicker.date, "hh:mm:ss")
84 }
85 DatePicker {
86 id: datePicker
87 mode: "Hours|Minutes|Seconds"
88 }
89 }
90 \endqml
91 Note that the order in which the mode flags are specified does not influence
92 the order the pickers are arranged. That is driven by the date format of the
93 \l locale used in the picker. Also not all combinations of mode flags are
94 supported. See \l mode for the supported combinations.
95
96 The default interval the date values are chosen is a window starting at
97 the current date ending 50 years later. This window is defined by the
98 \a minimum and \a maximum properties. The interval can be altered considering
99 the following rules:
100 \list
101 \li \a minimum must be less or equal than the \l date; if the \a date
102 value is less than the given \a minimum, the date will be set to
103 the minimum's value
104 \li \a maximum value must be greater than the \a minimum, or invalid.
105 When the maximum is smaller than the \l date, the \l date property
106 will be updated to get the maximum value.
107 When set to invalid date (see Date.getInvalidDate()), the upper
108 limit of the date interval becomes infinite, meaning the year
109 picker will extend infinitely. This leads to increased memory
110 use and should be avoided if possible. Invalid date will make
111 hours picker presenting 24 hours.
112 \endlist
113 \qml
114 import QtQuick 2.4
115 import Lomiri.Components 1.3
116 import Lomiri.Components.Pickers 1.0
117
118 Column {
119 Label {
120 text: "Selected date: " + Qt.formatDate(datePicker.date, "dddd, dd-MMMM-yyyy")
121 }
122 DatePicker {
123 id: datePicker
124 minimum: {
125 var d = new Date();
126 d.setFullYear(d.getFullYear() - 1);
127 return d;
128 }
129 maximum: Date.prototype.getInvalidDate.call()
130 }
131 }
132 \endqml
133 \b Note: do not use the \l date property when initializing minimum and maximum
134 as it will cause binding loops.
135
136 \section2 Layout
137 As mentioned earlier, DatePicker combines up to three Picker tumblers depending
138 on the mode requested. These tumblers are laid out in a row in the order the
139 default date format of the \l locale is.
140
141 \section3 Date picker layout rules
142 The date picker consist of three pickers: year, month, and date. The exact
143 contents of the month and date pickers depends on the available width:
144 \list
145 \li full name for month, number and full day for date (“August” “28 Wednesday”)
146 \li otherwise full name for month, number and abbreviated day
147 for date (“August” “28 Wed”);
148 \li otherwise full name for month, number for date (“August” “28”);
149 \li otherwise abbreviated name for month, number for date (“Aug” “28”).
150 \li otherwise number for month, number for date (“08” “28”).
151 \endlist
152
153 \a{If the currently selected date becomes impossible due to year change (from a
154 leap to a non-leap year when the date is set to February 29) or month change
155 (e.g. from a month that has 31 days to one that has fewer when the date is
156 set to 31), the date reduces automatically to the last day of the month (i.e
157 February 28 or 30th day of the month).}
158
159 \section3 Time picker layout rules
160 Time units are shown in fixed width picker tumblers, numbers padded with
161 leading zeroes. There is no other special rule on the formatting of the time
162 unit numbers.
163
164 \section3 How minimum/maximum affects the tumblers
165
166 If minimum and maximum are within the same year, the year picker will be
167 insensitive. If minimum and maximum are within the same month, the month picker
168 will also be insensitive.
169 */
170 StyledItem {
171 id: datePicker
172
173 /*!
174 Specifies what kind of date value selectors should be shown by the picker.
175 This is a string of 'flags' separated by '|' separator, where flags are:
176 \table
177 \header
178 \li {2, 1} Date picker modes
179 \header
180 \li Value
181 \li Description
182 \row
183 \li Years
184 \li Specifies to show the year picker
185 \row
186 \li Months
187 \li Specifies to show the month picker
188 \row
189 \li Days
190 \li Specifies to show the day picker
191 \header
192 \li {2, 1} Time picker modes
193 \header
194 \li Value
195 \li Description
196 \row
197 \li Hours
198 \li Specifies to show the hours picker
199 \row
200 \li FiveMinutes
201 \li Specifies to show a minute picker in five minute intervals
202 \row
203 \li Minutes
204 \li Specifies to show the minutes picker
205 \row
206 \li Seconds
207 \li Specifies to show the seconds picker
208 \endtable
209 With some exceptions, any combination of these flags is allowed within the
210 same group. Date and time picker modes cannot be combined.
211
212 The supported combinations are: \a{Years|Months|Days}, \a{Years|Months},
213 \a{Months|Days}, \a{Hours|FiveMinutes|Seconds}, \a{Hours|Minutes|Seconds}, \a{Hours|FiveMinutes}, \a{Hours|Minutes}, \a{FiveMinutes|Seconds}, and \a{Minutes|Seconds},
214 as well as each mode flag individually.
215
216 The default value is "\a{Years|Months|Days}".
217 */
218 property string mode: "Years|Months|Days"
219
220 /*!
221 The date chosen by the DatePicker. The default value is the date at the
222 component creation time. The property automatically updates year, month
223 and day properties.
224 */
225 property date date: Date.prototype.midnight.call(new Date())
226
227 /*!
228 \qmlproperty int minimum
229 The minimum date (inclusive) to be shown in the picker.
230 Both year and month values will be considered from the properties.
231
232 The year and month picker values are filled based on these values. The
233 year picker will be infinite (extending infinitely) if the maximum is
234 an invalid date. If the distance between maximum and minimum is less than
235 a year, the year picker will be shown disabled.
236
237 The month picker will be circular if the distance between maximum and minimum
238 is at least one year, or if the maximum date is invalid.
239
240 The default values are the current date for the minimum, and 50 year distance
241 value for maximum.
242 */
243 property date minimum: Date.prototype.midnight.call(new Date())
244 /*!
245 \qmlproperty int maximum
246
247 The maximum date (inclusive) to be shown in the picker.
248 Both year and month values will be considered from the properties.
249
250 See \l minimum for more details.
251 */
252 property date maximum: {
253 var d = Date.prototype.midnight.call(new Date());
254 d.setFullYear(d.getFullYear() + 50);
255 return d;
256 }
257
258 /*!
259 For convenience, the \b year value of the \l date property.
260 */
261 readonly property int year: datePicker.date.getFullYear()
262 /*!
263 For convenience, the \b month value of the \l date property.
264 */
265 readonly property int month: datePicker.date.getMonth()
266 /*!
267 For convenience, the \b day value of the \l date property.
268 */
269 readonly property int day: datePicker.date.getDate()
270 /*!
271 For convenience, the \b week value of the \l date property.
272 */
273 readonly property int week: datePicker.date.getWeek()
274 /*!
275 For convenience, the \b hours value of the \l date property.
276 */
277 readonly property int hours: datePicker.date.getHours()
278 /*!
279 For convenience, the \b minutes value of the \l date property.
280 */
281 readonly property int minutes: datePicker.date.getMinutes()
282 /*!
283 For convenience, the \b seconds value of the \l date property.
284 */
285 readonly property int seconds: datePicker.date.getSeconds()
286
287 /*!
288 The property defines the locale used in the picker. The default value is
289 the system locale.
290 \qml
291 DatePicker {
292 locale: Qt.locale("hu_HU")
293 }
294 \endqml
295 */
296 property var locale: Qt.locale()
297
298 /*!
299 \qmlproperty bool moving
300 \readonly
301 The property holds whether the component's pickers are moving.
302 \sa Picker::moving
303 */
304 readonly property alias moving: positioner.moving
305
306 implicitWidth: units.gu(36)
307 implicitHeight: units.gu(20)
308 activeFocusOnPress: true
309
310 /*! \internal */
311 onMinimumChanged: {
312 if (internals.completed && !minimum.isValid()) {
313 // set the minimum to the date
314 minimum = date;
315 }
316
317 // adjust date
318 if (date !== undefined && Date.prototype.isValid.call(minimum) && date < minimum && internals.completed) {
319 date = minimum;
320 }
321 }
322 /*! \internal */
323 onMaximumChanged: {
324 // adjust date
325 if (date !== undefined && Date.prototype.isValid.call(maximum) && date > maximum && maximum > minimum && internals.completed) {
326 date = maximum;
327 }
328 }
329 /*! \internal */
330 onWidthChanged: {
331 // use dayPicker narrowFormatLimit even if the dayPicker is hidden
332 // and clamp the width so it cannot have less width that the sum of
333 // the three tumblers' narrowFormatLimit
334 var minWidth = 0.0;
335 for (var i = 0; i < tumblerModel.count; i++) {
336 minWidth += tumblerModel.get(i).pickerModel.narrowFormatLimit;
337 }
338 width = Math.max(width, minWidth);
339 }
340 /*! \internal */
341 onModeChanged: internals.updatePickers()
342 /*! \internal */
343 onLocaleChanged: internals.updatePickers()
344
345 Component.onCompleted: {
346 if (minimum === undefined) {
347 minimum = date;
348 }
349 internals.completed = true;
350 internals.updatePickers();
351 }
352
353 // models
354 YearModel {
355 id: yearModel
356 mainComponent: datePicker
357 pickerCompleted: internals.completed && internals.showYearPicker
358 pickerWidth: (!pickerItem) ? 0 : narrowFormatLimit
359 function syncModels() {
360 dayModel.syncModels();
361 }
362 }
363 MonthModel {
364 id: monthModel
365 mainComponent: datePicker
366 pickerCompleted: internals.completed && internals.showMonthPicker
367 pickerWidth: {
368 if (!pickerItem) {
369 return 0;
370 }
371 return MathUtils.clamp(datePicker.width - yearModel.pickerWidth - dayModel.pickerWidth, narrowFormatLimit, longFormatLimit);
372 }
373 function syncModels() {
374 dayModel.syncModels();
375 }
376 }
377 DayModel {
378 id: dayModel
379 mainComponent: datePicker
380 pickerCompleted: internals.completed && internals.showDayPicker
381 pickerWidth: {
382 if (!pickerItem) {
383 return 0;
384 }
385 var w = Math.max(datePicker.width * internals.dayPickerRatio, narrowFormatLimit);
386 if (w < longFormatLimit && w >= shortFormatLimit) {
387 return shortFormatLimit;
388 }
389 return w;
390 }
391 }
392 HoursModel {
393 id: hoursModel
394 mainComponent: datePicker
395 pickerCompleted: internals.completed && internals.showHoursPicker
396 pickerWidth: {
397 if (!pickerItem) {
398 return 0;
399 }
400 return narrowFormatLimit;
401 }
402 }
403 FiveMinutesModel {
404 id: fiveMinutesModel
405 mainComponent: datePicker
406 pickerCompleted: internals.completed && internals.showFiveMinutesPicker
407 pickerWidth: {
408 if (!pickerItem) {
409 return 0;
410 }
411 return narrowFormatLimit;
412 }
413 }
414 FifteenMinutesModel {
415 id: fifteenMinutesModel
416 mainComponent: datePicker
417 pickerCompleted: internals.completed && internals.showFifteenMinutesPicker
418 pickerWidth: {
419 if (!pickerItem) {
420 return 0;
421 }
422 return narrowFormatLimit;
423 }
424 }
425 MinutesModel {
426 id: minutesModel
427 mainComponent: datePicker
428 pickerCompleted: internals.completed && internals.showMinutesPicker
429 pickerWidth: {
430 if (!pickerItem) {
431 return 0;
432 }
433 return narrowFormatLimit;
434 }
435 }
436 SecondsModel {
437 id: secondsModel
438 mainComponent: datePicker
439 pickerCompleted: internals.completed && internals.showSecondsPicker
440 pickerWidth: {
441 if (!pickerItem) {
442 return 0;
443 }
444 return narrowFormatLimit;
445 }
446 }
447
448 styleName: "DatePickerStyle"
449 Binding {
450 target: __styleInstance
451 property: "view"
452 value: positioner
453 }
454 Binding {
455 target: __styleInstance
456 property: "pickerModels"
457 value: tumblerModel
458 }
459 Binding {
460 target: __styleInstance
461 property: "unitSeparator"
462 value: (internals.showHoursPicker || internals.showFiveMinutesPicker || internals.showMinutesPicker || internals.showSecondsPicker) ?
463 ":" : ""
464 }
465
466 // tumbler positioner
467 PickerRow {
468 id: positioner
469 parent: (datePicker.__styleInstance && datePicker.__styleInstance.hasOwnProperty("tumblerHolder")) ?
470 datePicker.__styleInstance.tumblerHolder : datePicker
471 mainComponent: datePicker
472 model: tumblerModel
473 margins: internals.margin
474 anchors {
475 top: parent.top
476 bottom: parent.bottom
477 horizontalCenter: parent.horizontalCenter
478 }
479 }
480 // tumbler model
481 ListModel {
482 /*
483 Model to hold tumbler order for repeaters.
484 Roles:
485 - pickerModel
486 - pickerName
487 */
488 id: tumblerModel
489
490 /*
491 Signal triggered when the model is about to remove a picker. We cannot rely on
492 rowAboutToBeRemoved, as by the time the signal is called the list element is
493 already removed from the model.
494 */
495 signal pickerRemoved(int index)
496
497 // the function checks whether a pickerModel was added or not
498 // returns the index of the model object the pickerModel was found
499 // or -1 on error.
500 function pickerModelIndex(name) {
501 for (var i = 0; i < count; i++) {
502 if (get(i).pickerName === name) {
503 return i;
504 }
505 }
506 return -1;
507 }
508
509 // the function checks whether a pickerModel is present in the list;
510 // moves the existing one to the given index or inserts it if not present
511 function setPickerModel(model, name, index) {
512 var idx = pickerModelIndex(name);
513 if (idx >= 0) {
514 move(idx, index, 1);
515 } else {
516 append({"pickerModel": model, "pickerName": name});
517 }
518 }
519
520 // removes the given picker
521 function removePicker(name) {
522 var idx = pickerModelIndex(name);
523 if (idx >= 0) {
524 pickerRemoved(idx);
525 remove(idx);
526 }
527 }
528 }
529
530 // component to calculate text fitting
531 Label { id: textSizer; visible: false }
532 QtObject {
533 id: internals
534 property bool completed: false
535 property real margin: units.gu(1.5)
536 property real dayPickerRatio: 0.1
537
538 property bool showYearPicker: true
539 property bool showMonthPicker: true
540 property bool showDayPicker: true
541
542 property bool showHoursPicker: false
543 property bool showFiveMinutesPicker: false
544 property bool showFifteenMinutesPicker: false
545 property bool showMinutesPicker: false
546 property bool showSecondsPicker: false
547
548 /*
549 Update pickers.
550 */
551 function updatePickers() {
552 if (completed) {
553 // check mode flags first
554 // FIXME: The js split(/\W/g) terminates the process on armhf with Qt 5.3 (v4 js) (https://bugreports.qt-project.org/browse/QTBUG-39255)
555 var modes = datePicker.mode.match(/\w+/g);
556
557 showYearPicker = showMonthPicker = showDayPicker =
558 showHoursPicker = showFiveMinutesPicker = showFiveMinutesPicker = showMinutesPicker = showSecondsPicker = false;
559 while (modes.length > 0) {
560 var modeFlag = modes.pop();
561 switch (modeFlag) {
562 case "Years":
563 showYearPicker = true;
564 break;
565 case "Months":
566 showMonthPicker = true;
567 break;
568 case "Days":
569 showDayPicker = true;
570 break;
571 case "Hours":
572 showHoursPicker = true;
573 break;
574 case "FiveMinutes":
575 showFiveMinutesPicker = true;
576 break;
577 case "FifteenMinutes":
578 showFifteenMinutesPicker = true;
579 break;
580 case "Minutes":
581 showMinutesPicker = true;
582 break;
583 case "Seconds":
584 showSecondsPicker = true;
585 break;
586 default:
587 console.warn("Unhandled mode flag: " + modeFlag + ". Mode will not be set!");
588 return;
589 }
590 }
591
592 if(showFiveMinutesPicker && showMinutesPicker || showFifteenMinutesPicker && showMinutesPicker) {
593 console.warn("Invalid DatePicker mode: " + datePicker.mode);
594 return;
595 }
596
597 // filter unaccepted date picking mode
598 if (!showMonthPicker && showYearPicker && showDayPicker) {
599 console.warn("Invalid DatePicker mode: " + datePicker.mode);
600 return;
601 }
602
603 // filter unaccepted time picking mode
604 if (showHoursPicker && showSecondsPicker && !(showMinutesPicker || showFiveMinutesPicker) && !(showFifteenMinutesPicker || showFiveMinutesPicker)) {
605 console.warn("Invalid DatePicker mode: " + datePicker.mode);
606 return;
607 }
608
609 // date and time picking not allowed at the same time
610 if ((showYearPicker || showMonthPicker || showDayPicker) &&
611 (showHoursPicker || showFiveMinutesPicker || showFifteenMinutesPicker || showMinutesPicker || showSecondsPicker)) {
612 console.warn("Date and Time picking not allowed at the same time.");
613 return;
614 }
615
616 arrangeTumblers();
617 resetPickers();
618 }
619 }
620
621 /*
622 Resets the pickers. Pickers will update their models with the given date,
623 minimum and maximum values.
624 */
625 function resetPickers() {
626 if (!completed) return;
627 for (var i = 0; i < tumblerModel.count; i++) {
628 var pickerItem = tumblerModel.get(i).pickerModel.pickerItem;
629 pickerItem.resetPicker();
630 }
631
632 // calculate the ratio for the dayPicker
633 var maxWidth = 0.0;
634 maxWidth += showYearPicker ? yearModel.longFormatLimit : 0.0;
635 maxWidth += showMonthPicker ? monthModel.longFormatLimit : 0.0;
636 maxWidth += showDayPicker ? dayModel.longFormatLimit : 0.0;
637 if (showDayPicker && maxWidth > 0.0) {
638 dayPickerRatio = (dayModel.longFormatLimit / maxWidth).toPrecision(3);
639 }
640 }
641
642 /*
643 Detects the tumbler order from the date format of the locale
644 */
645 function arrangeTumblers() {
646 // disable completion so avoid accidental date changes
647 completed = false;
648
649 // use short format to exclude any extra characters
650 // FIXME: The js split(/\W/g) terminates the process on armhf with Qt 5.3 (v4 js) (https://bugreports.qt-project.org/browse/QTBUG-39255)
651 var format = datePicker.locale.dateFormat(Locale.ShortFormat).match(/\w+/g);
652 // loop through the format to decide the position of the tumbler
653 var formatIndex = 0;
654 for (var i in format) {
655 if (!format[i].length) continue;
656 // check the first two characters
657 switch (format[i].substr(0, 1).toLowerCase()) {
658 case 'y':
659 if (showYearPicker) {
660 tumblerModel.setPickerModel(yearModel, "YearPicker", formatIndex);
661 formatIndex++;
662 } else {
663 tumblerModel.removePicker("YearPicker");
664 }
665
666 break;
667 case 'm':
668 if (showMonthPicker) {
669 tumblerModel.setPickerModel(monthModel, "MonthPicker", formatIndex);
670 formatIndex++;
671 } else {
672 tumblerModel.removePicker("MonthPicker");
673 }
674
675 break;
676 case 'd':
677 if (showDayPicker) {
678 tumblerModel.setPickerModel(dayModel, "DayPicker", formatIndex);
679 formatIndex++;
680 } else {
681 tumblerModel.removePicker("DayPicker");
682 }
683 break;
684 }
685 }
686 // check hms
687 if (showHoursPicker) {
688 tumblerModel.setPickerModel(hoursModel, "HoursPicker", formatIndex);
689 formatIndex++;
690 } else {
691 tumblerModel.removePicker("HoursPicker");
692 }
693 if (showFiveMinutesPicker) {
694 tumblerModel.setPickerModel(fiveMinutesModel, "FiveMinutesPicker", formatIndex);
695 formatIndex++;
696 } else {
697 tumblerModel.removePicker("FiveMinutesPicker");
698 }
699 if (showFifteenMinutesPicker) {
700 tumblerModel.setPickerModel(fifteenMinutesModel, "FifteenMinutesPicker", formatIndex);
701 formatIndex++;
702 } else {
703 tumblerModel.removePicker("FifteenMinutesPicker");
704 }
705 if (showMinutesPicker) {
706 tumblerModel.setPickerModel(minutesModel, "MinutesPicker", formatIndex);
707 formatIndex++;
708 } else {
709 tumblerModel.removePicker("MinutesPicker");
710 }
711 if (showSecondsPicker) {
712 tumblerModel.setPickerModel(secondsModel, "SecondsPicker", formatIndex);
713 formatIndex++;
714 } else {
715 tumblerModel.removePicker("SecondsPicker");
716 }
717
718 // re-enable completion
719 completed = true;
720 }
721 }
722 }