241 lines
8.6 KiB
TypeScript
241 lines
8.6 KiB
TypeScript
import type { DirectChallenge, ServerWsMessage, UserSummary } from '../shared/types';
|
|
import { apiRequest, wsClient } from './api';
|
|
import { Navbar } from './components/navbar';
|
|
import { clearNode, el } from './dom';
|
|
import { sound } from './sound';
|
|
import { mountAnalysisView } from './views/analysisView';
|
|
import { mountAuthView } from './views/authView';
|
|
import { mountBotView } from './views/botView';
|
|
import type { AppContext, ViewHandle } from './views/context';
|
|
import { mountFriendsView } from './views/friendsView';
|
|
import { mountGameView } from './views/gameView';
|
|
import { mountHomeView } from './views/homeView';
|
|
import { mountInviteView } from './views/inviteView';
|
|
import { mountLeaderboardView } from './views/leaderboardView';
|
|
import { mountProfileView } from './views/profileView';
|
|
|
|
class App {
|
|
private user: UserSummary | null = null;
|
|
private activeGameId: string | null = null;
|
|
private friendBadgeCount = 0;
|
|
private activeView: ViewHandle | null = null;
|
|
|
|
private readonly navbarEl = document.getElementById('navbar')!;
|
|
private readonly mainEl = document.getElementById('main-content')!;
|
|
private readonly toastEl = document.getElementById('toast-container')!;
|
|
private readonly navbar: Navbar;
|
|
|
|
private readonly ctx: AppContext = {
|
|
getUser: () => this.user,
|
|
getActiveGameId: () => this.activeGameId,
|
|
setActiveGameId: (gid) => {
|
|
this.activeGameId = gid;
|
|
this.renderNavbar();
|
|
},
|
|
refreshSession: () => this.refreshSession(),
|
|
navigate: (path, replace) => this.navigate(path, replace),
|
|
toast: (msg, kind) => this.toast(msg, kind)
|
|
};
|
|
|
|
constructor() {
|
|
this.navbar = new Navbar(this.navbarEl, {
|
|
onNavigate: (path) => this.navigate(path),
|
|
onLogout: () => this.logout()
|
|
});
|
|
|
|
window.addEventListener('popstate', () => {
|
|
this.renderRoute();
|
|
});
|
|
|
|
wsClient.onMessage((msg) => this.handleGlobalWs(msg));
|
|
}
|
|
|
|
async init(): Promise<void> {
|
|
await this.refreshSession();
|
|
wsClient.connect();
|
|
this.renderRoute();
|
|
}
|
|
|
|
private async refreshSession(): Promise<void> {
|
|
try {
|
|
const me = await apiRequest<{ user: UserSummary | null; activeGameId: string | null }>('/api/auth/me');
|
|
this.user = me.user;
|
|
this.activeGameId = me.activeGameId;
|
|
if (this.user) {
|
|
this.refreshFriendBadge();
|
|
} else {
|
|
this.friendBadgeCount = 0;
|
|
}
|
|
} catch {
|
|
this.user = null;
|
|
this.activeGameId = null;
|
|
this.friendBadgeCount = 0;
|
|
}
|
|
this.renderNavbar();
|
|
}
|
|
|
|
private async refreshFriendBadge(): Promise<void> {
|
|
if (!this.user) {
|
|
this.friendBadgeCount = 0;
|
|
this.renderNavbar();
|
|
return;
|
|
}
|
|
try {
|
|
const data = await apiRequest<{
|
|
requests: Array<{ direction: string }>;
|
|
challenges: DirectChallenge[];
|
|
}>('/api/friends');
|
|
const incomingReqs = data.requests.filter((r) => r.direction === 'incoming').length;
|
|
const incomingChals = data.challenges.filter((c) => c.toUserId === this.user!.id).length;
|
|
this.friendBadgeCount = incomingReqs + incomingChals;
|
|
this.renderNavbar();
|
|
} catch {
|
|
// Ignore
|
|
}
|
|
}
|
|
|
|
private async logout(): Promise<void> {
|
|
try {
|
|
await apiRequest('/api/auth/logout', { method: 'POST' });
|
|
} catch {
|
|
// Ignore
|
|
}
|
|
this.user = null;
|
|
this.activeGameId = null;
|
|
this.friendBadgeCount = 0;
|
|
wsClient.reconnectNow();
|
|
this.renderNavbar();
|
|
this.navigate('/');
|
|
}
|
|
|
|
private renderNavbar(): void {
|
|
this.navbar.render({
|
|
user: this.user,
|
|
currentPath: window.location.pathname,
|
|
friendBadgeCount: this.friendBadgeCount,
|
|
activeGameId: this.activeGameId
|
|
});
|
|
}
|
|
|
|
navigate(path: string, replace: boolean = false): void {
|
|
if (replace) {
|
|
window.history.replaceState(null, '', path);
|
|
} else {
|
|
window.history.pushState(null, '', path);
|
|
}
|
|
this.renderRoute();
|
|
}
|
|
|
|
private renderRoute(): void {
|
|
if (this.activeView) {
|
|
this.activeView.destroy();
|
|
this.activeView = null;
|
|
}
|
|
clearNode(this.mainEl);
|
|
this.renderNavbar();
|
|
|
|
const pathname = window.location.pathname;
|
|
const search = new URLSearchParams(window.location.search);
|
|
const nextParam = search.get('next') || undefined;
|
|
|
|
if (pathname === '/' || pathname === '') {
|
|
this.activeView = mountHomeView(this.mainEl, this.ctx);
|
|
} else if (pathname === '/login') {
|
|
this.activeView = mountAuthView(this.mainEl, this.ctx, 'login', nextParam);
|
|
} else if (pathname === '/register') {
|
|
this.activeView = mountAuthView(this.mainEl, this.ctx, 'register', nextParam);
|
|
} else if (pathname === '/bots') {
|
|
this.activeView = mountBotView(this.mainEl, this.ctx);
|
|
} else if (pathname === '/friends') {
|
|
this.activeView = mountFriendsView(this.mainEl, this.ctx);
|
|
} else if (pathname === '/leaderboard') {
|
|
this.activeView = mountLeaderboardView(this.mainEl, this.ctx);
|
|
} else if (pathname === '/analysis') {
|
|
this.activeView = mountAnalysisView(this.mainEl, this.ctx);
|
|
} else if (pathname.indexOf('/analysis/') === 0) {
|
|
const gameId = decodeURIComponent(pathname.slice('/analysis/'.length));
|
|
this.activeView = mountAnalysisView(this.mainEl, this.ctx, gameId);
|
|
} else if (pathname.indexOf('/game/') === 0) {
|
|
const gameId = decodeURIComponent(pathname.slice('/game/'.length));
|
|
this.activeView = mountGameView(this.mainEl, this.ctx, gameId);
|
|
} else if (pathname.indexOf('/u/') === 0) {
|
|
const username = decodeURIComponent(pathname.slice('/u/'.length));
|
|
this.activeView = mountProfileView(this.mainEl, this.ctx, username);
|
|
} else if (pathname.indexOf('/invite/') === 0) {
|
|
const token = decodeURIComponent(pathname.slice('/invite/'.length));
|
|
this.activeView = mountInviteView(this.mainEl, this.ctx, token);
|
|
} else {
|
|
const card = el('div', { className: 'page-container narrow-page' }, [
|
|
el('div', { className: 'card' }, [
|
|
el('div', { className: 'card-body' }, [
|
|
el('h1', { className: 'card-title' }, 'Page Not Found'),
|
|
el('p', { className: 'muted' }, 'That ChessUp page does not exist.'),
|
|
el('button', {
|
|
type: 'button',
|
|
className: 'btn btn-primary'
|
|
}, 'Go to Lobby')
|
|
])
|
|
])
|
|
]);
|
|
const btn = card.querySelector('button')!;
|
|
btn.addEventListener('click', () => this.navigate('/'));
|
|
this.mainEl.appendChild(card);
|
|
}
|
|
}
|
|
|
|
private handleGlobalWs(msg: ServerWsMessage): void {
|
|
if (msg.type === 'session:init') {
|
|
this.user = msg.user;
|
|
this.activeGameId = msg.activeGameId;
|
|
this.refreshFriendBadge();
|
|
this.renderNavbar();
|
|
} else if (msg.type === 'game:started') {
|
|
this.activeGameId = msg.gameId;
|
|
sound.play('notify');
|
|
this.renderNavbar();
|
|
this.navigate(`/game/${msg.gameId}`);
|
|
} else if (msg.type === 'challenge:received') {
|
|
sound.play('notify');
|
|
this.refreshFriendBadge();
|
|
this.showChallengeToast(msg.challenge);
|
|
} else if (msg.type === 'challenge:removed' || msg.type === 'challenge:list' || msg.type === 'friend:update') {
|
|
this.refreshFriendBadge();
|
|
} else if (msg.type === 'error') {
|
|
this.toast(msg.message, 'error');
|
|
}
|
|
}
|
|
|
|
private showChallengeToast(ch: DirectChallenge): void {
|
|
const item = el('div', { className: 'toast toast-info' });
|
|
item.appendChild(el('div', { className: 'toast-text' }, `${ch.fromUsername} (${ch.fromRating}) challenged you!`));
|
|
const btns = el('div', { className: 'btn-row' });
|
|
const acc = el('button', { type: 'button', className: 'btn btn-xs btn-primary' }, 'Accept');
|
|
const dec = el('button', { type: 'button', className: 'btn btn-xs' }, 'Decline');
|
|
acc.addEventListener('click', () => {
|
|
wsClient.send({ type: 'challenge:respond', challengeId: ch.id, accept: true });
|
|
if (item.parentNode) item.parentNode.removeChild(item);
|
|
});
|
|
dec.addEventListener('click', () => {
|
|
wsClient.send({ type: 'challenge:respond', challengeId: ch.id, accept: false });
|
|
if (item.parentNode) item.parentNode.removeChild(item);
|
|
});
|
|
btns.appendChild(acc);
|
|
btns.appendChild(dec);
|
|
item.appendChild(btns);
|
|
this.toastEl.appendChild(item);
|
|
window.setTimeout(() => {
|
|
if (item.parentNode) item.parentNode.removeChild(item);
|
|
}, 15_000);
|
|
}
|
|
|
|
toast(message: string, kind: 'info' | 'success' | 'error' = 'info'): void {
|
|
const item = el('div', { className: `toast toast-${kind}` }, message);
|
|
this.toastEl.appendChild(item);
|
|
window.setTimeout(() => {
|
|
if (item.parentNode) item.parentNode.removeChild(item);
|
|
}, 4000);
|
|
}
|
|
}
|
|
|
|
const app = new App();
|
|
app.init();
|