add component for a custom date picker that also knows relative date ranges like 'last month'

This commit is contained in:
2024-03-31 14:48:33 +02:00
parent b0467c4571
commit 6b8e3d2089
8 changed files with 443 additions and 75 deletions

View File

@@ -0,0 +1,107 @@
import { Component } from "@angular/core";
import { FormControl, FormGroup, Validators } from "@angular/forms";
export type DateType = "quick" | "relative" | "absolute";
export type DateValue = { type: DateType; value: string; display: string };
@Component({
selector: "app-date-picker",
templateUrl: "./date-picker.component.html",
})
export class DatePickerComponent {
isOpen = false;
relativeTimeRangeUnit = "relativeTimeRangeMinutes";
relativeTimeRangeAmount = 15;
relativeTimeRange = {
seconds: 0,
minutes: 15,
hours: 0,
days: 0,
months: 0,
years: 0,
};
dateRangeFormGroup = new FormGroup({
dateRange: new FormControl<string>(
"2019-10-05 00:00:00 - 2019-10-11 23:59:59",
[
Validators.pattern(
/^\d{4}-\d{2}-\d{2} ([01][0-9]|2[0-3]):\d{2}:\d{2} - \d{4}-\d{2}-\d{2} ([01][0-9]|2[0-3]):\d{2}:\d{2}$/,
),
],
),
});
dateValue: DateValue = {
type: "quick",
value: "BM/EM",
display: "this month",
};
selectedTabIndex = 0;
constructor() {}
dateDisplay(): string {
return this.dateValue.value;
}
tabChange() {
//(<any> window).initSimpleDatePicker(); // breaks form control
}
applyQuick(value: string, display: string) {
this.dateValue.type = "quick";
this.dateValue.value = value;
this.dateValue.display = display;
this.isOpen = false;
}
private fixToRange(val: number, min: number, max: number) {
return val < min ? min : (val > max ? max : val);
}
applyRelativeTimeRange() {
const x = this.relativeTimeRange;
const years = x.years ? x.years + "Y" : "";
const months = x.months ? x.months + "M" : "";
const days = x.days ? x.days + "D" : "";
const time = x.hours || x.minutes || x.seconds ? "T" : "";
const hours = x.hours ? x.hours + "H" : "";
const minutes = x.minutes ? x.minutes + "M" : "";
const seconds = x.seconds ? x.seconds + "S" : "";
const isoTimeRange =
`P${years}${months}${days}${time}${hours}${minutes}${seconds}`;
this.dateValue.type = "relative";
this.dateValue.value = isoTimeRange;
this.dateValue.display = isoTimeRange;
this.isOpen = false;
}
applyAbsoluteTime() {
this.dateValue.type = "absolute";
this.dateValue.value = <string> this.dateRangeFormGroup.controls.dateRange
.value;
this.dateValue.display = <string> this.dateRangeFormGroup.controls.dateRange
.value;
this.isOpen = false;
console.log(this.dateValue);
}
scrollRelativeTimeRange(
event: WheelEvent,
unit: "seconds" | "minutes" | "hours" | "days" | "months" | "years",
max: number,
) {
this.relativeTimeRange[unit] = this.fixToRange(
this.relativeTimeRange[unit] + (event.deltaY > 0 ? -1 : 1),
0,
max,
);
}
}