All files / tools/ReFlex.TrackingServer/ClientApp/src/app/processing/interactions-visualization interactions-visualization.component.ts

97.8% Statements 89/91
92% Branches 46/50
100% Functions 20/20
97.67% Lines 84/86

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 222 223 224 225 226 227 2282x                                                     2x 2x 2x 2x 2x 2x 2x 2x                 93x         16x 16x 16x 16x 16x 16x 16x 16x 16x 16x   16x           16x   16x 16x     16x 16x 16x 16x     16x             16x     98x         1x       13x 1x   12x 3x 3x 3x 3x   3x   9x     9x 9x   9x 9x     2x 2x 2x 2x   2x           6x 6x     1x 1x 1x           15x 15x 15x         15x         13x 13x     1x 1x           16x 16x 16x       98x 7x                 91x                   28x   28x 28x 28x 28x 28x 28x                   28x       9x   9x 1x     8x 1x     7x 7x            
import { CommonModule } from '@angular/common';
import {
  AfterViewInit,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  ElementRef,
  EventEmitter,
  Output,
  SimpleChanges,
  Input,
  OnChanges,
  OnDestroy,
  OnInit,
  ViewChild,
  inject
} from '@angular/core';
import { FormsModule } from '@angular/forms';
import {
  CompleteInteractionData,
  ElementPosition,
  ExtremumDescription,
  ExtremumType,
  FrameSizeDefinition,
  Interaction,
  InteractionVelocity
} from '@reflex/shared-types';
import { EMPTY, Subscription, catchError, exhaustMap, tap } from 'rxjs';
import { LogService } from 'src/app/log/log.service';
import { ProcessingService } from 'src/shared/services/processing.service';
import { CalibrationService } from 'src/shared/services/calibration.service';
import { markViewForCheck } from 'src/shared/util/mark-view-for-check';
import { InteractionsVelocityVisualizationComponent } from '../interactions-velocity-visualization/interactions-velocity-visualization.component';
import { calibratePredictions } from './calibrate-predictions';
import { HistoryVisualizationComponent } from '../history-visualization/history-visualization.component';
 
@Component({
  selector: 'app-interactions-visualization',
  templateUrl: './interactions-visualization.component.html',
  styleUrls: ['./interactions-visualization.component.scss'],
  changeDetection: ChangeDetectionStrategy.Eager,
  imports: [CommonModule, FormsModule, HistoryVisualizationComponent, InteractionsVelocityVisualizationComponent]
})
export class InteractionsVisualizationComponent implements OnInit, OnChanges, AfterViewInit, OnDestroy {
 
  @ViewChild('interactionVis')
  public container?: ElementRef<HTMLDivElement>;
 
  @Input() public isProcessing = false;
  @Input() public showPrediction = true;
  @Input() public showMatching = true;
  @Input() public showLinear = true;
  @Input() public showAccelerated = true;
  @Output() public predictionDataChange = new EventEmitter<Array<InteractionVelocity>>(true);
  public viewportWidth = 500;
  public viewportHeight = 400;
  public predictionData: Array<InteractionVelocity> = [];
  public predictionMessage = '';
 
  public interactions: CompleteInteractionData = {
    raw: [],
    absolute: [],
    normalized: []
  };
 
  public calibratedInteractions: Array<Interaction> = [];
 
  public fullScreen = false;
  public maxConfidence = 30;
  private resizeObserver?: ResizeObserver;
  private predictionSubscription?: Subscription;
  private readonly processingService = inject(ProcessingService);
  private readonly changeDetector = inject(ChangeDetectorRef);
  private readonly calibrationService = inject(CalibrationService);
  private readonly logService = inject(LogService);
 
  private frameSizeSubscription?: Subscription;
  private frameSize: FrameSizeDefinition = {
    top: 0,
    left: 0,
    width: 500,
    height: 400
  };
 
  private pEventId = 0;
 
  public get eventId(): number {
    return this.pEventId;
  }
 
  @Input()
  public set eventId(value: number) {
    this.pEventId = value;
  }
 
  public ngOnChanges(changes: SimpleChanges): void {
    if (!('isProcessing' in changes) && !('showPrediction' in changes)) {
      return;
    }
    if (!this.isProcessing || !this.showPrediction) {
      this.predictionSubscription?.unsubscribe();
      this.predictionSubscription = undefined;
      this.predictionData = [];
      this.predictionDataChange.emit([]);
 
      return;
    }
    Iif (this.predictionSubscription && !this.predictionSubscription.closed) {
      return;
    }
    this.predictionMessage = '';
    this.predictionSubscription = this.processingService.getVelocities()
      .pipe(
        tap((data) => this.predictionDataChange.emit(data)),
        exhaustMap((data) => calibratePredictions(data, this.calibrationService).pipe(
          catchError(() => {
            // A failed frame must not unsubscribe from subsequent velocity snapshots.
            this.predictionMessage = 'Prediction stream or calibration unavailable.';
            this.predictionData = [];
            this.predictionDataChange.emit([]);
            this.changeDetector.markForCheck();
 
            return EMPTY;
          })
        )),
        markViewForCheck(this.changeDetector)
      ).subscribe({
        next: (data) => {
          this.predictionMessage = '';
          this.predictionData = data;
        },
        error: () => {
          this.predictionMessage = 'Prediction stream or calibration unavailable.';
          this.predictionData = [];
          this.predictionDataChange.emit([]);
        }
      });
  }
 
  public ngAfterViewInit(): void {
    this.resizeObserver = new ResizeObserver(() => this.updateCalibratedInteractions(this.interactions));
    Eif (this.container) {
      this.resizeObserver.observe(this.container.nativeElement);
    }
  }
 
  public ngOnInit(): void {
    this.frameSizeSubscription = this.calibrationService
      .getFrameSize()
      .pipe(markViewForCheck(this.changeDetector))
      .subscribe(
        (result) => {
          this.frameSize = result;
          this.updateCalibratedInteractions(this.interactions);
        },
        (error) => {
          console.error(error);
          this.logService.sendErrorLog(`${error}`);
        }
      );
  }
 
  public ngOnDestroy(): void {
    this.resizeObserver?.disconnect();
    this.predictionSubscription?.unsubscribe();
    this.frameSizeSubscription?.unsubscribe();
  }
 
  public getInteractionsViewStyle(): ElementPosition {
    if (this.fullScreen) {
      return {
        position: 'absolute',
        top: `${this.frameSize.top}px`,
        left: `${this.frameSize.left}px`,
        width: `${this.frameSize.width}px`,
        height: `${this.frameSize.height}px`
      };
    }
 
    return {
      position: 'relative',
      top: `0`,
      left: `0`,
      width: `100%`,
      height: `40vh`
    };
  }
 
  public updateCalibratedInteractions(result: CompleteInteractionData): void {
    this.interactions = result;
 
    const width = this.container?.nativeElement.clientWidth ?? 0;
    const height = this.container?.nativeElement.clientHeight ?? 0;
    this.viewportWidth = this.fullScreen ? this.frameSize.width : width > 0 ? width : 500;
    this.viewportHeight = this.fullScreen ? this.frameSize.height : height > 0 ? height : 400;
    const source = this.fullScreen ? result.absolute : result.normalized;
    this.calibratedInteractions = source.map((item) => ({
      ...item,
      position: {
        ...item.position,
        x: this.fullScreen ? item.position.x - this.frameSize.left : item.position.x * this.viewportWidth,
        y: this.fullScreen ? item.position.y - this.frameSize.top : item.position.y * this.viewportHeight,
        z: Math.abs(item.position.z) * 2
      }
    }));
    // Also used imperatively by ProcessingComponent through ViewChild.
    this.changeDetector.markForCheck();
  }
 
  public getClass(extremum: ExtremumDescription): string {
    const extremumDef = extremum.type;
 
    if (extremumDef === ExtremumType.Undefined) {
      return 'interaction-undefined';
    }
 
    if (extremumDef === ExtremumType.Maximum) {
      return 'interaction-maximum';
    }
 
    Eif (extremumDef === ExtremumType.Minimum) {
      return 'interaction-minimum';
    }
 
    return 'interaction-invalid';
  }
}