fix: NCWF-1 401 #5
+91
-123
@@ -1,125 +1,93 @@
|
||||
<div class="challenge-create-dialog-overlay" (click)="cancel()" [class.loading]="loading">
|
||||
<div class="challenge-create-dialog" (click)="$event.stopPropagation()">
|
||||
<div class="dialog-header">
|
||||
<h2>Create Challenge</h2>
|
||||
<button type="button" class="close-btn" (click)="cancel()" [disabled]="loading">×</button>
|
||||
<div class="challenge-create-dialog" (click)="$event.stopPropagation()">
|
||||
<div class="dialog-header">
|
||||
<h2>Create Challenge</h2>
|
||||
<button type="button" class="close-btn" (click)="cancel()" [disabled]="loading">×</button>
|
||||
</div>
|
||||
|
||||
<form [formGroup]="form" (ngSubmit)="submit()" class="dialog-form">
|
||||
<!-- Error Message -->
|
||||
<div *ngIf="errorMessage" class="error-message">
|
||||
{{ errorMessage }}
|
||||
</div>
|
||||
|
||||
<!-- Target Username -->
|
||||
<div class="form-group">
|
||||
<label for="targetUsername">Opponent Username</label>
|
||||
<input type="text" id="targetUsername" formControlName="targetUsername"
|
||||
placeholder="Enter opponent's username" [disabled]="loading" required />
|
||||
<small *ngIf="form.get('targetUsername')?.hasError('required') && form.get('targetUsername')?.touched">
|
||||
Username is required
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<!-- Player Color Selection -->
|
||||
<div class="form-group">
|
||||
<label for="color">Play as</label>
|
||||
<select id="color" formControlName="color" [disabled]="loading">
|
||||
<option value="white">White</option>
|
||||
<option value="black">Black</option>
|
||||
<option value="random">Random</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- Time Control Mode Selection -->
|
||||
<div class="form-group">
|
||||
<label for="timeMode">Time Control</label>
|
||||
<select id="timeMode" formControlName="timeMode" [disabled]="loading">
|
||||
<option value="blitz">Blitz</option>
|
||||
<option value="rapid">Rapid</option>
|
||||
<option value="classical">Classical</option>
|
||||
<option value="unlimited">Unlimited</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- Time Presets -->
|
||||
<div class="form-group" *ngIf="selectedTimeMode !== 'unlimited'">
|
||||
<label>Presets</label>
|
||||
<div class="preset-buttons">
|
||||
<button type="button" *ngFor="let preset of getAvailablePresets()" class="preset-btn"
|
||||
(click)="selectPreset(preset)" [disabled]="loading">
|
||||
{{ preset.label }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Custom Time Control -->
|
||||
<div class="form-group" *ngIf="selectedTimeMode !== 'unlimited'">
|
||||
<div class="form-row">
|
||||
<div class="form-col">
|
||||
<label for="limitMinutes">Time (minutes)</label>
|
||||
<input type="number" id="limitMinutes" formControlName="limitMinutes" min="1" max="1000"
|
||||
[disabled]="loading" />
|
||||
</div>
|
||||
<div class="form-col">
|
||||
<label for="incrementSeconds">Increment (seconds)</label>
|
||||
<input type="number" id="incrementSeconds" formControlName="incrementSeconds" min="0" max="300"
|
||||
[disabled]="loading" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- TTL (Time to Live) -->
|
||||
<div class="form-group">
|
||||
<label for="ttlSeconds">Challenge Expires In</label>
|
||||
<select id="ttlSeconds" formControlName="ttlSeconds" [disabled]="loading">
|
||||
<option *ngFor="let ttl of ttlOptions" [value]="ttl.seconds">
|
||||
{{ ttl.label }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- Buttons -->
|
||||
<div class="dialog-buttons">
|
||||
<button type="button" class="btn btn-secondary" (click)="cancel()" [disabled]="loading">
|
||||
Cancel
|
||||
</button>
|
||||
<button type="submit" class="btn btn-primary" [disabled]="form.invalid || loading">
|
||||
{{ loading ? 'Sending...' : 'Send Challenge' }}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<form [formGroup]="form" (ngSubmit)="submit()" class="dialog-form">
|
||||
<!-- Error Message -->
|
||||
<div *ngIf="errorMessage" class="error-message">
|
||||
{{ errorMessage }}
|
||||
</div>
|
||||
|
||||
<!-- Target Username -->
|
||||
<div class="form-group">
|
||||
<label for="targetUsername">Opponent Username</label>
|
||||
<input
|
||||
type="text"
|
||||
id="targetUsername"
|
||||
formControlName="targetUsername"
|
||||
placeholder="Enter opponent's username"
|
||||
[disabled]="loading"
|
||||
required
|
||||
/>
|
||||
<small *ngIf="form.get('targetUsername')?.hasError('required') && form.get('targetUsername')?.touched">
|
||||
Username is required
|
||||
</small>
|
||||
</div>
|
||||
|
||||
<!-- Player Color Selection -->
|
||||
<div class="form-group">
|
||||
<label for="color">Play as</label>
|
||||
<select id="color" formControlName="color" [disabled]="loading">
|
||||
<option value="white">White</option>
|
||||
<option value="black">Black</option>
|
||||
<option value="random">Random</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- Time Control Mode Selection -->
|
||||
<div class="form-group">
|
||||
<label for="timeMode">Time Control</label>
|
||||
<select id="timeMode" formControlName="timeMode" [disabled]="loading">
|
||||
<option value="blitz">Blitz</option>
|
||||
<option value="rapid">Rapid</option>
|
||||
<option value="classical">Classical</option>
|
||||
<option value="unlimited">Unlimited</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- Time Presets -->
|
||||
<div class="form-group" *ngIf="selectedTimeMode !== 'unlimited'">
|
||||
<label>Presets</label>
|
||||
<div class="preset-buttons">
|
||||
<button
|
||||
type="button"
|
||||
*ngFor="let preset of getAvailablePresets()"
|
||||
class="preset-btn"
|
||||
(click)="selectPreset(preset)"
|
||||
[disabled]="loading"
|
||||
>
|
||||
{{ preset.label }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Custom Time Control -->
|
||||
<div class="form-group" *ngIf="selectedTimeMode !== 'unlimited'">
|
||||
<div class="form-row">
|
||||
<div class="form-col">
|
||||
<label for="limitMinutes">Time (minutes)</label>
|
||||
<input
|
||||
type="number"
|
||||
id="limitMinutes"
|
||||
formControlName="limitMinutes"
|
||||
min="1"
|
||||
max="1000"
|
||||
[disabled]="loading"
|
||||
/>
|
||||
</div>
|
||||
<div class="form-col">
|
||||
<label for="incrementSeconds">Increment (seconds)</label>
|
||||
<input
|
||||
type="number"
|
||||
id="incrementSeconds"
|
||||
formControlName="incrementSeconds"
|
||||
min="0"
|
||||
max="300"
|
||||
[disabled]="loading"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- TTL (Time to Live) -->
|
||||
<div class="form-group">
|
||||
<label for="ttlSeconds">Challenge Expires In</label>
|
||||
<select id="ttlSeconds" formControlName="ttlSeconds" [disabled]="loading">
|
||||
<option *ngFor="let ttl of ttlOptions" [value]="ttl.seconds">
|
||||
{{ ttl.label }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- Buttons -->
|
||||
<div class="dialog-buttons">
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-secondary"
|
||||
(click)="cancel()"
|
||||
[disabled]="loading"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
class="btn btn-primary"
|
||||
[disabled]="form.invalid || loading"
|
||||
>
|
||||
{{ loading ? 'Sending...' : 'Send Challenge' }}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -11,149 +11,149 @@ import { PlayerColor } from '../../models/challenge.models';
|
||||
type TimeMode = 'blitz' | 'rapid' | 'classical' | 'unlimited';
|
||||
|
||||
interface TimePreset {
|
||||
label: string;
|
||||
limitSeconds: number;
|
||||
incrementSeconds: number;
|
||||
label: string;
|
||||
limitSeconds: number;
|
||||
incrementSeconds: number;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'app-challenge-create-dialog',
|
||||
standalone: true,
|
||||
imports: [CommonModule, FormsModule, ReactiveFormsModule],
|
||||
templateUrl: './challenge-create-dialog.component.html',
|
||||
styleUrls: ['./challenge-create-dialog.component.css']
|
||||
selector: 'app-challenge-create-dialog',
|
||||
standalone: true,
|
||||
imports: [CommonModule, FormsModule, ReactiveFormsModule],
|
||||
templateUrl: './challenge-create-dialog.component.html',
|
||||
styleUrls: ['./challenge-create-dialog.component.css']
|
||||
})
|
||||
export class ChallengeCreateDialogComponent implements OnInit, OnDestroy {
|
||||
private readonly challengeService = inject(ChallengeService);
|
||||
private readonly router = inject(Router);
|
||||
private readonly fb = inject(FormBuilder);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly challengeService = inject(ChallengeService);
|
||||
private readonly router = inject(Router);
|
||||
private readonly fb = inject(FormBuilder);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
|
||||
@Output() closeChallengeDialog = new EventEmitter<void>();
|
||||
@Output() closeChallengeDialog = new EventEmitter<void>();
|
||||
|
||||
form!: FormGroup;
|
||||
loading = false;
|
||||
errorMessage = '';
|
||||
selectedTimeMode: TimeMode = 'rapid';
|
||||
form!: FormGroup;
|
||||
loading = false;
|
||||
errorMessage = '';
|
||||
selectedTimeMode: TimeMode = 'rapid';
|
||||
|
||||
timePresets: Record<TimeMode, TimePreset[]> = {
|
||||
blitz: [
|
||||
{ label: '1+0', limitSeconds: 60, incrementSeconds: 0 },
|
||||
{ label: '2+1', limitSeconds: 120, incrementSeconds: 1 },
|
||||
{ label: '3+0', limitSeconds: 180, incrementSeconds: 0 },
|
||||
{ label: '3+2', limitSeconds: 180, incrementSeconds: 2 },
|
||||
{ label: '5+0', limitSeconds: 300, incrementSeconds: 0 }
|
||||
],
|
||||
rapid: [
|
||||
{ label: '10+0', limitSeconds: 600, incrementSeconds: 0 },
|
||||
{ label: '10+5', limitSeconds: 600, incrementSeconds: 5 },
|
||||
{ label: '15+10', limitSeconds: 900, incrementSeconds: 10 },
|
||||
{ label: '25+10', limitSeconds: 1500, incrementSeconds: 10 }
|
||||
],
|
||||
classical: [
|
||||
{ label: '30+0', limitSeconds: 1800, incrementSeconds: 0 },
|
||||
{ label: '30+20', limitSeconds: 1800, incrementSeconds: 20 },
|
||||
{ label: '60+30', limitSeconds: 3600, incrementSeconds: 30 },
|
||||
{ label: '90+30', limitSeconds: 5400, incrementSeconds: 30 }
|
||||
],
|
||||
unlimited: []
|
||||
};
|
||||
timePresets: Record<TimeMode, TimePreset[]> = {
|
||||
blitz: [
|
||||
{ label: '1+0', limitSeconds: 60, incrementSeconds: 0 },
|
||||
{ label: '2+1', limitSeconds: 120, incrementSeconds: 1 },
|
||||
{ label: '3+0', limitSeconds: 180, incrementSeconds: 0 },
|
||||
{ label: '3+2', limitSeconds: 180, incrementSeconds: 2 },
|
||||
{ label: '5+0', limitSeconds: 300, incrementSeconds: 0 }
|
||||
],
|
||||
rapid: [
|
||||
{ label: '10+0', limitSeconds: 600, incrementSeconds: 0 },
|
||||
{ label: '10+5', limitSeconds: 600, incrementSeconds: 5 },
|
||||
{ label: '15+10', limitSeconds: 900, incrementSeconds: 10 },
|
||||
{ label: '25+10', limitSeconds: 1500, incrementSeconds: 10 }
|
||||
],
|
||||
classical: [
|
||||
{ label: '30+0', limitSeconds: 1800, incrementSeconds: 0 },
|
||||
{ label: '30+20', limitSeconds: 1800, incrementSeconds: 20 },
|
||||
{ label: '60+30', limitSeconds: 3600, incrementSeconds: 30 },
|
||||
{ label: '90+30', limitSeconds: 5400, incrementSeconds: 30 }
|
||||
],
|
||||
unlimited: []
|
||||
};
|
||||
|
||||
ttlOptions = [
|
||||
{ label: '5 minutes', seconds: 300 },
|
||||
{ label: '1 hour', seconds: 3600 },
|
||||
{ label: '1 day', seconds: 86400 },
|
||||
{ label: 'No expiry', seconds: 0 }
|
||||
];
|
||||
ttlOptions = [
|
||||
{ label: '5 minutes', seconds: 300 },
|
||||
{ label: '1 hour', seconds: 3600 },
|
||||
{ label: '1 day', seconds: 86400 },
|
||||
{ label: 'No expiry', seconds: 0 }
|
||||
];
|
||||
|
||||
ngOnInit(): void {
|
||||
this.initializeForm();
|
||||
}
|
||||
ngOnInit(): void {
|
||||
this.initializeForm();
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
}
|
||||
ngOnDestroy(): void {
|
||||
}
|
||||
|
||||
private initializeForm(): void {
|
||||
this.form = this.fb.group({
|
||||
targetUsername: ['', [Validators.required, Validators.minLength(1)]],
|
||||
color: ['random', Validators.required],
|
||||
timeMode: ['rapid'],
|
||||
limitMinutes: [10, [Validators.required, Validators.min(1), Validators.max(1000)]],
|
||||
incrementSeconds: [5, [Validators.required, Validators.min(0), Validators.max(300)]],
|
||||
ttlSeconds: [3600, Validators.required]
|
||||
});
|
||||
private initializeForm(): void {
|
||||
this.form = this.fb.group({
|
||||
targetUsername: ['', [Validators.required, Validators.minLength(1)]],
|
||||
color: ['random', Validators.required],
|
||||
timeMode: ['rapid'],
|
||||
limitMinutes: [10, [Validators.required, Validators.min(1), Validators.max(1000)]],
|
||||
incrementSeconds: [5, [Validators.required, Validators.min(0), Validators.max(300)]],
|
||||
ttlSeconds: [3600, Validators.required]
|
||||
});
|
||||
|
||||
this.form.get('timeMode')?.valueChanges
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe((mode: unknown) => {
|
||||
const timeMode = mode as TimeMode;
|
||||
this.selectedTimeMode = timeMode;
|
||||
if (timeMode !== 'unlimited') {
|
||||
const firstPreset = this.timePresets[timeMode][0];
|
||||
if (firstPreset) {
|
||||
this.form.patchValue({
|
||||
limitMinutes: firstPreset.limitSeconds / 60,
|
||||
incrementSeconds: firstPreset.incrementSeconds
|
||||
this.form.get('timeMode')?.valueChanges
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe((mode: unknown) => {
|
||||
const timeMode = mode as TimeMode;
|
||||
this.selectedTimeMode = timeMode;
|
||||
if (timeMode !== 'unlimited') {
|
||||
const firstPreset = this.timePresets[timeMode][0];
|
||||
if (firstPreset) {
|
||||
this.form.patchValue({
|
||||
limitMinutes: firstPreset.limitSeconds / 60,
|
||||
incrementSeconds: firstPreset.incrementSeconds
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
selectPreset(preset: TimePreset): void {
|
||||
this.form.patchValue({
|
||||
limitMinutes: preset.limitSeconds / 60,
|
||||
incrementSeconds: preset.incrementSeconds
|
||||
});
|
||||
}
|
||||
|
||||
getAvailablePresets(): TimePreset[] {
|
||||
return this.timePresets[this.selectedTimeMode] || [];
|
||||
}
|
||||
|
||||
submit(): void {
|
||||
if (this.form.invalid || this.loading) {
|
||||
return;
|
||||
}
|
||||
|
||||
const targetUsername = this.form.get('targetUsername')?.value?.trim();
|
||||
if (!targetUsername) {
|
||||
this.errorMessage = 'Please enter a valid username';
|
||||
return;
|
||||
selectPreset(preset: TimePreset): void {
|
||||
this.form.patchValue({
|
||||
limitMinutes: preset.limitSeconds / 60,
|
||||
incrementSeconds: preset.incrementSeconds
|
||||
});
|
||||
}
|
||||
|
||||
this.errorMessage = '';
|
||||
this.loading = true;
|
||||
getAvailablePresets(): TimePreset[] {
|
||||
return this.timePresets[this.selectedTimeMode] || [];
|
||||
}
|
||||
|
||||
const limitSeconds = Math.round((this.form.get('limitMinutes')?.value || 0) * 60);
|
||||
const incrementSeconds = this.form.get('incrementSeconds')?.value || 0;
|
||||
const ttlSeconds = this.form.get('ttlSeconds')?.value;
|
||||
const color = (this.form.get('color')?.value || 'random') as PlayerColor;
|
||||
|
||||
this.challengeService.sendChallenge(targetUsername, {
|
||||
timeControl: {
|
||||
limitSeconds,
|
||||
incrementSeconds
|
||||
},
|
||||
color,
|
||||
ttlSeconds: ttlSeconds > 0 ? ttlSeconds : undefined
|
||||
})
|
||||
.pipe(finalize(() => (this.loading = false)))
|
||||
.subscribe({
|
||||
next: (challenge) => {
|
||||
// Challenge sent successfully - navigate to challenges page to view status
|
||||
this.form.reset();
|
||||
this.closeChallengeDialog.emit();
|
||||
void this.router.navigate(['/challenges']);
|
||||
},
|
||||
error: (error) => {
|
||||
this.errorMessage = getErrorMessage(error, 'Failed to send challenge. Please try again.');
|
||||
submit(): void {
|
||||
if (this.form.invalid || this.loading) {
|
||||
return;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
cancel(): void {
|
||||
this.form.reset();
|
||||
this.closeChallengeDialog.emit();
|
||||
}
|
||||
const targetUsername = this.form.get('targetUsername')?.value?.trim();
|
||||
if (!targetUsername) {
|
||||
this.errorMessage = 'Please enter a valid username';
|
||||
return;
|
||||
}
|
||||
|
||||
this.errorMessage = '';
|
||||
this.loading = true;
|
||||
|
||||
const limitSeconds = Math.round((this.form.get('limitMinutes')?.value || 0) * 60);
|
||||
const incrementSeconds = this.form.get('incrementSeconds')?.value || 0;
|
||||
const ttlSeconds = this.form.get('ttlSeconds')?.value;
|
||||
const color = (this.form.get('color')?.value || 'random') as PlayerColor;
|
||||
|
||||
this.challengeService.sendChallenge(targetUsername, {
|
||||
timeControl: {
|
||||
limitSeconds,
|
||||
incrementSeconds
|
||||
},
|
||||
color,
|
||||
ttlSeconds: ttlSeconds > 0 ? ttlSeconds : undefined
|
||||
})
|
||||
.pipe(finalize(() => (this.loading = false)))
|
||||
.subscribe({
|
||||
next: (challenge) => {
|
||||
// Challenge sent successfully - navigate to challenges page to view status
|
||||
this.form.reset();
|
||||
this.closeChallengeDialog.emit();
|
||||
void this.router.navigate(['/challenges']);
|
||||
},
|
||||
error: (error) => {
|
||||
this.errorMessage = getErrorMessage(error, 'Failed to send challenge. Please try again.');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
cancel(): void {
|
||||
this.form.reset();
|
||||
this.closeChallengeDialog.emit();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,45 +1,38 @@
|
||||
<div class="challenge-notification" [class.error]="!!errorMessage">
|
||||
<div class="notification-header">
|
||||
<div class="notification-title">
|
||||
<span class="badge">CHALLENGE</span>
|
||||
<span class="title">{{ getCreatedByDisplay() }} challenged you!</span>
|
||||
</div>
|
||||
<button type="button" class="close-btn" (click)="onClose()" [disabled]="acceptingChallenge || decliningChallenge">
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="notification-content">
|
||||
<div class="time-control">
|
||||
<span class="label">Time Control:</span>
|
||||
<span class="value">{{ getTimeControlDisplay() }}</span>
|
||||
<div class="notification-header">
|
||||
<div class="notification-title">
|
||||
<span class="badge">CHALLENGE</span>
|
||||
<span class="title">{{ getCreatedByDisplay() }} challenged you!</span>
|
||||
</div>
|
||||
<button type="button" class="close-btn" (click)="onClose()"
|
||||
[disabled]="acceptingChallenge || decliningChallenge">
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="expiration">
|
||||
<span class="label">{{ getExpirationInfo() }}</span>
|
||||
</div>
|
||||
<div class="notification-content">
|
||||
<div class="time-control">
|
||||
<span class="label">Time Control:</span>
|
||||
<span class="value">{{ getTimeControlDisplay() }}</span>
|
||||
</div>
|
||||
|
||||
<div *ngIf="errorMessage" class="error-message">
|
||||
{{ errorMessage }}
|
||||
</div>
|
||||
<div class="expiration">
|
||||
<span class="label">{{ getExpirationInfo() }}</span>
|
||||
</div>
|
||||
|
||||
<div class="notification-actions">
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-decline"
|
||||
(click)="onDecline()"
|
||||
[disabled]="acceptingChallenge || decliningChallenge"
|
||||
>
|
||||
{{ decliningChallenge ? 'Declining...' : 'Decline' }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-accept"
|
||||
(click)="onAccept()"
|
||||
[disabled]="acceptingChallenge || decliningChallenge"
|
||||
>
|
||||
{{ acceptingChallenge ? 'Accepting...' : 'Accept' }}
|
||||
</button>
|
||||
<div *ngIf="errorMessage" class="error-message">
|
||||
{{ errorMessage }}
|
||||
</div>
|
||||
|
||||
<div class="notification-actions">
|
||||
<button type="button" class="btn btn-decline" (click)="onDecline()"
|
||||
[disabled]="acceptingChallenge || decliningChallenge">
|
||||
{{ decliningChallenge ? 'Declining...' : 'Decline' }}
|
||||
</button>
|
||||
<button type="button" class="btn btn-accept" (click)="onAccept()"
|
||||
[disabled]="acceptingChallenge || decliningChallenge">
|
||||
{{ acceptingChallenge ? 'Accepting...' : 'Accept' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -6,96 +6,96 @@ import { finalize } from 'rxjs';
|
||||
import { getErrorMessage } from '../../core/http/error-message.util';
|
||||
|
||||
@Component({
|
||||
selector: 'app-challenge-notification',
|
||||
standalone: true,
|
||||
imports: [CommonModule],
|
||||
templateUrl: './challenge-notification.component.html',
|
||||
styleUrls: ['./challenge-notification.component.css']
|
||||
selector: 'app-challenge-notification',
|
||||
standalone: true,
|
||||
imports: [CommonModule],
|
||||
templateUrl: './challenge-notification.component.html',
|
||||
styleUrls: ['./challenge-notification.component.css']
|
||||
})
|
||||
export class ChallengeNotificationComponent {
|
||||
@Input() challenge!: Challenge;
|
||||
@Output() accept = new EventEmitter<Challenge>();
|
||||
@Output() decline = new EventEmitter<Challenge>();
|
||||
@Output() close = new EventEmitter<void>();
|
||||
@Input() challenge!: Challenge;
|
||||
@Output() accept = new EventEmitter<Challenge>();
|
||||
@Output() decline = new EventEmitter<Challenge>();
|
||||
@Output() close = new EventEmitter<void>();
|
||||
|
||||
private readonly challengeService = inject(ChallengeService);
|
||||
private readonly challengeService = inject(ChallengeService);
|
||||
|
||||
acceptingChallenge = false;
|
||||
decliningChallenge = false;
|
||||
errorMessage = '';
|
||||
acceptingChallenge = false;
|
||||
decliningChallenge = false;
|
||||
errorMessage = '';
|
||||
|
||||
onAccept(): void {
|
||||
if (this.acceptingChallenge || this.decliningChallenge) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.acceptingChallenge = true;
|
||||
this.errorMessage = '';
|
||||
|
||||
this.challengeService.acceptChallenge(this.challenge.id)
|
||||
.pipe(finalize(() => (this.acceptingChallenge = false)))
|
||||
.subscribe({
|
||||
next: () => {
|
||||
this.accept.emit(this.challenge);
|
||||
},
|
||||
error: (error) => {
|
||||
this.errorMessage = getErrorMessage(error, 'Failed to accept challenge');
|
||||
onAccept(): void {
|
||||
if (this.acceptingChallenge || this.decliningChallenge) {
|
||||
return;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onDecline(): void {
|
||||
if (this.acceptingChallenge || this.decliningChallenge) {
|
||||
return;
|
||||
this.acceptingChallenge = true;
|
||||
this.errorMessage = '';
|
||||
|
||||
this.challengeService.acceptChallenge(this.challenge.id)
|
||||
.pipe(finalize(() => (this.acceptingChallenge = false)))
|
||||
.subscribe({
|
||||
next: () => {
|
||||
this.accept.emit(this.challenge);
|
||||
},
|
||||
error: (error) => {
|
||||
this.errorMessage = getErrorMessage(error, 'Failed to accept challenge');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
this.decliningChallenge = true;
|
||||
this.errorMessage = '';
|
||||
|
||||
this.challengeService.declineChallenge(this.challenge.id, { reason: 'Not interested' })
|
||||
.pipe(finalize(() => (this.decliningChallenge = false)))
|
||||
.subscribe({
|
||||
next: () => {
|
||||
this.decline.emit(this.challenge);
|
||||
},
|
||||
error: (error) => {
|
||||
this.errorMessage = getErrorMessage(error, 'Failed to decline challenge');
|
||||
onDecline(): void {
|
||||
if (this.acceptingChallenge || this.decliningChallenge) {
|
||||
return;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onClose(): void {
|
||||
this.close.emit();
|
||||
}
|
||||
this.decliningChallenge = true;
|
||||
this.errorMessage = '';
|
||||
|
||||
getTimeControlDisplay(): string {
|
||||
const { limit, increment } = this.challenge.timeControl;
|
||||
if (!limit || !increment) {
|
||||
return 'Unlimited';
|
||||
}
|
||||
const minutes = Math.floor(limit / 60);
|
||||
return `${minutes}+${increment}`;
|
||||
}
|
||||
|
||||
getCreatedByDisplay(): string {
|
||||
return this.challenge.challenger.name;
|
||||
}
|
||||
|
||||
getExpirationInfo(): string {
|
||||
const expiresAt = new Date(this.challenge.expiresAt);
|
||||
const now = new Date();
|
||||
const diffMs = expiresAt.getTime() - now.getTime();
|
||||
|
||||
if (diffMs <= 0) {
|
||||
return 'Expired';
|
||||
this.challengeService.declineChallenge(this.challenge.id, { reason: 'Not interested' })
|
||||
.pipe(finalize(() => (this.decliningChallenge = false)))
|
||||
.subscribe({
|
||||
next: () => {
|
||||
this.decline.emit(this.challenge);
|
||||
},
|
||||
error: (error) => {
|
||||
this.errorMessage = getErrorMessage(error, 'Failed to decline challenge');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const minutes = Math.floor(diffMs / 60000);
|
||||
if (minutes > 60) {
|
||||
const hours = Math.floor(minutes / 60);
|
||||
return `Expires in ${hours}h`;
|
||||
onClose(): void {
|
||||
this.close.emit();
|
||||
}
|
||||
|
||||
return `Expires in ${minutes}m`;
|
||||
}
|
||||
getTimeControlDisplay(): string {
|
||||
const { limit, increment } = this.challenge.timeControl;
|
||||
if (!limit || !increment) {
|
||||
return 'Unlimited';
|
||||
}
|
||||
const minutes = Math.floor(limit / 60);
|
||||
return `${minutes}+${increment}`;
|
||||
}
|
||||
|
||||
getCreatedByDisplay(): string {
|
||||
return this.challenge.challenger.name;
|
||||
}
|
||||
|
||||
getExpirationInfo(): string {
|
||||
const expiresAt = new Date(this.challenge.expiresAt);
|
||||
const now = new Date();
|
||||
const diffMs = expiresAt.getTime() - now.getTime();
|
||||
|
||||
if (diffMs <= 0) {
|
||||
return 'Expired';
|
||||
}
|
||||
|
||||
const minutes = Math.floor(diffMs / 60000);
|
||||
if (minutes > 60) {
|
||||
const hours = Math.floor(minutes / 60);
|
||||
return `Expires in ${hours}h`;
|
||||
}
|
||||
|
||||
return `Expires in ${minutes}m`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,13 +5,8 @@
|
||||
<div class="d-flex align-items-center gap-2">
|
||||
<!-- Challenge Notification Badge -->
|
||||
<div class="notification-container">
|
||||
<button
|
||||
type="button"
|
||||
class="notification-badge"
|
||||
(click)="toggleNotificationMenu()"
|
||||
[class.has-notifications]="incomingChallenges.length > 0"
|
||||
title="View challenges"
|
||||
>
|
||||
<button type="button" class="notification-badge" (click)="toggleNotificationMenu()"
|
||||
[class.has-notifications]="incomingChallenges.length > 0" title="View challenges">
|
||||
🔔
|
||||
<span *ngIf="incomingChallenges.length > 0" class="badge">
|
||||
{{ incomingChallenges.length }}
|
||||
@@ -67,12 +62,8 @@
|
||||
|
||||
<!-- Challenge Notification Popup -->
|
||||
@if (displayedChallenge) {
|
||||
<app-challenge-notification
|
||||
[challenge]="displayedChallenge"
|
||||
(accept)="onChallengeAccepted($event)"
|
||||
(decline)="onChallengeDeclined($event)"
|
||||
(close)="onNotificationClose()"
|
||||
/>
|
||||
<app-challenge-notification [challenge]="displayedChallenge" (accept)="onChallengeAccepted($event)"
|
||||
(decline)="onChallengeDeclined($event)" (close)="onNotificationClose()" />
|
||||
}
|
||||
|
||||
@if (showLoginDialog) {
|
||||
|
||||
@@ -3,47 +3,47 @@ export type ChallengeStatus = 'created' | 'pending' | 'accepted' | 'declined' |
|
||||
export type PlayerColor = 'white' | 'black' | 'random';
|
||||
|
||||
export interface Player {
|
||||
id: string;
|
||||
name: string;
|
||||
rating: number;
|
||||
id: string;
|
||||
name: string;
|
||||
rating: number;
|
||||
}
|
||||
|
||||
export interface TimeControl {
|
||||
type: string | null;
|
||||
limit: number | null;
|
||||
increment: number | null;
|
||||
type: string | null;
|
||||
limit: number | null;
|
||||
increment: number | null;
|
||||
}
|
||||
|
||||
export interface Challenge {
|
||||
id: string;
|
||||
challenger: Player;
|
||||
destUser: Player;
|
||||
variant: string;
|
||||
color: PlayerColor;
|
||||
timeControl: TimeControl;
|
||||
status: ChallengeStatus;
|
||||
declineReason: string | null;
|
||||
gameId: string | null;
|
||||
expiresAt: string;
|
||||
createdAt: string;
|
||||
id: string;
|
||||
challenger: Player;
|
||||
destUser: Player;
|
||||
variant: string;
|
||||
color: PlayerColor;
|
||||
timeControl: TimeControl;
|
||||
status: ChallengeStatus;
|
||||
declineReason: string | null;
|
||||
gameId: string | null;
|
||||
expiresAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface SendChallengeRequest {
|
||||
timeControl: {
|
||||
limitSeconds: number;
|
||||
incrementSeconds: number;
|
||||
};
|
||||
color?: PlayerColor;
|
||||
ttlSeconds?: number;
|
||||
timeControl: {
|
||||
limitSeconds: number;
|
||||
incrementSeconds: number;
|
||||
};
|
||||
color?: PlayerColor;
|
||||
ttlSeconds?: number;
|
||||
}
|
||||
|
||||
export interface ListChallengesResponse {
|
||||
'in'?: Challenge[];
|
||||
'out'?: Challenge[];
|
||||
incoming?: Challenge[];
|
||||
outgoing?: Challenge[];
|
||||
'in'?: Challenge[];
|
||||
'out'?: Challenge[];
|
||||
incoming?: Challenge[];
|
||||
outgoing?: Challenge[];
|
||||
}
|
||||
|
||||
export interface DeclineChallengeRequest {
|
||||
reason?: string;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
@@ -1,102 +1,90 @@
|
||||
<div class="challenges-container">
|
||||
<div class="challenges-header">
|
||||
<h1>Active Challenges</h1>
|
||||
<button type="button" class="back-btn" (click)="goBack()">← Back</button>
|
||||
</div>
|
||||
|
||||
<div *ngIf="errorMessage" class="error-banner">
|
||||
{{ errorMessage }}
|
||||
</div>
|
||||
|
||||
<div class="challenges-grid">
|
||||
<!-- Incoming Challenges -->
|
||||
<div class="challenges-section">
|
||||
<h2>Incoming Challenges</h2>
|
||||
<div *ngIf="loading" class="loading-spinner">Loading...</div>
|
||||
|
||||
<div *ngIf="!loading && incomingChallenges.length === 0" class="empty-state">
|
||||
<p>No incoming challenges</p>
|
||||
</div>
|
||||
|
||||
<div *ngIf="!loading && incomingChallenges.length > 0" class="challenge-list">
|
||||
<div *ngFor="let challenge of incomingChallenges" class="challenge-card">
|
||||
<div class="challenge-header">
|
||||
<span class="challenger-name">{{ getChallengerDisplay(challenge) }}</span>
|
||||
<span class="time-control">{{ getTimeControlDisplay(challenge) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="challenge-details">
|
||||
<div class="detail">
|
||||
<span class="label">Status:</span>
|
||||
<span class="value" [class]="'status-' + challenge.status">
|
||||
{{ challenge.status | uppercase }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="detail">
|
||||
<span class="label">Expires in:</span>
|
||||
<span class="value">{{ getExpirationInfo(challenge) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="challenge-actions" *ngIf="challenge.status === 'created'">
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-decline"
|
||||
(click)="declineChallenge(challenge)"
|
||||
>
|
||||
Decline
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-accept"
|
||||
(click)="acceptChallenge(challenge)"
|
||||
>
|
||||
Accept
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="challenges-header">
|
||||
<h1>Active Challenges</h1>
|
||||
<button type="button" class="back-btn" (click)="goBack()">← Back</button>
|
||||
</div>
|
||||
|
||||
<!-- Outgoing Challenges -->
|
||||
<div class="challenges-section">
|
||||
<h2>Outgoing Challenges</h2>
|
||||
|
||||
<div *ngIf="!loading && outgoingChallenges.length === 0" class="empty-state">
|
||||
<p>No outgoing challenges</p>
|
||||
</div>
|
||||
|
||||
<div *ngIf="!loading && outgoingChallenges.length > 0" class="challenge-list">
|
||||
<div *ngFor="let challenge of outgoingChallenges" class="challenge-card">
|
||||
<div class="challenge-header">
|
||||
<span class="challenger-name">→ {{ getOpponentDisplay(challenge) }}</span>
|
||||
<span class="time-control">{{ getTimeControlDisplay(challenge) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="challenge-details">
|
||||
<div class="detail">
|
||||
<span class="label">Status:</span>
|
||||
<span class="value" [class]="'status-' + challenge.status">
|
||||
{{ challenge.status | uppercase }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="detail">
|
||||
<span class="label">Expires in:</span>
|
||||
<span class="value">{{ getExpirationInfo(challenge) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="challenge-actions" *ngIf="challenge.status === 'created'">
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-cancel"
|
||||
(click)="cancelChallenge(challenge)"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div *ngIf="errorMessage" class="error-banner">
|
||||
{{ errorMessage }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="challenges-grid">
|
||||
<!-- Incoming Challenges -->
|
||||
<div class="challenges-section">
|
||||
<h2>Incoming Challenges</h2>
|
||||
<div *ngIf="loading" class="loading-spinner">Loading...</div>
|
||||
|
||||
<div *ngIf="!loading && incomingChallenges.length === 0" class="empty-state">
|
||||
<p>No incoming challenges</p>
|
||||
</div>
|
||||
|
||||
<div *ngIf="!loading && incomingChallenges.length > 0" class="challenge-list">
|
||||
<div *ngFor="let challenge of incomingChallenges" class="challenge-card">
|
||||
<div class="challenge-header">
|
||||
<span class="challenger-name">{{ getChallengerDisplay(challenge) }}</span>
|
||||
<span class="time-control">{{ getTimeControlDisplay(challenge) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="challenge-details">
|
||||
<div class="detail">
|
||||
<span class="label">Status:</span>
|
||||
<span class="value" [class]="'status-' + challenge.status">
|
||||
{{ challenge.status | uppercase }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="detail">
|
||||
<span class="label">Expires in:</span>
|
||||
<span class="value">{{ getExpirationInfo(challenge) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="challenge-actions" *ngIf="challenge.status === 'created'">
|
||||
<button type="button" class="btn btn-decline" (click)="declineChallenge(challenge)">
|
||||
Decline
|
||||
</button>
|
||||
<button type="button" class="btn btn-accept" (click)="acceptChallenge(challenge)">
|
||||
Accept
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Outgoing Challenges -->
|
||||
<div class="challenges-section">
|
||||
<h2>Outgoing Challenges</h2>
|
||||
|
||||
<div *ngIf="!loading && outgoingChallenges.length === 0" class="empty-state">
|
||||
<p>No outgoing challenges</p>
|
||||
</div>
|
||||
|
||||
<div *ngIf="!loading && outgoingChallenges.length > 0" class="challenge-list">
|
||||
<div *ngFor="let challenge of outgoingChallenges" class="challenge-card">
|
||||
<div class="challenge-header">
|
||||
<span class="challenger-name">→ {{ getOpponentDisplay(challenge) }}</span>
|
||||
<span class="time-control">{{ getTimeControlDisplay(challenge) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="challenge-details">
|
||||
<div class="detail">
|
||||
<span class="label">Status:</span>
|
||||
<span class="value" [class]="'status-' + challenge.status">
|
||||
{{ challenge.status | uppercase }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="detail">
|
||||
<span class="label">Expires in:</span>
|
||||
<span class="value">{{ getExpirationInfo(challenge) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="challenge-actions" *ngIf="challenge.status === 'created'">
|
||||
<button type="button" class="btn btn-cancel" (click)="cancelChallenge(challenge)">
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -8,160 +8,160 @@ import { Challenge } from '../../models/challenge.models';
|
||||
import { getErrorMessage } from '../../core/http/error-message.util';
|
||||
|
||||
@Component({
|
||||
selector: 'app-challenges',
|
||||
standalone: true,
|
||||
imports: [CommonModule],
|
||||
templateUrl: './challenges.component.html',
|
||||
styleUrls: ['./challenges.component.css']
|
||||
selector: 'app-challenges',
|
||||
standalone: true,
|
||||
imports: [CommonModule],
|
||||
templateUrl: './challenges.component.html',
|
||||
styleUrls: ['./challenges.component.css']
|
||||
})
|
||||
export class ChallengesComponent implements OnInit, OnDestroy {
|
||||
private readonly challengeService = inject(ChallengeService);
|
||||
private readonly challengeEventService = inject(ChallengeEventService);
|
||||
private readonly router = inject(Router);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
private readonly challengeService = inject(ChallengeService);
|
||||
private readonly challengeEventService = inject(ChallengeEventService);
|
||||
private readonly router = inject(Router);
|
||||
private readonly destroyRef = inject(DestroyRef);
|
||||
|
||||
incomingChallenges: Challenge[] = [];
|
||||
outgoingChallenges: Challenge[] = [];
|
||||
loading = false;
|
||||
errorMessage = '';
|
||||
incomingChallenges: Challenge[] = [];
|
||||
outgoingChallenges: Challenge[] = [];
|
||||
loading = false;
|
||||
errorMessage = '';
|
||||
|
||||
private pollInterval: any = null;
|
||||
private readonly pollIntervalMs = 5000; // Poll every 5 seconds
|
||||
private pollInterval: any = null;
|
||||
private readonly pollIntervalMs = 5000; // Poll every 5 seconds
|
||||
|
||||
ngOnInit(): void {
|
||||
this.loadChallenges(true);
|
||||
ngOnInit(): void {
|
||||
this.loadChallenges(true);
|
||||
|
||||
// Subscribe to challenge events
|
||||
this.challengeEventService.getChallengeReceived$()
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe(() => {
|
||||
this.loadChallenges();
|
||||
});
|
||||
// Subscribe to challenge events
|
||||
this.challengeEventService.getChallengeReceived$()
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe(() => {
|
||||
this.loadChallenges();
|
||||
});
|
||||
|
||||
// Start polling for challenge updates
|
||||
this.startPolling();
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.stopPolling();
|
||||
}
|
||||
|
||||
private startPolling(): void {
|
||||
this.pollInterval = setInterval(() => {
|
||||
this.loadChallenges(false);
|
||||
}, this.pollIntervalMs);
|
||||
}
|
||||
|
||||
private stopPolling(): void {
|
||||
if (this.pollInterval) {
|
||||
clearInterval(this.pollInterval);
|
||||
this.pollInterval = null;
|
||||
}
|
||||
}
|
||||
|
||||
loadChallenges(showLoader = false): void {
|
||||
if (showLoader) {
|
||||
this.loading = true;
|
||||
this.errorMessage = '';
|
||||
// Start polling for challenge updates
|
||||
this.startPolling();
|
||||
}
|
||||
|
||||
this.challengeService.listChallenges()
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe({
|
||||
next: (response) => {
|
||||
this.incomingChallenges = response.in || response.incoming || [];
|
||||
this.outgoingChallenges = response.out || response.outgoing || [];
|
||||
if (showLoader) {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
error: (error) => {
|
||||
this.errorMessage = getErrorMessage(error, 'Failed to load challenges');
|
||||
if (showLoader) {
|
||||
this.loading = false;
|
||||
}
|
||||
ngOnDestroy(): void {
|
||||
this.stopPolling();
|
||||
}
|
||||
|
||||
private startPolling(): void {
|
||||
this.pollInterval = setInterval(() => {
|
||||
this.loadChallenges(false);
|
||||
}, this.pollIntervalMs);
|
||||
}
|
||||
|
||||
private stopPolling(): void {
|
||||
if (this.pollInterval) {
|
||||
clearInterval(this.pollInterval);
|
||||
this.pollInterval = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
acceptChallenge(challenge: Challenge): void {
|
||||
this.challengeService.acceptChallenge(challenge.id)
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe({
|
||||
next: () => {
|
||||
this.challengeEventService.onChallengeAccepted(challenge);
|
||||
this.loadChallenges();
|
||||
// Navigate to game (if backend creates game automatically)
|
||||
},
|
||||
error: (error) => {
|
||||
this.errorMessage = getErrorMessage(error, 'Failed to accept challenge');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
declineChallenge(challenge: Challenge): void {
|
||||
this.challengeService.declineChallenge(challenge.id, { reason: 'Not interested' })
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe({
|
||||
next: () => {
|
||||
this.challengeEventService.removeChallenge(challenge.id);
|
||||
this.loadChallenges();
|
||||
},
|
||||
error: (error) => {
|
||||
this.errorMessage = getErrorMessage(error, 'Failed to decline challenge');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
cancelChallenge(challenge: Challenge): void {
|
||||
this.challengeService.cancelChallenge(challenge.id)
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe({
|
||||
next: () => {
|
||||
this.loadChallenges();
|
||||
},
|
||||
error: (error) => {
|
||||
this.errorMessage = getErrorMessage(error, 'Failed to cancel challenge');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
goBack(): void {
|
||||
void this.router.navigate(['/']);
|
||||
}
|
||||
|
||||
getTimeControlDisplay(challenge: Challenge): string {
|
||||
const { limit, increment } = challenge.timeControl;
|
||||
if (!limit || !increment) {
|
||||
return 'Unlimited';
|
||||
}
|
||||
const minutes = Math.floor(limit / 60);
|
||||
return `${minutes}+${increment}`;
|
||||
}
|
||||
|
||||
getChallengerDisplay(challenge: Challenge): string {
|
||||
return challenge.challenger.name;
|
||||
}
|
||||
|
||||
getOpponentDisplay(challenge: Challenge): string {
|
||||
return challenge.destUser.name;
|
||||
}
|
||||
|
||||
getExpirationInfo(challenge: Challenge): string {
|
||||
const expiresAt = new Date(challenge.expiresAt);
|
||||
const now = new Date();
|
||||
const diffMs = expiresAt.getTime() - now.getTime();
|
||||
|
||||
if (diffMs <= 0 || challenge.status === 'expired') {
|
||||
return 'Expired';
|
||||
}
|
||||
|
||||
const minutes = Math.floor(diffMs / 60000);
|
||||
if (minutes > 60) {
|
||||
const hours = Math.floor(minutes / 60);
|
||||
return `${hours}h`;
|
||||
loadChallenges(showLoader = false): void {
|
||||
if (showLoader) {
|
||||
this.loading = true;
|
||||
this.errorMessage = '';
|
||||
}
|
||||
|
||||
this.challengeService.listChallenges()
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe({
|
||||
next: (response) => {
|
||||
this.incomingChallenges = response.in || response.incoming || [];
|
||||
this.outgoingChallenges = response.out || response.outgoing || [];
|
||||
if (showLoader) {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
error: (error) => {
|
||||
this.errorMessage = getErrorMessage(error, 'Failed to load challenges');
|
||||
if (showLoader) {
|
||||
this.loading = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return `${minutes}m`;
|
||||
}
|
||||
acceptChallenge(challenge: Challenge): void {
|
||||
this.challengeService.acceptChallenge(challenge.id)
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe({
|
||||
next: () => {
|
||||
this.challengeEventService.onChallengeAccepted(challenge);
|
||||
this.loadChallenges();
|
||||
// Navigate to game (if backend creates game automatically)
|
||||
},
|
||||
error: (error) => {
|
||||
this.errorMessage = getErrorMessage(error, 'Failed to accept challenge');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
declineChallenge(challenge: Challenge): void {
|
||||
this.challengeService.declineChallenge(challenge.id, { reason: 'Not interested' })
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe({
|
||||
next: () => {
|
||||
this.challengeEventService.removeChallenge(challenge.id);
|
||||
this.loadChallenges();
|
||||
},
|
||||
error: (error) => {
|
||||
this.errorMessage = getErrorMessage(error, 'Failed to decline challenge');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
cancelChallenge(challenge: Challenge): void {
|
||||
this.challengeService.cancelChallenge(challenge.id)
|
||||
.pipe(takeUntilDestroyed(this.destroyRef))
|
||||
.subscribe({
|
||||
next: () => {
|
||||
this.loadChallenges();
|
||||
},
|
||||
error: (error) => {
|
||||
this.errorMessage = getErrorMessage(error, 'Failed to cancel challenge');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
goBack(): void {
|
||||
void this.router.navigate(['/']);
|
||||
}
|
||||
|
||||
getTimeControlDisplay(challenge: Challenge): string {
|
||||
const { limit, increment } = challenge.timeControl;
|
||||
if (!limit || !increment) {
|
||||
return 'Unlimited';
|
||||
}
|
||||
const minutes = Math.floor(limit / 60);
|
||||
return `${minutes}+${increment}`;
|
||||
}
|
||||
|
||||
getChallengerDisplay(challenge: Challenge): string {
|
||||
return challenge.challenger.name;
|
||||
}
|
||||
|
||||
getOpponentDisplay(challenge: Challenge): string {
|
||||
return challenge.destUser.name;
|
||||
}
|
||||
|
||||
getExpirationInfo(challenge: Challenge): string {
|
||||
const expiresAt = new Date(challenge.expiresAt);
|
||||
const now = new Date();
|
||||
const diffMs = expiresAt.getTime() - now.getTime();
|
||||
|
||||
if (diffMs <= 0 || challenge.status === 'expired') {
|
||||
return 'Expired';
|
||||
}
|
||||
|
||||
const minutes = Math.floor(diffMs / 60000);
|
||||
if (minutes > 60) {
|
||||
const hours = Math.floor(minutes / 60);
|
||||
return `${hours}h`;
|
||||
}
|
||||
|
||||
return `${minutes}m`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,57 +8,57 @@ import { Challenge } from '../models/challenge.models';
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class ChallengeEventService {
|
||||
private readonly incomingChallenges$ = new BehaviorSubject<Challenge[]>([]);
|
||||
private readonly challengeReceived$ = new Subject<Challenge>();
|
||||
private readonly challengeAccepted$ = new Subject<Challenge>();
|
||||
private readonly challengeDeclined$ = new Subject<Challenge>();
|
||||
private readonly incomingChallenges$ = new BehaviorSubject<Challenge[]>([]);
|
||||
private readonly challengeReceived$ = new Subject<Challenge>();
|
||||
private readonly challengeAccepted$ = new Subject<Challenge>();
|
||||
private readonly challengeDeclined$ = new Subject<Challenge>();
|
||||
|
||||
getIncomingChallenges$(): Observable<Challenge[]> {
|
||||
return this.incomingChallenges$.asObservable();
|
||||
}
|
||||
getIncomingChallenges$(): Observable<Challenge[]> {
|
||||
return this.incomingChallenges$.asObservable();
|
||||
}
|
||||
|
||||
getChallengeReceived$(): Observable<Challenge> {
|
||||
return this.challengeReceived$.asObservable();
|
||||
}
|
||||
getChallengeReceived$(): Observable<Challenge> {
|
||||
return this.challengeReceived$.asObservable();
|
||||
}
|
||||
|
||||
getChallengeAccepted$(): Observable<Challenge> {
|
||||
return this.challengeAccepted$.asObservable();
|
||||
}
|
||||
getChallengeAccepted$(): Observable<Challenge> {
|
||||
return this.challengeAccepted$.asObservable();
|
||||
}
|
||||
|
||||
getChallengeDeclined$(): Observable<Challenge> {
|
||||
return this.challengeDeclined$.asObservable();
|
||||
}
|
||||
getChallengeDeclined$(): Observable<Challenge> {
|
||||
return this.challengeDeclined$.asObservable();
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when a new challenge is received via WebSocket
|
||||
*/
|
||||
onChallengeReceived(challenge: Challenge): void {
|
||||
const current = this.incomingChallenges$.value;
|
||||
this.incomingChallenges$.next([...current, challenge]);
|
||||
this.challengeReceived$.next(challenge);
|
||||
}
|
||||
/**
|
||||
* Called when a new challenge is received via WebSocket
|
||||
*/
|
||||
onChallengeReceived(challenge: Challenge): void {
|
||||
const current = this.incomingChallenges$.value;
|
||||
this.incomingChallenges$.next([...current, challenge]);
|
||||
this.challengeReceived$.next(challenge);
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when a challenge is accepted
|
||||
*/
|
||||
onChallengeAccepted(challenge: Challenge): void {
|
||||
const current = this.incomingChallenges$.value;
|
||||
this.incomingChallenges$.next(current.filter(c => c.id !== challenge.id));
|
||||
this.challengeAccepted$.next(challenge);
|
||||
}
|
||||
/**
|
||||
* Called when a challenge is accepted
|
||||
*/
|
||||
onChallengeAccepted(challenge: Challenge): void {
|
||||
const current = this.incomingChallenges$.value;
|
||||
this.incomingChallenges$.next(current.filter(c => c.id !== challenge.id));
|
||||
this.challengeAccepted$.next(challenge);
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when a challenge is declined or expires
|
||||
*/
|
||||
onChallengeRemoved(challengeId: string): void {
|
||||
const current = this.incomingChallenges$.value;
|
||||
this.incomingChallenges$.next(current.filter(c => c.id !== challengeId));
|
||||
}
|
||||
/**
|
||||
* Called when a challenge is declined or expires
|
||||
*/
|
||||
onChallengeRemoved(challengeId: string): void {
|
||||
const current = this.incomingChallenges$.value;
|
||||
this.incomingChallenges$.next(current.filter(c => c.id !== challengeId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a challenge from the incoming list
|
||||
*/
|
||||
removeChallenge(challengeId: string): void {
|
||||
this.onChallengeRemoved(challengeId);
|
||||
}
|
||||
/**
|
||||
* Remove a challenge from the incoming list
|
||||
*/
|
||||
removeChallenge(challengeId: string): void {
|
||||
this.onChallengeRemoved(challengeId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,127 +9,127 @@ import { Challenge } from '../models/challenge.models';
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class ChallengeWebSocketService {
|
||||
private readonly challengeEventService = inject(ChallengeEventService);
|
||||
private ws: WebSocket | null = null;
|
||||
private reconnectAttempts = 0;
|
||||
private readonly maxReconnectAttempts = 5;
|
||||
private readonly reconnectDelay = 3000;
|
||||
private readonly challengeEventService = inject(ChallengeEventService);
|
||||
private ws: WebSocket | null = null;
|
||||
private reconnectAttempts = 0;
|
||||
private readonly maxReconnectAttempts = 5;
|
||||
private readonly reconnectDelay = 3000;
|
||||
|
||||
/**
|
||||
* Initialize WebSocket connection for challenge events
|
||||
*/
|
||||
connect(): void {
|
||||
if (this.ws) {
|
||||
return; // Already connected
|
||||
/**
|
||||
* Initialize WebSocket connection for challenge events
|
||||
*/
|
||||
connect(): void {
|
||||
if (this.ws) {
|
||||
return; // Already connected
|
||||
}
|
||||
|
||||
const wsProtocol = window.location.protocol === 'https:' ? 'wss' : 'ws';
|
||||
const wsUrl = `${wsProtocol}://${window.location.host}/ws/challenges`;
|
||||
|
||||
try {
|
||||
this.ws = new WebSocket(wsUrl);
|
||||
|
||||
this.ws.onopen = () => {
|
||||
console.log('Challenge WebSocket connected');
|
||||
this.reconnectAttempts = 0;
|
||||
};
|
||||
|
||||
this.ws.onmessage = (event) => {
|
||||
this.handleMessage(event.data);
|
||||
};
|
||||
|
||||
this.ws.onerror = (error) => {
|
||||
console.error('Challenge WebSocket error:', error);
|
||||
};
|
||||
|
||||
this.ws.onclose = () => {
|
||||
console.log('Challenge WebSocket disconnected');
|
||||
this.ws = null;
|
||||
this.attemptReconnect();
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Failed to create WebSocket:', error);
|
||||
this.attemptReconnect();
|
||||
}
|
||||
}
|
||||
|
||||
const wsProtocol = window.location.protocol === 'https:' ? 'wss' : 'ws';
|
||||
const wsUrl = `${wsProtocol}://${window.location.host}/ws/challenges`;
|
||||
|
||||
try {
|
||||
this.ws = new WebSocket(wsUrl);
|
||||
|
||||
this.ws.onopen = () => {
|
||||
console.log('Challenge WebSocket connected');
|
||||
this.reconnectAttempts = 0;
|
||||
};
|
||||
|
||||
this.ws.onmessage = (event) => {
|
||||
this.handleMessage(event.data);
|
||||
};
|
||||
|
||||
this.ws.onerror = (error) => {
|
||||
console.error('Challenge WebSocket error:', error);
|
||||
};
|
||||
|
||||
this.ws.onclose = () => {
|
||||
console.log('Challenge WebSocket disconnected');
|
||||
this.ws = null;
|
||||
this.attemptReconnect();
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Failed to create WebSocket:', error);
|
||||
this.attemptReconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the WebSocket connection
|
||||
*/
|
||||
disconnect(): void {
|
||||
if (this.ws) {
|
||||
this.ws.close();
|
||||
this.ws = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a message through WebSocket
|
||||
*/
|
||||
send(message: any): void {
|
||||
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
||||
this.ws.send(JSON.stringify(message));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle incoming WebSocket messages
|
||||
*/
|
||||
private handleMessage(data: string): void {
|
||||
try {
|
||||
const message = JSON.parse(data);
|
||||
|
||||
if (!message.type) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (message.type) {
|
||||
case 'challenge.received':
|
||||
if (message.challenge) {
|
||||
this.challengeEventService.onChallengeReceived(message.challenge as Challenge);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'challenge.accepted':
|
||||
if (message.challenge) {
|
||||
this.challengeEventService.onChallengeAccepted(message.challenge as Challenge);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'challenge.declined':
|
||||
if (message.challengeId) {
|
||||
this.challengeEventService.removeChallenge(message.challengeId);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'challenge.expired':
|
||||
if (message.challengeId) {
|
||||
this.challengeEventService.removeChallenge(message.challengeId);
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
console.debug('Unknown challenge message type:', message.type);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to parse WebSocket message:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to reconnect to WebSocket
|
||||
*/
|
||||
private attemptReconnect(): void {
|
||||
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
|
||||
console.error('Max WebSocket reconnection attempts reached');
|
||||
return;
|
||||
/**
|
||||
* Close the WebSocket connection
|
||||
*/
|
||||
disconnect(): void {
|
||||
if (this.ws) {
|
||||
this.ws.close();
|
||||
this.ws = null;
|
||||
}
|
||||
}
|
||||
|
||||
this.reconnectAttempts++;
|
||||
console.log(`Attempting WebSocket reconnect (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`);
|
||||
/**
|
||||
* Send a message through WebSocket
|
||||
*/
|
||||
send(message: any): void {
|
||||
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
||||
this.ws.send(JSON.stringify(message));
|
||||
}
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
this.connect();
|
||||
}, this.reconnectDelay);
|
||||
}
|
||||
/**
|
||||
* Handle incoming WebSocket messages
|
||||
*/
|
||||
private handleMessage(data: string): void {
|
||||
try {
|
||||
const message = JSON.parse(data);
|
||||
|
||||
if (!message.type) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (message.type) {
|
||||
case 'challenge.received':
|
||||
if (message.challenge) {
|
||||
this.challengeEventService.onChallengeReceived(message.challenge as Challenge);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'challenge.accepted':
|
||||
if (message.challenge) {
|
||||
this.challengeEventService.onChallengeAccepted(message.challenge as Challenge);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'challenge.declined':
|
||||
if (message.challengeId) {
|
||||
this.challengeEventService.removeChallenge(message.challengeId);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'challenge.expired':
|
||||
if (message.challengeId) {
|
||||
this.challengeEventService.removeChallenge(message.challengeId);
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
console.debug('Unknown challenge message type:', message.type);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to parse WebSocket message:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to reconnect to WebSocket
|
||||
*/
|
||||
private attemptReconnect(): void {
|
||||
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
|
||||
console.error('Max WebSocket reconnection attempts reached');
|
||||
return;
|
||||
}
|
||||
|
||||
this.reconnectAttempts++;
|
||||
console.log(`Attempting WebSocket reconnect (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`);
|
||||
|
||||
setTimeout(() => {
|
||||
this.connect();
|
||||
}, this.reconnectDelay);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,46 +5,46 @@ import { Challenge, DeclineChallengeRequest, ListChallengesResponse, SendChallen
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class ChallengeService {
|
||||
private readonly http = inject(HttpClient);
|
||||
private readonly challengeBaseUrl = '/api/challenge';
|
||||
private readonly http = inject(HttpClient);
|
||||
private readonly challengeBaseUrl = '/api/challenge';
|
||||
|
||||
sendChallenge(username: string, request: SendChallengeRequest): Observable<Challenge> {
|
||||
return this.http.post<Challenge>(
|
||||
`${this.challengeBaseUrl}/${username}`,
|
||||
request
|
||||
);
|
||||
}
|
||||
sendChallenge(username: string, request: SendChallengeRequest): Observable<Challenge> {
|
||||
return this.http.post<Challenge>(
|
||||
`${this.challengeBaseUrl}/${username}`,
|
||||
request
|
||||
);
|
||||
}
|
||||
|
||||
listChallenges(): Observable<ListChallengesResponse> {
|
||||
return this.http.get<ListChallengesResponse>(
|
||||
`${this.challengeBaseUrl}`
|
||||
);
|
||||
}
|
||||
listChallenges(): Observable<ListChallengesResponse> {
|
||||
return this.http.get<ListChallengesResponse>(
|
||||
`${this.challengeBaseUrl}`
|
||||
);
|
||||
}
|
||||
|
||||
getChallenge(challengeId: string): Observable<Challenge> {
|
||||
return this.http.get<Challenge>(
|
||||
`${this.challengeBaseUrl}/${challengeId}`
|
||||
);
|
||||
}
|
||||
getChallenge(challengeId: string): Observable<Challenge> {
|
||||
return this.http.get<Challenge>(
|
||||
`${this.challengeBaseUrl}/${challengeId}`
|
||||
);
|
||||
}
|
||||
|
||||
acceptChallenge(challengeId: string): Observable<void> {
|
||||
return this.http.post<void>(
|
||||
`${this.challengeBaseUrl}/${challengeId}/accept`,
|
||||
{}
|
||||
);
|
||||
}
|
||||
acceptChallenge(challengeId: string): Observable<void> {
|
||||
return this.http.post<void>(
|
||||
`${this.challengeBaseUrl}/${challengeId}/accept`,
|
||||
{}
|
||||
);
|
||||
}
|
||||
|
||||
declineChallenge(challengeId: string, request?: DeclineChallengeRequest): Observable<void> {
|
||||
return this.http.post<void>(
|
||||
`${this.challengeBaseUrl}/${challengeId}/decline`,
|
||||
request || {}
|
||||
);
|
||||
}
|
||||
declineChallenge(challengeId: string, request?: DeclineChallengeRequest): Observable<void> {
|
||||
return this.http.post<void>(
|
||||
`${this.challengeBaseUrl}/${challengeId}/decline`,
|
||||
request || {}
|
||||
);
|
||||
}
|
||||
|
||||
cancelChallenge(challengeId: string): Observable<void> {
|
||||
return this.http.post<void>(
|
||||
`${this.challengeBaseUrl}/${challengeId}/cancel`,
|
||||
{}
|
||||
);
|
||||
}
|
||||
cancelChallenge(challengeId: string): Observable<void> {
|
||||
return this.http.post<void>(
|
||||
`${this.challengeBaseUrl}/${challengeId}/cancel`,
|
||||
{}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user