focus-visible.js 940 B

123456789101112131415161718192021222324252627
  1. const listeners = new WeakMap();
  2. export function observe(el) {
  3. const keys = ['Tab', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Home', 'End', 'PageDown', 'PageUp'];
  4. const is = (event) => {
  5. if (keys.includes(event.key)) {
  6. el.classList.add('focus-visible');
  7. }
  8. };
  9. const isNot = () => el.classList.remove('focus-visible');
  10. listeners.set(el, { is, isNot });
  11. el.addEventListener('keydown', is);
  12. el.addEventListener('keyup', is);
  13. el.addEventListener('mousedown', isNot);
  14. el.addEventListener('mousedown', isNot);
  15. }
  16. export function unobserve(el) {
  17. const { is, isNot } = listeners.get(el);
  18. el.classList.remove('focus-visible');
  19. el.removeEventListener('keydown', is);
  20. el.removeEventListener('keyup', is);
  21. el.removeEventListener('mousedown', isNot);
  22. el.removeEventListener('mousedown', isNot);
  23. }
  24. export const focusVisible = {
  25. observe,
  26. unobserve
  27. };