62 lines
2.7 KiB
JavaScript
62 lines
2.7 KiB
JavaScript
(() => {
|
||
const root = document.documentElement;
|
||
const installItem = document.querySelector('[data-pwa-install-item]');
|
||
const installButton = document.querySelector('[data-pwa-install]');
|
||
const status = document.querySelector('[data-pwa-status]');
|
||
const standalone = window.matchMedia('(display-mode: standalone)');
|
||
let installPrompt = null;
|
||
function updateMode() {
|
||
const installed = standalone.matches || navigator.standalone === true;
|
||
root.dataset.standalone = String(installed);
|
||
if (installItem) installItem.hidden = installed || !installPrompt;
|
||
}
|
||
function updateTheme() {
|
||
// The shell's tokens remain the only palette; theme changes include save rollback.
|
||
const color = getComputedStyle(root).getPropertyValue('--pd-chrome').trim();
|
||
if (color) document.querySelector('meta[name="theme-color"]')?.setAttribute('content', color);
|
||
}
|
||
window.addEventListener('plotdirector:theme-changed', updateTheme);
|
||
standalone.addEventListener('change', updateMode);
|
||
window.addEventListener('beforeinstallprompt', event => {
|
||
if (!installButton) return;
|
||
event.preventDefault();
|
||
installPrompt = event;
|
||
updateMode();
|
||
});
|
||
window.addEventListener('appinstalled', () => {
|
||
installPrompt = null;
|
||
updateMode();
|
||
if (status) status.textContent = 'PlotDirector installed';
|
||
});
|
||
installButton?.addEventListener('click', async () => {
|
||
if (!installPrompt) return;
|
||
const prompt = installPrompt;
|
||
installPrompt = null;
|
||
updateMode();
|
||
try {
|
||
await prompt.prompt();
|
||
await prompt.userChoice;
|
||
} catch {
|
||
if (status) status.textContent = 'Installation could not be opened. Use your browser’s app installation menu.';
|
||
}
|
||
});
|
||
updateMode();
|
||
updateTheme();
|
||
if ('serviceWorker' in navigator && window.isSecureContext) {
|
||
navigator.serviceWorker.register('/service-worker.js', { scope: '/', updateViaCache: 'none' })
|
||
.then(registration => {
|
||
// Each full navigation checks for updates; long-lived editors check on return.
|
||
// No controllerchange reload: unsaved work must remain undisturbed.
|
||
let checkedAt = Date.now();
|
||
registration.update().catch(() => {});
|
||
document.addEventListener('visibilitychange', () => {
|
||
if (!document.hidden && Date.now() - checkedAt > 60 * 60 * 1000) {
|
||
checkedAt = Date.now();
|
||
registration.update().catch(() => {});
|
||
}
|
||
});
|
||
})
|
||
.catch(() => { /* Installation enhancement must never block authoring. */ });
|
||
}
|
||
})();
|