/
Views.tsx
1205 lines (1094 loc) · 48.7 KB
/
Views.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as React from "react";
import * as Calendar from "./Calendar";
import * as Calendar_Contracts from "./Contracts";
import * as Calendar_Dialogs from "./Dialogs";
import { allSettled, realPromise } from "./Utils/Promise";
import * as Controls from "VSS/Controls";
import * as Controls_Dialogs from "VSS/Controls/Dialogs";
import * as Controls_Menus from "VSS/Controls/Menus";
import * as Controls_Navigation from "VSS/Controls/Navigation";
import * as Controls_StatusIndicator from "VSS/Controls/StatusIndicator";
import * as Service from "VSS/Service";
import * as Services_Navigation from "VSS/SDK/Services/Navigation";
import * as Tfs_Core_WebApi from "TFS/Core/RestClient";
import * as Utils_Core from "VSS/Utils/Core";
import * as Utils_Date from "VSS/Utils/Date";
import * as Utils_String from "VSS/Utils/String";
import { Hub } from "vss-ui/Hub";
import { HubHeader } from "vss-ui/HubHeader";
import { PickList, PickListDropdown, IPickListSelection } from "vss-ui/PickList";
import { IHubBreadcrumbItem } from "vss-ui/HubHeader";
import { HubViewState } from "vss-ui/Utilities/HubViewState";
import { IObservableValue, ObservableValue } from "vss-ui/Utilities/Observable";
import * as WebApi_Constants from "VSS/WebApi/Constants";
import * as WebApi_Contracts from "VSS/WebApi/Contracts";
import * as Work_Contracts from "TFS/Work/Contracts";
import * as FullCalendar from "fullcalendar"; // types only
import { BaseComponent, IBaseProps, IContextualMenuItem, IBreadcrumbItem, SelectionMode } from "office-ui-fabric-react";
import { PivotBarItem } from "vss-ui/PivotBar";
import { WebApiTeam } from "TFS/Core/Contracts";
import { Callout } from "vss-ui/node_modules/office-ui-fabric-react/lib/Callout";
const months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
// Polyfill Math.trunc...
(Math as any).trunc =
(Math as any).trunc ||
function(x) {
var n = x - x % 1;
return n === 0 && (x < 0 || (x === 0 && 1 / x !== 1 / 0)) ? -0 : n;
};
function newElement(tag: string, className?: string, text?: string): JQuery {
return $("<" + tag + "/>")
.addClass(className || "")
.text(text || "");
}
export class EventSourceCollection {
private static _createPromise: Promise<any>;
private _collection: Calendar_Contracts.IEventSource[] = [];
private _map: { [name: string]: Calendar_Contracts.IEventSource } = {};
constructor(sources: Calendar_Contracts.IEventSource[]) {
this._collection = sources || [];
for (const source of this._collection) {
this._map[source.id] = source;
}
}
public getById(id: string): Calendar_Contracts.IEventSource {
return this._map[id];
}
public getAllSources(): Calendar_Contracts.IEventSource[] {
return this._collection;
}
public updateTeamContext(newTeam: WebApiTeam) {
for (const eventSource of this._collection) {
if (typeof eventSource.updateTeamContext === "function") {
eventSource.updateTeamContext(newTeam);
}
}
}
public static create(team?: any): PromiseLike<EventSourceCollection> {
if (!this._createPromise) {
const extensionContext = VSS.getExtensionContext();
const eventSourcesTargetId =
extensionContext.publisherId + "." + extensionContext.extensionId + ".calendar-event-sources";
this._createPromise = realPromise(VSS.getServiceContributions(eventSourcesTargetId)).then(contributions => {
const servicePromises = contributions.map(c => c.getInstance(c.id, { team }));
return allSettled(servicePromises).then(promiseStates => {
const services = [];
promiseStates.forEach((promiseState, index: number) => {
if (promiseState.value) {
services.push(promiseState.value);
} else {
console.log("Failed to get calendar event source instance for: " + contributions[index].id);
}
});
return new EventSourceCollection(services);
});
});
}
return this._createPromise;
}
}
export interface CalendarViewOptions extends Calendar.CalendarOptions {
defaultEvents?: FullCalendar.EventObject[];
selectedTeam?: WebApiTeam;
}
export interface ICalendarHubProps extends IBaseProps {
onSelectedTeamChanged: (selectedTeam: WebApiTeam) => void;
onCalendarViewUpdated: (calendarView: CalendarView) => void;
selectedTeam?: WebApiTeam;
}
interface MonthAndYear {
month: number;
year: number;
}
export interface CalendarState {
calendar: MonthAndYear;
showMonthPicker: boolean;
monthPickerTarget: HTMLElement | null;
}
export class CalendarStateManagerComponent extends BaseComponent<
{},
{ calendarView?: ObservableValue<CalendarView>; selectedTeam?: WebApiTeam }
> {
constructor() {
super();
this.state = { calendarView: new ObservableValue() };
this.initialize();
}
private async initialize() {
const navSvc = await VSS.getService<IHostNavigationService>(VSS.ServiceIds.Navigation);
let selectedTeamId = (await navSvc.getCurrentState()).team;
if (!selectedTeamId) {
// Nothing in URL - check context
const contextTeam = VSS.getWebContext().team;
if (contextTeam && contextTeam.id) {
selectedTeamId = contextTeam.id;
}
}
if (!selectedTeamId) {
// Nothing in URL or context - check data service
const dataSvc = await VSS.getService<IExtensionDataService>(VSS.ServiceIds.ExtensionData);
selectedTeamId = await dataSvc.getValue<string>("selected-team", { scopeType: "User" });
}
if (selectedTeamId) {
// get the team if we found a way to choose one
const team = await Tfs_Core_WebApi.getClient().getTeam(VSS.getWebContext().project.id, selectedTeamId);
if (team) {
await this.setSelectedTeam(team);
// Work around a bug where pivot bar wont render properly on initial render.
setTimeout(() => {
this.forceUpdate();
}, 250);
}
}
}
private async setSelectedTeam(selectedTeam: WebApiTeam) {
// Set the URL and data service value to the selected team.
const navSvc = await VSS.getService<IHostNavigationService>(VSS.ServiceIds.Navigation);
navSvc.updateHistoryEntry(null, { team: selectedTeam.id }, true, true, null, false);
const dataSvc = await VSS.getService<IExtensionDataService>(VSS.ServiceIds.ExtensionData);
dataSvc.setValue<string>("selected-team", selectedTeam.id, { scopeType: "User" });
this.setState({ selectedTeam });
}
public render(): JSX.Element {
return (
<div>
<div className="calendar-area" id="calendarArea">
<CalendarComponent
onSelectedTeamChanged={async selectedTeam => {
this.setSelectedTeam(selectedTeam);
}}
onCalendarViewUpdated={calendarView => {
this.state.calendarView.value = calendarView;
this.forceUpdate();
}}
selectedTeam={this.state.selectedTeam}
/>
</div>
{this.state.selectedTeam &&
this.state.calendarView.value && (
<div className="summary-area" id="summaryArea">
<SummaryComponent calendarView={this.state.calendarView} />
</div>
)}
</div>
);
}
}
export class CalendarComponent extends BaseComponent<ICalendarHubProps, CalendarState> {
private hubViewState: HubViewState;
private calendarView: CalendarView;
private calendarDiv: HTMLElement;
private header: HubHeader;
private needToEnhance: boolean = false;
constructor() {
super();
this.hubViewState = new HubViewState({ defaultPivot: "calendar" });
this.state = {
calendar: { month: new Date().getMonth(), year: new Date().getFullYear() },
showMonthPicker: false,
monthPickerTarget: null,
};
}
private setSelectedTeam(team: WebApiTeam) {
if (team.id !== this.props.selectedTeam.id && typeof this.props.onSelectedTeamChanged === "function") {
this.props.onSelectedTeamChanged(team);
}
}
private static calcMonths(current: MonthAndYear, monthDelta: number): MonthAndYear {
let month = (current.month + monthDelta) % 12;
let year = current.year + Math.floor((current.month + monthDelta) / 12);
if (month < 0) {
month = 12 + month;
}
return { month, year };
}
private onMonthPickerClick(ev?: React.MouseEvent<HTMLElement>, item?: IBreadcrumbItem) {
this.setState({ showMonthPicker: true, monthPickerTarget: ev.target as HTMLElement });
}
/**
* Get list of current month -5 and +5 months
*/
private getHeaderItems(): IHubBreadcrumbItem[] {
return [
{
text: `${months[this.state.calendar.month]} ${this.state.calendar.year}`,
key: "monthpicker",
leftIconProps: { iconName: "Calendar" },
onClick: this.onMonthPickerClick.bind(this),
},
];
}
private getMonthPickerOptions(): MonthAndYear[] {
const options: MonthAndYear[] = [];
const listSize = 3;
for (let i = -listSize; i <= listSize; ++i) {
options.push(CalendarComponent.calcMonths(this.state.calendar, i));
}
return options;
}
private getMonthPickerListItem(item: MonthAndYear) {
const str = `${months[item.month]} ${item.year}`;
return {
name: str,
key: str,
};
}
private enhanceControls(): void {
if (this.calendarView) {
this.calendarView.dispose();
this.calendarView = null;
}
if (this.calendarDiv && this.props.selectedTeam) {
$(this.calendarDiv).empty();
this.calendarView = Controls.create(CalendarView, $(this.calendarDiv), {
selectedTeam: this.props.selectedTeam,
} as CalendarViewOptions);
this.calendarView.getCalendar().goTo(new Date(this.state.calendar.year, this.state.calendar.month, 1, 0, 0, 0));
this.props.onCalendarViewUpdated(this.calendarView);
}
}
public componentDidUpdate(prevProps: ICalendarHubProps, prevState: CalendarState): void {
if (prevProps.selectedTeam !== this.props.selectedTeam) {
if (this.needToEnhance) {
this.enhanceControls();
this.needToEnhance = false;
} else {
this.needToEnhance = true;
}
}
}
public render(): JSX.Element {
return (
<div>
{this.state.showMonthPicker && (
<Callout
isBeakVisible={false}
target={this.state.monthPickerTarget}
onDismiss={() => {
this.setState({ showMonthPicker: false });
}}>
<PickList
selectionMode={SelectionMode.single}
items={this.getMonthPickerOptions()}
getListItem={this.getMonthPickerListItem.bind(this)}
onSelectionChanged={selection => {
const selectedItem = selection.selectedItems[0] as MonthAndYear;
this.setState({ showMonthPicker: false, calendar: selection.selectedItems[0] });
this.calendarView.getCalendar().goTo(new Date(selectedItem.year, selectedItem.month, 1, 0, 0, 0));
}}
selectedItems={[this.state.calendar]}
/>
</Callout>
)}
<Hub
hideFullScreenToggle={true}
hubViewState={this.hubViewState}
viewActions={[
{
key: "move-today",
name: "Today",
important: true,
onClick: this._onCommandClick,
},
{
key: "move-left",
name: "Prev",
important: true,
iconProps: {
iconName: "ChevronLeft",
},
onClick: this._onCommandClick,
},
{
key: "move-right",
name: "Next",
important: true,
iconProps: {
iconName: "ChevronRight",
},
onClick: this._onCommandClick,
},
]}
commands={[
{
key: "new-item",
name: "New Item",
important: true,
iconProps: {
iconName: "Add",
},
onClick: this._onCommandClick,
},
{
key: "refresh",
name: "Refresh",
important: true,
iconProps: {
iconName: "Refresh",
},
onClick: this._onCommandClick,
},
]}>
<HubHeader
breadcrumbItems={this.getHeaderItems()}
ref={header => {
this.header = header;
}}
headerItemPicker={{
isSearchable: true,
searchTextPlaceholder: "Filter...",
getItems: () => {
return new Promise<WebApiTeam[]>((resolve, reject) => {
Tfs_Core_WebApi.getClient()
.getTeams(VSS.getWebContext().project.id, 1000)
.then(result => {
result.sort((a, b) => {
return a.name.toUpperCase().localeCompare(b.name.toUpperCase());
});
resolve(result);
}, reject);
});
},
getListItem: (item: WebApiTeam) => {
if (item) {
return {
name: item.name,
key: item.id,
};
}
return {
name: "Select a team",
key: "selectteammessage",
};
},
selectedItem: this.props.selectedTeam,
onSelectedItemChanged: (selectedTeam: WebApiTeam) => {
this.setSelectedTeam(selectedTeam);
},
}}
/>
{this.props.selectedTeam && (
<PivotBarItem name="Calendar" itemKey="calendar">
<div
className="calendar-canvas"
id="calendarCanvas"
ref={elem => {
if (elem) {
this.calendarDiv = elem;
if (this.needToEnhance) {
this.enhanceControls();
this.needToEnhance = false;
} else {
this.needToEnhance = true;
}
}
}}
/>
</PivotBarItem>
)}
</Hub>
</div>
);
}
private _onCommandClick = (ev: React.MouseEvent<HTMLElement>, item: IContextualMenuItem): void => {
switch (item.key) {
case "refresh":
this.calendarView.getCalendar().refreshEvents();
break;
case "new-item":
this.calendarView.addEventClicked();
break;
case "move-left":
const prevMonth = this.state.calendar.month - 1;
this.setState({ calendar: CalendarComponent.calcMonths(this.state.calendar, -1) });
this.calendarView.getCalendar().prev();
break;
case "move-right":
this.setState({ calendar: CalendarComponent.calcMonths(this.state.calendar, 1) });
this.calendarView.getCalendar().next();
break;
case "move-today":
const date = new Date();
this.setState({ calendar: { month: date.getMonth(), year: date.getFullYear() } });
this.calendarView.getCalendar().showToday();
break;
}
};
}
export class CalendarView extends Controls.BaseControl {
private _eventSources: EventSourceCollection;
private _calendar: Calendar.Calendar;
private _popupMenu: Controls_Menus.PopupMenu;
private _defaultEvents: FullCalendar.EventObject[];
private _calendarEventSourceMap: { [sourceId: string]: Calendar.CalendarEventSource } = {};
private _iterations: Work_Contracts.TeamSettingsIteration[];
private _currentMember: Calendar_Contracts.ICalendarMember;
private _processedSprints: { [key: string]: boolean } = {};
private _selectedTeam: WebApiTeam;
private static calendarEventFields: string[] = [
"title",
"__etag",
"id",
"category",
"iterationId",
"movable",
"member",
"description",
"icons",
"eventData",
];
constructor(options: CalendarViewOptions) {
super(options);
this._eventSources = new EventSourceCollection([]);
this._defaultEvents = options.defaultEvents || [];
this._selectedTeam = options.selectedTeam;
}
public initialize() {
const webContext: WebContext = VSS.getWebContext();
this._currentMember = {
displayName: webContext.user.name,
id: webContext.user.id,
imageUrl: "",
uniqueName: webContext.user.email,
url: "",
};
// Create calendar control
this._calendar = Controls.create(
Calendar.Calendar,
this._element,
$.extend(
{},
{
fullCalendarOptions: {
aspectRatio: this._getCalendarAspectRatio(),
handleWindowResize: false, // done by manually adjusting aspect ratio when the window is resized.
},
},
this._options,
),
);
EventSourceCollection.create(this._selectedTeam).then(eventSources => {
if (this._disposed) {
return;
}
eventSources.updateTeamContext(this._selectedTeam);
this._eventSources = eventSources;
this._calendar.addEvents(this._defaultEvents);
this._addDefaultEventSources();
this._calendar.addCallback(Calendar.FullCalendarCallbackType.viewDestroy, this._viewDestroy.bind(this));
this._calendar.addCallback(Calendar.FullCalendarCallbackType.eventAfterRender, this._eventAfterRender.bind(this));
this._calendar.addCallback(Calendar.FullCalendarCallbackType.eventClick, this._eventClick.bind(this));
this._calendar.addCallback(Calendar.FullCalendarCallbackType.eventDrop, this._eventMoved.bind(this));
this._calendar.addCallback(Calendar.FullCalendarCallbackType.eventResize, this._eventMoved.bind(this));
this._calendar.addCallback(Calendar.FullCalendarCallbackType.select, this._daysSelected.bind(this));
});
const setAspectRatio = Utils_Core.throttledDelegate(this, 300, () => {
this._calendar.setOption("aspectRatio", this._getCalendarAspectRatio());
});
window.addEventListener("resize", () => {
setAspectRatio();
});
}
public dispose() {
if (this._calendar) {
this._calendar.dispose();
this._calendar = null;
}
}
public getCalendar() {
return this._calendar;
}
private _viewDestroy() {
this._processedSprints = {};
}
private _getCalendarAspectRatio() {
const extensionFrame = this._element.closest("#extensionFrame");
const availableHeight =
extensionFrame.height() -
extensionFrame.find(".vss-PivotBar--bar-one-line").height() -
33 /* 23 margin pixels added */;
const availableWidth = extensionFrame.find(".calendar-area").width();
return availableWidth / availableHeight;
}
public addEventClicked(): void {
// Find the free form event source
const eventSource: Calendar_Contracts.IEventSource = $.grep(this._eventSources.getAllSources(), eventSource => {
return eventSource.id == "freeForm";
})[0];
// Setup the event
const now = new Date();
const event: Calendar_Contracts.CalendarEvent = {
title: "",
startDate: new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0)).toISOString(), // Create date equivalent to UTC midnight on the current Date
};
this._addEvent(event, eventSource);
}
private _addDefaultEventSources(): void {
const eventSources = $.map(this._eventSources.getAllSources(), eventSource => {
const sourceAndOptions = {
source: eventSource,
callbacks: {},
} as Calendar.SourceAndOptions;
sourceAndOptions.callbacks[Calendar.FullCalendarCallbackType.eventRender] = this._eventRender.bind(this, eventSource);
if (eventSource.background) {
sourceAndOptions.options = { rendering: "background" } as any;
}
return sourceAndOptions;
});
const calendarEventSources = this._calendar.addEventSources(eventSources);
calendarEventSources.forEach((calendarEventSource, index) => {
this._calendarEventSourceMap[eventSources[index].source.id] = calendarEventSource;
});
}
private _getCalendarEventSource(eventSourceId: string): Calendar.CalendarEventSource {
return this._calendarEventSourceMap[eventSourceId];
}
private _eventRender(
eventSource: Calendar_Contracts.IEventSource,
event: FullCalendar.EventObject,
element: JQuery,
view: FullCalendar.ViewObject,
) {
if (event.rendering !== "background") {
const eventObject = event as Calendar_Contracts.IExtendedCalendarEventObject;
const calendarEvent = this._eventObjectToCalendarEvent(eventObject);
if (calendarEvent.icons) {
for (const icon of calendarEvent.icons) {
const $image = $("<img/>")
.attr("src", icon.src)
.addClass("event-icon")
.addClass(icon.cssClass)
.prependTo(element.find(".fc-content"));
if (icon.title) {
$image.attr("title", icon.title);
}
if (eventSource.getEnhancer) {
eventSource.getEnhancer().then(enhancer => {
if (icon.action) {
const iconEvent = icon.linkedEvent || calendarEvent;
$image.bind("click", icon.action.bind(this, iconEvent));
}
if (icon.linkedEvent) {
enhancer.canEdit(calendarEvent, this._currentMember).then((canEdit: boolean) => {
const commands = [
{ rank: 5, id: "Edit", text: "Edit", icon: "icon-edit" },
{ rank: 10, id: "Delete", text: "Delete", icon: "icon-delete" },
];
const tempEvent = this._calendarEventToEventObject(icon.linkedEvent, eventSource);
this._buildContextMenu($image, tempEvent, commands);
$image.bind("click", this._editEvent.bind(this, tempEvent));
});
}
});
}
}
}
if (eventSource.getEnhancer) {
eventSource.getEnhancer().then(enhancer => {
enhancer.canEdit(calendarEvent, this._currentMember).then((canEdit: boolean) => {
if (canEdit) {
const commands = [
{ rank: 5, id: "Edit", text: "Edit", icon: "icon-edit" },
{ rank: 10, id: "Delete", text: "Delete", icon: "icon-delete" },
];
this._buildContextMenu($(element), eventObject, commands);
}
});
});
}
}
}
private _buildContextMenu($element: JQuery, eventObject: Calendar_Contracts.IExtendedCalendarEventObject, commands: any[]) {
const menuOptions = {
items: commands,
executeAction: e => {
const command = e.get_commandName();
switch (command) {
case "Edit":
this._editEvent(eventObject);
break;
case "Delete":
this._deleteEvent(eventObject);
break;
}
},
};
$element.on("contextmenu", (e: JQueryEventObject) => {
if (this._popupMenu) {
this._popupMenu.dispose();
this._popupMenu = null;
}
this._popupMenu = Controls.BaseControl.createIn(
Controls_Menus.PopupMenu,
this._element,
$.extend(
{
align: "left-bottom",
},
menuOptions,
{
items: [{ childItems: Controls_Menus.sortMenuItems(commands) }],
},
),
) as Controls_Menus.PopupMenu;
Utils_Core.delay(this, 10, () => {
this._popupMenu.popup(this._element, $element);
});
e.preventDefault();
});
}
private _eventAfterRender(event: FullCalendar.EventObject, element: JQuery, view: FullCalendar.ViewObject) {
if (event.rendering === "background") {
element.addClass("sprint-event");
element.data("event", event);
let contentCellIndex = 0;
const $contentCells = element.closest(".fc-row.fc-widget-content").find(".fc-content-skeleton table tr td");
element
.parent()
.children()
.each((index: number, child: Element) => {
if ($(child).data("event") && $(child).data("event").title === event.title) {
return false; // break;
}
contentCellIndex += parseInt($(child).attr("colspan"));
});
if (!this._processedSprints[event.title]) {
this._processedSprints[event.title] = true;
$contentCells.eq(contentCellIndex).append(
$("<span/>")
.addClass("sprint-label")
.text(event.title),
);
}
}
}
private _daysSelected(startDate: Date, endDate: Date, allDay: boolean, jsEvent: MouseEvent, view: FullCalendar.ViewObject) {
if (this._eventSources != null && this._eventSources.getAllSources().length > 0) {
let addEventSources: Calendar_Contracts.IEventSource[];
addEventSources = $.grep(this._eventSources.getAllSources(), eventSource => {
return !!eventSource.addEvent;
});
const start = new Date(startDate as any).toISOString();
const end = Utils_Date.addDays(new Date(endDate as any), -1).toISOString();
let event: Calendar_Contracts.CalendarEvent;
if (addEventSources.length > 0) {
event = {
title: "",
startDate: start,
endDate: end,
};
}
const commandsPromise = this._getAddCommands(addEventSources, event, start, end);
commandsPromise.then(commands => {
const menuOptions = {
items: commands,
};
const dataDate = Utils_Date.format(Utils_Date.shiftToUTC(new Date(event.endDate)), "yyyy-MM-dd"); //2015-04-19
const $element = $("td.fc-day-top[data-date='" + dataDate + "']");
if (this._popupMenu) {
this._popupMenu.dispose();
this._popupMenu = null;
}
this._popupMenu = Controls.BaseControl.createIn(
Controls_Menus.PopupMenu,
this._element,
$.extend(menuOptions, {
align: "left-bottom",
items: [{ childItems: Controls_Menus.sortMenuItems(commands) }],
}),
) as Controls_Menus.PopupMenu;
Utils_Core.delay(this, 10, () => {
this._popupMenu.popup(this._element, $element);
});
});
}
}
private _getAddCommands(
addEventSources: Calendar_Contracts.IEventSource[],
event: Calendar_Contracts.CalendarEvent,
start: string,
end: string,
): PromiseLike<any[]> {
const commandPromises: PromiseLike<any>[] = [];
let i = 0;
for (const source of addEventSources) {
if (source.getEnhancer) {
commandPromises.push(
source.getEnhancer().then(enhancer => {
return enhancer.canAdd(event, this._currentMember).then((canAdd: boolean) => {
return {
rank: source.order || i,
id: event.id,
text: Utils_String.format("Add {0}", source.name.toLocaleLowerCase()),
icon: enhancer.icon || "icon-add",
disabled: !canAdd,
action: this._addEvent.bind(this, event, source),
} as Controls_Menus.IMenuItemSpec;
});
}),
);
} else {
commandPromises.push(
Promise.resolve({
rank: source.order || i,
id: event.id,
text: Utils_String.format("Add {0}", source.name.toLocaleLowerCase()),
icon: "icon-add",
disabled: false,
action: this._addEvent.bind(this, event, source),
} as Controls_Menus.IMenuItemSpec),
);
}
i++;
}
return Promise.all(commandPromises);
}
private _eventClick(event: FullCalendar.EventObject, jsEvent: MouseEvent, view: FullCalendar.ViewObject) {
const eventObject = event as Calendar_Contracts.IExtendedCalendarEventObject;
const source = this._getEventSourceFromEvent(eventObject);
delete eventObject.source;
if (source.getEnhancer) {
source.getEnhancer().then(enhancer => {
enhancer.canEdit(eventObject as any, this._currentMember).then((canEdit: boolean) => {
if (canEdit) {
this._editEvent(eventObject);
}
});
});
}
}
private _eventMoved(
event: Calendar_Contracts.IExtendedCalendarEventObject,
dayDelta: number,
minuteDelta: number,
revertFunc: Function,
jsEvent: Event,
ui: any,
view: FullCalendar.ViewObject,
) {
const calendarEvent = this._eventObjectToCalendarEvent(event);
const eventSource: Calendar_Contracts.IEventSource = this._getEventSourceFromEvent(event);
if (eventSource && eventSource.updateEvent) {
if (eventSource.getEnhancer) {
eventSource.getEnhancer().then(enhancer => {
enhancer.canEdit(calendarEvent, this._currentMember).then((canEdit: boolean) => {
if (canEdit) {
eventSource
.updateEvent(null, calendarEvent)
.then((updatedEvent: Calendar_Contracts.CalendarEvent) => {
// Set underlying source to dirty so refresh picks up new changes
const originalEventSource = this._getCalendarEventSource(eventSource.id);
originalEventSource.state.dirty = true;
// Update dates
event.end = Utils_Date.addDays(new Date(updatedEvent.endDate), 1).toISOString();
event.start = updatedEvent.startDate;
event.__etag = updatedEvent.__etag;
this._calendar.updateEvent(event as any);
});
}
});
});
}
}
}
private _addEvent(event: Calendar_Contracts.CalendarEvent, eventSource: Calendar_Contracts.IEventSource) {
const query = this._calendar.getViewQuery();
event.member = this._currentMember;
const membersPromise = this._getTeamMembers();
const dialogOptions: Calendar_Dialogs.IEventDialogOptions = {
calendarEvent: event,
resizable: true,
source: eventSource,
membersPromise: membersPromise,
query: query,
bowtieVersion: 2,
okCallback: (calendarEvent: Calendar_Contracts.CalendarEvent) => {
eventSource.addEvent(calendarEvent).then((addedEvent: Calendar_Contracts.CalendarEvent) => {
const calendarEventSource = this._getCalendarEventSource(eventSource.id);
calendarEventSource.state.dirty = true;
if (addedEvent) {
this._calendar.renderEvent(addedEvent, eventSource.id);
} else {
this._calendar.refreshEvents(calendarEventSource);
}
});
},
};
//Calendar_Dialogs.ExternalEventDialog.showDialog(dialogOptions);
Controls_Dialogs.Dialog.show(Calendar_Dialogs.EditEventDialog, dialogOptions);
}
private _getTeamMembers(): PromiseLike<WebApi_Contracts.IdentityRef[]> {
const webContext = VSS.getWebContext();
// Hack to temporarily workaround API compat break in M125 which is being reverted
let coreClient: any = Service.VssConnection.getConnection().getHttpClient(
Tfs_Core_WebApi.CoreHttpClient2_2,
WebApi_Constants.ServiceInstanceTypes.TFS,
);
if (!coreClient.getTeamMembers) {
coreClient = Service.VssConnection.getConnection().getHttpClient(
Tfs_Core_WebApi.CoreHttpClient4,
WebApi_Constants.ServiceInstanceTypes.TFS,
);
}
return coreClient.getTeamMembers(webContext.project.name, this._selectedTeam.name);
}
private _editEvent(event: Calendar_Contracts.IExtendedCalendarEventObject): void {
const oldEvent = this._eventObjectToCalendarEvent(event);
const calendarEvent = $.extend({}, oldEvent);
const eventSource: Calendar_Contracts.IEventSource = this._getEventSourceFromEvent(event);
if (eventSource && eventSource.updateEvent) {
const query = this._calendar.getViewQuery();
const dialogOptions: Calendar_Dialogs.IEventDialogOptions = {
calendarEvent: calendarEvent,
source: eventSource,
resizable: true,
isEdit: true,
membersPromise: this._getTeamMembers(),
query: query,
bowtieVersion: 2,
okCallback: (calendarEvent: Calendar_Contracts.CalendarEvent) => {
eventSource.updateEvent(oldEvent, calendarEvent).then((updatedEvent: Calendar_Contracts.CalendarEvent) => {
// Set underlying source to dirty so refresh picks up new changes
const originalEventSource = this._getCalendarEventSource(eventSource.id);
originalEventSource.state.dirty = true;
if (updatedEvent) {
// Update title
event.title = updatedEvent.title;
// Update category
event.category = updatedEvent.category;
// Update color
event.color = updatedEvent.category.color;
// Update description
event.description = updatedEvent.description;
// Update data
event.eventData = updatedEvent.eventData;
//Update dates
event.end = Utils_Date.addDays(new Date(updatedEvent.endDate), 1).toISOString();
event.start = updatedEvent.startDate;
event.__etag = updatedEvent.__etag;
// Update iteration
event.iterationId = updatedEvent.iterationId;
this._calendar.updateEvent(event as any);
} else {
this._calendar.refreshEvents(originalEventSource);
}
});
},
};
//Calendar_Dialogs.ExternalEventDialog.showDialog(dialogOptions);
Controls_Dialogs.Dialog.show(Calendar_Dialogs.EditEventDialog, dialogOptions);
}
}
private _deleteEvent(event: Calendar_Contracts.IExtendedCalendarEventObject): void {
const calendarEvent = this._eventObjectToCalendarEvent(event);
const eventSource: Calendar_Contracts.IEventSource = this._getEventSourceFromEvent(event);
if (eventSource && eventSource.removeEvent) {
if (confirm("Are you sure you want to delete the event?")) {
eventSource.removeEvent(calendarEvent).then((calendarEvents: Calendar_Contracts.CalendarEvent[]) => {
const originalEventSource = this._getCalendarEventSource(eventSource.id);
originalEventSource.state.dirty = true;
this._calendar.removeEvent(event.id as string);
if (!calendarEvents) {
this._calendar.refreshEvents(originalEventSource);
}
});
}