2022-03-02 05:21:19 +01:00
|
|
|
// Copyright: Ankitects Pty Ltd and contributors
|
|
|
|
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|
|
|
|
|
|
|
import type { Readable } from "svelte/store";
|
|
|
|
import { derived } from "svelte/store";
|
|
|
|
|
2022-09-05 09:20:00 +02:00
|
|
|
import type { EventPredicateResult } from "./event-predicate";
|
|
|
|
|
2022-03-02 05:21:19 +01:00
|
|
|
interface ClosingKeyupArgs {
|
|
|
|
/**
|
|
|
|
* Clicking on the reference element should not close.
|
|
|
|
* The reference should handle this itself.
|
|
|
|
*/
|
|
|
|
reference: Node;
|
|
|
|
floating: Node;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Returns a derived store, which translates `MouseEvent`s into a boolean
|
|
|
|
* indicating whether they constitue a click that should close `floating`.
|
|
|
|
*
|
|
|
|
* @param: Should be an event store wrapping document.click.
|
|
|
|
*/
|
|
|
|
function isClosingKeyup(
|
|
|
|
store: Readable<KeyboardEvent>,
|
|
|
|
_args: ClosingKeyupArgs,
|
2022-09-05 09:20:00 +02:00
|
|
|
): Readable<EventPredicateResult> {
|
2022-03-02 05:21:19 +01:00
|
|
|
// TODO there needs to be special treatment, whether the keyup happens
|
|
|
|
// inside the floating element or outside, but I'll defer until we actually
|
|
|
|
// use this for a popover with an input field
|
2022-09-05 09:20:00 +02:00
|
|
|
function shouldClose(event: KeyboardEvent): string | false {
|
2022-03-02 05:21:19 +01:00
|
|
|
if (event.key === "Tab") {
|
|
|
|
// Allow Tab navigation.
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2022-09-05 09:20:00 +02:00
|
|
|
return "keyup";
|
2022-03-02 05:21:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return derived(
|
|
|
|
store,
|
2022-09-05 09:20:00 +02:00
|
|
|
(event: KeyboardEvent, set: (value: EventPredicateResult) => void): void => {
|
|
|
|
const reason = shouldClose(event);
|
|
|
|
|
|
|
|
if (reason) {
|
|
|
|
set({ reason, originalEvent: event });
|
2022-03-02 05:21:19 +01:00
|
|
|
}
|
|
|
|
},
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
export default isClosingKeyup;
|