ldc-lionor/resources/ts/fo/modules/ad_modal.ts
2024-05-27 14:46:07 +02:00

79 lines
2.4 KiB
TypeScript

import { Modal } from "bootstrap";
document.addEventListener("DOMContentLoaded", function () {
const adModal = document.getElementById("adModal");
if (!adModal) {
return;
}
const callback = (mutationList: Array<MutationRecord>, observer: MutationObserver) => {
for (const mutation of mutationList) {
if (mutation.type === "attributes") {
// Display only if the tiemstamp is correct and if no other modal is opened.
if (getAdModalCache() && !this.body.classList.contains("cn-open") && !this.body.classList.contains("modal-open")) {
displayAdModal(adModal);
observer.disconnect();
}
}
}
};
const observer = new MutationObserver(callback);
observer.observe(this.body, { attributes: true });
if (getAdModalCache() && !this.body.classList.contains("cn-open")) {
displayAdModal(adModal);
}
// Set the timer also if we click on the link
const modalLink = document.getElementById("adModalLink");
if (modalLink) {
modalLink.addEventListener("click", function () {
updateAdModalCache();
});
}
});
function displayAdModal(adModal: HTMLElement)
{
const myModal = new Modal(adModal);
myModal.show();
adModal.addEventListener("hidden.bs.modal", function () {
updateAdModalCache();
});
}
/** Check if we need to show the modal according to the stored timer */
function getAdModalCache(): boolean {
const localAdModalTimer = localStorage.getItem("hideAdModalUntil");
if (localAdModalTimer !== null) {
const localAdModalTimerJson = JSON.parse(localAdModalTimer);
const localStoredTime = new Date(localAdModalTimerJson.value);
if (isTimestampTooOld(localStoredTime)) {
localStorage.removeItem("hideAdModalUntil");
return true;
}
return false;
}
return true;
}
/** Update the local stored timestamp */
function updateAdModalCache(): void {
const time = { value: new Date() };
localStorage.setItem("hideAdModalUntil", JSON.stringify(time));
}
/** Check if the stored timestamp is older than yesterday */
function isTimestampTooOld(timestamp: Date): boolean
{
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
if (timestamp.getTime() - yesterday.getTime() > 0) {
return false;
}
return true;
}