All files / src/app/components/calendar-heatmap calendar-heatmap.component.ts

78.04% Statements 64/82
50% Branches 9/18
70% Functions 7/10
76.92% Lines 60/78

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                        95x                 380x       285x 285x 285x 285x             285x     144x   144x   144x         144x   48x 48x     48x 48x     48x 48x             144x   144x 144x 288x 288x 288x 288x     144x 144x                                                       144x 144x 144x 144x 144x 144x 144x   3024x 3024x 3024x 21168x 21168x 21168x 21168x 21168x     144x 144x   144x 144x   144x 144x   144x               144x   48x 48x   48x 48x   48x 48x     144x                                                                                     316x 316x 316x 316x                              
import { Component, Input, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { getWeekNumber } from '../../utils/utils';
import { TwinpadApiService } from '../../services/twinpad-api.service';
import { HttpErrorResponse } from '@angular/common/http';
import { NgIf } from '@angular/common';
 
import { EChartsOption, VisualMapComponentOption } from 'echarts';
import * as echarts from 'echarts/core';
import { HeatmapChart } from 'echarts/charts';
import { GridComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { TooltipComponent } from 'echarts/components';
import { VisualMapComponent } from 'echarts/components';
import { ErrorComponent } from '../error/error.component';
import { NgxEchartsDirective, provideEchartsCore } from 'ngx-echarts';
import { Observable } from 'rxjs';
import { TwinPadActivity } from '../../models/events';
import { NumberSuffixPipe } from '../../pipes/number-suffix.pipe';
 
echarts.use([HeatmapChart, GridComponent, CanvasRenderer, TooltipComponent, VisualMapComponent]);
 
@Component({
  selector: 'app-calendar-heatmap',
  imports: [NgxEchartsDirective, ErrorComponent, NgIf],
  providers: [provideEchartsCore({ echarts })],
  templateUrl: './calendar-heatmap.component.html',
  styleUrl: './calendar-heatmap.component.scss'
})
export class CalendarHeatmapComponent implements OnInit {
  @Input() heatMapType: "events" | "samples" | "commands";
  isLoading: boolean;
  options: EChartsOption;
  dayToGrid: Map<string, [number, number]> = new Map();
  gridToDay: Map<string, string> = new Map();
  gridToTimestampBounds: Map<string, [number, number]> = new Map();
  weeksDisplayed: number = 20;
  firstDayTs: number;
  lastDayTs: number;
  updateOptions: EChartsOption;
 
  error: HttpErrorResponse;
 
  constructor(private twinpadApiService: TwinpadApiService, private router: Router) { }
 
  ngOnInit(): void {
    this.isLoading = true;
 
    this.setOptions();
 
    this.getData();
  }
 
  getData() {
    let apiRequest: Observable<TwinPadActivity[]>;
    switch (this.heatMapType) {
      case "events": {
        apiRequest = this.twinpadApiService.getNumberEvents(this.firstDayTs, this.lastDayTs);
        break;
      }
      case "samples": {
        apiRequest = this.twinpadApiService.getNumberSamples(this.firstDayTs, this.lastDayTs);
        break;
      }
      case "commands": {
        apiRequest = this.twinpadApiService.getNumberCommands(this.firstDayTs, this.lastDayTs);
        break;
      }
      default: {
        this.error = new HttpErrorResponse({ status: 404, statusText: "Unknown heatmap type" });
        return;
      }
    }
    apiRequest.subscribe({
      next: response => {
        const data = [];
        for (const day_data of response) {
          const day = new Date(day_data.timestamp * 1000).toDateString();
          const grid = this.dayToGrid.get(day);
          Eif (grid !== undefined) {
            data.push([grid[0], grid[1], day_data.amount]);
          }
        }
        this.updateOptions = { series: [{ data: data }] };
        this.isLoading = false;
      },
      error: error => { this.error = error; }
    });
  }
 
  onChartClick(event: any): void { // eslint-disable-line
    if (event.seriesType === 'heatmap') {
      const timestamps = this.gridToTimestampBounds.get([event.data[0], event.data[1]].join(','));
      if (timestamps !== undefined) {
        switch (this.heatMapType) {
          case "events": {
            this.router.navigate(['/events'], { queryParams: { min_timestamp: timestamps[0], max_timestamp: timestamps[1] } });
            break;
          }
          case "commands": {
            this.router.navigate(['/commands'], { queryParams: { min_timestamp: timestamps[0], max_timestamp: timestamps[1] } });
            break;
          }
          default: {
            return;
          }
        }
      }
    }
  }
 
  setOptions() {
    const weeks = [];
    const day = new Date();
    const daysUntilSunday = (7 - day.getDay()) % 7;
    day.setDate(day.getDate() + daysUntilSunday);
    day.setHours(0, 0, 0, 0);
    this.lastDayTs = day.getTime() / 1000;
    for (let iweek = this.weeksDisplayed; iweek >= 0; iweek--) {
 
      const weekNumber: number = getWeekNumber(day);
      weeks.push('W' + weekNumber.toString());
      for (let iday = 0; iday < 7; iday++) {
        this.dayToGrid.set(day.toDateString(), [iweek, iday]);
        this.gridToDay.set([iweek, iday].join(','), day.toDateString());
        const tsMin = day.getTime() / 1000;
        this.gridToTimestampBounds.set([iweek, iday].join(','), [tsMin, tsMin + 24 * 3600]);
        day.setDate(day.getDate() - 1);
      }
    }
    this.firstDayTs = day.getTime() / 1000;
    weeks.reverse();
 
    const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'].reverse();
    const data: number[][] = [];
 
    const gridToDay = this.gridToDay;
    const heatMapType = this.heatMapType;
 
    const visualMap: VisualMapComponentOption = {
      min: 0,
      calculable: true,
      orient: 'horizontal',
      left: 'center',
      bottom: '15%'
    };
 
    switch (this.heatMapType) {
      case 'events':
        visualMap.max = 250;
        break;
      case 'samples':
        visualMap.max = 100_000_000;
        break;
      case 'commands':
        visualMap.max = 250;
        break;
    }
 
    this.options = {
      title: {
        left: 'center',
        text: 'Pad activity'
      },
      tooltip: {
        position: 'top',
        formatter: function (params: any) {  // eslint-disable-line
          const dataItem = params.data as [number, number, number];
          const x = dataItem[0];
          const y = dataItem[1];
          const value = dataItem[2];
          const day = gridToDay.get([x, y].join(','));
          return day + `<br>Number ${heatMapType}: ` + value;
        }
      },
      grid: {
        height: '50%',
        top: '10%'
      },
      xAxis: {
        type: 'category',
        data: weeks,
        splitArea: {
          show: true
        }
      },
      yAxis: {
        type: 'category',
        data: days,
        splitArea: {
          show: true
        }
      },
      visualMap: visualMap,
      series: [
        {
          name: 'Activity',
          type: 'heatmap',
          data: data,
          label: {
            show: true,
            formatter: function (params: any) {  // eslint-disable-line
              const numberPipe = new NumberSuffixPipe();
              const dataItem = params.data as [number, number, number];
              const value = dataItem[2];
              return numberPipe.transform(value);
            }
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    };
  }
 
}