-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrange.dart
More file actions
608 lines (541 loc) · 21.2 KB
/
range.dart
File metadata and controls
608 lines (541 loc) · 21.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
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
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
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
part of '../../../inputs.dart';
class ThemedDateTimeRangePicker extends StatefulWidget {
/// [value] is the value of the input.
final List<DateTime> value;
/// [onChanged] is the callback function when the input is changed.
final void Function(List<DateTime>)? onChanged;
/// [labelText] is the label text of the input. Avoid submit [label] and [labelText] at the same time.
final String? labelText;
/// [label] is the label widget of the input. Avoid submit [label] and [labelText] at the same time.
final Widget? label;
/// [placeholder] is the placeholder of the input.
final String? placeholder;
/// [prefixText] is the prefix text of the input.
final String? prefixText;
/// [prefixIcon] is the prefix icon of the input. Avoid submit [prefixIcon] and [prefixWidget] at the same time.
final IconData? prefixIcon;
/// [prefixWidget] is the prefix widget of the input. Avoid submit [prefixIcon] and [prefixWidget] at the same time.
final Widget? prefixWidget;
/// [onPrefixTap] is the callback function when the prefix is tapped.
final VoidCallback? onPrefixTap;
/// [customChild] is the custom child of the input.
/// If it is submitted, the input will be ignored.
final Widget? customChild;
/// [disabled] is the disabled state of the input.
final bool disabled;
/// [translations] is the translations of the input. By default we use [LayrzAppLocalizations] for translations,
/// but you can submit your own translations using this property. Consider when [LayrzAppLocalizations] is present,
/// is the default value of this property.
/// Required translations:
/// - `actions.cancel` (Cancel)
/// - `actions.save` (Save)
/// - `layrz.monthPicker.year` (Year {year})
/// - `layrz.monthPicker.back` (Previous year)
/// - `layrz.monthPicker.next` (Next year)
/// - `layrz.datetimePicker.date` (Date)
/// - `layrz.datetimePicker.time` (Time)
/// - `layrz.timePicker.hours` (Hours)
/// - `layrz.timePicker.minutes` (Minutes)
/// - `layrz.calendar.month.back` (Previous month)
/// - `layrz.calendar.month.next` (Next month)
/// - `layrz.calendar.today` (Today)
/// - `layrz.calendar.month` (View as month)
/// - `layrz.calendar.pickMonth` (Pick a month)
final Map<String, String> translations;
/// [overridesLayrzTranslations] is the flag to override the default translations of Layrz.
final bool overridesLayrzTranslations;
/// [disabledMonths] is the list of disabled months.
final List<DateTime> disabledDays;
/// [datePattern] is the date pattern of the date. By default is `%Y-%m-%d`.
final String datePattern;
/// [timePattern] is the time pattern of the date. By default, depending of [use24HourFormat] we use
/// `%I:%M %p` or `%H:%M`. If [timePattern] is submitted, this will be used instead of the default.
final String? timePattern;
/// [use24HourFormat] is the flag to use 24 hour format. By default is false, so it will use 12 hour format.
final bool use24HourFormat;
/// [patternSeparator] is the separator between date and time. By default is ` ` (space).
final String patternSeparator;
/// [hoverColor] is the hover color of the input. Only will affect when [customChild] is submitted.
/// By default, it will use `Colors.transparent`.
final Color hoverColor;
/// [focusColor] is the focus color of the input. Only will affect when [customChild] is submitted.
/// By default, it will use `Colors.transparent`.
final Color focusColor;
/// [splashColor] is the splash color of the input. Only will affect when [customChild] is submitted.
/// By default, it will use `Colors.transparent`.
final Color splashColor;
/// [highlightColor] is the highlight color of the input. Only will affect when [customChild] is submitted.
/// By default, it will use `Colors.transparent`.
final Color highlightColor;
/// [borderRadius] is the border radius of the input. Only will affect when [customChild] is submitted.
/// By default, it will use `BorderRadius.circular(10)`.
final BorderRadius borderRadius;
/// [errors] is the list of errors of the input.
final List<String> errors;
/// [hideDetails] is the state of hiding the details of the input.
final bool hideDetails;
/// [emptyListText] is the text to be displayed when the list is empty.
final EdgeInsets? padding;
/// [lastDay] any datetime after this day will be disabled. If null, the calendar will not have a limit.
final DateTime? lastDay;
/// [firstDay] any datetime before this day will be disabled. If null, the calendar will not have a limit.
final DateTime? firstDay;
/// [ThemedDateTimeRangePicker] is a date time picker input. It is a wrapper of [ThemedTextInput]
/// with a date time picker.
const ThemedDateTimeRangePicker({
super.key,
this.value = const [],
this.onChanged,
this.labelText,
this.label,
this.placeholder,
this.prefixText,
this.prefixIcon,
this.prefixWidget,
this.onPrefixTap,
this.customChild,
this.disabled = false,
this.translations = const {
'actions.cancel': 'Cancel',
'actions.save': 'Save',
'layrz.monthPicker.year': 'Year {year}',
'layrz.monthPicker.back': 'Previous year',
'layrz.monthPicker.next': 'Next year',
'layrz.datetimePicker.date': 'Date',
'layrz.datetimePicker.time': 'Time',
'layrz.timePicker.hours': 'Hours',
'layrz.timePicker.minutes': 'Minutes',
'layrz.calendar.month.back': 'Previous month',
'layrz.calendar.month.next': 'Next month',
'layrz.calendar.today': 'Today',
'layrz.calendar.month': 'View as month',
'layrz.calendar.pickMonth': 'Pick a month',
},
this.overridesLayrzTranslations = false,
this.disabledDays = const [],
this.datePattern = '%Y-%m-%d',
this.timePattern,
this.use24HourFormat = false,
this.patternSeparator = ' ',
this.hoverColor = Colors.transparent,
this.focusColor = Colors.transparent,
this.splashColor = Colors.transparent,
this.highlightColor = Colors.transparent,
this.borderRadius = const .all(.circular(10)),
this.errors = const [],
this.hideDetails = false,
this.padding,
this.firstDay,
this.lastDay,
}) : assert((label == null && labelText != null) || (label != null && labelText == null)),
assert(value.length == 0 || value.length == 2);
@override
State<ThemedDateTimeRangePicker> createState() => _ThemedDateTimeRangePickerState();
}
class _ThemedDateTimeRangePickerState extends State<ThemedDateTimeRangePicker> with SingleTickerProviderStateMixin {
final TextEditingController _controller = TextEditingController();
late TabController _tabController;
LayrzAppLocalizations? get i18n => .maybeOf(context);
bool get isDark => Theme.of(context).brightness == .dark;
String get timePattern => widget.timePattern ?? (widget.use24HourFormat ? '%H:%M' : '%I:%M %p');
String get pattern => '${widget.datePattern}${widget.patternSeparator}$timePattern';
String? get _parsedName {
if (widget.value.isEmpty) {
return null;
}
return widget.value
.map((t) {
return t.format(pattern: pattern, i18n: i18n);
})
.join(' - ');
}
@override
void initState() {
super.initState();
_tabController = TabController(length: 2, vsync: this);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _controller.text = _parsedName ?? '';
});
}
@override
void didUpdateWidget(covariant ThemedDateTimeRangePicker oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.value != oldWidget.value) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _controller.text = _parsedName ?? '';
});
}
}
@override
void dispose() {
_tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (widget.customChild != null) {
return InkWell(
hoverColor: widget.hoverColor,
focusColor: widget.focusColor,
splashColor: widget.splashColor,
highlightColor: widget.highlightColor,
borderRadius: widget.borderRadius,
onTap: widget.disabled ? null : _showPicker,
child: widget.customChild!,
);
}
return ThemedTextInput(
controller: _controller,
value: _parsedName ?? '',
labelText: widget.labelText,
label: widget.label,
placeholder: widget.placeholder,
prefixText: widget.prefixText,
prefixIcon: widget.prefixIcon,
prefixWidget: widget.prefixWidget,
onPrefixTap: widget.onPrefixTap,
suffixIcon: LayrzIcons.solarOutlineCalendar,
disabled: widget.disabled,
readonly: true,
onTap: widget.disabled ? null : _showPicker,
errors: widget.errors,
hideDetails: widget.hideDetails,
padding: widget.padding,
);
}
void _showPicker() async {
List<DateTime>? selected = await showDialog(
context: context,
builder: (context) => ThemedDateTimeRangeDialog(
value: widget.value,
labelText: widget.labelText,
disabledDays: widget.disabledDays,
translations: widget.translations,
overridesLayrzTranslations: widget.overridesLayrzTranslations,
use24HourFormat: widget.use24HourFormat,
firstDay: widget.firstDay,
lastDay: widget.lastDay,
),
);
if (selected != null) {
widget.onChanged?.call(selected);
}
}
String t(String key, [Map<String, dynamic> args = const {}]) {
String result = LayrzAppLocalizations.maybeOf(context)?.t(key, args) ?? widget.translations[key] ?? key;
if (widget.overridesLayrzTranslations) {
result = widget.translations[key] ?? key;
}
if (args.isNotEmpty) {
args.forEach((key, value) {
result = result.replaceAll('{$key}', value.toString());
});
}
return result;
}
}
class ThemedDateTimeRangeDialog extends StatefulWidget {
final List<DateTime> value;
final String? labelText;
final List<DateTime> disabledDays;
final Map<String, String> translations;
final bool overridesLayrzTranslations;
final DateTime? firstDay;
final DateTime? lastDay;
final bool use24HourFormat;
const ThemedDateTimeRangeDialog({
super.key,
this.value = const [],
this.labelText,
this.disabledDays = const [],
this.translations = const {},
this.overridesLayrzTranslations = false,
this.use24HourFormat = false,
this.firstDay,
this.lastDay,
});
@override
State<ThemedDateTimeRangeDialog> createState() => _ThemedDateTimeRangeDialogState();
}
class _ThemedDateTimeRangeDialogState extends State<ThemedDateTimeRangeDialog> with TickerProviderStateMixin {
bool get isDark => Theme.of(context).brightness == Brightness.dark;
late TabController _tabController;
late DateTime startDate;
late DateTime endDate;
late TimeOfDay startTime;
late TimeOfDay endTime;
late List<DateTime> filledDates;
@override
void initState() {
super.initState();
_tabController = TabController(length: 2, vsync: this);
startDate = widget.value.isNotEmpty ? widget.value.first : DateTime.now();
endDate = widget.value.isNotEmpty ? widget.value.last : DateTime.now();
startTime = widget.value.isNotEmpty ? TimeOfDay.fromDateTime(widget.value.first) : TimeOfDay.now();
endTime = widget.value.isNotEmpty ? TimeOfDay.fromDateTime(widget.value.last) : TimeOfDay.now();
filledDates = _fillDates(
[startDate, endDate]..sort((a, b) {
return a.compareTo(b);
}),
);
}
@override
void dispose() {
_tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
DateTime? tempDate;
return Dialog(
backgroundColor: Colors.transparent,
child: Container(
padding: const EdgeInsets.all(20),
constraints: const BoxConstraints(maxWidth: 400),
decoration: generateContainerElevation(context: context, elevation: 3),
child: StatefulBuilder(
builder: (context, setState) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
widget.labelText ?? '',
style: Theme.of(context).textTheme.bodyLarge?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 10),
Container(
height: 40,
decoration: BoxDecoration(
color: Theme.of(context).dividerColor,
borderRadius: BorderRadius.circular(10),
),
clipBehavior: Clip.antiAlias,
child: Row(
children: [
Expanded(
child: _drawTab(
index: 0,
labelText: t('layrz.datetimePicker.date'),
onTap: () {
_tabController.animateTo(0);
setState(() {});
},
),
),
Expanded(
child: _drawTab(
index: 1,
labelText: t('layrz.datetimePicker.time'),
onTap: () {
_tabController.animateTo(1);
setState(() {});
},
),
),
],
),
),
Container(
constraints: const BoxConstraints(maxWidth: 400, maxHeight: 400),
child: TabBarView(
controller: _tabController,
children: [
ThemedCalendar(
firstDay: widget.firstDay,
lastDay: widget.lastDay,
focusDay: tempDate,
focusOnHighlightedDays: tempDate == null,
showEntries: false,
smallWeekdays: true,
todayIndicator: false,
todayButton: false,
highlightedDays: tempDate != null ? [] : filledDates,
isHighlightDaysAsRange: tempDate == null,
disabledDays: widget.disabledDays,
translations: widget.translations,
overridesLayrzTranslations: widget.overridesLayrzTranslations,
onDayTap: (newDate) {
if (tempDate == null) {
tempDate = newDate;
startDate = newDate;
setState(() {});
return;
}
endDate = newDate;
tempDate = null;
if (endDate.isBefore(startDate)) {
final swap = startDate;
startDate = endDate;
endDate = swap;
}
filledDates = _fillDates([startDate, endDate]);
setState(() {});
},
),
Column(
children: [
const Spacer(),
_ThemedTimeUtility(
value: startTime,
use24HourFormat: widget.use24HourFormat,
titleText: widget.labelText ?? '',
hoursText: t('layrz.timePicker.hours'),
minutesText: t('layrz.timePicker.minutes'),
saveText: t('actions.save'),
cancelText: t('actions.cancel'),
inDialog: false,
onChanged: (newTime) => setState(() => startTime = newTime),
),
const Spacer(),
_ThemedTimeUtility(
value: endTime,
use24HourFormat: widget.use24HourFormat,
titleText: widget.labelText ?? '',
hoursText: t('layrz.timePicker.hours'),
minutesText: t('layrz.timePicker.minutes'),
saveText: t('actions.save'),
cancelText: t('actions.cancel'),
inDialog: false,
onChanged: (newTime) => setState(() => endTime = newTime),
),
const Spacer(),
],
),
],
),
),
const SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
ThemedButton.cancel(
labelText: t('actions.cancel'),
onTap: () => Navigator.of(context).pop(),
),
ThemedButton.save(
labelText: t('actions.save'),
onTap: () {
Location? tz;
if (widget.value.isNotEmpty && widget.value.first is TZDateTime) {
final value = widget.value.first;
if (value is TZDateTime) tz = value.location;
}
DateTime start;
DateTime end;
if (tz != null) {
start = TZDateTime(
tz,
startDate.year,
startDate.month,
startDate.day,
startTime.hour,
startTime.minute,
);
end = TZDateTime(
tz,
endDate.year,
endDate.month,
endDate.day,
endTime.hour,
endTime.minute,
);
} else {
start = DateTime(
startDate.year,
startDate.month,
startDate.day,
startTime.hour,
startTime.minute,
);
end = DateTime(
endDate.year,
endDate.month,
endDate.day,
endTime.hour,
endTime.minute,
);
}
_tabController.animateTo(0);
Navigator.of(context).pop(
[start, end]..sort((a, b) {
return a.compareTo(b);
}),
);
},
),
],
),
],
);
},
),
),
);
}
List<DateTime> _fillDates(List<DateTime> source) {
List<DateTime> filledDates = [];
if (source.isNotEmpty) {
filledDates.add(source.first);
while (true) {
final temp = filledDates.last.add(const Duration(days: 1));
if (temp.isAfter(source.last)) {
break;
}
filledDates.add(temp);
}
}
return filledDates;
}
String t(String key, [Map<String, dynamic> args = const {}]) {
String result = LayrzAppLocalizations.maybeOf(context)?.t(key, args) ?? widget.translations[key] ?? key;
if (widget.overridesLayrzTranslations) {
result = widget.translations[key] ?? key;
}
if (args.isNotEmpty) {
args.forEach((key, value) {
result = result.replaceAll('{$key}', value.toString());
});
}
return result;
}
Widget _drawTab({
required int index,
required String labelText,
required VoidCallback onTap,
}) {
bool isActive = _tabController.index == index;
return Material(
color: Colors.transparent,
child: InkWell(
onTap: isActive ? null : onTap,
child: Container(
height: double.infinity,
alignment: Alignment.center,
decoration: BoxDecoration(
color: isActive
? isDark
? Colors.white.withValues(alpha: 0.3)
: Theme.of(context).primaryColor.withValues(alpha: 0.3)
: Theme.of(context).dividerColor,
),
child: Text(
labelText,
style: TextStyle(
color: isActive
? isDark
? Colors.white
: isActive
? Theme.of(context).primaryColor
: validateColor(color: Theme.of(context).primaryColor)
: null,
fontWeight: FontWeight.bold,
),
),
),
),
);
}
}