UNPKG

maz-ui

Version:

A standalone components library for Vue.Js 3 & Nuxt.Js 3

57 lines (56 loc) 1.77 kB
import { i as isClient } from "../chunks/isClient.WI4oSt66.js"; class UserVisibility { constructor(callback, options) { this.callback = callback, this.options = { ...this.defaultOptions, ...options }, this.eventHandlerFunction = this.eventHandler.bind(this), isClient() && this.start(); } eventHandlerFunction; event = "visibilitychange"; timeoutHandler; options; defaultOptions = { timeout: 5e3, once: !1, immediate: !0 }; isVisible = !1; start() { if (!isClient()) { console.warn("[UserVisibility](start) you should run this method on client side"); return; } this.options.immediate && this.emitCallback(), this.addEventListener(); } emitCallback() { this.isVisible = document.visibilityState === "visible", this.callback({ isVisible: this.isVisible }), this.options.once && this.destroy(); } eventHandler() { document.visibilityState === "visible" && !this.isVisible ? (this.clearTimeout(), this.emitCallback()) : document.visibilityState === "hidden" && this.initTimeout(); } clearTimeout() { this.timeoutHandler && (clearTimeout(this.timeoutHandler), this.timeoutHandler = void 0); } initTimeout() { this.clearTimeout(), this.timeoutHandler = setTimeout(this.emitCallback.bind(this), this.options.timeout); } addEventListener() { document.addEventListener(this.event, this.eventHandlerFunction); } removeEventListener() { document.removeEventListener(this.event, this.eventHandlerFunction); } destroy() { this.removeEventListener(), this.timeoutHandler && clearTimeout(this.timeoutHandler); } } function useUserVisibility({ callback, options }) { return new UserVisibility(callback, options); } export { useUserVisibility };