Skip to content

Commit

Permalink
Avoid collapsing on double click (need to delay collapse)
Browse files Browse the repository at this point in the history
  • Loading branch information
CarsonF committed Oct 14, 2024
1 parent ec00a4b commit 41b127d
Showing 1 changed file with 61 additions and 10 deletions.
71 changes: 61 additions & 10 deletions src/scenes/Dashboard/ProgressReportsWidget/expansionState.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,29 +54,80 @@ export const ExpandAllButton = () => {
// i.e. to select the text within.
const MOVEMENT_THRESHOLD = 10;

interface Position {
x: number;
y: number;
}
const isPosClose = (a: Position, b: Position) =>
Math.abs(a.x - b.x) < MOVEMENT_THRESHOLD &&
Math.abs(a.y - b.y) < MOVEMENT_THRESHOLD;
const eventPos = (e: MouseEvent) => ({ x: e.clientX, y: e.clientY });

export const useExpandedSetup = () => {
const expanded = useSet<GridRowId>();

const lastDownPos = useRef({ x: 0, y: 0 });
const { current: lastDownPositions } = useRef(new Set<Position>());
const { current: collapseTimers } = useRef(new Map<GridRowId, number>());

const onMouseDown = useCallback((e: MouseEvent) => {
lastDownPos.current = { x: e.clientX, y: e.clientY };
if (!(e.target instanceof HTMLElement)) {
return;
}
const id = e.target.closest('[role="row"]')?.getAttribute('data-id');
if (!id) {
return;
}
const pos = eventPos(e);

const hasPrev = [...lastDownPositions].some((prev) =>
isPosClose(prev, pos)
);
if (hasPrev) {
const prevTimer = collapseTimers.get(id);
if (prevTimer) {
// console.log('cancelling collapse', id);
clearTimeout(prevTimer);
collapseTimers.delete(id);
}
}
// console.log('marking down pos');
lastDownPositions.add(pos);
setTimeout(() => {
// console.log('removing down pos');
lastDownPositions.delete(pos);
}, 500);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

const onRowClick = useCallback<GridProps['onRowClick'] & {}>(
({ id }, event) => {
const now = { x: event.clientX, y: event.clientY };
const prev = lastDownPos.current;
if (
Math.abs(now.x - prev.x) > MOVEMENT_THRESHOLD ||
Math.abs(now.y - prev.y) > MOVEMENT_THRESHOLD
) {
const now = eventPos(event);
const prev = [...lastDownPositions].at(-1);
if (!prev || !isPosClose(prev, now)) {
// console.log('up, but dragging');
// This click (up) event appears to be a drag, not a click.
return;
}
expanded.toggle(id);
if (event.detail > 1) {
// console.log('double click', event.detail);
const timer = collapseTimers.get(id);
clearTimeout(timer);
collapseTimers.delete(id);
return;
}
// console.log('single click');
if (!expanded.has(id)) {
expanded.add(id);
} else if (!collapseTimers.has(id)) {
const timer = window.setTimeout(() => {
collapseTimers.delete(id);
expanded.remove(id);
}, 500);
collapseTimers.set(id, timer);
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
[expanded]
);

return { expanded, onMouseDown, onRowClick };
Expand Down

0 comments on commit 41b127d

Please sign in to comment.