-
Notifications
You must be signed in to change notification settings - Fork 77
/
input-date-picker.tsx
1216 lines (1032 loc) · 35.6 KB
/
input-date-picker.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 {
Component,
Element,
Event,
EventEmitter,
h,
Host,
Listen,
Method,
Prop,
State,
VNode,
Watch,
} from "@stencil/core";
import { FocusTrap } from "focus-trap";
import {
dateFromISO,
dateFromLocalizedString,
dateFromRange,
datePartsFromISO,
datePartsFromLocalizedString,
dateToISO,
inRange,
} from "../../utils/date";
import { focusFirstTabbable, toAriaBoolean } from "../../utils/dom";
import {
connectFloatingUI,
defaultMenuPlacement,
disconnectFloatingUI,
filterValidFlipPlacements,
FloatingCSS,
FloatingUIComponent,
FlipPlacement,
MenuPlacement,
OverlayPositioning,
reposition,
} from "../../utils/floating-ui";
import {
connectForm,
disconnectForm,
FormComponent,
HiddenFormInputSlot,
MutableValidityState,
submitForm,
} from "../../utils/form";
import {
InteractiveComponent,
InteractiveContainer,
updateHostInteraction,
} from "../../utils/interactive";
import { numberKeys } from "../../utils/key";
import { connectLabel, disconnectLabel, LabelableComponent } from "../../utils/label";
import {
componentFocusable,
LoadableComponent,
setComponentLoaded,
setUpLoadableComponent,
} from "../../utils/loadable";
import {
connectLocalized,
getSupportedNumberingSystem,
disconnectLocalized,
LocalizedComponent,
NumberingSystem,
numberStringFormatter,
getDateFormatSupportedLocale,
} from "../../utils/locale";
import { onToggleOpenCloseComponent, OpenCloseComponent } from "../../utils/openCloseComponent";
import { DatePickerMessages } from "../date-picker/assets/date-picker/t9n";
import { DateLocaleData, getLocaleData, getValueAsDateRange } from "../date-picker/utils";
import { HeadingLevel } from "../functional/Heading";
import {
connectMessages,
disconnectMessages,
setUpMessages,
T9nComponent,
updateMessages,
} from "../../utils/t9n";
import {
activateFocusTrap,
connectFocusTrap,
deactivateFocusTrap,
FocusTrapComponent,
} from "../../utils/focusTrapComponent";
import { guid } from "../../utils/guid";
import { getIconScale } from "../../utils/component";
import { Status } from "../interfaces";
import { Validation } from "../functional/Validation";
import { IconNameOrString } from "../icon/interfaces";
import { syncHiddenFormInput } from "../input/common/input";
import { isBrowser } from "../../utils/browser";
import { normalizeToCurrentCentury, isTwoDigitYear } from "./utils";
import { InputDatePickerMessages } from "./assets/input-date-picker/t9n";
import { CSS, IDS } from "./resources";
@Component({
tag: "calcite-input-date-picker",
styleUrl: "input-date-picker.scss",
shadow: {
delegatesFocus: true,
},
assetsDirs: ["assets"],
})
export class InputDatePicker
implements
FloatingUIComponent,
FocusTrapComponent,
FormComponent,
InteractiveComponent,
LabelableComponent,
LoadableComponent,
LocalizedComponent,
OpenCloseComponent,
T9nComponent
{
//--------------------------------------------------------------------------
//
// Public Properties
//
//--------------------------------------------------------------------------
/**
* When `true`, interaction is prevented and the component is displayed with lower opacity.
*/
@Prop({ reflect: true }) disabled = false;
/**
* When `true`, prevents focus trapping.
*/
@Prop({ reflect: true }) focusTrapDisabled = false;
@Watch("focusTrapDisabled")
handleFocusTrapDisabled(focusTrapDisabled: boolean): void {
if (!this.open) {
return;
}
focusTrapDisabled ? deactivateFocusTrap(this) : activateFocusTrap(this);
}
/**
* The `id` of the form that will be associated with the component.
*
* When not set, the component will be associated with its ancestor form element, if any.
*/
@Prop({ reflect: true }) form: string;
/**
* When `true`, the component's value can be read, but controls are not accessible and the value cannot be modified.
*
* @mdn [readOnly](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/readonly)
*/
@Prop({ reflect: true }) readOnly = false;
@Watch("disabled")
@Watch("readOnly")
handleDisabledAndReadOnlyChange(value: boolean): void {
if (!value) {
this.open = false;
}
}
/** Selected date as a string in ISO format (`"yyyy-mm-dd"`). */
@Prop({ mutable: true }) value: string | string[] = "";
@Watch("value")
valueWatcher(newValue: string | string[]): void {
if (!this.userChangedValue) {
let newValueAsDate: Date | Date[];
if (Array.isArray(newValue)) {
newValueAsDate = getValueAsDateRange(newValue);
} else if (newValue) {
newValueAsDate = dateFromISO(newValue);
} else {
newValueAsDate = undefined;
}
if (!this.valueAsDateChangedExternally && newValueAsDate !== this.valueAsDate) {
this.valueAsDate = newValueAsDate;
}
this.localizeInputValues();
}
this.userChangedValue = false;
}
@Watch("valueAsDate")
valueAsDateWatcher(valueAsDate: Date): void {
this.datePickerActiveDate = valueAsDate;
const newValue =
this.range && Array.isArray(valueAsDate)
? [dateToISO(valueAsDate[0]), dateToISO(valueAsDate[1])]
: dateToISO(valueAsDate);
if (this.value !== newValue) {
this.valueAsDateChangedExternally = true;
this.value = newValue;
this.valueAsDateChangedExternally = false;
}
}
/**
* Specifies the component's fallback `calcite-date-picker` `placement` when it's initial or specified `placement` has insufficient space available.
*/
@Prop() flipPlacements: FlipPlacement[];
@Watch("flipPlacements")
flipPlacementsHandler(): void {
this.setFilteredPlacements();
this.reposition(true);
}
/**
* Specifies the heading level of the component's `heading` for proper document structure, without affecting visual styling.
*/
@Prop({ reflect: true }) headingLevel: HeadingLevel;
/** The component's value as a full date object. */
@Prop({ mutable: true }) valueAsDate: Date | Date[];
/**
* Use this property to override individual strings used by the component.
*/
// eslint-disable-next-line @stencil-community/strict-mutable -- updated by t9n module
@Prop({ mutable: true }) messageOverrides: Partial<InputDatePickerMessages & DatePickerMessages>;
/**
* Made into a prop for testing purposes only
*
* @internal
*/
// eslint-disable-next-line @stencil-community/strict-mutable -- updated by t9n module
@Prop({ mutable: true }) messages: InputDatePickerMessages;
@Watch("messageOverrides")
onMessagesChange(): void {
/* wired up by t9n util */
}
/** Specifies the earliest allowed date as a full date object. */
@Prop({ mutable: true }) minAsDate: Date;
/** Specifies the latest allowed date as a full date object. */
@Prop({ mutable: true }) maxAsDate: Date;
/** Specifies the earliest allowed date ("yyyy-mm-dd"). */
@Prop({ reflect: true }) min: string;
@Watch("min")
onMinChanged(min: string): void {
this.minAsDate = dateFromISO(min);
}
/** Specifies the latest allowed date ("yyyy-mm-dd"). */
@Prop({ reflect: true }) max: string;
@Watch("max")
onMaxChanged(max: string): void {
this.maxAsDate = dateFromISO(max);
}
/** When `true`, displays the `calcite-date-picker` component. */
@Prop({ mutable: true, reflect: true }) open = false;
@Watch("open")
openHandler(): void {
onToggleOpenCloseComponent(this);
if (this.disabled || this.readOnly) {
this.open = false;
return;
}
this.reposition(true);
}
/** Specifies the validation message to display under the component. */
@Prop() validationMessage: string;
/** Specifies the validation icon to display under the component. */
@Prop({ reflect: true }) validationIcon: IconNameOrString | boolean;
/**
* The current validation state of the component.
*
* @readonly
* @mdn [ValidityState](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState)
*/
// eslint-disable-next-line @stencil-community/strict-mutable -- updated in form util when syncing hidden input
@Prop({ mutable: true }) validity: MutableValidityState = {
valid: false,
badInput: false,
customError: false,
patternMismatch: false,
rangeOverflow: false,
rangeUnderflow: false,
stepMismatch: false,
tooLong: false,
tooShort: false,
typeMismatch: false,
valueMissing: false,
};
/**
* Specifies the name of the component.
*
* Required to pass the component's `value` on form submission.
*/
@Prop({ reflect: true }) name: string;
/**
* Specifies the Unicode numeral system used by the component for localization. This property cannot be dynamically changed.
*
*/
@Prop({ reflect: true }) numberingSystem: NumberingSystem;
/** Specifies the size of the component. */
@Prop({ reflect: true }) scale: "s" | "m" | "l" = "m";
/** Specifies the status of the input field, which determines message and icons. */
@Prop({ reflect: true }) status: Status = "idle";
/**
* Specifies the placement of the `calcite-date-picker` relative to the component.
*
* @default "bottom-start"
*/
@Prop({ reflect: true }) placement: MenuPlacement = defaultMenuPlacement;
/** When `true`, activates a range for the component. */
@Prop({ reflect: true }) range = false;
/** When `true`, the component must have a value in order for the form to submit. */
@Prop({ reflect: true }) required = false;
/**
* Determines the type of positioning to use for the overlaid content.
*
* Using `"absolute"` will work for most cases. The component will be positioned inside of overflowing parent containers and will affect the container's layout.
*
* `"fixed"` should be used to escape an overflowing parent container, or when the reference element's `position` CSS property is `"fixed"`.
*
*/
@Prop({ reflect: true }) overlayPositioning: OverlayPositioning = "absolute";
@Watch("overlayPositioning")
overlayPositioningHandler(): void {
this.reposition(true);
}
/**
* When `true`, disables the default behavior on the third click of narrowing or extending the range.
* Instead starts a new range.
*/
@Prop() proximitySelectionDisabled = false;
/** Defines the layout of the component. */
@Prop({ reflect: true }) layout: "horizontal" | "vertical" = "horizontal";
//--------------------------------------------------------------------------
//
// Event Listeners
//
//--------------------------------------------------------------------------
@Listen("calciteDaySelect")
calciteDaySelectHandler(): void {
if (this.shouldFocusRangeStart() || this.shouldFocusRangeEnd()) {
return;
}
this.open = false;
}
private calciteInternalInputInputHandler = (event: CustomEvent<any>): void => {
const target = event.target as HTMLCalciteInputElement;
const value = target.value;
const parsedValue = this.parseNumerals(value);
const formattedValue = this.formatNumerals(parsedValue);
target.value = formattedValue;
const { year } = datePartsFromLocalizedString(value, this.localeData);
if (year && year.length < 4) {
return;
}
const date = dateFromLocalizedString(value, this.localeData);
if (inRange(date, this.min, this.max)) {
this.datePickerActiveDate = date;
}
};
private calciteInternalInputBlurHandler = (): void => {
this.commitValue();
};
//--------------------------------------------------------------------------
//
// Events
//
//--------------------------------------------------------------------------
/**
* Fires when the component's `value` changes.
*/
@Event({ cancelable: false }) calciteInputDatePickerChange: EventEmitter<void>;
/** Fires when the component is requested to be closed and before the closing transition begins. */
@Event({ cancelable: false }) calciteInputDatePickerBeforeClose: EventEmitter<void>;
/** Fires when the component is closed and animation is complete. */
@Event({ cancelable: false }) calciteInputDatePickerClose: EventEmitter<void>;
/** Fires when the component is added to the DOM but not rendered, and before the opening transition begins. */
@Event({ cancelable: false }) calciteInputDatePickerBeforeOpen: EventEmitter<void>;
/** Fires when the component is open and animation is complete. */
@Event({ cancelable: false }) calciteInputDatePickerOpen: EventEmitter<void>;
// --------------------------------------------------------------------------
//
// Public Methods
//
// --------------------------------------------------------------------------
/** Sets focus on the component. */
@Method()
async setFocus(): Promise<void> {
await componentFocusable(this);
focusFirstTabbable(this.el);
}
/**
* Updates the position of the component.
*
* @param delayed If true, the repositioning is delayed.
* @returns void
*/
@Method()
async reposition(delayed = false): Promise<void> {
const { floatingEl, referenceEl, placement, overlayPositioning, filteredFlipPlacements } = this;
return reposition(
this,
{
floatingEl,
referenceEl,
overlayPositioning,
placement,
flipPlacements: filteredFlipPlacements,
type: "menu",
},
delayed,
);
}
// --------------------------------------------------------------------------
//
// Lifecycle
//
// --------------------------------------------------------------------------
connectedCallback(): void {
connectLocalized(this);
this.handleDateTimeFormatChange();
const { open } = this;
open && this.openHandler();
if (this.min) {
this.minAsDate = dateFromISO(this.min);
}
if (this.max) {
this.maxAsDate = dateFromISO(this.max);
}
if (Array.isArray(this.value)) {
this.valueAsDate = getValueAsDateRange(this.value);
} else if (this.value) {
try {
const date = dateFromISO(this.value);
const dateInRange = dateFromRange(date, this.minAsDate, this.maxAsDate);
this.valueAsDate = dateInRange;
} catch (error) {
this.warnAboutInvalidValue(this.value);
this.value = "";
}
} else if (this.valueAsDate) {
if (this.range && Array.isArray(this.valueAsDate)) {
this.value = [dateToISO(this.valueAsDate[0]), dateToISO(this.valueAsDate[1])];
} else if (!this.range && !Array.isArray(this.valueAsDate)) {
this.value = dateToISO(this.valueAsDate);
}
}
connectLabel(this);
connectForm(this);
connectMessages(this);
this.setFilteredPlacements();
numberStringFormatter.numberFormatOptions = {
numberingSystem: this.numberingSystem,
locale: this.effectiveLocale,
useGrouping: false,
};
if (this.open) {
onToggleOpenCloseComponent(this);
}
connectFloatingUI(this, this.referenceEl, this.floatingEl);
}
async componentWillLoad(): Promise<void> {
setUpLoadableComponent(this);
await Promise.all([this.loadLocaleData(), setUpMessages(this)]);
this.onMinChanged(this.min);
this.onMaxChanged(this.max);
}
componentDidLoad(): void {
setComponentLoaded(this);
this.localizeInputValues();
connectFloatingUI(this, this.referenceEl, this.floatingEl);
}
disconnectedCallback(): void {
deactivateFocusTrap(this);
disconnectLabel(this);
disconnectForm(this);
disconnectFloatingUI(this, this.referenceEl, this.floatingEl);
disconnectLocalized(this);
disconnectMessages(this);
}
componentDidRender(): void {
updateHostInteraction(this);
}
render(): VNode {
const { disabled, effectiveLocale, messages, numberingSystem, readOnly } = this;
numberStringFormatter.numberFormatOptions = {
numberingSystem,
locale: effectiveLocale,
useGrouping: false,
};
return (
<Host onBlur={this.blurHandler} onKeyDown={this.keyDownHandler}>
<InteractiveContainer disabled={this.disabled}>
{this.localeData && (
<div class={CSS.inputContainer}>
<div
class={CSS.inputWrapper}
data-position="start"
onClick={this.onInputWrapperClick}
onPointerDown={this.onInputWrapperPointerDown}
ref={this.setStartWrapper}
>
<calcite-input-text
aria-autocomplete="none"
aria-controls={this.dialogId}
aria-describedby={this.placeholderTextId}
aria-errormessage={IDS.validationMessage}
aria-expanded={toAriaBoolean(this.open)}
aria-haspopup="dialog"
aria-invalid={toAriaBoolean(this.status === "invalid")}
class={{
[CSS.input]: true,
[CSS.inputNoBottomBorder]: this.layout === "vertical" && this.range,
}}
disabled={disabled}
icon="calendar"
onCalciteInputTextInput={this.calciteInternalInputInputHandler}
onCalciteInternalInputTextBlur={this.calciteInternalInputBlurHandler}
onCalciteInternalInputTextFocus={this.startInputFocus}
placeholder={this.localeData?.placeholder}
readOnly={readOnly}
ref={this.setStartInput}
role="combobox"
scale={this.scale}
status={this.status}
/>
{!this.readOnly &&
this.renderToggleIcon(this.open && this.focusedInput === "start")}
<span aria-hidden="true" class={CSS.assistiveText} id={this.placeholderTextId}>
Date Format: {this.localeData?.placeholder}
</span>
</div>
<div
aria-hidden={toAriaBoolean(!this.open)}
aria-label={messages.chooseDate}
aria-live="polite"
aria-modal="true"
class={{
[CSS.menu]: true,
[CSS.menuActive]: this.open,
}}
id={this.dialogId}
ref={this.setFloatingEl}
role="dialog"
>
<div
class={{
[CSS.calendarWrapper]: true,
[CSS.calendarWrapperEnd]: this.focusedInput === "end",
[FloatingCSS.animation]: true,
[FloatingCSS.animationActive]: this.open,
}}
ref={this.setTransitionEl}
>
<calcite-date-picker
activeDate={this.datePickerActiveDate}
activeRange={this.focusedInput}
headingLevel={this.headingLevel}
max={this.max}
maxAsDate={this.maxAsDate}
messageOverrides={this.messageOverrides}
min={this.min}
minAsDate={this.minAsDate}
numberingSystem={numberingSystem}
onCalciteDatePickerChange={this.handleDateChange}
onCalciteDatePickerRangeChange={this.handleDateRangeChange}
proximitySelectionDisabled={this.proximitySelectionDisabled}
range={this.range}
ref={this.setDatePickerRef}
scale={this.scale}
tabIndex={this.open ? undefined : -1}
valueAsDate={this.valueAsDate}
/>
</div>
</div>
{this.range && this.layout === "horizontal" && (
<div class={CSS.horizontalArrowContainer}>
<calcite-icon
flipRtl={true}
icon="arrow-right"
scale={getIconScale(this.scale)}
/>
</div>
)}
{this.range && this.layout === "vertical" && this.scale !== "s" && (
<div class={CSS.verticalArrowContainer}>
<calcite-icon icon="arrow-down" scale={getIconScale(this.scale)} />
</div>
)}
{this.range && (
<div
class={CSS.inputWrapper}
data-position="end"
onClick={this.onInputWrapperClick}
onPointerDown={this.onInputWrapperPointerDown}
ref={this.setEndWrapper}
>
<calcite-input-text
aria-autocomplete="none"
aria-controls={this.dialogId}
aria-errormessage={IDS.validationMessage}
aria-expanded={toAriaBoolean(this.open)}
aria-haspopup="dialog"
aria-invalid={toAriaBoolean(this.status === "invalid")}
class={{
[CSS.input]: true,
[CSS.inputBorderTopColorOne]: this.layout === "vertical" && this.range,
}}
disabled={disabled}
icon="calendar"
onCalciteInputTextInput={this.calciteInternalInputInputHandler}
onCalciteInternalInputTextBlur={this.calciteInternalInputBlurHandler}
onCalciteInternalInputTextFocus={this.endInputFocus}
placeholder={this.localeData?.placeholder}
readOnly={readOnly}
ref={this.setEndInput}
role="combobox"
scale={this.scale}
status={this.status}
/>
{!this.readOnly &&
this.renderToggleIcon(this.open && this.focusedInput === "end")}
</div>
)}
</div>
)}
<HiddenFormInputSlot component={this} />
{this.validationMessage && this.status === "invalid" ? (
<Validation
icon={this.validationIcon}
id={IDS.validationMessage}
message={this.validationMessage}
scale={this.scale}
status={this.status}
/>
) : null}
</InteractiveContainer>
</Host>
);
}
renderToggleIcon(open: boolean): VNode {
return (
// we set tab index to -1 to prevent delegatesFocus from stealing focus before we can set it
<span class={CSS.toggleIcon} tabIndex={-1}>
<calcite-icon
class={CSS.chevronIcon}
icon={open ? "chevron-up" : "chevron-down"}
scale={getIconScale(this.scale)}
/>
</span>
);
}
//--------------------------------------------------------------------------
//
// Private State/Props
//
//--------------------------------------------------------------------------
@Element() el: HTMLCalciteInputDatePickerElement;
private currentOpenInput: "start" | "end";
private datePickerEl: HTMLCalciteDatePickerElement;
private dialogId = `date-picker-dialog--${guid()}`;
filteredFlipPlacements: FlipPlacement[];
private focusOnOpen = false;
focusTrap: FocusTrap;
labelEl: HTMLCalciteLabelElement;
formEl: HTMLFormElement;
defaultValue: InputDatePicker["value"];
private dateTimeFormat: Intl.DateTimeFormat;
@State() datePickerActiveDate: Date;
@State() defaultMessages: InputDatePickerMessages;
@State() effectiveLocale = "";
@Watch("effectiveLocale")
effectiveLocaleChange(): void {
updateMessages(this, this.effectiveLocale);
this.loadLocaleData();
}
@Watch("effectiveLocale")
@Watch("numberingSystem")
handleDateTimeFormatChange(): void {
const formattingOptions: Intl.DateTimeFormatOptions = {
// we explicitly set numberingSystem to prevent the browser-inferred value
// see https://github.com/Esri/calcite-design-system/issues/3079#issuecomment-1168964195 for more info
numberingSystem: getSupportedNumberingSystem(this.numberingSystem),
};
this.dateTimeFormat = new Intl.DateTimeFormat(
getDateFormatSupportedLocale(this.effectiveLocale),
formattingOptions,
);
}
@State() focusedInput: "start" | "end" = "start";
@State() private localeData: DateLocaleData;
private startInput: HTMLCalciteInputElement;
private endInput: HTMLCalciteInputElement;
private floatingEl: HTMLDivElement;
private referenceEl: HTMLDivElement;
private startWrapper: HTMLDivElement;
private endWrapper: HTMLDivElement;
private userChangedValue = false;
openTransitionProp = "opacity";
transitionEl: HTMLDivElement;
@Watch("layout")
@Watch("focusedInput")
setReferenceEl(): void {
const { focusedInput, layout, endWrapper, startWrapper } = this;
this.referenceEl =
focusedInput === "end" || layout === "vertical"
? endWrapper || startWrapper
: startWrapper || endWrapper;
requestAnimationFrame(() => connectFloatingUI(this, this.referenceEl, this.floatingEl));
}
private valueAsDateChangedExternally = false;
private placeholderTextId = `calcite-input-date-picker-placeholder-${guid()}`;
//--------------------------------------------------------------------------
//
// Private Methods
//
//--------------------------------------------------------------------------
private onInputWrapperPointerDown = (): void => {
this.currentOpenInput = this.focusedInput;
};
private onInputWrapperClick = (event: MouseEvent) => {
const { range, endInput, startInput, currentOpenInput } = this;
const currentTarget = event.currentTarget as HTMLDivElement;
const position = currentTarget.getAttribute("data-position") as "start" | "end";
const path = event.composedPath();
const wasToggleClicked = path.find((el: HTMLElement) => el.classList?.contains(CSS.toggleIcon));
if (wasToggleClicked) {
const targetInput = position === "start" ? startInput : endInput;
targetInput.setFocus();
}
if (!range || !this.open || currentOpenInput === position) {
this.open = !this.open;
}
};
setFilteredPlacements = (): void => {
const { el, flipPlacements } = this;
this.filteredFlipPlacements = flipPlacements
? filterValidFlipPlacements(flipPlacements, el)
: null;
};
private setTransitionEl = (el: HTMLDivElement): void => {
this.transitionEl = el;
};
onLabelClick(): void {
this.setFocus();
}
onBeforeOpen(): void {
this.calciteInputDatePickerBeforeOpen.emit();
}
onOpen(): void {
activateFocusTrap(this, {
onActivate: () => {
if (this.focusOnOpen) {
this.datePickerEl.setFocus();
this.focusOnOpen = false;
}
},
});
this.calciteInputDatePickerOpen.emit();
}
onBeforeClose(): void {
this.calciteInputDatePickerBeforeClose.emit();
}
onClose(): void {
this.calciteInputDatePickerClose.emit();
deactivateFocusTrap(this);
this.restoreInputFocus();
this.focusOnOpen = false;
this.datePickerEl.reset();
}
syncHiddenFormInput(input: HTMLInputElement): void {
syncHiddenFormInput("date", this, input);
}
setStartInput = (el: HTMLCalciteInputElement): void => {
this.startInput = el;
};
setEndInput = (el: HTMLCalciteInputElement): void => {
this.endInput = el;
};
private blurHandler = (): void => {
this.open = false;
};
private commitValue(): void {
const { focusedInput, value } = this;
const focusedInputName = `${focusedInput}Input`;
const focusedInputValue = this[focusedInputName].value;
const date = dateFromLocalizedString(focusedInputValue, this.localeData);
const dateAsISO = dateToISO(date);
const valueIsArray = Array.isArray(value);
if (this.range) {
const focusedInputValueIndex = focusedInput === "start" ? 0 : 1;
if (valueIsArray) {
if (dateAsISO === value[focusedInputValueIndex]) {
return;
}
if (date) {
this.setRangeValue([
focusedInput === "start" ? date : dateFromISO(value[0]),
focusedInput === "end" ? date : dateFromISO(value[1]),
]);
this.localizeInputValues();
} else {
this.setRangeValue([
focusedInput === "end" && dateFromISO(value[0]),
focusedInput === "start" && dateFromISO(value[1]),
]);
}
} else {
if (date) {
this.setRangeValue([
focusedInput === "start" ? date : dateFromISO(value[0]),
focusedInput === "end" ? date : dateFromISO(value[1]),
]);
this.localizeInputValues();
}
}
} else {
if (dateAsISO === value) {
return;
}
this.setValue(date);
this.localizeInputValues();
}
}
keyDownHandler = (event: KeyboardEvent): void => {
const { defaultPrevented, key } = event;
if (defaultPrevented) {
return;
}
if (key === "Enter") {
event.preventDefault();
this.commitValue();
if (this.shouldFocusRangeEnd()) {
this.endInput?.setFocus();
} else if (this.shouldFocusRangeStart()) {
this.startInput?.setFocus();
}
if (submitForm(this)) {
this.restoreInputFocus();
}
} else if (key === "ArrowDown") {
this.open = true;
this.focusOnOpen = true;
event.preventDefault();
} else if (key === "Escape") {
this.open = false;
event.preventDefault();
this.restoreInputFocus();
}
};
startInputFocus = (): void => {
this.focusedInput = "start";
};
endInputFocus = (): void => {
this.focusedInput = "end";
};
setFloatingEl = (el: HTMLDivElement): void => {
this.floatingEl = el;
connectFloatingUI(this, this.referenceEl, this.floatingEl);
};
setStartWrapper = (el: HTMLDivElement): void => {
this.startWrapper = el;
this.setReferenceEl();
};
setEndWrapper = (el: HTMLDivElement): void => {
this.endWrapper = el;
this.setReferenceEl();
};
setDatePickerRef = (el: HTMLCalciteDatePickerElement): void => {
this.datePickerEl = el;
connectFocusTrap(this, {
focusTrapEl: el,
focusTrapOptions: {