Add reusable content sets publication previews and focused input handling
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
type Menu = { element: HTMLElement; close: () => void; order: number; previous?: HTMLElement };
|
||||
const menus = new Set<Menu>();
|
||||
let order = 0;
|
||||
function visible(menu: Menu) {
|
||||
return menu.element.isConnected && !menu.element.closest('[hidden]') &&
|
||||
!menu.element.matches('dialog:not([open])') && menu.element.getClientRects().length > 0;
|
||||
}
|
||||
export function hasOpenMenu() { return [...menus].some(visible); }
|
||||
|
||||
// Menus use their own close operation, including inline editors and native dialogs.
|
||||
// Capture Escape before input fields or gameplay; close one focused layer only.
|
||||
document.addEventListener('keydown', event => {
|
||||
if (event.key !== 'Escape') return;
|
||||
const open = [...menus].filter(visible).sort((a, b) => b.order - a.order);
|
||||
const focused = open.filter(m => m.element.contains(document.activeElement));
|
||||
const menu = focused.find(m => !focused.some(other => other !== m && m.element.contains(other.element))) ?? open[0];
|
||||
if (!menu) return;
|
||||
event.preventDefault(); event.stopImmediatePropagation();
|
||||
if (!event.repeat) menu.close();
|
||||
}, true);
|
||||
|
||||
export function registerMenu(element: HTMLElement, close: () => void) {
|
||||
const menu: Menu = { element, close: () => { close(); if (!visible(menu) && menu.previous?.isConnected) menu.previous.focus({preventScroll:true}); }, order: ++order };
|
||||
const touch = () => { menu.order = ++order; };
|
||||
element.addEventListener('focusin', touch); element.addEventListener('pointerdown', touch);
|
||||
menus.add(menu);
|
||||
return {
|
||||
opened(previous = document.activeElement) {
|
||||
menu.previous = previous instanceof HTMLElement ? previous : undefined;
|
||||
touch(); element.tabIndex = -1;
|
||||
(element.querySelector<HTMLElement>('button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled])') ?? element).focus({preventScroll:true});
|
||||
},
|
||||
close: menu.close,
|
||||
dispose() { menus.delete(menu); element.removeEventListener('focusin', touch); element.removeEventListener('pointerdown', touch); }
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user