drishti/src/App.tsx

149 lines
3.1 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, IMailbox } from "./client/types";
import AppLayout from "./AppLayout";
import AuthModal from "./AuthModal";
import React from "react";
interface ILocation {
accountId: string;
mailboxId: string;
}
type AppState = {
auth: IAuth;
account: IAccount | null;
accounts: AccountIdMap;
location: ILocation;
mailbox: IMailbox | null;
};
type AppProps = {};
class App extends React.Component<AppProps, AppState> {
account(): IAccount | null {
return this.client.account(this.state.location.accountId);
}
mailbox(): IMailbox | null {
return this.client.mailbox(
this.state.location.accountId,
this.state.location.mailboxId,
);
}
client: Client = new Client();
state: AppState = {
account: null,
accounts: {},
auth: { email: "", password: "" },
location: { accountId: "", mailboxId: "" },
mailbox: null,
};
onHashChange() {
const hash = window.location.hash.substring(1);
const parts = hash.split("/");
const accountId = parts[0];
const mailboxId = parts[1];
this.setState({
...this.state,
account: this.account(),
location: {
accountId: accountId,
mailboxId: mailboxId,
},
});
}
// 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 });
}
onMailboxSelect(mailboxId: string) {
if (!this.state.account) return;
this.client.emailList(this.state.account.id, mailboxId, []);
this.setState({
...this.state,
mailbox: this.client.mailbox(this.state.account.id, mailboxId),
});
window.location.hash = this.state.location.accountId + "/" + mailboxId;
}
// 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
: {},
mailbox: this.mailbox(),
});
});
}
componentWillUnmount() {
window.removeEventListener(
"hashchange",
() => {
this.onHashChange();
},
false,
);
}
render() {
return (
<div className="App">
<AppLayout
account={this.state.account}
accounts={this.state.accounts}
client={this.client}
mailbox={this.state.mailbox}
onMailboxSelect={(m) => {
this.onMailboxSelect(m);
}}
/>
<AuthModal
show={this.client.state.session == null}
onLogin={this.onLogin}
></AuthModal>
</div>
);
}
}
export default App;