forked from angular-gantt/angular-gantt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
angular-gantt.js
2524 lines (2139 loc) · 99.7 KB
/
angular-gantt.js
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
/*
Project: Gantt chart for Angular.js
Author: Marco Schweighauser (2013)
License: MIT License. See README.md
*/
var gantt = angular.module('gantt', []);
gantt.directive('gantt', ['Gantt', 'dateFunctions', 'mouseOffset', 'debounce', 'keepScrollPos', function (Gantt, df, mouseOffset, debounce, keepScrollPos) {
return {
restrict: "EA",
replace: true,
templateUrl: function (tElement, tAttrs) {
if (tAttrs.templateUrl === undefined) {
return "template/gantt.tmpl.html";
} else {
return tAttrs.templateUrl;
}
},
scope: {
sortMode: "=?", // Possible modes: 'name', 'date', 'custom'
viewScale: "=?", // Possible scales: 'hour', 'day', 'week', 'month'
columnWidth: "=?", // Defines the size of a column, 1 being 1em per unit (hour or day, .. depending on scale),
columnSubScale: "=?", // Defines how precise tasks should be positioned inside columns. 4 = in quarter steps, 2 = in half steps, ... Use values higher than 24 or 60 (hour view) to display them very accurate. Default (4)
allowTaskMoving: "=?", // Set to true if tasks should be moveable by the user.
allowTaskResizing: "=?", // Set to true if tasks should be resizable by the user.
allowTaskRowSwitching: "=?", // If false then tasks can be moved inside their current row only. The user can not move it to another row.
allowRowSorting: "=?", // Set to true if the user should be able to re-order rows.
allowLabelsResizing: "=?", // Set to true if the user should be able to resize the label section.
fromDate: "=?", // If not specified will use the earliest task date (note: as of now this can only expand not shrink)
toDate: "=?", // If not specified will use the latest task date (note: as of now this can only expand not shrink)
firstDayOfWeek: "=?", // 0=Sunday, 1=Monday, ... Default (1)
weekendDays: "=?", // Array of days: 0=Sunday, 1=Monday, ... Default ([0,6])
showWeekends: "=?", // True if the weekends shall be displayed Default (true)
workHours: "=?", // Array of valid work hours. Default ([8,9,..,16] equals a 8am - 17pm workday)
showNonWorkHours: "=?", // True if the non work hours shall be displayed Default (true)
autoExpand: "=?", // Set this both, left or right if the date range shall expand if the user scroll to the left or right end. Otherwise set to false or none.
maxHeight: "=?", // Define the maximum height of the Gantt in PX. > 0 to activate max height behaviour.
labelsWidth: "=?", // Define the width of the labels section. Changes when the user is resizing the labels width
showTooltips: "=?", // True when tooltips shall be enabled. Default (true)
data: "=?",
loadData: "&",
removeData: "&",
clearData: "&",
centerDate: "&",
onLabelsResized: "&",
onLabelClicked: "&",
onLabelDblClicked: "&",
onLabelContextClicked: "&",
onLabelHeaderClicked: "&",
onLabelHeaderDblClicked: "&",
onLabelHeaderContextClicked: "&",
onGanttReady: "&",
onRowAdded: "&",
onRowClicked: "&",
onRowDblClicked: "&",
onRowContextClicked: "&",
onRowUpdated: "&",
onScroll: "&",
onTaskClicked: "&",
onTaskDblClicked: "&",
onTaskContextClicked: "&",
onTaskUpdated: "&",
onTaskMoveBegin: "&",
onTaskMoveEnd: "&",
onTaskResizeBegin: "&",
onTaskResizeEnd: "&"
},
controller: ['$scope', '$element', function ($scope, $element) {
// Initialize defaults
if ($scope.sortMode === undefined) $scope.sortMode = "name";
if ($scope.viewScale === undefined) $scope.viewScale = "day";
if ($scope.columnWidth === undefined) $scope.columnWidth = 2;
if ($scope.columnSubScale === undefined) $scope.columnSubScale = 4;
if ($scope.allowTaskMoving === undefined) $scope.allowTaskMoving = true;
if ($scope.allowTaskResizing === undefined) $scope.allowTaskResizing = true;
if ($scope.allowTaskRowSwitching === undefined) $scope.allowTaskRowSwitching = true;
if ($scope.allowRowSorting === undefined) $scope.allowRowSorting = true;
if ($scope.allowLabelsResizing === undefined) $scope.allowLabelsResizing = true;
if ($scope.firstDayOfWeek === undefined) $scope.firstDayOfWeek = 1;
if ($scope.weekendDays === undefined) $scope.weekendDays = [0,6];
if ($scope.showWeekends === undefined) $scope.showWeekends = true;
if ($scope.workHours === undefined) $scope.workHours = [8,9,10,11,12,13,14,15,16];
if ($scope.showNonWorkHours === undefined) $scope.showNonWorkHours = true;
if ($scope.maxHeight === undefined) $scope.maxHeight = 0;
if ($scope.autoExpand === undefined) $scope.autoExpand = "none";
if ($scope.labelsWidth === undefined) $scope.labelsWidth = 0;
if ($scope.showTooltips === undefined) $scope.showTooltips = true;
// Gantt logic
$scope.gantt = new Gantt($scope.viewScale, $scope.columnWidth, $scope.columnSubScale, $scope.firstDayOfWeek, $scope.weekendDays, $scope.showWeekends, $scope.workHours, $scope.showNonWorkHours);
$scope.gantt.expandDefaultDateRange($scope.fromDate, $scope.toDate);
$scope.ganttHeader = $element.children()[1];
$scope.ganttScroll = angular.element($element.children()[2]);
$scope.$watch("sortMode", function (newValue, oldValue) {
if (!angular.equals(newValue, oldValue)) {
$scope.sortRows();
}
});
$scope.$watch("data", function (newValue, oldValue) {
if (!angular.equals(newValue, oldValue)) {
$scope.removeAllData();
$scope.setData(newValue);
}
});
// Add a watcher if a view related setting changed from outside of the Gantt. Update the gantt accordingly if so.
// All those changes need a recalculation of the header columns
$scope.$watch('viewScale+columnWidth+columnSubScale+firstDayOfWeek+weekendDays+showWeekends+workHours+showNonWorkHours', function(newValue, oldValue) {
if (!angular.equals(newValue, oldValue)) {
$scope.gantt.setViewScale($scope.viewScale, $scope.columnWidth, $scope.columnSubScale, $scope.firstDayOfWeek, $scope.weekendDays, $scope.showWeekends, $scope.workHours, $scope.showNonWorkHours);
if (!$scope.gantt.reGenerateColumns()) {
// Re-generate failed, e.g. because there was no previous date-range. Try to apply the default range.
$scope.gantt.expandDefaultDateRange($scope.fromDate, $scope.toDate);
}
}
});
$scope.$watch('fromDate+toDate', function(newValue, oldValue) {
if (!angular.equals(newValue, oldValue)) {
$scope.gantt.expandDefaultDateRange($scope.fromDate, $scope.toDate);
}
});
$scope.getPxToEmFactor = function() {
return $scope.ganttScroll.children()[0].offsetWidth / $scope.gantt.width;
};
// Swaps two rows and changes the sort order to custom to display the swapped rows
$scope.swapRows = function (a, b) {
$scope.gantt.swapRows(a, b);
// Raise change events
$scope.raiseRowUpdatedEvent(a, true);
$scope.raiseRowUpdatedEvent(b, true);
// Switch to custom sort mode and trigger sort
if ($scope.sortMode !== "custom") {
$scope.sortMode = "custom"; // Sort will be triggered by the watcher
} else {
$scope.sortRows();
}
};
// Sort rows by the current sort mode
$scope.sortRows = function () {
$scope.gantt.sortRows($scope.sortMode);
};
// Scroll to the specified x
$scope.scrollTo = function(x) {
$scope.ganttScroll[0].scrollLeft = x;
$scope.ganttScroll.triggerHandler('scroll');
};
// Scroll to the left side by specified x
$scope.scrollLeft = function(x) {
$scope.ganttScroll[0].scrollLeft -= x;
$scope.ganttScroll.triggerHandler('scroll');
};
// Scroll to the right side by specified x
$scope.scrollRight = function(x) {
$scope.ganttScroll[0].scrollLeft += x;
$scope.ganttScroll.triggerHandler('scroll');
};
// Tries to center the specified date
$scope.scrollToDate = function(date) {
var column = $scope.gantt.getColumnByDate(date);
if (column !== undefined) {
var x = (column.left + column.width / 2) * $scope.getPxToEmFactor();
$scope.ganttScroll[0].scrollLeft = x - $scope.ganttScroll[0].offsetWidth/2;
}
};
$scope.autoExpandColumns = keepScrollPos($scope, function(el, date, direction) {
if ( $scope.autoExpand !== "both" && $scope.autoExpand !== true && $scope.autoExpand !== direction ){
return;
}
var from, to;
var expandHour = 1, expandDay = 31;
if (direction === "left") {
from = $scope.viewScale === "hour" ? df.addDays(date, -expandHour, true) : df.addDays(date, -expandDay, true);
to = date;
} else {
from = date;
to = $scope.viewScale === "hour" ? df.addDays(date, expandHour, true) : df.addDays(date, expandDay, true);
}
$scope.gantt.expandDefaultDateRange(from, to);
});
$scope.raiseLabelsResized = function(width) {
$scope.onLabelsResized({ event: { width: width } });
};
$scope.raiseLabelClickedEvent = function(evt, row) {
$scope.onLabelClicked({ event: { evt: evt, row: row, userTriggered: true } });
};
$scope.raiseLabelDblClickedEvent = function(evt, row) {
$scope.onLabelDblClicked({ event: { evt: evt, row: row, userTriggered: true } });
};
$scope.raiseLabelContextMenuEvent = function(evt, row) {
$scope.onLabelContextClicked({ event: { evt: evt, row: row, userTriggered: true } });
};
$scope.raiseLabelHeaderClickedEvent = function(evt) {
$scope.onLabelHeaderClicked({ event: { evt: evt, userTriggered: true } });
};
$scope.raiseLabelHeaderDblClickedEvent = function(evt) {
$scope.onLabelHeaderDblClicked({ event: { evt: evt, userTriggered: true } });
};
$scope.raiseLabelHeaderContextMenuEvent = function(evt) {
$scope.onLabelHeaderContextClicked({ event: { evt: evt, userTriggered: true } });
};
$scope.raiseRowAddedEvent = function(row, userTriggered) {
$scope.onRowAdded({ event: { row: row, userTriggered: userTriggered } });
};
$scope.raiseDOMRowClickedEvent = function(e, row) {
var x = mouseOffset.getOffset(e).x;
var xInEm = x / $scope.getPxToEmFactor();
var clickedColumn = $scope.gantt.getColumnByPosition(xInEm);
var date = $scope.gantt.getDateByPosition(xInEm);
$scope.raiseRowClickedEvent(e, row, clickedColumn, date);
};
$scope.raiseRowClickedEvent = function(evt, row, column, date) {
$scope.onRowClicked({ event: { evt: evt, row: row, column: column.clone(), date: date, userTriggered: true } });
};
$scope.raiseDOMRowDblClickedEvent = function(e, row) {
var x = mouseOffset.getOffset(e).x;
var xInEm = x / $scope.getPxToEmFactor();
var clickedColumn = $scope.gantt.getColumnByPosition(xInEm);
var date = $scope.gantt.getDateByPosition(xInEm);
$scope.raiseRowDblClickedEvent(e, row, clickedColumn, date);
};
$scope.raiseRowDblClickedEvent = function(evt, row, column, date) {
$scope.onRowDblClicked({ event: { evt: evt, row: row, column: column.clone(), date: date, userTriggered: true } });
};
$scope.raiseDOMRowContextMenuEvent = function(e, row) {
var x = mouseOffset.getOffset(e).x;
var xInEm = x / $scope.getPxToEmFactor();
var clickedColumn = $scope.gantt.getColumnByPosition(xInEm);
var date = $scope.gantt.getDateByPosition(xInEm);
$scope.raiseRowContextMenuEvent(e, row, clickedColumn, date);
};
$scope.raiseRowContextMenuEvent = function(evt, row, column, date) {
$scope.onRowContextClicked({ event: { evt: evt, row: row, column: column.clone(), date: date, userTriggered: true } });
};
$scope.raiseRowUpdatedEvent = function(row, userTriggered) {
$scope.onRowUpdated({ event: { row: row, userTriggered: userTriggered } });
};
$scope.raiseScrollEvent = debounce(function() {
if ($scope.gantt.getDateRange() === undefined) {
return;
}
var el = $scope.ganttScroll[0];
var direction;
var date;
if (el.scrollLeft === 0) {
direction = 'left';
date = $scope.gantt.getDateRange().from;
} else if (el.offsetWidth + el.scrollLeft >= el.scrollWidth) {
direction = 'right';
date = $scope.gantt.getDateRange().to;
}
if (date !== undefined) {
$scope.autoExpandColumns(el, date, direction);
$scope.onScroll({ event: { date: date, direction: direction, userTriggered: true }});
}
}, 5);
$scope.raiseTaskUpdatedEvent = function(task, userTriggered) {
$scope.onTaskUpdated({ event: { task: task, userTriggered: userTriggered } });
};
$scope.raiseTaskMoveStartEvent = function(task) {
$scope.onTaskMoveBegin({ event: { task: task, userTriggered: true } });
};
$scope.raiseTaskMoveEndEvent = function(task) {
$scope.onTaskMoveEnd({ event: { task: task, userTriggered: true } });
};
$scope.raiseTaskResizeStartEvent = function(task) {
$scope.onTaskResizeBegin({ event: { task: task, userTriggered: true } });
};
$scope.raiseTaskResizeEndEvent = function(task) {
$scope.onTaskResizeEnd({ event: { task: task, userTriggered: true } });
};
$scope.raiseTaskClickedEvent = function(evt, task) {
$scope.onTaskClicked({ event: { evt: evt, task: task, userTriggered: true } });
};
$scope.raiseTaskDblClickedEvent = function(evt, task) {
$scope.onTaskDblClicked({ event: { evt: evt, task: task, userTriggered: true } });
};
$scope.raiseTaskContextMenuEvent = function(evt, task) {
$scope.onTaskContextClicked({ event: { evt: evt, task: task, userTriggered: true } });
};
// Add or update rows and tasks
$scope.setData = keepScrollPos($scope, function (data) {
$scope.gantt.addData(data,
function(row) {
$scope.raiseRowAddedEvent(row, false);
}, function(row) {
$scope.raiseRowUpdatedEvent(row, false);
});
$scope.sortRows();
});
// Remove specified rows and tasks.
$scope.removeData({ fn: function(data) {
$scope.gantt.removeData(data, function(row) {
$scope.raiseRowUpdatedEvent(row, false);
});
$scope.sortRows();
}});
// Clear all existing rows and tasks
$scope.removeAllData = function() {
// Clears rows, task and columns
$scope.gantt.removeAllRows();
// Restore default columns
$scope.gantt.expandDefaultDateRange($scope.fromDate, $scope.toDate);
};
// Bind scroll event
$scope.ganttScroll.bind('scroll', $scope.raiseScrollEvent);
// Load data handler.
// The Gantt chart will keep the current view position if this function is called during scrolling.
$scope.loadData({ fn: $scope.setData});
// Clear data handler.
$scope.clearData({ fn: $scope.removeAllData});
// Scroll to specified date handler.
$scope.centerDate({ fn: $scope.scrollToDate});
// Gantt is initialized. Signal that the Gantt is ready.
$scope.onGanttReady();
}
]};
}]);
;gantt.factory('Column', [ 'dateFunctions', function (df) {
// Used to display the Gantt grid and header.
// The columns are generated by the column generator.
var calcDbyP = function(column, maxDateValue, currentPosition) {
return Math.round(maxDateValue/column.width * currentPosition / (maxDateValue / column.subScale)) * (maxDateValue / column.subScale);
};
var calcPbyD = function(column, date, maxDateValue, currentDateValue, a, b) {
var factor;
if (date - column.date > 0 && a !== b) {
factor = 1;
} else {
factor = Math.round(currentDateValue/maxDateValue * column.subScale) / column.subScale;
}
return Math.round( (column.left + column.width * factor) * 10) / 10;
};
var Column = function(date, left, width, subScale) {
var self = this;
self.date = date;
self.left = left;
self.width = width;
self.subScale = subScale;
self.clone = function() {
return new Column(self.date, self.left, self.width, self.subScale);
};
self.equals = function(other) {
return self.date === other.date;
};
};
var MonthColumn = function(date, left, width, subScale) {
var column = new Column(date, left, width, subScale);
column.daysInMonth = df.getDaysInMonth(column.date);
column.clone = function() {
return new Column(column.date, column.left, column.width, column.subScale);
};
column.getDateByPosition = function(position) {
if (position < 0) position = 0;
if (position > column.width) position = column.width;
var res = df.clone(column.date);
res.setDate(1 + calcDbyP(column, column.daysInMonth, position));
return res;
};
column.getPositionByDate = function(date) {
return calcPbyD(column, date, column.daysInMonth, date.getDate(), date.getMonth(), column.date.getMonth());
};
return column;
};
var WeekColumn = function(date, left, width, subScale, firstDayOfWeek) {
var column = new Column(date, left, width, subScale);
column.week = df.getWeek(date);
column.firstDayOfWeek = firstDayOfWeek;
column.daysInWeek = 7;
column.clone = function() {
var copy = new Column(column.date, column.left, column.width, column.subScale);
copy.week = column.week;
return copy;
};
// Adjusts the day so that the specified first day of week is index = 0
var firstDayIs0 = function(day) {
return ((column.daysInWeek - column.firstDayOfWeek) + day) % column.daysInWeek;
};
// Adjusts the day so that Sunday= 0, Monday = 1, ...
var firstDayIsSunday = function(day) {
return (column.firstDayOfWeek + day) % column.daysInWeek;
};
var getWeek = function(date) {
if (column.firstDayOfWeek !== 1) {
// Adjust date so that firstDayOfWeek is always Monday because df.getWeek returns a ISO week number which starts on Monday.
// Otherwise if for e.g. firstDayOfWeek is 0 the Sunday would be in week number X while Monday would be in week number Y.
df.getWeek(df.addDays(date, 1 - column.firstDayOfWeek, true));
} else {
return df.getWeek(date);
}
};
column.getDateByPosition = function(position) {
if (position < 0) position = 0;
if (position > column.width) position = column.width;
var res = df.clone(column.date);
var day = Math.round(calcDbyP(column, column.daysInWeek, position));
// If day === 7, then jump forward to next week
var direction = day !== 7 && day < 0 ? -1: 1; // -1: <<<<< | 1: >>>>>
df.setToDayOfWeek(res, day !== 7 ? firstDayIsSunday(day): firstDayIsSunday(day) + 7, false, direction);
return res;
};
column.getPositionByDate = function(date) {
return calcPbyD(column, date, column.daysInWeek, firstDayIs0(date.getDay()), getWeek(date), getWeek(column.date));
};
return column;
};
var DayColumn = function(date, left, width, subScale, isWeekend, daysToNextWorkingDay, daysToPrevWorkingDay, workHours, showNonWorkHours) {
var column = new Column(date, left, width, subScale);
column.isWeekend = isWeekend;
column.showNonWorkHours = showNonWorkHours;
var startHour = 0;
var endHour = 24;
if(arguments.length == 9 && !showNonWorkHours && workHours.length > 1){
startHour = workHours[0];
endHour = workHours[workHours.length-1] + 1;
}
column.clone = function() {
var copy = new Column(column.date, column.left, column.width, column.subScale);
copy.isWeekend = column.isWeekend;
return copy;
};
column.getDateByPosition = function(position, snapForward) {
if (position < 0) position = 0;
if (position > column.width) position = column.width;
var res = df.clone(column.date);
var hours = startHour + calcDbyP(column, (endHour-startHour), position);
// Snap is done because a DAY can hide the non-work hours. If this is the case the start or end date of a task shall be the last work hour of the current day and not the next day.
if(arguments.length == 2){
if (hours === endHour && snapForward){
//We have snapped to the end of one day but this is a start of a task so it should snap to the start of the next displayed day
res = df.addDays(res, daysToNextWorkingDay);
hours = startHour;
}
else if (hours === startHour && !snapForward){
//We have snapped to the start of one day but this is the end of a task so it should snap to the end of the previous displayed day
res = df.addDays(res, -daysToPrevWorkingDay);
hours = endHour;
}
}
res.setHours(hours);
return res;
};
column.getPositionByDate = function(date) {
//first check that the date actually corresponds to this column
//(it is possible that it might not if weekends are hidden, in which case this will be the nearest previous column)
if (df.setTimeZero(date,true) > df.setTimeZero(column.date, true)) return column.left + column.width;
var maxDateValue = endHour-startHour;
var currentDateValue = date.getHours()-startHour;
if (currentDateValue < 0) return column.left;
else if (currentDateValue > maxDateValue) return column.left + column.width;
else return calcPbyD(column, date, maxDateValue, currentDateValue, date.getDate(), column.date.getDate());
};
return column;
};
var HourColumn = function(date, left, width, subScale, isWeekend, isWorkHour, hoursToNextWorkingDay, hoursToPrevWorkingDay) {
var column = new Column(date, left, width, subScale);
column.isWeekend = isWeekend;
column.isWorkHour = isWorkHour;
column.clone = function() {
var copy = new Column(column.date, column.left, column.width, column.subScale);
copy.isWeekend = column.isWeekend;
copy.isWorkHour = column.isWorkHour;
return copy;
};
column.getDateByPosition = function(position, snapForward) {
if (position < 0) position = 0;
if (position > column.width) position = column.width;
var res = df.clone(column.date);
var minutes = calcDbyP(column, 60, position);
// Snap is done because a HOUR can hide the non-work hours. If this is the case the start or end date of a task shall be the last work hour of the current day and not the next day.
if(arguments.length == 2){
if (minutes === 60 && snapForward){
//We have snapped to the end of one day but this is a start of a task so it should snap to the start of the next displayed day
res = df.addHours(res, hoursToNextWorkingDay);
minutes = 0;
}
else if (minutes === 0 && !snapForward){
//We have snapped to the start of one day but this is the end of a task so it should snap to the end of the previous displayed day
res = df.addHours(res, -hoursToPrevWorkingDay);
minutes = 60;
}
}
res.setMinutes(minutes);
return res;
};
column.getPositionByDate = function(date) {
if (df.setTimeZero(date,true) > df.setTimeZero(column.date, true)) return column.left + column.width;
return calcPbyD(column, date, 60, date.getMinutes(), date.getHours(), column.date.getHours());
};
return column;
};
return {
Hour: HourColumn,
Day: DayColumn,
Week: WeekColumn,
Month: MonthColumn
};
}]);;gantt.factory('ColumnGenerator', [ 'Column', 'dateFunctions', function (Column, df) {
// Returns a map to lookup if the current day is a weekend day
var getWeekendDaysMap = function(weekendDays) {
var weekendDaysMap = {};
for (var i = 0, l = weekendDays.length; i < l; i++) {
weekendDaysMap[weekendDays[i]] = true;
}
return weekendDaysMap;
};
// Returns true if the given day is a weekend day
var checkIsWeekend = function(weekendDaysMap, day) {
return weekendDaysMap[day] === true;
};
// Returns a map to lookup if the current hour is a work hour
var getWorkHoursMap = function(workHours) {
var workHoursMap = {};
for (var i = 0, l = workHours.length; i < l; i++) {
workHoursMap[workHours[i]] = true;
}
return workHoursMap;
};
// Returns true if the given hour is a work hour
var checkIsWorkHour = function(workHoursMap, hour) {
return workHoursMap[hour] === true;
};
var HourColumnGenerator = function(columnWidth, columnSubScale, weekendDays, showWeekends, workHours, showNonWorkHours) {
// Generates 24 columns for each day between the given from and to date. The task will later be places between the matching columns.
this.generate = function(from, to) {
var excludeTo = isToDateToExclude(to);
from = df.setTimeZero(from, true);
to = df.setTimeZero(to, true);
var date = df.clone(from);
var generatedCols = [];
var left = 0;
var workHoursMap = getWorkHoursMap(workHours);
var weekendDaysMap = getWeekendDaysMap(weekendDays);
while(excludeTo && to - date > 0 || !excludeTo && to - date >= 0) {
var isWeekend = checkIsWeekend(weekendDaysMap, date.getDay());
for (var i = 0; i<24; i++) {
var cDate = new Date(date.getFullYear(), date.getMonth(), date.getDate(), i, 0, 0);
var isWorkHour = checkIsWorkHour(workHoursMap, i);
if ((isWeekend && showWeekends || !isWeekend) && (!isWorkHour && showNonWorkHours || isWorkHour)) {
var hoursToNextWorkingDay = 1;
var hoursToPrevWorkingDay = 1;
if(!showNonWorkHours) { //hours to next/prev working day is only relevant if non-work hours are hidden
hoursToNextWorkingDay = getHoursToNextWorkingDay(workHoursMap, cDate.getHours());
hoursToPrevWorkingDay = getHoursToPreviousWorkingDay(workHoursMap, cDate.getHours());
}
generatedCols.push(new Column.Hour(cDate, left, columnWidth, columnSubScale, isWeekend, isWorkHour, hoursToNextWorkingDay, hoursToPrevWorkingDay));
left += columnWidth;
}
}
date = df.addDays(date, 1);
}
return generatedCols;
};
this.columnExpandNecessary = function(firstColDate, lastColDate, newFromDate, newToDate) {
// If the To date was excluded from generating then go back one hour.
if (isToDateToExclude(newToDate)) {
newToDate = df.addHours(newToDate, -1, true);
}
// Set time of newToDate to zero before comparing as the hour columns are generated for the whole day
// and the newToDate could be e.g. 23:35 while the last column for this date has time 23:00.
// If we wouldn`t set the time to zero the comparison would trigger an expand in that case.
return firstColDate > newFromDate || lastColDate < df.setTimeZero(newToDate, true);
};
// Columns are generated including or excluding the to date.
// If the To date time is 00:00 then no new columns are generated for this day.
var isToDateToExclude = function(to) {
return df.isTimeZero(to);
};
// Returns the count of hours until the next working day
// For example with working hours from 8-16, Wed 9am would return 1, Thu 16pm would return 16
// Should also be able to handle gaps like 8-12, 13-17
var getHoursToNextWorkingDay = function(workHoursMap, hour){
for(var i = 1; i < 25; i++) {
var nextHour = (hour+i)%24;
if(checkIsWorkHour(workHoursMap, nextHour)){
return i;
}
}
return 1; //default to 1, should only get here if the whole day is a work day
};
var getHoursToPreviousWorkingDay = function(workHours, hour){
for(var i = 1; i < 25; i++) {
var prevHour = (((hour-i)%24)+24)%24;
if(checkIsWorkHour(workHours, prevHour)){
return i;
}
}
return 1; //default to 1, should only get here if the whole day is a work day
};
};
var DayColumnGenerator = function(columnWidth, columnSubScale, weekendDays, showWeekends, workHours, showNonWorkHours) {
// Generates one column for each day between the given from and to date.
this.generate = function(from, to) {
var excludeTo = isToDateToExclude(to);
from = df.setTimeZero(from, true);
to = df.setTimeZero(to, true);
var date = df.clone(from);
var generatedCols = [];
var left = 0;
var weekendDaysMap = getWeekendDaysMap(weekendDays);
while(excludeTo && to - date > 0 || !excludeTo && to - date >= 0) {
var isWeekend = checkIsWeekend(weekendDaysMap, date.getDay());
if (isWeekend && showWeekends || !isWeekend) {
var daysToNextWorkingDay = 1;
var daysToPreviousWorkingDay = 1;
if(!showWeekends){ //days to next/prev working day is only relevant if weekends are hidden
daysToNextWorkingDay = getDaysToNextWorkingDay(weekendDaysMap, date.getDay());
daysToPreviousWorkingDay = getDaysToPrevWorkingDay(weekendDaysMap, date.getDay());
}
generatedCols.push(new Column.Day(df.clone(date), left, columnWidth, columnSubScale, isWeekend, daysToNextWorkingDay, daysToPreviousWorkingDay, workHours, showNonWorkHours));
left += columnWidth;
}
date = df.addDays(date, 1);
}
return generatedCols;
};
this.columnExpandNecessary = function(firstColDate, lastColDate, newFromDate, newToDate) {
// If the To date was excluded from generating then go back one day.
if (isToDateToExclude(newToDate)) {
newToDate = df.addDays(newToDate, -1, true);
}
// Set time of newToDate to zero before comparing as the day columns generated have time 00:00
// and the newToDate could be e.g. 16:23.
// If we wouldn`t set the time to zero the comparison would trigger an expand in that case.
return firstColDate > newFromDate || lastColDate < df.setTimeZero(newToDate, true);
};
// Columns are generated including or excluding the to date.
// If the To date time is 00:00 then no new column is generated for this day.
var isToDateToExclude = function(to) {
return df.isTimeZero(to);
};
// Returns the count of days until the next working day
// For example with a Mon-Fri working week, Wed would return 1, Fri would return 3, Sat would return 2
var getDaysToNextWorkingDay = function(weekendDays, day){
for(var i = 1; i < 8; i++) {
var nextDay = (day+i)%7;
if(!checkIsWeekend(weekendDays, nextDay)){
return i;
}
}
return 1; //default to 1, should only get here if the whole week is the weekend
};
// Returns the count of days from the previous working day
// For example with a Mon-Fri working week, Wed would return 1, Mon would return 3.
var getDaysToPrevWorkingDay = function(weekendDays, day){
for(var i = 1; i < 8; i++) {
var prevDay = (((day-i)%7)+7)%7;
if(!checkIsWeekend(weekendDays, prevDay)){
return i;
}
}
return 1; //default to 1, should only get here if the whole week is the weekend
};
};
var WeekColumnGenerator = function(columnWidth, columnSubScale, firstDayOfWeek) {
// Generates one column for each week between the given from and to date.
this.generate = function(from, to) {
var excludeTo = isToDateToExclude(to);
from = df.setToDayOfWeek(df.setTimeZero(from, true), firstDayOfWeek, false);
to = df.setToDayOfWeek(df.setTimeZero(to, true), firstDayOfWeek, false);
var date = df.clone(from);
var generatedCols = [];
var left = 0;
while(excludeTo && to - date > 0 || !excludeTo && to - date >= 0) {
generatedCols.push(new Column.Week(df.clone(date), left, columnWidth, columnSubScale, firstDayOfWeek));
left += columnWidth;
date = df.addWeeks(date, 1);
}
return generatedCols;
};
this.columnExpandNecessary = function(firstColDate, lastColDate, newFromDate, newToDate) {
// If the To date was excluded from generating then go back one week.
if (isToDateToExclude(newToDate)) {
newToDate = df.addWeeks(newToDate, -1, true);
}
// Set time of newToDate to zero before comparing as the week columns generated have day = firstDayOfWeek and time = 00:00
// and the newToDate could be e.g. day 3 and time 16:23.
// If we wouldn`t set the day to firstDayOfWeek and time to zero the comparison would trigger an expand in that case.
return firstColDate > newFromDate || lastColDate < df.setToDayOfWeek(df.setTimeZero(newToDate, true), firstDayOfWeek);
};
// Columns are generated including or excluding the to date.
// If the To date is the first day of week and the time is 00:00 then no new column is generated for this week.
var isToDateToExclude = function(to) {
return to.getDay() === firstDayOfWeek && df.isTimeZero(to);
};
};
var MonthColumnGenerator = function(columnWidth, columnSubScale) {
// Generates one column for each month between the given from and to date.
this.generate = function(from, to) {
var excludeTo = isToDateToExclude(to);
from = df.setToFirstDayOfMonth(df.setTimeZero(from, true), false);
to = df.setToFirstDayOfMonth(df.setTimeZero(to, true), false);
var date = df.clone(from);
var generatedCols = [];
var left = 0;
while(excludeTo && to - date > 0 || !excludeTo && to - date >= 0) {
generatedCols.push(new Column.Month(df.clone(date), left, columnWidth, columnSubScale));
left += columnWidth;
date = df.addMonths(date, 1);
}
return generatedCols;
};
this.columnExpandNecessary = function(firstColDate, lastColDate, newFromDate, newToDate) {
// If the To date was excluded from generating then go back one month.
if (isToDateToExclude(newToDate)) {
newToDate = df.addMonths(newToDate, -1, true);
}
// Set time of newToDate to zero before comparing as the month columns generated have day = 1 and time = 00:00
// and the newToDate could be e.g. day 7 and time 16:23.
// If we wouldn`t set the day to 1 and time to zero the comparison would trigger an expand in that case.
return firstColDate > newFromDate || lastColDate < df.setToFirstDayOfMonth(df.setTimeZero(newToDate, true));
};
// Columns are generated including or excluding the to date.
// If the To date is the first day of month and the time is 00:00 then no new column is generated for this month.
var isToDateToExclude = function(to) {
return to.getDate() === 1 && df.isTimeZero(to);
};
};
return {
HourGenerator: HourColumnGenerator,
DayGenerator: DayColumnGenerator,
WeekGenerator: WeekColumnGenerator,
MonthGenerator: MonthColumnGenerator
};
}]);;gantt.factory('Gantt', ['Row', 'ColumnGenerator', 'HeaderGenerator', 'dateFunctions', 'binarySearch', function (Row, ColumnGenerator, HeaderGenerator, df, bs) {
// Gantt logic. Manages the columns, rows and sorting functionality.
var Gantt = function(viewScale, columnWidth, columnSubScale, firstDayOfWeek, weekendDays, showWeekends, workHours, showNonWorkHours) {
var self = this;
self.rowsMap = {};
self.rows = [];
self.columns = [];
self.headers = {};
self.width = 0;
var dateRange;
// Sets the Gantt view scale. Call reGenerateColumns to make changes visible after changing the view scale.
// The headers are shown depending on the defined view scale.
self.setViewScale = function(viewScale, columnWidth, columnSubScale, firstDayOfWeek, weekendDays, showWeekends, workHours, showNonWorkHours) {
switch(viewScale) {
case 'hour': self.columnGenerator = new ColumnGenerator.HourGenerator(columnWidth, columnSubScale, weekendDays, showWeekends, workHours, showNonWorkHours); break;
case 'day': self.columnGenerator = new ColumnGenerator.DayGenerator(columnWidth, columnSubScale, weekendDays, showWeekends, workHours, showNonWorkHours); break;
case 'week': self.columnGenerator = new ColumnGenerator.WeekGenerator(columnWidth, columnSubScale, firstDayOfWeek); break;
case 'month': self.columnGenerator = new ColumnGenerator.MonthGenerator(columnWidth, columnSubScale); break;
default:
throw "Unsupported view scale: " + viewScale;
}
self.headerGenerator = new HeaderGenerator.instance(viewScale);
};
self.setViewScale(viewScale, columnWidth, columnSubScale, firstDayOfWeek, weekendDays, showWeekends, workHours, showNonWorkHours);
// Expands the default date range. Even if there tasks are smaller the specified date range is shown.
self.expandDefaultDateRange = function(from, to) {
if (from !== undefined && to !== undefined) {
expandDateRange(from, to);
expandColumns();
}
};
var expandDateRange = function(from, to) {
from = df.clone(from);
to = df.clone(to);
if (dateRange === undefined) {
dateRange = {};
dateRange.from = from;
dateRange.to = to;
} else {
if (from < dateRange.from) {
dateRange.from = from;
}
if (to > dateRange.to) {
dateRange.to = to;
}
}
};
// Generates the Gantt columns according to the current dateRange. The columns are generated if necessary only.
var expandColumns = function() {
if (dateRange === undefined) {
throw "From and to date range cannot be undefined";
}
// Only expand if expand is necessary
if (self.columns.length === 0) {
expandColumnsNoCheck(dateRange.from, dateRange.to);
} else if (self.columnGenerator.columnExpandNecessary(self.getFirstColumn().date, self.getLastColumn().date, dateRange.from, dateRange.to)) {
var minFrom = self.getFirstColumn().date > dateRange.from ? dateRange.from: self.getFirstColumn().date;
var maxTo = self.getLastColumn().date < dateRange.to ? dateRange.to: self.getLastColumn().date;
expandColumnsNoCheck(minFrom, maxTo);
}
};
// Generates the Gantt columns according to the specified from - to date range. Uses the currently assigned column generator.
var expandColumnsNoCheck = function(from ,to) {
self.columns = self.columnGenerator.generate(from, to);
self.headers = self.headerGenerator.generate(self.columns);
self.updateTasksPosAndSize();
var lastColumn = self.getLastColumn();
self.width = lastColumn !== undefined ? lastColumn.left + lastColumn.width: 0;
};
// Removes all existing columns and re-generates them. E.g. after e.g. the view scale changed.
// Rows can be re-generated only if there is a data-range specified. If the re-generation failed the function returns false.
self.reGenerateColumns = function() {
self.columns = [];
if (dateRange !== undefined) {
expandColumns();
return true;
} else {
return false;
}
};
// Update the position/size of all tasks in the Gantt
self.updateTasksPosAndSize = function() {
for (var i = 0, l = self.rows.length; i < l; i++) {
for (var j = 0, k = self.rows[i].tasks.length; j < k; j++) {
self.rows[i].tasks[j].updatePosAndSize();
}
}
};
// Returns the first Gantt column or undefined
self.getLastColumn = function() {
if (self.columns.length > 0) {
return self.columns[self.columns.length-1];
} else {
return undefined;
}
};
// Returns the last Gantt column or undefined
self.getFirstColumn = function() {
if (self.columns.length > 0) {
return self.columns[0];
} else {
return undefined;
}
};
// Returns the column at the given or next possible date