anki/ts/sveltelib/event-store.ts
Hikaru Y e35a938368
Prevent MathJax editor from closing unexpectedly when selecting text (#2484)
* Prevent MathJax editor from closing unexpectedly when selecting text

* Revert "Prevent MathJax editor from closing unexpectedly when selecting text"

This reverts commit b43d33a6de36d0af38933c6dae8bdd635294effd.

* Prevent floating/overlay element from closing when selecting text

Apply suggestions from code review.

Use a 'mousedown' event instead of a 'click' event so that releasing
the mouse button at the end of a text selection operation when the
pointer is outside a floating/overlay element does not close it.

Co-authored-by: Damien Elmes <dae@users.noreply.github.com>

---------

Co-authored-by: Damien Elmes <dae@users.noreply.github.com>
2023-04-28 11:39:50 +10:00

41 lines
1.4 KiB
TypeScript

// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import type { EventTargetToMap } from "@tslib/events";
import { on } from "@tslib/events";
import type { Callback } from "@tslib/typing";
import type { Readable, Subscriber } from "svelte/store";
import { readable } from "svelte/store";
type Init<T> = { new(type: string): T; prototype: T };
/**
* A store wrapping an event. Automatically adds/removes event handler upon
* first/last subscriber.
*
* @remarks
* Should probably always be used in conjunction with `subscribeToUpdates`.
*/
function eventStore<T extends EventTarget, K extends keyof EventTargetToMap<T>>(
target: T,
eventType: Exclude<K, symbol | number>,
/**
* Store needs an initial value. This should probably be a freshly
* constructed event, e.g. `new MouseEvent("click")`.
*/
constructor: Init<EventTargetToMap<T>[K]>,
): Readable<EventTargetToMap<T>[K]> {
const initEvent = new constructor(eventType);
return readable(
initEvent,
(set: Subscriber<EventTargetToMap<T>[K]>): Callback => on(target, eventType, set),
);
}
export default eventStore;
const documentMouseDown = eventStore(document, "mousedown", MouseEvent);
const documentKeyup = eventStore(document, "keyup", KeyboardEvent);
export { documentKeyup, documentMouseDown };