import Banner from "./Banner"; import Connection from "./Connection"; import KeyboardController from "./Keyboard"; import { getAuth, setAuth } from "./LocalConfiguration"; import LoginPrompt from "./LoginPrompt"; import TouchpadController from "./Touchpad"; class App { constructor(mountElement) { this.mountElement = mountElement; this.connection = new Connection(`ws://${location.host}/gateway`); this.touchpad = new TouchpadController(this.connection); this.keyboard = new KeyboardController(this.connection); this.loginPromptComponent = null; this.connection.connect(getAuth()); this.connection.ws.addEventListener("close", ({code}) => { this.unmountApp(); if (code === 4001) { // 4001 - code for bad auth this.transitionTo("login"); } else { this.transitionTo("reconnectingBanner"); } }); this.connection.onHandshakeCompleted = () => { this.transitionTo("app"); }; } transitionTo(type) { switch (type) { case "login": this.unmountBannerComponent(); this.unmountApp(); this.mountLoginComponent(); break; case "app": this.unmountBannerComponent(); this.unmountLoginComponent(); this.mountApp(); break; case "reconnectingBanner": this.unmountApp(); this.unmountLoginComponent(); this.mountBannerComponent("Connecting...", "Looks like you've lost connection. We're trying to reconnect you."); break; default: throw new Error(`transitionTo type ${type} is invalid`); } } mountBannerComponent(title, text) { if (!this.bannerComponent) this.bannerComponent = new Banner(); this.bannerComponent.mountOn(this.mountElement); this.bannerComponent.updateTitle(title); this.bannerComponent.updateText(text); } unmountBannerComponent() { if (this.bannerComponent) this.bannerComponent.unmount(); } mountLoginComponent() { if (!this.loginPromptComponent) this.loginPromptComponent = new LoginPrompt(this.connection); this.loginPromptComponent.mountOn(this.mountElement); this.loginPromptComponent.onPasswordSubmitted = (p) => { setAuth(p); this.connection.connect(p); }; } unmountLoginComponent() { if (this.loginPromptComponent) this.loginPromptComponent.unmount(); } mountApp() { this.touchpad.mountOn(this.mountElement); this.keyboard.mountOn(this.mountElement); } unmountApp() { this.touchpad.unmount(); this.keyboard.unmount(); } } export default App;