moviewyrm/bookwyrm/static/js/status_cache.js

92 lines
2.4 KiB
JavaScript
Raw Normal View History

2021-09-08 20:58:10 +00:00
/* exported StatusCache */
2021-09-09 14:39:38 +00:00
/* globals BookWyrm */
2021-09-08 20:58:10 +00:00
let StatusCache = new class {
constructor() {
document.querySelectorAll('[data-cache-draft]')
.forEach(t => t.addEventListener('change', this.updateDraft.bind(this)));
2021-09-09 13:54:34 +00:00
2021-09-08 20:58:10 +00:00
document.querySelectorAll('[data-cache-draft]')
.forEach(t => this.populateDraft(t));
2021-09-09 13:54:34 +00:00
document.querySelectorAll('.submit-status')
.forEach(button => button.addEventListener(
'submit',
this.submitStatus.bind(this))
);
2021-09-08 20:58:10 +00:00
}
/**
* Update localStorage copy of drafted status
*
* @param {Event} event
* @return {undefined}
*/
updateDraft(event) {
// Used in set reading goal
let key = event.target.dataset.cacheDraft;
let value = event.target.value;
2021-09-09 14:39:38 +00:00
if (!value) {
window.localStorage.removeItem(key);
return;
}
2021-09-08 20:58:10 +00:00
window.localStorage.setItem(key, value);
}
/**
* Toggle display of a DOM node based on its value in the localStorage.
*
* @param {object} node - DOM node to toggle.
* @return {undefined}
*/
populateDraft(node) {
// Used in set reading goal
let key = node.dataset.cacheDraft;
let value = window.localStorage.getItem(key);
2021-09-09 14:39:38 +00:00
if (!value) {
return;
}
2021-09-08 20:58:10 +00:00
node.value = value;
}
2021-09-09 13:54:34 +00:00
/**
* Post a status with ajax
*
* @param {Event} event
* @return {undefined}
*/
submitStatus(event) {
event.preventDefault();
const form = event.currentTarget;
2021-09-09 14:39:38 +00:00
BookWyrm.ajaxPost(form).catch(error => {
2021-09-09 13:54:34 +00:00
// @todo Display a notification in the UI instead.
console.warn('Request failed:', error);
});
// Clear form data
form.reset();
2021-09-09 14:39:38 +00:00
// Clear localstorage
form.querySelectorAll('[data-cache-draft]')
.forEach(node => window.localStorage.removeItem(node.dataset.cacheDraft));
// Close modals
2021-09-09 15:06:36 +00:00
let modal = form.closest(".modal.is-active");
if (!!modal) {
modal.getElementsByClassName("modal-close")[0].click();
}
2021-09-09 15:20:55 +00:00
// Close reply panel
let reply = form.closest(".reply-panel");
if (!!reply) {
document.querySelector("[data-controls=" + reply.id + "]").click();
}
// Update shelve buttons
2021-09-09 13:54:34 +00:00
}
2021-09-08 20:58:10 +00:00
}();