All files / react useHover.ts

96.67% Statements 29/30
54.55% Branches 6/11
100% Functions 8/8
96.67% Lines 29/30

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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92                                                                          3x   3x   3x 3x 3x   3x 3x   3x 2x 1x 1x     3x 2x 1x 1x       3x 1x 1x 1x 1x       3x 1x 1x 1x 1x             3x 1x 1x     3x            
import { useCallback, useRef, useState } from 'react'
import { useLatest, useUnmount } from 'react-use'
 
export interface UseHoverOptions {
  /**
   * 悬停开始后多久开启悬停态,单位为毫秒。
   *
   * @default 50
   */
  hoverStartDelay?: number
 
  /**
   * 悬停结束后多久关闭悬停态,单位为毫秒。
   *
   * @default 400
   */
  hoverEndDelay?: number
}
 
export interface UseHoverResult {
  /**
   * 当前的悬停态。
   */
  hovering: boolean
 
  /**
   * 开始悬停。
   */
  startHover: () => any
 
  /**
   * 结束悬停。
   */
  endHover: () => any
}
 
export function useHover(options: UseHoverOptions = {}): UseHoverResult {
  const { hoverStartDelay = 50, hoverEndDelay = 400 } = options
 
  const [hovering, setHovering] = useState(false)
 
  const latestHoverStartDelay = useLatest(hoverStartDelay)
  const latestHoverEndDelay = useLatest(hoverEndDelay)
  const latestHovering = useLatest(hovering)
 
  const hoverStartTimer = useRef<any>()
  const hoverEndTimer = useRef<any>()
 
  const clearHoverStartTimer = useCallback(() => {
    if (hoverStartTimer.current) {
      clearTimeout(hoverStartTimer.current)
      hoverStartTimer.current = undefined
    }
  }, [])
  const clearHoverEndTimer = useCallback(() => {
    if (hoverEndTimer.current) {
      clearTimeout(hoverEndTimer.current)
      hoverEndTimer.current = undefined
    }
  }, [])
 
  const startHover = useCallback(() => {
    if (!latestHovering.current) {
      clearHoverStartTimer()
      hoverStartTimer.current = setTimeout(() => {
        setHovering(true)
      }, latestHoverStartDelay.current)
    }
  }, [])
  const endHover = useCallback(() => {
    if (latestHovering.current) {
      clearHoverEndTimer()
      hoverEndTimer.current = setTimeout(() => {
        setHovering(false)
      }, latestHoverEndDelay.current)
    } else E{
      clearHoverStartTimer()
    }
  }, [])
 
  useUnmount(() => {
    clearHoverStartTimer()
    clearHoverEndTimer()
  })
 
  return {
    hovering,
    startHover,
    endHover,
  }
}