-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathdate-range-picker.ts
More file actions
1216 lines (1046 loc) · 38.5 KB
/
date-range-picker.ts
File metadata and controls
1216 lines (1046 loc) · 38.5 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
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 { LitElement, type TemplateResult, html, nothing } from 'lit';
import {
property,
query,
queryAll,
queryAssignedElements,
state,
} from 'lit/decorators.js';
import { ifDefined } from 'lit/directives/if-defined.js';
import { live } from 'lit/directives/live.js';
import { getThemeController, themes } from '../../theming/theming-decorator.js';
import IgcCalendarComponent, { focusActiveDate } from '../calendar/calendar.js';
import { convertToDate, convertToDateRange } from '../calendar/helpers.js';
import { CalendarDay } from '../calendar/model.js';
import {
type DateRangeDescriptor,
DateRangeType,
type WeekDays,
} from '../calendar/types.js';
import {
addKeybindings,
altKey,
arrowDown,
arrowUp,
escapeKey,
} from '../common/controllers/key-bindings.js';
import { blazorAdditionalDependencies } from '../common/decorators/blazorAdditionalDependencies.js';
import { watch } from '../common/decorators/watch.js';
import { registerComponent } from '../common/definitions/register.js';
import { IgcDateRangePickerResourceStringsEN } from '../common/i18n/date-range-picker.resources.js';
import { IgcBaseComboBoxLikeComponent } from '../common/mixins/combo-box.js';
import type { AbstractConstructor } from '../common/mixins/constructor.js';
import { EventEmitterMixin } from '../common/mixins/event-emitter.js';
import { FormAssociatedRequiredMixin } from '../common/mixins/forms/associated-required.js';
import {
type FormValueOf,
createFormValueState,
defaultDateRangeTransformers,
} from '../common/mixins/forms/form-value.js';
import {
asNumber,
clamp,
createCounter,
equal,
findElementFromEventPath,
isEmpty,
} from '../common/util.js';
import IgcDateTimeInputComponent from '../date-time-input/date-time-input.js';
import { DateTimeUtil } from '../date-time-input/date-util.js';
import IgcDialogComponent from '../dialog/dialog.js';
import IgcFocusTrapComponent from '../focus-trap/focus-trap.js';
import IgcIconComponent from '../icon/icon.js';
import IgcInputComponent from '../input/input.js';
import IgcPopoverComponent from '../popover/popover.js';
import type { ContentOrientation, PickerMode } from '../types.js';
import IgcValidationContainerComponent from '../validation-container/validation-container.js';
import { styles } from './date-range-picker.base.css.js';
import IgcPredefinedRangesAreaComponent from './predefined-ranges-area.js';
import { styles as shared } from './themes/shared/date-range-picker.common.css.js';
import { all } from './themes/themes.js';
import { dateRangeValidators, isCompleteDateRange } from './validators.js';
export interface DateRangeValue {
start: Date | null;
end: Date | null;
}
export interface CustomDateRange {
label: string;
dateRange: DateRangeValue;
}
export interface IgcDateRangePickerComponentEventMap {
igcOpening: CustomEvent<void>;
igcOpened: CustomEvent<void>;
igcClosing: CustomEvent<void>;
igcClosed: CustomEvent<void>;
igcChange: CustomEvent<DateRangeValue | null>;
igcInput: CustomEvent<DateRangeValue | null>;
}
/* blazorIndirectRender */
/* blazorSupportsVisualChildren */
/**
* The igc-date-range-picker allows the user to select a range of dates.
*
* @element igc-date-range-picker
*
* @slot prefix - Renders content before the input (single input).
* @slot prefix-start - Renders content before the start input (two inputs).
* @slot prefix-end - Renders content before the end input (two inputs).
* @slot suffix - Renders content after the input (single input).
* @slot suffix-start - Renders content after the start input (single input).
* @slot suffix-end - Renders content after the end input (single input).
* @slot helper-text - Renders content below the input.
* @slot bad-input - Renders content when the value is in the disabledDates ranges.
* @slot value-missing - Renders content when the required validation fails.
* @slot range-overflow - Renders content when the max validation fails.
* @slot range-underflow - Renders content when the min validation fails.
* @slot custom-error - Renders content when setCustomValidity(message) is set.
* @slot invalid - Renders content when the component is in invalid state (validity.valid = false).
* @slot title - Renders content in the calendar title.
* @slot header-date - Renders content instead of the current date/range in the calendar header.
* @slot clear-icon - Renders a clear icon template.
* @slot clear-icon-start - Renders a clear icon template for the start input (two inputs).
* @slot clear-icon-end - Renders a clear icon template for the end input (two inputs).
* @slot calendar-icon - Renders the icon/content for the calendar picker.
* @slot calendar-icon-start - Renders the icon/content for the calendar picker for the start input (two inputs).
* @slot calendar-icon-end - Renders the icon/content for the calendar picker for the end input (two inputs).
* @slot calendar-icon-open - Renders the icon/content for the picker in open state.
* @slot calendar-icon-open-start - Renders the icon/content for the picker in open state for the start input (two inputs).
* @slot calendar-icon-open-end - Renders the icon/content for the picker in open state for the end input (two inputs).
* @slot actions - Renders content in the action part of the picker in open state.
* @slot separator - Renders the separator element between the two inputs.
*
* @fires igcOpening - Emitted just before the calendar dropdown is shown.
* @fires igcOpened - Emitted after the calendar dropdown is shown.
* @fires igcClosing - Emitted just before the calendar dropdown is hidden.
* @fires igcClosed - Emitted after the calendar dropdown is hidden.
* @fires igcChange - Emitted when the user modifies and commits the elements's value.
* @fires igcInput - Emitted when when the user types in the element.
*
* @csspart separator - The separator element between the two inputs.
* @csspart ranges - The wrapper that renders the custom and predefined ranges.
* @csspart label - The label wrapper that renders content above the target input.
* @csspart calendar-icon - The calendar icon wrapper for closed state (single input).
* @csspart calendar-icon-start - The calendar icon wrapper for closed state for the start input (two inputs).
* @csspart calendar-icon-end - The calendar icon wrapper for closed state for the end input (two inputs).
* @csspart calendar-icon-open - The calendar icon wrapper for opened state (single input).
* @csspart calendar-icon-open-start - The calendar icon wrapper for opened state for the start input (two inputs).
* @csspart calendar-icon-open-end - The calendar icon wrapper for opened state for the end input (two inputs).
* @csspart clear-icon - The clear icon wrapper (single input).
* @csspart clear-icon-start - The clear icon wrapper for the start input (two inputs).
* @csspart clear-icon-end - The clear icon wrapper for the end input (two inputs).
* @csspart actions - The wrapper for the custom actions area.
* @csspart clear-icon - The clear icon wrapper.
* @csspart input - The native input element.
* @csspart prefix - The prefix wrapper.
* @csspart suffix - The suffix wrapper.
* @csspart helper-text - The helper-text wrapper that renders content below the target input.
* @csspart header - The calendar header element.
* @csspart header-title - The calendar header title element.
* @csspart header-date - The calendar header date element.
* @csspart calendar-content - The calendar content element which contains the views and navigation elements.
* @csspart navigation - The calendar navigation container element.
* @csspart months-navigation - The calendar months navigation button element.
* @csspart years-navigation - The calendar years navigation button element.
* @csspart years-range - The calendar years range element.
* @csspart navigation-buttons - The calendar navigation buttons container.
* @csspart navigation-button - The calendar previous/next navigation button.
* @csspart days-view-container - The calendar days view container element.
* @csspart days-view - The calendar days view element.
* @csspart months-view - The calendar months view element.
* @csspart years-view - The calendar years view element.
* @csspart days-row - The calendar days row element.
* @csspart calendar-label - The calendar week header label element.
* @csspart week-number - The calendar week number element.
* @csspart week-number-inner - The calendar week number inner element.
* @csspart date - The calendar date element.
* @csspart date-inner - The calendar date inner element.
* @csspart first - The calendar first selected date element in range selection.
* @csspart last - The calendar last selected date element in range selection.
* @csspart inactive - The calendar inactive date element.
* @csspart hidden - The calendar hidden date element.
* @csspart weekend - The calendar weekend date element.
* @csspart range - The calendar range selected element.
* @csspart special - The calendar special date element.
* @csspart disabled - The calendar disabled date element.
* @csspart single - The calendar single selected date element.
* @csspart preview - The calendar range selection preview date element.
* @csspart month - The calendar month element.
* @csspart month-inner - The calendar month inner element.
* @csspart year - The calendar year element.
* @csspart year-inner - The calendar year inner element.
* @csspart selected - The calendar selected state for element(s). Applies to date, month and year elements.
* @csspart current - The calendar current state for element(s). Applies to date, month and year elements.
*/
@themes(all, { exposeController: true })
@blazorAdditionalDependencies(
'IgcCalendarComponent, IgcDateTimeInputComponent, IgcDialogComponent, IgcIconComponent, IgcChipComponent, IgcInputComponent'
)
export default class IgcDateRangePickerComponent extends FormAssociatedRequiredMixin(
EventEmitterMixin<
IgcDateRangePickerComponentEventMap,
AbstractConstructor<IgcBaseComboBoxLikeComponent>
>(IgcBaseComboBoxLikeComponent)
) {
public static readonly tagName = 'igc-date-range-picker';
public static styles = [styles, shared];
protected static shadowRootOptions = {
...LitElement.shadowRootOptions,
delegatesFocus: true,
};
/* blazorSuppress */
public static register(): void {
registerComponent(
IgcDateRangePickerComponent,
IgcCalendarComponent,
IgcDateTimeInputComponent,
IgcInputComponent,
IgcFocusTrapComponent,
IgcIconComponent,
IgcPopoverComponent,
IgcDialogComponent,
IgcValidationContainerComponent,
IgcPredefinedRangesAreaComponent
);
}
// #region Internal state & properties
private static readonly _increment = createCounter();
protected readonly _inputId = `date-range-picker-${IgcDateRangePickerComponent._increment()}`;
protected override readonly _formValue: FormValueOf<DateRangeValue | null> =
createFormValueState(this, {
initialValue: {
start: null,
end: null,
},
transformers: defaultDateRangeTransformers,
});
private _activeDate: Date | null = null;
private _min: Date | null = null;
private _max: Date | null = null;
private _disabledDates: DateRangeDescriptor[] = [];
private _dateConstraints: DateRangeDescriptor[] = [];
private _displayFormat?: string;
private _inputFormat?: string;
private _placeholder?: string;
private _defaultMask!: string;
private _oldValue: DateRangeValue | null = null;
private _visibleMonths = 2;
protected override get __validators() {
return dateRangeValidators;
}
private get _isDropDown(): boolean {
return this.mode === 'dropdown';
}
private get _firstDefinedInRange(): Date | null {
return this.value?.start ?? this.value?.end ?? null;
}
@state()
private _maskedRangeValue = '';
@queryAll(IgcDateTimeInputComponent.tagName)
private readonly _inputs!: IgcDateTimeInputComponent[];
@query(IgcInputComponent.tagName)
private readonly _input!: IgcInputComponent;
@query(IgcCalendarComponent.tagName)
private readonly _calendar!: IgcCalendarComponent;
@queryAssignedElements({ slot: 'prefix' })
private readonly _prefixes!: HTMLElement[];
@queryAssignedElements({ slot: 'prefix-start' })
private readonly _startPrefixes!: HTMLElement[];
@queryAssignedElements({ slot: 'prefix-end' })
private readonly _endPrefixes!: HTMLElement[];
@queryAssignedElements({ slot: 'suffix' })
private readonly _suffixes!: HTMLElement[];
@queryAssignedElements({ slot: 'suffix-start' })
private readonly _startSuffixes!: HTMLElement[];
@queryAssignedElements({ slot: 'suffix-end' })
private readonly _endSuffixes!: HTMLElement[];
@queryAssignedElements({ slot: 'actions' })
private readonly _actions!: HTMLElement[];
@queryAssignedElements({ slot: 'header-date' })
private readonly _headerDateSlotItems!: HTMLElement[];
protected get _isIndigoTheme(): boolean {
return getThemeController(this)?.theme === 'indigo';
}
// #endregion
// #region General properties
@property({ converter: convertToDateRange })
public set value(value: DateRangeValue | string | null | undefined) {
const converted = convertToDateRange(value);
this._formValue.setValueAndFormState(converted);
this._validate();
this._setCalendarRangeValues();
this._updateMaskedRangeValue();
}
public get value(): DateRangeValue | null {
return this._formValue.value;
}
/**
* Renders chips with custom ranges based on the elements of the array.
*/
@property({ attribute: false })
public customRanges: CustomDateRange[] = [];
/**
* Determines whether the calendar is opened in a dropdown or a modal dialog
* @attr mode
*/
@property()
public mode: PickerMode = 'dropdown';
/**
* Use two inputs to display the date range values. Makes the input editable in dropdown mode.
* @attr use-two-inputs
*/
@property({ type: Boolean, reflect: true, attribute: 'use-two-inputs' })
public useTwoInputs = false;
/**
* Whether the control will show chips with predefined ranges.
* @attr
*/
@property({
type: Boolean,
reflect: true,
attribute: 'use-predefined-ranges',
})
public usePredefinedRanges = false;
/**
* The locale settings used to display the value.
* @attr
*/
@property()
public locale = 'en';
/** The resource strings of the date range picker. */
@property({ attribute: false })
public resourceStrings = IgcDateRangePickerResourceStringsEN;
// #endregion
// #region Input-related properties
/**
* Makes the control a readonly field.
* @attr readonly
*/
@property({ type: Boolean, reflect: true, attribute: 'readonly' })
public readOnly = false;
/**
* Whether to allow typing in the input.
* @attr non-editable
*/
@property({ type: Boolean, reflect: true, attribute: 'non-editable' })
public nonEditable = false;
/**
* Whether the control will have outlined appearance.
* @attr
*/
@property({ type: Boolean, reflect: true })
public outlined = false;
/**
* The label of the control (single input).
* @attr label
*/
@property()
public label!: string;
/**
* The label attribute of the start input.
* @attr label-start
*/
@property({ attribute: 'label-start' })
public labelStart = '';
/**
* The label attribute of the end input.
* @attr label-end
*/
@property({ attribute: 'label-end' })
public labelEnd = '';
/**
* The placeholder attribute of the control (single input).
* @attr
*/
@property()
public set placeholder(value: string) {
this._placeholder = value;
}
public get placeholder(): string {
const rangePlaceholder = `${this.inputFormat} - ${this.inputFormat}`;
return this._placeholder ?? rangePlaceholder;
}
/**
* The placeholder attribute of the start input.
* @attr placeholder-start
*/
@property({ attribute: 'placeholder-start' })
public placeholderStart = '';
/**
* The placeholder attribute of the end input.
* @attr placeholder-end
*/
@property({ attribute: 'placeholder-end' })
public placeholderEnd = '';
/** The prompt symbol to use for unfilled parts of the mask.
* @attr
*/
@property()
public prompt = '_';
/**
* Format to display the value in when not editing.
* Defaults to the input format if not set.
* @attr display-format
*/
@property({ attribute: 'display-format' })
public set displayFormat(value: string) {
this._displayFormat = value;
this._updateMaskedRangeValue();
}
public get displayFormat(): string {
return this._displayFormat ?? this.inputFormat;
}
/**
* The date format to apply on the inputs.
* Defaults to the current locale Intl.DateTimeFormat
* @attr input-format
*/
@property({ attribute: 'input-format' })
public set inputFormat(value: string) {
this._inputFormat = value;
this._updateMaskedRangeValue();
}
public get inputFormat(): string {
return this._inputFormat ?? this._defaultMask;
}
// #endregion
// #region Validation properties
/**
* The minimum value required for the date range picker to remain valid.
* @attr
*/
@property({ converter: convertToDate })
public set min(value: Date | string | null | undefined) {
this._min = convertToDate(value);
this._setDateConstraints();
this._updateValidity();
}
public get min(): Date | null {
return this._min;
}
/**
* The maximum value required for the date range picker to remain valid.
* @attr
*/
@property({ converter: convertToDate })
public set max(value: Date | string | null | undefined) {
this._max = convertToDate(value);
this._setDateConstraints();
this._updateValidity();
}
public get max(): Date | null {
return this._max;
}
/** Gets/sets disabled dates. */
@property({ attribute: false })
public set disabledDates(dates: DateRangeDescriptor[]) {
this._disabledDates = dates;
this._setDateConstraints();
this._updateValidity();
}
public get disabledDates() {
return this._disabledDates as DateRangeDescriptor[];
}
// #endregion
// #region Calendar properties
/**
* The number of months displayed in the calendar.
* @attr visible-months
*/
@property({ type: Number, attribute: 'visible-months' })
public get visibleMonths(): number {
return this._visibleMonths;
}
public set visibleMonths(value: number) {
this._visibleMonths = clamp(asNumber(value, 2), 1, 2);
}
/**
* The orientation of the calendar header.
* @attr header-orientation
*/
@property({ attribute: 'header-orientation', reflect: true })
public headerOrientation: ContentOrientation = 'horizontal';
/**
* The orientation of the multiple months displayed in the calendar's days view.
* @attr
*/
@property()
public orientation: ContentOrientation = 'horizontal';
/**
* Determines whether the calendar hides its header.
* @attr hide-header
*/
@property({ type: Boolean, reflect: true, attribute: 'hide-header' })
public hideHeader = false;
/**
* Gets/Sets the date which is shown in the calendar picker and is highlighted.
* By default it is the current date.
*/
@property({ attribute: 'active-date', converter: convertToDate })
public set activeDate(value: Date | string | null | undefined) {
this._activeDate = convertToDate(value);
}
public get activeDate(): Date {
return this._activeDate ?? this._calendar?.activeDate;
}
/**
* Whether to show the number of the week in the calendar.
* @attr show-week-numbers
*/
@property({ type: Boolean, reflect: true, attribute: 'show-week-numbers' })
public showWeekNumbers = false;
/**
* Controls the visibility of the dates that do not belong to the current month.
* @attr hide-outside-days
*/
@property({ type: Boolean, reflect: true, attribute: 'hide-outside-days' })
public hideOutsideDays = false;
/** Gets/sets special dates. */
@property({ attribute: false })
public specialDates!: DateRangeDescriptor[];
/** Sets the start day of the week for the calendar. */
@property({ attribute: 'week-start' })
public weekStart: WeekDays = 'sunday';
// #endregion
// #region Life-cycle hooks
constructor() {
super();
this._rootClickController.update({ hideCallback: this._handleClosing });
this.addEventListener('focusin', this._handleFocusIn);
this.addEventListener('focusout', this._handleFocusOut);
addKeybindings(this, {
skip: () => this.disabled || this.readOnly,
bindingDefaults: { preventDefault: true },
})
.set([altKey, arrowDown], this.handleAnchorClick)
.set([altKey, arrowUp], this._onEscapeKey)
.set(escapeKey, this._onEscapeKey);
}
protected override createRenderRoot(): HTMLElement | DocumentFragment {
const root = super.createRenderRoot();
root.addEventListener('slotchange', () => this.requestUpdate());
return root;
}
protected override firstUpdated() {
this._setCalendarRangeValues();
this._delegateInputsValidity();
}
protected override formResetCallback() {
super.formResetCallback();
this._setCalendarRangeValues();
this._updateMaskedRangeValue();
}
// #endregion
// #region Public API methods
/** Clears the input parts of the component of any user input */
public clear() {
this._oldValue = this.value;
this.value = null;
if (this.useTwoInputs) {
this._inputs[0]?.clear();
this._inputs[1]?.clear();
}
}
/** Selects a date range value in the picker */
public select(value: DateRangeValue | null): void {
this._select(value);
}
// #endregion
// #region Observed properties
@watch('open')
protected _openChange() {
this._rootClickController.update();
if (this.open) {
this._oldValue = this.value;
}
}
@watch('locale')
protected _updateDefaultMask(): void {
this._defaultMask = DateTimeUtil.getDefaultMask(this.locale);
this._updateMaskedRangeValue();
}
@watch('useTwoInputs')
protected async _updateDateRange() {
await this._calendar?.updateComplete;
this._updateMaskedRangeValue();
this._setCalendarRangeValues();
this._delegateInputsValidity();
}
@watch('mode')
protected async _modeChanged() {
if (!this._isDropDown) {
this.keepOpenOnSelect = true;
}
await this._calendar?.updateComplete;
this._setCalendarRangeValues();
}
// #endregion
// #region Event handlers
protected _handleClosing() {
this._hide(true);
}
protected _handleDialogClosing(event: Event) {
event.stopPropagation();
if (!equal(this.value, this._oldValue)) {
this.emitEvent('igcChange', { detail: this.value });
this._oldValue = this.value;
}
this._hide(true);
}
protected _handleDialogClosed(event: Event) {
event.stopPropagation();
}
protected _dialogCancel() {
this._revertValue();
this._hide(true);
}
protected _dialogDone() {
if (!equal(this.value, this._oldValue)) {
this.emitEvent('igcChange', { detail: this.value });
this._oldValue = this.value;
}
this._hide(true);
}
protected _handleInputEvent(event: CustomEvent<Date | null>) {
event.stopPropagation();
if (this.nonEditable) {
event.preventDefault();
return;
}
const input = event.target as IgcDateTimeInputComponent;
const newValue = input.value ? CalendarDay.from(input.value).native : null;
this.value = this._getUpdatedDateRange(input, newValue);
this._calendar.activeDate =
newValue ?? this._firstDefinedInRange ?? this._calendar.activeDate;
this.emitEvent('igcInput', { detail: this.value });
}
protected _handleInputChangeEvent(event: CustomEvent<Date | null>) {
event.stopPropagation();
const input = event.target as IgcDateTimeInputComponent;
const newValue = input.value ? CalendarDay.from(input.value).native : null;
const updatedRange = this._getUpdatedDateRange(input, newValue);
const { start, end } = this._swapDates(updatedRange);
this._setCalendarRangeValues();
this.value = { start, end };
this.emitEvent('igcChange', { detail: this.value });
}
protected _handleFocusIn() {
this._dirty = true;
}
protected _handleFocusOut({ relatedTarget }: FocusEvent) {
if (!this.contains(relatedTarget as Node)) {
this.checkValidity();
const isSameValue = equal(this.value, this._oldValue);
if (!(this.useTwoInputs || this.readOnly || isSameValue)) {
this.emitEvent('igcChange', { detail: this.value });
this._oldValue = this.value;
}
}
}
protected _handleInputClick(event: Event) {
if (findElementFromEventPath('input', event)) {
// Open only if the click originates from the underlying input
this.handleAnchorClick();
}
}
protected async _onEscapeKey() {
if (await this._hide(true)) {
if (!this._isDropDown) {
this._revertValue();
}
this._inputs[0]?.focus();
}
}
protected override async handleAnchorClick() {
super.handleAnchorClick();
this._setCalendarActiveDateAndViewIndex();
await this.updateComplete;
this._calendar[focusActiveDate]({ preventScroll: true });
}
protected async _handleCalendarChangeEvent(event: CustomEvent<Date>) {
event.stopPropagation();
if (this.readOnly) {
// Wait till the calendar finishes updating and then restore the current value from the date-picker.
await this._calendar.updateComplete;
const dateRange = [this.value?.start, this.value?.end];
this._calendar.values = dateRange?.map((d) => d ?? '');
return;
}
const rangeValues = (event.target as IgcCalendarComponent).values;
this.value = {
start: rangeValues[0],
end: rangeValues[rangeValues.length - 1],
};
if (this._isDropDown) {
this.emitEvent('igcChange', { detail: this.value });
}
this._shouldCloseCalendarDropdown();
}
protected _handleCalendarIconSlotPointerDown(event: PointerEvent) {
event.preventDefault();
}
// #endregion
// #region Private methods
protected _revertValue() {
this.value = this._oldValue;
}
/**
* Sets the active date of the calendar based on current selection, if any,
* or its current active date and its active day view index to always be the first one.
*/
private _setCalendarActiveDateAndViewIndex() {
const activeDaysViewIndex = 'activeDaysViewIndex';
this._calendar.activeDate =
this._firstDefinedInRange ?? this._calendar.activeDate;
this._calendar[activeDaysViewIndex] = 0;
}
private _getUpdatedDateRange(
input: IgcDateTimeInputComponent,
newValue: Date | null
): DateRangeValue {
const { start = null, end = null } = this.value ?? {};
return input === this._inputs[0]
? { start: newValue, end }
: { start, end: newValue };
}
// Delegates the validity methods of internal input elements
// to the component's own validation logic specific to date-range values.
// Checks for dirty state to avoid unnecessary validation on form reset,
// caused by the inputs value being set.
private _delegateInputsValidity() {
const inputs = this.useTwoInputs ? this._inputs : [this._input];
inputs.forEach((input) => {
input.checkValidity = () =>
this._dirty || !this._pristine ? this.checkValidity() : true;
input.reportValidity = () =>
this._dirty || !this._pristine ? this.reportValidity() : true;
});
}
private _setDateConstraints() {
const dates: DateRangeDescriptor[] = [];
if (this._min) {
dates.push({
type: DateRangeType.Before,
dateRange: [this._min],
});
}
if (this._max) {
dates.push({
type: DateRangeType.After,
dateRange: [this._max],
});
}
if (!isEmpty(this.disabledDates)) {
dates.push(...this.disabledDates);
}
this._dateConstraints = isEmpty(dates) ? [] : dates;
}
private _updateMaskedRangeValue() {
if (this.useTwoInputs) {
return;
}
if (!isCompleteDateRange(this.value)) {
this._maskedRangeValue = '';
return;
}
const { formatDate, predefinedToDateDisplayFormat } = DateTimeUtil;
const { start, end } = this.value;
const format =
predefinedToDateDisplayFormat(this._displayFormat) ??
this._displayFormat ??
this.inputFormat;
this._maskedRangeValue = format
? `${formatDate(start, this.locale, format)} - ${formatDate(end, this.locale, format)}`
: `${start.toLocaleDateString()} - ${end.toLocaleDateString()}`;
}
private _setCalendarRangeValues() {
if (!this._calendar) {
return;
}
if (isCompleteDateRange(this.value)) {
this._calendar.values =
CalendarDay.compare(this.value.start, this.value.end) === 0
? [this.value.start]
: [this.value.start, this.value.end];
this._calendar.activeDate = this._firstDefinedInRange;
return;
}
this._calendar.values = this._firstDefinedInRange
? [this._firstDefinedInRange]
: null;
}
private _swapDates(range: DateRangeValue): DateRangeValue {
return isCompleteDateRange(range) &&
CalendarDay.compare(range.start, range.end) >= 1
? { start: range.end, end: range.start }
: range;
}
private async _shouldCloseCalendarDropdown() {
if (
!this.keepOpenOnSelect &&
this._calendar.values.length > 1 &&
(await this._hide(true))
) {
return this.useTwoInputs ? this._inputs[0].select() : this._input.focus();
}
}
private _select(value: DateRangeValue | null, emitEvent = false) {
this.value = value;
this._calendar.activeDate =
this._firstDefinedInRange ?? this._calendar.activeDate;
if (emitEvent) {
this.emitEvent('igcChange', { detail: this.value });
this._oldValue = this.value;
this._hide(true);
}
}
// #endregion
// #region Rendering
private _renderClearIcon(picker: DateRangePickerInput = 'start') {
const clearIcon = this.useTwoInputs ? `clear-icon-${picker}` : 'clear-icon';
return this._firstDefinedInRange
? html`
<span
slot="suffix"
part=${clearIcon}
@click=${this.readOnly ? nothing : this.clear}
>
<slot name=${clearIcon}>
<igc-icon
name="input_clear"
collection="default"
aria-hidden="true"
></igc-icon>
</slot>
</span>
`
: nothing;
}
private _renderCalendarIcon(picker: DateRangePickerInput = 'start') {
const defaultIcon = html`
<igc-icon name="today" collection="default" aria-hidden="true"></igc-icon>
`;
const state = this.open ? 'calendar-icon-open' : 'calendar-icon';
const calendarIcon = this.useTwoInputs ? `${state}-${picker}` : state;
return html`
<span
slot="prefix"
part=${calendarIcon}
@pointerdown=${this._handleCalendarIconSlotPointerDown}
@click=${this.readOnly ? nothing : this.handleAnchorClick}
>
<slot name=${calendarIcon}>${defaultIcon}</slot>
</span>
`;
}
private _renderCalendarSlots() {
if (this._isDropDown) {
return nothing;
}
const hasHeaderDate = isEmpty(this._headerDateSlotItems)
? ''
: 'header-date';
return html`
<slot name="title" slot="title">
${this.resourceStrings.selectDate}
</slot>
<slot name="header-date" slot=${hasHeaderDate}></slot>
`;
}