Skip to content

Commit

Permalink
Avoid firing click event in floatables when user drags the mouse
Browse files Browse the repository at this point in the history
Alternative approach at fixing #2484
  • Loading branch information
dae committed May 1, 2023
1 parent bd79a06 commit 2e1c3fa
Showing 1 changed file with 34 additions and 1 deletion.
35 changes: 34 additions & 1 deletion ts/sveltelib/event-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,40 @@ function eventStore<T extends EventTarget, K extends keyof EventTargetToMap<T>>(

export default eventStore;

const documentClick = eventStore(document, "click", MouseEvent);
/**
* A click event that fires only if the mouse has not appreciably moved since the button
* was pressed down. This was added so that if the user clicks inside a floating area and
* drags the mouse outside the area while selecting text, it doesn't end up closing the
* floating area.
*/
function mouseClickWithoutDragStore(): Readable<MouseEvent> {
const initEvent = new MouseEvent("click");

return readable(
initEvent,
(set: Subscriber<MouseEvent>): Callback => {
let startingX: number;
let startingY: number;
function onMouseDown(evt: MouseEvent): void {
startingX = evt.clientX;
startingY = evt.clientY;
}
function onClick(evt: MouseEvent): void {
if (Math.abs(startingX - evt.clientX) < 5 && Math.abs(startingY - evt.clientY) < 5) {
set(evt);
}
}
document.addEventListener("mousedown", onMouseDown);
document.addEventListener("click", onClick);
return () => {
document.removeEventListener("click", onClick);
document.removeEventListener("mousedown", onMouseDown);
};
},
);
}

const documentClick = mouseClickWithoutDragStore();
const documentKeyup = eventStore(document, "keyup", KeyboardEvent);

export { documentClick, documentKeyup };

0 comments on commit 2e1c3fa

Please sign in to comment.