let USER = {};
let page = "Home";
let swRegistration = null;
// Реєструємо CustomElements
const Notifier = document.getElementById('notif-manager');
const Updater = document.querySelector('swipe-updater');
// Определение ID главного блока
let app = document.getElementById('app');
// Конфигурация роутера
Router.config({ mode: 'history' });
async function appReload() {
// location.reload();
// Router.check().listen().delegateLinks();
// // Закрытие старого соединения WebSocket
// if (Cloud.socket) Cloud.socket.close(1000, "Перезапуск з'єднання");
// Cloud.start();
// listEntrances = []
// listApartment = []
}
// Перевизначення функції, яка викликається при "свайпі"
// Updater.setReloadFunction(() => appReload());
// Функция загрузки приложения
window.addEventListener('load', async function () {
console.log('[OS] ', detectOS());
if (Router.getParams().uuid) {
localStorage.setItem("uuid", Router.getParams().uuid)
}
let uuid = localStorage.getItem("uuid");
if (!uuid) {
Router.navigate(`/auth`).check().listen().delegateLinks();
} else {
const URL = `${CONFIG.api}auth`;
USER = await fetch(URL, {
method: 'GET',
headers: {
"Content-Type": "application/json, text/plain, */*",
"Authorization": uuid
}
}).then(response => {
if (response.status === 401) {
localStorage.removeItem("uuid");
Router.navigate(`/auth`);
}
return response.json();
});
console.log("[APP] USER Info: ", USER);
if (USER.possibilities.can_view_stand) {
newMenuItems({
id: 'menu-stand',
title: 'Графік стенду',
icon: ``,
href: '/stand'
});
}
if (USER.possibilities.can_view_schedule) {
newMenuItems({
id: 'menu-schedule',
title: 'Графіки зібрань',
icon: ``,
href: '/schedule'
});
}
if (USER.possibilities.can_view_sheeps) {
newMenuItems({
id: 'menu-sheeps',
title: 'Вісники',
icon: ``,
href: '/sheeps',
hidden: true
});
await Sheeps.sheeps_list.loadAPI();
}
if (USER.possibilities.can_manager_territory) {
newMenuItems({
id: 'menu-territory',
title: 'Території',
icon: ``,
href: '/territory',
hidden: true
});
}
newMenuItems({
id: 'menu-options',
title: 'Опції',
icon: ``,
href: '/options'
});
if (Cloud.socket) Cloud.socket.close(1000, "Перезапуск з'єднання");
Cloud.start();
editFontStyle();
Router.check().listen().delegateLinks();
}
});
function newMenuItems({ id, title, icon, href, hidden=false }) {
const newItem = document.createElement('nav-item');
newItem.setAttribute('id', id);
newItem.setAttribute('title', title);
newItem.setAttribute('icon', icon);
newItem.setAttribute('href', href);
newItem.setAttribute('data-hidden', hidden);
document.querySelector('navigation-container').appendChild(newItem);
}
let offlineNode = null;
window.addEventListener("offline", () => {
console.log("[APP] Інтернет зник");
offlineNode = Notifier.error({
title: 'Оффлайн',
text: 'Втрачено з\'єднання з інтернетом'
}, { timeout: 0, lock: true });
});
window.addEventListener("online", () => {
console.log("[APP] Інтернет з'явився");
if (offlineNode) {
Notifier._removeNode(offlineNode);
offlineNode = null;
}
Notifier.success({
title: 'Онлайн',
text: 'Інтернет знову працює'
}, { timeout: 3000 });
});
function editFontStyle() {
let fontSize = localStorage.getItem("fontSize")
? localStorage.getItem("fontSize")
: 'medium';
applyFontMode(fontSize);
}
function applyFontMode(mode) {
const options = {
"small": {
"--FontSize1": "10px",
"--FontSize2": "11px",
"--FontSize3": "12px",
"--FontSize4": "13px",
"--FontSize5": "14px"
},
"medium": {
"--FontSize1": "12px",
"--FontSize2": "13px",
"--FontSize3": "14px",
"--FontSize4": "15px",
"--FontSize5": "16px"
},
"large": {
"--FontSize1": "15px",
"--FontSize2": "16px",
"--FontSize3": "17px",
"--FontSize4": "18px",
"--FontSize5": "19px"
}
};
const root = document.documentElement;
const config = options[mode];
if (!config) return;
Object.keys(config).forEach(key => {
if (key.startsWith("--")) {
root.style.setProperty(key, config[key]);
}
});
}
if ('serviceWorker' in navigator) {
let refreshing = false;
let updateNode = null;
const updateCache = sw => {
if (updateNode) {
Notifier._removeNode(updateNode);
updateNode = null;
}
Notifier.warn({ title: `Завантаження оновлення`, text: `Додаток буде перезавантажено!` }, { timeout: 3000 });
sw.postMessage('skipWaiting'); // активує новий SW
sw.postMessage('updateCache'); // оновлює кеш
};
navigator.serviceWorker.register('/sw.js').then(reg => {
// якщо є waiting SW, показуємо банер
if (reg.waiting) {
updateNode = Notifier.click({ title: `Доступне оновлення`, text: `Натисніть, щоб оновити додаток до останньої версії!` }, { type: 'info', f: () => updateCache(reg.waiting), timeout: 0 });
}
// слідкуємо за новим воркером
reg.addEventListener('updatefound', () => {
const newWorker = reg.installing;
if (!newWorker) return;
newWorker.addEventListener('statechange', () => {
if (newWorker.state === 'installed' && reg.waiting) {
updateNode = Notifier.click({ title: `Доступне оновлення`, text: `Натисніть, щоб оновити додаток до останньої версії!` }, { type: 'info', f: () => updateCache(reg.waiting), timeout: 0 });
}
});
});
navigator.serviceWorker.addEventListener('controllerchange', () => {
if (refreshing) return;
refreshing = true;
window.location.reload(); // відбувається ТІЛЬКИ після skipWaiting
});
}).catch(err => console.error('[ServiceWorker] Помилка реєстрації SW:', err));
}