Skip to content

Commit

Permalink
refactor(web/tooltip): open debounce delay
Browse files Browse the repository at this point in the history
  • Loading branch information
LukeWasTakenn committed Sep 29, 2023
1 parent fac8f33 commit 178e286
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 15 deletions.
36 changes: 21 additions & 15 deletions web/src/components/utils/Tooltip.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ import React from 'react';
import { flip, FloatingPortal, shift, useFloating, offset, useTransitionStyles } from '@floating-ui/react';
import { useAppSelector } from '../../store';
import SlotTooltip from '../inventory/SlotTooltip';
import { useDebounce } from '../../hooks/useDebounce';

const Tooltip: React.FC = () => {
const hoverData = useAppSelector((state) => state.tooltip);
const debounce = useDebounce(hoverData.open, 500);

const { refs, context, floatingStyles } = useFloating({
const { refs, update, context, floatingStyles } = useFloating({
middleware: [flip(), shift(), offset({ mainAxis: 10, crossAxis: 10 })],
open: hoverData.open,
open: hoverData.open ? debounce : false,
placement: 'right-start',
});

Expand All @@ -34,24 +36,28 @@ const Tooltip: React.FC = () => {
};

React.useEffect(() => {
!!hoverData
? window.addEventListener('mousemove', handleMouseMove)
: window.removeEventListener('mousemove', handleMouseMove);
if (hoverData.open) {
window.addEventListener('mousemove', handleMouseMove);

return () => window.removeEventListener('mousemove', handleMouseMove);
return () => {
window.removeEventListener('mousemove', handleMouseMove);
};
}
}, [hoverData.open]);

return (
<FloatingPortal>
{!!isMounted && (
<SlotTooltip
ref={refs.setFloating}
style={{ ...floatingStyles, ...styles }}
item={hoverData.item!}
inventory={hoverData!.inventory!}
/>
<>
{isMounted && (
<FloatingPortal>
<SlotTooltip
ref={refs.setFloating}
style={{ ...styles, ...floatingStyles }}
item={hoverData.item!}
inventory={hoverData!.inventory!}
/>
</FloatingPortal>
)}
</FloatingPortal>
</>
);
};

Expand Down
15 changes: 15 additions & 0 deletions web/src/hooks/useDebounce.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { useEffect, useState } from 'react';

export function useDebounce<T>(value: T, delay?: number): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value);

useEffect(() => {
const timer = setTimeout(() => setDebouncedValue(value), delay || 500);

return () => {
clearTimeout(timer);
};
}, [value, delay]);

return debouncedValue;
}

0 comments on commit 178e286

Please sign in to comment.