All files / modules/10-common/hooks useTabVisible.ts

65.52% Statements 19/29
33.33% Branches 5/15
80% Functions 4/5
65.52% Lines 19/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61              7x 7x 7x       21x 21x 21x   21x 21x               21x   7x       7x 77x 77x 21x                 21x               21x 21x 18x       77x    
/*
 * Copyright 2021 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import React from 'react'
import { loggerFor } from 'framework/logging/logging'
import { ModuleName } from 'framework/types/ModuleName'
 
function getVisiblePropEvent(): { hidden?: string; visibilityChange?: string } {
  // Set the name of the hidden property and the change event for visibility
  let hidden: string | undefined = undefined
  let visibilityChange: string | undefined = undefined
  Eif (typeof document.hidden !== 'undefined') {
    // Opera 12.10 and Firefox 18 and later support
    hidden = 'hidden'
    visibilityChange = 'visibilitychange'
  } else if (typeof document.msHidden !== 'undefined') {
    hidden = 'msHidden'
    visibilityChange = 'msvisibilitychange'
  } else if (typeof document.webkitHidden !== 'undefined') {
    hidden = 'webkitHidden'
    visibilityChange = 'webkitvisibilitychange'
  }
  return { hidden, visibilityChange }
}
const logger = loggerFor(ModuleName.COMMON)
 
// Adopted from https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
 
export default function useTabVisible(): boolean {
  const [visible, setVisibility] = React.useState<boolean>(true)
  React.useEffect(() => {
    const { hidden, visibilityChange } = getVisiblePropEvent()
    function handleVisibilityChange(): void {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      if (hidden && (document as any)[hidden]) {
        setVisibility(false)
      } else {
        setVisibility(true)
      }
    }
    Iif (
      typeof document.addEventListener === 'undefined' ||
      typeof hidden === 'undefined' ||
      typeof visibilityChange === 'undefined'
    ) {
      logger.info('The Page Visibility API is not supported')
    } else {
      // Handle page visibility change
      document.addEventListener(visibilityChange, handleVisibilityChange, false)
      return () => {
        document.removeEventListener(visibilityChange, handleVisibilityChange, false)
      }
    }
  }, [])
  return visible
}