62 lines
1.9 KiB
JavaScript
62 lines
1.9 KiB
JavaScript
import Service from '@ember/service';
|
|
|
|
// Tracks the page transitions that pause or discard the dashboard. Dashtab is a
|
|
// new-tab page, so it is frequently navigated away from while its integrations
|
|
// are still loading; the resulting cancelled requests and dropped sockets must
|
|
// not be mistaken for failures, and the dashboard has to recover when it is
|
|
// restored from the back/forward cache.
|
|
export default class PageLifecycleService extends Service {
|
|
// True while the document is being unloaded (a real navigation, not a
|
|
// bfcache freeze), so pollers can ignore errors raised during teardown.
|
|
leaving = false;
|
|
|
|
handlers = new Set();
|
|
|
|
constructor() {
|
|
super(...arguments);
|
|
|
|
this.onPageHide = (event) => {
|
|
this.leaving = !event.persisted;
|
|
};
|
|
|
|
this.onPageShow = (event) => {
|
|
this.leaving = false;
|
|
|
|
if (event.persisted) {
|
|
this.notifyRestore();
|
|
}
|
|
};
|
|
|
|
// The Page Lifecycle API freezes a backgrounded tab without unloading it;
|
|
// `resume` is the counterpart to `freeze` and lets us refresh a stale view.
|
|
this.onResume = () => {
|
|
this.notifyRestore();
|
|
};
|
|
|
|
window.addEventListener('pagehide', this.onPageHide);
|
|
window.addEventListener('pageshow', this.onPageShow);
|
|
window.addEventListener('resume', this.onResume);
|
|
}
|
|
|
|
// Registers a callback to run when the page is restored after being frozen or
|
|
// discarded. Returns an unsubscribe function.
|
|
onRestore(handler) {
|
|
this.handlers.add(handler);
|
|
return () => this.handlers.delete(handler);
|
|
}
|
|
|
|
notifyRestore() {
|
|
for (const handler of [...this.handlers]) {
|
|
handler();
|
|
}
|
|
}
|
|
|
|
willDestroy() {
|
|
window.removeEventListener('pagehide', this.onPageHide);
|
|
window.removeEventListener('pageshow', this.onPageShow);
|
|
window.removeEventListener('resume', this.onResume);
|
|
this.handlers.clear();
|
|
super.willDestroy();
|
|
}
|
|
}
|