Skip to content

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

Move doubled code to a separate service

Henriette Darge70e1a18b670e
diff --git a/frontend/src/app/features/team-planner/team-planner/planner/team-planner.component.html b/frontend/src/app/features/team-planner/team-planner/planner/team-planner.component.html
index eb1273726ff..0d9fd430100 100644
--- a/frontend/src/app/features/team-planner/team-planner/planner/team-planner.component.html
+++ b/frontend/src/app/features/team-planner/team-planner/planner/team-planner.component.html
@@ -6,6 +6,10 @@
*ngIf="calendarOptions"
[options]="calendarOptions"
></full-calendar>
+ <div
+ *ngIf="static"
+ [textContent]="calendar.tooManyResultsText"
+ class="op-wp-calendar--notification"></div>
</ng-container>
<ng-template #resourceContent let-resource="resource">
<op-principal
diff --git a/frontend/src/app/features/team-planner/team-planner/planner/team-planner.component.ts b/frontend/src/app/features/team-planner/team-planner/planner/team-planner.component.ts
index 3c0a79a2dbf..c348ff2f3a7 100644
--- a/frontend/src/app/features/team-planner/team-planner/planner/team-planner.component.ts
+++ b/frontend/src/app/features/team-planner/team-planner/planner/team-planner.component.ts
@@ -26,24 +26,15 @@ import { WorkPackagesListChecksumService } from 'core-app/features/work-packages
import { SchemaCacheService } from 'core-app/core/schemas/schema-cache.service';
import { CurrentProjectService } from 'core-app/core/current-project/current-project.service';
import { OpTitleService } from 'core-app/core/html/op-title.service';
-import {
- Observable,
- Subject,
-} from 'rxjs';
-import { take } from 'rxjs/internal/operators/take';
+import { Subject } from 'rxjs';
import { WorkPackageResource } from 'core-app/features/hal/resources/work-package-resource';
import { HalResource } from 'core-app/features/hal/resources/hal-resource';
import { UntilDestroyedMixin } from 'core-app/shared/helpers/angular/until-destroyed.mixin';
-import { EventClickArg } from '@fullcalendar/common';
-import { splitViewRoute } from 'core-app/features/work-packages/routing/split-view-routes.helper';
-import { HalEventsService } from 'core-app/features/hal/services/hal-events.service';
-import {
- debounceTime,
- map,
-} from 'rxjs/operators';
+import { debounceTime } from 'rxjs/operators';
import { APIV3Service } from 'core-app/core/apiv3/api-v3.service';
-import { CollectionResource } from 'core-app/features/hal/resources/collection-resource';
import { ResourceLabelContentArg } from '@fullcalendar/resource-common';
+import { OpCalendarService } from 'core-app/shared/components/calendar/op-calendar.service';
+import { WorkPackageCollectionResource } from 'core-app/features/hal/resources/wp-collection-resource';
@Component({
selector: 'op-team-planner',
@@ -52,6 +43,7 @@ import { ResourceLabelContentArg } from '@fullcalendar/resource-common';
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [
EventViewLookupService,
+ OpCalendarService,
],
})
export class TeamPlannerComponent extends UntilDestroyedMixin implements OnInit, OnDestroy {
@@ -59,26 +51,14 @@ export class TeamPlannerComponent extends UntilDestroyedMixin implements OnInit,
@ViewChild('ucCalendar', { read: ElementRef })
set ucCalendarElement(v:ElementRef|undefined) {
- if (!v) {
- return;
- }
-
- if (!this.resizeObserver) {
- this.resizeObserver = new ResizeObserver(() => this.resizeSubject.next());
- }
-
- this.resizeObserver.observe(v.nativeElement);
+ this.calendar.resizeObserver(v);
}
@ViewChild('resourceContent') resourceContent:TemplateRef<unknown>;
calendarOptions$ = new Subject<CalendarOptions>();
- projectIdentifier:string|null = null;
-
- private resizeObserver:ResizeObserver;
-
- private resizeSubject = new Subject<unknown>();
+ projectIdentifier:string|undefined = undefined;
text = {
assignees: this.I18n.t('js.team_planner.label_assignee_plural'),
@@ -100,7 +80,7 @@ export class TeamPlannerComponent extends UntilDestroyedMixin implements OnInit,
private titleService:OpTitleService,
private viewLookup:EventViewLookupService,
private I18n:I18nService,
- private halEvents:HalEventsService,
+ readonly calendar:OpCalendarService,
) {
super();
}
@@ -108,9 +88,9 @@ export class TeamPlannerComponent extends UntilDestroyedMixin implements OnInit,
ngOnInit():void {
this.setupWorkPackagesListener();
this.initializeCalendar();
- this.projectIdentifier = this.currentProject.identifier;
+ this.projectIdentifier = this.currentProject.identifier ? this.currentProject.identifier : undefined;
- this.resizeSubject
+ this.calendar.resize$
.pipe(
this.untilDestroyed(),
debounceTime(50),
@@ -122,7 +102,7 @@ export class TeamPlannerComponent extends UntilDestroyedMixin implements OnInit,
ngOnDestroy():void {
super.ngOnDestroy();
- this.resizeObserver?.disconnect();
+ this.calendar.resizeObs?.disconnect();
}
public calendarResourcesFunction(
@@ -131,10 +111,11 @@ export class TeamPlannerComponent extends UntilDestroyedMixin implements OnInit,
failureCallback:(error:unknown) => void,
):void|PromiseLike<EventInput[]> {
this
- .currentWorkPackages()
+ .calendar
+ .currentWorkPackages$
.toPromise()
- .then((workPackages) => {
- const resources = this.mapToCalendarResources(workPackages);
+ .then((workPackages:WorkPackageCollectionResource) => {
+ const resources = this.mapToCalendarResources(workPackages.elements);
successCallback(resources);
})
.catch(failureCallback);
@@ -146,82 +127,58 @@ export class TeamPlannerComponent extends UntilDestroyedMixin implements OnInit,
failureCallback:(error:unknown) => void,
):void|PromiseLike<EventInput[]> {
this
- .currentWorkPackages()
+ .calendar
+ .currentWorkPackages$
.toPromise()
- .then((workPackages) => {
- const events = this.mapToCalendarEvents(workPackages);
+ .then((workPackages:WorkPackageCollectionResource) => {
+ const events = this.mapToCalendarEvents(workPackages.elements);
successCallback(events);
})
.catch(failureCallback);
- this.updateTimeframe(fetchInfo);
- }
-
- private currentWorkPackages():Observable<WorkPackageResource[]> {
- return this
- .querySpace
- .results
- .values$()
- .pipe(
- take(1),
- map((collection:CollectionResource<WorkPackageResource>) => (
- collection
- .elements
- .map((wp) => this.apiV3Service.work_packages.cache.current(wp.id as string, wp) as WorkPackageResource)
- )),
- );
+ this.calendar.updateTimeframe(fetchInfo, this.projectIdentifier);
}
private initializeCalendar() {
void this.configuration.initialized
.then(() => {
- this.calendarOptions$.next({
- schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source',
- editable: false,
- locale: this.I18n.locale,
- fixedWeekCount: false,
- firstDay: this.configuration.startOfWeek(),
- timeZone: this.configuration.isTimezoneSet() ? this.configuration.timezone() : 'local',
- plugins: [
- resourceTimelinePlugin,
- ],
- headerToolbar: {
- left: 'prev,next today',
- center: 'title',
- right: '',
- },
- titleFormat: {
- year: 'numeric',
- month: 'long',
- day: 'numeric',
- },
- initialView: 'resourceTimelineWeekDaysOnly',
- height: 'auto',
- views: {
- resourceTimelineWeekDaysOnly: {
- type: 'resourceTimeline',
- duration: { weeks: 1 },
- slotDuration: { days: 1 },
- slotLabelFormat: [
- {
- weekday: 'long',
- day: '2-digit',
- },
- ],
- resourceAreaColumns: [
- {
- field: 'title',
- headerContent: this.text.assignees,
- },
- ],
+ this.calendarOptions$.next(
+ this.calendar.calendarOptions({
+ schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source',
+ plugins: [
+ resourceTimelinePlugin,
+ ],
+ titleFormat: {
+ year: 'numeric',
+ month: 'long',
+ day: 'numeric',
+ },
+ initialView: 'resourceTimelineWeekDaysOnly',
+ views: {
+ resourceTimelineWeekDaysOnly: {
+ type: 'resourceTimeline',
+ duration: { weeks: 1 },
+ slotDuration: { days: 1 },
+ slotLabelFormat: [
+ {
+ weekday: 'long',
+ day: '2-digit',
+ },
+ ],
+ resourceAreaColumns: [
+ {
+ field: 'title',
+ headerContent: this.text.assignees,
+ },
+ ],
+ },
},
- },
- events: this.calendarEventsFunction.bind(this) as unknown,
- resources: this.calendarResourcesFunction.bind(this) as unknown,
- eventClick: this.openSplitView.bind(this) as unknown,
- resourceLabelContent: (data:ResourceLabelContentArg) => this.renderTemplate(this.resourceContent, data.resource.id, data),
- resourceLabelWillUnmount: (data:ResourceLabelContentArg) => this.unrenderTemplate(data.resource.id),
- } as CalendarOptions);
+ events: this.calendarEventsFunction.bind(this) as unknown,
+ resources: this.calendarResourcesFunction.bind(this) as unknown,
+ resourceLabelContent: (data:ResourceLabelContentArg) => this.renderTemplate(this.resourceContent, data.resource.id, data),
+ resourceLabelWillUnmount: (data:ResourceLabelContentArg) => this.unrenderTemplate(data.resource.id),
+ } as CalendarOptions),
+ );
});
}
@@ -234,58 +191,10 @@ export class TeamPlannerComponent extends UntilDestroyedMixin implements OnInit,
this.viewLookup.destroyView(id);
}
- public updateTimeframe(fetchInfo:{ start:Date, end:Date, timeZone:string }):void {
- const filtersEmpty = this.wpTableFilters.isEmpty;
-
- if (filtersEmpty && this.querySpace.query.value) {
- // nothing to do
- return;
- }
-
- const startDate = moment(fetchInfo.start).format('YYYY-MM-DD');
- const endDate = moment(fetchInfo.end).format('YYYY-MM-DD');
-
- if (filtersEmpty) {
- let queryProps = this.defaultQueryProps(startDate, endDate);
-
- if (this.$state.params.query_props) {
- queryProps = decodeURIComponent(this.$state.params.query_props || '');
- }
-
- void this
- .wpListService
- .fromQueryParams({ query_props: queryProps }, this.projectIdentifier || undefined)
- .toPromise();
- } else {
- this.wpTableFilters.modify('datesInterval', (datesIntervalFilter) => {
- // eslint-disable-next-line no-param-reassign
- datesIntervalFilter.values[0] = startDate;
- // eslint-disable-next-line no-param-reassign
- datesIntervalFilter.values[1] = endDate;
- });
- }
- }
-
- private openSplitView(event:EventClickArg) {
- const workPackage = event.event.extendedProps.workPackage as WorkPackageResource;
-
- void this.$state.go(
- `${splitViewRoute(this.$state)}.tabs`,
- { workPackageId: workPackage.id, tabIdentifier: 'overview' },
- );
- }
-
- private setupWorkPackagesListener() {
- this
- .querySpace
- .results
- .values$()
- .pipe(
- this.untilDestroyed(),
- )
- .subscribe(() => {
- this.renderCurrent();
- });
+ private setupWorkPackagesListener():void {
+ this.calendar.workPackagesListener$(() => {
+ this.renderCurrent();
+ });
}
/**
@@ -303,8 +212,8 @@ export class TeamPlannerComponent extends UntilDestroyedMixin implements OnInit,
return undefined;
}
- const startDate = this.eventDate(workPackage, 'start');
- const endDate = this.eventDate(workPackage, 'due');
+ const startDate = this.calendar.eventDate(workPackage, 'start');
+ const endDate = this.calendar.eventDate(workPackage, 'due');
const exclusiveEnd = moment(endDate).add(1, 'days').format('YYYY-MM-DD');
const assignee = (workPackage.assignee as HalResource).href as string;
@@ -341,37 +250,4 @@ export class TeamPlannerComponent extends UntilDestroyedMixin implements OnInit,
return resources;
}
-
- private defaultQueryProps(startDate:string, endDate:string) {
- const props = {
- c: ['id'],
- t:
- 'id:asc',
- f: [{ n: 'status', o: 'o', v: [] },
- { n: 'datesInterval', o: '<>d', v: [startDate, endDate] }],
- pp: 100,
- };
-
- return JSON.stringify(props);
- }
-
- private eventDate(workPackage:WorkPackageResource, type:'start'|'due'):string {
- if (this.schemaCache.of(workPackage).isMilestone) {
- return workPackage.date;
- }
- return workPackage[`${type}Date`] as string;
- }
-
- private calendarHeight():number {
- let heightElement = jQuery(this.elementRef.nativeElement);
-
- while (!heightElement.height() && heightElement.parent()) {
- heightElement = heightElement.parent();
- }
-
- const topOfCalendar = jQuery(this.elementRef.nativeElement).position().top;
- const topOfHeightElement = heightElement.position().top;
-
- return heightElement.height()! - (topOfCalendar - topOfHeightElement);
- }
}
diff --git a/frontend/src/app/shared/components/calendar/op-calendar.service.ts b/frontend/src/app/shared/components/calendar/op-calendar.service.ts
new file mode 100644
index 00000000000..b7bc89b0f35
--- /dev/null
+++ b/frontend/src/app/shared/components/calendar/op-calendar.service.ts
@@ -0,0 +1,253 @@
+import {
+ ElementRef,
+ Injectable,
+ SecurityContext,
+} from '@angular/core';
+import {
+ CalendarOptions,
+ EventApi,
+} from '@fullcalendar/core';
+import { I18nService } from 'core-app/core/i18n/i18n.service';
+import { ConfigurationService } from 'core-app/core/config/configuration.service';
+import { WorkPackageResource } from 'core-app/features/hal/resources/work-package-resource';
+import { DomSanitizer } from '@angular/platform-browser';
+import { SchemaCacheService } from 'core-app/core/schemas/schema-cache.service';
+import { EventClickArg } from '@fullcalendar/common';
+import { splitViewRoute } from 'core-app/features/work-packages/routing/split-view-routes.helper';
+import { StateService } from '@uirouter/angular';
+import { WorkPackageCollectionResource } from 'core-app/features/hal/resources/wp-collection-resource';
+import { ToastService } from 'core-app/shared/components/toaster/toast.service';
+import {
+ Observable,
+ Subject,
+} from 'rxjs';
+import { WorkPackageViewFiltersService } from 'core-app/features/work-packages/routing/wp-view-base/view-services/wp-view-filters.service';
+import { WorkPackagesListService } from 'core-app/features/work-packages/components/wp-list/wp-list.service';
+import { IsolatedQuerySpace } from 'core-app/features/work-packages/directives/query-space/isolated-query-space';
+import { UntilDestroyedMixin } from 'core-app/shared/helpers/angular/until-destroyed.mixin';
+import { take } from 'rxjs/operators';
+
+export interface CalendarViewEvent {
+ el:HTMLElement;
+ event:EventApi;
+}
+
+@Injectable()
+export class OpCalendarService extends UntilDestroyedMixin {
+ static MAX_DISPLAYED = 100;
+
+ resize$ = new Subject<void>();
+
+ resizeObs:ResizeObserver;
+
+ tooManyResultsText:string|null;
+
+ currentWorkPackages$:Observable<WorkPackageCollectionResource> = this
+ .querySpace
+ .results
+ .values$()
+ .pipe(
+ take(1),
+ );
+
+ constructor(
+ private I18n:I18nService,
+ private configuration:ConfigurationService,
+ private sanitizer:DomSanitizer,
+ readonly schemaCache:SchemaCacheService,
+ private $state:StateService,
+ readonly toastService:ToastService,
+ readonly wpTableFilters:WorkPackageViewFiltersService,
+ readonly wpListService:WorkPackagesListService,
+ readonly querySpace:IsolatedQuerySpace,
+ ) {
+ super();
+ }
+
+ workPackagesListener$(callbackFn:() => void):void {
+ this
+ .querySpace
+ .results
+ .values$()
+ .pipe(
+ this.untilDestroyed(),
+ )
+ .subscribe(() => {
+ callbackFn();
+ });
+ }
+
+ calendarOptions(additionalOptions:CalendarOptions):CalendarOptions {
+ return { ...this.defaultOptions(), ...additionalOptions };
+ }
+
+ addTooltip(event:CalendarViewEvent):void {
+ jQuery(event.el).tooltip({
+ content: this.tooltipContentString(event.event.extendedProps.workPackage),
+ items: '.fc-event',
+ close() {
+ jQuery('.ui-helper-hidden-accessible').remove();
+ },
+ track: true,
+ });
+ }
+
+ removeTooltip(element:HTMLElement):void {
+ // deactivate tooltip so that it is not displayed on the wp show page
+ jQuery(element).tooltip({
+ close() {
+ jQuery('.ui-helper-hidden-accessible').remove();
+ },
+ disabled: true,
+ });
+ }
+
+ eventDate(workPackage:WorkPackageResource, type:'start'|'due'):string {
+ if (this.schemaCache.of(workPackage).isMilestone) {
+ return workPackage.date;
+ }
+ return workPackage[`${type}Date`];
+ }
+
+ warnOnTooManyResults(collection:WorkPackageCollectionResource, isStatic = false):void {
+ if (collection.count < collection.total) {
+ this.tooManyResultsText = this.I18n.t('js.calendar.too_many',
+ {
+ count: collection.total,
+ max: OpCalendarService.MAX_DISPLAYED,
+ });
+ } else {
+ this.tooManyResultsText = null;
+ }
+
+ if (this.tooManyResultsText && !isStatic) {
+ this.toastService.addNotice(this.tooManyResultsText);
+ }
+ }
+
+ resizeObserver(v:ElementRef|undefined):void {
+ if (!v) {
+ return;
+ }
+
+ if (!this.resizeObs) {
+ this.resizeObs = new ResizeObserver(() => this.resize$.next());
+ }
+
+ this.resizeObs.observe(v.nativeElement);
+ }
+
+ updateTimeframe(fetchInfo:{ start:Date, end:Date, timeZone:string }, projectIdentifier:string|undefined):void {
+ const filtersEmpty = this.wpTableFilters.isEmpty;
+
+ if (filtersEmpty && this.querySpace.query.value) {
+ // nothing to do
+ return;
+ }
+
+ const startDate = moment(fetchInfo.start).format('YYYY-MM-DD');
+ const endDate = moment(fetchInfo.end).format('YYYY-MM-DD');
+
+ if (filtersEmpty) {
+ let queryProps = OpCalendarService.defaultQueryProps(startDate, endDate);
+
+ if (this.$state.params.query_props) {
+ queryProps = decodeURIComponent(this.$state.params.query_props || '');
+ }
+
+ void this
+ .wpListService
+ .fromQueryParams({ query_props: queryProps }, projectIdentifier || undefined)
+ .toPromise();
+ } else {
+ this.wpTableFilters.modify('datesInterval', (datesIntervalFilter) => {
+ // eslint-disable-next-line no-param-reassign
+ datesIntervalFilter.values[0] = startDate;
+ // eslint-disable-next-line no-param-reassign
+ datesIntervalFilter.values[1] = endDate;
+ });
+ }
+ }
+
+ private defaultOptions():CalendarOptions {
+ return {
+ editable: false,
+ locale: this.I18n.locale,
+ fixedWeekCount: false,
+ firstDay: this.configuration.startOfWeek(),
+ timeZone: this.configuration.isTimezoneSet() ? this.configuration.timezone() : 'local',
+ height: 'auto',
+ headerToolbar: {
+ left: 'prev,next today',
+ center: 'title',
+ right: '',
+ },
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+ eventClick: this.openSplitView.bind(this),
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+ eventDidMount: this.addTooltip.bind(this),
+ };
+ }
+
+ private openSplitView(event:EventClickArg) {
+ const workPackage = event.event.extendedProps.workPackage as WorkPackageResource;
+
+ void this.$state.go(
+ `${splitViewRoute(this.$state)}.tabs`,
+ { workPackageId: workPackage.id, tabIdentifier: 'overview' },
+ );
+ }
+
+ private sanitizedValue(workPackage:WorkPackageResource, attribute:string, toStringMethod:string|null = 'name'):string {
+ let value = workPackage[attribute];
+ value = toStringMethod && value ? value[toStringMethod] : value;
+ value = value || this.I18n.t('js.placeholders.default');
+
+ return this.sanitizer.sanitize(SecurityContext.HTML, value) || '';
+ }
+
+ private tooltipContentString(workPackage:WorkPackageResource) {
+ return `
+ ${this.sanitizedValue(workPackage, 'type')} #${workPackage.id}: ${this.sanitizedValue(workPackage, 'subject', null)}
+ <ul class="tooltip--map">
+ <li class="tooltip--map--item">
+ <span class="tooltip--map--key">${this.I18n.t('js.work_packages.properties.projectName')}:</span>
+ <span class="tooltip--map--value">${this.sanitizedValue(workPackage, 'project')}</span>
+ </li>
+ <li class="tooltip--map--item">
+ <span class="tooltip--map--key">${this.I18n.t('js.work_packages.properties.status')}:</span>
+ <span class="tooltip--map--value">${this.sanitizedValue(workPackage, 'status')}</span>
+ </li>
+ <li class="tooltip--map--item">
+ <span class="tooltip--map--key">${this.I18n.t('js.work_packages.properties.startDate')}:</span>
+ <span class="tooltip--map--value">${this.eventDate(workPackage, 'start')}</span>
+ </li>
+ <li class="tooltip--map--item">
+ <span class="tooltip--map--key">${this.I18n.t('js.work_packages.properties.dueDate')}:</span>
+ <span class="tooltip--map--value">${this.eventDate(workPackage, 'due')}</span>
+ </li>
+ <li class="tooltip--map--item">
+ <span class="tooltip--map--key">${this.I18n.t('js.work_packages.properties.assignee')}:</span>
+ <span class="tooltip--map--value">${this.sanitizedValue(workPackage, 'assignee')}</span>
+ </li>
+ <li class="tooltip--map--item">
+ <span class="tooltip--map--key">${this.I18n.t('js.work_packages.properties.priority')}:</span>
+ <span class="tooltip--map--value">${this.sanitizedValue(workPackage, 'priority')}</span>
+ </li>
+ </ul>
+ `;
+ }
+
+ private static defaultQueryProps(startDate:string, endDate:string) {
+ const props = {
+ c: ['id'],
+ t:
+ 'id:asc',
+ f: [{ n: 'status', o: 'o', v: [] },
+ { n: 'datesInterval', o: '<>d', v: [startDate, endDate] }],
+ pp: OpCalendarService.MAX_DISPLAYED,
+ };
+
+ return JSON.stringify(props);
+ }
+}
diff --git a/frontend/src/app/shared/components/calendar/te-calendar/te-calendar.component.ts b/frontend/src/app/shared/components/calendar/te-calendar/te-calendar.component.ts
index fae9f87dcc2..8b9a561fb12 100644
--- a/frontend/src/app/shared/components/calendar/te-calendar/te-calendar.component.ts
+++ b/frontend/src/app/shared/components/calendar/te-calendar/te-calendar.component.ts
@@ -1,5 +1,4 @@
import {
- AfterViewInit,
ChangeDetectionStrategy,
Component,
ElementRef,
@@ -20,7 +19,10 @@ import { I18nService } from 'core-app/core/i18n/i18n.service';
import { DomSanitizer } from '@angular/platform-browser';
import timeGrid from '@fullcalendar/timegrid';
import {
- CalendarOptions, Duration, EventApi, EventInput,
+ CalendarOptions,
+ Duration,
+ EventApi,
+ EventInput,
} from '@fullcalendar/core';
import { ConfigurationService } from 'core-app/core/config/configuration.service';
import { TimeEntryResource } from 'core-app/features/hal/resources/time-entry-resource';
@@ -37,6 +39,7 @@ import { FilterOperator } from 'core-app/shared/helpers/api-v3/api-v3-filter-bui
import { TimezoneService } from 'core-app/core/datetime/timezone.service';
import { HalResourceNotificationService } from 'core-app/features/hal/services/hal-resource-notification.service';
import idFromLink from 'core-app/features/hal/helpers/id-from-link';
+import { OpCalendarService } from 'core-app/shared/components/calendar/op-calendar.service';
interface CalendarViewEvent {
el:HTMLElement;
@@ -67,12 +70,13 @@ const ADD_ENTRY_PROHIBITED_CLASS_NAME = '-prohibited';
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [
+ OpCalendarService,
TimeEntryEditService,
TimeEntryCreateService,
HalResourceEditingService,
],
})
-export class TimeEntryCalendarComponent implements AfterViewInit {
+export class TimeEntryCalendarComponent {
@ViewChild(FullCalendarComponent) ucCalendar:FullCalendarComponent;
@Input() projectIdentifier:string;
@@ -129,6 +133,10 @@ export class TimeEntryCalendarComponent implements AfterViewInit {
events: this.calendarEventsFunction.bind(this),
eventOverlap: (stillEvent:any) => !stillEvent.classNames.includes(TIME_ENTRY_CLASS_NAME),
plugins: [timeGrid, interactionPlugin],
+ eventDidMount: this.alterEventEntry.bind(this),
+ eventWillUnmount: this.beforeEventRemove.bind(this),
+ eventClick: this.dispatchEventClick.bind(this),
+ eventDrop: this.moveEvent.bind(this),
};
constructor(readonly states:States,
@@ -145,26 +153,8 @@ export class TimeEntryCalendarComponent implements AfterViewInit {
private timeEntryCreate:TimeEntryCreateService,
private schemaCache:SchemaCacheService,
private colors:ColorsService,
- private browserDetector:BrowserDetector) {
- }
-
- ngAfterViewInit() {
- // The full-calendar component's outputs do not seem to work
- // see: https://github.com/fullcalendar/fullcalendar-angular/issues/228#issuecomment-523505044
- // Therefore, setting the outputs via the underlying API
- this.ucCalendar.getApi().setOption('eventDidMount', (event:CalendarViewEvent) => {
- this.alterEventEntry(event);
- });
- this.ucCalendar.getApi().setOption('eventWillUnmount', (event:CalendarViewEvent) => {
- this.beforeEventRemove(event);
- });
- this.ucCalendar.getApi().setOption('eventClick', (event:CalendarViewEvent) => {
- this.dispatchEventClick(event);
- });
- this.ucCalendar.getApi().setOption('eventDrop', (event:CalendarMoveEvent) => {
- this.moveEvent(event);
- });
- }
+ private browserDetector:BrowserDetector,
+ ) {}
public calendarEventsFunction(fetchInfo:{ start:Date, end:Date },
successCallback:(events:EventInput[]) => void,
diff --git a/frontend/src/app/shared/components/calendar/wp-calendar/wp-calendar.component.ts b/frontend/src/app/shared/components/calendar/wp-calendar/wp-calendar.component.ts
index 525a2119f5e..07d5aedf3e0 100644
--- a/frontend/src/app/shared/components/calendar/wp-calendar/wp-calendar.component.ts
+++ b/frontend/src/app/shared/components/calendar/wp-calendar/wp-calendar.component.ts
@@ -1,7 +1,14 @@
import {
- Component, ElementRef, Input, OnInit, SecurityContext, ViewChild,
+ Component,
+ ElementRef,
+ Input,
+ OnInit,
+ ViewChild,
} from '@angular/core';
-import { FullCalendarComponent } from '@fullcalendar/angular';
+import {
+ FullCalendarComponent,
+ ToolbarInput,
+} from '@fullcalendar/angular';
import { States } from 'core-app/core/states/states.service';
import { IsolatedQuerySpace } from 'core-app/features/work-packages/directives/query-space/isolated-query-space';
import { WorkPackageResource } from 'core-app/features/hal/resources/work-package-resource';
@@ -16,77 +23,45 @@ import { DomSanitizer } from '@angular/platform-browser';
import { WorkPackagesListChecksumService } from 'core-app/features/work-packages/components/wp-list/wp-list-checksum.service';
import { OpTitleService } from 'core-app/core/html/op-title.service';
import dayGridPlugin from '@fullcalendar/daygrid';
-import { CalendarOptions, EventApi, EventInput } from '@fullcalendar/core';
-import { Subject } from 'rxjs';
-import { debounceTime, take } from 'rxjs/operators';
+import {
+ CalendarOptions,
+ EventInput,
+} from '@fullcalendar/core';
+import { debounceTime } from 'rxjs/operators';
import { ConfigurationService } from 'core-app/core/config/configuration.service';
import { UntilDestroyedMixin } from 'core-app/shared/helpers/angular/until-destroyed.mixin';
import { SchemaCacheService } from 'core-app/core/schemas/schema-cache.service';
-
-interface CalendarViewEvent {
- el:HTMLElement;
- event:EventApi;
-}
+import {
+ CalendarViewEvent,
+ OpCalendarService,
+} from 'core-app/shared/components/calendar/op-calendar.service';
@Component({
templateUrl: './wp-calendar.template.html',
styleUrls: ['./wp-calendar.sass'],
selector: 'wp-calendar',
+ providers: [
+ OpCalendarService,
+ ],
})
export class WorkPackagesCalendarController extends UntilDestroyedMixin implements OnInit {
- private resizeObserver:ResizeObserver;
-
- private resizeSubject = new Subject<any>();
-
- private ucCalendar:FullCalendarComponent;
-
- @ViewChild(FullCalendarComponent)
- set container(v:FullCalendarComponent|undefined) {
- // ViewChild reference may be undefined initially
- // due to ngIf
- if (!v) {
- return;
- }
-
- this.ucCalendar = v;
-
- // The full-calendar component's outputs do not seem to work
- // see: https://github.com/fullcalendar/fullcalendar-angular/issues/228#issuecomment-523505044
- // Therefore, setting the outputs via the underlying API
- this.ucCalendar.getApi().setOption('eventDidMount', (event:CalendarViewEvent) => {
- this.addTooltip(event);
- });
- this.ucCalendar.getApi().setOption('eventClick', (event:CalendarViewEvent) => {
- this.toWPFullView(event);
- });
- }
+ @ViewChild(FullCalendarComponent) ucCalendar:FullCalendarComponent;
@ViewChild('ucCalendar', { read: ElementRef })
set ucCalendarElement(v:ElementRef|undefined) {
- if (!v) {
- return;
- }
-
- if (!this.resizeObserver) {
- this.resizeObserver = new ResizeObserver(() => this.resizeSubject.next());
- }
-
- this.resizeObserver.observe(v.nativeElement);
+ this.calendar.resizeObserver(v);
}
@Input() projectIdentifier:string;
@Input() static = false;
- static MAX_DISPLAYED = 100;
-
- public tooManyResultsText:string|null;
+ calendarOptions:CalendarOptions|undefined;
private alreadyLoaded = false;
- calendarOptions:CalendarOptions|undefined;
-
- constructor(readonly states:States,
+ constructor(
+ readonly states:States,
readonly $state:StateService,
readonly wpTableFilters:WorkPackageViewFiltersService,
readonly wpListService:WorkPackagesListService,
@@ -98,12 +73,14 @@ export class WorkPackagesCalendarController extends UntilDestroyedMixin implemen
readonly i18n:I18nService,
readonly toastService:ToastService,
private sanitizer:DomSanitizer,
- private configuration:ConfigurationService) {
+ private configuration:ConfigurationService,
+ readonly calendar:OpCalendarService,
+ ) {
super();
}
- ngOnInit() {
- this.resizeSubject
+ ngOnInit():void {
+ this.calendar.resize$
.pipe(
this.untilDestroyed(),
debounceTime(50),
@@ -120,32 +97,37 @@ export class WorkPackagesCalendarController extends UntilDestroyedMixin implemen
}
public calendarEventsFunction(fetchInfo:{ start:Date, end:Date, timeZone:string },
- successCallback:(events:EventInput[]) => void,
- failureCallback:(error:any) => void):void|PromiseLike<EventInput[]> {
+ successCallback:(events:EventInput[]) => void):void|PromiseLike<EventInput[]> {
if (this.alreadyLoaded) {
this.alreadyLoaded = false;
const events = this.updateResults(this.querySpace.results.value!);
successCallback(events);
} else {
- this.querySpace.results.values$().pipe(
- take(1),
- ).subscribe((collection:WorkPackageCollectionResource) => {
- const events = this.updateResults((collection));
- successCallback(events);
- });
+ this
+ .calendar
+ .currentWorkPackages$
+ .subscribe((collection:WorkPackageCollectionResource) => {
+ const events = this.updateResults((collection));
+ successCallback(events);
+ });
}
- this.updateTimeframe(fetchInfo);
+ this.calendar.updateTimeframe(fetchInfo, this.projectIdentifier);
+ }
+
+ // eslint-disable-next-line @angular-eslint/use-lifecycle-interface
+ ngOnDestroy():void {
+ super.ngOnDestroy();
+ this.calendar.resizeObs?.disconnect();
}
private initializeCalendar() {
- this.configuration.initialized
+ void this.configuration.initialized
.then(() => {
- this.calendarOptions = {
- editable: false,
- locale: this.i18n.locale,
- fixedWeekCount: false,
- firstDay: this.configuration.startOfWeek(),
+ this.calendarOptions = this.calendar.calendarOptions({
+ height: this.calendarHeight(),
+ headerToolbar: this.buildHeader(),
+ eventClick: this.toWPFullView.bind(this),
events: this.calendarEventsFunction.bind(this),
plugins: [dayGridPlugin],
initialView: (() => {
@@ -154,58 +136,16 @@ export class WorkPackagesCalendarController extends UntilDestroyedMixin implemen
}
return undefined;
})(),
- height: this.calendarHeight(),
- headerToolbar: this.buildHeader(),
- };
- });
- }
-
- public updateTimeframe(fetchInfo:{ start:Date, end:Date, timeZone:string }) {
- const filtersEmpty = this.wpTableFilters.isEmpty;
-
- if (filtersEmpty && this.querySpace.query.value) {
- // nothing to do
- return;
- }
-
- const startDate = moment(fetchInfo.start).format('YYYY-MM-DD');
- const endDate = moment(fetchInfo.end).format('YYYY-MM-DD');
-
- if (filtersEmpty) {
- let queryProps = this.defaultQueryProps(startDate, endDate);
-
- if (this.$state.params.query_props) {
- queryProps = decodeURIComponent(this.$state.params.query_props || '');
- }
-
- this.wpListService.fromQueryParams({ query_props: queryProps }, this.projectIdentifier).toPromise();
- } else {
- const { params } = this.$state;
-
- this.wpTableFilters.modify('datesInterval', (datesIntervalFilter) => {
- datesIntervalFilter.values[0] = startDate;
- datesIntervalFilter.values[1] = endDate;
+ });
});
- }
}
- public addTooltip(event:CalendarViewEvent) {
- jQuery(event.el).tooltip({
- content: this.tooltipContentString(event.event.extendedProps.workPackage),
- items: '.fc-event',
- close() {
- jQuery('.ui-helper-hidden-accessible').remove();
- },
- track: true,
- });
- }
-
- public toWPFullView(event:CalendarViewEvent) {
+ toWPFullView(event:CalendarViewEvent):void {
const { workPackage } = event.event.extendedProps;
if (event.el) {
// do not display the tooltip on the wp show page
- this.removeTooltip(event.el);
+ this.calendar.removeTooltip(event.el);
}
// Ensure checksum is removed to allow queries to load
@@ -214,7 +154,7 @@ export class WorkPackagesCalendarController extends UntilDestroyedMixin implemen
// Ensure current calendar URL is pushed to history
window.history.pushState({}, this.titleService.current, window.location.href);
- this.$state.go(
+ void this.$state.go(
'work-packages.show',
{ workPackageId: workPackage.id },
{ inherit: false },
@@ -242,7 +182,7 @@ export class WorkPackagesCalendarController extends UntilDestroyedMixin implemen
return jQuery(window).height()! - this.calendarElement.offset()!.top - 12;
}
- public buildHeader() {
+ public buildHeader():false|ToolbarInput|undefined {
if (this.static) {
return false;
}
@@ -253,7 +193,7 @@ export class WorkPackagesCalendarController extends UntilDestroyedMixin implemen
};
}
- private setCalendarsDate() {
+ private setCalendarsDate():void {
const query = this.querySpace.query.value;
if (!query) {
return;
@@ -283,27 +223,23 @@ export class WorkPackagesCalendarController extends UntilDestroyedMixin implemen
}
}
- private setupWorkPackagesListener() {
- this.querySpace.results.values$().pipe(
- this.untilDestroyed(),
- ).subscribe((collection:WorkPackageCollectionResource) => {
+ private setupWorkPackagesListener():void {
+ this.calendar.workPackagesListener$(() => {
this.alreadyLoaded = true;
this.setCalendarsDate();
-
this.ucCalendar.getApi().refetchEvents();
});
}
private updateResults(collection:WorkPackageCollectionResource) {
- this.warnOnTooManyResults(collection);
-
+ this.calendar.warnOnTooManyResults(collection, this.static);
return this.mapToCalendarEvents(collection.elements);
}
private mapToCalendarEvents(workPackages:WorkPackageResource[]) {
const events = workPackages.map((workPackage:WorkPackageResource) => {
- const startDate = this.eventDate(workPackage, 'start');
- const endDate = this.eventDate(workPackage, 'due');
+ const startDate = this.calendar.eventDate(workPackage, 'start');
+ const endDate = this.calendar.eventDate(workPackage, 'due');
const exclusiveEnd = moment(endDate).add(1, 'days').format('YYYY-MM-DD');
@@ -319,90 +255,4 @@ export class WorkPackagesCalendarController extends UntilDestroyedMixin implemen
return events;
}
-
- private warnOnTooManyResults(collection:WorkPackageCollectionResource) {
- if (collection.count < collection.total) {
- this.tooManyResultsText = this.i18n.t('js.calendar.too_many',
- {
- count: collection.total,
- max: WorkPackagesCalendarController.MAX_DISPLAYED,
- });
- } else {
- this.tooManyResultsText = null;
- }
-
- if (this.tooManyResultsText && !this.static) {
- this.toastService.addNotice(this.tooManyResultsText);
- }
- }
-
- private defaultQueryProps(startDate:string, endDate:string) {
- const props = {
- c: ['id'],
- t:
- 'id:asc',
- f: [{ n: 'status', o: 'o', v: [] },
- { n: 'datesInterval', o: '<>d', v: [startDate, endDate] }],
- pp: WorkPackagesCalendarController.MAX_DISPLAYED,
- };
-
- return JSON.stringify(props);
- }
-
- private eventDate(workPackage:WorkPackageResource, type:'start'|'due') {
- if (this.schemaCache.of(workPackage).isMilestone) {
- return workPackage.date;
- }
- return workPackage[`${type}Date`];
- }
-
- private tooltipContentString(workPackage:WorkPackageResource) {
- return `
- ${this.sanitizedValue(workPackage, 'type')} #${workPackage.id}: ${this.sanitizedValue(workPackage, 'subject', null)}
- <ul class="tooltip--map">
- <li class="tooltip--map--item">
- <span class="tooltip--map--key">${this.i18n.t('js.work_packages.properties.projectName')}:</span>
- <span class="tooltip--map--value">${this.sanitizedValue(workPackage, 'project')}</span>
- </li>
- <li class="tooltip--map--item">
- <span class="tooltip--map--key">${this.i18n.t('js.work_packages.properties.status')}:</span>
- <span class="tooltip--map--value">${this.sanitizedValue(workPackage, 'status')}</span>
- </li>
- <li class="tooltip--map--item">
- <span class="tooltip--map--key">${this.i18n.t('js.work_packages.properties.startDate')}:</span>
- <span class="tooltip--map--value">${this.eventDate(workPackage, 'start')}</span>
- </li>
- <li class="tooltip--map--item">
- <span class="tooltip--map--key">${this.i18n.t('js.work_packages.properties.dueDate')}:</span>
- <span class="tooltip--map--value">${this.eventDate(workPackage, 'due')}</span>
- </li>
- <li class="tooltip--map--item">
- <span class="tooltip--map--key">${this.i18n.t('js.work_packages.properties.assignee')}:</span>
- <span class="tooltip--map--value">${this.sanitizedValue(workPackage, 'assignee')}</span>
- </li>
- <li class="tooltip--map--item">
- <span class="tooltip--map--key">${this.i18n.t('js.work_packages.properties.priority')}:</span>
- <span class="tooltip--map--value">${this.sanitizedValue(workPackage, 'priority')}</span>
- </li>
- </ul>
- `;
- }
-
- private sanitizedValue(workPackage:WorkPackageResource, attribute:string, toStringMethod:string|null = 'name') {
- let value = workPackage[attribute];
- value = toStringMethod && value ? value[toStringMethod] : value;
- value = value || this.i18n.t('js.placeholders.default');
-
- return this.sanitizer.sanitize(SecurityContext.HTML, value);
- }
-
- private removeTooltip(element:HTMLElement) {
- // deactivate tooltip so that it is not displayed on the wp show page
- jQuery(element).tooltip({
- close() {
- jQuery('.ui-helper-hidden-accessible').remove();
- },
- disabled: true,
- });
- }
}
diff --git a/frontend/src/app/shared/components/calendar/wp-calendar/wp-calendar.template.html b/frontend/src/app/shared/components/calendar/wp-calendar/wp-calendar.template.html
index 3305c76336a..98be86116cc 100644
--- a/frontend/src/app/shared/components/calendar/wp-calendar/wp-calendar.template.html
+++ b/frontend/src/app/shared/components/calendar/wp-calendar/wp-calendar.template.html
@@ -9,6 +9,6 @@
</full-calendar>
<div
*ngIf="static"
- [textContent]="tooManyResultsText"
+ [textContent]="calendar.tooManyResultsText"
class="op-wp-calendar--notification"></div>
</div>