From 1c7110e4c9d5511dd130342a1c35237d5a427060 Mon Sep 17 00:00:00 2001 From: Robin Townsend Date: Thu, 6 Jul 2023 00:37:16 -0400 Subject: [PATCH] Improve the double click detection So that it doesn't cause unnecessary renders, and interprets a series of three clicks as a double-click followed by a single click, rather than two overlapping double-clicks. (That behavior felt odd to me during testing of NewVideoGrid, which is why I picked up this small change.) --- src/video-grid/NewVideoGrid.tsx | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/src/video-grid/NewVideoGrid.tsx b/src/video-grid/NewVideoGrid.tsx index 0361e97..57be72f 100644 --- a/src/video-grid/NewVideoGrid.tsx +++ b/src/video-grid/NewVideoGrid.tsx @@ -60,6 +60,11 @@ interface DragState { cursorY: number; } +interface TapData { + tileId: string; + ts: number; +} + interface SlotProps { style?: CSSProperties; } @@ -257,10 +262,7 @@ export function NewVideoGrid({ ); }; - const [lastTappedTileId, setLastTappedTileId] = useState( - undefined - ); - const [lastTapTime, setLastTapTime] = useState(0); + const lastTap = useRef(null); // Callback for useDrag. We could call useDrag here, but the default // pattern of spreading {...bind()} across the children to bind the gesture @@ -279,12 +281,15 @@ export function NewVideoGrid({ if (tap) { const now = Date.now(); - if (tileId === lastTappedTileId && now - lastTapTime < 500) { + if ( + tileId === lastTap.current?.tileId && + now - lastTap.current.ts < 500 + ) { toggleFocus?.(items.find((i) => i.id === tileId)!); + lastTap.current = null; + } else { + lastTap.current = { tileId, ts: now }; } - - setLastTappedTileId(tileId); - setLastTapTime(now); } else { const tileController = springRef.current.find( (c) => (c.item as Tile).item.id === tileId