[ACS-5857] reverted moment migration for DateWidget and DateCloudWidget

This commit is contained in:
SheenaMalhotra182
2023-10-09 23:51:22 +05:30
parent 2cc6f6c96c
commit 27dbd03fe6
10 changed files with 96 additions and 145 deletions
@@ -163,7 +163,7 @@ export class DateFnsUtils {
/** /**
* Parses a date string using the specified date format. * Parses a date string using the specified date format.
* *
* @param value - The date string to parse. * @param date - The date string to parse.
* @param dateFormat - The date format string to use for parsing. * @param dateFormat - The date format string to use for parsing.
* @returns The parsed Date object. * @returns The parsed Date object.
*/ */
@@ -17,6 +17,7 @@
/* eslint-disable @angular-eslint/component-selector */ /* eslint-disable @angular-eslint/component-selector */
import moment from 'moment';
import { FormFieldTypes } from './form-field-types'; import { FormFieldTypes } from './form-field-types';
import { isNumberValue } from './form-field-utils'; import { isNumberValue } from './form-field-utils';
import { FormFieldModel } from './form-field.model'; import { FormFieldModel } from './form-field.model';
@@ -148,8 +149,8 @@ export class DateFieldValidator implements FormFieldValidator {
// Validates that the input string is a valid date formatted as <dateFormat> (default D-M-YYYY) // Validates that the input string is a valid date formatted as <dateFormat> (default D-M-YYYY)
static isValidDate(inputDate: string, dateFormat: string = 'D-M-YYYY'): boolean { static isValidDate(inputDate: string, dateFormat: string = 'D-M-YYYY'): boolean {
if (inputDate) { if (inputDate) {
const date = DateFnsUtils.parseDate(inputDate, dateFormat); const d = moment(inputDate, dateFormat, true);
return isValid(date); return d.isValid();
} }
return false; return false;
@@ -164,7 +165,7 @@ export class DateFieldValidator implements FormFieldValidator {
if (DateFieldValidator.isValidDate(field.value, field.dateDisplayFormat)) { if (DateFieldValidator.isValidDate(field.value, field.dateDisplayFormat)) {
return true; return true;
} }
field.validationSummary.message = DateFnsUtils.convertDateFnsToMomentFormat(field.dateDisplayFormat); field.validationSummary.message = field.dateDisplayFormat;
return false; return false;
} }
return true; return true;
@@ -211,8 +212,8 @@ export class DateTimeFieldValidator implements FormFieldValidator {
export abstract class BoundaryDateFieldValidator implements FormFieldValidator { export abstract class BoundaryDateFieldValidator implements FormFieldValidator {
DATE_FORMAT_CLOUD = 'yyyy-MM-dd'; DATE_FORMAT_CLOUD = 'YYYY-MM-DD';
DATE_FORMAT = 'dd-MM-yyyy'; DATE_FORMAT = 'DD-MM-YYYY';
supportedTypes = [ supportedTypes = [
FormFieldTypes.DATE FormFieldTypes.DATE
@@ -251,17 +252,17 @@ export class MinDateFieldValidator extends BoundaryDateFieldValidator {
// remove time and timezone info // remove time and timezone info
let fieldValueData; let fieldValueData;
if (typeof field.value === 'string') { if (typeof field.value === 'string') {
fieldValueData = DateFnsUtils.parseDate(field.value.split('T')[0], dateFormat); fieldValueData = moment(field.value.split('T')[0], dateFormat);
} else { } else {
fieldValueData = field.value; fieldValueData = field.value;
} }
const minValueDateFormat = this.extractDateFormat(field.minValue); const minValueDateFormat = this.extractDateFormat(field.minValue);
const min = DateFnsUtils.parseDate(field.minValue, minValueDateFormat); const min = moment(field.minValue, minValueDateFormat);
if (isBefore(fieldValueData, min)) { if (fieldValueData.isBefore(min)) {
field.validationSummary.message = `FORM.FIELD.VALIDATOR.NOT_LESS_THAN`; field.validationSummary.message = `FORM.FIELD.VALIDATOR.NOT_LESS_THAN`;
field.validationSummary.attributes.set('minValue', DateFnsUtils.formatDate(min, field.dateDisplayFormat).toLocaleUpperCase()); field.validationSummary.attributes.set('minValue', min.format(field.dateDisplayFormat).toLocaleUpperCase());
isFieldValid = false; isFieldValid = false;
} }
return isFieldValid; return isFieldValid;
@@ -281,17 +282,17 @@ export class MaxDateFieldValidator extends BoundaryDateFieldValidator {
// remove time and timezone info // remove time and timezone info
let fieldValueData; let fieldValueData;
if (typeof field.value === 'string') { if (typeof field.value === 'string') {
fieldValueData = DateFnsUtils.parseDate(field.value.split('T')[0], dateFormat); fieldValueData = moment(field.value.split('T')[0], dateFormat);
} else { } else {
fieldValueData = field.value; fieldValueData = field.value;
} }
const maxValueDateFormat = this.extractDateFormat(field.maxValue); const maxValueDateFormat = this.extractDateFormat(field.maxValue);
const max = DateFnsUtils.parseDate(field.maxValue, maxValueDateFormat); const max = moment(field.maxValue, maxValueDateFormat);
if (isAfter(fieldValueData, max)) { if (fieldValueData.isAfter(max)) {
field.validationSummary.message = `FORM.FIELD.VALIDATOR.NOT_GREATER_THAN`; field.validationSummary.message = `FORM.FIELD.VALIDATOR.NOT_GREATER_THAN`;
field.validationSummary.attributes.set('maxValue', DateFnsUtils.formatDate(max, field.dateDisplayFormat).toLocaleUpperCase()); field.validationSummary.attributes.set('maxValue', max.format(field.dateDisplayFormat).toLocaleUpperCase());
isFieldValid = false; isFieldValid = false;
} }
return isFieldValid; return isFieldValid;
@@ -320,7 +321,7 @@ export class MinDateTimeFieldValidator implements FormFieldValidator {
if (this.isSupported(field) && field.value && field.isVisible) { if (this.isSupported(field) && field.value && field.isVisible) {
const dateFormat = field.dateDisplayFormat; const dateFormat = field.dateDisplayFormat;
if (!DateFieldValidator.isValidDate(field.value, dateFormat)) { if (!DateTimeFieldValidator.isValidDate(field.value, dateFormat)) {
field.validationSummary.message = 'FORM.FIELD.VALIDATOR.INVALID_DATE'; field.validationSummary.message = 'FORM.FIELD.VALIDATOR.INVALID_DATE';
isFieldValid = false; isFieldValid = false;
} else { } else {
@@ -366,7 +367,7 @@ export class MaxDateTimeFieldValidator implements FormFieldValidator {
if (this.isSupported(field) && field.value && field.isVisible) { if (this.isSupported(field) && field.value && field.isVisible) {
const dateFormat = field.dateDisplayFormat; const dateFormat = field.dateDisplayFormat;
if (!DateFieldValidator.isValidDate(field.value, dateFormat)) { if (!DateTimeFieldValidator.isValidDate(field.value, dateFormat)) {
field.validationSummary.message = 'FORM.FIELD.VALIDATOR.INVALID_DATE'; field.validationSummary.message = 'FORM.FIELD.VALIDATOR.INVALID_DATE';
isFieldValid = false; isFieldValid = false;
} else { } else {
@@ -15,6 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
import moment from 'moment';
import { FormFieldTypes } from './form-field-types'; import { FormFieldTypes } from './form-field-types';
import { FormFieldModel } from './form-field.model'; import { FormFieldModel } from './form-field.model';
import { FormModel } from './form.model'; import { FormModel } from './form.model';
@@ -273,9 +274,9 @@ describe('FormFieldModel', () => {
dateDisplayFormat: 'DD-MM-YYYY' dateDisplayFormat: 'DD-MM-YYYY'
}); });
const currentDate = new Date(); const currentDate = moment(new Date());
const expectedDate = DateFnsUtils.formatDate(currentDate, 'DD-MM-YYYY'); const expectedDate = moment(currentDate).format('DD-MM-YYYY');
const expectedDateFormat = `${DateFnsUtils.formatDate(currentDate, 'YYYY-MM-DD')}T00:00:00.000Z`; const expectedDateFormat = `${currentDate.format('YYYY-MM-DD')}T00:00:00.000Z`;
expect(field.value).toBe(expectedDate); expect(field.value).toBe(expectedDate);
expect(form.values['ddmmyyy']).toEqual(expectedDateFormat); expect(form.values['ddmmyyy']).toEqual(expectedDateFormat);
@@ -16,6 +16,7 @@
*/ */
/* eslint-disable @angular-eslint/component-selector */ /* eslint-disable @angular-eslint/component-selector */
import moment from 'moment';
import { WidgetVisibilityModel } from '../../../models/widget-visibility.model'; import { WidgetVisibilityModel } from '../../../models/widget-visibility.model';
import { ContainerColumnModel } from './container-column.model'; import { ContainerColumnModel } from './container-column.model';
import { ErrorMessageModel } from './error-message.model'; import { ErrorMessageModel } from './error-message.model';
@@ -39,7 +40,7 @@ export class FormFieldModel extends FormWidgetModel {
private _isValid: boolean = true; private _isValid: boolean = true;
private _required: boolean = false; private _required: boolean = false;
readonly defaultDateFormat: string = 'd-M-yyyy'; readonly defaultDateFormat: string = 'D-M-YYYY';
readonly defaultDateTimeFormat: string = 'd-M-yyyy hh:mm a'; readonly defaultDateTimeFormat: string = 'd-M-yyyy hh:mm a';
// model members // model members
@@ -190,7 +191,7 @@ export class FormFieldModel extends FormWidgetModel {
this.visibilityCondition = json.visibilityCondition ? new WidgetVisibilityModel(json.visibilityCondition) : undefined; this.visibilityCondition = json.visibilityCondition ? new WidgetVisibilityModel(json.visibilityCondition) : undefined;
this.enableFractions = json.enableFractions; this.enableFractions = json.enableFractions;
this.currency = json.currency; this.currency = json.currency;
this.dateDisplayFormat = DateFnsUtils.convertMomentToDateFnsFormat(json.dateDisplayFormat) || this.getDefaultDateFormat(json); this.dateDisplayFormat = json.dateDisplayFormat || this.getDefaultDateFormat(json);
this._value = this.parseValue(json); this._value = this.parseValue(json);
this.validationSummary = new ErrorMessageModel(); this.validationSummary = new ErrorMessageModel();
this.tooltip = json.tooltip; this.tooltip = json.tooltip;
@@ -241,22 +242,11 @@ export class FormFieldModel extends FormWidgetModel {
} }
private getDefaultDateFormat(jsonField: any): string { private getDefaultDateFormat(jsonField: any): string {
if (jsonField.fields) {
Object.keys(jsonField.fields).forEach((el) => {
if (jsonField.fields[el]) {
jsonField.fields[el].forEach((element) => {
element.dateDisplayFormat = element.dateDisplayFormat
? DateFnsUtils.convertMomentToDateFnsFormat(element.dateDisplayFormat)
: element.dateDisplayFormat;
});
}
});
}
let originalType = jsonField.type; let originalType = jsonField.type;
if (FormFieldTypes.isReadOnlyType(jsonField.type) && jsonField.params && jsonField.params.field) { if (FormFieldTypes.isReadOnlyType(jsonField.type) && jsonField.params && jsonField.params.field) {
originalType = jsonField.params.field.type; originalType = jsonField.params.field.type;
} }
return originalType === FormFieldTypes.DATETIME ? this.defaultDateTimeFormat : this.defaultDateFormat; return originalType === FormFieldTypes.DATETIME ? DateFnsUtils.convertMomentToDateFnsFormat(this.defaultDateTimeFormat) : this.defaultDateFormat;
} }
private isTypeaheadFieldType(type: string): boolean { private isTypeaheadFieldType(type: string): boolean {
@@ -366,12 +356,12 @@ export class FormFieldModel extends FormWidgetModel {
if (value) { if (value) {
let dateValue; let dateValue;
if (isNumberValue(value)) { if (isNumberValue(value)) {
dateValue = new Date(value); dateValue = moment(value);
} else { } else {
dateValue = DateFnsUtils.parseDate(value.split('T')[0], 'YYYY-M-D'); dateValue = moment.utc(value.split('T')[0], 'YYYY-M-D');
} }
if (isValid(dateValue)) { if (dateValue?.isValid()) {
value = DateFnsUtils.formatDate(dateValue, this.dateDisplayFormat); value = dateValue.utc().format(this.dateDisplayFormat);
} }
} }
} }
@@ -46,7 +46,7 @@ export class DateTimeWidgetComponent extends WidgetComponent implements OnInit,
private onDestroy$ = new Subject<boolean>(); private onDestroy$ = new Subject<boolean>();
constructor(public formService: FormService, constructor(public formService: FormService,
private dateAdapter: DateAdapter<DateFnsAdapter>, private dateAdapter: DateAdapter<Date>,
private userPreferencesService: UserPreferencesService, private userPreferencesService: UserPreferencesService,
@Inject(MAT_DATE_FORMATS) private dateFormatConfig: MatDateFormats, @Inject(MAT_DATE_FORMATS) private dateFormatConfig: MatDateFormats,
private translationService: TranslationService) { private translationService: TranslationService) {
@@ -16,14 +16,13 @@
*/ */
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import moment from 'moment';
import { FormFieldModel } from '../core/form-field.model'; import { FormFieldModel } from '../core/form-field.model';
import { FormModel } from '../core/form.model'; import { FormModel } from '../core/form.model';
import { DateWidgetComponent } from './date.widget'; import { DateWidgetComponent } from './date.widget';
import { CoreTestingModule } from '../../../../testing/core.testing.module'; import { CoreTestingModule } from '../../../../testing/core.testing.module';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { FormFieldTypes } from '../core/form-field-types'; import { FormFieldTypes } from '../core/form-field-types';
import { isSameDay } from 'date-fns';
import { DateFnsUtils } from '../../../../common';
describe('DateWidgetComponent', () => { describe('DateWidgetComponent', () => {
let widget: DateWidgetComponent; let widget: DateWidgetComponent;
@@ -63,8 +62,8 @@ describe('DateWidgetComponent', () => {
widget.ngOnInit(); widget.ngOnInit();
const expectedMinDate = DateFnsUtils.parseDate(minValue, widget.field.dateDisplayFormat); const expected = moment(minValue, widget.field.dateDisplayFormat);
expect(isSameDay(widget.minDate, expectedMinDate)).toBeTruthy(); expect(widget.minDate.isSame(expected)).toBeTruthy();
}); });
it('should date field be present', () => { it('should date field be present', () => {
@@ -86,8 +85,8 @@ describe('DateWidgetComponent', () => {
}); });
widget.ngOnInit(); widget.ngOnInit();
const expectedMaxDate = DateFnsUtils.parseDate(maxValue, widget.field.dateDisplayFormat); const expected = moment(maxValue, widget.field.dateDisplayFormat);
expect(isSameDay(widget.maxDate, expectedMaxDate)).toBeTruthy(); expect(widget.maxDate.isSame(expected)).toBeTruthy();
}); });
it('should eval visibility on date changed', () => { it('should eval visibility on date changed', () => {
@@ -250,20 +249,4 @@ describe('DateWidgetComponent', () => {
expect(dateElement?.value).toContain('03-02-2020'); expect(dateElement?.value).toContain('03-02-2020');
}); });
describe('format label', () => {
beforeEach(() => {
widget.field = new FormFieldModel(new FormModel({ taskId: '<id>' }), {
name: 'Date',
dateDisplayFormat: 'd-M-yyyy'
});
fixture.detectChanges();
});
it('should format label correctly', () => {
const result = widget.formatDateLabel(widget.field);
expect(result).toBe('Date (D-M-YYYY)');
});
});
}); });
@@ -32,9 +32,8 @@ import { MatDatepickerInputEvent } from '@angular/material/datepicker';
@Component({ @Component({
selector: 'date-widget', selector: 'date-widget',
providers: [ providers: [
{ provide: DateAdapter, useClass: DateFnsAdapter }, { provide: DateAdapter, useClass: MomentDateAdapter },
{ provide: MAT_DATE_FORMATS, useValue: MAT_DATE_FNS_FORMATS } { provide: MAT_DATE_FORMATS, useValue: MOMENT_DATE_FORMATS }],
],
templateUrl: './date.widget.html', templateUrl: './date.widget.html',
host: { host: {
'(click)': 'event($event)', '(click)': 'event($event)',
@@ -63,10 +62,8 @@ export class DateWidgetComponent extends WidgetComponent implements OnInit, OnDe
private onDestroy$ = new Subject<boolean>(); private onDestroy$ = new Subject<boolean>();
constructor(public formService: FormService, constructor(public formService: FormService,
private dateAdapter: DateAdapter<DateFnsAdapter>, private dateAdapter: DateAdapter<Moment>,
private userPreferencesService: UserPreferencesService, private userPreferencesService: UserPreferencesService) {
@Inject(MAT_DATE_FORMATS) private dateFormatConfig: MatDateFormats,
private translationService: TranslationService) {
super(formService); super(formService);
} }
@@ -74,9 +71,10 @@ export class DateWidgetComponent extends WidgetComponent implements OnInit, OnDe
this.userPreferencesService this.userPreferencesService
.select(UserPreferenceValues.Locale) .select(UserPreferenceValues.Locale)
.pipe(takeUntil(this.onDestroy$)) .pipe(takeUntil(this.onDestroy$))
.subscribe(locale => this.dateAdapter.setLocale(DateFnsUtils.getLocaleFromString(locale))); .subscribe(locale => this.dateAdapter.setLocale(locale));
this.dateFormatConfig.display.dateInput = this.field.dateDisplayFormat; const momentDateAdapter = this.dateAdapter as MomentDateAdapter;
momentDateAdapter.overrideDisplayFormat = this.field.dateDisplayFormat;
if (this.field) { if (this.field) {
if (this.field.minValue) { if (this.field.minValue) {
@@ -1,11 +1,11 @@
<div class="{{field.className}}" id="data-widget" [class.adf-invalid]="!field.isValid && isTouched()" [class.adf-left-label-input-container]="field.leftLabels"> <div class="{{field.className}}" id="data-widget" [class.adf-invalid]="!field.isValid && isTouched()" [class.adf-left-label-input-container]="field.leftLabels">
<div *ngIf="field.leftLabels"> <div *ngIf="field.leftLabels">
<label class="adf-label adf-left-label" [attr.for]="field.id">{{formatLabel(field)}}<span class="adf-asterisk" <label class="adf-label adf-left-label" [attr.for]="field.id">{{field.name | translate }} ({{field.dateDisplayFormat}})<span class="adf-asterisk"
*ngIf="isRequired()">*</span></label> *ngIf="isRequired()">*</span></label>
</div> </div>
<div> <div>
<mat-form-field class="adf-date-widget" [class.adf-left-label-input-datepicker]="field.leftLabels" [hideRequiredMarker]="true"> <mat-form-field class="adf-date-widget" [class.adf-left-label-input-datepicker]="field.leftLabels" [hideRequiredMarker]="true">
<label class="adf-label" *ngIf="!field.leftLabels" [attr.for]="field.id">{{formatLabel(field)}}<span class="adf-asterisk" <label class="adf-label" *ngIf="!field.leftLabels" [attr.for]="field.id">{{field.name | translate }} ({{field.dateDisplayFormat}})<span class="adf-asterisk"
*ngIf="isRequired()">*</span></label> *ngIf="isRequired()">*</span></label>
<input matInput <input matInput
[id]="field.id" [id]="field.id"
@@ -22,11 +22,11 @@
</mat-form-field> </mat-form-field>
<error-widget [error]="field.validationSummary"></error-widget> <error-widget [error]="field.validationSummary"></error-widget>
<error-widget *ngIf="isInvalidFieldRequired() && isTouched()" required="{{ 'FORM.FIELD.REQUIRED' | translate }}"></error-widget> <error-widget *ngIf="isInvalidFieldRequired() && isTouched()" required="{{ 'FORM.FIELD.REQUIRED' | translate }}"></error-widget>
<mat-datepicker #datePicker [touchUi]="true" [startAt]="field.value | adfDate: field.dateDisplayFormat" [disabled]="field.readOnly"></mat-datepicker> <mat-datepicker #datePicker [touchUi]="true" [startAt]="field.value | adfMomentDate: field.dateDisplayFormat" [disabled]="field.readOnly"></mat-datepicker>
<input <input
type="hidden" type="hidden"
[matDatepicker]="datePicker" [matDatepicker]="datePicker"
[value]="field.value | adfDate: field.dateDisplayFormat" [value]="field.value | adfMomentDate: field.dateDisplayFormat"
[min]="minDate" [min]="minDate"
[max]="maxDate" [max]="maxDate"
[disabled]="field.readOnly" [disabled]="field.readOnly"
@@ -17,12 +17,12 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { DateCloudWidgetComponent } from './date-cloud.widget'; import { DateCloudWidgetComponent } from './date-cloud.widget';
import { FormFieldModel, FormModel, FormFieldTypes, DateFnsUtils } from '@alfresco/adf-core'; import { FormFieldModel, FormModel, FormFieldTypes } from '@alfresco/adf-core';
import moment from 'moment';
import { ProcessServiceCloudTestingModule } from '../../../../testing/process-service-cloud.testing.module'; import { ProcessServiceCloudTestingModule } from '../../../../testing/process-service-cloud.testing.module';
import { TranslateModule } from '@ngx-translate/core'; import { TranslateModule } from '@ngx-translate/core';
import { DATE_FORMAT_CLOUD } from '../../../../models/date-format-cloud.model'; import { DATE_FORMAT_CLOUD } from '../../../../models/date-format-cloud.model';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { addDays, isSameDay, subDays } from 'date-fns';
describe('DateWidgetComponent', () => { describe('DateWidgetComponent', () => {
@@ -52,8 +52,8 @@ describe('DateWidgetComponent', () => {
widget.ngOnInit(); widget.ngOnInit();
const expected = DateFnsUtils.parseDate(minValue, DATE_FORMAT_CLOUD); const expected = moment(minValue, DATE_FORMAT_CLOUD);
expect(isSameDay(widget.minDate, expected)).toBeTruthy(); expect(widget.minDate.isSame(expected)).toBeTruthy();
}); });
it('should date field be present', () => { it('should date field be present', () => {
@@ -75,8 +75,8 @@ describe('DateWidgetComponent', () => {
}); });
widget.ngOnInit(); widget.ngOnInit();
const expected = DateFnsUtils.parseDate(maxValue, DATE_FORMAT_CLOUD); const expected = moment(maxValue, DATE_FORMAT_CLOUD);
expect(isSameDay(widget.maxDate, expected)).toBeTruthy(); expect(widget.maxDate.isSame(expected)).toBeTruthy();
}); });
it('should eval visibility on date changed', () => { it('should eval visibility on date changed', () => {
@@ -91,8 +91,8 @@ describe('DateWidgetComponent', () => {
}); });
widget.field = field; widget.field = field;
const todayDate = new Date(); const todayDate = moment().format(DATE_FORMAT_CLOUD);
widget.onDateChanged({ value: DateFnsUtils.formatDate(todayDate, DATE_FORMAT_CLOUD) }); widget.onDateChanged({ value: todayDate });
expect(widget.onFieldChanged).toHaveBeenCalledWith(field); expect(widget.onFieldChanged).toHaveBeenCalledWith(field);
}); });
@@ -293,10 +293,9 @@ describe('DateWidgetComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const todayDate = new Date(); const todayDate = moment().format(DATE_FORMAT_CLOUD);
const expected = DateFnsUtils.formatDate(subDays(todayDate, widget.field.minDateRangeValue), DATE_FORMAT_CLOUD); const expected = moment(todayDate).subtract(widget.field.minDateRangeValue, 'days');
const minDateFormatted = DateFnsUtils.formatDate(widget.minDate, DATE_FORMAT_CLOUD); expect(widget.minDate).toEqual(expected);
expect(minDateFormatted).toEqual(expected);
}); });
it('should min date and max date be undefined if dynamic min and max date are not set', async () => { it('should min date and max date be undefined if dynamic min and max date are not set', async () => {
@@ -344,10 +343,9 @@ describe('DateWidgetComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const todayDate = new Date(); const todayDate = moment().format(DATE_FORMAT_CLOUD);
const expected = DateFnsUtils.formatDate(addDays(todayDate, widget.field.maxDateRangeValue), DATE_FORMAT_CLOUD); const expected = moment(todayDate).add(widget.field.maxDateRangeValue, 'days');
const maxDateFormatted = DateFnsUtils.formatDate(widget.maxDate, DATE_FORMAT_CLOUD); expect(widget.maxDate).toEqual(expected);
expect(maxDateFormatted).toEqual(expected);
}); });
it('should maxDate and minDate be undefined if minDateRangeValue and maxDateRangeValue are null', async () => { it('should maxDate and minDate be undefined if minDateRangeValue and maxDateRangeValue are null', async () => {
@@ -394,6 +392,7 @@ describe('DateWidgetComponent', () => {
describe('check date validation by dynamic date ranges', () => { describe('check date validation by dynamic date ranges', () => {
it('should minValue be equal to today date minus minDateRangeValue', async () => { it('should minValue be equal to today date minus minDateRangeValue', async () => {
spyOn(widget, 'getTodaysFormattedDate').and.returnValue('2022-07-22');
widget.field = new FormFieldModel(null, { widget.field = new FormFieldModel(null, {
dynamicDateRangeSelection: true, dynamicDateRangeSelection: true,
maxDateRangeValue: null, maxDateRangeValue: null,
@@ -405,8 +404,7 @@ describe('DateWidgetComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const currentDate = new Date(); const expectedMinValueString = '2022-07-21';
const expectedMinValueString = DateFnsUtils.formatDate(subDays(currentDate, 1), DATE_FORMAT_CLOUD);
expect(widget.field.minValue).toEqual(expectedMinValueString); expect(widget.field.minValue).toEqual(expectedMinValueString);
expect(widget.maxDate).toBeUndefined(); expect(widget.maxDate).toBeUndefined();
@@ -414,6 +412,7 @@ describe('DateWidgetComponent', () => {
}); });
it('should maxValue be equal to today date plus maxDateRangeValue', async () => { it('should maxValue be equal to today date plus maxDateRangeValue', async () => {
spyOn(widget, 'getTodaysFormattedDate').and.returnValue('2022-07-22');
widget.field = new FormFieldModel(null, { widget.field = new FormFieldModel(null, {
dynamicDateRangeSelection: true, dynamicDateRangeSelection: true,
maxDateRangeValue: 8, maxDateRangeValue: 8,
@@ -425,8 +424,7 @@ describe('DateWidgetComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const currentDate = new Date(); const expectedMaxValueString = '2022-07-30';
const expectedMaxValueString = DateFnsUtils.formatDate(addDays(currentDate, 8), DATE_FORMAT_CLOUD);
expect(widget.field.maxValue).toEqual(expectedMaxValueString); expect(widget.field.maxValue).toEqual(expectedMaxValueString);
expect(widget.minDate).toBeUndefined(); expect(widget.minDate).toBeUndefined();
@@ -434,6 +432,7 @@ describe('DateWidgetComponent', () => {
}); });
it('should maxValue and minValue be null if maxDateRangeValue and minDateRangeValue are null', async () => { it('should maxValue and minValue be null if maxDateRangeValue and minDateRangeValue are null', async () => {
spyOn(widget, 'getTodaysFormattedDate').and.returnValue('2022-07-22');
widget.field = new FormFieldModel(null, { widget.field = new FormFieldModel(null, {
dynamicDateRangeSelection: true, dynamicDateRangeSelection: true,
maxDateRangeValue: null, maxDateRangeValue: null,
@@ -452,6 +451,7 @@ describe('DateWidgetComponent', () => {
}); });
it('should maxValue and minValue not be null if maxDateRangeVale and minDateRangeValue are not null', async () => { it('should maxValue and minValue not be null if maxDateRangeVale and minDateRangeValue are not null', async () => {
spyOn(widget, 'getTodaysFormattedDate').and.returnValue('2022-07-22');
widget.field = new FormFieldModel(null, { widget.field = new FormFieldModel(null, {
dynamicDateRangeSelection: true, dynamicDateRangeSelection: true,
maxDateRangeValue: 8, maxDateRangeValue: 8,
@@ -463,9 +463,8 @@ describe('DateWidgetComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const currentDate = new Date(); const expectedMaxValueString = '2022-07-30';
const expectedMaxValueString = DateFnsUtils.formatDate(addDays(currentDate, 8), DATE_FORMAT_CLOUD); const expectedMinValueString = '2022-07-12';
const expectedMinValueString = DateFnsUtils.formatDate(subDays(currentDate, 10), DATE_FORMAT_CLOUD);
expect(widget.field.maxValue).toEqual(expectedMaxValueString); expect(widget.field.maxValue).toEqual(expectedMaxValueString);
expect(widget.field.minValue).toEqual(expectedMinValueString); expect(widget.field.minValue).toEqual(expectedMinValueString);
@@ -543,20 +542,4 @@ describe('DateWidgetComponent', () => {
expect(element.querySelector('.adf-invalid')).toBeTruthy(); expect(element.querySelector('.adf-invalid')).toBeTruthy();
}); });
}); });
describe('format label', () => {
beforeEach(() => {
widget.field = new FormFieldModel(new FormModel({ taskId: '<id>' }), {
name: 'Date Field',
dateDisplayFormat: 'd-M-yyyy'
});
fixture.detectChanges();
});
it('should format label correctly', () => {
const result = widget.formatLabel(widget.field);
expect(result).toBe('Date Field (D-M-YYYY)');
});
});
}); });
@@ -17,23 +17,22 @@
/* eslint-disable @angular-eslint/component-selector */ /* eslint-disable @angular-eslint/component-selector */
import { Component, OnInit, ViewEncapsulation, OnDestroy, Inject } from '@angular/core'; import { Component, OnInit, ViewEncapsulation, OnDestroy } from '@angular/core';
import { DateAdapter, MAT_DATE_FORMATS, MatDateFormats } from '@angular/material/core'; import { DateAdapter, MAT_DATE_FORMATS } from '@angular/material/core';
import moment, { Moment } from 'moment';
import { Subject } from 'rxjs'; import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators'; import { takeUntil } from 'rxjs/operators';
import { import {
WidgetComponent, MOMENT_DATE_FORMATS, MomentDateAdapter, WidgetComponent,
UserPreferencesService, UserPreferenceValues, FormService, DateFnsUtils, TranslationService, FormFieldModel UserPreferencesService, UserPreferenceValues, FormService
} from '@alfresco/adf-core'; } from '@alfresco/adf-core';
import { DATE_FORMAT_CLOUD } from '../../../../models/date-format-cloud.model'; import { DATE_FORMAT_CLOUD } from '../../../../models/date-format-cloud.model';
import { DateFnsAdapter, MAT_DATE_FNS_FORMATS } from '@angular/material-date-fns-adapter';
import { addDays, isValid, subDays } from 'date-fns';
@Component({ @Component({
selector: 'date-widget', selector: 'date-widget',
providers: [ providers: [
{ provide: DateAdapter, useClass: DateFnsAdapter }, { provide: DateAdapter, useClass: MomentDateAdapter },
{ provide: MAT_DATE_FORMATS, useValue: MAT_DATE_FNS_FORMATS }], { provide: MAT_DATE_FORMATS, useValue: MOMENT_DATE_FORMATS }],
templateUrl: './date-cloud.widget.html', templateUrl: './date-cloud.widget.html',
styleUrls: ['./date-cloud.widget.scss'], styleUrls: ['./date-cloud.widget.scss'],
host: { host: {
@@ -52,16 +51,14 @@ import { addDays, isValid, subDays } from 'date-fns';
export class DateCloudWidgetComponent extends WidgetComponent implements OnInit, OnDestroy { export class DateCloudWidgetComponent extends WidgetComponent implements OnInit, OnDestroy {
typeId = 'DateCloudWidgetComponent'; typeId = 'DateCloudWidgetComponent';
minDate: Date; minDate: Moment;
maxDate: Date; maxDate: Moment;
private onDestroy$ = new Subject<boolean>(); private onDestroy$ = new Subject<boolean>();
constructor(public formService: FormService, constructor(public formService: FormService,
private dateAdapter: DateAdapter<DateFnsAdapter>, private dateAdapter: DateAdapter<Moment>,
private userPreferencesService: UserPreferencesService, private userPreferencesService: UserPreferencesService) {
@Inject(MAT_DATE_FORMATS) private dateFormatConfig: MatDateFormats,
private translationService: TranslationService) {
super(formService); super(formService);
} }
@@ -69,49 +66,47 @@ export class DateCloudWidgetComponent extends WidgetComponent implements OnInit,
this.userPreferencesService this.userPreferencesService
.select(UserPreferenceValues.Locale) .select(UserPreferenceValues.Locale)
.pipe(takeUntil(this.onDestroy$)) .pipe(takeUntil(this.onDestroy$))
.subscribe(locale => this.dateAdapter.setLocale(DateFnsUtils.getLocaleFromString(locale))); .subscribe(locale => this.dateAdapter.setLocale(locale));
this.dateFormatConfig.display.dateInput = this.field.dateDisplayFormat; const momentDateAdapter = this.dateAdapter as MomentDateAdapter;
momentDateAdapter.overrideDisplayFormat = this.field.dateDisplayFormat;
if (this.field) { if (this.field) {
if (this.field.dynamicDateRangeSelection) { if (this.field.dynamicDateRangeSelection) {
const today = new Date(); const today = this.getTodaysFormattedDate();
if (Number.isInteger(this.field.minDateRangeValue)) { if (Number.isInteger(this.field.minDateRangeValue)) {
this.minDate = subDays(today, this.field.minDateRangeValue); this.minDate = moment(today).subtract(this.field.minDateRangeValue, 'days');
this.field.minValue = DateFnsUtils.formatDate(this.minDate, DATE_FORMAT_CLOUD); this.field.minValue = this.minDate.format(DATE_FORMAT_CLOUD);
} }
if (Number.isInteger(this.field.maxDateRangeValue)) { if (Number.isInteger(this.field.maxDateRangeValue)) {
this.maxDate = addDays(today, this.field.maxDateRangeValue); this.maxDate = moment(today).add(this.field.maxDateRangeValue, 'days');
this.field.maxValue = DateFnsUtils.formatDate(this.maxDate, DATE_FORMAT_CLOUD); this.field.maxValue = this.maxDate.format(DATE_FORMAT_CLOUD);
} }
} else { } else {
if (this.field.minValue) { if (this.field.minValue) {
this.minDate = DateFnsUtils.parseDate(this.field.minValue, DATE_FORMAT_CLOUD); this.minDate = moment(this.field.minValue, DATE_FORMAT_CLOUD);
} }
if (this.field.maxValue) { if (this.field.maxValue) {
this.maxDate = DateFnsUtils.parseDate(this.field.maxValue, DATE_FORMAT_CLOUD); this.maxDate = moment(this.field.maxValue, DATE_FORMAT_CLOUD);
} }
} }
} }
} }
getTodaysFormattedDate() {
return moment().format(DATE_FORMAT_CLOUD);
}
ngOnDestroy() { ngOnDestroy() {
this.onDestroy$.next(true); this.onDestroy$.next(true);
this.onDestroy$.complete(); this.onDestroy$.complete();
} }
formatLabel(field: FormFieldModel): string {
const displayName = this.translationService.instant(field.name);
const displayFormat = DateFnsUtils.convertDateFnsToMomentFormat(field.dateDisplayFormat);
return `${displayName} (${displayFormat})`;
}
onDateChanged(newDateValue) { onDateChanged(newDateValue) {
const date = DateFnsUtils.parseDate(newDateValue, this.field.dateDisplayFormat); const date = moment(newDateValue, this.field.dateDisplayFormat, true);
if (isValid(date)) { if (date.isValid()) {
this.field.value = DateFnsUtils.formatDate(date, this.field.dateDisplayFormat); this.field.value = date.format(this.field.dateDisplayFormat);
} else { } else {
this.field.value = newDateValue; this.field.value = newDateValue;
} }