-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathinput-time-zone.tsx
612 lines (521 loc) · 17.7 KB
/
input-time-zone.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
import {
Component,
Element,
Event,
EventEmitter,
h,
Host,
Method,
Prop,
State,
VNode,
Watch,
} from "@stencil/core";
import { connectLabel, disconnectLabel, LabelableComponent } from "../../utils/label";
import {
InteractiveComponent,
InteractiveContainer,
updateHostInteraction,
} from "../../utils/interactive";
import {
connectLocalized,
disconnectLocalized,
LocalizedComponent,
SupportedLocale,
} from "../../utils/locale";
import { Scale, Status } from "../interfaces";
import {
connectMessages,
disconnectMessages,
setUpMessages,
T9nComponent,
updateMessages,
} from "../../utils/t9n";
import { OverlayPositioning } from "../../utils/floating-ui";
import {
componentFocusable,
LoadableComponent,
setComponentLoaded,
setUpLoadableComponent,
} from "../../utils/loadable";
import {
afterConnectDefaultValueSet,
connectForm,
disconnectForm,
FormComponent,
HiddenFormInputSlot,
MutableValidityState,
} from "../../utils/form";
import { IconNameOrString } from "../icon/interfaces";
import { CSS } from "./resources";
import {
createTimeZoneItems,
findTimeZoneItemByProp,
getNormalizer,
getSelectedRegionTimeZoneLabel,
getUserTimeZoneName,
getUserTimeZoneOffset,
} from "./utils";
import { InputTimeZoneMessages } from "./assets/input-time-zone/t9n";
import { OffsetStyle, TimeZone, TimeZoneItem, TimeZoneItemGroup, TimeZoneMode } from "./interfaces";
@Component({
tag: "calcite-input-time-zone",
styleUrl: "input-time-zone.scss",
assetsDirs: ["assets"],
shadow: {
delegatesFocus: true,
},
})
export class InputTimeZone
implements
FormComponent,
InteractiveComponent,
LabelableComponent,
LoadableComponent,
LocalizedComponent,
T9nComponent
{
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
/**
* When `true`, an empty value (`null`) will be allowed as a `value`.
*
* When `false`, an offset or name value is enforced, and clearing the input or blurring will restore the last valid `value`.
*/
@Prop({ reflect: true }) clearable = false;
/**
* When `true`, interaction is prevented and the component is displayed with lower opacity.
*/
@Prop({ reflect: true }) disabled = false;
/**
* 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;
/** Specifies the component's maximum number of options to display before displaying a scrollbar. */
@Prop({ reflect: true }) maxItems = 0;
/**
* 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: InputTimeZoneMessages;
/**
* 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<InputTimeZoneMessages>;
@Watch("messageOverrides")
onMessagesChange(): void {
/* wired up by t9n util */
}
/**
* This specifies the type of `value` and the associated options presented to the user:
*
* Using `"offset"` will provide options that show timezone offsets.
*
* Using `"name"` will provide options that show the IANA time zone names.
*
* @default "offset"
*/
@Prop({ reflect: true }) mode: TimeZoneMode = "offset";
@Watch("messages")
@Watch("mode")
@Watch("referenceDate")
handleTimeZoneItemPropsChange(): void {
if (!this.timeZoneItems) {
return;
}
this.updateTimeZoneItems();
this.updateTimeZoneSelection();
}
/**
* Specifies how the offset will be displayed, where
*
* `"user"` uses `UTC` or `GMT` depending on the user's locale,
* `"gmt"` always uses `GMT`, and
* `"utc"` always uses `UTC`.
*
* This only applies to the `offset` mode.
*
* @default "user"
*/
@Prop({ reflect: true }) offsetStyle: OffsetStyle = "user";
/** 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;
/** When `true`, displays and positions the component. */
@Prop({ mutable: true, reflect: true }) open = false;
@Watch("open")
openChanged(): void {
// we set the property instead of the attribute to ensure open/close events are emitted properly
this.comboboxEl.open = this.open;
}
/**
* 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";
/**
* This `date` will be used as a reference to Daylight Savings Time when creating time zone item groups.
*
* It can be either a Date instance or a string in ISO format (`"YYYY-MM-DD"`, `"YYYY-MM-DDTHH:MM:SS.SSSZ"`).
*
* @see [Date.prototype.toISOString](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)
*/
@Prop() referenceDate: Date | string;
/**
* When `true`, the component must have a value in order for the form to submit.
*
* @internal
*/
@Prop({ reflect: true }) required = false;
/** Specifies the size of the component. */
@Prop({ reflect: true }) scale: Scale = "m";
/** Specifies the status of the input field, which determines message and icons. */
@Prop({ reflect: true }) status: Status = "idle";
/**
* The component's value, where the value is the time zone offset or the difference, in minutes, between the selected time zone and UTC.
*
* If no value is provided, the user's time zone offset will be selected by default.
*
* @see https://www.w3.org/International/core/2005/09/timezone.html#:~:text=What%20is%20a%20%22zone%20offset,or%20%22%2D%22%20from%20UTC.
*/
@Prop({ mutable: true }) value: string;
@Watch("value")
handleValueChange(value: string, oldValue: string): void {
value = this.normalizeValue(value);
if (!value) {
if (this.clearable) {
this.value = value;
this.selectedTimeZoneItem = null;
return;
}
this.value = oldValue;
this.selectedTimeZoneItem = this.findTimeZoneItem(oldValue);
return;
}
const timeZoneItem = this.findTimeZoneItem(value);
if (!timeZoneItem) {
this.value = oldValue;
return;
}
this.selectedTimeZoneItem = timeZoneItem;
}
/**
* When `true`, the component's value can be read, but controls are not accessible and the value cannot be modified.
*/
@Prop({ reflect: true }) readOnly = false;
//--------------------------------------------------------------------------
//
// Public Methods
//
//--------------------------------------------------------------------------
@Method()
async setFocus(): Promise<void> {
await componentFocusable(this);
await this.comboboxEl.setFocus();
}
//--------------------------------------------------------------------------
//
// Events
//
//--------------------------------------------------------------------------
/**
* Fires when the component is requested to be closed and before the closing transition begins.
*/
@Event({ cancelable: false }) calciteInputTimeZoneBeforeClose: EventEmitter<void>;
/**
* Fires when the component is added to the DOM but not rendered, and before the opening transition begins.
*/
@Event({ cancelable: false }) calciteInputTimeZoneBeforeOpen: EventEmitter<void>;
/**
* Fires when the component's `value` changes.
*/
@Event({ cancelable: false }) calciteInputTimeZoneChange: EventEmitter<void>;
/**
* Fires after the component is closed and animation is complete.
*/
@Event({ cancelable: false }) calciteInputTimeZoneClose: EventEmitter<void>;
/**
* Fires after the component is opened and animation is complete.
*/
@Event({ cancelable: false }) calciteInputTimeZoneOpen: EventEmitter<void>;
//--------------------------------------------------------------------------
//
// Private Properties
//
//--------------------------------------------------------------------------
@Element() el: HTMLCalciteInputTimeZoneElement;
private comboboxEl: HTMLCalciteComboboxElement;
@State() defaultMessages: InputTimeZoneMessages;
defaultValue: InputTimeZone["value"];
@State() effectiveLocale: SupportedLocale = "";
@Watch("effectiveLocale")
effectiveLocaleWatcher(): void {
updateMessages(this, this.effectiveLocale);
}
formEl: HTMLFormElement;
labelEl: HTMLCalciteLabelElement;
private selectedTimeZoneItem: TimeZoneItem;
private timeZoneItems: TimeZoneItem[] | TimeZoneItemGroup[];
//--------------------------------------------------------------------------
//
// Private Methods
//
//--------------------------------------------------------------------------
onLabelClick(): void {
this.setFocus();
}
private setComboboxRef = (el: HTMLCalciteComboboxElement): void => {
this.comboboxEl = el;
};
/**
* Helps override the selected item's label for region mode outside of item rendering logic to avoid flickering text change
*
* @param open
* @private
*/
private overrideSelectedLabelForRegion(open: boolean): void {
if (this.mode !== "region" || !this.selectedTimeZoneItem) {
return;
}
const { label, metadata } = this.selectedTimeZoneItem;
this.comboboxEl.selectedItems[0].textLabel =
!metadata.country || open
? label
: getSelectedRegionTimeZoneLabel(label, metadata.country, this.messages);
}
private onComboboxBeforeClose = (event: CustomEvent): void => {
event.stopPropagation();
this.overrideSelectedLabelForRegion(false);
this.calciteInputTimeZoneBeforeClose.emit();
};
private onComboboxBeforeOpen = (event: CustomEvent): void => {
event.stopPropagation();
this.overrideSelectedLabelForRegion(true);
this.calciteInputTimeZoneBeforeOpen.emit();
};
private onComboboxChange = (event: CustomEvent): void => {
event.stopPropagation();
const combobox = event.target as HTMLCalciteComboboxElement;
const selectedItem = combobox.selectedItems[0];
if (!selectedItem) {
this.value = null;
this.selectedTimeZoneItem = null;
this.calciteInputTimeZoneChange.emit();
return;
}
const selected = this.findTimeZoneItemByLabel(selectedItem.getAttribute("data-label"));
const selectedValue = `${selected.value}`;
if (this.value === selectedValue && selected.label === this.selectedTimeZoneItem.label) {
return;
}
this.value = selectedValue;
this.selectedTimeZoneItem = selected;
this.calciteInputTimeZoneChange.emit();
};
private onComboboxClose = (event: CustomEvent): void => {
event.stopPropagation();
this.open = false;
this.calciteInputTimeZoneClose.emit();
};
private onComboboxOpen = (event: CustomEvent): void => {
this.open = true;
event.stopPropagation();
this.calciteInputTimeZoneOpen.emit();
};
private findTimeZoneItem(value: number | string | null): TimeZoneItem | null {
return findTimeZoneItemByProp(this.timeZoneItems, "value", value);
}
private findTimeZoneItemByLabel(label: string | null): TimeZoneItem | null {
return findTimeZoneItemByProp(this.timeZoneItems, "label", label);
}
private async updateTimeZoneItems(): Promise<void> {
this.timeZoneItems = await this.createTimeZoneItems();
}
private async updateTimeZoneSelection(): Promise<void> {
if (this.value === "" && this.clearable) {
this.selectedTimeZoneItem = null;
return;
}
const fallbackValue = this.mode === "offset" ? getUserTimeZoneOffset() : getUserTimeZoneName();
const valueToMatch = this.value ?? fallbackValue;
this.selectedTimeZoneItem =
this.findTimeZoneItem(valueToMatch) || this.findTimeZoneItem(fallbackValue);
}
private async createTimeZoneItems(): Promise<TimeZoneItem[] | TimeZoneItemGroup[]> {
if (!this.effectiveLocale || !this.messages) {
return [];
}
return createTimeZoneItems(
this.effectiveLocale,
this.messages,
this.mode,
this.referenceDate instanceof Date
? this.referenceDate
: new Date(this.referenceDate ?? Date.now()),
this.offsetStyle,
);
}
// --------------------------------------------------------------------------
//
// Lifecycle
//
//--------------------------------------------------------------------------
connectedCallback(): void {
connectForm(this);
connectLabel(this);
connectLocalized(this);
connectMessages(this);
}
disconnectedCallback(): void {
disconnectForm(this);
disconnectLabel(this);
disconnectLocalized(this);
disconnectMessages(this);
}
private normalizeValue(value: string | null): string {
value = value === null ? "" : value;
return value ? this.normalizer(value) : value;
}
private normalizer: (timeZone: TimeZone) => TimeZone;
async componentWillLoad(): Promise<void> {
setUpLoadableComponent(this);
const [, normalizer] = await Promise.all([setUpMessages(this), getNormalizer(this.mode)]);
this.normalizer = normalizer;
await this.updateTimeZoneItems();
this.value = this.normalizeValue(this.value);
await this.updateTimeZoneSelection();
const selectedValue = this.selectedTimeZoneItem ? `${this.selectedTimeZoneItem.value}` : null;
afterConnectDefaultValueSet(this, selectedValue);
this.value = selectedValue;
}
componentDidLoad(): void {
setComponentLoaded(this);
this.openChanged();
}
componentDidRender(): void {
updateHostInteraction(this);
this.overrideSelectedLabelForRegion(this.open);
}
render(): VNode {
return (
<Host>
<InteractiveContainer disabled={this.disabled}>
<calcite-combobox
clearDisabled={!this.clearable}
disabled={this.disabled}
label={this.messages.chooseTimeZone}
lang={this.effectiveLocale}
maxItems={this.maxItems}
onCalciteComboboxBeforeClose={this.onComboboxBeforeClose}
onCalciteComboboxBeforeOpen={this.onComboboxBeforeOpen}
onCalciteComboboxChange={this.onComboboxChange}
onCalciteComboboxClose={this.onComboboxClose}
onCalciteComboboxOpen={this.onComboboxOpen}
overlayPositioning={this.overlayPositioning}
placeholder={
this.mode === "name"
? this.messages.namePlaceholder
: this.mode === "offset"
? this.messages.offsetPlaceholder
: this.messages.regionPlaceholder
}
placeholderIcon="search"
readOnly={this.readOnly}
ref={this.setComboboxRef}
scale={this.scale}
selectionMode={this.clearable ? "single" : "single-persist"}
status={this.status}
validation-icon={this.validationIcon}
validation-message={this.validationMessage}
>
{this.renderItems()}
</calcite-combobox>
<HiddenFormInputSlot component={this} />
</InteractiveContainer>
</Host>
);
}
private renderItems(): VNode[] {
if (this.mode === "region") {
return this.renderRegionItems();
}
return this.timeZoneItems.map((group) => {
const selected = this.selectedTimeZoneItem === group;
const { label, metadata, value } = group;
return (
<calcite-combobox-item
data-label={label}
key={label}
metadata={metadata}
selected={selected}
textLabel={label}
value={value}
/>
);
});
}
private renderRegionItems(): VNode[] {
return (this.timeZoneItems as TimeZoneItemGroup[]).flatMap(({ label, items }) => (
<calcite-combobox-item-group key={label} label={label}>
{items.map((item) => {
const selected = this.selectedTimeZoneItem === item;
const { label, metadata, value } = item;
return (
<calcite-combobox-item
data-label={label}
description={metadata.country}
key={label}
metadata={metadata}
selected={selected}
textLabel={label}
value={value}
>
<span class={CSS.offset} slot="content-end">
{metadata.offset}
</span>
</calcite-combobox-item>
);
})}
</calcite-combobox-item-group>
));
}
}