helpers/visibility.js

53 lines
1.3 KiB
JavaScript
Raw Permalink Normal View History

2025-01-26 13:43:30 +01:00
/**
@license
Copyright (c) 2025 trading_peter
This program is available under Apache License Version 2.0
*/
/**
* Orchastrates a intersetion observer to execute code if the element becomes visible or hidden/disconnected.
*/
export const Visibility = function(superClass) {
return class extends superClass {
constructor() {
super();
// Create intersection observer
this._observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
this.visibilityChanged(true);
} else {
this.visibilityChanged(false);
}
});
});
}
/**
* Invoked when the element becomes either visible / connected or hidden / disconnected.
* The callback's logic must be able to handle multiple, successive calls with the same state.
* @param {boolean} visible
*/
visibilityChanged(visible) {
console.warn(this.tagName, 'should override onVisible');
}
connectedCallback() {
super.connectedCallback();
// Start observing this element
this._observer.observe(this);
}
disconnectedCallback() {
super.disconnectedCallback();
// Clean up
this._observer.unobserve(this);
this._observer.disconnect();
this.visibilityChanged(false);
}
};
}