Files
smeta-web/static/admin2/ui/drawer.js

43 lines
1.8 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { h } from '/static/admin2/vendor/preact.module.js';
import { useEffect, useRef } from '/static/admin2/vendor/hooks.module.js';
import htm from '/static/admin2/vendor/htm.module.js';
const html = htm.bind(h);
const FOCUSABLE = 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
export const Drawer = ({ title, onClose, children }) => {
const ref = useRef(null);
useEffect(() => {
const prev = document.activeElement;
const root = ref.current;
const box = root && root.querySelector('.drawer');
if (box) {
const first = box.querySelector(FOCUSABLE);
if (first) first.focus();
}
const onKey = (e) => {
if (e.key === 'Escape') { onClose(); return; }
if (e.key !== 'Tab' || !box) return;
const items = [...box.querySelectorAll(FOCUSABLE)].filter((el) => el.offsetParent !== null);
if (!items.length) return;
const first = items[0], last = items[items.length - 1];
if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
};
document.addEventListener('keydown', onKey);
return () => {
document.removeEventListener('keydown', onKey);
if (prev && prev.focus) prev.focus();
};
}, [onClose]);
return html`
<div class="overlay" ref=${ref} onClick=${onClose}>
<aside class="drawer" role="dialog" aria-modal="true" aria-label=${title}
onClick=${(e) => e.stopPropagation()}>
<header class="drawer-head"><h2>${title}</h2>
<button type="button" class="drawer-close" onClick=${onClose} aria-label="Закрыть">×</button></header>
${children}
</aside>
</div>`;
};