-
Notifications
You must be signed in to change notification settings - Fork 13.5k
/
datetime.tsx
2209 lines (1952 loc) · 68.4 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 { caretDownSharp, caretUpSharp, chevronBack, chevronDown, chevronForward } from 'ionicons/icons';
import { getIonMode } from '../../global/ionic-global';
import type {
Color,
DatetimePresentation,
DatetimeChangeEventDetail,
DatetimeParts,
Mode,
StyleEventDetail,
} from '../../interface';
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 type { PickerColumnItem } from '../picker-column-internal/picker-column-internal-interfaces';
import { isSameDay, warnIfValueOutOfBounds } from './utils/comparison';
import {
generateMonths,
getDaysOfMonth,
getDaysOfWeek,
getToday,
getMonthColumnData,
getDayColumnData,
getYearColumnData,
getTimeColumnsData,
getCombinedDateColumnData,
} from './utils/data';
import { formatValue, getLocalizedTime, getMonthAndDay, getMonthAndYear } from './utils/format';
import { is24Hour, isLocaleDayPeriodRTL, isMonthFirstLocale } from './utils/helpers';
import {
calculateHourFromAMPM,
convertDataToISO,
getEndOfWeek,
getNextDay,
getNextMonth,
getNextWeek,
getNextYear,
getPreviousDay,
getPreviousMonth,
getPreviousWeek,
getPreviousYear,
getStartOfWeek,
} from './utils/manipulation';
import { clampDate, convertToArrayOfNumbers, getPartsFromCalendarDay, parseAmPm, parseDate } from './utils/parse';
import {
getCalendarDayState,
isDayDisabled,
isMonthDisabled,
isNextMonthDisabled,
isPrevMonthDisabled,
} from './utils/state';
/**
* @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.
*/
@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 clearFocusVisible?: () => void;
/**
* Whether to highlight the active day with a solid circle (as opposed
* to the outline circle around today). If you don't specify an initial
* value for the datetime, it doesn't automatically init to a default to
* avoid unwanted change events firing. If the solid circle were still
* shown then, it would look like a date had already been selected, which
* is misleading UX.
*/
private highlightActiveParts = false;
private parsedMinuteValues?: number[];
private parsedHourValues?: number[];
private parsedMonthValues?: number[];
private parsedYearValues?: number[];
private parsedDayValues?: number[];
private destroyCalendarListener?: () => void;
private destroyKeyboardMO?: () => void;
private minParts?: any;
private maxParts?: any;
private todayParts = parseDate(getToday());
private prevPresentation: string | null = null;
/**
* Duplicate reference to `activeParts` that does not trigger a re-render of the component.
* Allows caching an instance of the `activeParts` in between render cycles.
*/
private activePartsClone!: DatetimeParts | DatetimeParts[];
@State() showMonthAndYear = false;
@State() activeParts: DatetimeParts | DatetimeParts[] = {
month: 5,
day: 28,
year: 2021,
hour: 13,
minute: 52,
ampm: 'pm',
};
@State() workingParts: DatetimeParts = {
month: 5,
day: 28,
year: 2021,
hour: 13,
minute: 52,
ampm: 'pm',
};
@Element() el!: HTMLIonDatetimeElement;
@State() isPresented = false;
@State() isTimePopoverOpen = false;
/**
* 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;
/**
* If `true`, the datetime appears normal but is not interactive.
*/
@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';
/**
* 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="2024,2020,2016,2012,2008"`.
*/
@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);
}
@Watch('activeParts')
protected activePartsChanged() {
this.activePartsClone = this.activeParts;
}
/**
* 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;
/**
* If `true`, multiple dates can be selected at once. Only
* applies to `presentation="date"` and `preferWheel="false"`.
*/
@Prop() multiple = false;
/**
* The value of the datetime as a valid ISO 8601 datetime string.
* Should be an array of strings if `multiple="true"`.
*/
@Prop({ mutable: true }) value?: string | string[] | null;
/**
* Update the datetime value when the value changes
*/
@Watch('value')
protected valueChanged() {
const { value, minParts, maxParts, workingParts, multiple } = this;
if (this.hasValue()) {
if (!multiple && Array.isArray(value)) {
this.value = value[0];
return; // setting this.value will trigger re-run of this function
}
/**
* Clones the value of the `activeParts` to the private clone, to update
* the date display on the current render cycle without causing another render.
*
* This allows us to update the current value's date/time display without
* refocusing or shifting the user's display (leaves the user in place).
*/
const valueDateParts = parseDate(value);
if (valueDateParts) {
warnIfValueOutOfBounds(valueDateParts, minParts, maxParts);
if (Array.isArray(valueDateParts)) {
this.activePartsClone = [...valueDateParts];
} else {
const { month, day, year, hour, minute } = valueDateParts;
const ampm = hour != null ? (hour >= 12 ? 'pm' : 'am') : undefined;
this.activePartsClone = {
...this.activeParts,
month,
day,
year,
hour,
minute,
ampm,
};
/**
* The working parts am/pm value must be updated when the value changes, to
* ensure the time picker hour column values are generated correctly.
*
* Note that we don't need to do this if valueDateParts is an array, since
* multiple="true" does not apply to time pickers.
*/
this.setWorkingParts({
...workingParts,
ampm,
});
}
} else {
printIonWarning(`Unable to parse date string: ${value}. Please provide a valid ISO 8601 datetime string.`);
}
}
this.emitStyle();
this.ionChange.emit({ value });
}
/**
* If `true`, a header will be shown above the calendar
* picker. On `ios` mode this will include the
* slotted title, and on `md` mode this will include
* 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?: 'h23' | 'h12';
/**
* 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.
*/
@Event() ionChange!: 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 { highlightActiveParts, isCalendarPicker, activeParts } = this;
/**
* We only update the value if the presentation is not a calendar picker,
* or if `highlightActiveParts` is true; indicating that the user
* has selected a date from the calendar picker.
*
* Otherwise "today" would accidentally be set as the value.
*/
if (highlightActiveParts || !isCalendarPicker) {
const activePartsIsArray = Array.isArray(activeParts);
if (activePartsIsArray && activeParts.length === 0) {
this.value = undefined;
} else {
/**
* Prevent convertDataToISO from doing any
* kind of transformation based on timezone
* This cancels out any change it attempts to make
*
* Important: Take the timezone offset based on
* the date that is currently selected, otherwise
* there can be 1 hr difference when dealing w/ DST
*/
if (activePartsIsArray) {
const dates = convertDataToISO(activeParts).map((str) => new Date(str));
for (let i = 0; i < dates.length; i++) {
activeParts[i].tzOffset = dates[i].getTimezoneOffset() * -1;
}
} else {
const date = new Date(convertDataToISO(activeParts));
activeParts.tzOffset = date.getTimezoneOffset() * -1;
}
this.value = convertDataToISO(activeParts);
}
}
if (closeOverlay) {
this.closeParentOverlay();
}
}
/**
* 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();
}
}
private closeParentOverlay = () => {
const popoverOrModal = this.el.closest('ion-modal, ion-popover') as
| HTMLIonModalElement
| HTMLIonPopoverElement
| null;
if (popoverOrModal) {
popoverOrModal.dismiss();
}
};
private setWorkingParts = (parts: DatetimeParts) => {
this.workingParts = {
...parts,
};
};
private setActiveParts = (parts: DatetimeParts, removeDate = false) => {
const { multiple, activePartsClone, highlightActiveParts } = this;
if (multiple) {
/**
* We read from activePartsClone here because valueChanged() only updates that,
* so it's the more reliable source of truth. If we read from activeParts, then
* if you click July 1, manually set the value to July 2, and then click July 3,
* the new value would be [July 1, July 3], ignoring the value set.
*
* We can then pass the new value to activeParts (rather than activePartsClone)
* since the clone will be updated automatically by activePartsChanged().
*/
const activePartsArray = Array.isArray(activePartsClone) ? activePartsClone : [activePartsClone];
if (removeDate) {
this.activeParts = activePartsArray.filter((p) => !isSameDay(p, parts));
} else if (highlightActiveParts) {
this.activeParts = [...activePartsArray, parts];
} else {
/**
* If highlightActiveParts is false, that means we just have a
* default value of today in activeParts; we need to replace that
* rather than adding to it since it's just a placeholder.
*/
this.activeParts = [parts];
}
} else {
this.activeParts = {
...parts,
};
}
/**
* Now that the user has interacted somehow to select something, we can
* show the solid highlight. This needs to be done after checking it above,
* but before the confirm call below.
*
* Note that for datetimes with confirm/cancel buttons, the value
* isn't updated until you call confirm(). We need to bring the
* solid circle back on day click for UX reasons, rather than only
* show the circle if `value` is truthy.
*/
this.highlightActiveParts = true;
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';
}
/**
* Stencil sometimes sets calendarBodyRef to null on rerender, even though
* the element is present. Query for it manually as a fallback.
*
* TODO(FW-901) Remove when issue is resolved: https://github.com/ionic-team/stencil/issues/3253
*/
private getCalendarBodyEl = () => {
return this.calendarBodyRef || this.el.shadowRoot?.querySelector('.calendar-body');
};
private initializeKeyboardListeners = () => {
const calendarBodyRef = this.getCalendarBodyEl();
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 calenday-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:nth-of-type(${padding.length + day})`
) as HTMLElement | null;
if (dayEl) {
dayEl.focus();
}
};
private processMinParts = () => {
if (this.min === undefined) {
this.minParts = undefined;
return;
}
const { month, day, year, hour, minute } = parseDate(this.min);
this.minParts = {
month,
day,
year,
hour,
minute,
};
};
private processMaxParts = () => {
if (this.max === undefined) {
this.maxParts = undefined;
return;
}
const { month, day, year, hour, minute } = parseDate(this.max);
this.maxParts = {
month,
day,
year,
hour,
minute,
};
};
private initializeCalendarListener = () => {
const calendarBodyRef = this.getCalendarBodyEl();
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();
const root = this.el!.shadowRoot!;
/**
* Get the element that is in the center of the calendar body.
* This will be an element inside of the active month.
*/
const elementAtCenter = root.elementFromPoint(box.x + box.width / 2, box.y + box.height / 2);
/**
* If there is no element then the
* component may be re-rendering on a slow device.
*/
if (!elementAtCenter) return;
const month = elementAtCenter.closest('.calendar-month');
if (!month) return;
/**
* 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;
/**
* 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');
});
};
/**
* When the container finishes scrolling we
* need to update the DOM with the selected month.
*/
let scrollTimeout: ReturnType<typeof setTimeout> | undefined;
/**
* We do not want to attempt to set pointer-events
* multiple times within a single swipe gesture as
* that adds unnecessary work to the main thread.
*/
let appliediOSRubberBandFix = false;
const scrollCallback = () => {
if (scrollTimeout) {
clearTimeout(scrollTimeout);
}
/**
* On iOS it is possible to quickly rubber band
* the scroll area before the scroll timeout has fired.
* This results in users reaching the end of the scrollable
* container before the DOM has updated.
* By setting `pointer-events: none` we can ensure that
* subsequent swipes do not happen while the container
* is snapping.
*/
if (!appliediOSRubberBandFix && needsiOSRubberBandFix) {
calendarBodyRef.style.setProperty('pointer-events', 'none');
appliediOSRubberBandFix = true;
}
// Wait ~3 frames
scrollTimeout = setTimeout(updateActiveMonth, 50);
};
calendarBodyRef.addEventListener('scroll', scrollCallback);
this.destroyCalendarListener = () => {
calendarBodyRef.removeEventListener('scroll', scrollCallback);
};
});