@dile/utils 3.3.22 → 3.4.1

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.
@@ -1,8 +1,27 @@
1
- import { css } from 'lit';
2
- //import { LionCalendar } from '@lion/ui/components/calendar/src/LionCalendar.js';
1
+ import { css, html, svg, nothing } from 'lit';
3
2
  import { LionCalendar } from '@lion/ui/calendar.js';
3
+ import { getMonthNames } from '@lion/ui/localize-no-side-effects.js';
4
+ import '@dile/ui/components/wheel-picker/wheel-picker.js';
5
+
6
+ const DEFAULT_YEAR_RANGE = 100;
7
+ // Lion normalizes dates with new Date(year, month, day), which maps years 0-99 to 1900-1999,
8
+ // so the earliest date that compares correctly is in year 100.
9
+ const EARLIEST_DATE = new Date(100, 0, 1);
10
+ const LATEST_DATE = new Date(8640000000000000);
11
+ const isValidDate = (date) => date instanceof Date && !Number.isNaN(date.getTime());
12
+ const checkIcon = svg`<path d="M9 16.17 4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>`;
4
13
 
5
14
  export class DileCalendar extends LionCalendar {
15
+ static get properties() {
16
+ return {
17
+ ...super.properties,
18
+ minYear: { type: Number },
19
+ maxYear: { type: Number },
20
+ monthYearAcceptLabel: { type: String },
21
+ __monthYearOpen: { type: Boolean, state: true },
22
+ };
23
+ }
24
+
6
25
  static get styles() {
7
26
  return [
8
27
  super.styles,
@@ -23,7 +42,7 @@ export class DileCalendar extends LionCalendar {
23
42
  align-items: center;
24
43
  min-height: auto;
25
44
  font-size: 0.9rem;
26
-
45
+ line-height: 1.36;
27
46
  }
28
47
  @media(min-width: 400px) {
29
48
  .calendar__navigation h2 {
@@ -36,6 +55,14 @@ export class DileCalendar extends LionCalendar {
36
55
  background-color: var(--dile-calendar-day-background-color, rgba(90, 90, 90, 0.08));
37
56
  color: var(--dile-calendar-day-text-color, #303030);
38
57
  border-radius: var(--dile-calendar-day-border-radius, 2px);
58
+ font: inherit;
59
+ font-weight: normal;
60
+ line-height: 1;
61
+ }
62
+ .calendar__day-button__text {
63
+ font: inherit;
64
+ font-weight: normal;
65
+ line-height: 1;
39
66
  }
40
67
  .calendar__day-button[today] {
41
68
  background-color: var(--dile-calendar-today-background-color, rgba(90, 90, 90, 0.20));
@@ -67,7 +94,365 @@ export class DileCalendar extends LionCalendar {
67
94
  min-height: var(--dile-calendar-day-size, 36px);
68
95
  }
69
96
  }
97
+ .calendar__navigation-toggle {
98
+ min-height: 30px;
99
+ padding: 0 4px;
100
+ border: 0;
101
+ border-bottom: 1px dotted currentColor;
102
+ border-radius: 0;
103
+ background: transparent;
104
+ color: var(--dile-calendar-day-text-color, #303030);
105
+ font: inherit;
106
+ text-align: center;
107
+ cursor: pointer;
108
+ }
109
+ .calendar__navigation-toggle[aria-expanded="true"] {
110
+ border-bottom-style: solid;
111
+ }
112
+ .calendar__navigation-toggle:focus-visible {
113
+ outline: 2px solid var(--dile-input-focus-border-color, var(--dile-link-color, #6af));
114
+ outline-offset: 2px;
115
+ }
116
+ .calendar-body {
117
+ position: relative;
118
+ }
119
+ .calendar-body.month-year-open > :not(.month-year-layer) {
120
+ visibility: hidden;
121
+ }
122
+ .month-year-layer {
123
+ position: absolute;
124
+ inset: 0;
125
+ display: flex;
126
+ flex-direction: column;
127
+ align-items: stretch;
128
+ gap: 0.25rem;
129
+ padding-bottom: 12px;
130
+ box-sizing: border-box;
131
+ --dile-wheel-picker-item-height: var(--dile-calendar-wheel-item-height, 36px);
132
+ --dile-wheel-picker-font-size: var(--dile-calendar-wheel-font-size, 1.1rem);
133
+ --dile-wheel-picker-text-color: var(--dile-calendar-wheel-text-color, color-mix(in srgb, var(--dile-calendar-day-text-color, #303030) 60%, transparent));
134
+ --dile-wheel-picker-selected-text-color: var(--dile-calendar-wheel-selected-text-color, var(--dile-calendar-day-text-color, #303030));
135
+ --dile-wheel-picker-band-background-color: var(--dile-calendar-wheel-band-background-color, var(--dile-calendar-day-background-color, rgba(90, 90, 90, 0.08)));
136
+ }
137
+ .month-year-columns {
138
+ flex: 1;
139
+ display: flex;
140
+ align-items: center;
141
+ gap: 0.5rem;
142
+ }
143
+ .month-year-accept {
144
+ flex-shrink: 0;
145
+ align-self: center;
146
+ display: inline-flex;
147
+ align-items: center;
148
+ justify-content: center;
149
+ width: 28px;
150
+ height: 28px;
151
+ padding: 0;
152
+ border: 1px solid var(--dile-calendar-month-year-accept-border-color, color-mix(in srgb, currentColor 35%, transparent));
153
+ border-radius: 50%;
154
+ background: transparent;
155
+ color: var(--dile-calendar-month-year-accept-color, var(--dile-calendar-nav-buttons-color, #303030));
156
+ cursor: pointer;
157
+ }
158
+ .month-year-accept:hover {
159
+ background-color: var(--dile-calendar-day-background-color, rgba(90, 90, 90, 0.08));
160
+ }
161
+ .month-year-accept:focus-visible {
162
+ outline: 2px solid var(--dile-input-focus-border-color, var(--dile-link-color, #6af));
163
+ outline-offset: 2px;
164
+ }
165
+ .month-year-accept svg {
166
+ width: 18px;
167
+ height: 18px;
168
+ fill: currentColor;
169
+ }
170
+ .month-wheel {
171
+ flex: 3;
172
+ }
173
+ .year-wheel {
174
+ flex: 2;
175
+ }
70
176
  `
71
177
  ];
72
178
  }
73
- }
179
+
180
+ constructor() {
181
+ super();
182
+ this.minDate = new Date(EARLIEST_DATE);
183
+ this.monthYearAcceptLabel = 'OK';
184
+ this.__monthYearOpen = false;
185
+ this.__monthItemsCache = { key: '', items: [] };
186
+ this.__yearItemsCache = { key: '', items: [] };
187
+ }
188
+
189
+ requestUpdate(name, oldValue, options) {
190
+ // Lion rebuilds the days as soon as these properties change, so empty
191
+ // or invalid values are replaced by the defaults before that happens.
192
+ if (name === 'minDate' && (!isValidDate(this.minDate) || this.minDate < EARLIEST_DATE)) {
193
+ this.minDate = new Date(EARLIEST_DATE);
194
+ return;
195
+ }
196
+ if (name === 'maxDate' && !isValidDate(this.maxDate)) {
197
+ this.maxDate = new Date(LATEST_DATE);
198
+ return;
199
+ }
200
+ if (name === 'disableDates' && typeof this.disableDates !== 'function') {
201
+ this.disableDates = () => false;
202
+ return;
203
+ }
204
+ super.requestUpdate(name, oldValue, options);
205
+ }
206
+
207
+ willUpdate(changedProperties) {
208
+ super.willUpdate?.(changedProperties);
209
+ const limitsChanged = ['minDate', 'maxDate', 'disableDates'].some(name => changedProperties.has(name));
210
+ if (this.hasUpdated && limitsChanged && !this.__isEnabledDate(this.centralDate)) {
211
+ this.centralDate = this.findNearestEnabledDate(this.centralDate);
212
+ }
213
+ }
214
+
215
+ render() {
216
+ return html`
217
+ <div class="calendar" role="application" @keydown="${this.__onCalendarKeydown}">
218
+ ${this.__renderNavigation()}
219
+ <div class="calendar-body ${this.__monthYearOpen ? 'month-year-open' : ''}">
220
+ ${this.__renderData()}
221
+ ${this.__monthYearOpen ? this.__renderMonthYearLayer() : nothing}
222
+ </div>
223
+ </div>
224
+ `;
225
+ }
226
+
227
+ /**
228
+ * Shows the month and year selection layer instead of the days grid.
229
+ * @param {'month'|'year'} focusColumn column that receives the focus
230
+ */
231
+ async openMonthYearPicker(focusColumn = 'year') {
232
+ this.__monthYearOpen = true;
233
+ await this.updateComplete;
234
+ const wheel = this.shadowRoot.querySelector(focusColumn === 'month' ? '.month-wheel' : '.year-wheel');
235
+ await wheel?.updateComplete;
236
+ wheel?.focus();
237
+ }
238
+
239
+ /**
240
+ * Hides the month and year selection layer and shows the days grid again.
241
+ */
242
+ closeMonthYearPicker() {
243
+ this.__monthYearOpen = false;
244
+ }
245
+
246
+ /**
247
+ * Shows the month of the given date, or of the nearest enabled date.
248
+ * @param {Date} [date] defaults to today
249
+ */
250
+ goToDate(date = new Date()) {
251
+ const target = new Date(date);
252
+ this.centralDate = this.__isEnabledDate(target) ? target : this.findNearestEnabledDate(target);
253
+ }
254
+
255
+ get monthYearPickerOpened() {
256
+ return this.__monthYearOpen;
257
+ }
258
+
259
+ __renderNavigation() {
260
+ const monthNames = this.__monthNames();
261
+ const monthIndex = this.centralDate.getMonth();
262
+ const month = monthNames[monthIndex];
263
+ const year = this.centralDate.getFullYear();
264
+ const nextMonth = monthNames[(monthIndex + 1) % 12];
265
+ const previousMonth = monthNames[(monthIndex + 11) % 12];
266
+ const nextMonthYear = monthIndex === 11 ? year + 1 : year;
267
+ const previousMonthYear = monthIndex === 0 ? year - 1 : year;
268
+ return html`
269
+ <div class="calendar__navigation">
270
+ <div class="calendar__navigation__month">
271
+ ${this.__renderPreviousButton('Month', previousMonth, previousMonthYear)}
272
+ <h2 class="calendar__navigation-heading" id="month" aria-atomic="true">
273
+ ${this.__renderToggle('month', month, this.__fieldLabel('month'))}
274
+ </h2>
275
+ ${this.__renderNextButton('Month', nextMonth, nextMonthYear)}
276
+ </div>
277
+ <div class="calendar__navigation__year">
278
+ ${this.__renderPreviousButton('FullYear', month, year - 1)}
279
+ <h2 class="calendar__navigation-heading" id="year" aria-atomic="true">
280
+ ${this.__renderToggle('year', year, this.__fieldLabel('year'))}
281
+ </h2>
282
+ ${this.__renderNextButton('FullYear', month, year + 1)}
283
+ </div>
284
+ </div>
285
+ `;
286
+ }
287
+
288
+ __renderToggle(column, text, fieldLabel) {
289
+ return html`
290
+ <button
291
+ type="button"
292
+ class="calendar__navigation-toggle calendar__navigation-toggle--${column}"
293
+ aria-expanded="${this.__monthYearOpen ? 'true' : 'false'}"
294
+ aria-controls="month-year-layer"
295
+ aria-label="${fieldLabel}: ${text}"
296
+ title="${fieldLabel}"
297
+ @click="${() => this.__toggleMonthYear(column)}"
298
+ >${text}</button>
299
+ `;
300
+ }
301
+
302
+ __renderMonthYearLayer() {
303
+ return html`
304
+ <div
305
+ id="month-year-layer"
306
+ class="month-year-layer"
307
+ @dile-wheel-picker-changed="${this.__stopEvent}"
308
+ @element-changed="${this.__stopEvent}"
309
+ >
310
+ <div class="month-year-columns">
311
+ <dile-wheel-picker
312
+ class="month-wheel"
313
+ label="${this.__fieldLabel('month')}"
314
+ .items="${this.__monthItems()}"
315
+ .value="${this.centralDate.getMonth()}"
316
+ @dile-wheel-picker-changed="${this.__onMonthChanged}"
317
+ ></dile-wheel-picker>
318
+ <dile-wheel-picker
319
+ class="year-wheel"
320
+ label="${this.__fieldLabel('year')}"
321
+ .items="${this.__yearItems()}"
322
+ .value="${this.centralDate.getFullYear()}"
323
+ @dile-wheel-picker-changed="${this.__onYearChanged}"
324
+ ></dile-wheel-picker>
325
+ </div>
326
+ <button
327
+ type="button"
328
+ class="month-year-accept"
329
+ aria-label="${this.monthYearAcceptLabel}"
330
+ title="${this.monthYearAcceptLabel}"
331
+ @click="${this.__acceptMonthYear}"
332
+ ><svg viewBox="0 0 24 24" aria-hidden="true">${checkIcon}</svg></button>
333
+ </div>
334
+ `;
335
+ }
336
+
337
+ __monthNames() {
338
+ return getMonthNames({ locale: this.__getLocale() });
339
+ }
340
+
341
+ __fieldLabel(field) {
342
+ const fallback = field === 'year' ? 'Year' : 'Month';
343
+ try {
344
+ const locale = this.__getLocale() || document.documentElement.lang || navigator.language || 'en';
345
+ return new Intl.DisplayNames([locale], { type: 'dateTimeField' }).of(field) || fallback;
346
+ } catch (e) {
347
+ return fallback;
348
+ }
349
+ }
350
+
351
+ __monthItems() {
352
+ const year = this.centralDate.getFullYear();
353
+ const names = this.__monthNames();
354
+ const key = [names.join(), year, this.minDate?.getTime(), this.maxDate?.getTime()].join('|');
355
+ if (this.__monthItemsCache.key !== key) {
356
+ const items = names.map((label, month) => {
357
+ const firstDay = new Date(this.centralDate);
358
+ firstDay.setFullYear(year, month, 1);
359
+ firstDay.setHours(0, 0, 0, 0);
360
+ const lastDay = new Date(firstDay);
361
+ lastDay.setFullYear(year, month + 1, 0);
362
+ lastDay.setHours(23, 59, 59, 999);
363
+ const disabled = Boolean((this.minDate && lastDay < this.minDate)
364
+ || (this.maxDate && firstDay > this.maxDate));
365
+ return { value: month, label, disabled };
366
+ });
367
+ this.__monthItemsCache = { key, items };
368
+ }
369
+ return this.__monthItemsCache.items;
370
+ }
371
+
372
+ __yearRange() {
373
+ const currentYear = new Date().getFullYear();
374
+ let from = Number.isFinite(this.minYear) ? this.minYear : currentYear - DEFAULT_YEAR_RANGE;
375
+ let to = Number.isFinite(this.maxYear) ? this.maxYear : currentYear + DEFAULT_YEAR_RANGE;
376
+ if (this.minDate) {
377
+ from = Math.max(from, this.minDate.getFullYear());
378
+ }
379
+ if (this.maxDate) {
380
+ to = Math.min(to, this.maxDate.getFullYear());
381
+ }
382
+ const centralYear = this.centralDate.getFullYear();
383
+ return { from: Math.min(from, centralYear), to: Math.max(to, centralYear) };
384
+ }
385
+
386
+ __yearItems() {
387
+ const { from, to } = this.__yearRange();
388
+ const key = `${from}|${to}`;
389
+ if (this.__yearItemsCache.key !== key) {
390
+ const items = [];
391
+ for (let year = from; year <= to; year++) {
392
+ items.push(year);
393
+ }
394
+ this.__yearItemsCache = { key, items };
395
+ }
396
+ return this.__yearItemsCache.items;
397
+ }
398
+
399
+ __toggleMonthYear(column) {
400
+ if (this.__monthYearOpen) {
401
+ this.closeMonthYearPicker();
402
+ } else {
403
+ this.openMonthYearPicker(column);
404
+ }
405
+ }
406
+
407
+ __acceptMonthYear() {
408
+ this.closeMonthYearPicker();
409
+ this.updateComplete.then(() => {
410
+ this.shadowRoot.querySelector('.calendar__navigation-toggle--year')?.focus();
411
+ });
412
+ }
413
+
414
+ __stopEvent(e) {
415
+ e.stopPropagation();
416
+ }
417
+
418
+ __onMonthChanged(e) {
419
+ this.__setCentralMonthYear(this.centralDate.getFullYear(), Number(e.detail.value));
420
+ }
421
+
422
+ __onYearChanged(e) {
423
+ this.__setCentralMonthYear(Number(e.detail.value), this.centralDate.getMonth());
424
+ }
425
+
426
+ __setCentralMonthYear(year, month) {
427
+ const lastDayOfMonth = new Date(this.centralDate);
428
+ lastDayOfMonth.setFullYear(year, month + 1, 0);
429
+ const date = new Date(this.centralDate);
430
+ date.setFullYear(year, month, Math.min(this.centralDate.getDate(), lastDayOfMonth.getDate()));
431
+ if (Number.isNaN(date.getTime())) {
432
+ return;
433
+ }
434
+ if (this.minDate && date < this.minDate) {
435
+ this.centralDate = new Date(this.minDate);
436
+ } else if (this.maxDate && date > this.maxDate) {
437
+ this.centralDate = new Date(this.maxDate);
438
+ } else {
439
+ this.centralDate = date;
440
+ }
441
+ }
442
+
443
+ __onCalendarKeydown(e) {
444
+ if (!this.__monthYearOpen) {
445
+ return;
446
+ }
447
+ const inLayer = e.composedPath().some(node => node.id === 'month-year-layer');
448
+ if (e.key === 'Escape' || (e.key === 'Enter' && inLayer)) {
449
+ e.preventDefault();
450
+ e.stopPropagation();
451
+ const column = e.composedPath().some(node => node.classList?.contains('month-wheel')) ? 'month' : 'year';
452
+ this.closeMonthYearPicker();
453
+ this.updateComplete.then(() => {
454
+ this.shadowRoot.querySelector(`.calendar__navigation-toggle--${column}`)?.focus();
455
+ });
456
+ }
457
+ }
458
+ }
@@ -6,8 +6,105 @@ import '@dile/ui/components/menu-overlay/menu-overlay.js';
6
6
 
7
7
  import {
8
8
  formatDate,
9
+ parseDate,
9
10
  } from '@lion/ui/localize.js';
10
11
 
12
+ function deepActiveElement() {
13
+ let active = document.activeElement;
14
+ while (active?.shadowRoot?.activeElement) {
15
+ active = active.shadowRoot.activeElement;
16
+ }
17
+ return active;
18
+ }
19
+
20
+ /**
21
+ * Converts the minDate / maxDate values of the datepicker to a Date.
22
+ * Accepts Date objects and strings: "YYYY-MM-DD" is read as a local date.
23
+ * @param {Date|string} value
24
+ * @returns {Date|undefined}
25
+ */
26
+ export function toCalendarDate(value) {
27
+ if (value === undefined || value === null || value === '') {
28
+ return undefined;
29
+ }
30
+ if (value instanceof Date) {
31
+ return Number.isNaN(value.getTime()) ? undefined : value;
32
+ }
33
+ const isoDate = parseIsoDate(value);
34
+ if (isoDate !== null) {
35
+ return isoDate;
36
+ }
37
+ const date = new Date(value);
38
+ return Number.isNaN(date.getTime()) ? undefined : date;
39
+ }
40
+
41
+ /**
42
+ * Reads the date part of "YYYY-MM-DD" strings (an optional time after a space or a "T" is ignored)
43
+ * as a local date. Returns null when the string has another format and undefined when the date doesn't exist.
44
+ * @param {string} value
45
+ * @returns {Date|undefined|null}
46
+ */
47
+ function parseIsoDate(value) {
48
+ const match = /^(\d{1,6})-(\d{1,2})-(\d{1,2})(?:[ T].*)?$/.exec(String(value).trim());
49
+ if (!match) {
50
+ return null;
51
+ }
52
+ const [year, month, day] = match.slice(1).map(Number);
53
+ const date = new Date(2000, 0, 1);
54
+ date.setFullYear(year, month - 1, day);
55
+ return date.getMonth() === month - 1 && date.getDate() === day ? date : undefined;
56
+ }
57
+
58
+ /**
59
+ * Converts the text value of the datepicker to a Date: "YYYY-MM-DD" values
60
+ * or dates written in the format of the locale (the page locale by default).
61
+ * @param {string} value
62
+ * @param {string} [locale]
63
+ * @returns {Date|undefined}
64
+ */
65
+ export function valueToDate(value, locale) {
66
+ if (value === undefined || value === null || String(value).trim() === '') {
67
+ return undefined;
68
+ }
69
+ const isoDate = parseIsoDate(value);
70
+ return isoDate !== null ? isoDate : parseDate(String(value).trim(), locale ? { locale } : undefined);
71
+ }
72
+
73
+ const VALIDATION_MESSAGES = {
74
+ en: {
75
+ invalid: 'Enter a valid date, for example {example}.',
76
+ beforeMin: 'The date must be on or after {date}.',
77
+ afterMax: 'The date must be on or before {date}.',
78
+ disabled: 'This date is not available.',
79
+ },
80
+ es: {
81
+ invalid: 'Introduce una fecha válida, por ejemplo {example}.',
82
+ beforeMin: 'La fecha debe ser igual o posterior al {date}.',
83
+ afterMax: 'La fecha debe ser igual o anterior al {date}.',
84
+ disabled: 'Esta fecha no está disponible.',
85
+ },
86
+ ca: {
87
+ invalid: 'Introdueix una data vàlida, per exemple {example}.',
88
+ beforeMin: 'La data ha de ser igual o posterior al {date}.',
89
+ afterMax: 'La data ha de ser igual o anterior al {date}.',
90
+ disabled: 'Aquesta data no està disponible.',
91
+ },
92
+ fr: {
93
+ invalid: 'Saisissez une date valide, par exemple {example}.',
94
+ beforeMin: 'La date doit être le {date} ou après.',
95
+ afterMax: 'La date doit être le {date} ou avant.',
96
+ disabled: 'Cette date n’est pas disponible.',
97
+ },
98
+ de: {
99
+ invalid: 'Geben Sie ein gültiges Datum ein, z. B. {example}.',
100
+ beforeMin: 'Das Datum muss am oder nach dem {date} liegen.',
101
+ afterMax: 'Das Datum muss am oder vor dem {date} liegen.',
102
+ disabled: 'Dieses Datum ist nicht verfügbar.',
103
+ },
104
+ };
105
+
106
+ const dayKey = (date) => date.getFullYear() * 10000 + date.getMonth() * 100 + date.getDate();
107
+
11
108
  export class DileDatepicker extends DileCloseOnEscPressed(DileInputIcon) {
12
109
  static get styles() {
13
110
  return [
@@ -61,11 +158,20 @@ export class DileDatepicker extends DileCloseOnEscPressed(DileInputIcon) {
61
158
  return {
62
159
  ...super.properties,
63
160
  firstDayOfWeek: { type: Number },
161
+ weekdayHeaderNotation: { type: String },
162
+ locale: { type: String },
64
163
  horizontalAlign: { type: String },
65
164
  verticalAlign: { type: String },
66
165
  moveTop: { type: Number },
67
166
  moveLeft: { type: Number },
68
167
  opened: { type: Boolean },
168
+ minYear: { type: Number },
169
+ maxYear: { type: Number },
170
+ minDate: {},
171
+ maxDate: {},
172
+ disableDates: { attribute: false },
173
+ validateDate: { type: Boolean },
174
+ validationMessages: { type: Object },
69
175
  };
70
176
  }
71
177
 
@@ -73,6 +179,9 @@ export class DileDatepicker extends DileCloseOnEscPressed(DileInputIcon) {
73
179
  super();
74
180
  this.icon = 'lucide.calendar';
75
181
  this.firstDayOfWeek = 0;
182
+ this.weekdayHeaderNotation = 'short';
183
+ this.validateDate = false;
184
+ this.validationMessages = {};
76
185
  this.horizontalAlign = 'under_right';
77
186
  this.verticalAlign = 'center';
78
187
  this.moveTop = 0;
@@ -80,8 +189,18 @@ export class DileDatepicker extends DileCloseOnEscPressed(DileInputIcon) {
80
189
  this.opened = false;
81
190
  }
82
191
 
192
+ willUpdate(changedProperties) {
193
+ super.willUpdate?.(changedProperties);
194
+ if (changedProperties.has('minDate')) {
195
+ this._calendarMinDate = toCalendarDate(this.minDate);
196
+ }
197
+ if (changedProperties.has('maxDate')) {
198
+ this._calendarMaxDate = toCalendarDate(this.maxDate);
199
+ }
200
+ }
201
+
83
202
  renderIconButton() {
84
- if (this.disabled) {
203
+ if (this.isDisabled) {
85
204
  return super.renderIconButton();
86
205
  }
87
206
  return html`
@@ -92,6 +211,7 @@ export class DileDatepicker extends DileCloseOnEscPressed(DileInputIcon) {
92
211
  horizontalAlign="${this.horizontalAlign}"
93
212
  id="menu"
94
213
  @overlay-opened="${this.overlayOpenedHandler}"
214
+ @overlay-ready="${this.overlayReadyHandler}"
95
215
  @overlay-closed="${this.overlayClosedHandler}"
96
216
  >
97
217
  <div slot="trigger" class="trigger-container">
@@ -104,22 +224,151 @@ export class DileDatepicker extends DileCloseOnEscPressed(DileInputIcon) {
104
224
  `;
105
225
  }
106
226
 
227
+ get calendar() {
228
+ return this.shadowRoot.querySelector('dile-calendar');
229
+ }
230
+
107
231
  overlayOpenedHandler() {
108
232
  this.opened = true;
233
+ this._focusBeforeOpen = deepActiveElement();
234
+ this.syncCalendarWithValue();
235
+ }
236
+
237
+ async overlayReadyHandler() {
238
+ const calendar = this.calendar;
239
+ if (!calendar) {
240
+ return;
241
+ }
242
+ await calendar.updateComplete;
243
+ calendar.focusCentralDate();
109
244
  }
110
245
 
111
246
  overlayClosedHandler() {
112
247
  this.opened = false;
248
+ this.calendar?.closeMonthYearPicker();
249
+ if (this.shadowRoot.activeElement?.closest('.calendar')) {
250
+ const previous = this._focusBeforeOpen;
251
+ const target = previous?.isConnected && previous !== document.body && !this.calendar?.contains(previous) && !this.calendar?.shadowRoot.contains(previous)
252
+ ? previous
253
+ : this.shadowRoot.querySelector('.input-icon-btn');
254
+ target?.focus();
255
+ }
256
+ }
257
+
258
+ /**
259
+ * Marks the date of the current value in the calendar and shows its month.
260
+ * Without a valid value, the calendar shows today (or the nearest enabled date).
261
+ */
262
+ syncCalendarWithValue() {
263
+ const calendar = this.calendar;
264
+ if (!calendar) {
265
+ return;
266
+ }
267
+ const date = valueToDate(this.value, this.locale);
268
+ calendar.selectedDate = date;
269
+ calendar.goToDate(date);
113
270
  }
114
271
 
115
272
  showDate(e) {
116
- let date = formatDate(e.detail.selectedDate);
117
- this.value = date;
273
+ this.value = this.dateToValue(e.detail.selectedDate);
274
+ if (this.validateDate) {
275
+ this.validate();
276
+ }
118
277
  const menu = this.shadowRoot.getElementById('menu');
119
278
  if (menu) {
120
279
  menu.close();
121
280
  }
122
281
  }
282
+
283
+ /**
284
+ * Text written in the input for a date selected in the calendar.
285
+ * @param {Date} date
286
+ * @returns {string}
287
+ */
288
+ dateToValue(date) {
289
+ return formatDate(date, this.locale ? { locale: this.locale } : undefined);
290
+ }
291
+
292
+ doBlur(e) {
293
+ super.doBlur?.(e);
294
+ if (!this.validateDate) {
295
+ return;
296
+ }
297
+ if (this.validate()) {
298
+ const { date } = this.getDateValidation();
299
+ const normalized = date ? this.dateToValue(date) : undefined;
300
+ if (normalized && normalized !== this.value) {
301
+ this.value = normalized;
302
+ }
303
+ }
304
+ }
305
+
306
+ /**
307
+ * Checks the current value without changing the component state.
308
+ * An empty value is valid (use your form validation to make it required).
309
+ * @param {string} [value]
310
+ * @returns {{valid: boolean, reason?: 'invalid'|'beforeMin'|'afterMax'|'disabled', date?: Date}}
311
+ */
312
+ getDateValidation(value = this.value) {
313
+ if (value === undefined || value === null || String(value).trim() === '') {
314
+ return { valid: true };
315
+ }
316
+ const date = valueToDate(value, this.locale);
317
+ if (!date) {
318
+ return { valid: false, reason: 'invalid' };
319
+ }
320
+ const minDate = toCalendarDate(this.minDate);
321
+ const maxDate = toCalendarDate(this.maxDate);
322
+ if (minDate && dayKey(date) < dayKey(minDate)) {
323
+ return { valid: false, reason: 'beforeMin', date };
324
+ }
325
+ if (maxDate && dayKey(date) > dayKey(maxDate)) {
326
+ return { valid: false, reason: 'afterMax', date };
327
+ }
328
+ if (typeof this.disableDates === 'function' && this.disableDates(date)) {
329
+ return { valid: false, reason: 'disabled', date };
330
+ }
331
+ return { valid: true, date };
332
+ }
333
+
334
+ /**
335
+ * Validates the current value, showing or removing the error message.
336
+ * @returns {boolean} true when the value is valid
337
+ */
338
+ validate() {
339
+ const result = this.getDateValidation();
340
+ if (result.valid) {
341
+ if (this._dateErrorShown) {
342
+ this.errored = Boolean(this._stateBeforeDateError.errored);
343
+ this.message = this._stateBeforeDateError.message ?? '';
344
+ this._dateErrorShown = false;
345
+ }
346
+ this.internals?.setValidity({});
347
+ return true;
348
+ }
349
+ if (!this._dateErrorShown) {
350
+ this._stateBeforeDateError = { errored: this.errored, message: this.message };
351
+ this._dateErrorShown = true;
352
+ }
353
+ this.errored = true;
354
+ this.message = this.getValidationMessage(result.reason);
355
+ this.internals?.setValidity({ customError: true }, this.message, this.el);
356
+ return false;
357
+ }
358
+
359
+ /**
360
+ * @param {'invalid'|'beforeMin'|'afterMax'|'disabled'} reason
361
+ * @returns {string}
362
+ */
363
+ getValidationMessage(reason) {
364
+ const language = (this.locale || document.documentElement.lang || 'en').slice(0, 2).toLowerCase();
365
+ const messages = { ...VALIDATION_MESSAGES.en, ...VALIDATION_MESSAGES[language], ...this.validationMessages };
366
+ const limit = reason === 'beforeMin' ? toCalendarDate(this.minDate) : toCalendarDate(this.maxDate);
367
+ const example = new Date(new Date().getFullYear(), 11, 31);
368
+ return String(messages[reason] || '')
369
+ .replace('{date}', limit ? this.dateToValue(limit) : '')
370
+ .replace('{example}', this.dateToValue(example));
371
+ }
123
372
 
124
373
  close() {
125
374
  const menu = this.shadowRoot.getElementById('menu');
@@ -144,6 +393,13 @@ export class DileDatepicker extends DileCloseOnEscPressed(DileInputIcon) {
144
393
  <dile-calendar
145
394
  class="demo-calendar"
146
395
  .firstDayOfWeek="${this.firstDayOfWeek}"
396
+ .weekdayHeaderNotation="${this.weekdayHeaderNotation}"
397
+ .locale="${this.locale}"
398
+ .minYear="${this.minYear}"
399
+ .maxYear="${this.maxYear}"
400
+ .minDate="${this._calendarMinDate}"
401
+ .maxDate="${this._calendarMaxDate}"
402
+ .disableDates="${this.disableDates}"
147
403
  @user-selected-date-changed=${this.showDate}
148
404
  ></dile-calendar>
149
405
  `;
@@ -1,17 +1,26 @@
1
- import { html, css } from 'lit';
1
+ import { html, css, svg, nothing } from 'lit';
2
2
  import { DileDatepicker } from './DileDatepicker.js';
3
3
  import '@dile/iconlib/lucide-icons/calendar-clock.js';
4
- import '@dile/ui/components/time-picker/time-picker.js';
4
+ import '@dile/ui/components/wheel-picker/wheel-picker.js';
5
5
  import '@dile/ui/components/icon/icon.js';
6
6
  import { doneIcon } from '@dile/icons';
7
7
 
8
+ const checkIcon = svg`<path d="M9 16.17 4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>`;
9
+ const pad = n => String(n).padStart(2, '0');
10
+
8
11
  function formatToIsoOnlyDate(date) {
9
- const pad = n => String(n).padStart(2, '0');
10
- return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
12
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
11
13
  }
12
14
 
15
+ /**
16
+ * Converts ISO 8601 date-times ("2024-03-15T10:30:00Z", "2024-03-15T10:30:00+02:00",
17
+ * "2024-03-15T10:30") to the "YYYY-MM-DD HH:mm:ss" format, in local time.
18
+ * Other values are returned without changes.
19
+ * @param {string} dateStr
20
+ * @returns {string}
21
+ */
13
22
  function formatIfIso8601(dateStr) {
14
- const iso8601Regex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;
23
+ const iso8601Regex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?$/;
15
24
 
16
25
  if (!iso8601Regex.test(dateStr)) {
17
26
  return dateStr;
@@ -22,11 +31,52 @@ function formatIfIso8601(dateStr) {
22
31
  return dateStr;
23
32
  }
24
33
 
25
- const pad = n => n.toString().padStart(2, '0');
26
- return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +
34
+ return `${formatToIsoOnlyDate(date)} ` +
27
35
  `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
28
36
  }
29
37
 
38
+ /**
39
+ * Reads the "HH:mm" or "HH:mm:ss" time written after the date in the value.
40
+ * @param {string} value
41
+ * @returns {string|undefined} the time as "HH:mm:ss", or undefined when there is no valid time
42
+ */
43
+ export function valueToTime(value) {
44
+ const match = /(?:^|[ T])(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?/.exec(String(value ?? '').trim());
45
+ if (!match) {
46
+ return undefined;
47
+ }
48
+ const [hours, minutes, seconds = 0] = match.slice(1).map((part) => Number(part ?? 0));
49
+ if (hours > 23 || minutes > 59 || seconds > 59) {
50
+ return undefined;
51
+ }
52
+ return `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
53
+ }
54
+
55
+ function timeToParts(time) {
56
+ const [hours, minutes, seconds] = time.split(':').map(Number);
57
+ return { hours, minutes, seconds };
58
+ }
59
+
60
+ function validStep(step) {
61
+ const value = Math.round(Number(step));
62
+ return value >= 1 && value <= 59 ? value : 1;
63
+ }
64
+
65
+ /**
66
+ * Wheel items from 0 to max with the given step. A current value out of the step is also included.
67
+ */
68
+ function stepItems(max, step, current) {
69
+ const values = [];
70
+ for (let value = 0; value <= max; value += step) {
71
+ values.push(value);
72
+ }
73
+ if (Number.isInteger(current) && !values.includes(current)) {
74
+ values.push(current);
75
+ values.sort((a, b) => a - b);
76
+ }
77
+ return values.map((value) => ({ value, label: pad(value) }));
78
+ }
79
+
30
80
  export class DileDatetimepicker extends DileDatepicker {
31
81
 
32
82
  static get styles() {
@@ -39,6 +89,58 @@ export class DileDatetimepicker extends DileDatepicker {
39
89
  gap: 0.5rem;
40
90
  align-items: center;
41
91
  }
92
+ .date-time-body {
93
+ position: relative;
94
+ }
95
+ .date-time-body.time-open > dile-calendar {
96
+ visibility: hidden;
97
+ }
98
+ .time-layer {
99
+ position: absolute;
100
+ inset: 0;
101
+ display: flex;
102
+ flex-direction: column;
103
+ align-items: center;
104
+ justify-content: center;
105
+ gap: 0.5rem;
106
+ box-sizing: border-box;
107
+ --dile-wheel-picker-width: var(--dile-datetimepicker-wheel-width, 4.5rem);
108
+ --dile-wheel-picker-item-height: var(--dile-calendar-wheel-item-height, 36px);
109
+ --dile-wheel-picker-font-size: var(--dile-calendar-wheel-font-size, 1.1rem);
110
+ --dile-wheel-picker-text-color: var(--dile-calendar-wheel-text-color, color-mix(in srgb, var(--dile-calendar-day-text-color, #303030) 60%, transparent));
111
+ --dile-wheel-picker-selected-text-color: var(--dile-calendar-wheel-selected-text-color, var(--dile-calendar-day-text-color, #303030));
112
+ --dile-wheel-picker-band-background-color: var(--dile-calendar-wheel-band-background-color, var(--dile-calendar-day-background-color, rgba(90, 90, 90, 0.08)));
113
+ }
114
+ .time-columns {
115
+ display: flex;
116
+ align-items: center;
117
+ gap: 0.25rem;
118
+ }
119
+ .time-separator {
120
+ font-size: var(--dile-calendar-wheel-font-size, 1.1rem);
121
+ color: var(--dile-calendar-day-text-color, #303030);
122
+ }
123
+ .time-layer-accept {
124
+ display: inline-flex;
125
+ align-items: center;
126
+ justify-content: center;
127
+ width: 28px;
128
+ height: 28px;
129
+ padding: 0;
130
+ border: 1px solid var(--dile-calendar-month-year-accept-border-color, color-mix(in srgb, currentColor 35%, transparent));
131
+ border-radius: 50%;
132
+ background: transparent;
133
+ color: var(--dile-calendar-month-year-accept-color, var(--dile-calendar-nav-buttons-color, #303030));
134
+ cursor: pointer;
135
+ }
136
+ .time-layer-accept:hover {
137
+ background-color: var(--dile-calendar-day-background-color, rgba(90, 90, 90, 0.08));
138
+ }
139
+ .time-layer-accept svg {
140
+ width: 18px;
141
+ height: 18px;
142
+ fill: currentColor;
143
+ }
42
144
  .time-area {
43
145
  display: flex;
44
146
  flex-direction: row;
@@ -47,9 +149,26 @@ export class DileDatetimepicker extends DileDatepicker {
47
149
  align-items: center;
48
150
  margin-bottom: 0.5rem;
49
151
  }
50
- .time-area span {
51
- display: flex;
52
- align-items: center;
152
+ .time-toggle {
153
+ min-height: 30px;
154
+ padding: 0 4px;
155
+ border: 0;
156
+ border-bottom: 1px dotted currentColor;
157
+ border-radius: 0;
158
+ background: transparent;
159
+ color: var(--dile-datetimepicker-time-color, var(--dile-calendar-day-text-color, #303030));
160
+ font: inherit;
161
+ font-size: var(--dile-datetimepicker-time-font-size, 1.1rem);
162
+ font-variant-numeric: tabular-nums;
163
+ cursor: pointer;
164
+ }
165
+ .time-toggle[aria-expanded="true"] {
166
+ border-bottom-style: solid;
167
+ }
168
+ .time-toggle:focus-visible,
169
+ .time-layer-accept:focus-visible {
170
+ outline: 2px solid var(--dile-input-focus-border-color, var(--dile-link-color, #6af));
171
+ outline-offset: 2px;
53
172
  }
54
173
  .accept-button {
55
174
  display: flex;
@@ -73,9 +192,6 @@ export class DileDatetimepicker extends DileDatepicker {
73
192
  --dile-icon-rounded-background-color: var(--dile-datetimepicker-accept-icon-background-color, var(--dile-primary-color, #f4f4f4));
74
193
  cursor: pointer;
75
194
  }
76
- dile-time-picker {
77
- margin-bottom: 0;
78
- }
79
195
  `];
80
196
  }
81
197
 
@@ -83,6 +199,13 @@ export class DileDatetimepicker extends DileDatepicker {
83
199
  return {
84
200
  ...super.properties,
85
201
  acceptLabel: { type: String },
202
+ timeLabel: { type: String },
203
+ timeAcceptLabel: { type: String },
204
+ showSeconds: { type: Boolean },
205
+ minuteStep: { type: Number },
206
+ secondStep: { type: Number },
207
+ _time: { state: true },
208
+ _timeOpen: { state: true },
86
209
  };
87
210
  }
88
211
 
@@ -90,24 +213,48 @@ export class DileDatetimepicker extends DileDatepicker {
90
213
  super();
91
214
  this.icon = 'lucide.calendar-clock';
92
215
  this.acceptLabel = 'Accept date and time';
216
+ this.timeLabel = 'Time';
217
+ this.timeAcceptLabel = 'OK';
218
+ this.showSeconds = false;
219
+ this.minuteStep = 1;
220
+ this.secondStep = 1;
221
+ this._time = undefined;
222
+ this._timeOpen = false;
93
223
  }
94
224
 
95
225
  get contentTemplate() {
226
+ const time = this.selectedTime;
227
+ const shownTime = this.showSeconds ? time : time.slice(0, 5);
96
228
  return html`
97
229
  <div class="overlay-view">
98
- <dile-calendar
99
- class="demo-calendar"
100
- .firstDayOfWeek="${this.firstDayOfWeek}"
101
- @user-selected-date-changed=${this.showDateHandler}
102
- ></dile-calendar>
230
+ <div class="date-time-body ${this._timeOpen ? 'time-open' : ''}">
231
+ <dile-calendar
232
+ class="demo-calendar"
233
+ .firstDayOfWeek="${this.firstDayOfWeek}"
234
+ .weekdayHeaderNotation="${this.weekdayHeaderNotation}"
235
+ .locale="${this.locale}"
236
+ .minYear="${this.minYear}"
237
+ .maxYear="${this.maxYear}"
238
+ .minDate="${this._calendarMinDate}"
239
+ .maxDate="${this._calendarMaxDate}"
240
+ .disableDates="${this.disableDates}"
241
+ ></dile-calendar>
242
+ ${this._timeOpen ? this.timeLayerTemplate : nothing}
243
+ </div>
103
244
  <div class="time-area">
104
- <span>
105
- <dile-time-picker></dile-time-picker>
106
- </span>
107
- <button
108
- type="button"
109
- class="accept-button"
110
- aria-label="${this.acceptLabel}"
245
+ <button
246
+ type="button"
247
+ class="time-toggle"
248
+ aria-expanded="${this._timeOpen ? 'true' : 'false'}"
249
+ aria-controls="time-layer"
250
+ aria-label="${this.timeLabel}: ${shownTime}"
251
+ title="${this.timeLabel}"
252
+ @click=${this.toggleTimePicker}
253
+ >${shownTime}</button>
254
+ <button
255
+ type="button"
256
+ class="accept-button"
257
+ aria-label="${this.acceptLabel}"
111
258
  title="${this.acceptLabel}"
112
259
  @click=${this.acceptTime}
113
260
  >
@@ -118,32 +265,195 @@ export class DileDatetimepicker extends DileDatepicker {
118
265
  `;
119
266
  }
120
267
 
121
- get eltime() {
122
- return this.shadowRoot.querySelector('dile-time-picker');
268
+ get timeLayerTemplate() {
269
+ const { hours, minutes, seconds } = this._timeParts;
270
+ return html`
271
+ <div
272
+ id="time-layer"
273
+ class="time-layer"
274
+ role="group"
275
+ aria-label="${this.timeLabel}"
276
+ @keydown=${this.timeLayerKeydown}
277
+ @dile-wheel-picker-changed=${this.stopInnerEvent}
278
+ @element-changed=${this.stopInnerEvent}
279
+ >
280
+ <div class="time-columns">
281
+ <dile-wheel-picker
282
+ class="hours-wheel"
283
+ label="${this.fieldLabel('hour')}"
284
+ .items="${stepItems(23, 1, hours)}"
285
+ .value="${hours}"
286
+ @dile-wheel-picker-changed=${(e) => this.setTimePart('hours', e.detail.value)}
287
+ ></dile-wheel-picker>
288
+ <span class="time-separator" aria-hidden="true">:</span>
289
+ <dile-wheel-picker
290
+ class="minutes-wheel"
291
+ label="${this.fieldLabel('minute')}"
292
+ .items="${stepItems(59, validStep(this.minuteStep), minutes)}"
293
+ .value="${minutes}"
294
+ @dile-wheel-picker-changed=${(e) => this.setTimePart('minutes', e.detail.value)}
295
+ ></dile-wheel-picker>
296
+ ${this.showSeconds ? html`
297
+ <span class="time-separator" aria-hidden="true">:</span>
298
+ <dile-wheel-picker
299
+ class="seconds-wheel"
300
+ label="${this.fieldLabel('second')}"
301
+ .items="${stepItems(59, validStep(this.secondStep), seconds)}"
302
+ .value="${seconds}"
303
+ @dile-wheel-picker-changed=${(e) => this.setTimePart('seconds', e.detail.value)}
304
+ ></dile-wheel-picker>
305
+ ` : nothing}
306
+ </div>
307
+ <button
308
+ type="button"
309
+ class="time-layer-accept"
310
+ aria-label="${this.timeAcceptLabel}"
311
+ title="${this.timeAcceptLabel}"
312
+ @click=${this.closeTimePickerAndFocusToggle}
313
+ ><svg viewBox="0 0 24 24" aria-hidden="true">${checkIcon}</svg></button>
314
+ </div>
315
+ `;
123
316
  }
124
317
 
125
318
  get elmenu() {
126
319
  return this.shadowRoot.getElementById('menu');
127
320
  }
128
321
 
129
- showDateHandler(e) {
130
- this.showDate(e.detail.selectedDate);
322
+ /**
323
+ * Time selected in the picker, as "HH:mm:ss".
324
+ * Before the picker is opened, it is the current time.
325
+ * @returns {string}
326
+ */
327
+ get selectedTime() {
328
+ return this._time ?? this.currentTime();
329
+ }
330
+
331
+ get timePickerOpened() {
332
+ return this._timeOpen;
333
+ }
334
+
335
+ get _timeParts() {
336
+ return timeToParts(this.selectedTime);
337
+ }
338
+
339
+ /**
340
+ * Current time (seconds at 00), with the minutes rounded down to the minuteStep.
341
+ * @returns {string}
342
+ */
343
+ currentTime() {
344
+ const now = new Date();
345
+ const step = validStep(this.minuteStep);
346
+ return `${pad(now.getHours())}:${pad(Math.floor(now.getMinutes() / step) * step)}:00`;
347
+ }
348
+
349
+ /**
350
+ * Besides the calendar, sets the time of the picker to the time of the current value.
351
+ * Without a valid time in the value, the picker shows the current time.
352
+ */
353
+ syncCalendarWithValue() {
354
+ super.syncCalendarWithValue();
355
+ this._time = valueToTime(this.value) ?? this.currentTime();
356
+ this._timeOpen = false;
357
+ }
358
+
359
+ overlayClosedHandler() {
360
+ this._timeOpen = false;
361
+ super.overlayClosedHandler();
362
+ }
363
+
364
+ /**
365
+ * Shows the hours and minutes wheels over the calendar.
366
+ */
367
+ async openTimePicker() {
368
+ this._timeOpen = true;
369
+ await this.updateComplete;
370
+ const wheel = this.shadowRoot.querySelector('.hours-wheel');
371
+ await wheel?.updateComplete;
372
+ wheel?.focus();
373
+ }
374
+
375
+ /**
376
+ * Hides the time wheels and shows the calendar again.
377
+ */
378
+ closeTimePicker() {
379
+ this._timeOpen = false;
380
+ }
381
+
382
+ toggleTimePicker() {
383
+ if (this._timeOpen) {
384
+ this.closeTimePicker();
385
+ } else {
386
+ this.openTimePicker();
387
+ }
388
+ }
389
+
390
+ async closeTimePickerAndFocusToggle() {
391
+ this.closeTimePicker();
392
+ await this.updateComplete;
393
+ this.shadowRoot.querySelector('.time-toggle')?.focus();
394
+ }
395
+
396
+ timeLayerKeydown(e) {
397
+ if (e.key === 'Escape' || e.key === 'Enter') {
398
+ e.preventDefault();
399
+ e.stopPropagation();
400
+ this.closeTimePickerAndFocusToggle();
401
+ }
131
402
  }
132
403
 
404
+ // The inner wheels are not fields of the form: their changes must not leave the component.
405
+ stopInnerEvent(e) {
406
+ e.stopPropagation();
407
+ }
408
+
409
+ setTimePart(part, value) {
410
+ const parts = { ...this._timeParts, [part]: Number(value) };
411
+ this._time = `${pad(parts.hours)}:${pad(parts.minutes)}:${pad(parts.seconds)}`;
412
+ }
413
+
414
+ fieldLabel(field) {
415
+ const fallback = { hour: 'Hour', minute: 'Minute', second: 'Second' }[field];
416
+ try {
417
+ const locale = this.locale || document.documentElement.lang || navigator.language || 'en';
418
+ return new Intl.DisplayNames([locale], { type: 'dateTimeField' }).of(field) || fallback;
419
+ } catch (e) {
420
+ return fallback;
421
+ }
422
+ }
423
+
424
+ /**
425
+ * Writes the given date with the selected time in the value and closes the picker.
426
+ * @param {Date} selectedDate
427
+ */
133
428
  showDate(selectedDate) {
134
- let date = formatToIsoOnlyDate(selectedDate);
135
- let time = this.eltime.value;
136
- this.value = `${date} ${time}`;
137
- this.elmenu.close();
429
+ this.value = `${formatToIsoOnlyDate(selectedDate)} ${this.selectedTime}`;
430
+ if (this.validateDate) {
431
+ this.validate();
432
+ }
433
+ this.elmenu?.close();
138
434
  }
139
435
 
140
- acceptTime() {
141
- let date = this.shadowRoot.querySelector('dile-calendar').selectedDate;
142
- if(!date) {
143
- date = new Date();
436
+ dateToValue(date) {
437
+ return formatToIsoOnlyDate(date);
438
+ }
439
+
440
+ doBlur(e) {
441
+ // The value includes the time, so it is validated but never rewritten on blur.
442
+ if (this.validateDate) {
443
+ this.validate();
144
444
  }
445
+ }
446
+
447
+ /**
448
+ * Accepts the day selected in the calendar and the selected time.
449
+ * Without a selected day, uses the day focused in the calendar,
450
+ * which is always an enabled date (today or the nearest enabled date by default).
451
+ */
452
+ acceptTime() {
453
+ const calendar = this.calendar;
454
+ const date = calendar?.selectedDate || calendar?.centralDate || new Date();
145
455
  this.showDate(date);
146
- }
456
+ }
147
457
 
148
458
  computeValue(value){
149
459
  return formatIfIso8601(value);
@@ -1,5 +1,4 @@
1
1
  import { html, css } from 'lit';
2
- import { ifDefined } from 'lit/directives/if-defined.js';
3
2
  import { DileInput } from '@dile/ui/components/input/index.js';
4
3
  import '../../phone-prefix-select/phone-prefix-select.js';
5
4
  import {
@@ -117,39 +116,21 @@ export class DileInputPhone extends DileInput {
117
116
  }
118
117
  }
119
118
 
120
- render() {
121
- return html`
122
- <main>
123
- ${this.label
124
- ? html`<label for="textField">${this.label}</label>`
125
- : ""}
126
- <section class="for-input">
127
- ${this.noPrefix ? '' : this.prefixTemplate}
128
- <input
129
- type="tel"
130
- inputmode="tel"
131
- id="textField"
132
- name="${this.name}"
133
- aria-label="${ifDefined(this.inputAriaLabel)}"
134
- placeholder="${this.placeholder}"
135
- ?disabled="${this.disabled}"
136
- ?readonly="${this.readonly}"
137
- autocomplete="${this.computeAutocomplete()}"
138
- .value="${this._typedNumber}"
139
- class="${this.errored ? 'errored' : ''}"
140
- @keypress="${this._lookForEnter}"
141
- @input="${this._input}"
142
- @blur="${this.doBlur}"
143
- @focus="${this.doFocus}"
144
- />
145
- ${this.labelRight
146
- ? html`<span class="labelright">${this.labelRight}</span>`
147
- : ''
148
- }
149
- </section>
150
- ${this.messageTemplate}
151
- </main>
152
- `;
119
+ get fieldStartTemplate() {
120
+ return this.noPrefix ? '' : this.prefixTemplate;
121
+ }
122
+
123
+ get inputType() {
124
+ return 'tel';
125
+ }
126
+
127
+ get inputModeValue() {
128
+ return 'tel';
129
+ }
130
+
131
+ /** The input field shows the number as typed by the user, not the E.164 value */
132
+ computeValue() {
133
+ return this._typedNumber;
153
134
  }
154
135
 
155
136
  get prefixTemplate() {
@@ -161,7 +142,7 @@ export class DileInputPhone extends DileInput {
161
142
  language="${this.language}"
162
143
  priority-countries="${this.priorityCountries}"
163
144
  placeholder="${this.prefixPlaceholder || PREFIX_PLACEHOLDERS[this.language] || PREFIX_PLACEHOLDERS.en}"
164
- ?disabled=${this.disabled}
145
+ ?disabled=${this.isDisabled}
165
146
  ?errored=${this.errored}
166
147
  @dile-phone-prefix-changed=${this.onPrefixChanged}
167
148
  @element-changed=${this.stopEvent}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dile/utils",
3
- "version": "3.3.22",
3
+ "version": "3.4.1",
4
4
  "description": "Utility Components of Diverse Uses Based on the Lit Library and Web Components Standard.",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -21,8 +21,8 @@
21
21
  "homepage": "https://dile-components.com/",
22
22
  "dependencies": {
23
23
  "@dile/iconlib": "^2.0.2",
24
- "@dile/ui": "^3.22.0",
25
- "@lion/ui": "^0.21.0",
24
+ "@dile/ui": "^3.23.0",
25
+ "@lion/ui": "^0.27.0",
26
26
  "linkify-string": "^4.1.3",
27
27
  "linkifyjs": "^4.1.3",
28
28
  "lit": "^2.7.0 || ^3.0.0",
@@ -31,5 +31,5 @@
31
31
  "publishConfig": {
32
32
  "access": "public"
33
33
  },
34
- "gitHead": "707eaedea1d20e5e5bb081d9a05fab7acc1d698c"
34
+ "gitHead": "828a98ebe286539d42d66f8acf6d5efcdb463136"
35
35
  }