-
-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathindex.mjs
More file actions
83 lines (72 loc) · 2.55 KB
/
index.mjs
File metadata and controls
83 lines (72 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import {state} from "./lib/state.mjs";
import {handleRouteChange} from "./lib/router.mjs";
import {apiService} from "./lib/api.mjs";
import {handleErrorDialog} from "./components/error.mjs";
// get all the dynamic areas of the initial DOM
const getLogoutContainer = () => document.getElementById("logout-container");
const getLoginContainer = () => document.getElementById("login-container");
const getSignupContainer = () => document.getElementById("signup-container");
const getBloomFormContainer = () =>
document.getElementById("bloom-form-container");
const getProfileContainer = () => document.getElementById("profile-container");
const getTimelineContainer = () =>
document.getElementById("timeline-container");
const getErrorDialog = () => document.getElementById("error-container");
const getHeadingContainer = () => document.getElementById("heading-container");
/**
* Init the application
* - Check for token and restore session if exists
* - Handle the current route based on URL
* - Set up state change listeners
*/
async function init() {
const path = window.location.pathname;
const isProfilePage = path.startsWith("/profile/");
const profileUsername = isProfilePage ? path.split("/")[2] : null;
// Attempt to restore session if token exists
if (state.token || localStorage.getItem("token")) {
if (localStorage.getItem("token") && !state.token) {
state.updateState({token: localStorage.getItem("token")});
}
await apiService.getProfile();
if (isProfilePage && profileUsername) {
await apiService.getProfile(profileUsername);
}
}
handleRouteChange();
document.addEventListener("state-change", () => {
handleRouteChange();
});
}
// TODO Check any unhandled errors bubble up to this central handler
window.onload = () => {
init().catch((error) => {
handleErrorDialog(error);
});
};
// TODO rm this backstop
window.addEventListener("unhandledrejection", (event) => {
console.error("Unhandled promise rejection:", event.reason);
handleErrorDialog(event.reason);
});
// Rebloom click handler
document.querySelector("#app").addEventListener("click", async (event) => {
const action = event.target.dataset.action;
if (action === "rebloom") {
const bloomElement = event.target.closest("[data-bloom]");
const bloomId = bloomElement.dataset.bloomId;
await apiService.rebloom(bloomId);
}
});
export {
getLogoutContainer,
getLoginContainer,
getSignupContainer,
getBloomFormContainer,
getProfileContainer,
getHeadingContainer,
getTimelineContainer,
getErrorDialog,
state,
apiService,
};