@ministryofjustice/frontend 2.1.3 → 2.2.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.
@@ -0,0 +1,933 @@
1
+ /**
2
+ * Datepicker config
3
+ *
4
+ * @typedef {object} DatepickerConfig
5
+ * @property {string} [excludedDates] - Dates that cannot be selected
6
+ * @property {string} [excludedDays] - Days that cannot be selected
7
+ * @property {boolean} [leadingZeroes] - Whether to add leading zeroes when populating the field
8
+ * @property {string} [minDate] - The earliest available date
9
+ * @property {string} [maxDate] - The latest available date
10
+ * @property {string} [weekStartDay] - First day of the week in calendar view
11
+ */
12
+
13
+ /**
14
+ * @param {HTMLElement} $module - HTML element
15
+ * @param {DatepickerConfig} config - config object
16
+ * @constructor
17
+ */
18
+ function Datepicker($module, config) {
19
+ if (!$module) {
20
+ return this;
21
+ }
22
+
23
+ const schema = Object.freeze({
24
+ properties: {
25
+ excludedDates: { type: "string" },
26
+ excludedDays: { type: "string" },
27
+ leadingZeros: { type: "string" },
28
+ maxDate: { type: "string" },
29
+ minDate: { type: "string" },
30
+ weekStartDay: { type: "string" },
31
+ },
32
+ });
33
+
34
+ const defaults = {
35
+ leadingZeros: false,
36
+ weekStartDay: "monday",
37
+ };
38
+
39
+ // data attributes override JS config, which overrides defaults
40
+ this.config = this.mergeConfigs(
41
+ defaults,
42
+ config,
43
+ this.parseDataset(schema, $module.dataset),
44
+ );
45
+
46
+ this.dayLabels = [
47
+ "Monday",
48
+ "Tuesday",
49
+ "Wednesday",
50
+ "Thursday",
51
+ "Friday",
52
+ "Saturday",
53
+ "Sunday",
54
+ ];
55
+
56
+ this.monthLabels = [
57
+ "January",
58
+ "February",
59
+ "March",
60
+ "April",
61
+ "May",
62
+ "June",
63
+ "July",
64
+ "August",
65
+ "September",
66
+ "October",
67
+ "November",
68
+ "December",
69
+ ];
70
+
71
+ this.currentDate = new Date();
72
+ this.currentDate.setHours(0, 0, 0, 0);
73
+ this.calendarDays = [];
74
+ this.excludedDates = [];
75
+ this.excludedDays = [];
76
+
77
+ this.buttonClass = "moj-datepicker__button";
78
+ this.selectedDayButtonClass = "moj-datepicker__button--selected";
79
+ this.currentDayButtonClass = "moj-datepicker__button--current";
80
+ this.todayButtonClass = "moj-datepicker__button--today";
81
+
82
+ this.$module = $module;
83
+ this.$input = $module.querySelector(".moj-js-datepicker-input");
84
+ }
85
+
86
+ Datepicker.prototype.init = function () {
87
+ // Check that required elements are present
88
+ if (!this.$input) {
89
+ return;
90
+ }
91
+
92
+ this.setOptions();
93
+ this.initControls();
94
+ };
95
+
96
+ Datepicker.prototype.initControls = function () {
97
+ this.id = `datepicker-${this.$input.id}`;
98
+
99
+ this.$dialog = this.createDialog();
100
+ this.createCalendarHeaders();
101
+
102
+ const $componentWrapper = document.createElement("div");
103
+ const $inputWrapper = document.createElement("div");
104
+ $componentWrapper.classList.add("moj-datepicker__wrapper");
105
+ $inputWrapper.classList.add("govuk-input__wrapper");
106
+
107
+ this.$input.parentNode.insertBefore($componentWrapper, this.$input);
108
+ $componentWrapper.appendChild($inputWrapper);
109
+ $inputWrapper.appendChild(this.$input);
110
+
111
+ $inputWrapper.insertAdjacentHTML("beforeend", this.toggleTemplate());
112
+ $componentWrapper.insertAdjacentElement("beforeend", this.$dialog);
113
+
114
+ this.$calendarButton = this.$module.querySelector(
115
+ ".moj-js-datepicker-toggle",
116
+ );
117
+ this.$dialogTitle = this.$dialog.querySelector(
118
+ ".moj-js-datepicker-month-year",
119
+ );
120
+
121
+ this.createCalendar();
122
+
123
+ this.$prevMonthButton = this.$dialog.querySelector(
124
+ ".moj-js-datepicker-prev-month",
125
+ );
126
+ this.$prevYearButton = this.$dialog.querySelector(
127
+ ".moj-js-datepicker-prev-year",
128
+ );
129
+ this.$nextMonthButton = this.$dialog.querySelector(
130
+ ".moj-js-datepicker-next-month",
131
+ );
132
+ this.$nextYearButton = this.$dialog.querySelector(
133
+ ".moj-js-datepicker-next-year",
134
+ );
135
+ this.$cancelButton = this.$dialog.querySelector(".moj-js-datepicker-cancel");
136
+ this.$okButton = this.$dialog.querySelector(".moj-js-datepicker-ok");
137
+
138
+ // add event listeners
139
+ this.$prevMonthButton.addEventListener("click", (event) =>
140
+ this.focusPreviousMonth(event, false),
141
+ );
142
+ this.$prevYearButton.addEventListener("click", (event) =>
143
+ this.focusPreviousYear(event, false),
144
+ );
145
+ this.$nextMonthButton.addEventListener("click", (event) =>
146
+ this.focusNextMonth(event, false),
147
+ );
148
+ this.$nextYearButton.addEventListener("click", (event) =>
149
+ this.focusNextYear(event, false),
150
+ );
151
+ this.$cancelButton.addEventListener("click", (event) => {
152
+ event.preventDefault();
153
+ this.closeDialog(event);
154
+ });
155
+ this.$okButton.addEventListener("click", () => {
156
+ this.selectDate(this.currentDate);
157
+ });
158
+
159
+ const dialogButtons = this.$dialog.querySelectorAll(
160
+ 'button:not([disabled="true"])',
161
+ );
162
+ // eslint-disable-next-line prefer-destructuring
163
+ this.$firstButtonInDialog = dialogButtons[0];
164
+ this.$lastButtonInDialog = dialogButtons[dialogButtons.length - 1];
165
+ this.$firstButtonInDialog.addEventListener("keydown", (event) =>
166
+ this.firstButtonKeydown(event),
167
+ );
168
+ this.$lastButtonInDialog.addEventListener("keydown", (event) =>
169
+ this.lastButtonKeydown(event),
170
+ );
171
+
172
+ this.$calendarButton.addEventListener("click", (event) =>
173
+ this.toggleDialog(event),
174
+ );
175
+
176
+ this.$dialog.addEventListener("keydown", (event) => {
177
+ if (event.key == "Escape") {
178
+ this.closeDialog();
179
+ event.preventDefault();
180
+ event.stopPropagation();
181
+ }
182
+ });
183
+
184
+ document.body.addEventListener("mouseup", (event) =>
185
+ this.backgroundClick(event),
186
+ );
187
+
188
+ // populates calendar with initial dates, avoids Wave errors about null buttons
189
+ this.updateCalendar();
190
+ };
191
+
192
+ Datepicker.prototype.createDialog = function () {
193
+ const titleId = `datepicker-title-${this.$input.id}`;
194
+ const $dialog = document.createElement("div");
195
+
196
+ $dialog.id = this.id;
197
+ $dialog.setAttribute("class", "moj-datepicker__dialog");
198
+ $dialog.setAttribute("role", "dialog");
199
+ $dialog.setAttribute("aria-modal", "true");
200
+ $dialog.setAttribute("aria-labelledby", titleId);
201
+ $dialog.innerHTML = this.dialogTemplate(titleId);
202
+
203
+ return $dialog;
204
+ };
205
+
206
+ Datepicker.prototype.createCalendar = function () {
207
+ const $tbody = this.$dialog.querySelector("tbody");
208
+ let dayCount = 0;
209
+ for (let i = 0; i < 6; i++) {
210
+ // create row
211
+ const $row = $tbody.insertRow(i);
212
+
213
+ for (let j = 0; j < 7; j++) {
214
+ // create cell (day)
215
+ const $cell = document.createElement("td");
216
+ const $dateButton = document.createElement("button");
217
+
218
+ $cell.appendChild($dateButton);
219
+ $row.appendChild($cell);
220
+
221
+ const calendarDay = new DSCalendarDay($dateButton, dayCount, i, j, this);
222
+ calendarDay.init();
223
+ this.calendarDays.push(calendarDay);
224
+ dayCount++;
225
+ }
226
+ }
227
+ };
228
+
229
+ Datepicker.prototype.toggleTemplate = function () {
230
+ return `<button class="moj-datepicker__toggle moj-js-datepicker-toggle" type="button" aria-haspopup="dialog" aria-controls="${this.id}" aria-expanded="false">
231
+ <span class="govuk-visually-hidden">Choose date</span>
232
+ <svg width="32" height="24" focusable="false" class="moj-datepicker-icon" aria-hidden="true" role="img" viewBox="0 0 22 22">
233
+ <path
234
+ fill="currentColor"
235
+ fill-rule="evenodd"
236
+ clip-rule="evenodd"
237
+ d="M16.1333 2.93333H5.86668V4.4C5.86668 5.21002 5.21003 5.86667 4.40002 5.86667C3.59 5.86667 2.93335 5.21002 2.93335 4.4V2.93333H2C0.895431 2.93333 0 3.82877 0 4.93334V19.2667C0 20.3712 0.89543 21.2667 2 21.2667H20C21.1046 21.2667 22 20.3712 22 19.2667V4.93333C22 3.82876 21.1046 2.93333 20 2.93333H19.0667V4.4C19.0667 5.21002 18.41 5.86667 17.6 5.86667C16.79 5.86667 16.1333 5.21002 16.1333 4.4V2.93333ZM20.5333 8.06667H1.46665V18.8C1.46665 19.3523 1.91436 19.8 2.46665 19.8H19.5333C20.0856 19.8 20.5333 19.3523 20.5333 18.8V8.06667Z"
238
+ ></path>
239
+ <rect x="3.66669" width="1.46667" height="5.13333" rx="0.733333" fill="currentColor"></rect>
240
+ <rect x="16.8667" width="1.46667" height="5.13333" rx="0.733333" fill="currentColor"></rect>
241
+ </svg>
242
+ </button>`;
243
+ };
244
+
245
+ /**
246
+ * HTML template for calendar dialog
247
+ *
248
+ * @param {string} [titleId] - Id attribute for dialog title
249
+ * @return {string}
250
+ */
251
+ Datepicker.prototype.dialogTemplate = function (titleId) {
252
+ return `<div class="moj-datepicker__dialog-header">
253
+ <div class="moj-datepicker__dialog-navbuttons">
254
+ <button class="moj-datepicker__button moj-js-datepicker-prev-year">
255
+ <span class="govuk-visually-hidden">Previous year</span>
256
+ <svg width="44" height="40" viewBox="0 0 44 40" fill="none" fill="none" focusable="false" aria-hidden="true" role="img">
257
+ <path fill-rule="evenodd" clip-rule="evenodd" d="M23.1643 20L28.9572 14.2071L27.5429 12.7929L20.3358 20L27.5429 27.2071L28.9572 25.7929L23.1643 20Z" fill="currentColor"/>
258
+ <path fill-rule="evenodd" clip-rule="evenodd" d="M17.1643 20L22.9572 14.2071L21.5429 12.7929L14.3358 20L21.5429 27.2071L22.9572 25.7929L17.1643 20Z" fill="currentColor"/>
259
+ </svg>
260
+ </button>
261
+
262
+ <button class="moj-datepicker__button moj-js-datepicker-prev-month">
263
+ <span class="govuk-visually-hidden">Previous month</span>
264
+ <svg width="44" height="40" viewBox="0 0 44 40" fill="none" focusable="false" aria-hidden="true" role="img">
265
+ <path fill-rule="evenodd" clip-rule="evenodd" d="M20.5729 20L25.7865 14.2071L24.5137 12.7929L18.0273 20L24.5137 27.2071L25.7865 25.7929L20.5729 20Z" fill="currentColor"/>
266
+ </svg>
267
+ </button>
268
+ </div>
269
+
270
+ <h2 id="${titleId}" class="moj-datepicker__dialog-title moj-js-datepicker-month-year" aria-live="polite">June 2020</h2>
271
+
272
+ <div class="moj-datepicker__dialog-navbuttons">
273
+ <button class="moj-datepicker__button moj-js-datepicker-next-month">
274
+ <span class="govuk-visually-hidden">Next month</span>
275
+ <svg width="44" height="40" viewBox="0 0 44 40" fill="none" focusable="false" aria-hidden="true" role="img">
276
+ <path fill-rule="evenodd" clip-rule="evenodd" d="M23.4271 20L18.2135 14.2071L19.4863 12.7929L25.9727 20L19.4863 27.2071L18.2135 25.7929L23.4271 20Z" fill="currentColor"/>
277
+ </svg>
278
+ </button>
279
+
280
+ <button class="moj-datepicker__button moj-js-datepicker-next-year">
281
+ <span class="govuk-visually-hidden">Next year</span>
282
+ <svg width="44" height="40" viewBox="0 0 44 40" fill="none" fill="none" focusable="false" aria-hidden="true" role="img">
283
+ <path fill-rule="evenodd" clip-rule="evenodd" d="M20.8357 20L15.0428 14.2071L16.4571 12.7929L23.6642 20L16.4571 27.2071L15.0428 25.7929L20.8357 20Z" fill="currentColor"/>
284
+ <path fill-rule="evenodd" clip-rule="evenodd" d="M26.8357 20L21.0428 14.2071L22.4571 12.7929L29.6642 20L22.4571 27.2071L21.0428 25.7929L26.8357 20Z" fill="currentColor"/>
285
+ </svg>
286
+ </button>
287
+ </div>
288
+ </div>
289
+
290
+ <table class="moj-datepicker__calendar moj-js-datepicker-grid" role="grid" aria-labelledby="${titleId}">
291
+ <thead>
292
+ <tr></tr>
293
+ </thead>
294
+
295
+ <tbody></tbody>
296
+ </table>
297
+
298
+ <div class="govuk-button-group">
299
+ <button type="button" class="govuk-button moj-js-datepicker-ok">Select</button>
300
+ <button type="button" class="govuk-button govuk-button--secondary moj-js-datepicker-cancel">Close</button>
301
+ </div>`;
302
+ };
303
+
304
+ Datepicker.prototype.createCalendarHeaders = function () {
305
+ this.dayLabels.forEach((day) => {
306
+ const html = `<th scope="col"><span aria-hidden="true">${day.substring(0, 3)}</span><span class="govuk-visually-hidden">${day}</span></th>`;
307
+ const $headerRow = this.$dialog.querySelector("thead > tr");
308
+ $headerRow.insertAdjacentHTML("beforeend", html);
309
+ });
310
+ };
311
+
312
+ /**
313
+ * Pads given number with leading zeros
314
+ *
315
+ * @param {number} value - The value to be padded
316
+ * @param {number} length - The length in characters of the output
317
+ * @return {string}
318
+ */
319
+ Datepicker.prototype.leadingZeros = function (value, length = 2) {
320
+ let ret = value.toString();
321
+
322
+ while (ret.length < length) {
323
+ ret = `0${ret}`;
324
+ }
325
+
326
+ return ret;
327
+ };
328
+
329
+ Datepicker.prototype.setOptions = function () {
330
+ this.setMinAndMaxDatesOnCalendar();
331
+ this.setExcludedDates();
332
+ this.setExcludedDays();
333
+ this.setLeadingZeros();
334
+ this.setWeekStartDay();
335
+ };
336
+
337
+ Datepicker.prototype.setMinAndMaxDatesOnCalendar = function () {
338
+ if (this.config.minDate) {
339
+ this.minDate = this.formattedDateFromString(
340
+ this.config.minDate,
341
+ null,
342
+ );
343
+ if (this.minDate && this.currentDate < this.minDate) {
344
+ this.currentDate = this.minDate;
345
+ }
346
+ }
347
+
348
+ if (this.config.maxDate) {
349
+ this.maxDate = this.formattedDateFromString(
350
+ this.config.maxDate,
351
+ null,
352
+ );
353
+ if (this.maxDate && this.currentDate > this.maxDate) {
354
+ this.currentDate = this.maxDate;
355
+ }
356
+ }
357
+ };
358
+
359
+ Datepicker.prototype.setExcludedDates = function () {
360
+ if (this.config.excludedDates) {
361
+ this.excludedDates = this.config.excludedDates
362
+ .replace(/\s+/, " ")
363
+ .split(" ")
364
+ .map((item) => {
365
+ if (item.includes("-")) {
366
+ // parse the date range from the format "dd/mm/yyyy-dd/mm/yyyy"
367
+ const [startDate, endDate] = item
368
+ .split("-")
369
+ .map((d) => this.formattedDateFromString(d, null));
370
+ if (startDate && endDate) {
371
+ const date = new Date(startDate.getTime());
372
+ const dates = [];
373
+ while (date <= endDate) {
374
+ dates.push(new Date(date));
375
+ date.setDate(date.getDate() + 1);
376
+ }
377
+ return dates;
378
+ }
379
+ } else {
380
+ return this.formattedDateFromString(item, null);
381
+ }
382
+ })
383
+ .flat()
384
+ .filter((item) => item);
385
+ }
386
+ };
387
+
388
+ Datepicker.prototype.setExcludedDays = function () {
389
+ if (this.config.excludedDays) {
390
+ // lowercase and arrange dayLabels to put indexOf sunday == 0 for comparison
391
+ // with getDay() function
392
+ let weekDays = this.dayLabels.map((item) => item.toLowerCase());
393
+ if (this.config.weekStartDay === "monday") {
394
+ weekDays.unshift(weekDays.pop());
395
+ }
396
+
397
+ this.excludedDays = this.config.excludedDays
398
+ .replace(/\s+/, " ")
399
+ .toLowerCase()
400
+ .split(" ")
401
+ .map((item) => weekDays.indexOf(item))
402
+ .filter((item) => item !== -1);
403
+ }
404
+ };
405
+
406
+ Datepicker.prototype.setLeadingZeros = function () {
407
+ if (typeof this.config.leadingZeros !== "boolean") {
408
+ if (this.config.leadingZeros.toLowerCase() === "true") {
409
+ this.config.leadingZeros = true;
410
+ }
411
+ if (this.config.leadingZeros.toLowerCase() === "false") {
412
+ this.config.leadingZeros = false;
413
+ }
414
+ }
415
+ };
416
+
417
+ Datepicker.prototype.setWeekStartDay = function () {
418
+ const weekStartDayParam = this.config.weekStartDay;
419
+ if (weekStartDayParam?.toLowerCase() === "sunday") {
420
+ this.config.weekStartDay = "sunday";
421
+ // Rotate dayLabels array to put Sunday as the first item
422
+ this.dayLabels.unshift(this.dayLabels.pop());
423
+ }
424
+ if (weekStartDayParam?.toLowerCase() === "monday") {
425
+ this.config.weekStartDay = "monday";
426
+ }
427
+ };
428
+
429
+ /**
430
+ * Determine if a date is selecteable
431
+ *
432
+ * @param {Date} date - the date to check
433
+ * @return {boolean}
434
+ *
435
+ */
436
+ Datepicker.prototype.isExcludedDate = function (date) {
437
+ if (this.minDate && this.minDate > date) {
438
+ return true;
439
+ }
440
+
441
+ if (this.maxDate && this.maxDate < date) {
442
+ return true;
443
+ }
444
+
445
+ for (const excludedDate of this.excludedDates) {
446
+ if (date.toDateString() === excludedDate.toDateString()) {
447
+ return true;
448
+ }
449
+ }
450
+
451
+ if (this.excludedDays.includes(date.getDay())) {
452
+ return true;
453
+ }
454
+
455
+ return false;
456
+ };
457
+
458
+ /**
459
+ * Get a Date object from a string
460
+ *
461
+ * @param {string} dateString - string in the format d/m/yyyy dd/mm/yyyy
462
+ * @param {Date} fallback - date object to return if formatting fails
463
+ * @return {Date}
464
+ */
465
+ Datepicker.prototype.formattedDateFromString = function (
466
+ dateString,
467
+ fallback = new Date(),
468
+ ) {
469
+ let formattedDate = null;
470
+ // Accepts d/m/yyyy and dd/mm/yyyy
471
+ const dateFormatPattern = /(\d{1,2})([-/,. ])(\d{1,2})\2(\d{4})/;
472
+
473
+ if (!dateFormatPattern.test(dateString)) return fallback;
474
+
475
+ const match = dateString.match(dateFormatPattern);
476
+ const day = match[1];
477
+ const month = match[3];
478
+ const year = match[4];
479
+
480
+ formattedDate = new Date(`${month}-${day}-${year}`);
481
+ if (formattedDate instanceof Date && !isNaN(formattedDate)) {
482
+ return formattedDate;
483
+ }
484
+ return fallback;
485
+ };
486
+
487
+ /**
488
+ * Get a formatted date string from a Date object
489
+ *
490
+ * @param {Date} date - date to format to a string
491
+ * @return {string}
492
+ */
493
+ Datepicker.prototype.formattedDateFromDate = function (date) {
494
+ if (this.config.leadingZeros) {
495
+ return `${this.leadingZeros(date.getDate())}/${this.leadingZeros(date.getMonth() + 1)}/${date.getFullYear()}`;
496
+ } else {
497
+ return `${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()}`;
498
+ }
499
+ };
500
+
501
+ /**
502
+ * Get a human readable date in the format Monday 2 March 2024
503
+ *
504
+ * @param {Date} - date to format
505
+ * @return {string}
506
+ */
507
+ Datepicker.prototype.formattedDateHuman = function (date) {
508
+ return `${this.dayLabels[(date.getDay() + 6) % 7]} ${date.getDate()} ${this.monthLabels[date.getMonth()]} ${date.getFullYear()}`;
509
+ };
510
+
511
+ Datepicker.prototype.backgroundClick = function (event) {
512
+ if (
513
+ this.isOpen() &&
514
+ !this.$dialog.contains(event.target) &&
515
+ !this.$input.contains(event.target) &&
516
+ !this.$calendarButton.contains(event.target)
517
+ ) {
518
+ event.preventDefault();
519
+ this.closeDialog();
520
+ }
521
+ };
522
+
523
+ Datepicker.prototype.firstButtonKeydown = function (event) {
524
+ if (event.key === "Tab" && event.shiftKey) {
525
+ this.$lastButtonInDialog.focus();
526
+ event.preventDefault();
527
+ }
528
+ };
529
+
530
+ Datepicker.prototype.lastButtonKeydown = function (event) {
531
+ if (event.key === "Tab" && !event.shiftKey) {
532
+ this.$firstButtonInDialog.focus();
533
+ event.preventDefault();
534
+ }
535
+ };
536
+
537
+ // render calendar
538
+ Datepicker.prototype.updateCalendar = function () {
539
+ this.$dialogTitle.innerHTML = `${this.monthLabels[this.currentDate.getMonth()]} ${this.currentDate.getFullYear()}`;
540
+
541
+ const day = this.currentDate;
542
+ const firstOfMonth = new Date(day.getFullYear(), day.getMonth(), 1);
543
+ let dayOfWeek;
544
+
545
+ if (this.config.weekStartDay === "monday") {
546
+ dayOfWeek = firstOfMonth.getDay() === 0 ? 6 : firstOfMonth.getDay() - 1; // Change logic to make Monday first day of week, i.e. 0
547
+ } else {
548
+ dayOfWeek = firstOfMonth.getDay();
549
+ }
550
+
551
+ firstOfMonth.setDate(firstOfMonth.getDate() - dayOfWeek);
552
+
553
+ const thisDay = new Date(firstOfMonth);
554
+
555
+ // loop through our days
556
+ for (let i = 0; i < this.calendarDays.length; i++) {
557
+ const hidden = thisDay.getMonth() !== day.getMonth();
558
+ const disabled = this.isExcludedDate(thisDay);
559
+
560
+ this.calendarDays[i].update(thisDay, hidden, disabled);
561
+
562
+ thisDay.setDate(thisDay.getDate() + 1);
563
+ }
564
+ };
565
+
566
+ Datepicker.prototype.setCurrentDate = function (focus = true) {
567
+ const { currentDate } = this;
568
+
569
+ this.calendarDays.forEach((calendarDay) => {
570
+ calendarDay.button.classList.add("moj-datepicker__button");
571
+ calendarDay.button.classList.add("moj-datepicker__calendar-day");
572
+ calendarDay.button.setAttribute("tabindex", -1);
573
+ calendarDay.button.classList.remove(this.selectedDayButtonClass);
574
+ const calendarDayDate = calendarDay.date;
575
+ calendarDayDate.setHours(0, 0, 0, 0);
576
+
577
+ const today = new Date();
578
+ today.setHours(0, 0, 0, 0);
579
+
580
+ if (
581
+ calendarDayDate.getTime() ===
582
+ currentDate.getTime() /* && !calendarDay.button.disabled */
583
+ ) {
584
+ if (focus) {
585
+ calendarDay.button.setAttribute("tabindex", 0);
586
+ calendarDay.button.focus();
587
+ calendarDay.button.classList.add(this.selectedDayButtonClass);
588
+ }
589
+ }
590
+
591
+ if (
592
+ this.inputDate &&
593
+ calendarDayDate.getTime() === this.inputDate.getTime()
594
+ ) {
595
+ calendarDay.button.classList.add(this.currentDayButtonClass);
596
+ calendarDay.button.setAttribute("aria-selected", true);
597
+ } else {
598
+ calendarDay.button.classList.remove(this.currentDayButtonClass);
599
+ calendarDay.button.removeAttribute("aria-selected");
600
+ }
601
+
602
+ if (calendarDayDate.getTime() === today.getTime()) {
603
+ calendarDay.button.classList.add(this.todayButtonClass);
604
+ } else {
605
+ calendarDay.button.classList.remove(this.todayButtonClass);
606
+ }
607
+ });
608
+
609
+ // if no date is tab-able, make the first non-disabled date tab-able
610
+ if (!focus) {
611
+ const enabledDays = this.calendarDays.filter((calendarDay) => {
612
+ return (
613
+ window.getComputedStyle(calendarDay.button).display === "block" &&
614
+ !calendarDay.button.disabled
615
+ );
616
+ });
617
+
618
+ enabledDays[0].button.setAttribute("tabindex", 0);
619
+
620
+ this.currentDate = enabledDays[0].date;
621
+ }
622
+ };
623
+
624
+ Datepicker.prototype.selectDate = function (date) {
625
+ if (this.isExcludedDate(date)) {
626
+ return;
627
+ }
628
+
629
+ this.$calendarButton.querySelector("span").innerText =
630
+ `Choose date. Selected date is ${this.formattedDateHuman(date)}`;
631
+ this.$input.value = this.formattedDateFromDate(date);
632
+
633
+ const changeEvent = new Event("change", { bubbles: true, cancelable: true });
634
+ this.$input.dispatchEvent(changeEvent);
635
+
636
+ this.closeDialog();
637
+ };
638
+
639
+ Datepicker.prototype.isOpen = function () {
640
+ return this.$dialog.classList.contains("moj-datepicker__dialog--open");
641
+ };
642
+
643
+ Datepicker.prototype.toggleDialog = function (event) {
644
+ event.preventDefault();
645
+ if (this.isOpen()) {
646
+ this.closeDialog();
647
+ } else {
648
+ this.setMinAndMaxDatesOnCalendar();
649
+ this.openDialog();
650
+ }
651
+ };
652
+
653
+ Datepicker.prototype.openDialog = function () {
654
+ this.$dialog.classList.add("moj-datepicker__dialog--open");
655
+ this.$calendarButton.setAttribute("aria-expanded", "true");
656
+
657
+ // position the dialog
658
+ // if input is wider than dialog pin it to the right
659
+ if (this.$input.offsetWidth > this.$dialog.offsetWidth) {
660
+ this.$dialog.style.right = `0px`;
661
+ }
662
+ this.$dialog.style.top = `${this.$input.offsetHeight + 3}px`;
663
+
664
+ // get the date from the input element
665
+ this.inputDate = this.formattedDateFromString(this.$input.value);
666
+ this.currentDate = this.inputDate;
667
+ this.currentDate.setHours(0, 0, 0, 0);
668
+
669
+ this.updateCalendar();
670
+ this.setCurrentDate();
671
+ };
672
+
673
+ Datepicker.prototype.closeDialog = function () {
674
+ this.$dialog.classList.remove("moj-datepicker__dialog--open");
675
+ this.$calendarButton.setAttribute("aria-expanded", "false");
676
+ this.$calendarButton.focus();
677
+ };
678
+
679
+ Datepicker.prototype.goToDate = function (date, focus) {
680
+ const current = this.currentDate;
681
+ this.currentDate = date;
682
+
683
+ if (
684
+ current.getMonth() !== this.currentDate.getMonth() ||
685
+ current.getFullYear() !== this.currentDate.getFullYear()
686
+ ) {
687
+ this.updateCalendar();
688
+ }
689
+
690
+ this.setCurrentDate(focus);
691
+ };
692
+
693
+ // day navigation
694
+ Datepicker.prototype.focusNextDay = function () {
695
+ const date = new Date(this.currentDate);
696
+ date.setDate(date.getDate() + 1);
697
+ this.goToDate(date);
698
+ };
699
+
700
+ Datepicker.prototype.focusPreviousDay = function () {
701
+ const date = new Date(this.currentDate);
702
+ date.setDate(date.getDate() - 1);
703
+ this.goToDate(date);
704
+ };
705
+
706
+ // week navigation
707
+ Datepicker.prototype.focusNextWeek = function () {
708
+ const date = new Date(this.currentDate);
709
+ date.setDate(date.getDate() + 7);
710
+ this.goToDate(date);
711
+ };
712
+
713
+ Datepicker.prototype.focusPreviousWeek = function () {
714
+ const date = new Date(this.currentDate);
715
+ date.setDate(date.getDate() - 7);
716
+ this.goToDate(date);
717
+ };
718
+
719
+ Datepicker.prototype.focusFirstDayOfWeek = function () {
720
+ const date = new Date(this.currentDate);
721
+ date.setDate(date.getDate() - date.getDay());
722
+ this.goToDate(date);
723
+ };
724
+
725
+ Datepicker.prototype.focusLastDayOfWeek = function () {
726
+ const date = new Date(this.currentDate);
727
+ date.setDate(date.getDate() - date.getDay() + 6);
728
+ this.goToDate(date);
729
+ };
730
+
731
+ // month navigation
732
+ Datepicker.prototype.focusNextMonth = function (event, focus = true) {
733
+ event.preventDefault();
734
+ const date = new Date(this.currentDate);
735
+ date.setMonth(date.getMonth() + 1, 1);
736
+ this.goToDate(date, focus);
737
+ };
738
+
739
+ Datepicker.prototype.focusPreviousMonth = function (event, focus = true) {
740
+ event.preventDefault();
741
+ const date = new Date(this.currentDate);
742
+ date.setMonth(date.getMonth() - 1, 1);
743
+ this.goToDate(date, focus);
744
+ };
745
+
746
+ // year navigation
747
+ Datepicker.prototype.focusNextYear = function (event, focus = true) {
748
+ event.preventDefault();
749
+ const date = new Date(this.currentDate);
750
+ date.setFullYear(date.getFullYear() + 1, date.getMonth(), 1);
751
+ this.goToDate(date, focus);
752
+ };
753
+
754
+ Datepicker.prototype.focusPreviousYear = function (event, focus = true) {
755
+ event.preventDefault();
756
+ const date = new Date(this.currentDate);
757
+ date.setFullYear(date.getFullYear() - 1, date.getMonth(), 1);
758
+ this.goToDate(date, focus);
759
+ };
760
+
761
+ /**
762
+ * Parse dataset
763
+ *
764
+ * Loop over an object and normalise each value using {@link normaliseString},
765
+ * optionally expanding nested `i18n.field`
766
+ *
767
+ * @param {{ schema: Schema }} Component - Component class
768
+ * @param {DOMStringMap} dataset - HTML element dataset
769
+ * @returns {Object} Normalised dataset
770
+ */
771
+ Datepicker.prototype.parseDataset = function (schema, dataset) {
772
+ const parsed = {};
773
+
774
+ for (const [field, attributes] of Object.entries(schema.properties)) {
775
+ if (field in dataset) {
776
+ parsed[field] = dataset[field];
777
+ }
778
+ }
779
+
780
+ return parsed;
781
+ };
782
+
783
+ /**
784
+ * Config merging function
785
+ *
786
+ * Takes any number of objects and combines them together, with
787
+ * greatest priority on the LAST item passed in.
788
+ *
789
+ * @param {...{ [key: string]: unknown }} configObjects - Config objects to merge
790
+ * @returns {{ [key: string]: unknown }} A merged config object
791
+ */
792
+ Datepicker.prototype.mergeConfigs = function (...configObjects) {
793
+ const formattedConfigObject = {};
794
+
795
+ // Loop through each of the passed objects
796
+ for (const configObject of configObjects) {
797
+ for (const key of Object.keys(configObject)) {
798
+ const option = formattedConfigObject[key];
799
+ const override = configObject[key];
800
+
801
+ // Push their keys one-by-one into formattedConfigObject. Any duplicate
802
+ // keys with object values will be merged, otherwise the new value will
803
+ // override the existing value.
804
+ if (typeof option === "object" && typeof override === "object") {
805
+ // @ts-expect-error Index signature for type 'string' is missing
806
+ formattedConfigObject[key] = this.mergeConfigs(option, override);
807
+ } else {
808
+ formattedConfigObject[key] = override;
809
+ }
810
+ }
811
+ }
812
+
813
+ return formattedConfigObject;
814
+ };
815
+
816
+ /**
817
+ *
818
+ * @param {HTMLElement} button
819
+ * @param {number} index
820
+ * @param {number} row
821
+ * @param {number} column
822
+ * @param {Datepicker} picker
823
+ * @constructor
824
+ */
825
+ function DSCalendarDay(button, index, row, column, picker) {
826
+ this.index = index;
827
+ this.row = row;
828
+ this.column = column;
829
+ this.button = button;
830
+ this.picker = picker;
831
+
832
+ this.date = new Date();
833
+ }
834
+
835
+ DSCalendarDay.prototype.init = function () {
836
+ this.button.addEventListener("keydown", this.keyPress.bind(this));
837
+ this.button.addEventListener("click", this.click.bind(this));
838
+ };
839
+
840
+ /**
841
+ * @param {Date} day - the Date for the calendar day
842
+ * @param {boolean} hidden - visibility of the day
843
+ * @param {boolean} disabled - is the day selectable or excluded
844
+ */
845
+ DSCalendarDay.prototype.update = function (day, hidden, disabled) {
846
+ let label = day.getDate();
847
+ let accessibleLabel = this.picker.formattedDateHuman(day);
848
+
849
+ if (disabled) {
850
+ this.button.setAttribute("aria-disabled", true);
851
+ accessibleLabel = "Excluded date, " + accessibleLabel;
852
+ } else {
853
+ this.button.removeAttribute("aria-disabled");
854
+ }
855
+
856
+ if (hidden) {
857
+ this.button.style.display = "none";
858
+ } else {
859
+ this.button.style.display = "block";
860
+ }
861
+
862
+ this.button.innerHTML = `<span class="govuk-visually-hidden">${accessibleLabel}</span><span aria-hidden="true">${label}</span>`;
863
+ this.date = new Date(day);
864
+ };
865
+
866
+ DSCalendarDay.prototype.click = function (event) {
867
+ this.picker.goToDate(this.date);
868
+ this.picker.selectDate(this.date);
869
+
870
+ event.stopPropagation();
871
+ event.preventDefault();
872
+ };
873
+
874
+ DSCalendarDay.prototype.keyPress = function (event) {
875
+ let calendarNavKey = true;
876
+
877
+ switch (event.key) {
878
+ case "ArrowLeft":
879
+ this.picker.focusPreviousDay();
880
+ break;
881
+ case "ArrowRight":
882
+ this.picker.focusNextDay();
883
+ break;
884
+ case "ArrowUp":
885
+ this.picker.focusPreviousWeek();
886
+ break;
887
+ case "ArrowDown":
888
+ this.picker.focusNextWeek();
889
+ break;
890
+ case "Home":
891
+ this.picker.focusFirstDayOfWeek();
892
+ break;
893
+ case "End":
894
+ this.picker.focusLastDayOfWeek();
895
+ break;
896
+ case "PageUp":
897
+ // eslint-disable-next-line no-unused-expressions
898
+ event.shiftKey
899
+ ? this.picker.focusPreviousYear(event)
900
+ : this.picker.focusPreviousMonth(event);
901
+ break;
902
+ case "PageDown":
903
+ // eslint-disable-next-line no-unused-expressions
904
+ event.shiftKey
905
+ ? this.picker.focusNextYear(event)
906
+ : this.picker.focusNextMonth(event);
907
+ break;
908
+ default:
909
+ calendarNavKey = false;
910
+ break;
911
+ }
912
+
913
+ if (calendarNavKey) {
914
+ event.preventDefault();
915
+ event.stopPropagation();
916
+ }
917
+ };
918
+
919
+ MOJFrontend.DatePicker = Datepicker;
920
+
921
+ /**
922
+ * Schema for component config
923
+ *
924
+ * @typedef {object} Schema
925
+ * @property {{ [field: string]: SchemaProperty | undefined }} properties - Schema properties
926
+ */
927
+
928
+ /**
929
+ * Schema property for component config
930
+ *
931
+ * @typedef {object} SchemaProperty
932
+ * @property {'string' | 'boolean' | 'number' | 'object'} type - Property type
933
+ */