drishti/src/App.tsx

120 lines
2.3 KiB
TypeScript
Raw Normal View History

import "./App.css";
import "bootstrap/dist/css/bootstrap.min.css";
import Client, { IAuth } from "./client/Client";
import { AccountIdMap, IAccount } from "./client/types";
import AppLayout from "./AppLayout";
import AuthModal from "./AuthModal";
import React from "react";
interface ILocation {
accountId: string;
}
type AppState = {
auth: IAuth;
account: IAccount | null;
accounts: AccountIdMap;
location: ILocation;
};
type AppProps = {};
class App extends React.Component<AppProps, AppState> {
account(): IAccount | null {
return this.client.account(this.state.location.accountId);
}
client: Client = new Client();
state: AppState = {
account: null,
accounts: {},
auth: { email: "", password: "" },
location: { accountId: "" },
};
onHashChange() {
console.log(window.location.hash);
const hash = window.location.hash.substring(1);
this.setState({
...this.state,
account: this.account(),
location: { accountId: hash },
});
}
// When the user provides credentials
onLogin(email: string, password: string) {
// Store the provided credentials for now
this.setState({
...this.state,
auth: {
email: email,
password: password,
},
});
localStorage.setItem("auth", JSON.stringify(this.state.auth));
this.client.doLogin({ email, password });
}
// Load up auth credentials from the local store
loadAuth() {
const data = localStorage.getItem("auth");
if (!data) return;
const auth = JSON.parse(data);
this.setState({
...this.state,
auth: auth,
});
this.client.ensureLogin(auth);
}
componentDidMount() {
window.addEventListener(
"hashchange",
() => {
this.onHashChange();
},
false,
);
this.loadAuth();
this.onHashChange();
this.client.onChange(() => {
this.setState({
...this.state,
account: this.account(),
accounts: this.client.state.session
? this.client.state.session.accounts
: {},
});
});
}
componentWillUnmount() {
window.removeEventListener(
"hashchange",
() => {
this.onHashChange();
},
false,
);
}
render() {
return (
<div className="App">
<AppLayout
account={this.state.account}
accounts={this.state.accounts}
client={this.client}
/>
<AuthModal
show={this.client.state.session == null}
onLogin={this.onLogin}
></AuthModal>
</div>
);
}
}
export default App;