Cleanup and refactor some JS

Folded some class assignments into loops, refactored observers, dealt with some formatting.
This commit is contained in:
Tetrakern 2024-02-01 09:46:40 +01:00
parent 9e77a50505
commit 81b479de43
7 changed files with 68 additions and 61 deletions

2
js/admin.min.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

2
js/story.min.js vendored
View File

@ -1 +1 @@
var fcn_storyCommentPage=1,fcn_storySettings=fcn_getStorySettings();function fcn_getStorySettings(){let t=fcn_parseJSON(localStorage.getItem("fcnStorySettings"))??fcn_defaultStorySettings();return(!t.hasOwnProperty("timestamp")||t.timestamp<1674770712849)&&(t=fcn_defaultStorySettings(),t.timestamp=Date.now()),fcn_setStorySettings(t),t}function fcn_defaultStorySettings(){return{view:"list",order:"asc",timestamp:1674770712849}}function fcn_setStorySettings(t){"object"==typeof t&&(fcn_storySettings=t,localStorage.setItem("fcnStorySettings",JSON.stringify(t)))}function fcn_applyStorySettings(){"object"==typeof fcn_storySettings&&(_$$("[data-view]").forEach((t=>{t.dataset.view="grid"==fcn_storySettings.view?"grid":"list"})),_$$("[data-order]").forEach((t=>{t.dataset.order="desc"==fcn_storySettings.order?"desc":"asc"})))}function fcn_toggleStoryTab(t){_$$(".story__article ._current").forEach((t=>{t.classList.remove("_current")})),_$$(`[data-finder="${t.dataset.target}"]`).forEach((t=>{t.classList.add("_current")})),_$$$("tabs").dataset.current=t.dataset.target,t.classList.add("_current")}function fcn_loadStoryComments(){let t;_$(".load-more-list-item").remove(),_$(".comments-loading-placeholder").classList.remove("hidden"),fcn_ajaxGet({post_id:fcn_inlineStorage.postId,page:fcn_storyCommentPage},"get_story_comments").then((e=>{e.success?(_$(".fictioneer-comments__list > ul").innerHTML+=e.data.html,fcn_storyCommentPage++):e.data?.error&&(t=fcn_buildErrorNotice(e.data.error))})).catch((e=>{t=fcn_buildErrorNotice(e)})).then((()=>{_$(".comments-loading-placeholder").remove(),t&&_$(".fictioneer-comments__list > ul").appendChild(t)}))}function fcn_startEpubDownload(t,e=0){e>3?t.classList.remove("ajax-in-progress"):fcn_ajaxGet({action:"fictioneer_ajax_download_epub",story_id:t.dataset.storyId}).then((r=>{r.success?(window.location.href=t.href,setTimeout((()=>{t.classList.remove("ajax-in-progress")}),2e3)):setTimeout((()=>{fcn_startEpubDownload(t,e+1)}),2e3)})).catch((e=>{t.classList.remove("ajax-in-progress"),e.status&&e.statusText&&fcn_showNotification(`${e.status}: ${e.statusText}`,5,"warning")}))}fcn_applyStorySettings(),_$$$("button-toggle-chapter-order")?.addEventListener("click",(t=>{fcn_storySettings.order="asc"===t.currentTarget.dataset.order?"desc":"asc",fcn_setStorySettings(fcn_storySettings),fcn_applyStorySettings()})),_$$$("button-toggle-chapter-view")?.addEventListener("click",(t=>{fcn_storySettings.view="list"===t.currentTarget.dataset.view?"grid":"list",fcn_setStorySettings(fcn_storySettings),fcn_applyStorySettings()})),_$$(".chapter-group__folding-toggle").forEach((t=>{t.addEventListener("click",(t=>{const e=t.currentTarget.closest(".chapter-group[data-folded]");e&&(e.dataset.folded="true"==e.dataset.folded?"false":"true")}))})),_$$(".tabs__item").forEach((t=>{t.addEventListener("click",(t=>{fcn_toggleStoryTab(t.currentTarget)}))})),_$(".comment-section")?.addEventListener("click",(t=>{t.target?.classList.contains("load-more-comments-button")&&fcn_loadStoryComments()})),_$$('[data-action="download-epub"]').forEach((t=>{t.addEventListener("click",(t=>{t.preventDefault(),t.currentTarget.classList.contains("ajax-in-progress")||(t.currentTarget.classList.add("ajax-in-progress"),fcn_startEpubDownload(t.currentTarget))}))}));
var fcn_storyCommentPage=1,fcn_storySettings=fcn_getStorySettings();function fcn_getStorySettings(){let t=fcn_parseJSON(localStorage.getItem("fcnStorySettings"))??fcn_defaultStorySettings();return(!t.hasOwnProperty("timestamp")||t.timestamp<1674770712849)&&(t=fcn_defaultStorySettings(),t.timestamp=Date.now()),fcn_setStorySettings(t),t}function fcn_defaultStorySettings(){return{view:"list",order:"asc",timestamp:1674770712849}}function fcn_setStorySettings(t){"object"==typeof t&&(fcn_storySettings=t,localStorage.setItem("fcnStorySettings",JSON.stringify(t)))}function fcn_applyStorySettings(){"object"==typeof fcn_storySettings&&(_$$("[data-view]").forEach((t=>{t.dataset.view="grid"==fcn_storySettings.view?"grid":"list"})),_$$("[data-order]").forEach((t=>{t.dataset.order="desc"==fcn_storySettings.order?"desc":"asc"})))}function fcn_toggleStoryTab(t){_$$(".story__article ._current").forEach((t=>{t.classList.remove("_current")})),_$$(`[data-finder="${t.dataset.target}"]`).forEach((t=>{t.classList.add("_current")})),_$$$("tabs").dataset.current=t.dataset.target,t.classList.add("_current")}function fcn_loadStoryComments(){let t;_$(".load-more-list-item").remove(),_$(".comments-loading-placeholder").classList.remove("hidden"),fcn_ajaxGet({post_id:fcn_inlineStorage.postId,page:fcn_storyCommentPage},"get_story_comments").then((e=>{e.success?(_$(".fictioneer-comments__list > ul").innerHTML+=e.data.html,fcn_storyCommentPage++):e.data?.error&&(t=fcn_buildErrorNotice(e.data.error))})).catch((e=>{t=fcn_buildErrorNotice(e)})).then((()=>{_$(".comments-loading-placeholder").remove(),t&&_$(".fictioneer-comments__list > ul").appendChild(t)}))}function fcn_startEpubDownload(t,e=0){e>3?t.classList.remove("ajax-in-progress"):fcn_ajaxGet({action:"fictioneer_ajax_download_epub",story_id:t.dataset.storyId}).then((r=>{r.success?(window.location.href=t.href,setTimeout((()=>{t.classList.remove("ajax-in-progress")}),2e3)):setTimeout((()=>{fcn_startEpubDownload(t,e+1)}),2e3)})).catch((e=>{t.classList.remove("ajax-in-progress"),e.status&&e.statusText&&fcn_showNotification(`${e.status}: ${e.statusText}`,5,"warning")}))}fcn_applyStorySettings(),_$$$("button-toggle-chapter-order")?.addEventListener("click",(t=>{fcn_storySettings.order="asc"===t.currentTarget.dataset.order?"desc":"asc",fcn_setStorySettings(fcn_storySettings),fcn_applyStorySettings()})),_$$$("button-toggle-chapter-view")?.addEventListener("click",(t=>{fcn_storySettings.view="list"===t.currentTarget.dataset.view?"grid":"list",fcn_setStorySettings(fcn_storySettings),fcn_applyStorySettings()})),_$$(".chapter-group__folding-toggle").forEach((t=>{t.addEventListener("click",(t=>{const e=t.currentTarget.closest(".chapter-group[data-folded]");e&&(e.dataset.folded="true"==e.dataset.folded?"false":"true")}))})),_$$(".tabs__item").forEach((t=>{t.addEventListener("click",(t=>{fcn_toggleStoryTab(t.currentTarget)}))})),_$(".comment-section")?.addEventListener("click",(t=>{t.target?.classList.contains("load-more-comments-button")&&fcn_loadStoryComments()})),_$$('[data-action="download-epub"]').forEach((t=>{t.addEventListener("click",(t=>{t.preventDefault(),t.currentTarget.classList.contains("ajax-in-progress")||(t.currentTarget.classList.add("ajax-in-progress"),fcn_startEpubDownload(t.currentTarget))}))}));

View File

@ -460,8 +460,8 @@ function fcn_ebookMediaUpload(event) {
// Open media modal
var uploader = wp.media({
multiple: false,
library : {
type : ['application/pdf', 'text/plain', 'application/rtf', 'application/x-mobipocket-ebook', 'application/epub+zip']
library: {
type: ['application/pdf', 'text/plain', 'application/rtf', 'application/x-mobipocket-ebook', 'application/epub+zip']
}
})
.open()
@ -473,10 +473,11 @@ function fcn_ebookMediaUpload(event) {
metabox.querySelector('[data-target*="size"]').textContent = attachment.filesizeHumanReadable;
metabox.querySelector('[data-target*="filename"]').textContent = attachment.filename;
metabox.querySelector('[data-target*="filename"]').href = attachment.url;
metabox.querySelector('[data-target*="upload"]').classList.add('hidden');
metabox.querySelector('[data-target*="replace"]').classList.remove('hidden');
metabox.querySelector('[data-target*="remove"]').classList.remove('hidden');
metabox.querySelector('[data-target*="display"]').classList.remove('hidden');
metabox.querySelectorAll('[data-target*="replace"], [data-target*="remove"], [data-target*="display"]')
.forEach(el => el.classList.remove('hidden'));
});
}
@ -503,10 +504,11 @@ function fcn_ebookMediaRemove(event) {
metabox.querySelector('[data-target*="size"]').textContent = '';
metabox.querySelector('[data-target*="filename"]').textContent = '';
metabox.querySelector('[data-target*="filename"]').href = '';
metabox.querySelector('[data-target*="upload"]').classList.remove('hidden');
metabox.querySelector('[data-target*="replace"]').classList.add('hidden');
metabox.querySelector('[data-target*="remove"]').classList.add('hidden');
metabox.querySelector('[data-target*="display"]').classList.add('hidden');
metabox.querySelectorAll('[data-target*="replace"], [data-target*="remove"], [data-target*="display"]')
.forEach(el => el.classList.add('hidden'));
}
// Listen for clicks on upload and replace

View File

@ -59,28 +59,25 @@ if (typeof fcn_removeQueryArgs === 'function') {
*/
function fcn_cleanupWebStorage(keepGuestData = false) {
localStorage.removeItem('fcnProfileAvatar');
localStorage.removeItem('fcnBookshelfContent');
const localItems = ['fcnProfileAvatar', 'fcnBookshelfContent'];
if (!keepGuestData) {
localStorage.removeItem('fcnChapterBookmarks');
localItems.push('fcnChapterBookmarks');
}
// Clean up user data
// Remove local data
localItems.forEach(item => localStorage.removeItem(item));
// Remove user data (if any)
const userDataKeys = ['loggedIn', 'follows', 'reminders', 'checkmarks', 'bookmarks', 'fingerprint'];
const userData = fcn_parseJSON(localStorage.getItem('fcnUserData'));
if (userData) {
userData['loggedIn'] = false;
userData['follows'] = false;
userData['reminders'] = false;
userData['checkmarks'] = false;
userData['bookmarks'] = false;
userData['fingerprint'] = false;
userDataKeys.forEach(key => userData[key] = false);
localStorage.setItem('fcnUserData', JSON.stringify(userData));
}
// Clean up private authentication data
// Remove private authentication data
const auth = fcn_parseJSON(localStorage.getItem('fcnAuth'));
if (auth?.loggedIn) {
@ -294,22 +291,22 @@ function fcn_setLoggedInState(state) {
// Cleanup view for users
if (!state.isAdmin) {
_$$('.only-admins').forEach(element => { element.remove() });
_$$('.only-admins').forEach(el => el.remove());
}
if (!state.isModerator && !state.isAdmin) {
_$$('.only-moderators').forEach(element => { element.remove() });
_$$('.only-moderators').forEach(el => el.remove());
}
if (!state.isAuthor && !state.isAdmin) {
_$$('.only-authors').forEach(element => { element.remove() });
_$$('.only-authors').forEach(el => el.remove());
}
if (!state.isModerator && !state.isAdmin) {
_$$('.only-editors').forEach(element => { element.remove() });
_$$('.only-editors').forEach(el => el.remove());
}
_$$('label[for="modal-login-toggle"], #modal-login-toggle, #login-modal').forEach(element => { element.remove() });
_$$('label[for="modal-login-toggle"], #modal-login-toggle, #login-modal').forEach(el => el.remove());
// Initialize local user
fcn_getProfileImage();
@ -566,41 +563,41 @@ fcn_scrollDirection();
// OBSERVERS
// =============================================================================
// Main observer
const /** @const {IntersectionObserver} */ fcn_mainObserver = new IntersectionObserver(
([e]) => {
fcn_theBody.classList.toggle('is-inside-main', e.intersectionRatio < 1 && e.boundingClientRect.top <= 0);
},
{ threshold: [1] }
);
/**
* Create and initialize an IntersectionObserver.
*
* @param {String} selector - Selector for the element to be observed.
* @param {Function} callback - Callback for the IntersectionObserver.
* @param {Object} options - Options for the IntersectionObserver.
*/
function fcn_observe(selector, callback, options = {}) {
const element = _$(selector);
// End of chapter observer
const /** @const {IntersectionObserver} */ fcn_endOfChapterObserver = new IntersectionObserver(
([e]) => {
fcn_theBody.classList.toggle('is-end-of-chapter', e.isIntersecting || e.boundingClientRect.top < 0)
}, { root: null, threshold: 0 }
);
if (!element) {
return null;
}
// Sticky navigation observer
const /** @const {IntersectionObserver} */ fct_navStickyObserver = new IntersectionObserver(
([e]) => {
fcn_mainNavigation.classList.toggle('is-sticky', e.intersectionRatio < 1);
}, { threshold: [1] }
);
const observer = new IntersectionObserver(entries => callback(entries[0]), options);
observer.observe(element);
}
// Apply observers
document.addEventListener('DOMContentLoaded', () => {
if (_$('.main-observer')) {
fcn_mainObserver.observe(_$('.main-observer'));
}
const mainObserverCallback = e => {
fcn_theBody.classList.toggle('is-inside-main', e.intersectionRatio < 1 && e.boundingClientRect.top <= 0);
};
if (_$('.chapter-end')) {
fcn_endOfChapterObserver.observe(_$('.chapter-end'));
}
const endOfChapterCallback = e => {
fcn_theBody.classList.toggle('is-end-of-chapter', e.isIntersecting || e.boundingClientRect.top < 0);
};
if (_$$$('nav-observer-sticky')) {
fct_navStickyObserver.observe(_$$$('nav-observer-sticky'));
}
const navStickyCallback = e => {
fcn_mainNavigation.classList.toggle('is-sticky', e.intersectionRatio < 1);
};
// Initialize observers
fcn_observe('.main-observer', mainObserverCallback, { threshold: [1] });
fcn_observe('.chapter-end', endOfChapterCallback, { root: null, threshold: 0 });
fcn_observe('#nav-observer-sticky', navStickyCallback, { threshold: [1] });
});
// =============================================================================

View File

@ -143,7 +143,7 @@ _$$('.chapter-group__folding-toggle').forEach(element => {
// =============================================================================
/**
* Toggles the active story tab
* Toggles the active story tab.
*
* @since 5.4.0
*
@ -152,7 +152,7 @@ _$$('.chapter-group__folding-toggle').forEach(element => {
function fcn_toggleStoryTab(target) {
// Clear previous tab
_$$('.story__article ._current').forEach(item => {
_$$('.story__article ._current').forEach(item => {
item.classList.remove('_current');
});

View File

@ -264,7 +264,11 @@ function fcn_readTextStack() {
// End of stack reached
if (fcn_ttsStack.length === 0) {
fcn_ttsInterface.classList.add('ended');
if (current) current.classList.remove('current-reading');
if (current) {
current.classList.remove('current-reading');
}
fcn_currentReadingId = -1;
fcn_ttsCurrentText = '';
return;
@ -277,7 +281,11 @@ function fcn_readTextStack() {
if (fcn_currentReadingId != item[0]) {
fcn_currentReadingId = item[0];
if (current) current.classList.remove('current-reading');
if (current) {
current.classList.remove('current-reading');
}
_$$$(fcn_currentReadingId).classList.add('current-reading');
}