-
Notifications
You must be signed in to change notification settings - Fork 274
/
Copy pathTimePickerInternals.ts
507 lines (434 loc) · 13.4 KB
/
TimePickerInternals.ts
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
import UI5Element from "@ui5/webcomponents-base/dist/UI5Element.js";
import litRender from "@ui5/webcomponents-base/dist/renderer/LitRenderer.js";
import customElement from "@ui5/webcomponents-base/dist/decorators/customElement.js";
import property from "@ui5/webcomponents-base/dist/decorators/property.js";
import event from "@ui5/webcomponents-base/dist/decorators/event.js";
import { getI18nBundle } from "@ui5/webcomponents-base/dist/i18nBundle.js";
import type I18nBundle from "@ui5/webcomponents-base/dist/i18nBundle.js";
import getLocale from "@ui5/webcomponents-base/dist/locale/getLocale.js";
import DateFormat from "@ui5/webcomponents-localization/dist/DateFormat.js";
import getCachedLocaleDataInstance from "@ui5/webcomponents-localization/dist/getCachedLocaleDataInstance.js";
import "@ui5/webcomponents-localization/dist/features/calendar/Gregorian.js"; // default calendar for bundling
import CalendarType from "@ui5/webcomponents-base/dist/types/CalendarType.js";
import { fetchCldr } from "@ui5/webcomponents-base/dist/asset-registries/LocaleData.js";
import Integer from "@ui5/webcomponents-base/dist/types/Integer.js";
import UI5Date from "@ui5/webcomponents-localization/dist/dates/UI5Date.js";
import SegmentedButton from "./SegmentedButton.js";
import {
getHoursConfigByFormat,
getTimeControlsByFormat,
HourType,
} from "./timepicker-utils/TimeSlider.js";
import {
TIMEPICKER_HOURS_LABEL,
TIMEPICKER_MINUTES_LABEL,
TIMEPICKER_SECONDS_LABEL,
TIMEPICKER_CLOCK_DIAL_LABEL,
} from "./generated/i18n/i18n-defaults.js";
type TimePickerComponentIndexMap = {
hours: number,
minutes: number,
seconds: number,
}
type TimeSelectionPeriodProperties = {
label: string,
selected: boolean,
}
type TimeSelectionChangeEventDetail = {
value: string | undefined,
valid: boolean,
}
type TimePickerEntityAttributes = {
min: number,
max: number,
step: number,
}
type TimePickerEntityProperties = {
label: string,
entity?: string,
itemMin?: number,
itemMax?: number,
value: number,
stringValue?: string,
textValue?: string,
displayStep?: number,
lastItemReplacement?: number,
showInnerCircle?: boolean,
prependZero: boolean,
active?: boolean,
focused?: boolean,
hasSeparator?: boolean,
attributes?: TimePickerEntityAttributes,
}
const TYPE_COOLDOWN_DELAY = 1000; // Cooldown delay; 0 = disabled cooldown
/**
* @class
*
* ### Overview
*
* `ui5-time-picker-internals` is helper component that contains shared methods used in `ui5-time-selection-clocks`
* and `<ui5-time-selection-inputs>` components and should not be used separately.
* @constructor
* @extends UI5Element
* @abstract
* @since 1.15.0
* @private
*/
@customElement({
renderer: litRender,
})
/**
* Fired when the value changes due to user interaction with the sliders.
*/
@event<TimeSelectionChangeEventDetail>("change", {
detail: {
value: { type: String },
valid: { type: Boolean },
},
})
class TimePickerInternals extends UI5Element {
/**
* Defines a formatted time value.
* @default undefined
* @public
*/
@property({ defaultValue: undefined })
value?: string;
/**
* Determines the format, displayed in the input field.
*
* Example:
* HH:mm:ss -> 11:42:35
* hh:mm:ss a -> 2:23:15 PM
* mm:ss -> 12:04 (only minutes and seconds)
* @default ""
* @public
*/
@property()
formatPattern!: string;
/**
* The index of the active Clock/TogleSpinButton.
* @default 0
* @private
*/
@property({ validator: Integer, defaultValue: 0, noAttribute: true })
_activeIndex!: number;
/**
* Contains calendar type.
* @private
*/
@property({ type: CalendarType })
_calendarType!: CalendarType;
/**
* Contains currently available Time Picker components depending on time format.
* @private
*/
@property({ type: Object, multiple: true })
_entities!: Array<TimePickerEntityProperties>;
/**
* Contains component-to-index map.
* @private
*/
@property({ type: Object })
_componentMap!: TimePickerComponentIndexMap;
/**
* Contains currently available Button components depending on time format.
* @private
*/
@property({ type: Object, multiple: true })
_periods!: Array<TimeSelectionPeriodProperties>;
/**
* Id of the cooldown interval
* @private
*/
@property({ validator: Integer, noAttribute: true })
_typeCooldownId?: ReturnType<typeof setTimeout>;
/**
* Exact match number buffer
* @private
*/
@property({ validator: Integer, noAttribute: true })
_exactMatch?: number;
/**
* Buffer for entered by keyboard numbers
* @private
*/
@property({ defaultValue: "", noAttribute: true })
_keyboardBuffer!: string;
static i18nBundle: I18nBundle;
static async onDefine() {
[TimePickerInternals.i18nBundle] = await Promise.all([
getI18nBundle("@ui5/webcomponents"),
fetchCldr(getLocale().getLanguage(), getLocale().getRegion(), getLocale().getScript()),
]);
}
get _hoursConfiguration() {
// @ts-ignore aFormatArray is a private API of DateFormat
const formatArray = this.getFormat().aFormatArray as Array<{ type: HourType }>;
const hourFormat = formatArray.find(item => item.type.startsWith("hour")); // try to find an entry for the hours
return getHoursConfigByFormat(hourFormat ? hourFormat.type : "hour0_23");
}
get _zeroPaddedHours() {
// @ts-ignore aFormatArray is a private API of DateFormat
const formatArray = this.getFormat().aFormatArray as Array<{ type: HourType }>;
const hourFormat = formatArray.find(item => item.type.startsWith("hour")); // try to find an entry for the hours
// @ts-ignore digits is a private API of aFormatArray
return !(hourFormat.digits && (hourFormat.digits as Integer) === 1);
}
get _neededComponents() {
// @ts-ignore aFormatArray is a private API of DateFormat
const formatArray = this.getFormat().aFormatArray as Array<{ type: HourType }>;
return getTimeControlsByFormat(formatArray, this._hoursConfiguration);
}
get _hasHoursComponent() {
return this._neededComponents[0];
}
get _hasMinutesComponent() {
return this._neededComponents[1];
}
get _hasSecondsComponent() {
return this._neededComponents[2];
}
get _hasPeriodsComponent() {
return this._neededComponents[3];
}
get dateValue() {
return this.value ? this.getFormat().parse(this.value, undefined as unknown as boolean, undefined as unknown as boolean) as Date : UI5Date.getInstance();
}
get validDateValue() {
return this.value !== undefined && this.isValid(this.value) ? this.dateValue : UI5Date.getInstance();
}
get periodsArray() {
// @ts-ignore aDayPeriodsAbbrev is a private API of DateFormat
const dayPeriodsAbbrev = this.getFormat().aDayPeriodsAbbrev as Array<string>;
return dayPeriodsAbbrev.map((x: string) => x.toUpperCase());
}
get _hours() {
let hours;
const dateValue = this.validDateValue;
if (this._hoursConfiguration.isTwelveHoursFormat && dateValue.getHours() > this._hoursConfiguration.maxHour) {
hours = dateValue.getHours() - 12;
} else if (this._hoursConfiguration.isTwelveHoursFormat && dateValue.getHours() < this._hoursConfiguration.minHour) {
hours = dateValue.getHours() + 12;
} else {
hours = dateValue.getHours();
}
if (hours.toString().length === 1 && this._zeroPaddedHours) {
hours = `0${hours}`;
}
return hours.toString();
}
get _minutes() {
const minutes = this.validDateValue.getMinutes().toString();
return minutes.length === 1 ? `0${minutes}` : minutes;
}
get _seconds() {
const seconds = this.validDateValue.getSeconds().toString();
return seconds.length === 1 ? `0${seconds}` : seconds;
}
get _period() {
let period;
const dateValue = this.validDateValue;
if (!this._hoursConfiguration.isTwelveHoursFormat) {
return undefined;
}
if (this._hoursConfiguration.minHour === 1) {
period = dateValue.getHours() >= this._hoursConfiguration.maxHour ? this.periodsArray[1] : this.periodsArray[0];
} else {
period = (dateValue.getHours() > this._hoursConfiguration.maxHour || dateValue.getHours() === this._hoursConfiguration.minHour) ? this.periodsArray[1] : this.periodsArray[0];
}
return period;
}
get _formatPattern() {
const pattern = this.formatPattern;
const hasHours = !!pattern.match(/H/i);
const fallback = !pattern || !hasHours;
const localeData = getCachedLocaleDataInstance(getLocale());
return fallback ? localeData.getCombinedDateTimePattern("medium", "medium", undefined) : pattern;
}
get _isPattern() {
return this._formatPattern !== "medium" && this._formatPattern !== "short" && this._formatPattern !== "long";
}
get hoursLabel() {
return TimePickerInternals.i18nBundle.getText(TIMEPICKER_HOURS_LABEL);
}
get minutesLabel() {
return TimePickerInternals.i18nBundle.getText(TIMEPICKER_MINUTES_LABEL);
}
get secondsLabel() {
return TimePickerInternals.i18nBundle.getText(TIMEPICKER_SECONDS_LABEL);
}
get clockDialAriaLabel() {
return TimePickerInternals.i18nBundle.getText(TIMEPICKER_CLOCK_DIAL_LABEL);
}
setValue(date: Date) {
const value = this.formatValue(date);
if (this.isValid(value)) {
this.value = this.normalizeValue(value);
this.fireEvent<TimeSelectionChangeEventDetail>("change", { value: this.value, valid: true });
}
}
isValid(value: string) {
return value === "" || this.getFormat().parse(value, undefined as unknown as boolean, undefined as unknown as boolean);
}
normalizeValue(value: string) {
if (value === "") {
return value;
}
return this.getFormat().format(this.getFormat().parse(value, undefined as unknown as boolean, undefined as unknown as boolean));
}
getFormat() {
let dateFormat: DateFormat;
if (this._isPattern) {
dateFormat = DateFormat.getDateInstance({
calendarType: this._calendarType,
pattern: this._formatPattern,
});
} else {
dateFormat = DateFormat.getDateInstance({
calendarType: this._calendarType,
style: this._formatPattern,
});
}
return dateFormat;
}
formatValue(date: Date) {
return this.getFormat().format(date);
}
_componentKey(name: string) {
type ComponentKey = keyof typeof this._componentMap;
return name as ComponentKey;
}
_indexFromName(name: string) {
return this._componentMap[this._componentKey(name)];
}
/**
* Returns name of the clock or button from the id of the event target.
* @returns name of the clock/button
*/
_getNameFromId(id: string): string | undefined {
const parts = id.split("_");
return parts.length ? parts[parts.length - 1] : undefined;
}
/**
* Returns index of the clock or button from the id of the event target.
* @returns index of the clock/button
*/
_getIndexFromId(id: string): number {
const name = this._getNameFromId(id);
return name ? this._indexFromName(name) : 0;
}
/**
* Changes hours value.
* @param hours new hours value
*/
_hoursChange(hours: number) {
if (this._hoursConfiguration.isTwelveHoursFormat) {
hours = this._shiftHours(hours);
}
const date = this.validDateValue;
date.setHours(hours);
this.setValue(date);
}
/**
* Changes minutes value.
* @param minutes new minutes value
*/
_minutesChange(minutes: number) {
const date = this.validDateValue;
date.setMinutes(minutes);
this.setValue(date);
}
/**
* Changes seconds value.
* @param seconds new seconds value
*/
_secondsChange(seconds: number) {
const date = this.validDateValue;
date.setSeconds(seconds);
this.setValue(date);
}
_buttonAmPm() {
return this._hasPeriodsComponent ? this.shadowRoot?.querySelector<SegmentedButton>(`#${this._id}_AmPm`) : undefined;
}
_createPeriodComponent() {
if (this._hasPeriodsComponent) {
// add period item
this.periodsArray.forEach(item => {
this._periods.push({
"label": item,
"selected": this._period === item,
});
});
}
}
_periodChange(evt: PointerEvent) {
const periodItem = evt.target;
if (periodItem) {
const period = (periodItem as HTMLElement).textContent;
this._calculatePeriodChange(period as string);
}
}
_calculatePeriodChange(period: string) {
const date = this.validDateValue;
if (period === this._periods[0].label && date.getHours() >= 12) {
date.setHours(date.getHours() - 12);
} if (period === this._periods[1].label && date.getHours() < 12) {
date.setHours(date.getHours() + 12);
}
this.setValue(date);
}
/**
* Shifts hours value with +/- 12 depending on hour value and day period.
* @param hours current hours
* @returns shifted hours
*/
_shiftHours(hours: number): number {
if (this._period === this.periodsArray[0]) { // AM
hours = hours === 12 ? 0 : hours;
} else if (this._period === this.periodsArray[1]) { // PM
hours = hours === 12 ? hours : hours + 12;
}
return hours;
}
/**
* Clears the currently existing cooldown period and starts new one if requested.
* @param startNewCooldown whether to start new cooldown period after clearing previous one
*/
_resetCooldown(startNewCooldown: boolean) {
if (!TYPE_COOLDOWN_DELAY) {
return; // if delay is 0, cooldown is disabled
}
if (this._typeCooldownId) {
clearTimeout(this._typeCooldownId);
}
if (startNewCooldown) {
this._startCooldown();
}
}
/**
* Starts new cooldown period.
*/
_startCooldown() {
if (!TYPE_COOLDOWN_DELAY) {
return; // if delay is 0, cooldown is disabled
}
this._typeCooldownId = setTimeout(() => {
this._keyboardBuffer = "";
this._typeCooldownId = undefined;
if (this._exactMatch) {
this._setExactMatch();
this._exactMatch = undefined;
}
}, TYPE_COOLDOWN_DELAY);
}
/**
* Sets the exact match value. Override if necessary.
*/
_setExactMatch() {}
}
export default TimePickerInternals;
export type {
TimePickerComponentIndexMap,
TimeSelectionChangeEventDetail,
};