-
Notifications
You must be signed in to change notification settings - Fork 161
/
Copy pathc-summary.vue
1049 lines (940 loc) · 36.9 KB
/
c-summary.vue
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
<template lang="pug">
#summary
form.summary-picker.mui-form--inline(v-if="!isWidgetMode", onsubmit="return false;")
.summary-picker__section
.mui-textfield.search_box
input(type="text", v-on:change="updateFilterSearch", v-model="filterSearch")
label search
button.mui-btn.mui-btn--raised(type="button", v-on:click.prevent="resetFilterSearch") x
.mui-select.grouping
select(v-model="filterGroupSelection")
option(value="groupByNone") None
option(value="groupByRepos") Repo/Branch
option(value="groupByAuthors") Author
label group by
.mui-select.sort-group
select(v-model="sortGroupSelection", v-on:change="getFiltered")
option(value="groupTitle") ↑ group title
option(value="groupTitle dsc") ↓ group title
option(value="totalCommits") ↑ contribution
option(value="totalCommits dsc") ↓ contribution
option(value="variance") ↑ variance
option(value="variance dsc") ↓ variance
label sort groups by
.mui-select.sort-within-group
select(
v-model="sortWithinGroupSelection",
v-bind:disabled="filterGroupSelection === 'groupByNone' || allGroupsMerged",
v-on:change="getFiltered"
)
option(value="title") ↑ title
option(value="title dsc") ↓ title
option(value="totalCommits") ↑ contribution
option(value="totalCommits dsc") ↓ contribution
option(value="variance") ↑ variance
option(value="variance dsc") ↓ variance
label sort within groups by
.mui-select.granularity
select(v-model="filterTimeFrame", v-on:change="getFiltered")
option(value="commit") Commit
option(value="day") Day
option(value="week") Week
label granularity
.mui-textfield
input(v-if="isSafariBrowser", type="text", placeholder="yyyy-mm-dd",
v-bind:value="filterSinceDate", v-on:keyup.enter="updateTmpFilterSinceDate",
onkeydown="formatInputDateOnKeyDown(event)", oninput="appendDashInputDate(event)", maxlength=10)
input(v-else, type="date", name="since", v-bind:value="filterSinceDate", v-on:input="updateTmpFilterSinceDate",
v-bind:min="minDate", v-bind:max="filterUntilDate")
label since
.mui-textfield
input(v-if="isSafariBrowser", type="text", placeholder="yyyy-mm-dd",
v-bind:value="filterUntilDate", v-on:keyup.enter="updateTmpFilterUntilDate",
onkeydown="formatInputDateOnKeyDown(event)", oninput="appendDashInputDate(event)", maxlength=10)
input(v-else, type="date", name="until", v-bind:value="filterUntilDate", v-on:input="updateTmpFilterUntilDate",
v-bind:min="filterSinceDate", v-bind:max="maxDate")
label until
.mui-textfield
a(v-on:click="resetDateRange") Reset date range
.summary-picker__checkboxes.summary-picker__section
label.filter-breakdown
input.mui-checkbox(
type="checkbox",
v-model="filterBreakdown",
v-on:change="toggleBreakdown"
)
span breakdown by file type
label.merge-group(
v-bind:style="filterGroupSelection === 'groupByNone' ? { opacity:0.5 } : { opacity:1.0 }"
)
input.mui-checkbox(
type="checkbox",
v-model="allGroupsMerged",
v-bind:disabled="filterGroupSelection === 'groupByNone'"
)
span merge all groups
label.show-tags
input.mui-checkbox(
type="checkbox",
v-model="viewRepoTags",
v-on:change="getFiltered"
)
span show tags
label.optimise-timeline
input.mui-checkbox(
type="checkbox",
v-model="optimiseTimeline",
v-on:change="getFiltered"
)
span trim timeline
.error-message-box(v-if="Object.entries(errorMessages).length && !isWidgetMode")
.error-message-box__close-button(v-on:click="dismissTab($event)") ×
.error-message-box__message The following issues occurred when analyzing the following repositories:
.error-message-box__failed-repo(
v-for="errorBlock in errorIsShowingMore\
? errorMessages\
: Object.values(errorMessages).slice(0, numberOfErrorMessagesToShow)"
)
font-awesome-icon(icon="exclamation")
span.error-message-box__failed-repo--name {{ errorBlock.repoName }}
.error-message-box__failed-repo--reason(
v-if="errorBlock.errorMessage.startsWith('Unexpected error stack trace')"
)
span Oops, an unexpected error occurred. If this is due to a problem in RepoSense, please report in
a(
v-bind:href="getReportIssueGitHubLink(errorBlock.errorMessage)", target="_blank"
)
strong our issue tracker
span or email us at
a(
v-bind:href="getReportIssueEmailLink(errorBlock.errorMessage)"
)
span {{ getReportIssueEmailAddress() }}
.error-message-box__failed-repo--reason(v-else) {{ errorBlock.errorMessage }}\
.error-message-box__show-more-container(v-if="Object.keys(errorMessages).length > numberOfErrorMessagesToShow")
span(v-if="!errorIsShowingMore") Remaining error messages omitted to save space.
a(v-if="!errorIsShowingMore", v-on:click="toggleErrorShowMore()") SHOW ALL...
a(v-else, v-on:click="toggleErrorShowMore()") SHOW LESS...
.fileTypes(v-if="filterBreakdown && !isWidgetMode")
c-file-type-checkboxes(
v-bind:file-types="fileTypes",
v-bind:file-type-colors="fileTypeColors",
v-model:selected-file-types="checkedFileTypes",
@update:selected-file-types="getFiltered"
)
c-summary-charts(
v-bind:filtered="filtered",
v-bind:checked-file-types="checkedFileTypes",
v-bind:avg-contribution-size="avgContributionSize",
v-bind:filter-group-selection="filterGroupSelection",
v-bind:filter-breakdown="filterBreakdown",
v-bind:filter-time-frame="filterTimeFrame",
v-bind:filter-since-date="filterSinceDate",
v-bind:filter-until-date="filterUntilDate",
v-bind:filter-search="filterSearch",
v-bind:min-date="minDate",
v-bind:max-date="maxDate",
v-bind:sort-group-selection="sortGroupSelection",
v-bind:chart-group-index="chartGroupIndex",
v-bind:chart-index="chartIndex",
v-bind:view-repo-tags="viewRepoTags",
v-bind:optimise-timeline="optimiseTimeline"
)
</template>
<script lang='ts'>
import { mapState } from 'vuex';
import { PropType, defineComponent } from 'vue';
import cSummaryCharts from '../components/c-summary-charts.vue';
import cFileTypeCheckboxes from '../components/c-file-type-checkboxes.vue';
import getNonRepeatingColor from '../utils/random-color-generator';
import sortFiltered from '../utils/repo-sorter';
import {
Commit,
DailyCommit,
Repo,
User,
isCommit,
CommitResult,
} from '../types/types';
import { ErrorMessage } from '../types/zod/summary-type';
import {
AuthorDailyContributions,
AuthorFileTypeContributions,
FileTypeAndContribution,
} from '../types/zod/commits-type';
import { ZoomInfo } from '../types/vuex.d';
import {
FilterGroupSelection, FilterTimeFrame, SortGroupSelection, SortWithinGroupSelection,
} from '../types/summary';
const dateFormatRegex = /([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))$/;
export default defineComponent({
name: 'c-summary',
components: {
cSummaryCharts,
cFileTypeCheckboxes,
},
props: {
repos: {
type: Array<Repo>,
required: true,
},
errorMessages: {
type: Object as PropType<ErrorMessage>,
default() {
return {};
},
},
isWidgetMode: {
type: Boolean,
default: false,
},
},
data(): {
checkedFileTypes: Array<string>,
fileTypes: Array<string>,
filtered: Array<Array<User>>,
filterSearch: string,
filterGroupSelection: FilterGroupSelection,
sortGroupSelection: SortGroupSelection,
sortWithinGroupSelection: SortWithinGroupSelection,
sortingOption: string,
isSortingDsc: string,
sortingWithinOption: string,
isSortingWithinDsc: string,
filterTimeFrame: FilterTimeFrame,
filterBreakdown: boolean,
tmpFilterSinceDate: string,
tmpFilterUntilDate: string,
hasModifiedSinceDate: boolean,
hasModifiedUntilDate: boolean,
filterHash: string,
minDate: string,
maxDate: string,
fileTypeColors: { [key: string]: string },
isSafariBrowser: boolean,
filterGroupSelectionWatcherFlag: boolean,
chartGroupIndex: number | undefined,
chartIndex: number | undefined,
errorIsShowingMore: boolean,
numberOfErrorMessagesToShow: number,
viewRepoTags: boolean,
optimiseTimeline: boolean,
} {
return {
checkedFileTypes: [] as Array<string>,
fileTypes: [] as Array<string>,
filtered: [] as Array<Array<User>>,
filterSearch: '',
filterGroupSelection: FilterGroupSelection.GroupByRepos,
sortGroupSelection: SortGroupSelection.GroupTitleDsc, // UI for sorting groups
sortWithinGroupSelection: SortWithinGroupSelection.Title, // UI for sorting within groups
sortingOption: '',
isSortingDsc: '',
sortingWithinOption: '',
isSortingWithinDsc: '',
filterTimeFrame: FilterTimeFrame.Commit,
filterBreakdown: false,
tmpFilterSinceDate: '',
tmpFilterUntilDate: '',
hasModifiedSinceDate: window.isSinceDateProvided,
hasModifiedUntilDate: window.isUntilDateProvided,
filterHash: '',
minDate: window.sinceDate,
maxDate: window.untilDate,
fileTypeColors: {} as { [key: string]: string },
isSafariBrowser: /.*Version.*Safari.*/.test(navigator.userAgent),
filterGroupSelectionWatcherFlag: false,
chartGroupIndex: undefined as number | undefined,
chartIndex: undefined as number | undefined,
errorIsShowingMore: false,
numberOfErrorMessagesToShow: 4,
viewRepoTags: false,
optimiseTimeline: false,
};
},
computed: {
avgContributionSize(): number {
let totalLines = 0;
let totalCount = 0;
this.repos.forEach((repo) => {
repo.users?.forEach((user) => {
if (user.checkedFileTypeContribution === undefined || user.checkedFileTypeContribution === 0) {
this.updateCheckedFileTypeContribution(user);
}
if (user.checkedFileTypeContribution && user.checkedFileTypeContribution > 0) {
totalCount += 1;
totalLines += user.checkedFileTypeContribution;
}
});
});
if (totalCount === 0) {
return 0;
}
return totalLines / totalCount;
},
allGroupsMerged: {
get(): boolean {
if (this.mergedGroups.length === 0) {
return false;
}
return this.mergedGroups.length === this.filtered.length;
},
set(value: boolean): void {
if (value) {
const mergedGroups: Array<string> = [];
this.filtered.forEach((group) => {
mergedGroups.push(this.getGroupName(group));
});
this.filtered = [];
this.$store.commit('updateMergedGroup', mergedGroups);
} else {
this.$store.commit('updateMergedGroup', []);
}
},
},
filterSinceDate(): string {
if (this.tmpFilterSinceDate && this.tmpFilterSinceDate >= this.minDate) {
return this.tmpFilterSinceDate;
}
// If user clears the since date field
return this.minDate;
},
filterUntilDate(): string {
if (this.tmpFilterUntilDate && this.tmpFilterUntilDate <= this.maxDate) {
return this.tmpFilterUntilDate;
}
return this.maxDate;
},
...mapState(['mergedGroups']),
},
watch: {
filterGroupSelection(): void {
// Deactivates watcher
if (!this.filterGroupSelectionWatcherFlag) {
return;
}
const { allGroupsMerged } = this;
this.$store.dispatch('incrementLoadingOverlayCountForceReload', 1).then(() => {
this.getFilteredRepos();
this.updateMergedGroup(allGroupsMerged);
}).then(async () => {
await this.$store.dispatch('incrementLoadingOverlayCountForceReload', -1);
});
},
'$store.state.summaryDates': function (): void {
this.hasModifiedSinceDate = true;
this.hasModifiedUntilDate = true;
this.tmpFilterSinceDate = this.$store.state.summaryDates.since;
this.tmpFilterUntilDate = this.$store.state.summaryDates.until;
window.deactivateAllOverlays();
this.getFiltered();
},
mergedGroups: {
deep: true,
handler(): void {
this.getFiltered();
},
},
},
created(): void {
this.processFileTypes();
this.renderFilterHash();
this.getFiltered();
if (this.$store.state.tabZoomInfo.isRefreshing) {
const zoomInfo = Object.assign({}, this.$store.state.tabZoomInfo);
this.restoreZoomFiltered(zoomInfo);
}
},
mounted(): void {
// Delay execution of filterGroupSelection watcher
// to prevent clearing of merged groups
setTimeout(() => {
this.filterGroupSelectionWatcherFlag = true;
}, 0);
},
methods: {
dismissTab(event: Event): void {
if (event.target instanceof Element && event.target.parentNode instanceof HTMLElement) {
event.target.parentNode.style.display = 'none';
}
},
// view functions //
getReportIssueGitHubLink(stackTrace: string): string {
return `${window.REPOSENSE_REPO_URL}/issues/new?title=${this.getReportIssueTitle()
}&body=${this.getReportIssueMessage(stackTrace)}`;
},
getReportIssueEmailAddress(): string {
return 'seer@comp.nus.edu.sg';
},
getReportIssueEmailLink(stackTrace: string): string {
return `mailto:${this.getReportIssueEmailAddress()}?subject=${this.getReportIssueTitle()
}&body=${this.getReportIssueMessage(stackTrace)}`;
},
getReportIssueTitle(): string {
return `${encodeURI('Unexpected error with RepoSense version ')}${window.repoSenseVersion}`;
},
getReportIssueMessage(message: string): string {
return encodeURI(message);
},
// model functions //
resetFilterSearch(): void {
this.filterSearch = '';
this.getFiltered();
},
updateFilterSearch(evt: Event): void {
// Only called from an input onchange event, target guaranteed to be input element
this.filterSearch = (evt.target as HTMLInputElement).value;
this.getFiltered();
},
setSummaryHash(): void {
const { addHash, encodeHash, removeHash } = window;
addHash('search', this.filterSearch);
addHash('sort', this.sortGroupSelection);
addHash('sortWithin', this.sortWithinGroupSelection);
if (this.hasModifiedSinceDate) {
addHash('since', this.filterSinceDate);
}
if (this.hasModifiedUntilDate) {
addHash('until', this.filterUntilDate);
}
addHash('timeframe', this.filterTimeFrame);
let mergedGroupsHash = this.mergedGroups.join(window.HASH_DELIMITER);
if (mergedGroupsHash.length === 0) {
mergedGroupsHash = '';
}
addHash('mergegroup', mergedGroupsHash);
addHash('groupSelect', this.filterGroupSelection);
addHash('breakdown', this.filterBreakdown);
if (this.filterBreakdown) {
const checkedFileTypesHash = this.checkedFileTypes.length > 0
? this.checkedFileTypes.join(window.HASH_DELIMITER)
: '';
addHash('checkedFileTypes', checkedFileTypesHash);
} else {
removeHash('checkedFileTypes');
}
if (this.viewRepoTags) {
addHash('viewRepoTags', 'true');
} else {
removeHash('viewRepoTags');
}
if (this.optimiseTimeline) {
addHash('optimiseTimeline', 'true');
} else {
removeHash('optimiseTimeline');
}
encodeHash();
},
renderFilterHash(): void {
const convertBool = (txt: string): boolean => (txt === 'true');
const hash = Object.assign({}, window.hashParams);
if (hash.search) { this.filterSearch = hash.search; }
if (hash.sort && Object.values(SortGroupSelection).includes(hash.sort as SortGroupSelection)) {
this.sortGroupSelection = hash.sort as SortGroupSelection;
}
if (hash.sortWithin
&& Object.values(SortWithinGroupSelection).includes(hash.sortWithin as SortWithinGroupSelection)) {
this.sortWithinGroupSelection = hash.sortWithin as SortWithinGroupSelection;
}
if (hash.timeframe && Object.values(FilterTimeFrame).includes(hash.timeframe as FilterTimeFrame)) {
this.filterTimeFrame = hash.timeframe as FilterTimeFrame;
}
if (hash.mergegroup) {
this.$store.commit(
'updateMergedGroup',
hash.mergegroup.split(window.HASH_DELIMITER),
);
}
if (hash.since && dateFormatRegex.test(hash.since)) {
this.tmpFilterSinceDate = hash.since;
}
if (hash.until && dateFormatRegex.test(hash.until)) {
this.tmpFilterUntilDate = hash.until;
}
if (hash.groupSelect && Object.values(FilterGroupSelection).includes(hash.groupSelect as FilterGroupSelection)) {
this.filterGroupSelection = hash.groupSelect as FilterGroupSelection;
}
if (hash.breakdown) {
this.filterBreakdown = convertBool(hash.breakdown);
}
if (hash.checkedFileTypes || hash.checkedFileTypes === '') {
const parsedFileTypes = hash.checkedFileTypes.split(window.HASH_DELIMITER);
this.checkedFileTypes = parsedFileTypes.filter((type) => this.fileTypes.includes(type));
}
if (hash.chartGroupIndex) {
this.chartGroupIndex = parseInt(hash.chartGroupIndex, 10);
}
if (hash.chartIndex) {
this.chartIndex = parseInt(hash.chartIndex, 10);
}
if (hash.viewRepoTags) {
this.viewRepoTags = convertBool(hash.viewRepoTags);
}
if (hash.optimiseTimeline) {
this.optimiseTimeline = convertBool(hash.optimiseTimeline);
}
},
getGroupName(group: Array<User>): string {
return window.getGroupName(group, this.filterGroupSelection);
},
isMatchSearchedUser(filterSearch: string, user: User): boolean {
return !filterSearch || filterSearch.toLowerCase()
.split(' ')
.filter(Boolean)
.some((param) => user.searchPath.includes(param));
},
isMatchSearchedTag(filterSearch: string, tag: string) {
return !filterSearch || filterSearch.toLowerCase()
.split(' ')
.filter(Boolean)
.some((param) => tag.includes(param));
},
toggleBreakdown(): void {
// Reset the file type filter
if (this.checkedFileTypes.length !== this.fileTypes.length) {
this.checkedFileTypes = this.fileTypes.slice();
}
this.getFiltered();
},
async getFiltered(): Promise<void> {
this.setSummaryHash();
window.deactivateAllOverlays();
await this.$store.dispatch('incrementLoadingOverlayCountForceReload', 1);
this.getFilteredRepos();
this.getMergedRepos();
await this.$store.dispatch('incrementLoadingOverlayCountForceReload', -1);
},
getFilteredRepos(): void {
// array of array, sorted by repo
const full: Array<Array<User>> = [];
const tagSearchPrefix = 'tag:';
// create deep clone of this.repos to not modify the original content of this.repos
// when merging groups
const groups = this.hasMergedGroups() ? JSON.parse(JSON.stringify(this.repos)) as Array<Repo> : this.repos;
if (this.filterSearch.startsWith(tagSearchPrefix)) {
const searchedTags = this.filterSearch.split(tagSearchPrefix)[1];
groups.forEach((repo) => {
const commits = repo.commits;
if (!commits) return;
const res: Array<User> = [];
Object.entries(commits.authorDailyContributionsMap).forEach(([author, contributions]) => {
contributions = contributions as Array<AuthorDailyContributions>;
const tags = contributions.flatMap((c) => c.commitResults).flatMap((r) => r.tags);
if (tags.some((tag) => tag && this.isMatchSearchedTag(searchedTags, tag))) {
const user = repo.users?.find((u) => u.name === author);
if (user) {
this.updateCheckedFileTypeContribution(user);
res.push(user);
}
}
});
if (res.length) {
full.push(res);
}
});
} else {
groups.forEach((repo) => {
const res: Array<User> = [];
// filtering
repo.users?.forEach((user) => {
if (this.isMatchSearchedUser(this.filterSearch, user)) {
this.getUserCommits(user, this.filterSinceDate, this.filterUntilDate);
if (this.filterTimeFrame === 'week') {
this.splitCommitsWeek(user, this.filterSinceDate, this.filterUntilDate);
}
this.updateCheckedFileTypeContribution(user);
res.push(user);
}
});
if (res.length) {
full.push(res);
}
});
}
this.filtered = full;
this.getOptionWithOrder();
const filterControl = {
filterGroupSelection: this.filterGroupSelection,
sortingOption: this.sortingOption,
sortingWithinOption: this.sortingWithinOption,
isSortingDsc: this.isSortingDsc,
isSortingWithinDsc: this.isSortingWithinDsc,
};
this.getOptionWithOrder();
this.filtered = sortFiltered(this.filtered, filterControl);
},
updateMergedGroup(allGroupsMerged: boolean): void {
// merge group is not allowed when group by none
// also reset merged groups
if (this.filterGroupSelection === 'groupByNone' || !allGroupsMerged) {
this.$store.commit('updateMergedGroup', []);
} else {
const mergedGroups: Array<string> = [];
this.filtered.forEach((group) => {
mergedGroups.push(this.getGroupName(group));
});
this.$store.commit('updateMergedGroup', mergedGroups);
}
},
getMergedRepos(): void {
this.filtered.forEach((group, groupIndex) => {
if (this.mergedGroups.includes(this.getGroupName(group))) {
this.mergeGroupByIndex(this.filtered, groupIndex);
}
});
},
mergeGroupByIndex(filtered: Array<Array<User>>, groupIndex: number): void {
const dateToIndexMap: { [key: string]: number } = {};
const dailyIndexMap: { [key: string]: number } = {};
const mergedCommits: Array<Commit> = [];
const mergedDailyCommits: Array<DailyCommit> = [];
const mergedFileTypeContribution: AuthorFileTypeContributions = {};
let mergedVariance = 0;
let totalMergedCheckedFileTypeCommits = 0;
filtered[groupIndex].forEach((user) => {
user.commits?.forEach((commit) => {
this.mergeCommits(commit, user, dateToIndexMap, mergedCommits);
});
user.dailyCommits.forEach((commit) => {
this.mergeCommits(commit, user, dailyIndexMap, mergedDailyCommits);
});
this.mergeFileTypeContribution(user, mergedFileTypeContribution);
totalMergedCheckedFileTypeCommits += user.checkedFileTypeContribution || 0;
mergedVariance += user.variance;
});
mergedCommits.sort(window.comparator((ele) => ele.date));
filtered[groupIndex][0].commits = mergedCommits;
filtered[groupIndex][0].dailyCommits = mergedDailyCommits;
filtered[groupIndex][0].fileTypeContribution = mergedFileTypeContribution;
filtered[groupIndex][0].variance = mergedVariance;
filtered[groupIndex][0].checkedFileTypeContribution = totalMergedCheckedFileTypeCommits;
// only take the merged group
filtered[groupIndex] = filtered[groupIndex].slice(0, 1);
},
hasMergedGroups(): boolean {
return this.mergedGroups.length > 0;
},
mergeCommits(
commit: Commit | DailyCommit,
user: User,
dateToIndexMap: { [key: string]: number },
merged: Array<Commit> | Array<DailyCommit>,
): void {
const {
commitResults, date,
} = commit;
// bind repoId to each commit
commitResults.forEach((commitResult) => {
commitResult.repoId = user.repoId;
});
if (Object.prototype.hasOwnProperty.call(dateToIndexMap, date)) {
const commitWithSameDate = merged[dateToIndexMap[date]];
commitResults.forEach((commitResult) => {
commitWithSameDate.commitResults.push(commitResult);
});
if (isCommit(commit) && isCommit(commitWithSameDate)) {
const { insertions, deletions } = commit;
commitWithSameDate.insertions += insertions;
commitWithSameDate.deletions += deletions;
}
} else {
dateToIndexMap[date] = Object.keys(dateToIndexMap).length;
merged.push(JSON.parse(JSON.stringify(commit)));
}
},
mergeFileTypeContribution(user: User, merged: AuthorFileTypeContributions): void {
Object.entries(user.fileTypeContribution).forEach((fileType) => {
const key = fileType[0];
const value = fileType[1];
if (!Object.prototype.hasOwnProperty.call(merged, key)) {
merged[key] = 0;
}
merged[key] += value;
});
},
processFileTypes(): void {
const selectedColors = ['#ffe119', '#4363d8', '#3cb44b', '#f58231', '#911eb4', '#46f0f0', '#f032e6',
'#bcf60c', '#fabebe', '#008080', '#e6beff', '#9a6324', '#fffac8', '#800000', '#aaffc3', '#808000', '#ffd8b1',
'#000075', '#808080'];
const fileTypeColors = {} as { [key: string]: string };
let i = 0;
this.repos.forEach((repo) => {
repo.users?.forEach((user) => {
Object.keys(user.fileTypeContribution).forEach((fileType) => {
if (!Object.prototype.hasOwnProperty.call(fileTypeColors, fileType)) {
if (i < selectedColors.length) {
fileTypeColors[fileType] = selectedColors[i];
i += 1;
} else {
fileTypeColors[fileType] = getNonRepeatingColor(Object.values(fileTypeColors));
}
}
if (!this.fileTypes.includes(fileType)) {
this.fileTypes.push(fileType);
}
});
});
this.fileTypeColors = fileTypeColors;
});
this.checkedFileTypes = this.fileTypes.slice();
this.$store.commit('updateFileTypeColors', this.fileTypeColors);
},
splitCommitsWeek(user: User, sinceDate: string, untilDate: string): void {
const { commits } = user;
if (commits === undefined) {
return;
}
const res: Array<Commit> = [];
const nextMondayDate = this.dateRounding(sinceDate, 0); // round up for the next monday
const nextMondayMs = (new Date(nextMondayDate)).getTime();
const sinceMs = new Date(sinceDate).getTime();
const untilMs = (new Date(untilDate)).getTime();
if (nextMondayDate <= untilDate) {
this.pushCommitsWeek(sinceMs, nextMondayMs - 1, res, commits);
this.pushCommitsWeek(nextMondayMs, untilMs, res, commits);
} else {
this.pushCommitsWeek(sinceMs, untilMs, res, commits);
}
user.commits = res;
},
pushCommitsWeek(sinceMs: number, untilMs: number, res: Array<Commit>, commits: Array<Commit>): void {
const diff = Math.round(Math.abs((untilMs - sinceMs) / window.DAY_IN_MS));
const weekInMS = window.DAY_IN_MS * 7;
for (let weekId = 0; weekId < diff / 7; weekId += 1) {
const startOfWeekMs = sinceMs + (weekId * weekInMS);
const endOfWeekMs = startOfWeekMs + weekInMS - window.DAY_IN_MS;
const endOfWeekMsWithinUntilMs = endOfWeekMs <= untilMs ? endOfWeekMs : untilMs;
const week: Commit = {
insertions: 0,
deletions: 0,
date: window.getDateStr(startOfWeekMs),
endDate: window.getDateStr(endOfWeekMsWithinUntilMs),
commitResults: [],
};
this.addLineContributionWeek(endOfWeekMsWithinUntilMs, week, commits);
if (week.commitResults.length > 0) {
res.push(week);
}
}
},
addLineContributionWeek(endOfWeekMs: number, week: Commit, commits: Array<Commit>): void {
// commits are not contiguous, meaning there are gaps of days without
// commits, so we are going to check each commit's date and make sure
// it is within the duration of a week
while (commits.length > 0
&& (new Date(commits[0].date)).getTime() <= endOfWeekMs) {
const commit = commits.shift();
// shift() never returns undefined here because we check for commits.length > 0,
// but TypeScript is unable to infer this
if (commit === undefined) {
break;
}
week.insertions += commit.insertions;
week.deletions += commit.deletions;
commit.commitResults.forEach((commitResult) => week.commitResults.push(commitResult));
}
},
getUserCommits(user: User, sinceDate: string, untilDate: string): null {
user.commits = [];
const userFirst = user.dailyCommits[0];
const userLast = user.dailyCommits[user.dailyCommits.length - 1];
if (!userFirst) {
return null;
}
if (!sinceDate || sinceDate === 'undefined') {
sinceDate = userFirst.date;
}
if (!untilDate) {
untilDate = userLast.date;
}
user.dailyCommits.forEach((commit) => {
const { date } = commit;
if (date >= sinceDate && date <= untilDate) {
const filteredCommit: DailyCommit = JSON.parse(JSON.stringify(commit));
this.filterCommitByCheckedFileTypes(filteredCommit);
if (filteredCommit.commitResults.length > 0) {
filteredCommit.commitResults.forEach((commitResult) => {
if (commitResult.messageBody !== '') {
commitResult.isOpen = true;
}
});
// The typecast is safe here as we add the insertions and deletions fields
// in the filterCommitByCheckedFileTypes method above
user.commits?.push(filteredCommit as Commit);
}
}
});
return null;
},
filterCommitByCheckedFileTypes(commit: DailyCommit): void {
let commitResults = commit.commitResults.map((result) => {
const filteredFileTypes = this.getFilteredFileTypes(result);
this.updateCommitResultWithFileTypes(result, filteredFileTypes);
return result;
});
if (!this.isAllFileTypesChecked()) {
commitResults = commitResults.filter(
(result) => Object.values(result.fileTypesAndContributionMap).length > 0,
);
}
// Typecast from DailyCommit to Commit as we add insertions and deletions fields
(commit as Commit).insertions = commitResults.reduce((acc, result) => acc + result.insertions, 0);
(commit as Commit).deletions = commitResults.reduce((acc, result) => acc + result.deletions, 0);
commit.commitResults = commitResults;
},
getFilteredFileTypes(commitResult: CommitResult): { [key: string]: { insertions: number; deletions: number; }; } {
return Object.keys(commitResult.fileTypesAndContributionMap)
.filter(this.isFileTypeChecked)
.reduce((obj: { [key: string]: FileTypeAndContribution }, fileType) => {
obj[fileType] = commitResult.fileTypesAndContributionMap[fileType];
return obj;
}, {});
},
isFileTypeChecked(fileType: string): boolean {
if (this.filterBreakdown) {
return this.checkedFileTypes.includes(fileType);
}
return true;
},
updateCommitResultWithFileTypes(
commitResult: CommitResult,
filteredFileTypes: { [key: string]: FileTypeAndContribution },
): void {
commitResult.insertions = Object.values(filteredFileTypes)
.reduce((acc, fileType) => acc + fileType.insertions, 0);
commitResult.deletions = Object.values(filteredFileTypes)
.reduce((acc, fileType) => acc + fileType.deletions, 0);
commitResult.fileTypesAndContributionMap = filteredFileTypes;
},
getOptionWithOrder(): void {
[this.sortingOption, this.isSortingDsc] = this.sortGroupSelection.split(' ');
[this.sortingWithinOption, this.isSortingWithinDsc] = this.sortWithinGroupSelection.split(' ');
},
// updating filters programically //
resetDateRange(): void {
this.hasModifiedSinceDate = false;
this.hasModifiedUntilDate = false;
this.tmpFilterSinceDate = '';
this.tmpFilterUntilDate = '';
window.removeHash('since');
window.removeHash('until');
this.getFiltered();
},
updateTmpFilterSinceDate(event: Event): void {
// Only called from an input onchange event, target guaranteed to be input element
const since = (event.target as HTMLInputElement).value;
this.hasModifiedSinceDate = true;
if (!this.isSafariBrowser) {
this.tmpFilterSinceDate = since;
(event.target as HTMLInputElement).value = this.filterSinceDate;
this.getFiltered();
} else if (dateFormatRegex.test(since) && since >= this.minDate) {
this.tmpFilterSinceDate = since;
(event.currentTarget as HTMLInputElement).style.removeProperty('border-bottom-color');
this.getFiltered();
} else {
// invalid since date detected
(event.currentTarget as HTMLInputElement).style.borderBottomColor = 'red';
}
},
updateTmpFilterUntilDate(event: Event): void {
// Only called from an input onchange event, target guaranteed to be input element
const until = (event.target as HTMLInputElement).value;
this.hasModifiedUntilDate = true;
if (!this.isSafariBrowser) {
this.tmpFilterUntilDate = until;
(event.target as HTMLInputElement).value = this.filterUntilDate;
this.getFiltered();
} else if (dateFormatRegex.test(until) && until <= this.maxDate) {
this.tmpFilterUntilDate = until;
(event.currentTarget as HTMLInputElement).style.removeProperty('border-bottom-color');
this.getFiltered();
} else {
// invalid until date detected
(event.currentTarget as HTMLInputElement).style.borderBottomColor = 'red';
}
},
updateCheckedFileTypeContribution(ele: User): void {
let validCommits = 0;
Object.keys(ele.fileTypeContribution).forEach((fileType) => {
if (!this.filterBreakdown) {
validCommits += ele.fileTypeContribution[fileType];
} else if (this.checkedFileTypes.includes(fileType)) {
validCommits += ele.fileTypeContribution[fileType];
}
});
ele.checkedFileTypeContribution = validCommits;
},
restoreZoomFiltered(info: ZoomInfo): void {
const {
zSince, zUntil, zTimeFrame, zIsMerged, zFilterSearch,
} = info;
const filtered: Array<Array<User>> = [];
const groups: Array<Repo> = JSON.parse(JSON.stringify(this.repos));
const res: Array<User> = [];
groups.forEach((repo) => {
repo.users?.forEach((user) => {
// only filter users that match with zoom user and previous searched user
if (this.matchZoomUser(info, user) && this.isMatchSearchedUser(zFilterSearch, user)) {
this.getUserCommits(user, zSince, zUntil);
if (zTimeFrame === 'week') {
this.splitCommitsWeek(user, zSince, zUntil);
}
this.updateCheckedFileTypeContribution(user);
res.push(user);
}
});
});
if (res.length) {
filtered.push(res);
}
if (zIsMerged) {
this.mergeGroupByIndex(filtered, 0);
}
if (filtered.length) [[info.zUser]] = filtered;
info.zFileTypeColors = this.fileTypeColors;
info.isRefreshing = false;
this.$store.commit('updateTabZoomInfo', info);