Debian Codegraph @

src/imports/Components/Pickers/2.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
19
20 /*!
21 \qmltype DatePicker
22 \inqmlmodule Lomiri.Components.Pickers 1.0
23 \ingroup lomiri-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
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
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
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
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 Minutes
201 \li Specifies to show the minutes picker
202 \row
203 \li Seconds
204 \li Specifies to show the seconds picker
205 \endtable
206 With some exceptions, any combination of these flags is allowed within the
207 same group. Date and time picker modes cannot be combined.
208
209 The supported combinations are: \a{Years|Months|Days}, \a{Years|Months},
210 \a{Months|Days}, \a{Hours|Minutes|Seconds}, \a{Hours|Minutes} and \a{Minutes|Seconds},
211 as well as each mode flag individually.
212
213 The default value is "\a{Years|Months|Days}".
214 */
215 property string mode: "Years|Months|Days"
216
217 /*!
218 The date chosen by the DatePicker. The default value is the date at the
219 component creation time. The property automatically updates year, month
220 and day properties.
221 */
222 property date date: Date.prototype.midnight.call(new Date())
223
224 /*!
225 \qmlproperty int minimum
226 The minimum date (inclusive) to be shown in the picker.
227 Both year and month values will be considered from the properties.
228
229 The year and month picker values are filled based on these values. The
230 year picker will be infinite (extending infinitely) if the maximum is
231 an invalid date. If the distance between maximum and minimum is less than
232 a year, the year picker will be shown disabled.
233
234 The month picker will be circular if the distance between maximum and minimum
235 is at least one year, or if the maximum date is invalid.
236
237 The default values are the current date for the minimum, and 50 year distance
238 value for maximum.
239 */
240 property date minimum: Date.prototype.midnight.call(new Date())
241 /*!
242 \qmlproperty int maximum
243
244 The maximum date (inclusive) to be shown in the picker.
245 Both year and month values will be considered from the properties.
246
247 See \l minimum for more details.
248 */
249 property date maximum: {
250 var d = Date.prototype.midnight.call(new Date());
251 d.setFullYear(d.getFullYear() + 50);
252 return d;
253 }
254
255 /*!
256 For convenience, the \b year value of the \l date property.
257 */
258 readonly property int year: datePicker.date.getFullYear()
259 /*!
260 For convenience, the \b month value of the \l date property.
261 */
262 readonly property int month: datePicker.date.getMonth()
263 /*!
264 For convenience, the \b day value of the \l date property.
265 */
266 readonly property int day: datePicker.date.getDate()
267 /*!
268 For convenience, the \b week value of the \l date property.
269 */
270 readonly property int week: datePicker.date.getWeek()
271 /*!
272 For convenience, the \b hours value of the \l date property.
273 */
274 readonly property int hours: datePicker.date.getHours()
275 /*!
276 For convenience, the \b minutes value of the \l date property.
277 */
278 readonly property int minutes: datePicker.date.getMinutes()
279 /*!
280 For convenience, the \b seconds value of the \l date property.
281 */
282 readonly property int seconds: datePicker.date.getSeconds()
283
284 /*!
285 The property defines the locale used in the picker. The default value is
286 the system locale.
287 \qml
288 DatePicker {
289 locale: Qt.locale("hu_HU")
290 }
291 \endqml
292 */
293 property var locale: Qt.locale()
294
295 /*!
296 \qmlproperty bool moving
297 \readonly
298 The property holds whether the component's pickers are moving.
299 \sa Picker::moving
300 */
301 readonly property alias moving: positioner.moving
302
303 implicitWidth: units.gu(36)
304 implicitHeight: units.gu(20)
305 activeFocusOnPress: true
306
307 /*! \internal */
308 onMinimumChanged: {
309 if (internals.completed && !minimum.isValid()) {
310 // set the minimum to the date
311 minimum = date;
312 }
313
314 // adjust date
315 if (date !== undefined && Date.prototype.isValid.call(minimum) && date < minimum && internals.completed) {
316 date = minimum;
317 }
318 }
319 /*! \internal */
320 onMaximumChanged: {
321 // adjust date
322 if (date !== undefined && Date.prototype.isValid.call(maximum) && date > maximum && maximum > minimum && internals.completed) {
323 date = maximum;
324 }
325 }
326 /*! \internal */
327 onWidthChanged: {
328 // use dayPicker narrowFormatLimit even if the dayPicker is hidden
329 // and clamp the width so it cannot have less width that the sum of
330 // the three tumblers' narrowFormatLimit
331 var minWidth = 0.0;
332 for (var i = 0; i < tumblerModel.count; i++) {
333 minWidth += tumblerModel.get(i).pickerModel.narrowFormatLimit;
334 }
335 width = Math.max(width, minWidth);
336 }
337 /*! \internal */
338 onModeChanged: internals.updatePickers()
339 /*! \internal */
340 onLocaleChanged: internals.updatePickers()
341
342 Component.onCompleted: {
343 if (minimum === undefined) {
344 minimum = date;
345 }
346 internals.completed = true;
347 internals.updatePickers();
348 }
349
350 // models
351 YearModel {
352 id: yearModel
353 mainComponent: datePicker
354 pickerCompleted: internals.completed && internals.showYearPicker
355 pickerWidth: (!pickerItem) ? 0 : narrowFormatLimit
356 function syncModels() {
357 dayModel.syncModels();
358 }
359 }
360 MonthModel {
361 id: monthModel
362 mainComponent: datePicker
363 pickerCompleted: internals.completed && internals.showMonthPicker
364 pickerWidth: {
365 if (!pickerItem) {
366 return 0;
367 }
368 return MathUtils.clamp(datePicker.width - yearModel.pickerWidth - dayModel.pickerWidth, narrowFormatLimit, longFormatLimit);
369 }
370 function syncModels() {
371 dayModel.syncModels();
372 }
373 }
374 DayModel {
375 id: dayModel
376 mainComponent: datePicker
377 pickerCompleted: internals.completed && internals.showDayPicker
378 pickerWidth: {
379 if (!pickerItem) {
380 return 0;
381 }
382 var w = Math.max(datePicker.width * internals.dayPickerRatio, narrowFormatLimit);
383 if (w < longFormatLimit && w >= shortFormatLimit) {
384 return shortFormatLimit;
385 }
386 return w;
387 }
388 }
389 HoursModel {
390 id: hoursModel
391 mainComponent: datePicker
392 pickerCompleted: internals.completed && internals.showHoursPicker
393 pickerWidth: {
394 if (!pickerItem) {
395 return 0;
396 }
397 return narrowFormatLimit;
398 }
399 }
400 MinutesModel {
401 id: minutesModel
402 mainComponent: datePicker
403 pickerCompleted: internals.completed && internals.showMinutesPicker
404 pickerWidth: {
405 if (!pickerItem) {
406 return 0;
407 }
408 return narrowFormatLimit;
409 }
410 }
411 SecondsModel {
412 id: secondsModel
413 mainComponent: datePicker
414 pickerCompleted: internals.completed && internals.showSecondsPicker
415 pickerWidth: {
416 if (!pickerItem) {
417 return 0;
418 }
419 return narrowFormatLimit;
420 }
421 }
422
423 styleName: "DatePickerStyle"
424 Binding {
425 target: __styleInstance
426 property: "view"
427 value: positioner
428 }
429 Binding {
430 target: __styleInstance
431 property: "pickerModels"
432 value: tumblerModel
433 }
434 Binding {
435 target: __styleInstance
436 property: "unitSeparator"
437 value: (internals.showHoursPicker || internals.showMinutesPicker || internals.showSecondsPicker) ?
438 ":" : ""
439 }
440
441 // tumbler positioner
442 PickerRow {
443 id: positioner
444 parent: (datePicker.__styleInstance && datePicker.__styleInstance.hasOwnProperty("tumblerHolder")) ?
445 datePicker.__styleInstance.tumblerHolder : datePicker
446 mainComponent: datePicker
447 model: internals.completed ? tumblerModel : null
448 margins: internals.margin
449 anchors {
450 top: parent.top
451 bottom: parent.bottom
452 horizontalCenter: parent.horizontalCenter
453 }
454 }
455 // tumbler model
456 ListModel {
457 /*
458 Model to hold tumbler order for repeaters.
459 Roles:
460 - pickerModel
461 - pickerName
462 */
463 id: tumblerModel
464
465 /*
466 Signal triggered when the model is about to remove a picker. We cannot rely on
467 rowAboutToBeRemoved, as by the time the signal is called the list element is
468 already removed from the model.
469 */
470 signal pickerRemoved(int index)
471
472 // the function checks whether a pickerModel was added or not
473 // returns the index of the model object the pickerModel was found
474 // or -1 on error.
475 function pickerModelIndex(name) {
476 for (var i = 0; i < count; i++) {
477 if (get(i).pickerName === name) {
478 return i;
479 }
480 }
481 return -1;
482 }
483
484 // the function checks whether a pickerModel is present in the list;
485 // moves the existing one to the given index or inserts it if not present
486 function setPickerModel(model, name, index) {
487 var idx = pickerModelIndex(name);
488 if (idx >= 0) {
489 move(idx, index, 1);
490 } else {
491 append({"pickerModel": model, "pickerName": name});
492 }
493 }
494
495 // removes the given picker
496 function removePicker(name) {
497 var idx = pickerModelIndex(name);
498 if (idx >= 0) {
499 pickerRemoved(idx);
500 remove(idx);
501 }
502 }
503 }
504
505 // component to calculate text fitting
506 Label { id: textSizer; visible: false }
507 QtObject {
508 id: internals
509 property bool completed: false
510 property real margin: units.gu(1.5)
511 property real dayPickerRatio: 0.1
512
513 property bool showYearPicker: true
514 property bool showMonthPicker: true
515 property bool showDayPicker: true
516
517 property bool showHoursPicker: false
518 property bool showMinutesPicker: false
519 property bool showSecondsPicker: false
520
521 /*
522 Update pickers.
523 */
524 function updatePickers() {
525 if (completed) {
526 // check mode flags first
527 // 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)
528 var modes = datePicker.mode.match(/\w+/g);
529
530 showYearPicker = showMonthPicker = showDayPicker =
531 showHoursPicker = showMinutesPicker = showSecondsPicker = false;
532 while (modes.length > 0) {
533 var modeFlag = modes.pop();
534 switch (modeFlag) {
535 case "Years":
536 showYearPicker = true;
537 break;
538 case "Months":
539 showMonthPicker = true;
540 break;
541 case "Days":
542 showDayPicker = true;
543 break;
544 case "Hours":
545 showHoursPicker = true;
546 break;
547 case "Minutes":
548 showMinutesPicker = true;
549 break;
550 case "Seconds":
551 showSecondsPicker = true;
552 break;
553 default:
554 console.warn("Unhandled mode flag: " + modeFlag + ". Mode will not be set!");
555 return;
556 }
557 }
558
559 // filter unaccepted date picking mode
560 if (!showMonthPicker && showYearPicker && showDayPicker) {
561 console.warn("Invalid DatePicker mode: " + datePicker.mode);
562 return;
563 }
564
565 // filter unaccepted time picking mode
566 if (showHoursPicker && showSecondsPicker && !showMinutesPicker) {
567 console.warn("Invalid DatePicker mode: " + datePicker.mode);
568 return;
569 }
570
571 // date and time picking not allowed at the same time
572 if ((showYearPicker || showMonthPicker || showDayPicker) &&
573 (showHoursPicker || showMinutesPicker || showSecondsPicker)) {
574 console.warn("Date and Time picking not allowed at the same time.");
575 return;
576 }
577
578 arrangeTumblers();
579 }
580 }
581
582 /*
583 Detects the tumbler order from the date format of the locale
584 */
585 function arrangeTumblers() {
586 // disable completion so avoid accidental date changes
587 completed = false;
588
589 // use short format to exclude any extra characters
590 // 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)
591 var format = datePicker.locale.dateFormat(Locale.ShortFormat).match(/\w+/g);
592 // loop through the format to decide the position of the tumbler
593 var formatIndex = 0;
594 for (var i in format) {
595 if (!format[i].length) continue;
596 // check the first two characters
597 switch (format[i].substr(0, 1).toLowerCase()) {
598 case 'y':
599 if (showYearPicker) {
600 tumblerModel.setPickerModel(yearModel, "YearPicker", formatIndex);
601 formatIndex++;
602 } else {
603 tumblerModel.removePicker("YearPicker");
604 }
605
606 break;
607 case 'm':
608 if (showMonthPicker) {
609 tumblerModel.setPickerModel(monthModel, "MonthPicker", formatIndex);
610 formatIndex++;
611 } else {
612 tumblerModel.removePicker("MonthPicker");
613 }
614
615 break;
616 case 'd':
617 if (showDayPicker) {
618 tumblerModel.setPickerModel(dayModel, "DayPicker", formatIndex);
619 formatIndex++;
620 } else {
621 tumblerModel.removePicker("DayPicker");
622 }
623 break;
624 }
625 }
626 // check hms
627 if (showHoursPicker) {
628 tumblerModel.setPickerModel(hoursModel, "HoursPicker", formatIndex);
629 formatIndex++;
630 } else {
631 tumblerModel.removePicker("HoursPicker");
632 }
633 if (showMinutesPicker) {
634 tumblerModel.setPickerModel(minutesModel, "MinutesPicker", formatIndex);
635 formatIndex++;
636 } else {
637 tumblerModel.removePicker("MinutesPicker");
638 }
639 if (showSecondsPicker) {
640 tumblerModel.setPickerModel(secondsModel, "SecondsPicker", formatIndex);
641 formatIndex++;
642 } else {
643 tumblerModel.removePicker("SecondsPicker");
644 }
645
646 // calculate the ratio for the dayPicker
647 var maxWidth = 0.0;
648 maxWidth += showYearPicker ? yearModel.longFormatLimit : 0.0;
649 maxWidth += showMonthPicker ? monthModel.longFormatLimit : 0.0;
650 maxWidth += showDayPicker ? dayModel.longFormatLimit : 0.0;
651 if (showDayPicker && maxWidth > 0.0) {
652 dayPickerRatio = (dayModel.longFormatLimit / maxWidth).toPrecision(3);
653 }
654
655 // re-enable completion
656 completed = true;
657 }
658 }
659 }