/
datepicker.js
627 lines (546 loc) · 19.9 KB
/
datepicker.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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
import { Controller } from '@hotwired/stimulus'
import IsoDate from './iso_date.js'
// All dates are local, not UTC.
export default class Datepicker extends Controller {
static targets = ['input', 'hidden', 'toggle', 'calendar',
'month', 'year', 'prevMonth', 'today', 'nextMonth', 'days']
static values = {
date: String,
min: String,
max: String,
format: {type: String, default: '%Y-%m-%d'},
firstDayOfWeek: {type: Number, default: 1},
dayNameLength: {type: Number, default: 2},
allowWeekends: {type: Boolean, default: true},
monthJump: {type: String, default: 'dayOfMonth'},
disallow: Array,
text: Object
}
static defaultTextValue = {
underflow: '',
overflow: '',
previousMonth: 'Previous month',
nextMonth: 'Next month',
today: 'Today',
chooseDate: 'Choose Date',
changeDate: 'Change Date'
}
text(key) {
return {...this.constructor.defaultTextValue, ...this.textValue}[key]
}
connect() {
if (!this.hasHiddenTarget) this.addHiddenInput()
this.addInputAction()
this.addToggleAction()
this.setToggleAriaLabel()
this.dateValue = this.inputTarget.value
}
dateValueChanged(value, previousValue) {
if (!this.hasHiddenTarget) return
this.hiddenTarget.value = value
this.inputTarget.value = this.format(value)
// Trigger change event on input when user selects date from picker.
// http://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event
if (value != previousValue) this.inputTarget.dispatchEvent(new Event('change'))
this.validate(value)
}
validate(dateStr) {
const message = this.validationMessage(dateStr)
this.inputTarget.setCustomValidity(message)
if (message) this.inputTarget.reportValidity()
}
validationMessage(dateStr) {
if (!dateStr) return ''
const isoDate = new IsoDate(dateStr)
return this.rangeUnderflow(isoDate) ? this.underflowMessage()
: this.rangeOverflow(isoDate) ? this.overflowMessage()
: ''
}
underflowMessage() {
return this.text('underflow').replace('%s', this.format(this.minValue))
}
overflowMessage() {
return this.text('overflow').replace('%s', this.format(this.maxValue))
}
addHiddenInput() {
this.inputTarget.insertAdjacentHTML('afterend', `
<input type="hidden"
name="${this.inputTarget.getAttribute('name')}"
data-datepicker-target="hidden"/>
`)
}
addInputAction() {
this.addAction(this.inputTarget, 'datepicker#update')
}
addToggleAction() {
if (!this.hasToggleTarget) return
let action = 'click->datepicker#toggle'
if (!(this.toggleTarget instanceof HTMLButtonElement)) action += ' keydown->datepicker#toggle'
this.addAction(this.toggleTarget, action)
}
addAction(element, action) {
if (('action') in element.dataset) {
element.dataset.action += ` ${action}`
} else {
element.dataset.action = action
}
}
setToggleAriaLabel(value = this.text('chooseDate')) {
if (!this.hasToggleTarget) return
this.toggleTarget.setAttribute('aria-label', value);
}
update() {
const dateStr = this.parse(this.inputTarget.value)
if (dateStr != '') this.dateValue = dateStr
}
toggle(event) {
event.preventDefault()
event.stopPropagation()
if (event.type == 'keydown' && ![' ', 'Enter'].includes(event.key)) return
this.hasCalendarTarget ? this.close(true) : this.open(true)
}
close(animate) {
if (animate) {
this.calendarTarget.onanimationend = e => e.target.remove()
this.calendarTarget.classList.add('fade-out')
} else {
this.calendarTarget.remove()
}
this.toggleTarget.focus()
}
open(animate, isoDate = this.initialIsoDate()) {
this.render(isoDate)
this.focusDate(isoDate)
}
// Returns the date to focus on initially. This is `dateValue` if given
// or today. Whichever is used, it is clamped to `minValue` and/or `maxValue`
// dates if given.
initialIsoDate() {
return this.clamp(new IsoDate(this.dateValue))
}
clamp(isoDate) {
return this.rangeUnderflow(isoDate) ? new IsoDate(this.minValue)
: this.rangeOverflow(isoDate) ? new IsoDate(this.maxValue)
: isoDate
}
rangeUnderflow(isoDate) {
return this.hasMinValue && isoDate.before(new IsoDate(this.minValue))
}
rangeOverflow(isoDate) {
return this.hasMaxValue && isoDate.after(new IsoDate(this.maxValue))
}
isOutOfRange(isoDate) {
return this.rangeUnderflow(isoDate) || this.rangeOverflow(isoDate)
}
closeOnOutsideClick(event) {
// `event.target` could already have been removed from the DOM
// (e.g. if the previous-month button was clicked) so we cannot
// use `this.calendarTarget.contains(event.target)`.
if (event.target.closest('[data-datepicker-target="calendar"]')) return
this.close(true)
}
redraw() {
const isoDate = this.dateFromMonthYearSelectsAndDayGrid()
this.close(false)
this.open(false, isoDate)
}
gotoPrevMonth() {
const isoDate = this.dateFromMonthYearSelectsAndDayGrid()
this.close(false)
this.open(false, isoDate.previousMonth(this.monthJumpValue == 'dayOfMonth'))
this.prevMonthTarget.focus()
}
gotoNextMonth() {
const isoDate = this.dateFromMonthYearSelectsAndDayGrid()
this.close(false)
this.open(false, isoDate.nextMonth(this.monthJumpValue == 'dayOfMonth'))
this.nextMonthTarget.focus()
}
gotoToday() {
this.close(false)
this.open(false, new IsoDate())
this.todayTarget.focus()
}
// Returns a date where the month and year come from the dropdowns
// and the day of the month from the grid.
// @return [IsoDate]
dateFromMonthYearSelectsAndDayGrid() {
const year = this.yearTarget.value
const month = this.monthTarget.value
let day = this.daysTarget.querySelector('button[tabindex="0"] time').textContent
const daysInMonth = IsoDate.daysInMonth(+month, +year)
if (day > daysInMonth) day = daysInMonth
return new IsoDate(year, month, day)
}
// Generates the HTML for the calendar and inserts it into the DOM.
//
// Does not focus the given date.
//
// @param isoDate [IsoDate] the date of interest
render(isoDate) {
const cal = `
<div class="sdp-cal" data-datepicker-target="calendar" data-action="click@window->datepicker#closeOnOutsideClick keydown->datepicker#key" role="dialog" aria-modal="true" aria-label="${this.text('chooseDate')}">
<div class="sdp-nav">
<div class="sdp-nav-dropdowns">
<div>
<select class="sdp-month" data-datepicker-target="month" data-action="datepicker#redraw">
${this.monthOptions(+isoDate.mm)}
</select>
</div>
<div>
<select class="sdp-year" data-datepicker-target="year" data-action="datepicker#redraw">
${this.yearOptions(+isoDate.yyyy)}
</select>
</div>
</div>
<div class="sdp-nav-buttons">
<button class="sdp-goto-prev" data-datepicker-target="prevMonth" data-action="datepicker#gotoPrevMonth" title="${this.text('previousMonth')}" aria-label="${this.text('previousMonth')}">
<svg viewBox="0 0 10 10">
<polyline points="7,1 3,5 7,9" />
</svg>
</button>
<button class="sdp-goto-today" data-datepicker-target="today" data-action="datepicker#gotoToday" title="${this.text('today')}" aria-label="${this.text('today')}">
<svg viewBox="0 0 10 10">
<circle cx="5" cy="5" r="4" />
</svg>
</button>
<button class="sdp-goto-next" data-datepicker-target="nextMonth" data-action="datepicker#gotoNextMonth" title="${this.text('nextMonth')}" aria-label="${this.text('nextMonth')}">
<svg viewBox="0 0 10 10">
<polyline points="3,1 7,5 3,9" />
</svg>
</button>
</div>
</div>
<div class="sdp-days-of-week">
${this.daysOfWeek()}
</div>
<div class="sdp-days" data-datepicker-target="days" data-action="click->datepicker#pick" role="grid">
${this.days(isoDate)}
</div>
</div>
`
this.element.insertAdjacentHTML('beforeend', cal)
}
monthTargetConnected() {
this.autoSizeSelect(this.monthTarget)
}
yearTargetConnected() {
this.autoSizeSelect(this.yearTarget)
}
// Set select's width to the width of the selected option.
autoSizeSelect(select) {
const tempSelect = document.createElement('select')
const tempOption = document.createElement('option')
tempOption.textContent = select.options[select.selectedIndex].text
tempSelect.style.cssText += 'visibility: hidden; position: fixed;'
tempSelect.appendChild(tempOption)
select.after(tempSelect)
const tempSelectWidth = tempSelect.getBoundingClientRect().width
select.style.width = `${tempSelectWidth}px`
tempSelect.remove()
}
pick(event) {
event.preventDefault()
let button, time
switch (event.target.constructor) {
case HTMLTimeElement:
time = event.target
button = time.parentElement
break
case HTMLButtonElement:
button = event.target
time = button.children[0]
break
default:
return
}
if (button.hasAttribute('aria-disabled')) return
const dateStr = time.getAttribute('datetime')
this.selectDate(new IsoDate(dateStr))
}
key(event) {
switch (event.key) {
case 'Escape':
this.close(true)
return
case 'Tab':
if (event.shiftKey) {
if (document.activeElement == this.firstTabStop()) {
event.preventDefault()
this.lastTabStop().focus()
}
} else {
if (document.activeElement == this.lastTabStop()) {
event.preventDefault()
this.firstTabStop().focus()
}
}
return
}
const button = event.target
if (!this.daysTarget.contains(button)) return
const dateStr = button.children[0].getAttribute('datetime')
const isoDate = new IsoDate(dateStr)
switch (event.key) {
case 'Enter':
case ' ':
event.preventDefault()
if (!button.hasAttribute('aria-disabled')) this.selectDate(isoDate)
break
case 'ArrowUp':
case 'k':
this.focusDate(isoDate.previousWeek())
break
case 'ArrowDown':
case 'j':
this.focusDate(isoDate.nextWeek())
break
case 'ArrowLeft':
case 'h':
this.focusDate(isoDate.previousDay())
break
case 'ArrowRight':
case 'l':
this.focusDate(isoDate.nextDay())
break
case 'Home':
case '0':
case '^':
this.focusDate(isoDate.firstDayOfWeek(this.firstDayOfWeekValue))
break
case 'End':
case '$':
this.focusDate(isoDate.lastDayOfWeek(this.firstDayOfWeekValue))
break
case 'PageUp':
event.shiftKey
? this.focusDate(isoDate.previousYear())
: this.focusDate(isoDate.previousMonth(this.monthJumpIsDayOfMonth()))
break
case 'PageDown':
event.shiftKey
? this.focusDate(isoDate.nextYear())
: this.focusDate(isoDate.nextMonth(this.monthJumpIsDayOfMonth()))
break
case 'b':
this.focusDate(isoDate.previousMonth(this.monthJumpIsDayOfMonth()))
break
case 'B':
this.focusDate(isoDate.previousYear())
break
case 'w':
this.focusDate(isoDate.nextMonth(this.monthJumpIsDayOfMonth()))
break
case 'W':
this.focusDate(isoDate.nextYear())
break
}
}
firstTabStop() {
return this.monthTarget
}
lastTabStop() {
return this.calendarTarget.querySelector('.sdp-days button[tabindex="0"]')
}
monthJumpIsDayOfMonth() {
return this.monthJumpValue == 'dayOfMonth'
}
// @param isoDate [isoDate] the date to select
selectDate(isoDate) {
this.close(true)
this.toggleTarget.focus()
this.dateValue = isoDate.toString()
}
// Focuses the given date in the calendar.
// If the date is not visible because it is in the hidden part of the previous or
// next month, the calendar is updated to show the corresponding month.
//
// @param isoDate [IsoDate] the date to focus on in the calendar
focusDate(isoDate) {
const time = this.daysTarget.querySelector(`time[datetime="${isoDate.toString()}"]`)
if (!time) {
const leadingDatetime = this.daysTarget.querySelector('time').getAttribute('datetime')
if (isoDate.before(new IsoDate(leadingDatetime))) {
this.gotoPrevMonth()
} else {
this.gotoNextMonth()
}
this.focusDate(isoDate)
return
}
const currentFocus = this.daysTarget.querySelector('button[tabindex="0"]')
if (currentFocus) currentFocus.setAttribute('tabindex', -1)
const button = time.parentElement
button.setAttribute('tabindex', 0)
button.focus()
if (!button.hasAttribute('aria-disabled')) {
this.setToggleAriaLabel(`${this.text('changeDate')}, ${this.format(isoDate.toString())}`)
}
}
// @param selected [Number] the selected month (January is 1)
monthOptions(selected) {
return this.monthNames('long')
.map((name, i) => `<option value="${i + 1}" ${i + 1 == selected ? 'selected' : ''}>${name}</option>`)
.join('')
}
// @param selected [Number] the selected year
yearOptions(selected) {
const years = []
const extent = 10
for (let y = selected - extent; y <= selected + extent; y++) years.push(y)
return years
.map(year => `<option ${year == selected ? 'selected' : ''}>${year}</option>`)
.join('')
}
daysOfWeek() {
return this.dayNames('long')
.map(name => `<div title="${name}">${name.slice(0, this.dayNameLengthValue)}</div>`)
.join('')
}
// Generates the day grid for the given date's month.
// The end of the previous month and the start of the next month
// are shown if there is space in the grid.
//
// Does not focus on the given date.
//
// @param isoDate [IsoDate] the month of interest
// @return [String] HTML for the day grid
days(isoDate) {
const days = []
const selected = new IsoDate(this.dateValue)
let date = isoDate.setDayOfMonth(1).firstDayOfWeek(this.firstDayOfWeekValue)
while (true) {
const isPreviousMonth = date.mm != isoDate.mm && date.before(isoDate)
const isNextMonth = date.mm != isoDate.mm && date.after(isoDate)
if (isNextMonth && date.isFirstDayOfWeek(this.firstDayOfWeekValue)) break
const klass = this.classAttribute(
isPreviousMonth ? 'sdp-prev-month' : '',
isNextMonth ? 'sdp-next-month' : '',
date.isToday() ? 'sdp-today' : '',
date.isWeekend() ? 'sdp-weekend' : '',
date.equals(selected) ? 'sdp-selected' : ''
)
days.push(`
<button type="button"
tabindex="-1"
${klass}
${date.equals(selected) ? 'aria-selected="true"' : ''}
${this.isDisabled(date) ? 'aria-disabled="true"' : ''}
>
<time datetime="${date.toString()}">${+date.dd}</time>
</button>
`)
date = date.nextDay()
}
return days.join('')
}
classAttribute(...classes) {
const presentClasses = classes.filter(c => c)
if (presentClasses.length == 0) return ''
return `class="${presentClasses.join(' ')}"`
}
isDisabled(isoDate) {
return this.isOutOfRange(isoDate)
|| (isoDate.isWeekend() && !this.allowWeekendsValue)
|| (this.disallowValue.includes(isoDate.toString()))
}
// Formats an ISO8601 date, using the `format` value, for display to the user.
// Returns an empty string if `str` cannot be formatted.
//
// @param str [String] a date in YYYY-MM-DD format
// @return [String] the date in a user-facing format, or an empty string if the
// given date cannot be formatted
format(str) {
if (!IsoDate.isValidStr(str)) return ''
const [yyyy, mm, dd] = str.split('-')
return this.formatValue
.replace('%d', dd)
.replace('%-d', +dd)
.replace('%m', this.zeroPad(mm))
.replace('%-m', +mm)
.replace('%B', this.localisedMonth(mm, 'long'))
.replace('%b', this.localisedMonth(mm, 'short'))
.replace('%Y', yyyy)
.replace('%y', +yyyy % 100)
}
// Returns a two-digit zero-padded string.
zeroPad(num) {
return num.toString().padStart(2, '0')
}
// Parses a date from the user, using the `format` value, into an ISO8601 date.
// Returns an empty string if `str` cannot be parsed.
//
// @param str [String] a user-facing date, e.g. 19/03/2022
// @return [String] the date in ISO8601 format, e.g. 2022-03-19; or an empty string
// if the given date cannot be parsed
parse(str) {
const directives = {
'd': ['\\d{2}', function(match) { this.day = +match }],
'-d': ['\\d{1,2}', function(match) { this.day = +match }],
'm': ['\\d{2}', function(match) { this.month = +match }],
'-m': ['\\d{1,2}', function(match) { this.month = +match }],
'B': ['\\w+', function(match, controller) { this.month = controller.monthNumber(match, 'long') }],
'b': ['\\w{3}', function(match, controller) { this.month = controller.monthNumber(match, 'short') }],
'Y': ['\\d{4}', function(match) { this.year = +match }],
'y': ['\\d{2}', function(match) { this.year = 2000 + +match }]
}
const funcs = []
const re = new RegExp(
this.formatValue.replace(/%(d|-d|m|-m|B|b|Y|y)/g, function(_, p) {
const directive = directives[p]
funcs.push(directive[1])
return `(${directive[0]})`
}))
const matches = str.match(re)
if (!matches) return ''
const parts = {}
for (let i = 0, len = funcs.length; i < len; i++) {
funcs[i].call(parts, matches[i + 1], this)
}
if (!IsoDate.isValidDate(parts.year, parts.month, parts.day)) return ''
return new IsoDate(parts.year, parts.month, parts.day).toString()
}
// Returns the name of the month in the current locale.
//
// @param month [Number] the month number (January is 1)
// @param monthFormat [String] "long" (January) | "short" (Jan)
// @return [String] the localised month name
localisedMonth(month, monthFormat) {
// Use the middle of the month to avoid timezone edge cases
return new Date(`2022-${month}-15`).toLocaleString('default', {month: monthFormat})
}
// Returns the number of the month (January is 1).
//
// @param name [String] the name of the month in the current locale (e.g. January or Jan)
// @param monthFormat [String] "long" (January) | "short" (Jan)
// @return [Number] the number of the month, or 0 if name is not recognised
monthNumber(name, monthFormat) {
return this.monthNames(monthFormat).findIndex(m => name.includes(m)) + 1
}
// Returns the month names in the the current locale.
//
// @param format [String] "long" (January) | "short" (Jan)
// @return [Array] localised month names
monthNames(format) {
const formatter = new Intl.DateTimeFormat('default', {month: format})
return ['01','02','03','04','05','06','07','08','09','10','11','12'].map(mm =>
// Use the middle of the month to avoid timezone edge cases
formatter.format(new Date(`2022-${mm}-15`))
)
}
// Returns the day names in the current locale, starting with the
// firstDayOfTheWeekValue.
//
// @param format [String] "long" (Monday) | "short" (Mon) | "narrow" (M)
// @return [Array] localised day names
dayNames(format) {
const formatter = new Intl.DateTimeFormat('default', {weekday: format})
const names = []
// Ensure date in month is two digits. 2022-04-10 is a Sunday
for (let i = this.firstDayOfWeekValue + 10, n = i + 7; i < n; i++) {
names.push(formatter.format(new Date(`2022-04-${i}T00:00:00`)))
}
return names
}
}
export { Datepicker }