watch-party/frontend/lib/join-session.mjs

94 lines
2.4 KiB
JavaScript
Raw Normal View History

2022-04-29 15:25:31 -07:00
import { joinSession } from "./watch-session.mjs?v=bfdcf2";
2022-03-30 06:02:08 -07:00
import { state } from "./state.mjs";
2021-11-09 05:21:14 -08:00
/**
* @param {HTMLInputElement} field
*/
const loadNickname = (field) => {
try {
const savedNickname = localStorage.getItem("watch-party-nickname");
field.value = savedNickname;
} catch (_err) {
// Sometimes localStorage is blocked from use
}
};
/**
* @param {HTMLInputElement} field
*/
const saveNickname = (field) => {
try {
localStorage.setItem("watch-party-nickname", field.value);
} catch (_err) {
// see loadNickname
}
};
/**
* @param {HTMLInputElement} field
*/
const loadColour = (field) => {
try {
const savedColour = localStorage.getItem("watch-party-colour");
if (savedColour != null && savedColour != "") {
field.value = savedColour;
}
} catch (_err) {
// Sometimes localStorage is blocked from use
}
};
/**
* @param {HTMLInputElement} field
*/
const saveColour = (field) => {
try {
localStorage.setItem("watch-party-colour", field.value);
} catch (_err) {
// see loadColour
}
};
2021-11-11 09:26:30 -08:00
const displayPostCreateMessage = () => {
const params = new URLSearchParams(window.location.search);
if (params.get("created") == "true") {
document.querySelector("#post-create-message").style["display"] = "block";
window.history.replaceState({}, document.title, `/${window.location.hash}`);
}
};
2021-11-09 05:21:14 -08:00
export const setupJoinSessionForm = () => {
2021-11-11 09:26:30 -08:00
displayPostCreateMessage();
2021-11-09 05:21:14 -08:00
const form = document.querySelector("#join-session-form");
const nickname = form.querySelector("#join-session-nickname");
const colour = form.querySelector("#join-session-colour");
2021-11-09 05:21:14 -08:00
const sessionId = form.querySelector("#join-session-id");
2021-12-03 11:37:16 -08:00
const button = form.querySelector("#join-session-button");
2021-11-09 05:21:14 -08:00
loadNickname(nickname);
loadColour(colour);
2021-11-09 05:21:14 -08:00
2022-05-04 22:40:45 -07:00
if (window.location.hash.match(/#[A-Za-z0-9_\-]+/)) {
2021-11-09 05:21:14 -08:00
sessionId.value = window.location.hash.substring(1);
}
2022-02-15 14:19:48 -08:00
form.addEventListener("submit", async (event) => {
2021-12-03 11:37:16 -08:00
event.preventDefault();
2021-11-09 05:21:14 -08:00
2021-12-03 11:37:16 -08:00
button.disabled = true;
saveNickname(nickname);
saveColour(colour);
2022-02-15 14:19:48 -08:00
try {
2022-03-30 06:02:08 -07:00
state().nickname = nickname.value;
state().sessionId = sessionId.value;
state().colour = colour.value.replace(/^#/, "");
await joinSession();
2022-02-15 14:19:48 -08:00
} catch (e) {
2022-02-15 16:30:22 -08:00
alert(e.message);
button.disabled = false;
2022-02-15 14:19:48 -08:00
}
2021-12-03 11:37:16 -08:00
});
2021-11-09 05:21:14 -08:00
};