From 2e1c3fa3358317792af515ec82bc4dcaf762c5bc Mon Sep 17 00:00:00 2001 From: Damien Elmes Date: Mon, 1 May 2023 11:41:19 +1000 Subject: [PATCH] Avoid firing click event in floatables when user drags the mouse Alternative approach at fixing #2484 --- ts/sveltelib/event-store.ts | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/ts/sveltelib/event-store.ts b/ts/sveltelib/event-store.ts index 0930919f4..74e31d810 100644 --- a/ts/sveltelib/event-store.ts +++ b/ts/sveltelib/event-store.ts @@ -34,7 +34,40 @@ function eventStore>( 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 { + const initEvent = new MouseEvent("click"); + + return readable( + initEvent, + (set: Subscriber): 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 };