Skip to content

Commit

Permalink
fix tooltip debounce
Browse files Browse the repository at this point in the history
  • Loading branch information
talentlessguy committed Aug 28, 2024
1 parent b72d620 commit 6e23835
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import * as React from 'react'
import { TransitionState, useTransition } from 'react-transition-state'

import { debounce } from 'es-toolkit'

import { Portal } from '../Portal'
import { Box, BoxProps } from '../Box/Box'
import { getValueForTransitionState } from './utils/getValueForTransitionState'
import { container } from './style.css'
import { debounceWithWait } from './utils/debounce'

export type DynamicPopoverSide = 'top' | 'right' | 'bottom' | 'left'

Expand Down Expand Up @@ -363,7 +362,7 @@ export const DynamicPopover: React.FC<DynamicPopoverProps> = ({
onShowCallback?.()
}

const debouncedMouseMove = debounce(
const debouncedMouseMove = debounceWithWait(
(e: MouseEvent) => {
const cursorXY = { x: e.clientX, y: e.clientY }
const targetRect = targetElement?.getBoundingClientRect()
Expand All @@ -381,7 +380,7 @@ export const DynamicPopover: React.FC<DynamicPopoverProps> = ({
document.removeEventListener('mousemove', handleMouseMove)
},
100,
{ signal: AbortSignal.timeout(1000) },
1000,
)

handleMouseMove = (e: MouseEvent) => {
Expand Down
40 changes: 40 additions & 0 deletions components/src/components/atoms/DynamicPopover/utils/debounce.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
export function debounceWithWait<T extends (...args: any[]) => any>(
func: T,
wait: number,
maxWait: number,
): (...args: Parameters<T>) => void {
let timer: NodeJS.Timeout | null = null
let maxTimer: NodeJS.Timeout | null = null

return function (...args: Parameters<T>): void {
// @ts-expect-error some magic
// eslint-disable-next-line @typescript-eslint/no-this-alias
const context = this

if (timer) {
clearTimeout(timer)
}

// Clear the maxWait timer if it exists
if (maxTimer) {
clearTimeout(maxTimer)
}

// Set the regular debounce timer
timer = setTimeout(() => {
if (maxTimer) {
clearTimeout(maxTimer)
}
func.apply(context, args)
}, wait)

// Set the maxWait timer
maxTimer = setTimeout(() => {
func.apply(context, args)
// Clear the regular timer since maxWait has fired
if (timer) {
clearTimeout(timer)
}
}, maxWait)
}
}

0 comments on commit 6e23835

Please sign in to comment.