Files

19 lines
552 B
TypeScript
Raw Permalink Normal View History

import type { Ref } from "vue";
/** Calls `handler` on Escape while `active` is true. */
export function useEscapeKey(active: Ref<boolean>, handler: () => void) {
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") handler();
};
watch(
active,
(on) => {
if (!import.meta.client) return;
if (on) document.addEventListener("keydown", onKey);
else document.removeEventListener("keydown", onKey);
},
{ immediate: true },
);
onBeforeUnmount(() => document.removeEventListener("keydown", onKey));
}