OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub
Ruby agile-developmentangularbcfboardsbug-trackerganttgantt-chartifcissue-trackerjira-alternativekanbanopenprojectproduct-managementproject-managementproject-planningroadmaprubyscrumtimelineworkflows
Don't make any changes except adding the datepickers
Benjamin Bädorf835df8456718
diff --git a/frontend/src/app/core/setup/global-dynamic-components.const.ts b/frontend/src/app/core/setup/global-dynamic-components.const.tsindex dfdca4efbce..e55b716ff4d 100644--- a/frontend/src/app/core/setup/global-dynamic-components.const.ts+++ b/frontend/src/app/core/setup/global-dynamic-components.const.ts@@ -211,6 +211,10 @@ import {OpModalOverlayComponent,opModalOverlaySelector,} from 'core-app/shared/components/modal/modal-overlay.component';+import {+ OpSingleDatePickerComponent,+ opSingleDatePickerSelector,+} from 'core-app/shared/components/datepicker/single-date-picker/single-date-picker.component';import {OpModalSingleDatePickerComponent,opModalSingleDatePickerSelector,@@ -279,6 +283,7 @@ export const globalDynamicComponents:OptionalBootstrapDefinition[] = [{ selector: opModalOverlaySelector, cls: OpModalOverlayComponent },// It is important to initialize the remoteFieldUpdaterSelector after the opModalSingleDatePickerSelector,// because we need to access the input field of the opModalSingleDatePickerSelector inside the remoteFieldUpdaterSelector+ { selector: opSingleDatePickerSelector, cls: OpSingleDatePickerComponent, embeddable: true },{ selector: opModalSingleDatePickerSelector, cls: OpModalSingleDatePickerComponent, embeddable: true },{ selector: opBasicSingleDatePickerSelector, cls: OpBasicSingleDatePickerComponent, embeddable: true },{ selector: remoteFieldUpdaterSelector, cls: RemoteFieldUpdaterComponent },diff --git a/frontend/src/app/features/user-preferences/reminder-settings/pause-reminders/pause-reminders.component.html b/frontend/src/app/features/user-preferences/reminder-settings/pause-reminders/pause-reminders.component.htmlindex 696b5e33c5f..46382eaccc8 100644--- a/frontend/src/app/features/user-preferences/reminder-settings/pause-reminders/pause-reminders.component.html+++ b/frontend/src/app/features/user-preferences/reminder-settings/pause-reminders/pause-reminders.component.html@@ -14,10 +14,10 @@/></spot-selector-field>- <op-basic-range-date-picker+ <op-multi-date-picker*ngIf="(enabled$ | async)"[required]="enabled$ | async"[value]="selectedDates$ | async"(valueChange)="setDates($event)"- ></op-basic-range-date-picker>+ ></op-multi-date-picker></div>diff --git a/frontend/src/app/features/work-packages/components/filters/filter-date-time-value/filter-date-time-value.component.html b/frontend/src/app/features/work-packages/components/filters/filter-date-time-value/filter-date-time-value.component.htmlindex 97e00c37d36..eafcc4c2368 100644--- a/frontend/src/app/features/work-packages/components/filters/filter-date-time-value/filter-date-time-value.component.html+++ b/frontend/src/app/features/work-packages/components/filters/filter-date-time-value/filter-date-time-value.component.html@@ -1,4 +1,4 @@-<op-basic-single-date-picker+<op-single-date-picker[id]="'values-' + filter.id"[name]="'v[' + filter.id + ']'"class="advanced-filters--date-field"@@ -8,7 +8,8 @@[value]="isoDateFormatter(value)"[opAutofocus]="shouldFocus"-></op-basic-single-date-picker>++></op-single-date-picker><spanclass="advanced-filters--tooltip-trigger -multiline"diff --git a/frontend/src/app/features/work-packages/components/filters/filter-date-times-value/filter-date-times-value.component.html b/frontend/src/app/features/work-packages/components/filters/filter-date-times-value/filter-date-times-value.component.htmlindex ee6884b9936..5912f06cf65 100644--- a/frontend/src/app/features/work-packages/components/filters/filter-date-times-value/filter-date-times-value.component.html+++ b/frontend/src/app/features/work-packages/components/filters/filter-date-times-value/filter-date-times-value.component.html@@ -1,25 +1,11 @@-<op-basic-single-date-picker- [ngModel]="isoDateFormatter(begin)"- (ngModelChange)="begin = isoDateParser($event)"- [opAutofocus]="shouldFocus"- required="true"- [id]="'values-' + filter.id + '-begin'"- [name]="'v[' + filter.id + ']-begin'"- classes="advanced-filters--date-field"-></op-basic-single-date-picker>--<span- class="advanced-filters--affix"- [textContent]="text.spacer"-></span>+<op-multi-date-picker+ [id]="'values-' + filter.id"+ [name]="'v[' + filter.id + ']'"+ class="advanced-filters--date-field"-<op-basic-single-date-picker- [ngModel]="isoDateFormatter(end)"- (ngModelChange)="end = isoDateParser($event)"- [id]="'values-' + filter.id + '-end'"- [name]="'v[' + filter.id + ']-end'"- classes="advanced-filters--date-field"-></op-basic-single-date-picker>+ [(ngModel)]="value"+ [opAutofocus]="shouldFocus"+></op-multi-date-picker><spanclass="advanced-filters--tooltip-trigger -multiline"diff --git a/frontend/src/app/features/work-packages/components/filters/filter-date-times-value/filter-date-times-value.component.ts b/frontend/src/app/features/work-packages/components/filters/filter-date-times-value/filter-date-times-value.component.tsindex 9fe4a6af965..859986e555e 100644--- a/frontend/src/app/features/work-packages/components/filters/filter-date-times-value/filter-date-times-value.component.ts+++ b/frontend/src/app/features/work-packages/components/filters/filter-date-times-value/filter-date-times-value.component.ts@@ -70,22 +70,21 @@ export class FilterDateTimesValueComponent extends AbstractDateTimeValueControllsuper(I18n, timezoneService);}- public get begin():HalResource|string {- return this.filter.values[0];+ public get value():(HalResource[]|string[]) {+ return this.filter.values;}- public set begin(val) {- this.filter.values[0] = val || '';+ public set value(val:(HalResource[]|string[])) {+ this.filter.values = val.map(d => this.isoDateParser(d));this.filterChanged.emit(this.filter);}- public get end() {- return this.filter.values[1];+ public get begin() {+ return this.filter.values[0];}- public set end(val) {- this.filter.values[1] = val || '';- this.filterChanged.emit(this.filter);+ public get end() {+ return this.filter.values[1];}public get lowerBoundary():Moment|null {diff --git a/frontend/src/app/shared/components/datepicker/multi-date-picker/multi-date-picker.component.html b/frontend/src/app/shared/components/datepicker/multi-date-picker/multi-date-picker.component.htmlnew file mode 100644index 00000000000..92b7873e6f1--- /dev/null+++ b/frontend/src/app/shared/components/datepicker/multi-date-picker/multi-date-picker.component.html@@ -0,0 +1,118 @@+<spot-drop-modal+ [opened]="opened"+ (closed)="close()"+ data-qa-selector="op-multi-date-picker"+>+ <input+ slot="trigger"+ type="text"+ class="spot-input"+ [attr.data-value]="value"+ [id]="id"+ [value]="datesString"+ (click)="onInputClick($event)"+ (focus)="opened = true"+ />++ <form+ slot="body"+ class="spot-container op-datepicker-modal op-datepicker-modal_wide"+ data-qa-selector="op-datepicker-modal"+ tabindex="0"+ cdkFocusInitial+ cdkTrapFocus+ [cdkTrapFocusAutoCapture]="true"+ (submit)="save($event)"+ >+ <spot-selector-field+ [reverseLabel]="true"+ [label]="text.ignoreNonWorkingDays.title"+ >+ <spot-switch+ slot="input"+ name="ignoreNonWorkingDays"+ [(ngModel)]="ignoreNonWorkingDays"+ (ngModelChange)="changeNonWorkingDays()"+ data-qa-selector="op-datepicker-modal--include-non-working-days"+ ></spot-switch>+ </spot-selector-field>++ <div class="op-datepicker-modal--dates-container">+ <spot-form-field+ [label]="text.startDate"+ >+ <spot-text-field+ slot="input"+ name="startDate"+ class="op-datepicker-modal--date-field"+ [attr.data-qa-highlighted]="showFieldAsActive('start') || undefined"+ [ngClass]="{'op-datepicker-modal--date-field_current' : showFieldAsActive('start')}"+ [ngModel]="dates.start"+ (ngModelChange)="startDateChanged$.next($event)"+ [showClearButton]="currentlyActivatedDateField === 'start'"+ (focusin)="setCurrentActivatedField('start')"+ ></spot-text-field>+ <button+ slot="action"+ type="button"+ class="spot-link"+ (click)="setToday('start')"+ [textContent]="text.today">+ </button>+ </spot-form-field>++ <spot-form-field+ [label]="text.endDate"+ >+ <spot-text-field+ slot="input"+ name="endDate"+ class="op-datepicker-modal--date-field"+ [attr.data-qa-highlighted]="showFieldAsActive('end') || undefined"+ [ngClass]="{'op-datepicker-modal--date-field_current' : showFieldAsActive('end')}"+ [ngModel]="dates.end"+ (ngModelChange)="endDateChanged$.next($event)"+ [showClearButton]="currentlyActivatedDateField === 'end'"+ (focusin)="setCurrentActivatedField('end')"+ ></spot-text-field>+ <button+ slot="action"+ type="button"+ class="spot-link"+ (click)="setToday('end')"+ [textContent]="text.today">+ </button>+ </spot-form-field>+ </div>++ <input+ id="flatpickr-input"+ #flatpickrTarget+ hidden>++ <div class="spot-action-bar">+ <div class="spot-action-bar--right">+ <button+ type="button"+ (click)="close()"+ class="button spot-action-bar--action"+ data-qa-selector="op-datepicker-modal--action"+ [textContent]="text.cancel"+ ></button>+ <button+ type="submit"+ class="button -highlight spot-action-bar--action"+ data-qa-selector="op-datepicker-modal--action"+ [textContent]="applyLabel"+ ></button>+ </div>+ </div>+ </form>+</spot-drop-modal>++<input+ [id]="id"+ [name]="name"+ [value]="value"+ hidden+>diff --git a/frontend/src/app/shared/components/datepicker/multi-date-picker/multi-date-picker.component.ts b/frontend/src/app/shared/components/datepicker/multi-date-picker/multi-date-picker.component.tsnew file mode 100644index 00000000000..2312408a70c--- /dev/null+++ b/frontend/src/app/shared/components/datepicker/multi-date-picker/multi-date-picker.component.ts@@ -0,0 +1,500 @@+// -- copyright+// OpenProject is an open source project management software.+// Copyright (C) 2012-2022 the OpenProject GmbH+//+// This program is free software; you can redistribute it and/or+// modify it under the terms of the GNU General Public License version 3.+//+// OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+// Copyright (C) 2006-2013 Jean-Philippe Lang+// Copyright (C) 2010-2013 the ChiliProject Team+//+// This program is free software; you can redistribute it and/or+// modify it under the terms of the GNU General Public License+// as published by the Free Software Foundation; either version 2+// of the License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+//+// See COPYRIGHT and LICENSE files for more details.+//++++import {+ ChangeDetectionStrategy,+ ChangeDetectorRef,+ Component,+ ElementRef,+ EventEmitter,+ forwardRef,+ HostBinding,+ Injector,+ Input,+ OnInit,+ Output,+ ViewChild,+ ViewEncapsulation,+} from '@angular/core';+import { I18nService } from 'core-app/core/i18n/i18n.service';+import {+ ControlValueAccessor,+ NG_VALUE_ACCESSOR,+} from '@angular/forms';+import {+ areDatesEqual,+ mappedDate,+ onDayCreate,+ parseDate,+ setDates,+ validDate,+} from 'core-app/shared/components/datepicker/helpers/date-modal.helpers';+import { TimezoneService } from 'core-app/core/datetime/timezone.service';+import { DatePicker } from '../datepicker';+import flatpickr from 'flatpickr';+import { DayElement } from 'flatpickr/dist/types/instance';+import {+ ActiveDateChange,+ DateFields,+ DateKeys,+} from '../wp-multi-date-form/wp-multi-date-form.component';+import {+ fromEvent,+ merge,+ Observable,+ Subject,+} from 'rxjs';+import { UntilDestroyedMixin } from 'core-app/shared/helpers/angular/until-destroyed.mixin';+import {+ debounceTime,+ filter,+ map,+} from 'rxjs/operators';+import { DeviceService } from 'core-app/core/browser/device.service';+import { DateOption } from 'flatpickr/dist/types/options';+import { WeekdayService } from 'core-app/core/days/weekday.service';+import { FocusHelperService } from 'core-app/shared/directives/focus/focus-helper';+import { SpotDropModalTeleportationService } from 'core-app/spot/components/drop-modal/drop-modal-teleportation.service';++@Component({+ selector: 'op-multi-date-picker',+ templateUrl: './multi-date-picker.component.html',+ styleUrls: ['../styles/datepicker.modal.sass', '../styles/datepicker_mobile.modal.sass'],+ changeDetection: ChangeDetectionStrategy.OnPush,+ encapsulation: ViewEncapsulation.None,+ providers: [+ {+ provide: NG_VALUE_ACCESSOR,+ useExisting: forwardRef(() => OpMultiDatePickerComponent),+ multi: true,+ },+ ],+})+export class OpMultiDatePickerComponent extends UntilDestroyedMixin implements OnInit, ControlValueAccessor {+ @ViewChild('modalContainer') modalContainer:ElementRef<HTMLElement>;++ @ViewChild('flatpickrTarget') flatpickrTarget:ElementRef;++ @Input() id = `flatpickr-input-${+(new Date())}`;++ @Input() name = '';++ @Input() fieldName:string = '';++ @Input() value:string[] = [];++ @Input() applyLabel:string;++ private _opened = false;++ @Input() set opened(opened:boolean) {+ if (this._opened === !!opened) {+ return;+ }++ this._opened = !!opened;++ if (this._opened) {+ this.initializeDatepickerAfterOpen();+ } else {+ this.datePickerInstance?.destroy();+ this.closed.emit();+ }+ }++ get opened() {+ return this._opened;+ }++ @Output() valueChange = new EventEmitter();++ @Output('closed') closed = new EventEmitter();++ text = {+ apply: this.I18n.t('js.modals.button_apply'),+ cancel: this.I18n.t('js.button_cancel'),+ startDate: this.I18n.t('js.work_packages.properties.startDate'),+ endDate: this.I18n.t('js.work_packages.properties.dueDate'),+ placeholder: this.I18n.t('js.placeholders.default'),+ today: this.I18n.t('js.label_today'),+ days: (count:number):string => this.I18n.t('js.units.day', { count }),+ ignoreNonWorkingDays: {+ title: this.I18n.t('js.work_packages.datepicker_modal.ignore_non_working_days.title'),+ },+ };++ get datesString():string {+ if (this.value?.[0] && this.value?.[1]) {+ return `${this.value[0]} - ${this.value[1]}`;+ }++ return this.text.placeholder;+ }++ ignoreNonWorkingDays = false;++ currentlyActivatedDateField:DateFields;++ htmlId = '';++ dates:{ [key in DateKeys]:string|null } = {+ start: null,+ end: null,+ };++ // Manual changes from the inputs to start and end dates+ startDateChanged$ = new Subject<string>();++ startDateDebounced$:Observable<ActiveDateChange> = this.debouncedInput(this.startDateChanged$, 'start');++ endDateChanged$ = new Subject<string>();++ endDateDebounced$:Observable<ActiveDateChange> = this.debouncedInput(this.endDateChanged$, 'end');++ // Manual changes to the datepicker, with information which field was active+ datepickerChanged$ = new Subject<ActiveDateChange>();++ ignoreNonWorkingDaysWritable = true;++ private datePickerInstance:DatePicker;++ constructor(+ readonly injector:Injector,+ readonly cdRef:ChangeDetectorRef,+ readonly I18n:I18nService,+ readonly timezoneService:TimezoneService,+ readonly deviceService:DeviceService,+ readonly weekdayService:WeekdayService,+ readonly focusHelper:FocusHelperService,+ readonly spotDropModalTeleportationService:SpotDropModalTeleportationService,+ ) {+ super();++ merge(+ this.startDateDebounced$,+ this.endDateDebounced$,+ this.datepickerChanged$,+ )+ .pipe(+ this.untilDestroyed(),+ filter(() => !!this.datePickerInstance),+ )+ .subscribe(([field, update]) => {+ // When clearing the one date, clear the others as well+ if (update !== null) {+ this.handleSingleDateUpdate(field, update);+ }++ this.cdRef.detectChanges();+ });+ }++ ngOnInit():void {+ this.applyLabel = this.applyLabel || this.text.apply;+ this.htmlId = `wp-datepicker-${this.fieldName as string}`;++ this.setCurrentActivatedField(this.initialActivatedField);+ }++ onInputClick(event:MouseEvent) {+ event.stopPropagation();+ }++ close():void {+ this.opened = false;+ }++ changeNonWorkingDays():void {+ this.initializeDatepicker();+ this.cdRef.detectChanges();+ }++ save($event:Event):void {+ $event.preventDefault();+ const value = [+ this.dates.start || '',+ this.dates.end || '',+ ];+ this.value = value;+ this.valueChange.emit(value);+ this.onChange(value);+ this.close();+ }++ updateDate(key:DateKeys, val:string|null):void {+ if ((val === null || validDate(val)) && this.datePickerInstance) {+ this.dates[key] = mappedDate(val);+ const dateValue = parseDate(val || '') || undefined;+ this.enforceManualChangesToDatepicker(dateValue);+ this.cdRef.detectChanges();+ }+ }++ setCurrentActivatedField(val:DateFields):void {+ this.currentlyActivatedDateField = val;+ }++ toggleCurrentActivatedField():void {+ this.currentlyActivatedDateField = this.currentlyActivatedDateField === 'start' ? 'end' : 'start';+ }++ isStateOfCurrentActivatedField(val:DateFields):boolean {+ return this.currentlyActivatedDateField === val;+ }++ setToday(key:DateKeys):void {+ this.datepickerChanged$.next([key, new Date()]);++ const nextActive = key === 'start' ? 'end' : 'start';+ this.setCurrentActivatedField(nextActive);+ }++ showFieldAsActive(field:DateFields):boolean {+ return this.isStateOfCurrentActivatedField(field);+ }++ private initializeDatepickerAfterOpen():void {+ this.spotDropModalTeleportationService+ .afterRenderOnce$(true)+ .subscribe(() => {+ this.initializeDatepicker();+ });+ }++ private initializeDatepicker(minimalDate?:Date|null) {+ this.datePickerInstance?.destroy();+ this.datePickerInstance = new DatePicker(+ this.injector,+ this.id,+ [this.dates.start || '', this.dates.end || ''],+ {+ mode: 'range',+ showMonths: this.deviceService.isMobile ? 1 : 2,+ inline: true,+ onReady: (_date, _datestr, instance) => {+ instance.calendarContainer.classList.add('op-datepicker-modal--flatpickr-instance');++ this.ensureHoveredSelection(instance.calendarContainer);+ },+ onChange: (dates:Date[], _datestr, instance) => {+ this.onTouched();++ if (dates.length === 2) {+ this.setDates(dates[0], dates[1]);+ this.toggleCurrentActivatedField();+ this.cdRef.detectChanges();+ return;+ }++ // Update with the same flow as entering a value+ const { latestSelectedDateObj } = instance as { latestSelectedDateObj:Date };+ const activeField = this.currentlyActivatedDateField;+ this.handleSingleDateUpdate(activeField, latestSelectedDateObj);+ this.cdRef.detectChanges();+ },+ onDayCreate: (dObj:Date[], dStr:string, fp:flatpickr.Instance, dayElem:DayElement) => {+ onDayCreate(+ dayElem,+ this.ignoreNonWorkingDays,+ this.weekdayService.isNonWorkingDay(dayElem.dateObj),+ this.isDayDisabled(dayElem, minimalDate),+ );+ },+ },+ this.flatpickrTarget.nativeElement,+ );+ }++ private enforceManualChangesToDatepicker(enforceDate?:Date) {+ let startDate = parseDate(this.dates.start || '');+ let endDate = parseDate(this.dates.end || '');++ if (startDate && endDate) {+ // If the start date is manually changed to be after the end date,+ // we adjust the end date to be at least the same as the newly entered start date.+ // Same applies if the end date is set manually before the current start date+ if (startDate > endDate && this.isStateOfCurrentActivatedField('start')) {+ endDate = startDate;+ this.dates.end = this.timezoneService.formattedISODate(endDate);+ } else if (endDate < startDate && this.isStateOfCurrentActivatedField('end')) {+ startDate = endDate;+ this.dates.start = this.timezoneService.formattedISODate(startDate);+ }+ }++ const dates = [startDate, endDate];+ setDates(dates, this.datePickerInstance, enforceDate);+ }++ private setDates(newStart:Date, newEnd:Date) {+ this.dates.start = this.timezoneService.formattedISODate(newStart);+ this.dates.end = this.timezoneService.formattedISODate(newEnd);+ }++ private handleSingleDateUpdate(activeField:DateFields, selectedDate:Date) {+ if (activeField === 'duration') {+ return;+ }++ this.replaceDatesWithNewSelection(activeField, selectedDate);++ // Set the selected date on the datepicker+ this.enforceManualChangesToDatepicker(selectedDate);+ }++ private replaceDatesWithNewSelection(activeField:DateFields, selectedDate:Date) {+ /**+ Overwrite flatpickr default behavior by not starting a new date range everytime but preserving either start or end date.+ There are three cases to cover.+ 1. Everything before the current start date will become the new start date (independent of the active field)+ 2. Everything after the current end date will become the new end date if that is the currently active field.+ If the active field is the start date, the selected date becomes the new start date and the end date is cleared.+ 3. Everything in between the current start and end date is dependent on the currently activated field.+ * */++ const parsedStartDate = parseDate(this.dates.start || '') as Date;+ const parsedEndDate = parseDate(this.dates.end || '') as Date;++ if (selectedDate < parsedStartDate) {+ if (activeField === 'start') {+ // Set start, derive end from+ this.applyNewDates([selectedDate]);+ } else {+ // Reset and end date+ this.applyNewDates(['', selectedDate]);+ }+ } else if (selectedDate > parsedEndDate) {+ if (activeField === 'end') {+ this.applyNewDates([parsedStartDate, selectedDate]);+ } else {+ // Reset and end date+ this.applyNewDates([selectedDate]);+ }+ } else if (areDatesEqual(selectedDate, parsedStartDate) || areDatesEqual(selectedDate, parsedEndDate)) {+ this.applyNewDates([selectedDate, selectedDate]);+ } else {+ const newDates = activeField === 'start' ? [selectedDate, parsedEndDate] : [parsedStartDate, selectedDate];+ this.applyNewDates(newDates);+ }+ }++ private applyNewDates([start, end]:DateOption[]) {+ this.dates.start = start ? this.timezoneService.formattedISODate(start) : null;+ this.dates.end = end ? this.timezoneService.formattedISODate(end) : null;++ // Apply the dates to the datepicker+ setDates([start, end], this.datePickerInstance);+ }++ private get initialActivatedField():DateFields {+ switch (this.fieldName) {+ case 'startDate':+ return 'start';+ case 'dueDate':+ return 'end';+ case 'duration':+ return 'duration';+ default:+ return (this.dates.start && !this.dates.end) ? 'end' : 'start';+ }+ }++ private isDayDisabled(dayElement:DayElement, minimalDate?:Date|null):boolean {+ return !!minimalDate && dayElement.dateObj <= minimalDate;+ }++ private debouncedInput(input$:Subject<string>, key:DateKeys):Observable<ActiveDateChange> {+ return input$+ .pipe(+ this.untilDestroyed(),+ // Skip values that are already set as the current model+ filter((value) => value !== this.dates[key]),+ // Avoid that the manual changes are moved to the datepicker too early.+ // The debounce is chosen quite large on purpose to catch the following case:+ // 1. Start date is for example 2022-07-15. The user wants to set the end date to the 19th.+ // 2. So he/she starts entering the finish date 2022-07-1 .+ // 3. This is already a valid date. Since it is before the start date,the start date would be changed automatically to the first without the debounce.+ // 4. The debounce gives the user enough time to type the last number "9" before the changes are converted to the datepicker and the start date would be affected.+ debounceTime(500),+ filter((date) => validDate(date)),+ map((date) => {+ if (date === '') {+ return null;+ }++ return parseDate(date) as Date;+ }),+ map((date) => [key, date]),+ );+ }++ /**+ * When hovering selections in the range datepicker, the range usually+ * stays active no matter where the cursor is.+ *+ * We want to hide any hovered selection preview when we leave the datepicker.+ * @param calendarContainer+ * @private+ */+ private ensureHoveredSelection(calendarContainer:HTMLDivElement) {+ fromEvent(calendarContainer, 'mouseenter')+ .pipe(+ this.untilDestroyed(),+ )+ .subscribe(() => calendarContainer.classList.remove('flatpickr-container-suppress-hover'));++ fromEvent(calendarContainer, 'mouseleave')+ .pipe(+ this.untilDestroyed(),+ filter(() => !(!!this.dates.start && !!this.dates.end)),+ )+ .subscribe(() => calendarContainer.classList.add('flatpickr-container-suppress-hover'));+ }++ writeValue(newValue:string[]|null):void {+ const value = (newValue || []).map(d => this.timezoneService.formattedISODate(d));+ if (value[0] === this.dates.start && value[1] === this.dates.end) {+ return;+ }+ this.value = value;+ this.dates.start = this.value[0];+ this.dates.end = this.value[1];+ }++ onChange = (_:string[]):void => {};++ onTouched = ():void => {};++ registerOnChange(fn:(_:string[]) => void):void {+ this.onChange = fn;+ }++ registerOnTouched(fn:() => void):void {+ this.onTouched = fn;+ }+}diff --git a/frontend/src/app/shared/components/datepicker/single-date-picker/single-date-picker.component.html b/frontend/src/app/shared/components/datepicker/single-date-picker/single-date-picker.component.htmlnew file mode 100644index 00000000000..8a09c09a78a--- /dev/null+++ b/frontend/src/app/shared/components/datepicker/single-date-picker/single-date-picker.component.html@@ -0,0 +1,100 @@+<spot-drop-modal+ [opened]="opened"+ (closed)="opened = false"+ data-qa-selector="op-single-date-picker"+>+ <ng-content+ slot="trigger"+ select="[slot=trigger]"+ ></ng-content>+ <ng-template [ngIf]="useDefaultTrigger" slot="trigger">+ <input+ type="text"+ class="spot-input"+ [attr.data-value]="value"+ [id]="id"+ [(ngModel)]="value"+ (ngModelChange)="changeValueFromInputDebounced($event)"+ (click)="onInputClick($event)"+ (focus)="opened = true"+ />+ </ng-template>++ <ng-container slot="body">+ <form+ class="spot-container op-datepicker-modal"+ data-qa-selector="op-datepicker-modal"+ tabindex="0"+ cdkFocusInitial+ cdkTrapFocus+ [cdkTrapFocusAutoCapture]="true"+ (submit)="save($event)"+ >+ <spot-selector-field+ *ngIf="showIgnoreNonWorkingDays"+ [reverseLabel]="true"+ [label]="text.ignoreNonWorkingDays.title"+ >+ <spot-switch+ slot="input"+ name="ignoreNonWorkingDays"+ [(ngModel)]="ignoreNonWorkingDays"+ (ngModelChange)="changeNonWorkingDays()"+ data-qa-selector="op-datepicker-modal--include-non-working-days"+ ></spot-switch>+ </spot-selector-field>++ <ng-content select="[slot=extra-fields]"></ng-content>++ <spot-form-field+ [label]="text.date"+ [required]="required"+ >+ <spot-text-field+ slot="input"+ name="date"+ class="op-datepicker-modal--date-field"+ [ngModel]="workingValue"+ [required]="required"+ (ngModelChange)="writeWorkingValue($event)"+ [showClearButton]="true"+ ></spot-text-field>+ <button+ slot="action"+ type="button"+ class="spot-link"+ (click)="setToday()"+ [textContent]="text.today">+ </button>+ </spot-form-field>++ <div #flatpickrTarget></div>++ <div class="spot-action-bar">+ <div class="spot-action-bar--right">+ <button+ type="button"+ (click)="opened = false"+ class="button spot-action-bar--action"+ data-qa-selector="op-datepicker-modal--action"+ [textContent]="text.cancel"+ ></button>+ <button+ type="submit"+ class="button -highlight spot-action-bar--action"+ data-qa-selector="op-datepicker-modal--action"+ [textContent]="applyLabel"+ ></button>+ </div>+ </div>+ </form>+ </ng-container>+</spot-drop-modal>++<input+ [name]="name"+ [value]="value"+ [ngClass]="{ 'remote-field--input': !!remoteFieldKey }"+ [attr.data-remote-field-key]="remoteFieldKey"+ hidden+>diff --git a/frontend/src/app/shared/components/datepicker/single-date-picker/single-date-picker.component.ts b/frontend/src/app/shared/components/datepicker/single-date-picker/single-date-picker.component.tsnew file mode 100644index 00000000000..31441990b05--- /dev/null+++ b/frontend/src/app/shared/components/datepicker/single-date-picker/single-date-picker.component.ts@@ -0,0 +1,293 @@+// -- copyright+// OpenProject is an open source project management software.+// Copyright (C) 2012-2022 the OpenProject GmbH+//+// This program is free software; you can redistribute it and/or+// modify it under the terms of the GNU General Public License version 3.+//+// OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+// Copyright (C) 2006-2013 Jean-Philippe Lang+// Copyright (C) 2010-2013 the ChiliProject Team+//+// This program is free software; you can redistribute it and/or+// modify it under the terms of the GNU General Public License+// as published by the Free Software Foundation; either version 2+// of the License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU General Public License for more details.+//+// You should have received a copy of the GNU General Public License+// along with this program; if not, write to the Free Software+// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+//+// See COPYRIGHT and LICENSE files for more details.+//++++import {+ AfterContentInit,+ ChangeDetectionStrategy,+ ChangeDetectorRef,+ Component,+ ElementRef,+ EventEmitter,+ forwardRef,+ Injector,+ Input,+ OnInit,+ Output,+ ViewChild,+ ViewEncapsulation,+} from '@angular/core';+import { I18nService } from 'core-app/core/i18n/i18n.service';+import {+ ControlValueAccessor,+ NG_VALUE_ACCESSOR,+} from '@angular/forms';+import {+ onDayCreate,+ parseDate,+ setDates,+} from 'core-app/shared/components/datepicker/helpers/date-modal.helpers';+import { TimezoneService } from 'core-app/core/datetime/timezone.service';+import { DatePicker } from '../datepicker';+import flatpickr from 'flatpickr';+import { DayElement } from 'flatpickr/dist/types/instance';+import { populateInputsFromDataset } from '../../dataset-inputs';+import { debounce } from 'lodash';+import { SpotDropModalTeleportationService } from 'core-app/spot/components/drop-modal/drop-modal-teleportation.service';++export const opSingleDatePickerSelector = 'op-single-date-picker';++@Component({+ selector: opSingleDatePickerSelector,+ templateUrl: './single-date-picker.component.html',+ styleUrls: ['../styles/datepicker.modal.sass', '../styles/datepicker_mobile.modal.sass'],+ changeDetection: ChangeDetectionStrategy.OnPush,+ encapsulation: ViewEncapsulation.None,+ providers: [+ {+ provide: NG_VALUE_ACCESSOR,+ useExisting: forwardRef(() => OpSingleDatePickerComponent),+ multi: true,+ },+ ],+})+export class OpSingleDatePickerComponent implements ControlValueAccessor, OnInit, AfterContentInit {+ @Output('closed') closed = new EventEmitter();++ @Output('valueChange') valueChange = new EventEmitter();++ private _value = '';++ @Input() set value(newValue:string) {+ this._value = newValue;+ this.writeWorkingValue(newValue);+ }++ get value() {+ return this._value;+ }++ @Input() id = `flatpickr-input-${+(new Date())}`;++ @Input() name = '';++ @Input() remoteFieldKey = '';++ @Input() required = false;++ @Input() minimalDate:Date|null = null;++ @Input() applyLabel:string;++ private _opened = false;++ @Input() set opened(opened:boolean) {+ if (this._opened === !!opened) {+ return;+ }++ this._opened = !!opened;++ if (this._opened) {+ this.initializeDatepickerAfterOpen();+ } else {+ this.closed.emit();+ }+ }++ get opened() {+ return this._opened;+ }++ @Input() showIgnoreNonWorkingDays = false;++ @Input() ignoreNonWorkingDays = false;++ @ViewChild('flatpickrTarget') flatpickrTarget:ElementRef;++ public workingValue = '';++ public workingDate:Date|null = null;++ public datePickerInstance:DatePicker;++ public useDefaultTrigger = false;++ text = {+ apply: this.I18n.t('js.modals.button_apply'),+ cancel: this.I18n.t('js.button_cancel'),+ date: this.I18n.t('js.work_packages.properties.date'),+ placeholder: this.I18n.t('js.placeholders.default'),+ today: this.I18n.t('js.label_today'),+ ignoreNonWorkingDays: {+ title: this.I18n.t('js.work_packages.datepicker_modal.ignore_non_working_days.title'),+ },+ };++ constructor(+ readonly I18n:I18nService,+ readonly timezoneService:TimezoneService,+ readonly injector:Injector,+ readonly cdRef:ChangeDetectorRef,+ readonly elementRef:ElementRef,+ readonly spotDropModalTeleportationService:SpotDropModalTeleportationService,+ ) {+ populateInputsFromDataset(this);+ }++ ngOnInit() {+ this.applyLabel = this.applyLabel || this.text.apply;+ }++ ngAfterContentInit() {+ const trigger = (this.elementRef.nativeElement as HTMLElement).querySelector("[slot='trigger']");+ this.useDefaultTrigger = trigger === null;+ }++ onInputClick(event:MouseEvent) {+ event.stopPropagation();+ }++ save($event:Event) {+ const form = $event.target as HTMLFormElement;++ if (form.reportValidity()) {+ $event.preventDefault();+ this.valueChange.emit(this.workingValue);+ this.onChange(this.workingValue);+ this.writeValue(this.workingValue);+ this.opened = false;+ this.workingValue = '';+ this.cdRef.detectChanges();+ }+ }++ setToday():void {+ const today = parseDate(new Date()) as Date;+ this.writeWorkingValue(this.timezoneService.formattedISODate(today));+ this.enforceManualChangesToDatepicker(today);+ }++ changeNonWorkingDays():void {+ this.initializeDatepickerAfterOpen();+ this.cdRef.detectChanges();+ }++ changeValueFromInputDebounced = debounce(this.changeValueFromInput.bind(this), 16);++ changeValueFromInput(value:string) {+ this.valueChange.emit(value);+ this.onChange(value);+ this.writeValue(value);++ const date = parseDate(value || '');++ if (date !== '') {+ const dateString = this.timezoneService.formattedISODate(date);+ this.writeWorkingValue(dateString);+ this.enforceManualChangesToDatepicker(date);+ this.onTouched(dateString);+ }+ this.cdRef.detectChanges();+ }++ private enforceManualChangesToDatepicker(enforceDate?:Date) {+ const date = parseDate(this.workingDate || '');+ setDates(date, this.datePickerInstance, enforceDate);+ }++ private initializeDatepickerAfterOpen():void {+ this.spotDropModalTeleportationService+ .afterRenderOnce$(true)+ .subscribe(() => {+ this.initializeDatepicker();+ });+ }++ private initializeDatepicker() {+ this.datePickerInstance?.destroy();++ // Initialize the working values.+ const initialDate = parseDate(this.value || new Date()) as Date;+ this.writeWorkingValue(this.timezoneService.formattedISODate(initialDate));++ this.datePickerInstance = new DatePicker(+ this.injector,+ this.id,+ this.workingDate || '',+ {+ mode: 'single',+ showMonths: 1,+ inline: true,+ onReady: (_date:Date[], _datestr:string, instance:flatpickr.Instance) => {+ instance.calendarContainer.classList.add('op-datepicker-modal--flatpickr-instance');+ },+ onChange: (dates:Date[]) => {+ if (dates.length > 0) {+ const dateString = this.timezoneService.formattedISODate(dates[0]);+ this.writeWorkingValue(dateString);+ this.enforceManualChangesToDatepicker(dates[0]);+ this.onTouched(dateString);+ }++ this.cdRef.detectChanges();+ },+ onDayCreate: (dObj:Date[], dStr:string, fp:flatpickr.Instance, dayElem:DayElement) => {+ onDayCreate(+ dayElem,+ !this.ignoreNonWorkingDays,+ this.datePickerInstance?.weekdaysService.isNonWorkingDay(dayElem.dateObj),+ !!this.minimalDate && dayElem.dateObj <= this.minimalDate,+ );+ },+ },+ this.flatpickrTarget.nativeElement as HTMLElement,+ );+ }++ writeWorkingValue(value:string):void {+ this.workingValue = value;+ this.workingDate = new Date(value);+ }++ writeValue(value:string):void {+ this.writeWorkingValue(value);+ this.value = value;+ }++ onChange = (_:string):void => {};++ onTouched = (_:string):void => {};++ registerOnChange(fn:(_:string) => void):void {+ this.onChange = fn;+ }++ registerOnTouched(fn:(_:string) => void):void {+ this.onTouched = fn;+ }+}diff --git a/frontend/src/app/shared/components/fields/edit/field-types/date-edit-field/date-edit-field.component.ts b/frontend/src/app/shared/components/fields/edit/field-types/date-edit-field/date-edit-field.component.tsindex b73a2e9ce58..1f8224a6d8a 100644--- a/frontend/src/app/shared/components/fields/edit/field-types/date-edit-field/date-edit-field.component.ts+++ b/frontend/src/app/shared/components/fields/edit/field-types/date-edit-field/date-edit-field.component.ts@@ -34,25 +34,25 @@ import { TimezoneService } from 'core-app/core/datetime/timezone.service';@Component({template: `- <op-basic-single-date-picker+ <op-single-date-picker[(ngModel)]="value"[id]="handler.htmlId"class="inline-edit--field"+ [opened]="opened"(closed)="onModalClosed()"- [opAutofocus]="autofocus"- ></op-basic-single-date-picker>+ ></op-single-date-picker>`,changeDetection: ChangeDetectionStrategy.OnPush,})export class DateEditFieldComponent extends EditFieldComponent implements OnInit {@InjectField() readonly timezoneService:TimezoneService;- autofocus = false;+ opened = false;ngOnInit():void {super.ngOnInit();// Open the datepicker when the field is not part of an editing form.- this.autofocus = !this.handler.inEditMode;+ this.opened = !this.handler.inEditMode;}public get value() {@@ -78,6 +78,8 @@ export class DateEditFieldComponent extends EditFieldComponent implements OnInit}public onModalClosed():void {+ this.opened = false;+if (!this.handler.inEditMode) {this.handler.deactivate(false);}diff --git a/frontend/src/app/shared/components/op-non-working-days-list/op-non-working-days-list.component.html b/frontend/src/app/shared/components/op-non-working-days-list/op-non-working-days-list.component.htmlindex acd7caeec96..b97b5d1b354 100644--- a/frontend/src/app/shared/components/op-non-working-days-list/op-non-working-days-list.component.html+++ b/frontend/src/app/shared/components/op-non-working-days-list/op-non-working-days-list.component.html@@ -19,7 +19,7 @@<divclass="op-non-working-days-list--add-button">- <op-modal-single-date-picker+ <op-single-date-pickerid="test"name="test"[showIgnoreNonWorkingDays]="false"@@ -54,6 +54,6 @@<span class="spot-icon spot-icon_add"></span><span [textContent]="text.add_non_working_day"></span></button>- </op-modal-single-date-picker>+ </op-single-date-picker></div>diff --git a/frontend/src/app/shared/shared.module.ts b/frontend/src/app/shared/shared.module.tsindex 467d727f492..93b4199c07c 100644--- a/frontend/src/app/shared/shared.module.ts+++ b/frontend/src/app/shared/shared.module.ts@@ -78,6 +78,10 @@ import { OpDatePickerBannerComponent } from 'core-app/shared/components/datepickimport { OpDatePickerWorkingDaysToggleComponent } from 'core-app/shared/components/datepicker/toggle/datepicker-working-days-toggle.component';import { OpDatePickerSchedulingToggleComponent } from 'core-app/shared/components/datepicker/scheduling-mode/datepicker-scheduling-toggle.component';+// Old datepickers+import { OpSingleDatePickerComponent } from 'core-app/shared/components/datepicker/single-date-picker/single-date-picker.component';+import { OpMultiDatePickerComponent } from 'core-app/shared/components/datepicker/multi-date-picker/multi-date-picker.component';+import { ToastsContainerComponent } from './components/toaster/toasts-container.component';import { UploadProgressComponent } from './components/toaster/upload-progress.component';import { ResizerComponent } from './components/resizer/resizer.component';@@ -218,6 +222,10 @@ export function bootstrapModule(injector:Injector):void {OpWpMultiDateFormComponent,OpDatePickerWorkingDaysToggleComponent,OpDatePickerSchedulingToggleComponent,++ // Old datepickers+ OpSingleDatePickerComponent,+ OpMultiDatePickerComponent,OpNonWorkingDaysListComponent,],@@ -286,6 +294,10 @@ export function bootstrapModule(injector:Injector):void {OpWpMultiDateFormComponent,OpDatePickerWorkingDaysToggleComponent,OpDatePickerSchedulingToggleComponent,++ // Old datepickers+ OpSingleDatePickerComponent,+ OpMultiDatePickerComponent,],})export class OpSharedModule {