Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Development: Use signals in date time picker #9694

Merged
merged 13 commits into from
Nov 9, 2024
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
@if (labelName) {
@if (labelName()) {
<label for="date-input-field" class="form-control-label col">
{{ labelName }}
{{ labelName() }}
</label>
}
@if (labelTooltip) {
<fa-stack class="text-secondary icon-full-size" [ngbTooltip]="labelTooltip">
@if (labelTooltip()) {
<fa-stack class="text-secondary icon-full-size" [ngbTooltip]="labelTooltip()">
<fa-icon [icon]="faQuestionCircle" stackItemSize="1x" />
</fa-stack>
}
@if (shouldDisplayTimeZoneWarning) {
@if (shouldDisplayTimeZoneWarning()) {
<fa-stack ngbTooltip="{{ 'entity.timeZoneWarning' | artemisTranslate: { timeZone: currentTimeZone } }}" class="icon-full-size">
<fa-icon [icon]="faGlobe" stackItemSize="1x" class="text-lightgrey" />
<fa-icon [icon]="faClock" stackItemSize="1x" transform="shrink-6 down-5 right-5" class="text-secondary" />
Expand All @@ -19,12 +19,12 @@
#dateInput="ngModel"
class="form-control position-relative ps-5"
id="date-input-field"
[ngClass]="{ 'is-invalid': error || dateInput.invalid || (requiredField && !dateInput.value) || warning, 'border-warning': warning }"
[class.ng-invalid]="error || dateInput.invalid || (requiredField && !dateInput.value) || warning"
[ngModel]="value"
[disabled]="disabled"
[min]="minDate"
[max]="maxDate"
[ngClass]="{ 'is-invalid': !isValid(), 'border-warning': warning() }"
[class.ng-invalid]="!isValid()"
[ngModel]="value()"
[disabled]="disabled()"
[min]="minDate()"
[max]="maxDate()"
(ngModelChange)="updateField($event)"
[owlDateTime]="dt"
name="datePicker"
Expand All @@ -38,12 +38,12 @@
</button>
</div>

<owl-date-time [startAt]="startDate" #dt />
<owl-date-time [startAt]="startDate()" #dt />
</div>
@if (dateInput.invalid || (requiredField && !dateInput.value)) {
<div class="invalid-feedback" jhiTranslate="entity.dateMissingOrNotValid" [translateValues]="{ labelName: labelName }"></div>
@if (dateInput.invalid || (requiredField() && !dateInput.value)) {
<div class="invalid-feedback" jhiTranslate="entity.dateMissingOrNotValid" [translateValues]="{ labelName: labelName() }"></div>
}
@if (warning) {
@if (warning()) {
<div class="invalid-feedback">
<fa-icon class="text-warning" [icon]="faTriangleExclamation" />
<span class="visible-date-warning" jhiTranslate="entity.warningError" ngbTooltip="{{ 'entity.warningToolTip' | artemisTranslate }}"></span>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Component, EventEmitter, Input, Output, ViewChild, forwardRef } from '@angular/core';
import { Component, ViewChild, computed, forwardRef, input, model, output, signal } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR, NgModel } from '@angular/forms';
import { faCalendarAlt, faCircleXmark, faClock, faGlobe, faQuestionCircle, faTriangleExclamation } from '@fortawesome/free-solid-svg-icons';
import dayjs from 'dayjs/esm';
Expand All @@ -16,26 +16,39 @@ import dayjs from 'dayjs/esm';
],
})
export class FormDateTimePickerComponent implements ControlValueAccessor {
protected readonly faCalendarAlt = faCalendarAlt;
protected readonly faGlobe = faGlobe;
protected readonly faClock = faClock;
protected readonly faQuestionCircle = faQuestionCircle;
protected readonly faCircleXmark = faCircleXmark;
protected readonly faTriangleExclamation = faTriangleExclamation;

@ViewChild('dateInput', { static: false }) dateInput: NgModel;
@Input() labelName: string;
@Input() labelTooltip: string;
@Input() value: any;
@Input() disabled: boolean;
@Input() error: boolean;
@Input() warning: boolean;
@Input() requiredField: boolean = false;
@Input() startAt?: dayjs.Dayjs; // Default selected date. By default, this sets it to the current time without seconds or milliseconds;
@Input() min?: dayjs.Dayjs; // Dates before this date are not selectable.
@Input() max?: dayjs.Dayjs; // Dates after this date are not selectable.
@Input() shouldDisplayTimeZoneWarning = true; // Displays a warning that the current time zone might differ from the participants'.
@Output() valueChange = new EventEmitter();

readonly faCalendarAlt = faCalendarAlt;
readonly faGlobe = faGlobe;
readonly faClock = faClock;
readonly faQuestionCircle = faQuestionCircle;
readonly faCircleXmark = faCircleXmark;
readonly faTriangleExclamation = faTriangleExclamation;
labelName = input<string>();
labelTooltip = input<string>();
value = model<dayjs.Dayjs | Date | null>();
disabled = input<boolean>(false);
error = input<boolean>();
warning = input<boolean>();
requiredField = input<boolean>(false);
startAt = input<dayjs.Dayjs | undefined>(); // Default selected date. By default, this sets it to the current time without seconds or milliseconds;
min = input<dayjs.Dayjs>(); // Dates before this date are not selectable.
max = input<dayjs.Dayjs>(); // Dates after this date are not selectable.
shouldDisplayTimeZoneWarning = input<boolean>(true); // Displays a warning that the current time zone might differ from the participants'.
valueChange = output<void>();

protected isInputValid = signal<boolean>(false);
protected dateInputValue = signal<string>('');

isValid = computed(() => {
const isInvalid = this.error() || !this.isInputValid() || (this.requiredField() && !this.dateInputValue()) || this.warning();
return !isInvalid;
});

private updateSignals(): void {
this.isInputValid.set(!Boolean(this.dateInput?.invalid));
this.dateInputValue.set(this.dateInput?.value);
}

florian-glombik marked this conversation as resolved.
Show resolved Hide resolved
private onChange?: (val?: dayjs.Dayjs) => void;

Expand All @@ -44,6 +57,7 @@ export class FormDateTimePickerComponent implements ControlValueAccessor {
*/
valueChanged() {
this.valueChange.emit();
this.updateSignals();
}

/**
Expand All @@ -53,10 +67,11 @@ export class FormDateTimePickerComponent implements ControlValueAccessor {
writeValue(value: any) {
// convert dayjs to date, because owl-date-time only works correctly with date objects
if (dayjs.isDayjs(value)) {
this.value = (value as dayjs.Dayjs).toDate();
this.value.set((value as dayjs.Dayjs).toDate());
} else {
this.value = value;
this.value.set(value);
}
this.updateSignals();
}

/**
Expand All @@ -79,8 +94,8 @@ export class FormDateTimePickerComponent implements ControlValueAccessor {
* @param newValue
*/
updateField(newValue: dayjs.Dayjs) {
this.value = newValue;
this.onChange?.(dayjs(this.value));
this.value.set(newValue);
this.onChange?.(dayjs(this.value()));
this.valueChanged();
}
florian-glombik marked this conversation as resolved.
Show resolved Hide resolved

Expand All @@ -91,17 +106,17 @@ export class FormDateTimePickerComponent implements ControlValueAccessor {
return Intl.DateTimeFormat().resolvedOptions().timeZone;
}

get startDate(): Date | null {
return this.convertToDate(this.startAt ?? dayjs().startOf('minutes'));
}
startDate = computed(() => {
return this.convertToDate(this.startAt?.() ?? dayjs().startOf('minutes'));
});

get minDate(): Date | null {
return this.convertToDate(this.min);
}
minDate = computed(() => {
return this.convertToDate(this.min?.());
});

get maxDate(): Date | null {
return this.convertToDate(this.max);
}
maxDate = computed(() => {
return this.convertToDate(this.max?.());
});

/**
* Function that converts a possibly undefined dayjs value to a date or null.
Expand All @@ -117,5 +132,6 @@ export class FormDateTimePickerComponent implements ControlValueAccessor {
*/
clearDate() {
this.dateInput.reset(undefined);
this.updateSignals();
}
}
florian-glombik marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ import { NgModel } from '@angular/forms';
import { OwlDateTimeModule } from '@danielmoncada/angular-datetime-picker';
import { FormDateTimePickerComponent } from 'app/shared/date-time-picker/date-time-picker.component';
import dayjs from 'dayjs/esm';
import { MockDirective, MockModule } from 'ng-mocks';
import { MockDirective, MockModule, MockPipe } from 'ng-mocks';
import { ArtemisTestModule } from '../../test.module';
import { ArtemisTranslatePipe } from '../../../../../main/webapp/app/shared/pipes/artemis-translate.pipe';
import { NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';

describe('FormDateTimePickerComponent', () => {
let component: FormDateTimePickerComponent;
Expand All @@ -15,7 +17,7 @@ describe('FormDateTimePickerComponent', () => {

beforeEach(() => {
TestBed.configureTestingModule({
imports: [ArtemisTestModule, MockModule(OwlDateTimeModule)],
imports: [ArtemisTestModule, MockModule(OwlDateTimeModule), MockPipe(ArtemisTranslatePipe), MockModule(NgbTooltipModule)],
declarations: [FormDateTimePickerComponent, MockDirective(NgModel)],
})
.compileComponents()
Expand Down Expand Up @@ -62,13 +64,13 @@ describe('FormDateTimePickerComponent', () => {
it('should write the correct date if date is dayjs object', () => {
component.writeValue(normalDate);

expect(component.value).toEqual(normalDateAsDateObject);
expect(component.value()).toEqual(normalDateAsDateObject);
});

it('should write the correct date if date is date object', () => {
component.writeValue(normalDateAsDateObject);

expect(component.value).toEqual(normalDateAsDateObject);
expect(component.value()).toEqual(normalDateAsDateObject);
});
});

Expand All @@ -87,27 +89,30 @@ describe('FormDateTimePickerComponent', () => {
component.registerOnChange(onChangeSpy);
const valueChangedStub = jest.spyOn(component, 'valueChanged').mockImplementation();
const newDate = normalDate.add(2, 'days');
component.value = normalDate;
fixture.componentRef.setInput('value', normalDate);
fixture.detectChanges();

component.updateField(newDate);

expect(component.value).toEqual(newDate);
expect(component.value()).toEqual(newDate);
expect(onChangeSpy).toHaveBeenCalledOnce();
expect(onChangeSpy).toHaveBeenCalledWith(newDate);
expect(valueChangedStub).toHaveBeenCalledOnce();
});

it('should have working getters', () => {
component.min = normalDate;
component.max = normalDate;
component.startAt = normalDate;
const expectedMinDate = normalDate.subtract(2, 'day');
const expectedMaxDate = normalDate.add(2, 'day');
const expectedStartDate = normalDate.add(1, 'day');

fixture.componentRef.setInput('min', expectedMinDate);
fixture.componentRef.setInput('max', expectedMaxDate);
fixture.componentRef.setInput('startAt', expectedStartDate);
const timeZone = component.currentTimeZone;
const minDate = component.minDate;
const maxDate = component.maxDate;
const startDate = component.startDate;

expect(timeZone).toBeDefined();
expect(minDate).toBeDefined();
expect(maxDate).toBeDefined();
expect(startDate).toBeDefined();
expect(dayjs(component.minDate())).toEqual(expectedMinDate);
expect(dayjs(component.maxDate())).toEqual(expectedMaxDate);
expect(dayjs(component.startDate())).toEqual(expectedStartDate);
});
});
Loading