@dile/ui 3.23.0 → 3.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/components/checkbox/src/DileCheckbox.js +14 -5
  2. package/components/drop-file/src/DileDropFile.js +5 -3
  3. package/components/input/index.js +1 -1
  4. package/components/input/src/DileInput.js +9 -3
  5. package/components/input/src/DileInputMask.js +16 -0
  6. package/components/input/src/DileInputSearch.js +2 -0
  7. package/components/input/src/label-styles.js +15 -0
  8. package/components/input-suggestions/src/DileInputSuggestionsBase.js +6 -3
  9. package/components/number-picker/src/DileNumberPicker.js +6 -3
  10. package/components/number-picker/src/DileNumberPickerElement.js +2 -0
  11. package/components/order-switch/src/DileOrderSwitch.js +18 -2
  12. package/components/otp-input/src/DileOtpInput.js +6 -3
  13. package/components/radio-group/src/DileRadioGroup.js +6 -3
  14. package/components/rating-scale-question/src/DileRatingScaleQuestion.js +35 -3
  15. package/components/select/src/DileSelect.js +12 -4
  16. package/components/select/src/DileSelectAjax.js +8 -3
  17. package/components/select/src/DileSelectBoolean.js +9 -2
  18. package/components/select/src/DileSelectOverlay.js +6 -3
  19. package/components/select/src/DileSelectSearchableBase.js +8 -3
  20. package/components/switch/src/DileSwitch.js +3 -1
  21. package/components/textarea/src/DileTextarea.js +7 -3
  22. package/components/time-picker/src/DileTimePicker.js +680 -126
  23. package/components/wheel-picker/src/DileWheelPicker.js +17 -2
  24. package/lib/time/time.js +171 -0
  25. package/lib/time/time.test.js +63 -0
  26. package/mixins/form/index.js +2 -1
  27. package/mixins/form/src/DileForm.js +240 -1
  28. package/mixins/form/src/DileNativeValidity.js +195 -0
  29. package/mixins/overlay/src/DileOverlay.js +16 -0
  30. package/package.json +2 -2
@@ -1,170 +1,724 @@
1
- import { LitElement, html, css } from 'lit';
2
- import { DileEmmitChange, FIELD_MESSAGE_ID } from '../../../mixins/form/index.js';
3
- import '../../number-picker/number-picker-element.js';
4
- import { labelStyles } from '../../input/src/label-styles.js';
5
- import { messageStyles } from '../../input/src/message-styles.js';
6
-
7
- export class DileTimePicker extends DileEmmitChange(LitElement) {
8
- static styles = [
9
- labelStyles,
10
- messageStyles,
11
- css`
12
- :host {
13
- display: block;
14
- margin-bottom: 10px;
15
- }
16
- section {
17
- display: flex;
18
- gap: 0.5rem;
19
- }
20
- `
21
- ];
1
+ import { html, css, nothing } from 'lit';
2
+ import { DileInputIcon } from '../../input/src/DileInputIcon.js';
3
+ import '@dile/iconlib/lucide-icons/clock.js';
4
+ import '../../menu-overlay/menu-overlay.js';
5
+ import '../../wheel-picker/wheel-picker.js';
6
+ import '../../icon/icon.js';
7
+ import { doneIcon } from '@dile/icons';
8
+ import {
9
+ parseTime,
10
+ formatTime,
11
+ formatTime12,
12
+ toSeconds,
13
+ fromSeconds,
14
+ checkTimeRange,
15
+ validStep,
16
+ stepValues,
17
+ } from '../../../lib/time/time.js';
18
+
19
+ const VALIDATION_MESSAGES = {
20
+ en: {
21
+ invalid: 'Enter a valid time, for example {example}.',
22
+ beforeMin: 'The time must be {min} or later.',
23
+ afterMax: 'The time must be {max} or earlier.',
24
+ outOfRange: 'The time must be between {min} and {max}.',
25
+ },
26
+ es: {
27
+ invalid: 'Introduce una hora válida, por ejemplo {example}.',
28
+ beforeMin: 'La hora debe ser igual o posterior a las {min}.',
29
+ afterMax: 'La hora debe ser igual o anterior a las {max}.',
30
+ outOfRange: 'La hora debe estar entre las {min} y las {max}.',
31
+ },
32
+ ca: {
33
+ invalid: 'Introdueix una hora vàlida, per exemple {example}.',
34
+ beforeMin: 'L’hora ha de ser igual o posterior a les {min}.',
35
+ afterMax: 'L’hora ha de ser igual o anterior a les {max}.',
36
+ outOfRange: 'L’hora ha d’estar entre les {min} i les {max}.',
37
+ },
38
+ fr: {
39
+ invalid: 'Saisissez une heure valide, par exemple {example}.',
40
+ beforeMin: 'L’heure doit être {min} ou plus tard.',
41
+ afterMax: 'L’heure doit être {max} ou plus tôt.',
42
+ outOfRange: 'L’heure doit être comprise entre {min} et {max}.',
43
+ },
44
+ de: {
45
+ invalid: 'Geben Sie eine gültige Uhrzeit ein, z. B. {example}.',
46
+ beforeMin: 'Die Uhrzeit muss {min} oder später sein.',
47
+ afterMax: 'Die Uhrzeit muss {max} oder früher sein.',
48
+ outOfRange: 'Die Uhrzeit muss zwischen {min} und {max} liegen.',
49
+ },
50
+ };
51
+
52
+ const SECONDS_PER_DAY = 24 * 60 * 60;
53
+
54
+ function deepActiveElement() {
55
+ let active = document.activeElement;
56
+ while (active?.shadowRoot?.activeElement) {
57
+ active = active.shadowRoot.activeElement;
58
+ }
59
+ return active;
60
+ }
22
61
 
23
- static get formAssociated() {
24
- return true;
62
+ export class DileTimePicker extends DileInputIcon {
63
+ static get styles() {
64
+ return [
65
+ ...super.styles,
66
+ css`
67
+ dile-menu-overlay {
68
+ display: flex;
69
+ align-items: center;
70
+ --dile-menu-overlay-width: var(--dile-time-picker-width, max-content);
71
+ --dile-menu-overlay-max-width: var(--dile-time-picker-max-width, 360px);
72
+ }
73
+ .trigger-container {
74
+ display: flex;
75
+ align-items: center;
76
+ }
77
+ .input-icon-btn {
78
+ --dile-input-icon-color: var(--dile-time-picker-trigger-color, var(--dile-on-background-color, #303030));
79
+ --dile-input-icon-size: var(--dile-time-picker-trigger-size, 20px);
80
+ --dile-input-icon-background-color: var(--dile-time-picker-trigger-background-color, transparent);
81
+ --dile-input-icon-hover-background-color: var(--dile-time-picker-trigger-hover-background-color, var(--dile-input-icon-hover-bg, rgba(0, 0, 0, 0.05)));
82
+ }
83
+ .input-icon-btn:disabled {
84
+ --dile-input-icon-color: var(--dile-time-picker-trigger-disabled-color, #ccc);
85
+ }
86
+ .time-panel {
87
+ display: flex;
88
+ flex-direction: column;
89
+ align-items: center;
90
+ gap: 0.5rem;
91
+ padding: var(--dile-time-picker-panel-padding, 0.75rem);
92
+ color: var(--dile-time-picker-text-color, var(--dile-on-background-color, #303030));
93
+ --dile-wheel-picker-width: var(--dile-time-picker-wheel-width, 4rem);
94
+ --dile-wheel-picker-item-height: var(--dile-time-picker-wheel-item-height, 36px);
95
+ --dile-wheel-picker-font-size: var(--dile-time-picker-wheel-font-size, 1.1rem);
96
+ --dile-wheel-picker-text-color: var(--dile-time-picker-wheel-text-color, color-mix(in srgb, var(--dile-time-picker-text-color, var(--dile-on-background-color, #303030)) 55%, transparent));
97
+ --dile-wheel-picker-selected-text-color: var(--dile-time-picker-wheel-selected-text-color, var(--dile-time-picker-text-color, var(--dile-on-background-color, #303030)));
98
+ --dile-wheel-picker-band-background-color: var(--dile-time-picker-wheel-band-background-color, rgba(90, 90, 90, 0.08));
99
+ }
100
+ .time-columns {
101
+ display: flex;
102
+ align-items: center;
103
+ gap: 0.25rem;
104
+ }
105
+ .time-separator {
106
+ font-size: var(--dile-time-picker-wheel-font-size, 1.1rem);
107
+ }
108
+ .meridiem-wheel {
109
+ --dile-wheel-picker-width: var(--dile-time-picker-meridiem-wheel-width, 4.5rem);
110
+ }
111
+ .time-actions {
112
+ display: flex;
113
+ align-items: center;
114
+ justify-content: center;
115
+ gap: 1rem;
116
+ width: 100%;
117
+ }
118
+ .now-button {
119
+ min-height: 30px;
120
+ padding: 0 0.75rem;
121
+ border: 1px solid var(--dile-time-picker-now-border-color, color-mix(in srgb, currentColor 35%, transparent));
122
+ border-radius: var(--dile-time-picker-now-border-radius, 15px);
123
+ background: transparent;
124
+ color: inherit;
125
+ font: inherit;
126
+ font-size: 0.9rem;
127
+ cursor: pointer;
128
+ }
129
+ .now-button:hover:not(:disabled) {
130
+ background-color: rgba(90, 90, 90, 0.08);
131
+ }
132
+ .now-button:disabled {
133
+ opacity: 0.4;
134
+ cursor: default;
135
+ }
136
+ .accept-button {
137
+ display: flex;
138
+ align-items: center;
139
+ justify-content: center;
140
+ background: transparent;
141
+ border: none;
142
+ padding: 0;
143
+ margin: 0;
144
+ cursor: pointer;
145
+ border-radius: 50%;
146
+ }
147
+ .now-button:focus-visible,
148
+ .accept-button:focus-visible {
149
+ outline: 2px solid var(--dile-time-picker-focus-ring-color, var(--dile-primary-color, #2563eb));
150
+ outline-offset: 2px;
151
+ }
152
+ .accept-button dile-icon {
153
+ --dile-icon-size: var(--dile-time-picker-accept-icon-size, 24px);
154
+ --dile-icon-color: var(--dile-time-picker-accept-icon-color, var(--dile-on-primary-color, #fff));
155
+ --dile-icon-rounded-background-color: var(--dile-time-picker-accept-icon-background-color, var(--dile-primary-color, #2563eb));
156
+ }
157
+ `
158
+ ];
25
159
  }
26
160
 
27
161
  static get properties() {
28
162
  return {
29
- value: { type: String },
30
- _hours: { type: String, state: true },
31
- _minutes: { type: String, state: true },
32
- _seconds: { type: String, state: true },
33
-
34
- label: { type: String },
35
- disabled: { type: Boolean },
36
- message: { type: String },
37
- errored: { type: Boolean },
38
- hideErrorOnInput: { type: Boolean },
39
- focusOnStart: { type: Boolean },
40
- name: { type: String, reflect: true },
163
+ ...super.properties,
164
+ /** Shows the seconds wheel and uses the "HH:mm:ss" format */
165
+ showSeconds: { type: Boolean },
166
+ /** Step between the values of the minutes wheel */
167
+ minuteStep: { type: Number },
168
+ /** Step between the values of the seconds wheel */
169
+ secondStep: { type: Number },
170
+ /** Earliest valid time ("HH:mm" or "HH:mm:ss") */
171
+ min: { type: String },
172
+ /** Latest valid time ("HH:mm" or "HH:mm:ss"). When it is earlier than min, the range goes through midnight */
173
+ max: { type: String },
174
+ /** "24" or "12". With "12" the field and the wheels use the AM/PM notation; the value is always in 24-hour notation */
175
+ hourCycle: { type: String },
176
+ amLabel: { type: String },
177
+ pmLabel: { type: String },
178
+ /** Shows a button to choose the current time */
179
+ showNow: { type: Boolean },
180
+ nowLabel: { type: String },
181
+ acceptLabel: { type: String },
182
+ /** Validates the value on blur and when a time is chosen, showing an error message */
183
+ validateTime: { type: Boolean },
184
+ validationMessages: { type: Object },
185
+ /** Locale used for the accessible names of the wheels and for the validation messages */
186
+ locale: { type: String },
187
+ horizontalAlign: { type: String },
188
+ verticalAlign: { type: String },
189
+ moveTop: { type: Number },
190
+ moveLeft: { type: Number },
191
+ opened: { type: Boolean },
192
+ _draft: { state: true },
193
+ _displayText: { state: true },
41
194
  };
42
195
  }
43
196
 
44
197
  constructor() {
45
198
  super();
46
- this.value = "00:00:00";
47
- this._setFromValue(this.value);
48
- this.internals = this.attachInternals();
199
+ this.icon = 'lucide.clock';
200
+ this.iconLabel = 'Choose time';
201
+ this.showSeconds = false;
202
+ this.minuteStep = 1;
203
+ this.secondStep = 1;
204
+ this.min = '';
205
+ this.max = '';
206
+ this.hourCycle = '24';
207
+ this.amLabel = 'AM';
208
+ this.pmLabel = 'PM';
209
+ this.showNow = false;
210
+ this.nowLabel = 'Now';
211
+ this.acceptLabel = 'Accept time';
212
+ this.validateTime = false;
213
+ this.validationMessages = {};
214
+ this.horizontalAlign = 'under_right';
215
+ this.verticalAlign = 'center';
216
+ this.moveTop = 0;
217
+ this.moveLeft = 0;
218
+ this.opened = false;
219
+ this._draft = undefined;
220
+ this._displayText = '';
221
+ }
222
+
223
+ get is12h() {
224
+ return String(this.hourCycle) === '12';
225
+ }
226
+
227
+ get meridiemLabels() {
228
+ return { amLabel: this.amLabel, pmLabel: this.pmLabel };
229
+ }
230
+
231
+ get menu() {
232
+ return this.shadowRoot.getElementById('menu');
233
+ }
234
+
235
+ /**
236
+ * Time of the current value, or undefined when the value is empty or not a valid time.
237
+ * @returns {{hours: number, minutes: number, seconds: number}|undefined}
238
+ */
239
+ get time() {
240
+ return parseTime(this.value, this.meridiemLabels);
241
+ }
242
+
243
+ /** Time selected in the wheels, as "HH:mm" or "HH:mm:ss". Undefined while the picker is closed */
244
+ get selectedTime() {
245
+ return this._draft ? this.timeToValue(this._draft) : undefined;
246
+ }
247
+
248
+ willUpdate(changedProperties) {
249
+ super.willUpdate?.(changedProperties);
250
+ if (changedProperties.has('min') || changedProperties.has('max')) {
251
+ this._min = parseTime(this.min);
252
+ this._max = parseTime(this.max);
253
+ }
254
+ const formatChanged = changedProperties.has('hourCycle') || changedProperties.has('showSeconds')
255
+ || changedProperties.has('amLabel') || changedProperties.has('pmLabel');
256
+ if ((changedProperties.has('value') && this.value !== this._valueFromTyping) || formatChanged) {
257
+ this._displayText = this.displayValue(this.value);
258
+ }
259
+ }
260
+
261
+ // ---- Text field ----
262
+
263
+ computeValue() {
264
+ return this._displayText;
265
+ }
266
+
267
+ /**
268
+ * Text shown in the field for a value: the time in the format of the component,
269
+ * or the value itself when it is not a valid time.
270
+ */
271
+ displayValue(value) {
272
+ const time = parseTime(value, this.meridiemLabels);
273
+ if (!time) {
274
+ return value ?? '';
275
+ }
276
+ return this.is12h
277
+ ? formatTime12(time, this.showSeconds, this.meridiemLabels)
278
+ : formatTime(time, this.showSeconds);
279
+ }
280
+
281
+ /** Value for a time: "HH:mm" or "HH:mm:ss" */
282
+ timeToValue(time) {
283
+ return formatTime(time, this.showSeconds);
284
+ }
285
+
286
+ _input(e) {
287
+ const text = e.target.value;
288
+ const time = parseTime(text, this.meridiemLabels);
289
+ const value = text.trim() === '' ? '' : time ? this.timeToValue(time) : text;
290
+ this._displayText = text;
291
+ this._valueFromTyping = value;
292
+ this.value = value;
293
+ if (this.hideErrorOnInput && this.errored) {
294
+ this.clearError();
295
+ }
296
+ }
297
+
298
+ doKeydown(e) {
299
+ if (e.key === 'ArrowDown' && e.altKey) {
300
+ e.preventDefault();
301
+ this.open();
302
+ } else if (e.key === 'Enter') {
303
+ this.normalizeText();
304
+ }
305
+ }
306
+
307
+ doBlur(e) {
308
+ super.doBlur?.(e);
309
+ this.normalizeText();
310
+ }
311
+
312
+ /** Rewrites the text of the field in the format of the component, when it is a valid time */
313
+ normalizeText() {
314
+ this._valueFromTyping = undefined;
315
+ if (this.time) {
316
+ this._displayText = this.displayValue(this.value);
317
+ }
318
+ if (this.validateTime) {
319
+ this.validate();
320
+ }
321
+ }
322
+
323
+ // ---- Validation ----
324
+
325
+ /**
326
+ * Checks the current value without changing the component state.
327
+ * An empty value is valid (use your form validation to make it required).
328
+ * @returns {{valid: boolean, reason?: 'invalid'|'beforeMin'|'afterMax'|'outOfRange', time?: object}}
329
+ */
330
+ getTimeValidation(value = this.value) {
331
+ if (value === undefined || value === null || String(value).trim() === '') {
332
+ return { valid: true };
333
+ }
334
+ const time = parseTime(value, this.meridiemLabels);
335
+ if (!time) {
336
+ return { valid: false, reason: 'invalid' };
337
+ }
338
+ const range = checkTimeRange(time, this._min, this._max);
339
+ return range === true ? { valid: true, time } : { valid: false, reason: range, time };
340
+ }
341
+
342
+ /**
343
+ * Error of the current value, without changing the component state (used by DileForm).
344
+ * Works regardless of validateTime. An empty value is valid.
345
+ * @returns {string} the error message, or '' when the value is valid
346
+ */
347
+ getValidationError() {
348
+ const result = this.getTimeValidation();
349
+ return result.valid ? '' : this.getValidationMessage(result.reason);
350
+ }
351
+
352
+ /**
353
+ * Validates the current value, showing or removing the error message.
354
+ * @returns {boolean} true when the value is valid
355
+ */
356
+ validate() {
357
+ const result = this.getTimeValidation();
358
+ if (result.valid) {
359
+ if (this._timeErrorShown) {
360
+ this.errored = Boolean(this._stateBeforeTimeError.errored);
361
+ this.message = this._stateBeforeTimeError.message ?? '';
362
+ this._timeErrorShown = false;
363
+ }
364
+ this.updateValidity();
365
+ return true;
366
+ }
367
+ if (!this._timeErrorShown) {
368
+ this._stateBeforeTimeError = { errored: this.errored, message: this.message };
369
+ this._timeErrorShown = true;
370
+ }
371
+ this.errored = true;
372
+ this.message = this.getValidationMessage(result.reason);
373
+ this.updateValidity();
374
+ return false;
375
+ }
376
+
377
+ /**
378
+ * @param {'invalid'|'beforeMin'|'afterMax'|'outOfRange'} reason
379
+ * @returns {string}
380
+ */
381
+ getValidationMessage(reason) {
382
+ const language = (this.locale || document.documentElement.lang || 'en').slice(0, 2).toLowerCase();
383
+ const messages = { ...VALIDATION_MESSAGES.en, ...VALIDATION_MESSAGES[language], ...this.validationMessages };
384
+ const show = (time) => (time ? this.displayValue(formatTime(time, true)) : '');
385
+ return String(messages[reason] || '')
386
+ .replace('{min}', show(this._min))
387
+ .replace('{max}', show(this._max))
388
+ .replace('{example}', show({ hours: 14, minutes: 30, seconds: 0 }));
49
389
  }
50
390
 
51
- render() {
391
+ clearError() {
392
+ super.clearError();
393
+ this._timeErrorShown = false;
394
+ }
395
+
396
+ formResetCallback() {
397
+ this._valueFromTyping = undefined;
398
+ this.close();
399
+ super.formResetCallback();
400
+ this.updateValidity();
401
+ }
402
+
403
+ // ---- Overlay ----
404
+
405
+ renderIconButton() {
406
+ if (this.isDisabled || this.readonly) {
407
+ return super.renderIconButton();
408
+ }
52
409
  return html`
53
- <main>
54
- ${this.label ? html`<label>${this.label}</label>` : ''}
55
- <section class="for-input">
56
- <dile-number-picker-element
57
- min="0"
58
- max="23"
59
- step="1"
60
- digits="2"
61
- leadingZeros
62
- .value=${this._hours}
63
- ?disabled=${this.disabled}
64
- ?errored=${this.errored}
65
- .accessibleDescription=${this.message || undefined}
66
- ?focusOnStart=${this.focusOnStart}
67
- @dile-number-picker-value-changed=${this._changeHours}
68
- ></dile-number-picker-element>
69
- <dile-number-picker-element
70
- min="0"
71
- max="59"
72
- step="5"
73
- digits="2"
74
- leadingZeros
75
- .value=${this._minutes}
76
- ?disabled=${this.disabled}
77
- ?errored=${this.errored}
78
- .accessibleDescription=${this.message || undefined}
79
- @dile-number-picker-value-changed=${this._changeMinutes}
80
- ></dile-number-picker-element>
81
- <dile-number-picker-element
82
- min="0"
83
- max="59"
84
- step="5"
85
- digits="2"
86
- leadingZeros
87
- .value=${this._seconds}
88
- ?disabled=${this.disabled}
89
- ?errored=${this.errored}
90
- .accessibleDescription=${this.message || undefined}
91
- @dile-number-picker-value-changed=${this._changeSeconds}
92
- ></dile-number-picker-element>
93
- </section>
94
- ${this.messageTemplate}
95
- </main>
410
+ <dile-menu-overlay
411
+ moveTop="${this.moveTop}"
412
+ moveLeft="${this.moveLeft}"
413
+ verticalAlign="${this.verticalAlign}"
414
+ horizontalAlign="${this.horizontalAlign}"
415
+ id="menu"
416
+ @overlay-opened="${this.overlayOpenedHandler}"
417
+ @overlay-ready="${this.overlayReadyHandler}"
418
+ @overlay-closed="${this.overlayClosedHandler}"
419
+ >
420
+ <div slot="trigger" class="trigger-container">
421
+ ${super.renderIconButton()}
422
+ </div>
423
+ <div slot="content" class="content">
424
+ ${this.opened ? this.panelTemplate : nothing}
425
+ </div>
426
+ </dile-menu-overlay>
96
427
  `;
97
428
  }
98
429
 
99
- get messageTemplate() {
430
+ get buttonTemplate() {
431
+ return html`<button
432
+ class="input-icon-btn"
433
+ type="button"
434
+ @click="${this._handleIconClick}"
435
+ ?disabled="${this.isDisabled || this.readonly}"
436
+ aria-label="${this.iconLabel || this.tooltip}"
437
+ aria-haspopup="dialog"
438
+ aria-expanded="${this.opened ? 'true' : 'false'}"
439
+ >
440
+ ${this.iconTemplate}
441
+ </button>`;
442
+ }
443
+
444
+ get panelTemplate() {
445
+ const draft = this._draft;
446
+ if (!draft) {
447
+ return nothing;
448
+ }
449
+ const nowTime = this.nowTime();
100
450
  return html`
101
- ${this.message
102
- ? html`<div id="${FIELD_MESSAGE_ID}" class="message ${this.errored ? 'errored-msg' : ''}"><span>${this.message}</span></div>`
103
- : ''
104
- }
105
- `
451
+ <div
452
+ class="time-panel"
453
+ role="group"
454
+ aria-label="${this.label || this.accessibleLabel || this.fieldLabel('time')}"
455
+ @keydown=${this.panelKeydown}
456
+ @dile-wheel-picker-changed=${this.stopInnerEvent}
457
+ @element-changed=${this.stopInnerEvent}
458
+ >
459
+ <div class="time-columns">
460
+ ${this.hoursWheelTemplate(draft)}
461
+ <span class="time-separator" aria-hidden="true">:</span>
462
+ <dile-wheel-picker
463
+ class="minutes-wheel"
464
+ label="${this.fieldLabel('minute')}"
465
+ .items="${this.minuteItems(draft)}"
466
+ .value="${draft.minutes}"
467
+ @dile-wheel-picker-changed=${(e) => this.setTimePart('minutes', e.detail.value)}
468
+ ></dile-wheel-picker>
469
+ ${this.showSeconds ? html`
470
+ <span class="time-separator" aria-hidden="true">:</span>
471
+ <dile-wheel-picker
472
+ class="seconds-wheel"
473
+ label="${this.fieldLabel('second')}"
474
+ .items="${this.secondItems(draft)}"
475
+ .value="${draft.seconds}"
476
+ @dile-wheel-picker-changed=${(e) => this.setTimePart('seconds', e.detail.value)}
477
+ ></dile-wheel-picker>
478
+ ` : nothing}
479
+ ${this.is12h ? html`
480
+ <dile-wheel-picker
481
+ class="meridiem-wheel"
482
+ label="${this.fieldLabel('dayPeriod')}"
483
+ .items="${this.meridiemItems()}"
484
+ .value="${draft.hours < 12 ? 'am' : 'pm'}"
485
+ @dile-wheel-picker-changed=${(e) => this.setTimePart('meridiem', e.detail.value)}
486
+ ></dile-wheel-picker>
487
+ ` : nothing}
488
+ </div>
489
+ <div class="time-actions">
490
+ ${this.showNow ? html`
491
+ <button
492
+ type="button"
493
+ class="now-button"
494
+ ?disabled="${!this.isAllowed(nowTime)}"
495
+ @click=${this.selectNow}
496
+ >${this.nowLabel}</button>
497
+ ` : nothing}
498
+ <button
499
+ type="button"
500
+ class="accept-button"
501
+ aria-label="${this.acceptLabel}"
502
+ title="${this.acceptLabel}"
503
+ @click=${this.accept}
504
+ >
505
+ <dile-icon rounded .icon=${doneIcon}></dile-icon>
506
+ </button>
507
+ </div>
508
+ </div>
509
+ `;
510
+ }
511
+
512
+ hoursWheelTemplate(draft) {
513
+ const items = this.is12h
514
+ ? [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].map((hour) => ({
515
+ value: hour,
516
+ label: String(hour).padStart(2, '0'),
517
+ disabled: !this.hourAllowed((hour % 12) + (draft.hours < 12 ? 0 : 12)),
518
+ }))
519
+ : stepValues(23, 1).map((hour) => ({
520
+ value: hour,
521
+ label: String(hour).padStart(2, '0'),
522
+ disabled: !this.hourAllowed(hour),
523
+ }));
524
+ const value = this.is12h ? (draft.hours % 12 || 12) : draft.hours;
525
+ return html`
526
+ <dile-wheel-picker
527
+ class="hours-wheel"
528
+ label="${this.fieldLabel('hour')}"
529
+ .items="${items}"
530
+ .value="${value}"
531
+ @dile-wheel-picker-changed=${(e) => this.setTimePart('hours', e.detail.value)}
532
+ ></dile-wheel-picker>
533
+ `;
106
534
  }
107
535
 
108
- get hoursEl() {
109
- return this.shadowRoot.querySelectorAll('dile-number-picker-element')[0];
536
+ get minuteValues() {
537
+ return stepValues(59, validStep(this.minuteStep));
110
538
  }
111
539
 
112
- willUpdate(changedProperties) {
113
- if (changedProperties.has('value')) {
114
- this._setFromValue(this.value);
540
+ get secondValues() {
541
+ return this.showSeconds ? stepValues(59, validStep(this.secondStep)) : [0];
542
+ }
543
+
544
+ /** Wheel items with the given values. A current value out of the step is also included */
545
+ _wheelItems(values, current, isDisabled) {
546
+ const all = values.includes(current) ? values : [...values, current].sort((a, b) => a - b);
547
+ return all.map((value) => ({
548
+ value,
549
+ label: String(value).padStart(2, '0'),
550
+ disabled: isDisabled(value),
551
+ }));
552
+ }
553
+
554
+ minuteItems(draft) {
555
+ return this._wheelItems(this.minuteValues, draft.minutes, (minute) => !this.minuteAllowed(draft.hours, minute));
556
+ }
557
+
558
+ secondItems(draft) {
559
+ return this._wheelItems(this.secondValues, draft.seconds,
560
+ (second) => !this.isAllowed({ hours: draft.hours, minutes: draft.minutes, seconds: second }));
561
+ }
562
+
563
+ meridiemItems() {
564
+ const halfAllowed = (offset) => stepValues(11, 1).some((hour) => this.hourAllowed(hour + offset));
565
+ return [
566
+ { value: 'am', label: this.amLabel, disabled: !halfAllowed(0) },
567
+ { value: 'pm', label: this.pmLabel, disabled: !halfAllowed(12) },
568
+ ];
569
+ }
570
+
571
+ // ---- Range checks of the wheels ----
572
+
573
+ get hasRange() {
574
+ return Boolean(this._min || this._max);
575
+ }
576
+
577
+ isAllowed(time) {
578
+ return !this.hasRange || checkTimeRange(time, this._min, this._max) === true;
579
+ }
580
+
581
+ minuteAllowed(hours, minutes) {
582
+ return !this.hasRange || this.secondValues.some((seconds) => this.isAllowed({ hours, minutes, seconds }));
583
+ }
584
+
585
+ hourAllowed(hours) {
586
+ return !this.hasRange || this.minuteValues.some((minutes) => this.minuteAllowed(hours, minutes));
587
+ }
588
+
589
+ /**
590
+ * Nearest time to the given one that can be chosen in the wheels and is inside the range.
591
+ * @returns {object} the same time when it is allowed
592
+ */
593
+ nearestAllowedTime(time) {
594
+ if (this.isAllowed(time)) {
595
+ return time;
596
+ }
597
+ const minutes = this.minuteValues;
598
+ const seconds = this.secondValues;
599
+ const base = toSeconds(time);
600
+ for (let offset = 1; offset < SECONDS_PER_DAY; offset++) {
601
+ for (const candidate of [base + offset, base - offset]) {
602
+ if (candidate < 0 || candidate >= SECONDS_PER_DAY) {
603
+ continue;
604
+ }
605
+ const t = fromSeconds(candidate);
606
+ if (minutes.includes(t.minutes) && seconds.includes(t.seconds) && this.isAllowed(t)) {
607
+ return t;
608
+ }
609
+ }
115
610
  }
611
+ return time;
612
+ }
613
+
614
+ /** Current time, with the minutes rounded down to the minuteStep (and the seconds too, when shown) */
615
+ nowTime() {
616
+ const now = new Date();
617
+ const minuteStep = validStep(this.minuteStep);
618
+ const secondStep = validStep(this.secondStep);
619
+ return {
620
+ hours: now.getHours(),
621
+ minutes: Math.floor(now.getMinutes() / minuteStep) * minuteStep,
622
+ seconds: this.showSeconds ? Math.floor(now.getSeconds() / secondStep) * secondStep : 0,
623
+ };
116
624
  }
117
625
 
118
- updated(changedProperties) {
119
- if(changedProperties.has('value')) {
120
- this.emmitChange();
121
- this.internals.setFormValue(this.value);
626
+ setTimePart(part, value) {
627
+ const draft = { ...this._draft };
628
+ if (part === 'hours') {
629
+ draft.hours = this.is12h ? (Number(value) % 12) + (draft.hours < 12 ? 0 : 12) : Number(value);
630
+ } else if (part === 'meridiem') {
631
+ draft.hours = (draft.hours % 12) + (value === 'pm' ? 12 : 0);
632
+ } else {
633
+ draft[part] = Number(value);
122
634
  }
635
+ this._draft = this.nearestAllowedTime(draft);
123
636
  }
124
637
 
125
- _changeHours(e) {
126
- this._hours = this._normalize(e.detail);
127
- this._updateValue();
128
- if (this.hideErrorOnInput && this.errored) this.clearError();
638
+ overlayOpenedHandler() {
639
+ this._focusBeforeOpen = deepActiveElement();
640
+ const time = this.time ?? this.nowTime();
641
+ this._draft = this.nearestAllowedTime({ ...time, seconds: this.showSeconds ? time.seconds : 0 });
642
+ this.opened = true;
129
643
  }
130
644
 
131
- _changeMinutes(e) {
132
- this._minutes = this._normalize(e.detail);
133
- this._updateValue();
134
- if (this.hideErrorOnInput && this.errored) this.clearError();
645
+ async overlayReadyHandler() {
646
+ await this.updateComplete;
647
+ const wheel = this.shadowRoot.querySelector('.hours-wheel');
648
+ await wheel?.updateComplete;
649
+ wheel?.focus();
135
650
  }
136
651
 
137
- _changeSeconds(e) {
138
- this._seconds = this._normalize(e.detail);
139
- this._updateValue();
140
- if (this.hideErrorOnInput && this.errored) this.clearError();
652
+ overlayClosedHandler() {
653
+ const focusInside = this.shadowRoot.activeElement?.closest('.content');
654
+ this.opened = false;
655
+ this._draft = undefined;
656
+ if (focusInside) {
657
+ const previous = this._focusBeforeOpen;
658
+ const target = previous?.isConnected && previous !== document.body
659
+ ? previous
660
+ : this.shadowRoot.querySelector('.input-icon-btn');
661
+ target?.focus();
662
+ }
141
663
  }
142
664
 
143
- _normalize(value) {
144
- const num = parseInt(value, 10);
145
- return isNaN(num) ? '00' : num.toString().padStart(2, '0');
665
+ panelKeydown(e) {
666
+ if (e.key === 'Enter' && !e.target.closest?.('button')) {
667
+ e.preventDefault();
668
+ this.accept();
669
+ }
146
670
  }
147
671
 
148
- _setFromValue(value) {
149
- const parts = (value || '00:00:00').split(':');
150
- this._hours = this._normalize(parts[0]);
151
- this._minutes = this._normalize(parts[1]);
152
- this._seconds = this._normalize(parts[2]);
672
+ // The inner wheels are not fields of the form: their changes must not leave the component.
673
+ stopInnerEvent(e) {
674
+ e.stopPropagation();
153
675
  }
154
676
 
155
- _updateValue() {
156
- const newValue = `${this._hours}:${this._minutes}:${this._seconds}`;
157
- if (this.value !== newValue) {
158
- this.value = newValue;
677
+ /** Writes the time selected in the wheels in the value and closes the picker */
678
+ accept() {
679
+ if (this._draft) {
680
+ this.setTime(this._draft);
159
681
  }
682
+ this.close();
160
683
  }
161
684
 
162
- focus() {
163
- this.hoursEl.focus();
685
+ /** Writes the current time in the value and closes the picker */
686
+ selectNow() {
687
+ this.setTime(this.nowTime());
688
+ this.close();
164
689
  }
165
690
 
166
- clearError() {
167
- this.errored = false;
168
- this.message = '';
691
+ setTime(time) {
692
+ this._valueFromTyping = undefined;
693
+ this.value = this.timeToValue(time);
694
+ if (this.hideErrorOnInput && this.errored) {
695
+ this.clearError();
696
+ }
697
+ if (this.validateTime) {
698
+ this.validate();
699
+ }
700
+ }
701
+
702
+ /** Opens the picker */
703
+ open() {
704
+ this.menu?.open();
705
+ }
706
+
707
+ /** Closes the picker without changing the value */
708
+ close() {
709
+ this.menu?.close();
710
+ }
711
+
712
+ fieldLabel(field) {
713
+ const fallback = { hour: 'Hour', minute: 'Minute', second: 'Second', dayPeriod: 'AM/PM', time: 'Time' }[field];
714
+ if (field === 'time') {
715
+ return fallback;
716
+ }
717
+ try {
718
+ const locale = this.locale || document.documentElement.lang || navigator.language || 'en';
719
+ return new Intl.DisplayNames([locale], { type: 'dateTimeField' }).of(field) || fallback;
720
+ } catch (e) {
721
+ return fallback;
722
+ }
169
723
  }
170
724
  }