-
Notifications
You must be signed in to change notification settings - Fork 6
/
app-date-picker.component.ts
813 lines (719 loc) · 24 KB
/
app-date-picker.component.ts
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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
import { FocusMonitor } from '@angular/cdk/a11y';
import { coerceBooleanProperty } from '@angular/cdk/coercion';
import {
Component,
DoCheck,
ElementRef,
EventEmitter,
HostBinding,
Input,
OnChanges,
OnDestroy,
Optional,
Output,
Self,
SimpleChanges,
ViewChild,
} from '@angular/core';
import {
ControlValueAccessor,
UntypedFormBuilder,
UntypedFormControl,
UntypedFormGroup,
FormGroupDirective,
NgControl,
NgForm,
Validators,
} from '@angular/forms';
import {
CanUpdateErrorState,
ErrorStateMatcher,
mixinErrorState,
_AbstractConstructor,
_Constructor,
} from '@angular/material/core';
import { MatFormFieldControl } from '@angular/material/form-field';
import { MatMenuTrigger } from '@angular/material/menu';
import { KnoraDate } from '@dasch-swiss/dsp-js';
import { Subject } from 'rxjs';
import {
CalendarDate,
CalendarPeriod,
GregorianCalendarDate,
IslamicCalendarDate,
JulianCalendarDate,
} from '@dasch-swiss/jdnconvertiblecalendar';
/** error when invalid control is dirty, touched, or submitted. */
export class DatePickerErrorStateMatcher implements ErrorStateMatcher {
isErrorState(
control: UntypedFormControl | null,
form: FormGroupDirective | NgForm | null
): boolean {
const isSubmitted = form && form.submitted;
return !!(
control &&
control.invalid &&
(control.dirty || control.touched || isSubmitted)
);
}
}
type CanUpdateErrorStateCtor = _Constructor<CanUpdateErrorState> &
_AbstractConstructor<CanUpdateErrorState>;
interface FormErrors {
[key: string]: string;
}
interface ValidationMessages {
[key: string]: {
[key: string]: string;
};
}
class MatInputBase {
constructor(
public _defaultErrorStateMatcher: ErrorStateMatcher,
public _parentForm: NgForm,
public _parentFormGroup: FormGroupDirective,
public ngControl: NgControl,
public stateChanges: Subject<void>
) {}
}
const _MatInputMixinBase: CanUpdateErrorStateCtor & typeof MatInputBase =
mixinErrorState(MatInputBase);
@Component({
selector: 'dasch-swiss-app-date-picker',
templateUrl: './app-date-picker.component.html',
styleUrls: ['./app-date-picker.component.scss'],
})
export class AppDatePickerComponent
extends _MatInputMixinBase
implements
ControlValueAccessor,
MatFormFieldControl<KnoraDate>,
OnChanges,
DoCheck,
CanUpdateErrorState,
OnDestroy
{
static nextId = 0;
@ViewChild(MatMenuTrigger) popover!: MatMenuTrigger;
@Output() closed: EventEmitter<void> = new EventEmitter();
@Input() override errorStateMatcher!: ErrorStateMatcher;
// disable calendar selector in case of end date in a period date value
@Input() disableCalendarSelector!: boolean;
// set predefinde calendar
@Input() calendar = 'GREGORIAN';
@HostBinding()
id = `dasch-swiss-app-date-picker-${AppDatePickerComponent.nextId++}`;
@HostBinding('attr.aria-describedby') describedBy = '';
dateForm: UntypedFormGroup;
focused = false;
override errorState = false;
controlType = 'dasch-swiss-app-date-picker';
matcher = new DatePickerErrorStateMatcher();
// own date picker variables
date!: KnoraDate;
form!: UntypedFormGroup;
formErrors: FormErrors = {
year: '',
};
validationMessages: ValidationMessages = {
year: {
required: 'At least the year has to be set.',
min: 'A valid year is greater than 0.',
},
};
// list of months
months = [
['Jan', 'Muḥarram'],
['Feb', 'Safar'],
['Mar', 'Rabīʿ al-ʾAwwal'],
['Apr', 'Rabīʿ ath-Thānī'],
['May', 'Jumadā al-ʾŪlā'],
['Jun', 'Jumādā ath-Thāniyah'],
['Jul', 'Rajab'],
['Aug', 'Shaʿbān'],
['Sep', 'Ramaḍān'],
['Oct', 'Shawwāl'],
['Nov', 'Ḏū al-Qaʿdah'],
['Dec', 'Ḏū al-Ḥijjah'],
];
weekDays = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
weeks: number[][] = [];
days: number[] = [];
day: number | undefined;
month!: number;
year!: number;
disableDaySelector!: boolean;
calendars = ['GREGORIAN', 'JULIAN', 'ISLAMIC'];
era = 'CE';
// ------
private _required = false;
private _disabled = false;
private _placeholder!: string;
@HostBinding('class.floating')
get shouldLabelFloat() {
return this.focused || !this.empty;
}
@Input()
get required() {
return this._required;
}
set required(req) {
this._required = coerceBooleanProperty(req);
this.stateChanges.next();
}
@Input()
get disabled(): boolean {
return this._disabled;
}
set disabled(value: boolean) {
this._disabled = coerceBooleanProperty(value);
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
this._disabled ? this.dateForm.disable() : this.dateForm.enable();
this.stateChanges.next();
}
@Input()
get placeholder() {
return this._placeholder;
}
set placeholder(plh) {
this._placeholder = plh;
this.stateChanges.next();
}
@Input()
get value(): KnoraDate | null {
const dateValue = this.dateForm.value;
if (dateValue !== null) {
return dateValue.knoraDate;
}
return null;
}
set value(dateValue: KnoraDate | null) {
if (dateValue !== null) {
this.dateForm.setValue({
date: this.transform(dateValue, 'dd.MM.YYYY', 'era'),
knoraDate: dateValue,
});
this.calendar = dateValue.calendar;
this.era =
this.calendar === 'ISLAMIC'
? 'noEra'
: dateValue.era === 'noEra'
? 'CE'
: dateValue.era;
this.day = dateValue.day;
this.month = dateValue.month ? dateValue.month : 0;
this.year = dateValue.year;
} else {
this.dateForm.setValue({ date: null, knoraDate: null });
}
this.stateChanges.next();
this.buildForm();
}
get empty() {
const dateInput = this.dateForm.value;
return !dateInput.knoraDate;
}
setDescribedByIds(ids: string[]) {
this.describedBy = ids.join(' ');
}
// eslint-disable-next-line @typescript-eslint/member-ordering
constructor(
_defaultErrorStateMatcher: ErrorStateMatcher,
@Optional() _parentForm: NgForm,
@Optional() _parentFormGroup: FormGroupDirective,
@Optional() @Self() public override ngControl: NgControl,
private _stateChanges: Subject<void>,
fb: UntypedFormBuilder,
private _elRef: ElementRef<HTMLElement>,
private _fm: FocusMonitor
) {
super(
_defaultErrorStateMatcher,
_parentForm,
_parentFormGroup,
ngControl,
_stateChanges
);
this.dateForm = fb.group({
date: [null, Validators.required],
knoraDate: [null, Validators.required],
});
_fm.monitor(_elRef.nativeElement, true).subscribe((origin) => {
this.focused = !!origin;
this.stateChanges.next();
});
if (this.ngControl != null) {
this.ngControl.valueAccessor = this;
}
// will be replaced by calendar and era
this.placeholder = 'Click to select a date';
this.buildForm();
this.dateForm.valueChanges.subscribe(() => this.handleInput());
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-empty-function
onChange = (_: any) => {};
// eslint-disable-next-line @typescript-eslint/no-empty-function
onTouched = () => {};
ngOnChanges(changes: SimpleChanges) {
// in case the calendar has changed (from parent e.g. in a period)
// update the calendar form control
if (changes['calendar'] && this.disableCalendarSelector) {
this._updateForm();
}
}
ngDoCheck() {
if (this.ngControl) {
this.updateErrorState();
}
}
ngOnDestroy() {
this.stateChanges.complete();
}
onContainerClick(event: MouseEvent) {
if ((event.target as Element).tagName.toLowerCase() !== 'input') {
this._elRef.nativeElement.querySelector('input')?.focus();
}
}
writeValue(dateValue: KnoraDate | null): void {
this.value = dateValue;
}
transform(
date: KnoraDate,
format?: string,
displayOptions?: 'era' | 'calendar' | 'calendarOnly' | 'all'
): string {
if (!(date instanceof KnoraDate)) {
// console.error('Non-KnoraDate provided. Expected a valid KnoraDate');
return '';
}
const formattedString = this.getFormattedString(date, format);
if (displayOptions) {
return this.addDisplayOptions(
date,
formattedString,
displayOptions
);
} else {
return formattedString;
}
}
getFormattedString(date: KnoraDate, format: string | undefined): string {
switch (format) {
case 'dd.MM.YYYY':
if (date.precision === 2) {
return `${this.leftPadding(date.day)}.${this.leftPadding(
date.month
)}.${date.year}`;
} else if (date.precision === 1) {
return `${this.leftPadding(date.month)}.${date.year}`;
} else {
return `${date.year}`;
}
case 'dd-MM-YYYY':
if (date.precision === 2) {
return `${this.leftPadding(date.day)}-${this.leftPadding(
date.month
)}-${date.year}`;
} else if (date.precision === 1) {
return `${this.leftPadding(date.month)}-${date.year}`;
} else {
return `${date.year}`;
}
case 'MM/dd/YYYY':
if (date.precision === 2) {
return `${this.leftPadding(date.month)}/${this.leftPadding(
date.day
)}/${date.year}`;
} else if (date.precision === 1) {
return `${this.leftPadding(date.month)}/${date.year}`;
} else {
return `${date.year}`;
}
default:
if (date.precision === 2) {
return `${this.leftPadding(date.day)}.${this.leftPadding(
date.month
)}.${date.year}`;
} else if (date.precision === 1) {
return `${this.leftPadding(date.month)}.${date.year}`;
} else {
return `${date.year}`;
}
}
}
leftPadding(value: number | undefined): string {
if (value !== undefined) {
return ('0' + value).slice(-2);
} else {
return '';
}
}
addDisplayOptions(date: KnoraDate, value: string, options: string): string {
switch (options) {
case 'era':
// displays date with era; era only in case of BCE
return (
value +
(date.era === 'noEra'
? ''
: date.era === 'BCE' || date.era === 'AD'
? ' ' + date.era
: '')
);
case 'calendar':
// displays date without era but with calendar type
return value + ' ' + this.titleCase(date.calendar);
case 'calendarOnly':
// displays only the selected calendar type without any data
return this.titleCase(date.calendar);
case 'all':
// displays date with era (only as BCE) and selected calendar type
return (
value +
(date.era === 'noEra'
? ''
: date.era === 'BCE'
? ' ' + date.era
: '') +
' ' +
this.titleCase(date.calendar)
);
default:
return '';
}
}
/**
* returns a string in Title Case format
* It's needed to transform a calendar name e.g. 'GREGORIAN' into 'Gregorian'
*
* @param str
* @returns string
*/
titleCase(str: string): string {
return str
.split(' ')
.map((w) => w[0].toUpperCase() + w.substring(1).toLowerCase())
.join(' ');
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
handleInput() {
this.onChange(this.value);
}
buildForm() {
this.form = new UntypedFormGroup({
calendar: new UntypedFormControl(),
era: new UntypedFormControl(''),
year: new UntypedFormControl('', [
Validators.required,
Validators.min(1),
]),
month: new UntypedFormControl(''),
});
this.disableDaySelector = this.month === 0;
if (this.value) {
this._updateForm();
} else if (!this.disableCalendarSelector) {
this.setToday();
}
this.form.valueChanges.subscribe((data) => this.onValueChanged(data));
}
/**
* this method is for the form error handling
*
* @param data Data which changed.
*/
onValueChanged(data?: any) {
if (!this.form) {
return;
}
this.calendar = this.form.controls['calendar'].value;
this.era =
this.calendar === 'ISLAMIC'
? 'noEra'
: this.form.controls['era'].value
? this.form.controls['era'].value
: 'CE';
// islamic calendar doesn't have a "before common era"
// in case of switching calendar from islamic to gregorian or julian set default era value to CE
if (this.calendar !== 'ISLAMIC' && this.era === 'noEra') {
this.form.controls['era'].setValue('CE');
}
if (data.year > 0) {
if (data.month) {
// give possibility to select day;
this.disableDaySelector = false;
// set the corresponding days
this._setDays(this.calendar, this.era, data.year, data.month);
} else {
// set precision to year only; disable the day selector
this.disableDaySelector = true;
this.day = undefined;
}
} else {
// not valid form; disable the day selector
this.disableDaySelector = true;
this.day = undefined;
}
const form = this.form;
Object.keys(this.formErrors).map((field: string) => {
this.formErrors[field] = '';
const control = form.get(field);
if (control && control.dirty && !control.valid && control.errors !== null) {
const messages = this.validationMessages[field];
Object.keys(control.errors).map((key: string) => {
this.formErrors[field] += messages[key] + ' ';
});
}
});
this.setDate(this.day);
}
setDate(day?: number) {
// set date on year, on year and month or on year, month and day precision
if (this.form.controls['year'].value > 0 && this.form.valid) {
this.day = day;
this.date = new KnoraDate(
this.calendar.toUpperCase(),
this.era,
this.form.controls['year'].value,
this.form.controls['month'].value
? this.form.controls['month'].value
: undefined,
day ? day : undefined
);
this.value = this.date;
}
}
setToday() {
const today = new Date();
let day: number;
let month: number;
let year: number;
let islamicDay: string;
let islamicMonth: string;
let islamicYear: string;
let julianDate: Date;
let difference: number;
this.era = 'CE';
switch (this.calendar) {
// islamic calendar
case 'ISLAMIC':
// found solution and formula here:
// https://medium.com/@Saf_Bes/get-today-hijri-date-in-javascript-90855d3cd45b
islamicDay = new Intl.DateTimeFormat('en-TN-u-ca-islamic', {
day: 'numeric',
}).format(today);
islamicMonth = new Intl.DateTimeFormat('en-TN-u-ca-islamic', {
month: 'numeric',
}).format(today);
islamicYear = new Intl.DateTimeFormat('en-TN-u-ca-islamic', {
year: 'numeric',
}).format(today);
day = parseInt(islamicDay, 10);
month = parseInt(islamicMonth, 10);
year = parseInt(islamicYear.substring(0, 4), 10);
this.era = 'noEra';
break;
// julian calendar
case 'JULIAN':
// found solution and formula here:
// https://sciencing.com/convert-julian-date-calender-date-6017669.html
julianDate = new Date();
difference =
parseInt(
(julianDate.getFullYear() + '').substring(0, 2),
10
) *
0.75 -
1.25;
julianDate.setDate(
julianDate.getDate() - Math.floor(difference)
);
day = julianDate.getDate();
month = julianDate.getMonth() + 1;
year = julianDate.getFullYear();
break;
// gregorian calendar
default:
day = today.getDate();
month = today.getMonth() + 1;
year = today.getFullYear();
}
this.day = day;
this.month = month;
this.year = year;
this._updateForm();
}
closeDatePicker() {
if (this.popover) {
this.popover.closeMenu();
}
}
private _updateForm() {
this.form.setValue({
calendar: this.calendar,
era: this.era,
year: this.year,
month: this.month,
});
if (this.disableCalendarSelector) {
this.form.controls['calendar'].disable();
} else {
this.form.controls['calendar'].enable();
}
this._setDays(this.calendar, this.era, this.year, this.month);
}
/**
* given a historical date (year), returns the astronomical year.
*
* @param year year of the given date.
* @param era era of the given date.
*/
convertHistoricalYearToAstronomicalYear(year: number, era: string) {
let yearAstro = year;
if (era === 'BCE') {
// convert historical date to astronomical date
yearAstro = yearAstro * -1 + 1;
}
return yearAstro;
}
/**
* calculates the number of days in a month for a given year.
*
* @param calendar the date's calendar.
* @param year the date's year.
* @param month the date's month.
*/
calculateDaysInMonth(
calendar: string,
year: number,
month: number
): number {
const date = new CalendarDate(year, month, 1);
if (calendar === 'GREGORIAN') {
const calDate = new GregorianCalendarDate(
new CalendarPeriod(date, date)
);
return calDate.daysInMonth(date);
} else if (calendar === 'JULIAN') {
const calDate = new JulianCalendarDate(
new CalendarPeriod(date, date)
);
return calDate.daysInMonth(date);
} else if (calendar === 'ISLAMIC') {
const calDate = new IslamicCalendarDate(
new CalendarPeriod(date, date)
);
return calDate.daysInMonth(date);
} else {
throw Error('Unknown calendar ' + calendar);
}
}
/**
* sets available days for a given year and month.
*
* @param calendar calendar of the given date.
* @param era era of the given date.
* @param year year of the given date.
* @param month month of the given date.
*/
private _setDays(
calendar: string,
era: string,
year: number,
month: number
) {
const yearAstro = this.convertHistoricalYearToAstronomicalYear(
year,
era
);
// count the days of the month
let days = this.calculateDaysInMonth(
calendar.toUpperCase(),
yearAstro,
month
);
// calculate the week day and the position of the first day of the month
// if date is before October 4th 1582, we should use the julian date converter for week day
let firstDayOfMonth: number;
const h = month <= 2 ? month + 12 : month;
const k = month <= 2 ? year - 1 : year;
// calculate weekday of the first the of the month;
// found solution and formular here:
// https://straub.as/java/basic/kalender.html
if (
year < 1582 ||
(year === 1582 && month <= 10) ||
calendar === 'JULIAN'
) {
// get the day of the week by using the julian date converter independet from selected calendar
firstDayOfMonth =
(1 +
2 * h +
Math.floor((3 * h + 3) / 5) +
k +
Math.floor(k / 4) -
1) %
7;
} else {
// firstDayOfMonth = new Date(year, month - 1, 1).getDay();
firstDayOfMonth =
(1 +
2 * h +
Math.floor((3 * h + 3) / 5) +
k +
Math.floor(k / 4) -
Math.floor(k / 100) +
Math.floor(k / 400) +
1) %
7;
}
// empty array of the days
this.days = [];
// if first day of the month is sunday (0)
// move it to the end of the week (7)
// because the first column is prepared for Monday
if (firstDayOfMonth === 0) {
firstDayOfMonth = 7;
}
// if era is not before common era, we support
// week days. The following loop helps to set
// position of the first day of the month
if (era === 'CE') {
for (let i = 1; i < firstDayOfMonth; i++) {
this.days.push(0);
}
}
// prepare list of the days
for (let i = 1; i <= days; i++) {
// special case for October 1582, which had only 21 days instead of 31
// because of the change from julian to gregorian calendar
if (
calendar === 'GREGORIAN' &&
year === 1582 &&
month === 10 &&
i === 5 &&
era === 'CE'
) {
i = 15;
days = 31;
}
this.days.push(i);
}
// split the list of the days in to
// list of days per week corresponding to the week day
const dates = this.days;
const weeks = [];
while (dates.length > 0) {
weeks.push(dates.splice(0, 7));
}
this.weeks = weeks;
}
}