<!--

    Usage:

    To perform an action the first time the browser tab becomes active, override the browserTabFirstActive() method.

    To watch for changes to the browser tab's active state, watch the isBrowserTabActive property.

-->
<script>
export default {
    data() {
        return { isBrowserTabActive: false, browserTabActivationCount: 0 };
    },
    mounted() {
        if (typeof document === 'undefined') {
            console.warn('Unable to create visibility change listener.  No document object.');
            return;
        }

        document.addEventListener('visibilitychange', this.onTabVisibilityChange);
        this.onTabVisibilityChange();
    },
    beforeUnmount() {
        document.removeEventListener('visibilitychange', this.onTabVisibilityChange);
    },
    methods: {
        onTabVisibilityChange() {
            if (document.visibilityState === 'visible') {
                this.isBrowserTabActive = true;
                this.browserTabActivationCount++;

                if (this.browserTabActivationCount == 1) {
                    if (this.browserTabFirstActive) {
                        this.browserTabFirstActive();
                    }
                }
            } else {
                this.isBrowserTabActive = false;
            }
        },

        // OVERRIDE this method to perform an action the first time the browser tab becomes active
        //
        // browserTabFirstActive() {
        //     console.log('browser tab first active');}
        // }
    },
};
</script>
