From fc43f25fd877f92e3dbc76d2b4f15ffba9aa171c Mon Sep 17 00:00:00 2001
From: eksrha <58111764+eksrha@users.noreply.github.com>
Date: Sat, 1 Oct 2022 12:29:44 +0200
Subject: [PATCH] dump moment.js and use date-fns
---
.vscode/settings.json | 28 +++
package.json | 2 +-
.../calender-showcase.component.html | 27 ++-
.../calender-showcase.component.ts | 62 +++---
projects/ng-mat-components/_theming.scss | 5 +
.../src/lib/fs-calendar/calendar.models.ts | 84 ++++----
.../fs-calendar/fs-calendar.component.html | 144 +++++++++----
.../lib/fs-calendar/fs-calendar.component.ts | 197 +++++++++++-------
.../src/lib/fs-calendar/fs-calendar.module.ts | 16 +-
.../lib/fs-calendar/fs-calendar.service.ts | 135 +++++-------
10 files changed, 415 insertions(+), 285 deletions(-)
create mode 100644 .vscode/settings.json
diff --git a/.vscode/settings.json b/.vscode/settings.json
new file mode 100644
index 0000000..d71926e
--- /dev/null
+++ b/.vscode/settings.json
@@ -0,0 +1,28 @@
+{
+ "editor.formatOnSave": true,
+ "editor.renderWhitespace": "all",
+ "prettier.arrowParens": "avoid",
+ "prettier.printWidth": 120,
+ "editor.tabSize": 2,
+ "files.trimTrailingWhitespace": true,
+ "files.trimFinalNewlines": true,
+ "workbench.iconTheme": "material-icon-theme",
+ "editor.defaultFormatter": "esbenp.prettier-vscode",
+ "[javascript]": {
+ "editor.defaultFormatter": "esbenp.prettier-vscode"
+ },
+ "javascript.updateImportsOnFileMove.enabled": "always",
+ "typescript.updateImportsOnFileMove.enabled": "always",
+ "[typescript]": {
+ "editor.codeActionsOnSave": {
+ "source.organizeImports": true
+ }
+ },
+ "angular.enable-strict-mode-prompt": false,
+ "files.associations": {
+ ".env*": "shell"
+ },
+ "[html]": {
+ "editor.defaultFormatter": "esbenp.prettier-vscode"
+ }
+}
diff --git a/package.json b/package.json
index 85bd351..03d0a02 100644
--- a/package.json
+++ b/package.json
@@ -27,7 +27,7 @@
"@angular/platform-browser": "~13.3.11",
"@angular/platform-browser-dynamic": "~13.3.11",
"@angular/router": "~13.3.11",
- "moment": "^2.29.4",
+ "date-fns": "^2.29.3",
"rxjs": "~7.5.6",
"tslib": "^2.4.0",
"zone.js": "~0.11.7"
diff --git a/projects/lib-workspace/src/app/content/calender-showcase/calender-showcase.component.html b/projects/lib-workspace/src/app/content/calender-showcase/calender-showcase.component.html
index 0a90982..4443ea6 100644
--- a/projects/lib-workspace/src/app/content/calender-showcase/calender-showcase.component.html
+++ b/projects/lib-workspace/src/app/content/calender-showcase/calender-showcase.component.html
@@ -1,4 +1,4 @@
-
+
Days placeholder
@@ -8,23 +8,34 @@
Months before
- {{num}}
+ {{
+ num
+ }}
Months after
- {{num}}
+ {{
+ num
+ }}
-
Selected range: {{range | json}}
+
Selected range: {{ range | json }}
-
-
+
+
diff --git a/projects/lib-workspace/src/app/content/calender-showcase/calender-showcase.component.ts b/projects/lib-workspace/src/app/content/calender-showcase/calender-showcase.component.ts
index f22acb2..8d53b0e 100644
--- a/projects/lib-workspace/src/app/content/calender-showcase/calender-showcase.component.ts
+++ b/projects/lib-workspace/src/app/content/calender-showcase/calender-showcase.component.ts
@@ -1,76 +1,86 @@
-import { CalendarConfig, Day, calendarSelected } from 'projects/ng-mat-components/src/public-api';
import { Component, OnInit } from '@angular/core';
+import {
+ CalendarConfig,
+ calendarSelected,
+ Day,
+} from 'projects/ng-mat-components/src/public-api';
@Component({
selector: 'lib-calender-showcase',
templateUrl: './calender-showcase.component.html',
- styleUrls: ['./calender-showcase.component.scss']
+ styleUrls: ['./calender-showcase.component.scss'],
})
export class CalenderShowcaseComponent implements OnInit {
- docsApi = "./assets/docs/calendar/api.md"
- range: any
+ docsApi = './assets/docs/calendar/api.md';
+ range: any;
- placeholder = false // boolean
- isLoading = true
- latestEvent: Object | undefined
+ placeholder = false; // boolean
+ isLoading = true;
+ latestEvent: Object | undefined;
- monthsAfterBefore = Array(5).fill(0).map((x, i) => i);
- monthsBefore = 2;
- monthsAfter = 0;
+ today = new Date();
+ todayMonth = this.today.getMonth();
+ todayYear = this.today.getFullYear();
+
+ monthsAfterBefore = Array(5)
+ .fill(0)
+ .map((x, i) => i);
+ monthsBefore = 1;
+ monthsAfter = 1;
calendarConfig: CalendarConfig = {
renderMode: 'monthly', // 'annual' | 'monthly'
- selectMode: 'range', // 'click' | 'range'
+ selectMode: 'range', // 'click' | 'range'
displayYear: true,
firstDayOfWeekMonday: true,
- calendarWeek: false,
+ calendarWeek: true,
switches: true,
panelWidth: '300px',
bluredDays: false, // default: false
- markWeekend: true // default: true
- }
+ markWeekend: true, // default: true
+ };
dataSource: Day[] = [
{
date: new Date(1634594400000),
backgroundColor: '#0167c7',
toolTip: 'Test ToolTip First',
- dayNumber: ''
+ dayNumber: '',
},
{
date: new Date(1634594400000),
backgroundColor: 'rgb(6, 182, 0)',
toolTip: 'Test ToolTip Second',
- dayNumber: ''
+ dayNumber: '',
},
{
date: new Date(1634853600000),
backgroundColor: 'rgb(6, 182, 0)',
toolTip: 'Test ToolTip 2',
- dayNumber: ''
+ dayNumber: '',
},
{
date: new Date(1635544800000),
backgroundColor: 'lightblue',
- dayNumber: ''
- }
- ]
+ dayNumber: '',
+ },
+ ];
- constructor() { }
+ constructor() {}
ngOnInit(): void {
- console.log(this.dataSource)
- this.isLoading = false
+ console.log(this.dataSource);
+ this.isLoading = false;
}
testMethod(event: calendarSelected) {
switch (event.type) {
- case "range":
+ case 'range':
this.range = event;
break;
- case "date":
+ case 'date':
this.range = event;
break;
}
- console.log(event)
+ console.log(event);
}
}
diff --git a/projects/ng-mat-components/_theming.scss b/projects/ng-mat-components/_theming.scss
index 4e45a46..3eb394b 100644
--- a/projects/ng-mat-components/_theming.scss
+++ b/projects/ng-mat-components/_theming.scss
@@ -125,4 +125,9 @@
transparent 100%
);
}
+
+ .month-header button {
+ border: 1px solid mat-color($foreground, "divider");
+ border-radius: 4px;
+ }
}
diff --git a/projects/ng-mat-components/src/lib/fs-calendar/calendar.models.ts b/projects/ng-mat-components/src/lib/fs-calendar/calendar.models.ts
index 08d28a0..104ff37 100644
--- a/projects/ng-mat-components/src/lib/fs-calendar/calendar.models.ts
+++ b/projects/ng-mat-components/src/lib/fs-calendar/calendar.models.ts
@@ -10,28 +10,28 @@
* @param {string} panelWidth set a with for an single panel
*/
export interface CalendarConfig {
- renderMode: string;
- selectMode: string;
- calendarWeek: boolean;
- displayYear?: boolean;
- switches?: boolean;
- bluredDays?: boolean;
- markWeekend?: boolean;
- firstDayOfWeekMonday?: boolean;
- panelWidth?: string;
+ renderMode: 'monthly' | 'annual';
+ selectMode: string;
+ calendarWeek: boolean;
+ displayYear?: boolean;
+ switches?: boolean;
+ bluredDays?: boolean;
+ markWeekend?: boolean;
+ firstDayOfWeekMonday?: boolean;
+ panelWidth?: string;
}
export class Calendar {
- year: number = 2022;
- dayNames: String[] = [''];
- months: Month[] = [];
- daysAbsolute: Date[] = []
+ year: number = 2022;
+ dayNames: String[] = [''];
+ months: Month[] = [];
+ daysAbsolute: Date[] = [];
}
export interface Month {
- name: string;
- days: Day[];
- year: number;
- render: [Day[]];
+ name: string;
+ days: Day[];
+ year: number;
+ render: [Day[]];
}
export interface selectedRange {
@@ -46,30 +46,30 @@ export interface selectedDate {
export type calendarSelected = selectedRange | selectedDate;
/**
- * Use this to customize your data in the calendar
- * @param {number} day number of day (override not allowed)
- * @param {Date} date Date to match
- * @param {number} kw calendar week (override not allowed)
- * @param {boolean} isWeekendDay Boolean if day weekend (override not allowed)
- * @param {string} color set a custom color (hex, string, or var)
- * @param {string} backgroundColor set a custom Background Color (hex, string, or var)
- * @param {boolean} badge if you want to use a Badge
- * @param {string} badgeMode badgeMode options: 'Int' or 'Icon'
- * @param {number} badgeInt if badgeMode == 'Int', set our Number here
- * @param {string} badgeIcon if badgeMode == 'Icon', set Icon (Matireal-Icons)
- * @param {string} toolTip if set, this displays a mat-tooltip
- */
+ * Use this to customize your data in the calendar
+ * @param {number} day number of day (override not allowed)
+ * @param {Date} date Date to match
+ * @param {number} kw calendar week (override not allowed)
+ * @param {boolean} isWeekendDay Boolean if day weekend (override not allowed)
+ * @param {string} color set a custom color (hex, string, or var)
+ * @param {string} backgroundColor set a custom Background Color (hex, string, or var)
+ * @param {boolean} badge if you want to use a Badge
+ * @param {string} badgeMode badgeMode options: 'Int' or 'Icon'
+ * @param {number} badgeInt if badgeMode == 'Int', set our Number here
+ * @param {string} badgeIcon if badgeMode == 'Icon', set Icon (Matireal-Icons)
+ * @param {string} toolTip if set, this displays a mat-tooltip
+ */
export interface Day {
- dayNumber: string;
- date: Date;
- kw?: number;
- isWeekendDay?: boolean;
- type?: string;
- color?: string;
- backgroundColor?: string;
- badge?: boolean;
- badgeMode?: string;
- badgeInt?: number;
- badgeIcon?: string;
- toolTip?: string;
+ dayNumber: string;
+ date: Date;
+ kw?: number;
+ isWeekendDay?: boolean;
+ type?: string;
+ color?: string;
+ backgroundColor?: string;
+ badge?: boolean;
+ badgeMode?: string;
+ badgeInt?: number;
+ badgeIcon?: string;
+ toolTip?: string;
}
diff --git a/projects/ng-mat-components/src/lib/fs-calendar/fs-calendar.component.html b/projects/ng-mat-components/src/lib/fs-calendar/fs-calendar.component.html
index cf4ab24..54902b0 100644
--- a/projects/ng-mat-components/src/lib/fs-calendar/fs-calendar.component.html
+++ b/projects/ng-mat-components/src/lib/fs-calendar/fs-calendar.component.html
@@ -1,62 +1,109 @@
-
+
-
-
-
+
-
-
-
+
+
- {{day.dayNumber}}
+ [class.selected-end]="isSelectedDayEnd(day.date)"
+ [class.date-between]="getAmIBetween(day.date)"
+ >
+ {{ day.dayNumber }}
-
+ [ngStyle]="{ background: day.backgroundColor }"
+ >
|
-
-
- {{placeholderDay? day.kw : ''}}
+
+
+ {{ placeholderDay ? day.kw : "" }}
- {{day.kw}}
+ {{ day.kw }}
|
-
+ |
{{ day.dayNumber }}
|
-
+ [ngClass]="config.calendarWeek ? 'eight' : 'seven'"
+ >
|
| |
|
- |
+ |
diff --git a/projects/ng-mat-components/src/lib/fs-calendar/fs-calendar.component.ts b/projects/ng-mat-components/src/lib/fs-calendar/fs-calendar.component.ts
index d5f9c84..6ef1866 100644
--- a/projects/ng-mat-components/src/lib/fs-calendar/fs-calendar.component.ts
+++ b/projects/ng-mat-components/src/lib/fs-calendar/fs-calendar.component.ts
@@ -1,18 +1,28 @@
-import { Component, EventEmitter, HostListener, Input, OnInit, Output } from '@angular/core';
-import { CalendarConfig, Day, Calendar, calendarSelected } from './calendar.models';
-import { FsCalendarService } from './fs-calendar.service';
-import { moment } from './fs-calendar.service';
+import {
+ Component,
+ EventEmitter,
+ HostListener,
+ Input,
+ OnInit,
+ Output,
+} from '@angular/core';
+import {
+ Calendar,
+ CalendarConfig,
+ calendarSelected,
+ Day,
+} from './calendar.models';
+import { dateFns, FsCalendarService } from './fs-calendar.service';
@Component({
selector: 'fs-calendar',
templateUrl: './fs-calendar.component.html',
styleUrls: ['./fs-calendar.component.scss'],
host: {
- 'class': 'fs-calendar',
+ class: 'fs-calendar',
},
})
export class FsCalendarComponent implements OnInit {
-
private _config: CalendarConfig = {
renderMode: 'monthly',
selectMode: 'click',
@@ -22,26 +32,26 @@ export class FsCalendarComponent implements OnInit {
switches: true,
bluredDays: false,
markWeekend: true,
- panelWidth: '350px'
+ panelWidth: '350px',
};
private _mode: string = '';
private _dataSource: Day[] = [];
private _month = new Date().getUTCMonth();
- private _year: number = new Date().getFullYear()
+ private _year: number = new Date().getFullYear();
private _monthsBefore: number = 0;
private _monthsAfter: number = 0;
- calendar: Calendar = new Calendar()
- today = new Date()
- selectedDayStart: Date | undefined
- selectedDayBetween: Date[] = []
- selectedDayEnd: Date | undefined
- markWeekend = this._config.markWeekend
- bluredDays = this._config.bluredDays
- isLoading = true
- monthOverrride = false
+ calendar: Calendar = new Calendar();
+ today = new Date();
+ selectedDayStart: Date | undefined;
+ selectedDayBetween: Date[] = [];
+ selectedDayEnd: Date | undefined;
+ markWeekend = this._config.markWeekend;
+ bluredDays = this._config.bluredDays;
+ isLoading = true;
+ monthOverrride = false;
- weekendColor = 'rgba(0, 0, 0, .25)'
+ weekendColor = 'rgba(0, 0, 0, .25)';
get config(): CalendarConfig {
return this._config;
@@ -68,40 +78,40 @@ export class FsCalendarComponent implements OnInit {
@Input()
set dataSource(data: Day[]) {
this._dataSource = data;
- this.generateX()
+ this.generateX();
}
@Input()
set mode(val: string) {
this._mode = val;
- this.generateX()
+ this.generateX();
}
@Input()
set month(data: number) {
this._month = data;
- this.monthOverrride = false
- this.generateX()
+ this.monthOverrride = false;
+ this.generateX();
}
@Input()
set config(data: CalendarConfig) {
this._config = data;
- this.markWeekend = data.markWeekend
- this.bluredDays = data.bluredDays
- this.generateX()
+ this.markWeekend = data.markWeekend;
+ this.bluredDays = data.bluredDays;
+ this.generateX();
}
@Input()
set year(data: number) {
this._year = data;
- this.generateX()
+ this.generateX();
}
@Input()
set monthsBefore(data: number) {
this._monthsBefore = data;
- this.generateX()
+ this.generateX();
}
@Input()
set monthsAfter(data: number) {
this._monthsAfter = data;
- this.generateX()
+ this.generateX();
}
@Input() placeholderDay: boolean = false;
@@ -109,125 +119,152 @@ export class FsCalendarComponent implements OnInit {
@HostListener('window:keyup', ['$event'])
keyEvent(event: KeyboardEvent) {
- if (event.key === "Escape") {
- this.selectedDayBetween = []
- this.selectedDayStart = undefined
- this.selectedDayEnd = undefined
+ if (event.key === 'Escape') {
+ this.selectedDayBetween = [];
+ this.selectedDayStart = undefined;
+ this.selectedDayEnd = undefined;
}
}
- constructor(private calendarService: FsCalendarService) { }
+ constructor(private calendarService: FsCalendarService) {}
ngOnInit() {
- this.isLoading = false
+ this.isLoading = false;
}
onClick(day: Day, type: string) {
if (type === 'date' && this.config.selectMode === 'range') {
- if (this.selectedDayStart != undefined && this.selectedDayEnd != undefined) {
- this.selectedDayBetween = []
- this.selectedDayStart = undefined
- this.selectedDayEnd = undefined
+ if (
+ this.selectedDayStart != undefined &&
+ this.selectedDayEnd != undefined
+ ) {
+ this.selectedDayBetween = [];
+ this.selectedDayStart = undefined;
+ this.selectedDayEnd = undefined;
}
- if (moment(day.date).isBefore(this.selectedDayStart, 'day') || this.selectedDayStart === undefined) {
- this.selectedDayStart = day.date
+ if (
+ dateFns.isBefore(day.date, this.selectedDayStart as Date) ||
+ this.selectedDayStart === undefined
+ ) {
+ this.selectedDayStart = day.date;
} else {
- this.selectedDayEnd = day.date
+ this.selectedDayEnd = day.date;
this.selectedDate.emit({
- type: "range",
+ type: 'range',
start: this.selectedDayStart,
end: this.selectedDayEnd,
});
}
} else {
this.selectedDate.emit({
- type: "date",
- date: day.date
+ type: 'date',
+ date: day.date,
});
}
}
onMouseOver(dateComp: Date) {
- if (this.selectedDayStart != undefined && this.selectedDayEnd == undefined) {
- this.selectedDayBetween = this.calendar.daysAbsolute.filter(date => {
- return moment(date).isBetween(this.selectedDayStart, dateComp, 'day')
- })
+ if (
+ this.selectedDayStart != undefined &&
+ this.selectedDayEnd == undefined
+ ) {
+ this.selectedDayBetween = this.calendar.daysAbsolute.filter((date) => {
+ return (
+ dateFns.isBefore(date, this.selectedDayStart as Date) &&
+ dateFns.isAfter(date, dateComp)
+ );
+ });
}
}
getAmIBetween(date: Date): boolean {
- const fIndex = this.selectedDayBetween.findIndex(selDate => {
- return moment(selDate).isSame(date, 'day')
- })
+ const fIndex = this.selectedDayBetween.findIndex((selDate) => {
+ return dateFns.isSameDay(selDate, date);
+ });
if (fIndex != -1) {
- return true
+ return true;
} else {
- return false
+ return false;
}
}
isSelectedDayStart(date: Date): boolean {
if (this.selectedDayStart) {
- return moment(this.selectedDayStart).isSame(date, 'day')
+ return dateFns.isSameDay(this.selectedDayStart, date);
} else {
- return false
+ return false;
}
}
isSelectedDayEnd(date: Date): boolean {
if (this.selectedDayEnd) {
- return moment(this.selectedDayEnd).isSame(date, 'day')
+ return dateFns.isSameDay(this.selectedDayEnd, date);
} else {
if (this.selectedDayBetween.length > 0) {
- if (moment(this.selectedDayBetween[this.selectedDayBetween.length - 1]).add(1, 'd').isSame(date, 'day')) {
- return true
+ if (
+ dateFns.isSameDay(
+ dateFns.addDays(
+ this.selectedDayBetween[this.selectedDayBetween.length - 1],
+ 1
+ ),
+ date
+ )
+ ) {
+ return true;
}
}
- return false
+ return false;
}
}
+
isToday(date: Date): boolean {
- return moment().isSame(date, 'day')
+ return dateFns.isSameDay(new Date(), date);
}
getCanIBeHighlighted(date: Date) {
if (this.selectedDayEnd) {
- if (!moment(this.selectedDayStart).isSame(date, 'day') && !moment(this.selectedDayEnd).isSame(date, 'day') && this.getAmIBetween(date)
- || (moment(this.selectedDayEnd).isSame(date, 'day') && this.selectedDayEnd != undefined)
- || (moment(this.selectedDayStart).isSame(date, 'day') && this.selectedDayStart != undefined)) {
- return true
+ if (
+ (!dateFns.isSameDay(this.selectedDayStart as Date, date) &&
+ !dateFns.isSameDay(this.selectedDayEnd, date) &&
+ this.getAmIBetween(date)) ||
+ (dateFns.isSameDay(this.selectedDayEnd, date) &&
+ this.selectedDayEnd != undefined) ||
+ (dateFns.isSameDay(this.selectedDayStart as Date, date) &&
+ this.selectedDayStart != undefined)
+ ) {
+ return true;
} else {
- return false
+ return false;
}
} else {
- return false
+ return false;
}
}
onMonthForward() {
- this.monthOverrride = true
+ this.monthOverrride = true;
if (this.month >= 11 || this._month >= 11) {
- this._year = parseInt(this.year.toString(), 10) + 1
- this._month = 0
+ this._year = parseInt(this.year.toString(), 10) + 1;
+ this._month = 0;
} else {
- this._month = parseInt(this._month.toString(), 10) + 1
+ this._month = parseInt(this._month.toString(), 10) + 1;
}
- this.generateX()
+ this.generateX();
}
onMonthBackward() {
- this.monthOverrride = true
+ this.monthOverrride = true;
if (this.month <= 0 || this._month <= 0) {
- this._year = parseInt(this.year.toString(), 10) - 1
- this._month = 11
+ this._year = parseInt(this.year.toString(), 10) - 1;
+ this._month = 11;
} else {
- this._month = parseInt(this._month.toString(), 10) - 1
+ this._month = parseInt(this._month.toString(), 10) - 1;
}
- this.generateX()
+ this.generateX();
}
generateX() {
- const usedYear = this.monthOverrride ? this._year : this.year
- const usedMonth = this.monthOverrride ? this._month : this.month
+ const usedYear = this.monthOverrride ? this._year : this.year;
+ const usedMonth = this.monthOverrride ? this._month : this.month;
this.calendar = this.calendarService.generateMatrix(
this.config.renderMode,
this.config.calendarWeek,
@@ -235,7 +272,7 @@ export class FsCalendarComponent implements OnInit {
usedYear,
usedMonth,
this.monthsBefore,
- this.monthsAfter)
+ this.monthsAfter
+ );
}
-
}
diff --git a/projects/ng-mat-components/src/lib/fs-calendar/fs-calendar.module.ts b/projects/ng-mat-components/src/lib/fs-calendar/fs-calendar.module.ts
index c94ba55..194acbd 100644
--- a/projects/ng-mat-components/src/lib/fs-calendar/fs-calendar.module.ts
+++ b/projects/ng-mat-components/src/lib/fs-calendar/fs-calendar.module.ts
@@ -1,16 +1,12 @@
-import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
-import { FsCalendarComponent } from './fs-calendar.component';
+import { NgModule } from '@angular/core';
+import { MatButtonModule } from '@angular/material/button';
import { MatTooltipModule } from '@angular/material/tooltip';
+import { FsCalendarComponent } from './fs-calendar.component';
@NgModule({
- imports: [
- CommonModule,
- MatTooltipModule
- ],
+ imports: [CommonModule, MatTooltipModule, MatButtonModule],
exports: [FsCalendarComponent],
- declarations: [FsCalendarComponent]
+ declarations: [FsCalendarComponent],
})
-export class FsCalendarModule { }
-
-
+export class FsCalendarModule {}
diff --git a/projects/ng-mat-components/src/lib/fs-calendar/fs-calendar.service.ts b/projects/ng-mat-components/src/lib/fs-calendar/fs-calendar.service.ts
index 165c6b2..df3595a 100644
--- a/projects/ng-mat-components/src/lib/fs-calendar/fs-calendar.service.ts
+++ b/projects/ng-mat-components/src/lib/fs-calendar/fs-calendar.service.ts
@@ -1,31 +1,20 @@
-import { Injectable, LOCALE_ID, Inject } from '@angular/core';
-import * as moment_ from 'moment';
-import 'moment/min/locales';
-import { Calendar, Month, Day } from './calendar.models';
+import { Inject, Injectable, LOCALE_ID } from '@angular/core';
+import * as dateFns_ from 'date-fns';
+import { Calendar, Day, Month } from './calendar.models';
-export const moment = moment_;
+export const dateFns = dateFns_;
@Injectable({
providedIn: 'root',
})
export class FsCalendarService {
- monthNames: string[];
- dayNames: string[];
- dayNamesEn: string[];
dayNamesDeVor: any;
dayNamesDe: any;
dataSourceCustom: Day[] = [];
daysAbsolute: Date[] = [];
- constructor(@Inject(LOCALE_ID) private appLocale: string) {
- moment.locale(this.appLocale.substring(0, 2));
- this.monthNames = moment.monthsShort();
- this.dayNames = moment.weekdaysShort();
- this.dayNamesEn = moment.weekdaysShort();
- this.dayNamesDeVor = JSON.parse(JSON.stringify(this.dayNamesEn));
- this.dayNamesDe = this.dayNamesDeVor.push(this.dayNamesDeVor.shift());
- }
+ constructor(@Inject(LOCALE_ID) private appLocale: string) {}
/**
* @param {String} mode calendar mode (monthly|annual)
@@ -37,7 +26,7 @@ export class FsCalendarService {
* @param {Number} monthsAfter months after the selected month, default 0
*/
generateMatrix(
- mode: string,
+ mode: 'monthly' | 'annual',
calendarWeek: boolean,
dataSource: Day[],
year: number,
@@ -90,36 +79,37 @@ export class FsCalendarService {
Object.assign(day, { type: 'date' });
});
let render: Day[] = month.days;
- const firstMonthDay = month.days[0];
- let currMonth = moment(month.days[0].date);
- const dayOfWeek = currMonth.day() == 0 ? 7 : currMonth.day();
- const nextMonth = moment(currMonth.add(1, 'M'));
- const nextMonthDay: Day = this.generateDay(nextMonth);
+ let firstDayOfMonth = month.days[0].date;
+ let dayOfWeek = dateFns.getDay(firstDayOfMonth);
+ let nextMonth = dateFns.addMonths(firstDayOfMonth, 1);
// Vormonat
for (let i = 0; i < dayOfWeek - 1; i++) {
render.splice(
- i,
0,
- this.makeWJObjekt(firstMonthDay, 'placeholderDay', dayOfWeek - 1 - i)
+ 0,
+ this.makeWJObjekt(
+ dateFns.subDays(firstDayOfMonth, i + 1),
+ 'placeholderDay'
+ )
);
}
// Nachmonat
- for (let i = 0; render.length < 42; i--) {
+ for (let i = 0; render.length < 42; i++) {
render.splice(
- render.length + 1,
+ render.length,
0,
- this.makeWJObjekt(nextMonthDay, 'placeholderDay', i)
+ this.makeWJObjekt(dateFns.addDays(nextMonth, i), 'placeholderDay')
);
}
// Kalenderwochen && tr rows
let renderTr = [];
if (calendarWeek) {
- render.splice(0, 0, this.makeWJObjekt(render[0], 'kw'));
- render.splice(8, 0, this.makeWJObjekt(render[8], 'kw'));
- render.splice(16, 0, this.makeWJObjekt(render[16], 'kw'));
- render.splice(24, 0, this.makeWJObjekt(render[24], 'kw'));
- render.splice(32, 0, this.makeWJObjekt(render[32], 'kw'));
- render.splice(40, 0, this.makeWJObjekt(render[40], 'kw'));
+ render.splice(0, 0, this.makeWJObjekt(render[0].date, 'kw'));
+ render.splice(8, 0, this.makeWJObjekt(render[8].date, 'kw'));
+ render.splice(16, 0, this.makeWJObjekt(render[16].date, 'kw'));
+ render.splice(24, 0, this.makeWJObjekt(render[24].date, 'kw'));
+ render.splice(32, 0, this.makeWJObjekt(render[32].date, 'kw'));
+ render.splice(40, 0, this.makeWJObjekt(render[40].date, 'kw'));
renderTr.push(render.slice(0, 8));
renderTr.push(render.slice(8, 16));
renderTr.push(render.slice(16, 24));
@@ -142,84 +132,74 @@ export class FsCalendarService {
return cal;
}
- makeWJObjekt(day: Day, type: string, dateBack?: number): Day {
+ makeWJObjekt(date: Date, type: 'kw' | 'placeholderDay'): Day {
let newDay: Day;
- let newMDate: moment.Moment;
- if (dateBack) {
- newMDate = moment(day.date).subtract(dateBack, 'days');
- } else {
- newMDate = moment(day.date);
- }
switch (type) {
case 'kw':
newDay = {
dayNumber: '',
- date: newMDate.toDate(),
- kw: day.kw,
+ date: date,
+ kw: dateFns.getWeek(date, { weekStartsOn: 4 }),
type: 'kw',
};
break;
case 'placeholderDay':
newDay = {
- dayNumber: newMDate.format('D'),
- date: newMDate.toDate(),
- kw: newMDate.week(),
+ dayNumber: dateFns.format(date, 'd'),
+ date: date,
+ kw: dateFns.getWeek(date, { weekStartsOn: 4 }),
type: 'placeholderDay',
- isWeekendDay: this.isWeekend(newMDate),
+ isWeekendDay: dateFns.isWeekend(date),
};
break;
- default:
- newDay = {
- dayNumber: newMDate.format('D'),
- date: newMDate.toDate(),
- kw: day.kw,
- type: 'not-set',
- };
}
return newDay;
}
generateCal(year: number): Calendar {
const months = [];
- for (let index = 0; index < this.monthNames.length; index++) {
+ for (let index = 0; index < 12; index++) {
months.push(this.generateMonth(index, year));
}
return {
year: year,
- dayNames: this.dayNames,
+ dayNames: [],
months: months,
daysAbsolute: this.daysAbsolute,
};
}
generateMonth(monthNumber: number, year: number): Month {
- const monthDay = moment(`${year}-${monthNumber + 1}`, 'YYYY-MM');
- const daysInMonth = monthDay.daysInMonth();
+ const firstDayInMonth = new Date(year, monthNumber, 1);
+ const daysInMonth = dateFns.getDaysInMonth(firstDayInMonth);
+
const days: Day[] = [];
for (let index = 0; index < daysInMonth; index++) {
- const currentDay = new Date(year, monthNumber, index + 1);
- days.push(this.generateDay(moment(currentDay)));
+ const date = new Date(year, monthNumber, index + 1);
+ days.push(this.generateDay(date));
}
+
return {
- name: this.monthNames[monthNumber],
+ name: dateFns.format(days[0].date, 'LLLL'),
year: year,
days: days,
render: [[]],
};
}
- generateDay(currentDay: moment.Moment): Day {
+ generateDay(dateToGenerate: Date): Day {
let tmpDay = this.dataSourceCustom;
let day: Day;
if (tmpDay != null) {
// Filter nach vorhandenem override
const filter = tmpDay.filter((obj) => {
- return currentDay.isSame(obj.date, 'day');
+ return dateFns.isSameDay(dateToGenerate, obj.date);
});
if (filter.length > 0) {
let backgroundColor = '';
let toolTip = '';
+
switch (filter.length) {
case 2:
backgroundColor = `linear-gradient(110deg, ${filter[0].backgroundColor} 49%, ${filter[1].backgroundColor} 51%)`;
@@ -249,34 +229,31 @@ export class FsCalendarService {
}
break;
}
+
day = filter[0];
day.backgroundColor = backgroundColor;
day.toolTip = toolTip;
- day['kw'] = currentDay.week();
- day.date = currentDay.toDate();
- day.dayNumber = currentDay.format('D');
- day['isWeekendDay'] = this.isWeekend(currentDay);
+ day['kw'] = dateFns.getWeek(dateToGenerate);
+ day.date = dateToGenerate;
+ day.dayNumber = dateFns.format(dateToGenerate, 'd');
+ day['isWeekendDay'] = dateFns.isWeekend(dateToGenerate);
} else {
day = {
- kw: currentDay.week(),
- dayNumber: currentDay.format('D'),
- date: currentDay.toDate(),
- isWeekendDay: this.isWeekend(currentDay),
+ kw: dateFns.getWeek(dateToGenerate),
+ dayNumber: dateFns.format(dateToGenerate, 'd'),
+ date: dateToGenerate,
+ isWeekendDay: dateFns.isWeekend(dateToGenerate),
};
}
} else {
day = {
- kw: currentDay.week(),
- dayNumber: currentDay.format('D'),
- date: currentDay.toDate(),
- isWeekendDay: this.isWeekend(currentDay),
+ kw: dateFns.getWeek(dateToGenerate),
+ dayNumber: dateFns.format(dateToGenerate, 'd'),
+ date: dateToGenerate,
+ isWeekendDay: dateFns.isWeekend(dateToGenerate),
};
}
- this.daysAbsolute.push(currentDay.toDate());
+ this.daysAbsolute.push(dateToGenerate);
return day;
}
-
- isWeekend(date: moment.Moment): boolean {
- return parseInt(date.format('E'), 0) > 5;
- }
}