Skip to content

Commit 2e1c3fa

Browse files
committed
Avoid firing click event in floatables when user drags the mouse
Alternative approach at fixing #2484
1 parent bd79a06 commit 2e1c3fa

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

ts/sveltelib/event-store.ts

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,40 @@ function eventStore<T extends EventTarget, K extends keyof EventTargetToMap<T>>(
3434

3535
export default eventStore;
3636

37-
const documentClick = eventStore(document, "click", MouseEvent);
37+
/**
38+
* A click event that fires only if the mouse has not appreciably moved since the button
39+
* was pressed down. This was added so that if the user clicks inside a floating area and
40+
* drags the mouse outside the area while selecting text, it doesn't end up closing the
41+
* floating area.
42+
*/
43+
function mouseClickWithoutDragStore(): Readable<MouseEvent> {
44+
const initEvent = new MouseEvent("click");
45+
46+
return readable(
47+
initEvent,
48+
(set: Subscriber<MouseEvent>): Callback => {
49+
let startingX: number;
50+
let startingY: number;
51+
function onMouseDown(evt: MouseEvent): void {
52+
startingX = evt.clientX;
53+
startingY = evt.clientY;
54+
}
55+
function onClick(evt: MouseEvent): void {
56+
if (Math.abs(startingX - evt.clientX) < 5 && Math.abs(startingY - evt.clientY) < 5) {
57+
set(evt);
58+
}
59+
}
60+
document.addEventListener("mousedown", onMouseDown);
61+
document.addEventListener("click", onClick);
62+
return () => {
63+
document.removeEventListener("click", onClick);
64+
document.removeEventListener("mousedown", onMouseDown);
65+
};
66+
},
67+
);
68+
}
69+
70+
const documentClick = mouseClickWithoutDragStore();
3871
const documentKeyup = eventStore(document, "keyup", KeyboardEvent);
3972

4073
export { documentClick, documentKeyup };

0 commit comments

Comments
 (0)