Procházet zdrojové kódy

Enforce Typescript in some SFCs

Enforce Typescript in some more SFCs
Nesta Bentum před 4 roky
rodič
revize
27a4a20765

+ 28 - 25
report-viewer/src/components/ClusterRadarChart.vue

@@ -5,10 +5,7 @@
 <template>
   <div class="wrapper">
     <select v-model="selectedMember">
-      <option
-        v-for="(member, index) in Object.keys(cluster.members)"
-        :key="index"
-      >
+      <option v-for="(member, index) in cluster.members.keys()" :key="index">
         {{ member }}
       </option>
     </select>
@@ -20,11 +17,12 @@
   </div>
 </template>
 
-<script>
-import { defineComponent, ref, watch } from "vue";
+<script lang="ts">
+import { defineComponent, PropType, Ref, ref, watch } from "vue";
 import { RadarChart } from "vue-chart-3";
-import { Chart, registerables } from "chart.js";
+import { Chart, ChartData, registerables } from "chart.js";
 import ChartDataLabels from "chartjs-plugin-datalabels";
+import { ClusterListElement } from "@/model/ClusterListElement";
 
 Chart.register(...registerables);
 Chart.register(ChartDataLabels);
@@ -33,27 +31,32 @@ export default defineComponent({
   name: "ClusterRadarChart",
   components: { RadarChart },
   props: {
-    cluster: {},
+    cluster: {
+      type: Object as PropType<ClusterListElement>,
+      required: true,
+    },
   },
   setup(props) {
-    const selectedMember = ref(Object.keys(props.cluster.members)[0]);
+    const getIdOfFirstSubmission = () =>
+      props.cluster.members.keys().next().value;
+    const selectedMember = ref(getIdOfFirstSubmission());
 
-    const createLabelsFor = (member) => {
-      let matchedWith = [];
-      props.cluster.members[member].forEach((m) =>
-        matchedWith.push(m.matchedWith)
-      );
+    const createLabelsFor = (member: string): Array<string> => {
+      let matchedWith = new Array<string>();
+      props.cluster.members
+        .get(member)
+        ?.forEach((m) => matchedWith.push(m.matchedWith));
       return matchedWith;
     };
-    const createDataSetFor = (member) => {
-      let data = [];
-      props.cluster.members[member].forEach((m) =>
-        data.push(roundToTwoDecimals(m.percentage))
-      );
+    const createDataSetFor = (member: string) => {
+      let data = new Array<number>();
+      props.cluster.members
+        .get(member)
+        ?.forEach((m) => data.push(roundToTwoDecimals(m.percentage)));
       return data;
     };
-    const roundToTwoDecimals = (number) =>
-      Math.round((number + Number.EPSILON) * 100) / 100;
+    const roundToTwoDecimals = (num: number): number =>
+      Math.round((num + Number.EPSILON) * 100) / 100;
 
     const chartStyle = {
       fill: true,
@@ -65,13 +68,13 @@ export default defineComponent({
       pointHoverBorderColor: "rgb(255, 99, 132)",
     };
 
-    const chartData = ref({
-      labels: createLabelsFor(Object.keys(props.cluster.members)[0]),
+    const chartData: Ref<ChartData<"radar", (number | null)[], unknown>> = ref({
+      labels: createLabelsFor(getIdOfFirstSubmission()),
       datasets: [
         {
           ...chartStyle,
-          label: Object.keys(props.cluster.members)[0],
-          data: createDataSetFor(Object.keys(props.cluster.members)[0]),
+          label: getIdOfFirstSubmission(),
+          data: createDataSetFor(getIdOfFirstSubmission()),
         },
       ],
     });

+ 20 - 10
report-viewer/src/components/ClustersList.vue

@@ -21,30 +21,40 @@
   </div>
 </template>
 
-<script>
-import { defineComponent, ref } from "vue";
+<script lang="ts">
+import { defineComponent, ref, PropType } from "vue";
 import { GDialog } from "gitart-vue-dialog";
-import ClusterRadarChart from "@/components/ClusterRadarChart";
-
+import ClusterRadarChart from "@/components/ClusterRadarChart.vue";
+import { ClusterListElement } from "@/model/ClusterListElement";
+import { ComparisonListElement } from "@/model/ComparisonListElement";
 export default defineComponent({
   name: "ClustersList",
   components: { ClusterRadarChart, GDialog },
   props: {
-    comparison: {},
-    clusters: Array,
+    comparison: {
+      type: Object as PropType<ComparisonListElement>,
+      required: true,
+
+    },
+    clusters: {
+      type: Array<ClusterListElement>,
+      required: true
+  },
   },
 
   setup() {
     const dialog = ref(false);
     const toggleDialog = () => (dialog.value = !dialog.value);
-    const getMemberNames = (cluster) => {
-      const members = Object.keys(cluster.members);
+    const getMemberNames = (cluster: ClusterListElement) => {
+      const membersIterator = cluster.members.keys();
+      const members = Array.from(membersIterator);
       let concatenatedMembers = "";
       let i;
       const maxMembersToShow = 5;
-      for (i = 0; i < Math.min(maxMembersToShow, members.length); i++) {
+      const numOfMembersActuallyShown = Math.min(maxMembersToShow, members.length);
+      for (i = 0; i < numOfMembersActuallyShown; i++) {
         concatenatedMembers += members[i];
-        if (i < maxMembersToShow - 1) {
+        if (i < numOfMembersActuallyShown - 1) {
           concatenatedMembers += ", ";
         }
       }

+ 25 - 22
report-viewer/src/components/ComparisonsTable.vue

@@ -102,37 +102,40 @@
   </table>
 </template>
 
-<script>
-import { defineComponent, ref } from "vue";
+<script lang="ts">
+import { defineComponent, Ref, ref } from "vue";
 import router from "@/router";
 import { GDialog } from "gitart-vue-dialog";
-import ClustersList from "@/components/ClustersList";
+import ClustersList from "@/components/ClustersList.vue";
 import { useStore } from "vuex";
+import { Cluster } from "@/model/Cluster";
+import { ComparisonListElement } from "@/model/ComparisonListElement";
+import { ClusterListElement } from "@/model/ClusterListElement";
 
 export default defineComponent({
   name: "ComparisonsTable",
   components: { ClustersList, GDialog },
   props: {
     topComparisons: {
-      type: Array,
+      type: Array<ComparisonListElement>,
       required: true,
     },
     clusters: {
-      type: Array,
+      type: Array<Cluster>,
+      required: true,
     },
   },
   setup(props) {
     const store = useStore();
-    console.log(store.state.files);
-    let formattedMatchPercentage = (number) => number.toFixed(2);
-    const dialog = ref([]);
+    let formattedMatchPercentage = (num: number) => num.toFixed(2);
+    const dialog :Ref<Array<boolean>> = ref([]);
     props.topComparisons.forEach(() => dialog.value.push(false));
 
-    const toggleDialog = (index) => {
+    const toggleDialog = (index:number) => {
       dialog.value[index] = true;
     };
 
-    const navigateToComparisonView = (firstId, secondId) => {
+    const navigateToComparisonView = (firstId: string, secondId: string) => {
       if (!store.state.single) {
         router.push({
           name: "ComparisonView",
@@ -141,18 +144,18 @@ export default defineComponent({
       }
     };
 
-    const isInCluster = (id1, id2) => {
+    const isInCluster = (id1: string, id2: string) => {
       return props.clusters.some(
-        (c) => c.members.includes(id1) && c.members.includes(id2)
+        (c: Cluster) => c.members.includes(id1) && c.members.includes(id2)
       );
     };
 
-    const isAnonymous = (id) => {
+    const isAnonymous = (id: string) => {
       return store.state.anonymous.has(id);
     };
 
-    const getParticipatingMatchesForId = (id, others) => {
-      let matches = [];
+    const getParticipatingMatchesForId = (id: string, others : Array<string>) => {
+      let matches : Array<{matchedWith: string, percentage: number,}>= [];
       props.topComparisons.forEach((comparison) => {
         if (
           comparison.firstSubmissionId.includes(id) &&
@@ -175,11 +178,11 @@ export default defineComponent({
       return matches;
     };
 
-    const clustersWithParticipatingMatches = props.clusters.map((cluster) => {
-      let membersArray = {};
-      cluster.members.forEach((member) => {
+    const clustersWithParticipatingMatches: Array<ClusterListElement> = props.clusters.map((cluster) => {
+      let membersArray = new Map<string,Array<{matchedWith: string, percentage: number,}>>();
+      cluster.members.forEach((member: string) => {
         let others = cluster.members.filter((m) => !m.includes(member));
-        membersArray[member] = getParticipatingMatchesForId(member, others);
+        membersArray.set(member ,getParticipatingMatchesForId(member, others));
       });
 
       return {
@@ -189,11 +192,11 @@ export default defineComponent({
       };
     });
 
-    const getClustersFor = (id1, id2) => {
+    const getClustersFor = (id1: string, id2: string) : Array<ClusterListElement> => {
       return clustersWithParticipatingMatches.filter(
         (c) =>
-          Object.keys(c.members).includes(id1) &&
-          Object.keys(c.members).includes(id2)
+          c.members.has(id1) &&
+          c.members.has(id2)
       );
     };
 

+ 33 - 31
report-viewer/src/components/FilesContainer.vue

@@ -5,63 +5,65 @@
   <div class="files-container">
     <h1>Files of {{ filesOwner }}</h1>
     <VueDraggableNext>
-      <CodePanel v-for="(file, index) in Object.keys(files)"
-                 :key="file.concat(index)"
-                 :collapse="files[file].collapsed"
-                 :file-index="index"
-                 :lines="files[file].lines"
-                 :matches="!matches[file] ? [] : matches[file]"
-                 :panel-id="containerId"
-                 :title="file"
-                 @toggle-collapse="$emit('toggle-collapse', file)"
-                 @line-selected="lineSelected"
+      <CodePanel
+        v-for="(file, index) in files.keys()"
+        :key="file.concat(index.toString())"
+        :collapse="files.get(file)?.collapsed"
+        :file-index="index"
+        :lines="!files.get(file)?.lines ? [] : files.get(file)?.lines"
+        :matches="!matches.get(file) ? [] : matches.get(file)"
+        :panel-id="containerId"
+        :title="file"
+        @toggle-collapse="$emit('toggle-collapse', file)"
+        @line-selected="lineSelected"
       />
     </VueDraggableNext>
   </div>
 </template>
 
-<script>
-import {defineComponent} from "vue";
-import CodePanel from "@/components/CodePanel";
-import {VueDraggableNext} from "vue-draggable-next"
+<script lang="ts">
+import { defineComponent } from "vue";
+import CodePanel from "../components/CodePanel.vue";
+import { VueDraggableNext } from "vue-draggable-next";
+import { SubmissionFile } from "@/model/SubmissionFile";
+import { MatchInSingleFile } from "@/model/MatchInSingleFile";
 
 export default defineComponent({
   name: "FilesContainer",
-  components: {CodePanel, VueDraggableNext},
+  components: { CodePanel, VueDraggableNext },
   props: {
     /**
      * Id of the files container. We have only two so it is either 1 or 2.
      */
     containerId: {
       type: Number,
-      required: true
+      required: true,
     },
     /**
      * Id of the submission to thich the files belong.
      */
     filesOwner: {
       type: String,
-      required: true
+      required: true,
     },
     /**
      * Files of the submission.
      * type: Array<SubmissionFile>
      */
     files: {
+      type: Map<string,SubmissionFile>,
       required: true,
-
     },
     /**
      * Matche of submission.
-     * type: Array<MatchInSingleFile>
      */
     matches: {
-      required: true
-    }
+     type: Map<string,MatchInSingleFile>,
+      required: true,
+    },
   },
 
-  setup(props, {emit}) {
-
+  setup(props, { emit }) {
     /**
      * Passes lineSelected event, emitted from LineOfCode, to parent.
      * @param e
@@ -69,14 +71,14 @@ export default defineComponent({
      * @param file
      * @param line
      */
-    const lineSelected = (e, index, file, line) => {
-      emit('lineSelected', e, index, file, line)
-    }
+    const lineSelected = (e: any, index: number, file: string, line: number) => {
+      emit("lineSelected", e, index, file, line);
+    };
     return {
-      lineSelected
-    }
-  }
-})
+      lineSelected,
+    };
+  },
+});
 </script>
 
 <style scoped>
@@ -92,4 +94,4 @@ h1 {
   width: 100%;
   overflow: auto;
 }
-</style>
+</style>

+ 10 - 0
report-viewer/src/model/ClusterListElement.ts

@@ -0,0 +1,10 @@
+type ClusterListElement = {
+  averageSimilarity: number;
+  strength: number;
+  members: ClusterListElementMember;
+};
+type ClusterListElementMember = Map<
+  string,
+  Array<{ matchedWith: string; percentage: number }>
+>;
+export { ClusterListElement, ClusterListElementMember };

+ 95 - 91
report-viewer/src/model/Comparison.ts

@@ -1,96 +1,100 @@
-import {Match} from "./Match";
-import {SubmissionFile} from "./SubmissionFile"
-import {MatchInSingleFile} from "./MatchInSingleFile";
+import { Match } from "./Match";
+import { SubmissionFile } from "./SubmissionFile";
+import { MatchInSingleFile } from "./MatchInSingleFile";
 
 /**
  * Comparison model used by the ComparisonView
  */
 export class Comparison {
-    private readonly _firstSubmissionId: string
-    private readonly _secondSubmissionId: string
-    private readonly _match_percentage: number
-
-    constructor(firstSubmissionId: string, secondSubmissionId: string, match_percentage: number) {
-        this._firstSubmissionId = firstSubmissionId;
-        this._secondSubmissionId = secondSubmissionId;
-        this._match_percentage = match_percentage;
-        this._filesOfFirstSubmission = {}
-        this._filesOfSecondSubmission = {}
-        this._colors = []
-        this._allMatches = []
-        this._matchesInFirstSubmission = {}
-        this._matchesInSecondSubmissions = {}
-    }
-
-    private _filesOfFirstSubmission: Record<string, SubmissionFile>
-
-    get filesOfFirstSubmission(): Record<string, SubmissionFile> {
-        return this._filesOfFirstSubmission;
-    }
-
-    set filesOfFirstSubmission(value: Record<string, SubmissionFile>) {
-        this._filesOfFirstSubmission = value;
-    }
-
-    private _filesOfSecondSubmission: Record<string, SubmissionFile>
-
-    get filesOfSecondSubmission(): Record<string, SubmissionFile> {
-        return this._filesOfSecondSubmission;
-    }
-
-    set filesOfSecondSubmission(value: Record<string, SubmissionFile>) {
-        this._filesOfSecondSubmission = value;
-    }
-
-    private _colors: Array<string>
-
-    get colors(): Array<string> {
-        return this._colors;
-    }
-
-    set colors(value: Array<string>) {
-        this._colors = value;
-    }
-
-    private _allMatches: Array<Match>
-
-    get allMatches(): Array<Match> {
-        return this._allMatches;
-    }
-
-    set allMatches(value: Array<Match>) {
-        this._allMatches = value;
-    }
-
-    private _matchesInFirstSubmission: Record<string, Array<MatchInSingleFile>>
-
-    get matchesInFirstSubmission(): Record<string, Array<MatchInSingleFile>> {
-        return this._matchesInFirstSubmission;
-    }
-
-    set matchesInFirstSubmission(value: Record<string, Array<MatchInSingleFile>>) {
-        this._matchesInFirstSubmission = value;
-    }
-
-    private _matchesInSecondSubmissions: Record<string, Array<MatchInSingleFile>>
-
-    get matchesInSecondSubmissions(): Record<string, Array<MatchInSingleFile>> {
-        return this._matchesInSecondSubmissions;
-    }
-
-    set matchesInSecondSubmissions(value: Record<string, Array<MatchInSingleFile>>) {
-        this._matchesInSecondSubmissions = value;
-    }
-
-    get firstSubmissionId(): string {
-        return this._firstSubmissionId;
-    }
-
-    get secondSubmissionId(): string {
-        return this._secondSubmissionId;
-    }
-
-    get match_percentage(): number {
-        return this._match_percentage;
-    }
-}
+  private readonly _firstSubmissionId: string;
+  private readonly _secondSubmissionId: string;
+  private readonly _match_percentage: number;
+
+  constructor(
+    firstSubmissionId: string,
+    secondSubmissionId: string,
+    match_percentage: number
+  ) {
+    this._firstSubmissionId = firstSubmissionId;
+    this._secondSubmissionId = secondSubmissionId;
+    this._match_percentage = match_percentage;
+    this._filesOfFirstSubmission = new Map();
+    this._filesOfSecondSubmission = new Map();
+    this._colors = [];
+    this._allMatches = [];
+    this._matchesInFirstSubmission = new Map();
+    this._matchesInSecondSubmissions = new Map();
+  }
+
+  private _filesOfFirstSubmission: Map<string, SubmissionFile>;
+
+  get filesOfFirstSubmission(): Map<string, SubmissionFile> {
+    return this._filesOfFirstSubmission;
+  }
+
+  set filesOfFirstSubmission(value: Map<string, SubmissionFile>) {
+    this._filesOfFirstSubmission = value;
+  }
+
+  private _filesOfSecondSubmission: Map<string, SubmissionFile>;
+
+  get filesOfSecondSubmission(): Map<string, SubmissionFile> {
+    return this._filesOfSecondSubmission;
+  }
+
+  set filesOfSecondSubmission(value: Map<string, SubmissionFile>) {
+    this._filesOfSecondSubmission = value;
+  }
+
+  private _colors: Array<string>;
+
+  get colors(): Array<string> {
+    return this._colors;
+  }
+
+  set colors(value: Array<string>) {
+    this._colors = value;
+  }
+
+  private _allMatches: Array<Match>;
+
+  get allMatches(): Array<Match> {
+    return this._allMatches;
+  }
+
+  set allMatches(value: Array<Match>) {
+    this._allMatches = value;
+  }
+
+  private _matchesInFirstSubmission: Map<string, Array<MatchInSingleFile>>;
+
+  get matchesInFirstSubmission(): Map<string, Array<MatchInSingleFile>> {
+    return this._matchesInFirstSubmission;
+  }
+
+  set matchesInFirstSubmission(value: Map<string, Array<MatchInSingleFile>>) {
+    this._matchesInFirstSubmission = value;
+  }
+
+  private _matchesInSecondSubmissions: Map<string, Array<MatchInSingleFile>>;
+
+  get matchesInSecondSubmissions(): Map<string, Array<MatchInSingleFile>> {
+    return this._matchesInSecondSubmissions;
+  }
+
+  set matchesInSecondSubmissions(value: Map<string, Array<MatchInSingleFile>>) {
+    this._matchesInSecondSubmissions = value;
+  }
+
+  get firstSubmissionId(): string {
+    return this._firstSubmissionId;
+  }
+
+  get secondSubmissionId(): string {
+    return this._secondSubmissionId;
+  }
+
+  get match_percentage(): number {
+    return this._match_percentage;
+  }
+}

+ 66 - 57
report-viewer/src/model/Overview.ts

@@ -1,70 +1,79 @@
-import {Metric} from "./Metric";
-import {Cluster} from "@/model/Cluster";
+import { Metric } from "./Metric";
+import { Cluster } from "@/model/Cluster";
 
 export class Overview {
-    private readonly _submissionFolderPath: Array<string>
-    private readonly _baseCodeFolderPath: string
-    private readonly _language: string
-    private readonly _fileExtensions: Array<string>
-    private readonly _matchSensitivity: number
-    private readonly _submissionIds: Array<string>
-    private readonly _dateOfExecution: string
-    private readonly _durationOfExecution: number
-    private readonly _metrics: Array<Metric>
-    private readonly _clusters: Array<Cluster>
+  private readonly _submissionFolderPath: Array<string>;
+  private readonly _baseCodeFolderPath: string;
+  private readonly _language: string;
+  private readonly _fileExtensions: Array<string>;
+  private readonly _matchSensitivity: number;
+  private readonly _submissionIds: Array<string>;
+  private readonly _dateOfExecution: string;
+  private readonly _durationOfExecution: number;
+  private readonly _metrics: Array<Metric>;
+  private readonly _clusters: Array<Cluster>;
 
+  constructor(
+    submissionFolderPath: Array<string>,
+    baseCodeFolderPath: string,
+    language: string,
+    fileExtensions: Array<string>,
+    matchSensitivity: number,
+    submissionIds: Array<string>,
+    dateOfExecution: string,
+    durationOfExecution: number,
+    metrics: Array<Metric>,
+    clusters: Array<Cluster>
+  ) {
+    this._submissionFolderPath = submissionFolderPath;
+    this._baseCodeFolderPath = baseCodeFolderPath;
+    this._language = language;
+    this._fileExtensions = fileExtensions;
+    this._matchSensitivity = matchSensitivity;
+    this._submissionIds = submissionIds;
+    this._dateOfExecution = dateOfExecution;
+    this._durationOfExecution = durationOfExecution;
+    this._metrics = metrics;
+    this._clusters = clusters;
+  }
 
-    constructor(submissionFolderPath: Array<string>, baseCodeFolderPath: string, language: string, fileExtensions: Array<string>, matchSensitivity: number, submissionIds: Array<string>, dateOfExecution: string, durationOfExecution: number, metrics: Array<Metric>, clusters: Array<Cluster>) {
-        this._submissionFolderPath = submissionFolderPath;
-        this._baseCodeFolderPath = baseCodeFolderPath;
-        this._language = language;
-        this._fileExtensions = fileExtensions
-        this._matchSensitivity = matchSensitivity;
-        this._submissionIds = submissionIds;
-        this._dateOfExecution = dateOfExecution;
-        this._durationOfExecution = durationOfExecution;
-        this._metrics = metrics;
-        this._clusters = clusters
-    }
+  get submissionFolderPath(): Array<string> {
+    return this._submissionFolderPath;
+  }
 
+  get baseCodeFolderPath(): string {
+    return this._baseCodeFolderPath;
+  }
 
-    get submissionFolderPath(): Array<string> {
-        return this._submissionFolderPath;
-    }
+  get language(): string {
+    return this._language;
+  }
 
-    get baseCodeFolderPath(): string {
-        return this._baseCodeFolderPath;
-    }
+  get fileExtensions(): Array<string> {
+    return this._fileExtensions;
+  }
 
-    get language(): string {
-        return this._language;
-    }
+  get matchSensitivity(): number {
+    return this._matchSensitivity;
+  }
 
-    get fileExtensions(): Array<string> {
-        return this._fileExtensions
-    }
+  get submissionIds(): Array<string> {
+    return this._submissionIds;
+  }
 
-    get matchSensitivity(): number {
-        return this._matchSensitivity;
-    }
+  get dateOfExecution(): string {
+    return this._dateOfExecution;
+  }
 
-    get submissionIds(): Array<string> {
-        return this._submissionIds;
-    }
+  get durationOfExecution(): number {
+    return this._durationOfExecution;
+  }
 
-    get dateOfExecution(): string {
-        return this._dateOfExecution;
-    }
+  get metrics(): Array<Metric> {
+    return this._metrics;
+  }
 
-    get durationOfExecution(): number {
-        return this._durationOfExecution;
-    }
-
-    get metrics(): Array<Metric> {
-        return this._metrics;
-    }
-
-    get clusters(): Array<Cluster> {
-        return this._clusters
-    }
-}
+  get clusters(): Array<Cluster> {
+    return this._clusters;
+  }
+}

+ 108 - 93
report-viewer/src/model/factories/ComparisonFactory.ts

@@ -1,106 +1,121 @@
-import {Comparison} from "../Comparison";
-import {Match} from "../Match";
-import {SubmissionFile} from "../SubmissionFile";
-import {MatchInSingleFile} from "../MatchInSingleFile";
+import { Comparison } from "../Comparison";
+import { Match } from "../Match";
+import { SubmissionFile } from "../SubmissionFile";
+import { MatchInSingleFile } from "../MatchInSingleFile";
 
 export class ComparisonFactory {
+  static getComparison(json: Record<string, unknown>): Comparison {
+    const filesOfFirst = this.convertToFilesByName(
+      json.files_of_first_submission as Array<Record<string, unknown>>
+    );
+    const filesOfSecond = this.convertToFilesByName(
+      json.files_of_second_submission as Array<Record<string, unknown>>
+    );
 
-    static getComparison(json: Record<string, unknown>): Comparison {
-        const filesOfFirst = this.convertToFilesByName(json.files_of_first_submission as Array<Record<string, unknown>>)
-        const filesOfSecond = this.convertToFilesByName(json.files_of_second_submission as Array<Record<string, unknown>>)
+    const matches = json.matches as Array<Record<string, unknown>>;
+    const colors = this.generateColorsForMatches(matches.length);
+    const coloredMatches = matches.map((match, index) =>
+      this.mapMatch(match, colors[index])
+    );
 
-        const matches = json.matches as Array<Record<string, unknown>>
-        const colors = this.generateColorsForMatches(matches.length)
-        const coloredMatches = matches.map((match, index) => this.mapMatch(match, colors[index]))
+    const matchesInFirst = this.groupMatchesByFileName(coloredMatches, 1);
+    const matchesInSecond = this.groupMatchesByFileName(coloredMatches, 2);
 
-        const matchesInFirst = this.groupMatchesByFileName(coloredMatches, 1)
-        const matchesInSecond = this.groupMatchesByFileName(coloredMatches, 2)
+    const comparison = new Comparison(
+      json.first_submission_id as string,
+      json.second_submission_id as string,
+      json.match_percentage as number
+    );
+    comparison.filesOfFirstSubmission = filesOfFirst;
+    comparison.filesOfSecondSubmission = filesOfSecond;
+    comparison.colors = colors;
+    comparison.allMatches = coloredMatches;
+    comparison.matchesInFirstSubmission = matchesInFirst;
+    comparison.matchesInSecondSubmissions = matchesInSecond;
 
-        const comparison = new Comparison(
-            json.first_submission_id as string,
-            json.second_submission_id as string,
-            json.match_percentage as number
-        )
-        comparison.filesOfFirstSubmission = filesOfFirst
-        comparison.filesOfSecondSubmission = filesOfSecond
-        comparison.colors = colors
-        comparison.allMatches = coloredMatches
-        comparison.matchesInFirstSubmission = matchesInFirst
-        comparison.matchesInSecondSubmissions = matchesInSecond
+    return comparison;
+  }
 
-        return comparison
-    }
-
-    private static convertToFilesByName(files: Array<Record<string, unknown>>): Record<string, SubmissionFile> {
-        return files.reduce((acc: Record<string, SubmissionFile>, val: Record<string, unknown>) => {
-            if (!acc[val.file_name as string]) {
-                acc[val.file_name as string] = {
-                    lines: [],
-                    collapsed: false
-                }
-            }
-            acc[val.file_name as string] = {
-                lines: val.lines as Array<string>,
-                collapsed: false
-            }
-            return acc;
-        }, {})
-    }
-
-    private static groupMatchesByFileName(matches: Array<Match>, index: number): Record<string, Array<MatchInSingleFile>> {
-        return matches.reduce((acc: Record<string, Array<MatchInSingleFile>>, val: Match) => {
-            const name = index === 1 ? val.firstFile as string : val.secondFile as string
-            if (!acc[name]) {
-                acc[name] = []
-            }
-            if (index === 1) {
-                const newVal: MatchInSingleFile = {
-                    start: val.startInFirst as number,
-                    end: val.endInFirst as number,
-                    linked_panel: 2,
-                    linked_file: val.secondFile as string,
-                    linked_line: val.startInSecond as number,
-                    color: val.color as string
-                }
-                acc[name].push(newVal)
-            } else {
-                const newVal: MatchInSingleFile = {
-                    start: val.startInSecond as number,
-                    end: val.endInSecond as number,
-                    linked_panel: 1,
-                    linked_file: val.firstFile as string,
-                    linked_line: val.startInFirst as number,
-                    color: val.color as string
-                }
-                acc[name].push(newVal)
-            }
-            return acc;
-        }, {})
-    }
+  private static convertToFilesByName(
+    files: Array<Record<string, unknown>>
+  ): Map<string, SubmissionFile> {
+    const map = new Map<string, SubmissionFile>();
+    files.forEach((val) => {
+      if (!map.get(val.file_name as string)) {
+        map.set(val.file_name as string, {
+          lines: [],
+          collapsed: false,
+        });
+      }
+      map.set(val.file_name as string, {
+        lines: val.lines as Array<string>,
+        collapsed: false,
+      });
+    });
+    return map;
+  }
 
-    private static generateColorsForMatches(num: number): Array<string> {
-        const colors = []
-        const hueDelta = Math.trunc(360 / (num))
+  private static groupMatchesByFileName(
+    matches: Array<Match>,
+    index: number
+  ): Map<string, Array<MatchInSingleFile>> {
+    const acc = new Map<string, Array<MatchInSingleFile>>();
+    matches.forEach((val) => {
+      const name =
+        index === 1 ? (val.firstFile as string) : (val.secondFile as string);
+      if (!acc.get(name)) {
+        acc.set(name, []);
+      }
+      if (index === 1) {
+        const newVal: MatchInSingleFile = {
+          start: val.startInFirst as number,
+          end: val.endInFirst as number,
+          linked_panel: 2,
+          linked_file: val.secondFile as string,
+          linked_line: val.startInSecond as number,
+          color: val.color as string,
+        };
+        acc.get(name)?.push(newVal);
+      } else {
+        const newVal: MatchInSingleFile = {
+          start: val.startInSecond as number,
+          end: val.endInSecond as number,
+          linked_panel: 1,
+          linked_file: val.firstFile as string,
+          linked_line: val.startInFirst as number,
+          color: val.color as string,
+        };
+        acc.get(name)?.push(newVal);
+      }
+    });
+    return acc;
+  }
 
-        for (let i = 0; i < num; i++) {
-            const hue = i * hueDelta
+  private static generateColorsForMatches(num: number): Array<string> {
+    const colors = [];
+    const hueDelta = Math.trunc(360 / num);
 
-            colors.push(`hsla(${hue}, 80%, 50%, 0.3)`)
-        }
-        return colors
-    }
+    for (let i = 0; i < num; i++) {
+      const hue = i * hueDelta;
 
-    private static mapMatch(match: Record<string, unknown>, color: string): Match {
-        return {
-            firstFile: match.first_file_name as string,
-            secondFile: match.second_file_name as string,
-            startInFirst: match.start_in_first as number,
-            endInFirst: match.end_in_first as number,
-            startInSecond: match.start_in_second as number,
-            endInSecond: match.end_in_second as number,
-            tokens: match.tokens as number,
-            color: color
-        };
+      colors.push(`hsla(${hue}, 80%, 50%, 0.3)`);
     }
+    return colors;
+  }
 
-}
+  private static mapMatch(
+    match: Record<string, unknown>,
+    color: string
+  ): Match {
+    return {
+      firstFile: match.first_file_name as string,
+      secondFile: match.second_file_name as string,
+      startInFirst: match.start_in_first as number,
+      endInFirst: match.end_in_first as number,
+      startInSecond: match.start_in_second as number,
+      endInSecond: match.end_in_second as number,
+      tokens: match.tokens as number,
+      color: color,
+    };
+  }
+}

+ 44 - 24
report-viewer/src/views/ComparisonView.vue

@@ -22,7 +22,7 @@
         </button>
       </div>
       <TextInformation
-        :anonymous="store.state.anonymous.has(firstId)"
+        :anonymous="isAnonymous(firstId)"
         :value="firstId"
         label="Submission 1"
       />
@@ -58,15 +58,16 @@
   </div>
 </template>
 
-<script>
+<script lang="ts">
 import { defineComponent, ref } from "vue";
 import { generateLineCodeLink } from "@/utils/Utils";
-import TextInformation from "@/components/TextInformation";
-import MatchTable from "@/components/MatchTable";
+import TextInformation from "@/components/TextInformation.vue";
+import MatchTable from "@/components/MatchTable.vue";
 import { ComparisonFactory } from "@/model/factories/ComparisonFactory";
-import FilesContainer from "@/components/FilesContainer";
+import FilesContainer from "@/components/FilesContainer.vue";
 import { useStore } from "vuex";
 import { useRouter } from "vue-router";
+import { Match } from "@/model/Match";
 
 export default defineComponent({
   name: "ComparisonView",
@@ -110,12 +111,11 @@ export default defineComponent({
         }
       }
     } else if (store.state.zip) {
-      const getComparisonFileFor = (id1, id2) => {
-        const index = Object.keys(store.state.files).filter((name) =>
-          name.endsWith(
-            id1.concat("-").concat(id2).concat(".json") ||
-              name.endsWith(id2.concat("-").concat(id1).concat(".json"))
-          )
+      const getComparisonFileFor = (id1: string, id2: string) => {
+        const index = Object.keys(store.state.files).filter(
+          (name) =>
+            name.endsWith(id1.concat("-").concat(id2).concat(".json")) ||
+            name.endsWith(id2.concat("-").concat(id1).concat(".json"))
         )[0];
         return store.state.files[index];
       };
@@ -132,6 +132,10 @@ export default defineComponent({
       );
     }
 
+    if (!comparison) {
+      console.warn("Could not build comparison file");
+      return;
+    }
     const filesOfFirst = ref(comparison.filesOfFirstSubmission);
     const filesOfSecond = ref(comparison.filesOfSecondSubmission);
 
@@ -139,17 +143,21 @@ export default defineComponent({
      * Collapses a file in the first files container.
      * @param title
      */
-    const toggleCollapseFirst = (title) => {
-      filesOfFirst.value[title].collapsed =
-        !filesOfFirst.value[title].collapsed;
+    const toggleCollapseFirst = (title: string) => {
+      const file = filesOfFirst.value.get(title);
+      if (file) {
+        file.collapsed = !file.collapsed;
+      }
     };
     /**
      * Collapses a file in the second files container.
      * @param title
      */
-    const toggleCollapseSecond = (title) => {
-      filesOfSecond.value[title].collapsed =
-        !filesOfSecond.value[title].collapsed;
+    const toggleCollapseSecond = (title: string) => {
+      const file = filesOfSecond.value.get(title);
+      if (file) {
+        file.collapsed = !file.collapsed;
+      }
     };
     /**
      * Shows a match in the first files container
@@ -158,13 +166,18 @@ export default defineComponent({
      * @param file
      * @param line
      */
-    const showMatchInFirst = (e, panel, file, line) => {
-      if (!filesOfFirst.value[file].collapsed) {
+    const showMatchInFirst = (
+      e: any,
+      panel: number,
+      file: string,
+      line: number
+    ) => {
+      if (!filesOfFirst.value.get(file)?.collapsed) {
         toggleCollapseFirst(file);
       }
       document
         .getElementById(generateLineCodeLink(panel, file, line))
-        .scrollIntoView();
+        ?.scrollIntoView();
     };
     /**
      * Shows a match in the second files container.
@@ -173,20 +186,26 @@ export default defineComponent({
      * @param file
      * @param line
      */
-    const showMatchInSecond = (e, panel, file, line) => {
-      if (!filesOfSecond.value[file].collapsed) {
+    const showMatchInSecond = (
+      e: any,
+      panel: number,
+      file: string,
+      line: number
+    ) => {
+      if (!filesOfSecond.value.get(file)?.collapsed) {
         toggleCollapseSecond(file);
       }
       document
         .getElementById(generateLineCodeLink(panel, file, line))
-        .scrollIntoView();
+        ?.scrollIntoView();
     };
 
-    const showMatch = (e, match) => {
+    const showMatch = (e: any, match: Match) => {
       showMatchInFirst(e, 1, match.firstFile, match.startInFirst);
       showMatchInSecond(e, 2, match.secondFile, match.startInSecond);
     };
 
+    const isAnonymous = (id: string) => store.state.anonymous.has(id);
     //Left panel
     const hideLeftPanel = ref(true);
     const togglePanel = () => {
@@ -205,6 +224,7 @@ export default defineComponent({
       showMatchInSecond,
       showMatch,
       togglePanel,
+      isAnonymous,
 
       store,
     };

+ 123 - 73
report-viewer/src/views/OverviewView.vue

@@ -7,25 +7,51 @@
       <h1>JPlag Report</h1>
       <p class="section-title">Main Info:</p>
       <div id="basicInfo">
-        <TextInformation :has-additional-info="hasMoreSubmissionPaths" :value="submissionPathValue"
-                         additional-info-title="" label="Directory path">
-          <p v-for="path in overview.submissionFolderPath" :key="path" :title="path">{{ path }}</p>
+        <TextInformation
+          :has-additional-info="hasMoreSubmissionPaths"
+          :value="submissionPathValue"
+          additional-info-title=""
+          label="Directory path"
+        >
+          <p
+            v-for="path in overview.submissionFolderPath"
+            :key="path"
+            :title="path"
+          >
+            {{ path }}
+          </p>
         </TextInformation>
-        <TextInformation :has-additional-info="true" :value="overview.language" additional-info-title="File extensions:"
-                         label="Language">
+        <TextInformation
+          :has-additional-info="true"
+          :value="overview.language"
+          additional-info-title="File extensions:"
+          label="Language"
+        >
           <p v-for="info in overview.fileExtensions" :key="info">{{ info }}</p>
         </TextInformation>
-        <TextInformation :value="overview.matchSensitivity" label="Match Sensitivity"/>
-        <TextInformation :has-additional-info="true" :value="overview.submissionIds.length"
-                         additional-info-title="Submission IDs:"
-                         label="Submissions">
-          <IDsList :ids="overview.submissionIds" @id-sent="handleId"/>
+        <TextInformation
+          :value="overview.matchSensitivity"
+          label="Match Sensitivity"
+        />
+        <TextInformation
+          :has-additional-info="true"
+          :value="overview.submissionIds.length"
+          additional-info-title="Submission IDs:"
+          label="Submissions"
+        >
+          <IDsList :ids="overview.submissionIds" @id-sent="handleId" />
         </TextInformation>
-        <TextInformation :value="overview.dateOfExecution" label="Date of execution"/>
-        <TextInformation :value="overview.durationOfExecution" label="Duration (in ms)"/>
+        <TextInformation
+          :value="overview.dateOfExecution"
+          label="Date of execution"
+        />
+        <TextInformation
+          :value="overview.durationOfExecution"
+          label="Duration (in ms)"
+        />
       </div>
       <div id="logo-section">
-        <img id="logo" alt="JPlag" src="@/assets/logo-nobg.png">
+        <img id="logo" alt="JPlag" src="@/assets/logo-nobg.png" />
       </div>
     </div>
 
@@ -33,40 +59,57 @@
       <div id="metrics">
         <p class="section-title">Metric:</p>
         <div id="metrics-list">
-          <MetricButton v-for="(metric, i) in overview.metrics" :id="metric.metricName"
-                        :key="metric.metricName"
-                        :is-selected="selectedMetric[i]"
-                        :metric-name="metric.metricName"
-                        :metric-threshold="metric.metricThreshold"
-                        @click="selectMetric(i)"/>
+          <MetricButton
+            v-for="(metric, index) in overview.metrics"
+            :id="metric.metricName"
+            :key="metric.metricName"
+            :is-selected="selectedMetric[index]"
+            :metric-name="metric.metricName"
+            :metric-threshold="metric.metricThreshold"
+            @click="selectMetric(index)"
+          />
         </div>
       </div>
       <p class="section-title">Distribution:</p>
-      <DistributionDiagram :distribution="distributions[selectedMetricIndex]" class="full-width"/>
+      <DistributionDiagram
+        :distribution="distributions[selectedMetricIndex]"
+        class="full-width"
+      />
     </div>
     <div class="column-container" style="width: 35%">
       <p class="section-title">Top Comparisons:</p>
       <div id="comparisonsList">
-        <ComparisonsTable :clusters="overview.clusters" :top-comparisons="topComps[selectedMetricIndex]"/>
+        <ComparisonsTable
+          :clusters="overview.clusters"
+          :top-comparisons="topComps[selectedMetricIndex]"
+        />
       </div>
     </div>
   </div>
 </template>
 
-<script>
-import { computed, defineComponent, ref } from "vue";
+<script lang="ts">
+import { computed, defineComponent, Ref, ref } from "vue";
 import router from "@/router";
-import TextInformation from "../components/TextInformation";
-import DistributionDiagram from "@/components/DistributionDiagram";
-import MetricButton from "@/components/MetricButton";
-import ComparisonsTable from "@/components/ComparisonsTable";
-import {OverviewFactory} from "@/model/factories/OverviewFactory";
-import IDsList from "@/components/IDsList";
+import TextInformation from "../components/TextInformation.vue";
+import DistributionDiagram from "@/components/DistributionDiagram.vue";
+import MetricButton from "@/components/MetricButton.vue";
+import ComparisonsTable from "@/components/ComparisonsTable.vue";
+import { OverviewFactory } from "@/model/factories/OverviewFactory";
+import IDsList from "@/components/IDsList.vue";
 import { useStore } from "vuex";
+import { Overview } from "@/model/Overview";
+import { ComparisonListElement } from "@/model/ComparisonListElement";
 
 export default defineComponent({
   name: "OverviewView",
-  components: {IDsList, ComparisonsTable, DistributionDiagram, MetricButton, TextInformation},
+  components: {
+    IDsList,
+    ComparisonsTable,
+    DistributionDiagram,
+    MetricButton,
+    TextInformation,
+  },
   setup() {
     const store = useStore();
     const overviewFile = computed(() => {
@@ -75,21 +118,27 @@ export default defineComponent({
       )[0];
       return store.state.files[index];
     });
-    let overview;
-    //Gets the overview file based on the used mode (zip, local, single).
-    if (store.state.local) {
-      try {
-        // eslint-disable-next-line @typescript-eslint/no-var-requires
-        overview = OverviewFactory.getOverview(require("../files/overview.json"))
-      } catch (e) {
-        router.back()
+
+    const getOverview = (): Overview => {
+      let temp!: Overview;
+      //Gets the overview file based on the used mode (zip, local, single).
+      if (store.state.local) {
+        try {
+          // eslint-disable-next-line @typescript-eslint/no-var-requires
+          temp = OverviewFactory.getOverview(require("../files/overview.json"));
+        } catch (e) {
+          router.back();
+        }
+      } else if (store.state.zip) {
+        const overviewJson = JSON.parse(overviewFile.value);
+        temp = OverviewFactory.getOverview(overviewJson);
+      } else if (store.state.single) {
+        temp = OverviewFactory.getOverview(JSON.parse(store.state.fileString));
       }
-    } else if (store.state.zip) {
-      const overviewJson = JSON.parse(overviewFile.value);
-      overview = OverviewFactory.getOverview(overviewJson);
-    } else if (store.state.single) {
-      overview = OverviewFactory.getOverview(JSON.parse(store.state.fileString))
-    }
+      return temp;
+    };
+
+    let overview = getOverview();
 
     /**
      * Handles the selection of an Id to anonymize.
@@ -97,58 +146,61 @@ export default defineComponent({
      * If a single id is provided it hides all of the other ids except for the chosen one.
      * @param id
      */
-    const handleId = (id) => {
+    const handleId = (id: string) => {
       if (id.length === overview.submissionIds.length) {
         if (store.state.anonymous.size > 0) {
-          store.commit("resetAnonymous")
+          store.commit("resetAnonymous");
         } else {
-          store.commit("addAnonymous", id)
+          store.commit("addAnonymous", id);
         }
       } else {
         if (store.state.anonymous.has(id[0])) {
-          store.commit("removeAnonymous", id)
+          store.commit("removeAnonymous", id);
         } else {
           if (store.state.anonymous.size === 0) {
-            store.commit("addAnonymous", overview.submissionIds.filter(s => s !== id[0]))
+            store.commit(
+              "addAnonymous",
+              overview.submissionIds.filter((s) => s !== id[0])
+            );
           } else {
-            store.commit("addAnonymous", id)
+            store.commit("addAnonymous", id);
           }
         }
       }
-    }
-
+    };
 
     //Metrics
     /**
      * Current metric to display distribution and comparisons for.
      * @type {Ref<UnwrapRef<boolean[]>>}
      */
-    let selectedMetric = ref(overview.metrics.map(() => false))
+    let selectedMetric = ref(overview.metrics.map(() => false));
     /**
      * Index of current selected metric. Used to obtain information for the metric from the distribution and top
      * comparisons array.
      * @type {Ref<UnwrapRef<number>>}
      */
-    let selectedMetricIndex = ref(0)
+    let selectedMetricIndex = ref(0);
     selectedMetric.value[0] = true;
 
-    const selectMetric = (metric) => {
+    const selectMetric = (metric: number) => {
       selectedMetric.value = selectedMetric.value.map(() => {
-        return false
-      })
-      selectedMetric.value[metric] = true
-      selectedMetricIndex.value = metric
-    }
+        return false;
+      });
+      selectedMetric.value[metric] = true;
+      selectedMetricIndex.value = metric;
+    };
 
     //Distribution
-    let distributions = ref(overview.metrics.map((m) => m.distribution))
+    let distributions = ref(overview.metrics.map((m) => m.distribution));
 
     //Top Comparisons
-    let topComps = ref(overview.metrics.map((m) => m.comparisons))
+    let topComps : Ref<Array<Array<ComparisonListElement>>>= ref(overview.metrics.map((m) => m.comparisons));
 
     const hasMoreSubmissionPaths = overview.submissionFolderPath.length > 1;
-    const submissionPathValue = hasMoreSubmissionPaths ? "Click arrow to see all paths"
-        : overview.submissionFolderPath[0]
+    const submissionPathValue = hasMoreSubmissionPaths
+      ? "Click arrow to see all paths"
+      : overview.submissionFolderPath[0];
 
     return {
       overview,
@@ -160,10 +212,10 @@ export default defineComponent({
       submissionPathValue,
       handleId,
       selectMetric,
-      store
-    }
-  }
-})
+      store,
+    };
+  },
+});
 </script>
 
 <style scoped>
@@ -176,9 +228,9 @@ h1 {
 hr {
   border: 0;
   height: 2px;
-  background: linear-gradient(to right, #EDF2FB, transparent, transparent);
+  background: linear-gradient(to right, #edf2fb, transparent, transparent);
   width: 100%;
-  box-shadow: #D7E3FC 0 1px;
+  box-shadow: #d7e3fc 0 1px;
 }
 
 .container {
@@ -252,6 +304,4 @@ hr {
 #logo {
   flex-shrink: 2;
 }
-
-
-</style>
+</style>