Skip to content

Commit

Permalink
chore: add poor type fixes to make app run
Browse files Browse the repository at this point in the history
The project lacks a lot of types, so the team that takes over this project should probably add these to make the dx better :)
  • Loading branch information
eTallang committed Jun 7, 2024
1 parent 7df8d1d commit f712940
Show file tree
Hide file tree
Showing 18 changed files with 111 additions and 97 deletions.
2 changes: 1 addition & 1 deletion src/app/admin/admin.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export class AdminComponent implements OnInit {

ngOnInit(): void {}

login(username, password) {
login(username: string, password: string) {
// Call on login service to authorize user
this.loginService.login(username, password).subscribe(
(res: any) => {
Expand Down
4 changes: 2 additions & 2 deletions src/app/admin/login.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export class LoginService {
private _loggedIn = false;
constructor(private http: HttpClient) {}

login(username, password) {
login(username: string, password: string) {
const formData = new FormData();
formData.append('password', password);
formData.append('username', username);
Expand Down Expand Up @@ -46,7 +46,7 @@ export class LoginService {
);
}

attemptLogin(formData) {
attemptLogin(formData: FormData) {
return this.http.post(`${endpoints.TEKNISKBACKEND}/${endpoints.AUTH}`, formData, {
withCredentials: true,
});
Expand Down
4 changes: 2 additions & 2 deletions src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { environment } from '../environments/environment';
export class AppComponent implements OnInit {
title = 'Teknisk Museum';

userActivity;
userActivity = 0;
userInactive: Subject<any> = new Subject();

isDialogOpen = false;
Expand Down Expand Up @@ -47,7 +47,7 @@ export class AppComponent implements OnInit {
}

setDialogTimeout() {
this.userActivity = setTimeout(() => this.userInactive.next(undefined), this.inactivityTime);
this.userActivity = window.setTimeout(() => this.userInactive.next(undefined), this.inactivityTime);
}

prepareRoute(outlet: RouterOutlet) {
Expand Down
116 changes: 64 additions & 52 deletions src/app/game/game-draw/game-draw.component.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Component, ElementRef, OnInit, ViewChild, Output, EventEmitter, OnDestroy } from '@angular/core';
import { Component, ElementRef, OnInit, Output, EventEmitter, OnDestroy, viewChild } from '@angular/core';
import { BehaviorSubject, interval, Observable, Subscription } from 'rxjs';
import { ImageService } from './services/image.service';
import { take } from 'rxjs/operators';
Expand All @@ -13,22 +13,19 @@ import { SoundService } from './services/sound.service';
styleUrls: ['./game-draw.component.scss'],
})
export class GameDrawComponent implements OnInit, OnDestroy {
@ViewChild('canvas', { static: true })
canvas: ElementRef<HTMLCanvasElement>;
@ViewChild('countDown', { static: true })
countDown: ElementRef<HTMLSpanElement>;

private ctx: CanvasRenderingContext2D;
canvas = viewChild.required<ElementRef<HTMLCanvasElement>>('canvas');
countDown = viewChild.required<ElementRef<HTMLSpanElement>>('countDown');
private ctx: CanvasRenderingContext2D | undefined;

@Output() isDoneDrawing = new EventEmitter();

x = 0;
y = 0;

minX;
minY;
maxX;
maxY;
minX = 0;
minY = 0;
maxX = 0;
maxY = 0;

isDrawing = false;
hasLeftCanvas = false;
Expand All @@ -45,11 +42,11 @@ export class GameDrawComponent implements OnInit, OnDestroy {
private readonly _timeOut = new BehaviorSubject<boolean>(false);
readonly _timeOut$ = this._timeOut.asObservable();

guessWord: string;
AI_GUESS: string;
guessWord = '';
AI_GUESS = '';

prediction: any;
result: Result;
result: Result | undefined;
hasAddedResult = false;

subscriptions = new Subscription();
Expand All @@ -64,13 +61,14 @@ export class GameDrawComponent implements OnInit, OnDestroy {

ngOnInit(): void {
this.multiplayerService.roundIsOver = false;
const ctx = this.canvas.nativeElement.getContext('2d');
const ctx = this.canvas().nativeElement.getContext('2d');
if (!ctx) {
throw new Error('getContext failed');
}
this.ctx = ctx;
this.canvas.nativeElement.width = this.canvas.nativeElement.parentElement?.offsetWidth || document.body.clientWidth;
this.canvas.nativeElement.height = document.body.clientHeight - 100;
this.canvas().nativeElement.width =
this.canvas().nativeElement.parentElement?.offsetWidth || document.body.clientWidth;
this.canvas().nativeElement.height = document.body.clientHeight - 100;
this.resetMinMaxMouseValues();
this.drawingService.guessDone = false;
if (this.multiplayerService.isMultiplayer) {
Expand Down Expand Up @@ -109,7 +107,7 @@ export class GameDrawComponent implements OnInit, OnDestroy {
});
}

updateResult(won) {
updateResult(won: boolean) {
const result: Result = this.createResult(won);
this.drawingService.guessUsed++;
this.addResultAndResize(result).subscribe({
Expand All @@ -120,7 +118,7 @@ export class GameDrawComponent implements OnInit, OnDestroy {
});
}

createResult(won) {
createResult(won: boolean) {
let score = 0;
if (won) {
score = this.getScore();
Expand All @@ -140,9 +138,15 @@ export class GameDrawComponent implements OnInit, OnDestroy {
this.drawingService.label = res.word ? res.word : '';
this.result = this.drawingService.createResult(res);
this.drawingService.addResult(this.result);
const croppedCoordinates: any = this.imageService.crop(this.minX, this.minY, this.maxX, this.maxY, this.LINE_WIDTH);
const croppedCoordinates: number[] = this.imageService.crop(
this.minX,
this.minY,
this.maxX,
this.maxY,
this.LINE_WIDTH
);
return this.imageService.resize(
this.canvas.nativeElement.toDataURL('image/png'),
this.canvas().nativeElement.toDataURL('image/png'),
croppedCoordinates,
this.resultImageSize
);
Expand Down Expand Up @@ -226,7 +230,7 @@ export class GameDrawComponent implements OnInit, OnDestroy {
}
}
if (this.timeLeft <= 5) {
this.countDown.nativeElement.style.color = color;
this.countDown().nativeElement.style.color = color;
color = color === 'white' ? 'red' : 'white';
this.soundService.playTickSound();
this.soundService.playTick = true;
Expand All @@ -243,7 +247,7 @@ export class GameDrawComponent implements OnInit, OnDestroy {
});
}

sortOnCertainty(res) {
sortOnCertainty(res: any) {
const arr: any = [];
Object.entries(res.certainty).map((keyValue) => {
const [label, certainty] = keyValue;
Expand All @@ -258,14 +262,14 @@ export class GameDrawComponent implements OnInit, OnDestroy {
return arr;
}

updateAiGuess(sortedCertaintyArr) {
updateAiGuess(sortedCertaintyArr: any[]) {
if (sortedCertaintyArr && sortedCertaintyArr.length > 1) {
const guess = sortedCertaintyArr[0].label;
this.AI_GUESS = guess === this.guessWord ? sortedCertaintyArr[1].label : guess;
}
}

handleSinglePlayerClassification(dataUrl, croppedCoordinates) {
handleSinglePlayerClassification(dataUrl: string, croppedCoordinates: number[]) {
const formData: FormData = this.createFormData(dataUrl);

this.drawingService.classify(formData).subscribe((res) => {
Expand All @@ -276,15 +280,15 @@ export class GameDrawComponent implements OnInit, OnDestroy {
const score = this.score > 0 ? this.score : 0;
this.drawingService.lastResult.score = Math.round(score);
this.imageService
.resize(this.canvas.nativeElement.toDataURL('image/png'), croppedCoordinates, this.resultImageSize)
.resize(this.canvas().nativeElement.toDataURL('image/png'), croppedCoordinates, this.resultImageSize)
.subscribe({
next: (dataUrlHighRes) => {
this.drawingService.lastResult.imageData = dataUrlHighRes;
},
});
} else {
this.imageService
.resize(this.canvas.nativeElement.toDataURL('image/png'), croppedCoordinates, this.resultImageSize)
.resize(this.canvas().nativeElement.toDataURL('image/png'), croppedCoordinates, this.resultImageSize)
.subscribe({
next: (dataUrlHighRes) => {
this.drawingService.pred.imageData = dataUrlHighRes;
Expand All @@ -295,12 +299,18 @@ export class GameDrawComponent implements OnInit, OnDestroy {
}

classify(isMultiplayer = false) {
const b64Image = this.canvas.nativeElement.toDataURL('image/png');
const croppedCoordinates: any = this.imageService.crop(this.minX, this.minY, this.maxX, this.maxY, this.LINE_WIDTH);
const b64Image = this.canvas().nativeElement.toDataURL('image/png');
const croppedCoordinates: number[] = this.imageService.crop(
this.minX,
this.minY,
this.maxX,
this.maxY,
this.LINE_WIDTH
);
this.imageService.resize(b64Image, croppedCoordinates).subscribe({
next: (dataUrl) => {
if (isMultiplayer) {
const body = {
const body: { game_id?: string; time_left: number } = {
game_id: this.multiplayerService.stateInfo.game_id,
time_left: this.timeLeft,
};
Expand All @@ -313,18 +323,18 @@ export class GameDrawComponent implements OnInit, OnDestroy {
});
}

createFormData(dataUrl): FormData {
createFormData(dataUrl: string): FormData {
const formData: FormData = this.imageService.createFormData(dataUrl);
formData.append('player_id', this.drawingService.playerid);
formData.append('time', this.timeLeft.toString());
formData.append('client_round_num', this.drawingService.guessUsed.toString());
return formData;
}

getClientOffset(event) {
getClientOffset(event: any) {
const { pageX, pageY } = event.touches ? event.touches[0] : event;
const x = pageX - this.canvas.nativeElement.offsetLeft;
const y = pageY - this.canvas.nativeElement.offsetTop;
const x = pageX - this.canvas().nativeElement.offsetLeft;
const y = pageY - this.canvas().nativeElement.offsetTop;

return { x, y };
}
Expand Down Expand Up @@ -358,14 +368,16 @@ export class GameDrawComponent implements OnInit, OnDestroy {
this.hasLeftCanvas = false;
}

drawLine(currentX, currentY) {
this.ctx.strokeStyle = 'black';
this.ctx.lineWidth = this.LINE_WIDTH;
this.ctx.lineCap = this.ctx.lineJoin = 'round';
this.ctx.beginPath();
this.ctx.moveTo(this.x, this.y);
this.ctx.lineTo(currentX, currentY);
this.ctx.stroke();
drawLine(currentX: number, currentY: number) {
if (this.ctx) {
this.ctx.strokeStyle = 'black';
this.ctx.lineWidth = this.LINE_WIDTH;
this.ctx.lineCap = this.ctx.lineJoin = 'round';
this.ctx.beginPath();
this.ctx.moveTo(this.x, this.y);
this.ctx.lineTo(currentX, currentY);
this.ctx.stroke();
}

this.isBlankImage = false;

Expand All @@ -388,30 +400,30 @@ export class GameDrawComponent implements OnInit, OnDestroy {
if (this.minY < 0) {
this.minY = 0;
}
if (this.maxX > this.canvas.nativeElement.width) {
this.maxX = this.canvas.nativeElement.width;
if (this.maxX > this.canvas().nativeElement.width) {
this.maxX = this.canvas().nativeElement.width;
}
if (this.maxY > this.canvas.nativeElement.height) {
this.maxY = this.canvas.nativeElement.height;
if (this.maxY > this.canvas().nativeElement.height) {
this.maxY = this.canvas().nativeElement.height;
}
}

clear() {
const canvas = this.canvas.nativeElement;
this.ctx.clearRect(0, 0, canvas.width, canvas.height);
const canvas = this.canvas().nativeElement;
this.ctx?.clearRect(0, 0, canvas.width, canvas.height);
this.isBlankImage = true;
this.resetMinMaxMouseValues();
}

resetMinMaxMouseValues() {
this.minX = this.canvas.nativeElement.width;
this.minY = this.canvas.nativeElement.height;
this.minX = this.canvas().nativeElement.width;
this.minY = this.canvas().nativeElement.height;
this.maxX = 0;
this.maxY = 0;
}

stop(e) {
if (!this.timeOut && this.isDrawing) {
stop(e: MouseEvent | TouchEvent) {
if (!this.timeOut && this.isDrawing && e instanceof MouseEvent) {
this.drawLine(e.offsetX, e.offsetY);
this.isDrawing = false;
}
Expand Down
6 changes: 3 additions & 3 deletions src/app/game/game-draw/services/drawing.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export class DrawingService {

classify(answerInfo: FormData): Observable<any> {
return this.http.post<FormData>(`${this.baseUrl}/${endpoints.CLASSIFY}`, answerInfo).pipe(
tap((res) => {
tap((res: any) => {
this.pred = res;
if (this.guessUsed <= res.serverRound && this.roundIsDone(res) && !this.hasAddedSingleplayerResult) {
res.roundIsDone = true;
Expand Down Expand Up @@ -72,7 +72,7 @@ export class DrawingService {
return result;
}

createResult(res): Result {
createResult(res: any): Result {
const result: Result = {
hasWon: res.hasWon,
imageData: '',
Expand All @@ -84,7 +84,7 @@ export class DrawingService {
return result;
}

roundIsDone(res) {
roundIsDone(res: any) {
return res.hasWon || res.gameState === 'Done';
}

Expand Down
10 changes: 5 additions & 5 deletions src/app/game/game-draw/services/image.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export class ImageService {

constructor() {}

b64ToUint8Array(b64Image) {
b64ToUint8Array(b64Image: string) {
const img = atob(b64Image.split(',')[1]);
const imgBuffer: number[] = [];
let i = 0;
Expand All @@ -20,7 +20,7 @@ export class ImageService {
return new Uint8Array(imgBuffer);
}

resize(b64Image, croppedCoordinates, imageSize = 256): Observable<string> {
resize(b64Image: string, croppedCoordinates: number[], imageSize = 256): Observable<string> {
return new Observable((observer) => {
const img = new Image();
const canvas = document.createElement('canvas');
Expand All @@ -42,7 +42,7 @@ export class ImageService {
});
}

crop(minX, minY, maxX, maxY, userDrawLineWidth) {
crop(minX: number, minY: number, maxX: number, maxY: number, userDrawLineWidth: number) {
const paddingForLineWidth = userDrawLineWidth / 2;
const paddingExtra = 20;
const paddingTotal = paddingForLineWidth + paddingExtra;
Expand All @@ -62,7 +62,7 @@ export class ImageService {
return [sx, sy, sw, sh];
}

createFormData(dataUrl) {
createFormData(dataUrl: string) {
const u8Image = this.b64ToUint8Array(dataUrl);
const blob = new Blob([u8Image], {
type: 'image/png',
Expand All @@ -73,7 +73,7 @@ export class ImageService {
return formData;
}

createBlob(dataUrl) {
createBlob(dataUrl: string) {
const u8Image = this.b64ToUint8Array(dataUrl);
const blob = new Blob([u8Image], {
type: 'image/png',
Expand Down
Loading

0 comments on commit f712940

Please sign in to comment.