BeKultur/public/js/pwa.js
2026-10-21 21:07:54 +00:00

231 lines
7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* BeKultur - PWA & Offline State Manager
*/
(function () {
let isOffline = !navigator.onLine;
let bannerTimeout = null;
// 1. Service Worker Registration
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker
.register('/sw.js', { scope: '/' })
.then((reg) => {
// If updated service worker found
reg.addEventListener('updatefound', () => {
const installing = reg.installing;
if (installing) {
installing.addEventListener('statechange', () => {
if (installing.state === 'installed' && navigator.serviceWorker.controller) {
console.log('New BeKultur version available.');
}
});
}
});
})
.catch((err) => {
console.warn('ServiceWorker registration failed:', err);
});
});
}
// 2. Offline Banner Component
function getOrCreateBanner() {
let banner = document.getElementById('offlineBanner');
if (!banner) {
banner = document.createElement('div');
banner.id = 'offlineBanner';
banner.className = 'offline-banner hidden';
document.body.prepend(banner);
}
return banner;
}
function showOfflineBanner() {
if (bannerTimeout) {
clearTimeout(bannerTimeout);
bannerTimeout = null;
}
const banner = getOrCreateBanner();
banner.className = 'offline-banner active';
banner.innerHTML = `
<div class="offline-banner-content">
<span class="offline-badge-pill">⚡ Offline</span>
<span class="offline-banner-text">Showing locally cached data. Actions requiring connection are paused.</span>
</div>
`;
}
function showOnlineBanner() {
if (bannerTimeout) {
clearTimeout(bannerTimeout);
bannerTimeout = null;
}
const banner = getOrCreateBanner();
banner.className = 'offline-banner online';
banner.innerHTML = `
<div class="offline-banner-content">
<span class="online-badge-pill">✓ Online</span>
<span class="offline-banner-text">Connection restored. Live features re-enabled.</span>
</div>
`;
bannerTimeout = setTimeout(() => {
banner.className = 'offline-banner hidden';
bannerTimeout = null;
}, 2800);
}
// 3. Apply Offline Safeguards to UI
function applyOfflineState(offline) {
isOffline = offline;
if (offline) {
showOfflineBanner();
} else {
showOnlineBanner();
}
// --- A. Homework Checkboxes & Exclude Buttons ---
const assignmentToggles = document.querySelectorAll('.assignment-toggle');
assignmentToggles.forEach((checkbox) => {
const card = checkbox.closest('.assignment-card');
const isExcluded = card && card.dataset.excluded === 'true';
if (offline) {
checkbox.disabled = true;
checkbox.title = 'Offline mode: Homework status cannot be changed without connection.';
} else {
// Only re-enable if not excluded
checkbox.disabled = isExcluded;
checkbox.title = '';
}
});
const excludeButtons = document.querySelectorAll('.btn-exclude, .btn-disinclude');
excludeButtons.forEach((btn) => {
if (offline) {
btn.disabled = true;
btn.title = 'Offline mode: Homework cannot be excluded without connection.';
} else {
btn.disabled = false;
btn.title = btn.textContent.trim() === 'Restore' ? 'Restore homework' : 'Exclude homework';
}
});
// --- B. Private Lesson Request Form ---
const lessonForm = document.getElementById('privateLessonForm');
const btnSubmitLesson = document.getElementById('btnSubmitRequest');
const formSelects = document.querySelectorAll('#privateLessonForm select, #privateLessonForm button[type="submit"]');
let noticeEl = document.getElementById('privateLessonOfflineNotice');
if (!noticeEl && lessonForm) {
noticeEl = document.createElement('div');
noticeEl.id = 'privateLessonOfflineNotice';
noticeEl.className = 'alert alert-warning hidden';
noticeEl.style.marginBottom = '12px';
noticeEl.innerHTML = '⚡ <strong>Çevrimdışı mod:</strong> Yeni özel ders başvurusu yapmak için internet bağlantısı gereklidir.';
lessonForm.prepend(noticeEl);
}
if (formSelects.length > 0) {
formSelects.forEach((el) => {
el.disabled = offline;
});
if (noticeEl) {
if (offline) {
noticeEl.classList.remove('hidden');
} else {
noticeEl.classList.add('hidden');
}
}
}
// --- C. Station Buttons in Syllabus ---
const stationButtons = document.querySelectorAll('.station-btn');
stationButtons.forEach((btn) => {
if (offline) {
btn.classList.add('station-btn-offline');
btn.title = 'Offline mode: Station selection requires connection.';
} else {
btn.classList.remove('station-btn-offline');
btn.title = '';
}
});
// --- D. Sync Buttons Across All Pages ---
const syncButtonSelectors = [
'#btnSyncRecent',
'#btnSyncAll',
'#btnSyncSyllabus',
'#btnSyncPrivateLessons',
'#btnSyncExams',
'#btnEmptySync'
];
syncButtonSelectors.forEach((sel) => {
const btn = document.querySelector(sel);
if (!btn) return;
if (offline) {
if (!btn.dataset.onlineLabel) {
btn.dataset.onlineLabel = btn.textContent.trim();
}
btn.disabled = true;
btn.classList.add('btn-offline-disabled');
btn.title = 'Offline mode: Sync requires internet connection.';
btn.textContent = `${btn.dataset.onlineLabel} (Offline)`;
} else {
btn.disabled = false;
btn.classList.remove('btn-offline-disabled');
btn.title = '';
if (btn.dataset.onlineLabel) {
btn.textContent = btn.dataset.onlineLabel;
}
}
});
}
// 4. Click interceptor on homework checkboxes when offline
document.addEventListener(
'click',
(e) => {
if (!isOffline) return;
const target = e.target;
if (target.classList && target.classList.contains('assignment-toggle')) {
e.preventDefault();
e.stopPropagation();
alert('Çevrimdışı moddasınız. Ödev durumu internet bağlantısı olmadan değiştirilemez.');
}
},
true
);
// 5. Connection Listeners
window.addEventListener('online', () => {
applyOfflineState(false);
});
window.addEventListener('offline', () => {
applyOfflineState(true);
});
// 6. Initial Application on DOM Ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
if (!navigator.onLine) {
applyOfflineState(true);
}
});
} else {
if (!navigator.onLine) {
applyOfflineState(true);
}
}
// Export helper globally
window.BeKulturPWA = {
isOffline: () => isOffline,
refreshState: () => applyOfflineState(!navigator.onLine)
};
})();