packages/js-toolkit/utils/focusTrap.js
/**
 * Trap tab navigation inside the given element.
 * @param {HTMLElement} element The element in which to trap the tabulations.
 * @param {KeyboardEvent} event The keydown or keyup event.
 */
Trap tab navigation inside the given element.
@param {HTMLElement} element The element in which to trap the tabulations.
@param {KeyboardEvent} event The keydown or keyup event.
Trap tab navigation inside the given element . @param { HTMLElement } element The element in which to trap the tabulations . @param { KeyboardEvent } event The keydown or keyup event .
function trap(element, event) {
  if (event.keyCode !== keyCodes.TAB) {
    return;
  }
  if (!focusedBefore) {
    focusedBefore = document.activeElement;
  }
  const focusableChildren = Array.from(element.querySelectorAll(FOCUSABLE_ELEMENTS.join(', ')));
  const focusedItemIndex =
    document.activeElement instanceof HTMLElement
      ? focusableChildren.indexOf(document.activeElement)
      : -1;
  if (!focusableChildren.length) {
    return;
  }
  if (focusedItemIndex < 0) {
    focusableChildren[0].focus();
    event.preventDefault();
  }
  if (event.shiftKey && focusedItemIndex === 0) {
    focusableChildren[focusableChildren.length - 1].focus();
    event.preventDefault();
  }
  else if (!event.shiftKey && focusedItemIndex === focusableChildren.length - 1) {
    focusableChildren[0].focus();
    event.preventDefault();
  }
}
function trap ( element , event ) { if ( event . keyCode !== keyCodes . TAB ) { return ; } if ( ! focusedBefore ) { focusedBefore = document . activeElement ; } const focusableChildren = Array . from ( element . querySelectorAll ( FOCUSABLE_ELEMENTS . join ( ', ' ) ) ) ; const focusedItemIndex = document . activeElement instanceof HTMLElement ? focusableChildren . indexOf ( document . activeElement ) : - 1 ; if ( ! focusableChildren . length ) { return ; } if ( focusedItemIndex < 0 ) { focusableChildren [ 0 ] . focus ( ) ; event . preventDefault ( ) ; } if ( event . shiftKey && focusedItemIndex === 0 ) { focusableChildren [ focusableChildren . length - 1 ] . focus ( ) ; event . preventDefault ( ) ; } else if ( ! event . shiftKey && focusedItemIndex === focusableChildren . length - 1 ) { focusableChildren [ 0 ] . focus ( ) ; event . preventDefault ( ) ; } }
Trap tab navigation inside the given element.
Trap tab navigation inside the given element .
// Save the previous focused element /** @type {Array<HTMLElement>} */ // If the SHIFT key is being pressed while tabbing (moving backwards) and // the currently focused item is the first one, move the focus to the last // focusable item from the dialog element // If the SHIFT key is not being pressed (moving forwards) and the currently // focused item is the last one, move the focus to the first focusable item // from the dialog element