All files / utils isElementVisible.ts

83.33% Statements 25/30
56% Branches 14/25
100% Functions 6/6
84% Lines 21/25

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 62      23x 23x 35x       35x   23x 9x 25x   1x   23x 5x   5x 16x                           5x   23x                         9x   8x 8x   8x 8x 3x   5x    
// ref: https://github.com/LuizAsFight/is-element-visible/blob/master/src/index.js
 
// @ts-nocheck
const isOverflowHidden = el => getComputedStyle(el, 'overflow') === 'hidden'
const getComputedStyle = (el, property) => {
  const computedStyle = window.getComputedStyle
    ? document.defaultView.getComputedStyle(el, null)
    : el.currentStyle
 
  return property ? computedStyle[property] : computedStyle
}
const isOnDocument = el => {
  while ((el = el.parentNode)) {
    if (el === document) return true
  }
  return false
}
const isVisibleDueToOverflow = el => {
  const elPositioning = getPositioning(el.getBoundingClientRect())
 
  while ((el = el.parentNode)) {
    Iif (el.nodeType !== 9 && isOverflowHidden(el)) {
      const parentElPositioning = getPositioning(el.getBoundingClientRect())
 
      const isElInsideParentRectX =
        elPositioning.startX >= parentElPositioning.startX &&
        elPositioning.endX <= parentElPositioning.endX
      const isElInsideParentRectY =
        elPositioning.startY >= parentElPositioning.startY &&
        elPositioning.endY <= parentElPositioning.endY
 
      if (!isElInsideParentRectX || !isElInsideParentRectY) return false
    }
  }
 
  return true
}
const getPositioning = ({ x, width, y, height }) => ({
  startX: parseInt(x),
  endX: parseInt(x) + parseInt(width),
  startY: parseInt(y),
  endY: parseInt(y) + parseInt(height),
})
 
/**
 * 检查 HTML 元素是否可见。
 *
 * @param el 要检查的 HTML 元素
 */
export function isElementVisible(el: HTMLElement): boolean {
  if (!isOnDocument(el)) return false
 
  const isHiddenDueToOpacity = getComputedStyle(el, 'opacity') === '0'
  const isHiddenDueToDisplay = getComputedStyle(el, 'display') === 'none'
  const isHiddenDueToVisibility =
    getComputedStyle(el, 'visibility') === 'hidden'
  if (isHiddenDueToOpacity || isHiddenDueToDisplay || isHiddenDueToVisibility)
    return false
 
  return isVisibleDueToOverflow(el)
}