-
Notifications
You must be signed in to change notification settings - Fork 13.5k
/
datetime.tsx
2662 lines (2365 loc) · 85.9 KB
/
datetime.tsx
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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { ComponentInterface, EventEmitter } from '@stencil/core';
import { Component, Element, Event, Host, Method, Prop, State, Watch, h, writeTask } from '@stencil/core';
import { startFocusVisible } from '@utils/focus-visible';
import { getElementRoot, raf, renderHiddenInput } from '@utils/helpers';
import { printIonError, printIonWarning } from '@utils/logging';
import { isRTL } from '@utils/rtl';
import { createColorClasses } from '@utils/theme';
import { caretDownSharp, caretUpSharp, chevronBack, chevronDown, chevronForward } from 'ionicons/icons';
import { getIonMode } from '../../global/ionic-global';
import type { Color, Mode, StyleEventDetail } from '../../interface';
import type {
DatetimePresentation,
DatetimeChangeEventDetail,
DatetimeParts,
TitleSelectedDatesFormatter,
DatetimeHighlight,
DatetimeHighlightStyle,
DatetimeHighlightCallback,
DatetimeHourCycle,
FormatOptions,
} from './datetime-interface';
import { isSameDay, warnIfValueOutOfBounds, isBefore, isAfter } from './utils/comparison';
import type { WheelColumnOption } from './utils/data';
import {
generateMonths,
getDaysOfMonth,
getDaysOfWeek,
getToday,
getMonthColumnData,
getDayColumnData,
getYearColumnData,
getTimeColumnsData,
getCombinedDateColumnData,
} from './utils/data';
import { formatValue, getLocalizedDateTime, getLocalizedTime, getMonthAndYear } from './utils/format';
import { isLocaleDayPeriodRTL, isMonthFirstLocale, getNumDaysInMonth, getHourCycle } from './utils/helpers';
import {
calculateHourFromAMPM,
convertDataToISO,
getClosestValidDate,
getEndOfWeek,
getNextDay,
getNextMonth,
getNextWeek,
getNextYear,
getPreviousDay,
getPreviousMonth,
getPreviousWeek,
getPreviousYear,
getStartOfWeek,
validateParts,
} from './utils/manipulation';
import {
clampDate,
convertToArrayOfNumbers,
getPartsFromCalendarDay,
parseAmPm,
parseDate,
parseMaxParts,
parseMinParts,
} from './utils/parse';
import {
getCalendarDayState,
getHighlightStyles,
isDayDisabled,
isMonthDisabled,
isNextMonthDisabled,
isPrevMonthDisabled,
} from './utils/state';
import { checkForPresentationFormatMismatch, warnIfTimeZoneProvided } from './utils/validate';
/**
* @virtualProp {"ios" | "md"} mode - The mode determines which platform styles to use.
*
* @slot title - The title of the datetime.
* @slot buttons - The buttons in the datetime.
* @slot time-label - The label for the time selector in the datetime.
*
* @part wheel-item - The individual items when using a wheel style layout, or in the
* month/year picker when using a grid style layout.
* @part wheel-item active - The currently selected wheel-item.
*
* @part time-button - The button that opens the time picker when using a grid style
* layout with `presentation="date-time"` or `"time-date"`.
* @part time-button active - The time picker button when the picker is open.
*
* @part month-year-button - The button that opens the month/year picker when
* using a grid style layout.
*
* @part calendar-day - The individual buttons that display a day inside of the datetime
* calendar.
* @part calendar-day active - The currently selected calendar day.
* @part calendar-day today - The calendar day that contains the current day.
* @part calendar-day disabled - The calendar day that is disabled.
*/
@Component({
tag: 'ion-datetime',
styleUrls: {
ios: 'datetime.ios.scss',
md: 'datetime.md.scss',
},
shadow: true,
})
export class Datetime implements ComponentInterface {
private inputId = `ion-dt-${datetimeIds++}`;
private calendarBodyRef?: HTMLElement;
private popoverRef?: HTMLIonPopoverElement;
private intersectionTrackerRef?: HTMLElement;
private clearFocusVisible?: () => void;
private parsedMinuteValues?: number[];
private parsedHourValues?: number[];
private parsedMonthValues?: number[];
private parsedYearValues?: number[];
private parsedDayValues?: number[];
private destroyCalendarListener?: () => void;
private destroyKeyboardMO?: () => void;
// TODO(FW-2832): types (DatetimeParts causes some errors that need untangling)
private minParts?: any;
private maxParts?: any;
private todayParts!: DatetimeParts;
private defaultParts!: DatetimeParts;
private prevPresentation: string | null = null;
private resolveForceDateScrolling?: () => void;
@State() showMonthAndYear = false;
@State() activeParts: DatetimeParts | DatetimeParts[] = [];
@State() workingParts: DatetimeParts = {
month: 5,
day: 28,
year: 2021,
hour: 13,
minute: 52,
ampm: 'pm',
};
@Element() el!: HTMLIonDatetimeElement;
@State() isTimePopoverOpen = false;
/**
* When defined, will force the datetime to render the month
* containing the specified date. Currently, this should only
* be used to enable immediately auto-scrolling to the new month,
* and should then be reset to undefined once the transition is
* finished and the forced month is now in view.
*
* Applies to grid-style datetimes only.
*/
@State() forceRenderDate?: DatetimeParts;
/**
* The color to use from your application's color palette.
* Default options are: `"primary"`, `"secondary"`, `"tertiary"`, `"success"`, `"warning"`, `"danger"`, `"light"`, `"medium"`, and `"dark"`.
* For more information on colors, see [theming](/docs/theming/basics).
*/
@Prop() color?: Color = 'primary';
/**
* The name of the control, which is submitted with the form data.
*/
@Prop() name: string = this.inputId;
/**
* If `true`, the user cannot interact with the datetime.
*/
@Prop() disabled = false;
/**
* Formatting options for dates and times.
* Should include a 'date' and/or 'time' object, each of which is of type [Intl.DateTimeFormatOptions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options).
*
*/
@Prop() formatOptions?: FormatOptions;
@Watch('formatOptions')
protected formatOptionsChanged() {
const { el, formatOptions, presentation } = this;
checkForPresentationFormatMismatch(el, presentation, formatOptions);
warnIfTimeZoneProvided(el, formatOptions);
}
/**
* If `true`, the datetime appears normal but the selected date cannot be changed.
*/
@Prop() readonly = false;
/**
* Returns if an individual date (calendar day) is enabled or disabled.
*
* If `true`, the day will be enabled/interactive.
* If `false`, the day will be disabled/non-interactive.
*
* The function accepts an ISO 8601 date string of a given day.
* By default, all days are enabled. Developers can use this function
* to write custom logic to disable certain days.
*
* The function is called for each rendered calendar day, for the previous, current and next month.
* Custom implementations should be optimized for performance to avoid jank.
*/
@Prop() isDateEnabled?: (dateIsoString: string) => boolean;
@Watch('disabled')
protected disabledChanged() {
this.emitStyle();
}
/**
* The minimum datetime allowed. Value must be a date string
* following the
* [ISO 8601 datetime format standard](https://www.w3.org/TR/NOTE-datetime),
* such as `1996-12-19`. The format does not have to be specific to an exact
* datetime. For example, the minimum could just be the year, such as `1994`.
* Defaults to the beginning of the year, 100 years ago from today.
*/
@Prop({ mutable: true }) min?: string;
@Watch('min')
protected minChanged() {
this.processMinParts();
}
/**
* The maximum datetime allowed. Value must be a date string
* following the
* [ISO 8601 datetime format standard](https://www.w3.org/TR/NOTE-datetime),
* `1996-12-19`. The format does not have to be specific to an exact
* datetime. For example, the maximum could just be the year, such as `1994`.
* Defaults to the end of this year.
*/
@Prop({ mutable: true }) max?: string;
@Watch('max')
protected maxChanged() {
this.processMaxParts();
}
/**
* Which values you want to select. `"date"` will show
* a calendar picker to select the month, day, and year. `"time"`
* will show a time picker to select the hour, minute, and (optionally)
* AM/PM. `"date-time"` will show the date picker first and time picker second.
* `"time-date"` will show the time picker first and date picker second.
*/
@Prop() presentation: DatetimePresentation = 'date-time';
@Watch('presentation')
protected presentationChanged() {
const { el, formatOptions, presentation } = this;
checkForPresentationFormatMismatch(el, presentation, formatOptions);
}
private get isGridStyle() {
const { presentation, preferWheel } = this;
const hasDatePresentation = presentation === 'date' || presentation === 'date-time' || presentation === 'time-date';
return hasDatePresentation && !preferWheel;
}
/**
* The text to display on the picker's cancel button.
*/
@Prop() cancelText = 'Cancel';
/**
* The text to display on the picker's "Done" button.
*/
@Prop() doneText = 'Done';
/**
* The text to display on the picker's "Clear" button.
*/
@Prop() clearText = 'Clear';
/**
* Values used to create the list of selectable years. By default
* the year values range between the `min` and `max` datetime inputs. However, to
* control exactly which years to display, the `yearValues` input can take a number, an array
* of numbers, or string of comma separated numbers. For example, to show upcoming and
* recent leap years, then this input's value would be `yearValues="2008,2012,2016,2020,2024"`.
*/
@Prop() yearValues?: number[] | number | string;
@Watch('yearValues')
protected yearValuesChanged() {
this.parsedYearValues = convertToArrayOfNumbers(this.yearValues);
}
/**
* Values used to create the list of selectable months. By default
* the month values range from `1` to `12`. However, to control exactly which months to
* display, the `monthValues` input can take a number, an array of numbers, or a string of
* comma separated numbers. For example, if only summer months should be shown, then this
* input value would be `monthValues="6,7,8"`. Note that month numbers do *not* have a
* zero-based index, meaning January's value is `1`, and December's is `12`.
*/
@Prop() monthValues?: number[] | number | string;
@Watch('monthValues')
protected monthValuesChanged() {
this.parsedMonthValues = convertToArrayOfNumbers(this.monthValues);
}
/**
* Values used to create the list of selectable days. By default
* every day is shown for the given month. However, to control exactly which days of
* the month to display, the `dayValues` input can take a number, an array of numbers, or
* a string of comma separated numbers. Note that even if the array days have an invalid
* number for the selected month, like `31` in February, it will correctly not show
* days which are not valid for the selected month.
*/
@Prop() dayValues?: number[] | number | string;
@Watch('dayValues')
protected dayValuesChanged() {
this.parsedDayValues = convertToArrayOfNumbers(this.dayValues);
}
/**
* Values used to create the list of selectable hours. By default
* the hour values range from `0` to `23` for 24-hour, or `1` to `12` for 12-hour. However,
* to control exactly which hours to display, the `hourValues` input can take a number, an
* array of numbers, or a string of comma separated numbers.
*/
@Prop() hourValues?: number[] | number | string;
@Watch('hourValues')
protected hourValuesChanged() {
this.parsedHourValues = convertToArrayOfNumbers(this.hourValues);
}
/**
* Values used to create the list of selectable minutes. By default
* the minutes range from `0` to `59`. However, to control exactly which minutes to display,
* the `minuteValues` input can take a number, an array of numbers, or a string of comma
* separated numbers. For example, if the minute selections should only be every 15 minutes,
* then this input value would be `minuteValues="0,15,30,45"`.
*/
@Prop() minuteValues?: number[] | number | string;
@Watch('minuteValues')
protected minuteValuesChanged() {
this.parsedMinuteValues = convertToArrayOfNumbers(this.minuteValues);
}
/**
* The locale to use for `ion-datetime`. This
* impacts month and day name formatting.
* The `"default"` value refers to the default
* locale set by your device.
*/
@Prop() locale = 'default';
/**
* The first day of the week to use for `ion-datetime`. The
* default value is `0` and represents Sunday.
*/
@Prop() firstDayOfWeek = 0;
/**
* A callback used to format the header text that shows how many
* dates are selected. Only used if there are 0 or more than 1
* selected (i.e. unused for exactly 1). By default, the header
* text is set to "numberOfDates days".
*
* See https://ionicframework.com/docs/troubleshooting/runtime#accessing-this
* if you need to access `this` from within the callback.
*/
@Prop() titleSelectedDatesFormatter?: TitleSelectedDatesFormatter;
/**
* If `true`, multiple dates can be selected at once. Only
* applies to `presentation="date"` and `preferWheel="false"`.
*/
@Prop() multiple = false;
/**
* Used to apply custom text and background colors to specific dates.
*
* Can be either an array of objects containing ISO strings and colors,
* or a callback that receives an ISO string and returns the colors.
*
* Only applies to the `date`, `date-time`, and `time-date` presentations,
* with `preferWheel="false"`.
*/
@Prop() highlightedDates?: DatetimeHighlight[] | DatetimeHighlightCallback;
/**
* The value of the datetime as a valid ISO 8601 datetime string.
* This should be an array of strings only when `multiple="true"`.
*/
@Prop({ mutable: true }) value?: string | string[] | null;
/**
* Update the datetime value when the value changes
*/
@Watch('value')
protected async valueChanged() {
const { value } = this;
if (this.hasValue()) {
this.processValue(value);
}
this.emitStyle();
this.ionValueChange.emit({ value });
}
/**
* If `true`, a header will be shown above the calendar
* picker. This will include both the slotted title, and
* the selected date.
*/
@Prop() showDefaultTitle = false;
/**
* If `true`, the default "Cancel" and "OK" buttons
* will be rendered at the bottom of the `ion-datetime`
* component. Developers can also use the `button` slot
* if they want to customize these buttons. If custom
* buttons are set in the `button` slot then the
* default buttons will not be rendered.
*/
@Prop() showDefaultButtons = false;
/**
* If `true`, a "Clear" button will be rendered alongside
* the default "Cancel" and "OK" buttons at the bottom of the `ion-datetime`
* component. Developers can also use the `button` slot
* if they want to customize these buttons. If custom
* buttons are set in the `button` slot then the
* default buttons will not be rendered.
*/
@Prop() showClearButton = false;
/**
* If `true`, the default "Time" label will be rendered
* for the time selector of the `ion-datetime` component.
* Developers can also use the `time-label` slot
* if they want to customize this label. If a custom
* label is set in the `time-label` slot then the
* default label will not be rendered.
*/
@Prop() showDefaultTimeLabel = true;
/**
* The hour cycle of the `ion-datetime`. If no value is set, this is
* specified by the current locale.
*/
@Prop() hourCycle?: DatetimeHourCycle;
/**
* If `cover`, the `ion-datetime` will expand to cover the full width of its container.
* If `fixed`, the `ion-datetime` will have a fixed width.
*/
@Prop() size: 'cover' | 'fixed' = 'fixed';
/**
* If `true`, a wheel picker will be rendered instead of a calendar grid
* where possible. If `false`, a calendar grid will be rendered instead of
* a wheel picker where possible.
*
* A wheel picker can be rendered instead of a grid when `presentation` is
* one of the following values: `"date"`, `"date-time"`, or `"time-date"`.
*
* A wheel picker will always be rendered regardless of
* the `preferWheel` value when `presentation` is one of the following values:
* `"time"`, `"month"`, `"month-year"`, or `"year"`.
*/
@Prop() preferWheel = false;
/**
* Emitted when the datetime selection was cancelled.
*/
@Event() ionCancel!: EventEmitter<void>;
/**
* Emitted when the value (selected date) has changed.
*
* This event will not emit when programmatically setting the `value` property.
*/
@Event() ionChange!: EventEmitter<DatetimeChangeEventDetail>;
/**
* Emitted when the value property has changed.
* This is used to ensure that ion-datetime-button can respond
* to any value property changes.
* @internal
*/
@Event() ionValueChange!: EventEmitter<DatetimeChangeEventDetail>;
/**
* Emitted when the datetime has focus.
*/
@Event() ionFocus!: EventEmitter<void>;
/**
* Emitted when the datetime loses focus.
*/
@Event() ionBlur!: EventEmitter<void>;
/**
* Emitted when the styles change.
* @internal
*/
@Event() ionStyle!: EventEmitter<StyleEventDetail>;
/**
* Emitted when componentDidRender is fired.
* @internal
*/
@Event() ionRender!: EventEmitter<void>;
/**
* Confirms the selected datetime value, updates the
* `value` property, and optionally closes the popover
* or modal that the datetime was presented in.
*/
@Method()
async confirm(closeOverlay = false) {
const { isCalendarPicker, activeParts, preferWheel, workingParts } = this;
/**
* We only update the value if the presentation is not a calendar picker.
*/
if (activeParts !== undefined || !isCalendarPicker) {
const activePartsIsArray = Array.isArray(activeParts);
if (activePartsIsArray && activeParts.length === 0) {
if (preferWheel) {
/**
* If the datetime is using a wheel picker, but the
* active parts are empty, then the user has confirmed the
* initial value (working parts) presented to them.
*/
this.setValue(convertDataToISO(workingParts));
} else {
this.setValue(undefined);
}
} else {
this.setValue(convertDataToISO(activeParts));
}
}
if (closeOverlay) {
this.closeParentOverlay(CONFIRM_ROLE);
}
}
/**
* Resets the internal state of the datetime but does not update the value.
* Passing a valid ISO-8601 string will reset the state of the component to the provided date.
* If no value is provided, the internal state will be reset to the clamped value of the min, max and today.
*/
@Method()
async reset(startDate?: string) {
this.processValue(startDate);
}
/**
* Emits the ionCancel event and
* optionally closes the popover
* or modal that the datetime was
* presented in.
*/
@Method()
async cancel(closeOverlay = false) {
this.ionCancel.emit();
if (closeOverlay) {
this.closeParentOverlay(CANCEL_ROLE);
}
}
private warnIfIncorrectValueUsage = () => {
const { multiple, value } = this;
if (!multiple && Array.isArray(value)) {
/**
* We do some processing on the `value` array so
* that it looks more like an array when logged to
* the console.
* Example given ['a', 'b']
* Default toString() behavior: a,b
* Custom behavior: ['a', 'b']
*/
printIonWarning(
`ion-datetime was passed an array of values, but multiple="false". This is incorrect usage and may result in unexpected behaviors. To dismiss this warning, pass a string to the "value" property when multiple="false".
Value Passed: [${value.map((v) => `'${v}'`).join(', ')}]
`,
this.el
);
}
};
private setValue = (value?: string | string[] | null) => {
this.value = value;
this.ionChange.emit({ value });
};
/**
* Returns the DatetimePart interface
* to use when rendering an initial set of
* data. This should be used when rendering an
* interface in an environment where the `value`
* may not be set. This function works
* by returning the first selected date and then
* falling back to defaultParts if no active date
* is selected.
*/
private getActivePartsWithFallback = () => {
const { defaultParts } = this;
return this.getActivePart() ?? defaultParts;
};
private getActivePart = () => {
const { activeParts } = this;
return Array.isArray(activeParts) ? activeParts[0] : activeParts;
};
private closeParentOverlay = (role: string) => {
const popoverOrModal = this.el.closest('ion-modal, ion-popover') as
| HTMLIonModalElement
| HTMLIonPopoverElement
| null;
if (popoverOrModal) {
popoverOrModal.dismiss(undefined, role);
}
};
private setWorkingParts = (parts: DatetimeParts) => {
this.workingParts = {
...parts,
};
};
private setActiveParts = (parts: DatetimeParts, removeDate = false) => {
/** if the datetime component is in readonly mode,
* allow browsing of the calendar without changing
* the set value
*/
if (this.readonly) {
return;
}
const { multiple, minParts, maxParts, activeParts } = this;
/**
* When setting the active parts, it is possible
* to set invalid data. For example,
* when updating January 31 to February,
* February 31 does not exist. As a result
* we need to validate the active parts and
* ensure that we are only setting valid dates.
* Additionally, we need to update the working parts
* too in the event that the validated parts are different.
*/
const validatedParts = validateParts(parts, minParts, maxParts);
this.setWorkingParts(validatedParts);
if (multiple) {
const activePartsArray = Array.isArray(activeParts) ? activeParts : [activeParts];
if (removeDate) {
this.activeParts = activePartsArray.filter((p) => !isSameDay(p, validatedParts));
} else {
this.activeParts = [...activePartsArray, validatedParts];
}
} else {
this.activeParts = {
...validatedParts,
};
}
const hasSlottedButtons = this.el.querySelector('[slot="buttons"]') !== null;
if (hasSlottedButtons || this.showDefaultButtons) {
return;
}
this.confirm();
};
private get isCalendarPicker() {
const { presentation } = this;
return presentation === 'date' || presentation === 'date-time' || presentation === 'time-date';
}
private initializeKeyboardListeners = () => {
const calendarBodyRef = this.calendarBodyRef;
if (!calendarBodyRef) {
return;
}
const root = this.el!.shadowRoot!;
/**
* Get a reference to the month
* element we are currently viewing.
*/
const currentMonth = calendarBodyRef.querySelector('.calendar-month:nth-of-type(2)')!;
/**
* When focusing the calendar body, we want to pass focus
* to the working day, but other days should
* only be accessible using the arrow keys. Pressing
* Tab should jump between bodies of selectable content.
*/
const checkCalendarBodyFocus = (ev: MutationRecord[]) => {
const record = ev[0];
/**
* If calendar body was already focused
* when this fired or if the calendar body
* if not currently focused, we should not re-focus
* the inner day.
*/
if (record.oldValue?.includes('ion-focused') || !calendarBodyRef.classList.contains('ion-focused')) {
return;
}
this.focusWorkingDay(currentMonth);
};
const mo = new MutationObserver(checkCalendarBodyFocus);
mo.observe(calendarBodyRef, { attributeFilter: ['class'], attributeOldValue: true });
this.destroyKeyboardMO = () => {
mo?.disconnect();
};
/**
* We must use keydown not keyup as we want
* to prevent scrolling when using the arrow keys.
*/
calendarBodyRef.addEventListener('keydown', (ev: KeyboardEvent) => {
const activeElement = root.activeElement;
if (!activeElement || !activeElement.classList.contains('calendar-day')) {
return;
}
const parts = getPartsFromCalendarDay(activeElement as HTMLElement);
let partsToFocus: DatetimeParts | undefined;
switch (ev.key) {
case 'ArrowDown':
ev.preventDefault();
partsToFocus = getNextWeek(parts);
break;
case 'ArrowUp':
ev.preventDefault();
partsToFocus = getPreviousWeek(parts);
break;
case 'ArrowRight':
ev.preventDefault();
partsToFocus = getNextDay(parts);
break;
case 'ArrowLeft':
ev.preventDefault();
partsToFocus = getPreviousDay(parts);
break;
case 'Home':
ev.preventDefault();
partsToFocus = getStartOfWeek(parts);
break;
case 'End':
ev.preventDefault();
partsToFocus = getEndOfWeek(parts);
break;
case 'PageUp':
ev.preventDefault();
partsToFocus = ev.shiftKey ? getPreviousYear(parts) : getPreviousMonth(parts);
break;
case 'PageDown':
ev.preventDefault();
partsToFocus = ev.shiftKey ? getNextYear(parts) : getNextMonth(parts);
break;
/**
* Do not preventDefault here
* as we do not want to override other
* browser defaults such as pressing Enter/Space
* to select a day.
*/
default:
return;
}
/**
* If the day we want to move focus to is
* disabled, do not do anything.
*/
if (isDayDisabled(partsToFocus, this.minParts, this.maxParts)) {
return;
}
this.setWorkingParts({
...this.workingParts,
...partsToFocus,
});
/**
* Give view a chance to re-render
* then move focus to the new working day
*/
requestAnimationFrame(() => this.focusWorkingDay(currentMonth));
});
};
private focusWorkingDay = (currentMonth: Element) => {
/**
* Get the number of padding days so
* we know how much to offset our next selector by
* to grab the correct calendar-day element.
*/
const padding = currentMonth.querySelectorAll('.calendar-day-padding');
const { day } = this.workingParts;
if (day === null) {
return;
}
/**
* Get the calendar day element
* and focus it.
*/
const dayEl = currentMonth.querySelector(
`.calendar-day-wrapper:nth-of-type(${padding.length + day}) .calendar-day`
) as HTMLElement | null;
if (dayEl) {
dayEl.focus();
}
};
private processMinParts = () => {
const { min, defaultParts } = this;
if (min === undefined) {
this.minParts = undefined;
return;
}
this.minParts = parseMinParts(min, defaultParts);
};
private processMaxParts = () => {
const { max, defaultParts } = this;
if (max === undefined) {
this.maxParts = undefined;
return;
}
this.maxParts = parseMaxParts(max, defaultParts);
};
private initializeCalendarListener = () => {
const calendarBodyRef = this.calendarBodyRef;
if (!calendarBodyRef) {
return;
}
/**
* For performance reasons, we only render 3
* months at a time: The current month, the previous
* month, and the next month. We have a scroll listener
* on the calendar body to append/prepend new months.
*
* We can do this because Stencil is smart enough to not
* re-create the .calendar-month containers, but rather
* update the content within those containers.
*
* As an added bonus, WebKit has some troubles with
* scroll-snap-stop: always, so not rendering all of
* the months in a row allows us to mostly sidestep
* that issue.
*/
const months = calendarBodyRef.querySelectorAll('.calendar-month');
const startMonth = months[0] as HTMLElement;
const workingMonth = months[1] as HTMLElement;
const endMonth = months[2] as HTMLElement;
const mode = getIonMode(this);
const needsiOSRubberBandFix = mode === 'ios' && typeof navigator !== 'undefined' && navigator.maxTouchPoints > 1;
/**
* Before setting up the scroll listener,
* scroll the middle month into view.
* scrollIntoView() will scroll entire page
* if element is not in viewport. Use scrollLeft instead.
*/
writeTask(() => {
calendarBodyRef.scrollLeft = startMonth.clientWidth * (isRTL(this.el) ? -1 : 1);
const getChangedMonth = (parts: DatetimeParts): DatetimeParts | undefined => {
const box = calendarBodyRef.getBoundingClientRect();
/**
* If the current scroll position is all the way to the left
* then we have scrolled to the previous month.
* Otherwise, assume that we have scrolled to the next
* month. We have a tolerance of 2px to account for
* sub pixel rendering.
*
* Check below the next line ensures that we did not
* swipe and abort (i.e. we swiped but we are still on the current month).
*/
const condition = isRTL(this.el) ? calendarBodyRef.scrollLeft >= -2 : calendarBodyRef.scrollLeft <= 2;
const month = condition ? startMonth : endMonth;
/**
* The edge of the month must be lined up with
* the edge of the calendar body in order for
* the component to update. Otherwise, it
* may be the case that the user has paused their
* swipe or the browser has not finished snapping yet.
* Rather than check if the x values are equal,
* we give it a tolerance of 2px to account for
* sub pixel rendering.
*/
const monthBox = month.getBoundingClientRect();
if (Math.abs(monthBox.x - box.x) > 2) return;
/**
* If we're force-rendering a month, assume we've
* scrolled to that and return it.
*
* If forceRenderDate is ever used in a context where the
* forced month is not immediately auto-scrolled to, this
* should be updated to also check whether `month` has the
* same month and year as the forced date.
*/
const { forceRenderDate } = this;
if (forceRenderDate !== undefined) {
return { month: forceRenderDate.month, year: forceRenderDate.year, day: forceRenderDate.day };
}
/**
* From here, we can determine if the start
* month or the end month was scrolled into view.
* If no month was changed, then we can return from
* the scroll callback early.
*/
if (month === startMonth) {
return getPreviousMonth(parts);
} else if (month === endMonth) {
return getNextMonth(parts);
} else {
return;
}
};
const updateActiveMonth = () => {
if (needsiOSRubberBandFix) {
calendarBodyRef.style.removeProperty('pointer-events');
appliediOSRubberBandFix = false;
}
/**
* If the month did not change
* then we can return early.
*/
const newDate = getChangedMonth(this.workingParts);
if (!newDate) return;
const { month, day, year } = newDate;
if (
isMonthDisabled(
{ month, year, day: null },
{
minParts: { ...this.minParts, day: null },
maxParts: { ...this.maxParts, day: null },
}
)
) {
return;
}
/**
* Prevent scrolling for other browsers
* to give the DOM time to update and the container
* time to properly snap.
*/
calendarBodyRef.style.setProperty('overflow', 'hidden');
/**
* Use a writeTask here to ensure
* that the state is updated and the
* correct month is scrolled into view
* in the same frame. This is not
* typically a problem on newer devices
* but older/slower device may have a flicker
* if we did not do this.
*/
writeTask(() => {
this.setWorkingParts({
...this.workingParts,
month,
day: day!,
year,
});
calendarBodyRef.scrollLeft = workingMonth.clientWidth * (isRTL(this.el) ? -1 : 1);
calendarBodyRef.style.removeProperty('overflow');