-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathinput-date.js
602 lines (543 loc) · 19.9 KB
/
input-date.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
import '../button/button-subtle.js';
import '../calendar/calendar.js';
import '../dropdown/dropdown.js';
import '../dropdown/dropdown-content.js';
import '../icons/icon.js';
import '../tooltip/tooltip.js';
import './input-text.js';
import { css, html, LitElement } from 'lit';
import { formatDate, getDateTimeDescriptor, parseDate } from '@brightspace-ui/intl/lib/dateTime.js';
import { formatDateInISO, getDateFromISODate, getToday } from '../../helpers/dateTime.js';
import { FocusMixin } from '../../mixins/focus/focus-mixin.js';
import { FormElementMixin } from '../form/form-element-mixin.js';
import { getUniqueId } from '../../helpers/uniqueId.js';
import { ifDefined } from 'lit/directives/if-defined.js';
import { LabelledMixin } from '../../mixins/labelled/labelled-mixin.js';
import { LocalizeCoreElement } from '../../helpers/localize-core-element.js';
import ResizeObserver from 'resize-observer-polyfill/dist/ResizeObserver.es.js';
import { SkeletonMixin } from '../skeleton/skeleton-mixin.js';
import { styleMap } from 'lit/directives/style-map.js';
const mediaQueryList = window.matchMedia('(max-width: 615px)');
export function formatISODateInUserCalDescriptor(val) {
return formatDate(getDateFromISODate(val));
}
/**
* A component that consists of a text input field for typing a date and an attached calendar (d2l-calendar) dropdown. It displays the "value" if one is specified, or a placeholder if not, and reflects the selected value when one is selected in the calendar or entered in the text input.
* @slot inline-help - Help text that will appear below the input. Use this only when other helpful cues are not sufficient, such as a carefully-worded label.
* @fires change - Dispatched when there is a change to selected date. `value` corresponds to the selected value and is formatted in ISO 8601 calendar date format (`YYYY-MM-DD`).
*/
class InputDate extends FocusMixin(LabelledMixin(SkeletonMixin(FormElementMixin(LocalizeCoreElement(LitElement))))) {
static get properties() {
return {
/**
* Disables the input
* @type {boolean}
*/
disabled: { type: Boolean },
/**
* @ignore
* Optionally add a 'Now' button to be used in date-time pickers only.
*/
hasNow: { attribute: 'has-now', type: Boolean },
/**
* Hides the label visually. Hidden labels are still read by screen readers so make sure to set an appropriate label.
* @type {boolean}
*/
labelHidden: { type: Boolean, attribute: 'label-hidden' },
/**
* Maximum valid date that could be selected by a user
* @type {string}
*/
maxValue: { attribute: 'max-value', reflect: true, type: String },
/**
* Minimum valid date that could be selected by a user
* @type {string}
*/
minValue: { attribute: 'min-value', reflect: true, type: String },
/**
* @ignore
* Disables validation of max and min value. The min and max value will still be enforced but the component will not be put into an error state or show an error tooltip.
*/
noValidateMinMax: { attribute: 'novalidateminmax', type: Boolean },
/**
* Indicates if the calendar dropdown is open
* @type {boolean}
*/
opened: { type: Boolean, reflect: true },
/**
* Temporary.
* @ignore
*/
preferFixedPositioning: { type: Boolean, attribute: 'prefer-fixed-positioning' },
/**
* Indicates that a value is required
* @type {boolean}
*/
required: { type: Boolean, reflect: true },
/**
* Value of the input
* @type {string}
*/
value: { type: String },
_hiddenContentWidth: { type: String },
_dateTimeDescriptor: { type: Object },
_dropdownFirstOpened: { type: Boolean },
_formattedValue: { type: String },
_inputTextFocusShowTooltip: { type: Boolean },
_showInfoTooltip: { type: Boolean },
_shownValue: { type: String },
_showRevertInstructions: { state: true },
_showRevertTooltip: { state: true }
};
}
static get styles() {
return [super.styles, css`
:host {
display: inline-block;
width: 100%;
}
:host([hidden]) {
display: none;
}
d2l-dropdown {
width: 100%;
}
d2l-icon {
--d2l-icon-height: 0.8rem;
--d2l-icon-width: 0.8rem;
margin-left: 0.6rem;
margin-right: 0.6rem;
}
:host([disabled]) d2l-icon {
opacity: 0.5;
}
.d2l-input-date-hidden-text {
font-family: inherit;
font-size: 0.8rem;
font-weight: 400;
letter-spacing: 0.02rem;
line-height: 1.4rem;
position: absolute;
visibility: hidden;
width: auto;
}
.d2l-input-date-hidden-text > div {
padding-left: 2rem; /* simulates space taken up by the icon */
}
d2l-calendar {
padding: 0.25rem 0.6rem;
}
.d2l-calendar-slot-buttons {
border-top: 1px solid var(--d2l-color-gypsum);
display: flex;
justify-content: center;
margin-top: 0.3rem;
padding-top: 0.3rem;
}
`];
}
constructor() {
super();
this.disabled = false;
/** @ignore */
this.hasNow = false;
this.labelHidden = false;
/** @ignore */
this.noValidateMinMax = false;
this.opened = false;
this.required = false;
this.value = '';
this._dropdownFirstOpened = false;
this._formattedValue = '';
this._hiddenContentWidth = '8rem';
this._inputId = getUniqueId();
this._inputTextFocusMouseup = false;
this._inputTextFocusShowTooltip = true; // true by default so hover triggers tooltip
this._openCalendarOnly = false;
this._openedOnKeydown = false;
this._showInfoTooltip = true;
this._showRevertInstructions = false;
this._showRevertTooltip = false;
this._shownValue = '';
this._dateTimeDescriptor = getDateTimeDescriptor();
}
static get focusElementSelector() {
return 'd2l-input-text';
}
/** @ignore */
get inputTextWidth() {
return `calc(${this._hiddenContentWidth} + 0.75rem + 3px)`; // text and icon width + paddingRight + border width + 1
}
/** @ignore */
get validationMessage() {
if (this.validity.rangeOverflow || this.validity.rangeUnderflow) {
const minDate = this.minValue ? formatDate(getDateFromISODate(this.minValue), { format: 'medium' }) : null;
const maxDate = this.maxValue ? formatDate(getDateFromISODate(this.maxValue), { format: 'medium' }) : null;
if (minDate && maxDate) {
return this.localize('components.input-date.errorOutsideRange', { minDate, maxDate });
} else if (maxDate) {
return this.localize('components.input-date.errorMaxDateOnly', { maxDate });
} else if (this.minValue) {
return this.localize('components.input-date.errorMinDateOnly', { minDate });
}
}
return super.validationMessage;
}
disconnectedCallback() {
super.disconnectedCallback();
if (this._hiddenContentResizeObserver) this._hiddenContentResizeObserver.disconnect();
}
async firstUpdated(changedProperties) {
super.firstUpdated(changedProperties);
this._textInput = this.shadowRoot.querySelector('d2l-input-text');
const hiddenContent = this.shadowRoot.querySelector('.d2l-input-date-hidden-text');
const tryUpdateHiddenContentWidth = () => {
const width = Math.ceil(parseFloat(getComputedStyle(hiddenContent).getPropertyValue('width')));
if (isNaN(width)) return false; // hidden elements will have "auto" width
this._hiddenContentWidth = `${width}px`;
return true;
};
this.addEventListener('blur', this._handleBlur);
this.addEventListener('d2l-localize-resources-change', () => {
this._dateTimeDescriptor = getDateTimeDescriptor();
this.requestUpdate();
this.updateComplete.then(() => tryUpdateHiddenContentWidth());
});
await (document.fonts ? document.fonts.ready : Promise.resolve());
// resize observer needed to handle case where it's initially hidden
if (!tryUpdateHiddenContentWidth()) {
this._hiddenContentResizeObserver = new ResizeObserver(() => {
if (tryUpdateHiddenContentWidth()) {
this._hiddenContentResizeObserver.disconnect();
this._hiddenContentResizeObserver = null;
}
});
this._hiddenContentResizeObserver.observe(hiddenContent);
}
}
render() {
const formattedWideDate = formatISODateInUserCalDescriptor('2323-12-23');
const shortDateFormat = (this._dateTimeDescriptor.formats.dateFormats.short).toUpperCase();
const clearButton = !this.required ? html`<d2l-button-subtle text="${this.localize('components.input-date.clear')}" @click="${this._handleClear}"></d2l-button-subtle>` : null;
const nowButton = this.hasNow ? html`<d2l-button-subtle text="${this.localize('components.input-date.now')}" @click="${this._handleSetToNow}"></d2l-button-subtle>` : null;
const icon = (this.invalid || this.childErrors.size > 0)
? html`<d2l-icon icon="tier1:alert" slot="left" style="${styleMap({ color: 'var(--d2l-color-cinnabar)' })}"></d2l-icon>`
: html`<d2l-icon icon="tier1:calendar" slot="left"></d2l-icon>`;
const tooltip = this._getErrorTooltip() || this._getRevertTooltip(shortDateFormat);
const inputTextInstructions = (this._showInfoTooltip && !tooltip && !this.invalid && this.childErrors.size === 0 && this._inputTextFocusShowTooltip)
? this.localize('components.input-date.openInstructions', { format: shortDateFormat })
: undefined;
const dropdownContent = this._dropdownFirstOpened ? html`
<d2l-dropdown-content
class="vdiff-target"
@d2l-dropdown-close="${this._handleDropdownClose}"
@d2l-dropdown-open="${this._handleDropdownOpen}"
@d2l-dropdown-focus-enter="${this._handleFocusTrapEnter}"
max-width="335"
min-height="415"
?no-auto-fit="${!mediaQueryList.matches}"
trap-focus
no-auto-focus
mobile-tray="bottom"
no-padding
?prefer-fixed-positioning="${this.preferFixedPositioning}">
<d2l-calendar
@d2l-calendar-selected="${this._handleDateSelected}"
label="${ifDefined(this.label)}"
max-value="${ifDefined(this.maxValue)}"
min-value="${ifDefined(this.minValue)}"
selected-value="${ifDefined(this._shownValue)}">
<div class="d2l-calendar-slot-buttons">
<d2l-button-subtle text="${this.localize('components.input-date.today')}" @click="${this._handleSetToToday}"></d2l-button-subtle>
${nowButton}
${clearButton}
</div>
</d2l-calendar>
</d2l-dropdown-content>` : null;
return html`
<div aria-hidden="true" class="d2l-input-date-hidden-text">
<div>${formattedWideDate}</div>
<div>${shortDateFormat}</div>
</div>
${tooltip}
<d2l-dropdown ?disabled="${this.disabled || this.skeleton}" no-auto-open ?prefer-fixed-positioning="${this.preferFixedPositioning}">
<d2l-input-text
?novalidate="${this.noValidate}"
aria-invalid="${this.invalid ? 'true' : 'false'}"
@blur="${this._handleInputTextBlur}"
@change="${this._handleChange}"
class="d2l-dropdown-opener vdiff-target"
instructions="${ifDefined(inputTextInstructions)}"
?disabled="${this.disabled}"
@focus="${this._handleInputTextFocus}"
@keydown="${this._handleKeydown}"
hide-invalid-icon
id="${this._inputId}"
label="${ifDefined(this.label)}"
?label-hidden="${this.labelHidden || this.labelledBy}"
.labelRequired="${false}"
@mouseup="${this._handleMouseup}"
placeholder="${shortDateFormat}"
?required="${this.required}"
?skeleton="${this.skeleton}"
style="${styleMap({ maxWidth: this.inputTextWidth })}"
.value="${this._formattedValue}">
${icon}
<slot slot="inline-help" name="inline-help"></slot>
</d2l-input-text>
${dropdownContent}
</d2l-dropdown>
`;
}
updated(changedProperties) {
super.updated(changedProperties);
changedProperties.forEach((oldVal, prop) => {
if (prop === '_dateTimeDescriptor' || prop === 'value') {
this._shownValue = this.value;
this._setFormattedValue();
if (prop === 'value') {
this.setFormValue(this.value);
this.setValidity({
rangeUnderflow: !this.noValidateMinMax && this.value && this.minValue && getDateFromISODate(this.value).getTime() < getDateFromISODate(this.minValue).getTime(),
rangeOverflow: !this.noValidateMinMax && this.value && this.maxValue && getDateFromISODate(this.value).getTime() > getDateFromISODate(this.maxValue).getTime()
});
this.requestValidate(false);
}
} else if (prop === 'opened') {
if (this.opened) this._open();
else this._close();
} else if (prop === 'disabled' || prop === 'skeleton') {
if (this.opened) this._open();
}
});
}
willUpdate(changedProperties) {
super.willUpdate(changedProperties);
if (changedProperties.has('_hiddenContentWidth')) this.style.maxWidth = this.inputTextWidth;
}
async validate() {
if (!this.shadowRoot) return;
const textInput = this.shadowRoot.querySelector('d2l-input-text');
const errors = await Promise.all([textInput.validate(), super.validate()]);
return [...errors[0], ...errors[1]];
}
_close() {
if (!this._dropdown || !this._dropdown.opened) return;
this._dropdown.close();
}
_getErrorTooltip() {
if (!this.validationError || this.opened || this.childErrors.size > 0) return null;
const message = (this._showRevertTooltip || this._showRevertInstructions)
? html`
<div>${this.localize('components.input-date.revert', { label: this.label })}</div>
<br>
<div>${this.validationError}</div>`
: this.validationError;
return html`
<d2l-tooltip
align="start"
announced
class="vdiff-target"
for="${this._inputId}"
?force-show="${this._showRevertTooltip}"
state="error">
${message}
</d2l-tooltip>
`;
}
_getRevertTooltip(shortDateFormat) {
if (this.opened || this.invalid || (!this._showRevertInstructions && !this._showRevertTooltip)) return null;
const revertMessage = this.localize('components.input-date.revert', { label: this.label });
const secondaryMessage = this._showRevertInstructions
? this.localize('components.input-date.openInstructions', { format: shortDateFormat })
: this.localize('components.input-date.useDateFormat', { format: shortDateFormat });
return html`
<d2l-tooltip
align="start"
announced
class="vdiff-target"
for="${this._inputId}"
?force-show="${this._showRevertTooltip}">
<div>${revertMessage}</div>
<br>
<div>${secondaryMessage}</div>
</d2l-tooltip>
`;
}
_handleBlur() {
this._showInfoTooltip = true;
this.requestValidate(true);
}
async _handleChange() {
this._showRevertTooltip = false;
const value = this._textInput.value;
const isNewVal = value !== this.value;
if (!value && !this.required) {
if (isNewVal) {
await this._updateValueDispatchEvent('');
if (this._calendar) {
await this.updateComplete;
await this._calendar.reset();
}
}
return;
}
this._formattedValue = value;
await this.updateComplete;
try {
const date = parseDate(value);
await this._updateValueDispatchEvent(formatDateInISO({ year: date.getFullYear(), month: (parseInt(date.getMonth()) + 1), date: date.getDate() }));
} catch {
// leave value the same when invalid input
if (isNewVal) this._showRevertTooltip = true;
}
this._setFormattedValue(); // keep out here in case parseDate is same date, e.g., user adds invalid text to end of parseable date
if (this._calendar) {
await this.updateComplete;
await this._calendar.reset(true);
}
}
async _handleClear() {
await this._updateValueDispatchEvent('');
if (this._dropdown) {
this._dropdown.close();
}
this.focus();
}
async _handleDateSelected(e) {
this._showRevertTooltip = false;
const value = e.target.selectedValue;
await this._updateValueDispatchEvent(value);
if (this._dropdown) {
this._dropdown.close();
}
}
_handleDropdownClose() {
if (this._calendar) this._calendar.reset();
this.opened = false;
this._textInput.scrollIntoView({ block: 'nearest', behavior: 'smooth', inline: 'nearest' });
/** @ignore */
this.dispatchEvent(new CustomEvent(
'd2l-input-date-dropdown-toggle',
{ bubbles: true, composed: false, detail: { opened: false } }
));
}
_handleDropdownOpen() {
if (!this.shadowRoot) return;
const calendarOffset = this.shadowRoot.querySelector('d2l-calendar').getBoundingClientRect();
const fullCalendarVisible = calendarOffset.y + calendarOffset.height < window.innerHeight;
if (this._dropdown && !this._dropdown.openedAbove && !fullCalendarVisible) {
this._dropdown.querySelector('d2l-calendar').scrollIntoView({ block: 'nearest', behavior: 'smooth', inline: 'nearest' });
}
// if keyboard opens (in all cases except mobile calendar view),
// ensure text input is in viewport
if (!(mediaQueryList.matches && this._dropdown.opened)) {
// use setTimeout to wait for keyboard to open on mobile devices
setTimeout(() => {
this._textInput.scrollIntoView({ block: 'nearest', behavior: 'smooth', inline: 'nearest' });
}, 150);
}
/** @ignore */
this.dispatchEvent(new CustomEvent(
'd2l-input-date-dropdown-toggle',
{ bubbles: true, composed: false, detail: { opened: true } }
));
this._showInfoTooltip = false; // tooltip should not reappear after user has opened dropdown and closed unless focus leaves input-date and returns
}
async _handleFirstDropdownOpen() {
this._dropdownFirstOpened = true;
await this.updateComplete;
if (!this.shadowRoot) return;
this._calendar = this.shadowRoot.querySelector('d2l-calendar');
this._dropdown = this.shadowRoot.querySelector('d2l-dropdown-content');
await this._calendar.updateComplete;
}
async _handleFocusTrapEnter() {
if (this._calendar) this._calendar.focus();
}
_handleInputTextBlur() {
this._inputTextFocusMouseup = false;
this._inputTextFocusShowTooltip = true;
this._showRevertInstructions = false;
}
async _handleInputTextFocus() {
if (this._showRevertTooltip) {
this._showRevertTooltip = false;
await this.updateComplete;
this._showRevertInstructions = true;
}
this._formattedValue = this._shownValue ? formatISODateInUserCalDescriptor(this._shownValue) : '';
// hide tooltip when focus, wait to see if click happened, then show
this._inputTextFocusShowTooltip = false;
setTimeout(() => {
if (!this._inputTextFocusMouseup) this._inputTextFocusShowTooltip = true;
}, 150);
}
_handleKeydown(e) {
// open dropdown on down arrow or enter and focus on calendar focus date
if (e.keyCode === 40 || e.keyCode === 13) {
this._openedOnKeydown = true;
this.opened = true;
e.preventDefault();
}
}
_handleMouseup(e) {
this._inputTextFocusMouseup = true;
this._openCalendarOnly = e.srcElement.tagName.toLowerCase() === 'd2l-icon';
this.opened = !this.opened;
}
async _handleSetToNow() {
await this._handleSetToToday(undefined, true);
}
async _handleSetToToday(_, setToNow) {
const date = getToday();
await this._updateValueDispatchEvent(formatDateInISO(date), setToNow);
if (this._dropdown) {
this._dropdown.close();
}
this.focus();
}
async _open() {
if (this.disabled || this.skeleton) return;
if (!this._dropdownFirstOpened || !this._dropdown) await this._handleFirstDropdownOpen();
await this._handleChange();
// on small screens, only open calendar if calendar icon is selected,
// otherwise only open text input
if (mediaQueryList.matches && this._openCalendarOnly) {
this._dropdown.toggleOpen(true);
} else if (mediaQueryList.matches && !this._openCalendarOnly && !this._openedOnKeydown) {
this._openCalendarOnly = false;
this._openedOnKeydown = false;
this.opened = false;
return;
}
else if (this._inputTextFocusMouseup) {
this._dropdown.open(false);
} else {
this._dropdown.open();
this._calendar.focus();
this._setFormattedValue();
}
if (mediaQueryList.matches) this._calendar.focus();
this._openCalendarOnly = false;
this._openedOnKeydown = false;
}
_setFormattedValue() {
this._formattedValue = this._shownValue ? formatISODateInUserCalDescriptor(this._shownValue) : '';
}
async _updateValueDispatchEvent(dateInISO, setToNow) {
// prevent validation from happening multiple times for same change,
// except for now button that affects time
if (!setToNow && dateInISO === this._shownValue) return;
this._shownValue = dateInISO;
this.value = dateInISO;
this.dispatchEvent(new CustomEvent(
'change', {
bubbles: true,
composed: false,
detail: { setToNow: setToNow }
}
));
}
}
customElements.define('d2l-input-date', InputDate);