Files
PrivateChat/client/src/app/home-page.component.ts
2026-03-09 19:35:08 +01:00

103 lines
2.6 KiB
TypeScript

import { CommonModule } from '@angular/common';
import { Component, effect, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Router, RouterLink } from '@angular/router';
import { ChatSessionService } from './chat-session.service';
import { ThemeService } from './theme.service';
@Component({
selector: 'app-home-page',
imports: [CommonModule, FormsModule, RouterLink],
templateUrl: './home-page.component.html',
styleUrl: './home-page.component.scss',
})
export class HomePageComponent {
private readonly router = inject(Router);
readonly theme = inject(ThemeService);
authMode: 'login' | 'register' = 'login';
readonly embeddedMode =
typeof window !== 'undefined' && window.localStorage.getItem('privatechat.embeddedMode') === '1';
serverUrl = '';
displayName = '';
username = '';
password = '';
accessKeyLabel = '';
constructor(readonly session: ChatSessionService) {
this.serverUrl = session.serverUrl();
if (this.embeddedMode) {
effect(() => {
const currentUser = this.session.currentUser();
const activePeerId = this.session.activePeerId();
if (!currentUser || !activePeerId) {
return;
}
void this.router.navigate(['/chat', activePeerId], { replaceUrl: true });
});
}
}
async submitAuth(): Promise<void> {
this.applyServerUrl();
if (this.authMode === 'register') {
const authenticated = await this.session.register(this.username, this.password, this.displayName);
this.password = '';
if (!authenticated) {
this.authMode = 'login';
}
return;
}
await this.session.login(this.username, this.password);
}
applyServerUrl(): void {
this.session.setServerUrl(this.serverUrl);
}
async logout(): Promise<void> {
await this.session.logout();
this.authMode = 'login';
this.displayName = '';
this.password = '';
}
async loginWithAccessKey(): Promise<void> {
this.applyServerUrl();
await this.session.loginWithAccessKey(this.username);
this.password = '';
}
async registerAccessKey(): Promise<void> {
await this.session.registerAccessKey(this.accessKeyLabel);
this.accessKeyLabel = '';
}
canOpenChatUi(): boolean {
return this.session.peers().length > 0;
}
async openChatUi(): Promise<void> {
const peerId = this.session.activePeerId() ?? this.session.peers()[0]?.id;
if (!peerId) {
this.session.error.set('No connected peers are available yet.');
return;
}
this.session.selectPeer(peerId);
await this.router.navigate(['/chat', peerId]);
}
cycleTheme(): void {
this.theme.cycleMode();
}
}