Files
stpweb/vue/src/js/useOverlayStack.js
T
adamf 3da49f4b24
Test and deploy / test (push) Successful in 1m39s
Test and deploy / deploy (push) Successful in 26s
Refactor frontend overlays
2026-10-15 12:40:56 +01:00

43 lines
1021 B
JavaScript

import { onUnmounted, watch } from "vue";
const entries = [];
let listening = false;
function onKeydown(event) {
if (event.key !== "Escape") return;
entries.at(-1)?.close();
}
function updateListener() {
if (entries.length && !listening) {
window.addEventListener("keydown", onKeydown);
listening = true;
} else if (!entries.length && listening) {
window.removeEventListener("keydown", onKeydown);
listening = false;
}
}
/** Registers one open overlay so Escape always closes only the topmost one. */
export function useOverlayStack(open, close) {
let entry = null;
function register() {
if (entry) return;
entry = { close };
entries.push(entry);
updateListener();
}
function unregister() {
if (!entry) return;
const index = entries.indexOf(entry);
if (index !== -1) entries.splice(index, 1);
entry = null;
updateListener();
}
watch(open, (isOpen) => (isOpen ? register() : unregister()), { immediate: true });
onUnmounted(unregister);
}