Skip to content

A games launcher for GOG, Amazon and Epic Games for Linux, Windows and macOS.

15.0 KB
Raw Blame
/*
 * DOM focus helpers for gamepad navigation. Settings and tab panels are
 * vertical forms, so the gamepad walks focus in DOM order instead of relying
 * on spatial navigation, which prefers nearby columns.
 */

export const GAMEPAD_SKIP_ATTR = 'data-gamepad-skip'
export const GAMEPAD_TAB_EVENT = 'gamepad-tab'
export const GAMEPAD_TABLIST_EVENT = 'gamepad-tablist-changed'

const CONTROL_SELECTOR =
  'a[href], button:not([disabled]), input:not([disabled]), ' +
  'select:not([disabled]), textarea:not([disabled]), ' +
  '[tabindex]:not([tabindex="-1"]), .MuiSelect-select'

/*
 * MUI's Dialog puts `role="dialog"` on the paper and never sets `aria-modal`,
 * and it can also focus the portal root, so `.MuiDialog-root` is needed too.
 * The hand-rolled modals (login, console overlay) mark themselves with
 * `aria-modal="true"`. Keep every modal check on this one selector.
 */
export const MODAL_SELECTOR =
  '.MuiDialog-root, [role="dialog"], [aria-modal="true"]'

function isGamepadFocusable(element: HTMLElement): boolean {
  if (element.closest(`[${GAMEPAD_SKIP_ATTR}]`)) return false
  if (element.hasAttribute('disabled')) return false
  if (element.getAttribute('aria-disabled') === 'true') return false
  if (element.hidden || element.getClientRects().length === 0) return false

  return element.tabIndex >= 0 || element.classList.contains('MuiSelect-select')
}

export function getFocusableControls(scope: HTMLElement): HTMLElement[] {
  return Array.from(
    scope.querySelectorAll<HTMLElement>(CONTROL_SELECTOR)
  ).filter(isGamepadFocusable)
}

export function getActiveSettingsScope(): HTMLElement | null {
  const modal =
    document.querySelector<HTMLElement>('.settingsDialogContent') ??
    document.querySelector<HTMLElement>('.InstallModal__content')
  const pane =
    modal && modal.getClientRects().length > 0
      ? modal
      : document.querySelector<HTMLElement>('.settingsPane')
  if (!pane) return null

  // Games settings can nest tab panels; the last visible one is the active
  // panel in DOM order.
  const panels = Array.from(
    pane.querySelectorAll<HTMLElement>('[role="tabpanel"]')
  ).filter((panel) => !panel.hidden && panel.getClientRects().length > 0)

  return panels.at(-1) ?? pane
}

export function clearGamepadRowFocus() {
  document
    .querySelectorAll('.SettingRow.gamepad-focus')
    .forEach((row) => row.classList.remove('gamepad-focus'))
  document
    .querySelectorAll('[data-gamepad-focused]')
    .forEach((element) => element.removeAttribute('data-gamepad-focused'))
  document
    .querySelectorAll('[data-gamepad-tab-focused]')
    .forEach((element) => element.removeAttribute('data-gamepad-tab-focused'))
}

function focusControl(element: HTMLElement) {
  clearGamepadRowFocus()
  element.focus()
  element.setAttribute('data-gamepad-focused', 'true')

  const row = element.closest<HTMLElement>('.SettingRow')
  if (row) row.classList.add('gamepad-focus')

  element.addEventListener(
    'focusout',
    () => {
      element.removeAttribute('data-gamepad-focused')
      row?.classList.remove('gamepad-focus')
    },
    { once: true }
  )
}

export function focusTabControl(tab: HTMLElement) {
  clearGamepadRowFocus()
  tab.focus()
  tab.setAttribute('data-gamepad-tab-focused', 'true')
  tab.addEventListener(
    'focusout',
    () => tab.removeAttribute('data-gamepad-tab-focused'),
    { once: true }
  )
}

export function focusFirstControlIn(
  scope: HTMLElement,
  preferToggle = true
): boolean {
  const controls = getFocusableControls(scope)
  if (!controls.length) return false

  const target =
    (preferToggle &&
      controls.find(
        (element) =>
          element.classList.contains('ToggleSwitch__input') ||
          !!element.closest('.ToggleSwitch')
      )) ||
    controls[0]

  focusControl(target)
  return true
}

export function focusFirstSettingsControl(): boolean {
  const scope = getActiveSettingsScope()
  return scope ? focusFirstControlIn(scope) : false
}

export function moveSettingsFocus(direction: 1 | -1): boolean {
  const scope = getActiveSettingsScope()
  if (!scope) return false

  const controls = getFocusableControls(scope)
  const current = controls.indexOf(document.activeElement as HTMLElement)

  // Empty search: Down enters the active panel. Other out-of-scope focus
  // (nav/tab bar) keeps spatial navigation.
  if (current === -1) {
    const active = document.activeElement as HTMLElement | null
    const emptySearch =
      active?.tagName === 'INPUT' &&
      !!active.closest('.settingsSearchRow') &&
      (active as HTMLInputElement).value === ''

    if (direction === 1 && emptySearch) {
      return focusFirstControlIn(scope)
    }
    return false
  }

  const next = controls[current + direction]
  if (!next) return false

  focusControl(next)
  return true
}

/**
 * Focus order step for a control the settings walk cannot reach. Sliders keep
 * the arrow keys for their value, so a slider outside the settings (the
 * Discounts price and rating filters) can only be left by walking the focus
 * order. That walk stays inside the settings pane whenever the pane owns the
 * focus, so a settings slider never jumps to the page behind it.
 */
export function moveFocusSequentially(direction: 1 | -1): boolean {
  const active = document.activeElement as HTMLElement | null
  const settingsScope = getActiveSettingsScope()
  const scope =
    settingsScope && active && settingsScope.contains(active)
      ? settingsScope
      : document.body

  const controls = getFocusableControls(scope)
  const current = active ? controls.indexOf(active) : -1
  if (current === -1) return false

  const next = controls[current + direction]
  if (!next) return false

  focusControl(next)
  return true
}

function isTextEditingControl(element: HTMLElement | null): boolean {
  if (!element) return false

  if (element.tagName === 'TEXTAREA') return true
  if (element.tagName !== 'INPUT') return false

  const type = (element as HTMLInputElement).type
  return !['checkbox', 'radio', 'button', 'submit', 'reset'].includes(type)
}

function isEditingControl(element: HTMLElement | null): boolean {
  if (!element) return false
  if (element.closest('[contenteditable="true"]')) return true
  if (element.tagName === 'TEXTAREA' || element.tagName === 'SELECT')
    return true
  return isTextEditingControl(element)
}

export function moveSettingsFocusHorizontal(direction: 1 | -1): boolean {
  const active = document.activeElement as HTMLElement | null
  const row = active?.closest<HTMLElement>('.SettingRow')
  if (!row || isTextEditingControl(active)) return false

  const controls = getFocusableControls(row)
  const current = controls.indexOf(active as HTMLElement)
  if (current === -1) return false

  const next = controls[current + direction]
  if (!next) return false

  focusControl(next)
  return true
}

export function getVisibleTabButtons(tablist: HTMLElement): HTMLElement[] {
  return Array.from(
    tablist.querySelectorAll<HTMLElement>('[role="tab"]')
  ).filter(
    (tab) =>
      !tab.hasAttribute('disabled') &&
      tab.getAttribute('aria-disabled') !== 'true' &&
      tab.getClientRects().length > 0
  )
}

const isGamepadTabList = (list: HTMLElement) =>
  list.dataset.gamepadTabs === 'true'

let lastGamepadTabList: HTMLElement | null = null

const isValidGamepadTabList = (list: HTMLElement | null): list is HTMLElement =>
  !!list &&
  list.isConnected &&
  isGamepadTabList(list) &&
  list.getClientRects().length > 0 &&
  getVisibleTabButtons(list).length > 1

function getControllingTabList(panel: HTMLElement): HTMLElement | null {
  if (!panel.id) return null

  const pane = panel.closest<HTMLElement>(
    '.settingsPane, .settingsDialogContent'
  )
  const controllingTabs = Array.from(
    document.querySelectorAll<HTMLElement>('[role="tab"]')
  ).filter((tab) => tab.getAttribute('aria-controls') === panel.id)

  // The narrow settings sidebar and the inner GamesSettings tabs can share the
  // same legacy ids. Prefer the tablist living in the panel's own pane.
  const controllingTab =
    controllingTabs.find((tab) => {
      const list = tab.closest<HTMLElement>('[role="tablist"]')
      return (
        pane &&
        list?.closest<HTMLElement>('.settingsPane, .settingsDialogContent') ===
          pane
      )
    }) ?? controllingTabs[0]

  return controllingTab?.closest<HTMLElement>('[role="tablist"]') ?? null
}

function resolveTabListForTarget(
  target: HTMLElement | null
): HTMLElement | null {
  if (!target) return null

  const focusedList = target.closest<HTMLElement>('[role="tablist"]')
  if (focusedList) return focusedList

  const panel = target.closest<HTMLElement>('[role="tabpanel"]')
  return panel ? getControllingTabList(panel) : null
}

export function rememberGamepadTabListForFocus(target: HTMLElement | null) {
  if (!target) return

  const modal = target.closest<HTMLElement>(MODAL_SELECTOR)
  if (modal && (!lastGamepadTabList || !modal.contains(lastGamepadTabList))) {
    // A different modal took focus: never carry the previous tablist across.
    lastGamepadTabList = null
  }

  const list = resolveTabListForTarget(target)
  if (isValidGamepadTabList(list)) {
    lastGamepadTabList = list
  }
}

export function forgetGamepadTabList(list: HTMLElement | null) {
  if (!list || lastGamepadTabList === list) lastGamepadTabList = null
}

export function getPreferredTabList(): HTMLElement | null {
  const active = document.activeElement as HTMLElement | null
  if (isEditingControl(active)) return null

  const fromFocus = resolveTabListForTarget(active)

  if (fromFocus) {
    if (isValidGamepadTabList(fromFocus)) {
      lastGamepadTabList = fromFocus
      return fromFocus
    }

    // Focus is inside a tablist or panel that is not opted in, so it must not
    // fall back to a different tablist elsewhere on the page.
    return null
  }

  const activeModal = active?.closest<HTMLElement>(MODAL_SELECTOR)

  // A modal that does not own the remembered tablist breaks the chain.
  if (
    activeModal &&
    lastGamepadTabList &&
    !activeModal.contains(lastGamepadTabList)
  ) {
    lastGamepadTabList = null
    return null
  }

  // No focus in a tablist or panel: only the last one that had focus may
  // respond. Without history (or if it disappeared) this is a no-op.
  if (isValidGamepadTabList(lastGamepadTabList)) return lastGamepadTabList

  return null
}

export function hasSwitchableTablist(): boolean {
  return getPreferredTabList() !== null
}

export function isTabSwitchingBlocked(): boolean {
  if (typeof window === 'undefined') return true
  if (window.location.hash.startsWith('#/console')) return true
  if (document.body.classList.contains('console-launching')) return true
  if (document.body.classList.contains('console-modal-open')) return true
  return !!document.querySelector('.consoleLaunchOverlay')
}

export function scrollTabPanelToTop(tab: HTMLElement) {
  const panelId = tab.getAttribute('aria-controls')
  const panel = panelId ? document.getElementById(panelId) : null
  if (!panel) return

  panel.scrollTop = 0

  let parent = panel.parentElement
  while (parent) {
    const overflow = getComputedStyle(parent).overflowY
    if (
      (overflow === 'auto' || overflow === 'scroll') &&
      parent.scrollHeight > parent.clientHeight
    ) {
      parent.scrollTop = 0
      return
    }
    parent = parent.parentElement
  }

  // The settings page itself scrolls the document rather than a pane.
  if (panel.closest('.Settings')) {
    window.scrollTo({ top: 0 })
  }
}

export function canContinueSettingsFocusRetry(
  requireBody: boolean,
  active: HTMLElement | null,
  gamepadActive: boolean
): boolean {
  const bodyFocused =
    !active ||
    active === document.body ||
    active === document.documentElement ||
    active.id === 'app'

  if (bodyFocused) {
    return requireBody || gamepadActive
  }

  if (requireBody) return false

  // A normal gamepad route change can leave focus on the section nav. Search
  // and controls must stop the retry instead of being pulled into the pane.
  return gamepadActive && !!active?.closest('.settingsNav')
}

export function retrySettingsFocus(
  focus: () => boolean,
  canContinue: () => boolean,
  {
    maxRetries = 40,
    retryMs = 50
  }: { maxRetries?: number; retryMs?: number } = {}
): () => void {
  let cancelled = false
  let timer: ReturnType<typeof setTimeout> | undefined

  const attempt = (retry: number) => {
    if (cancelled || !canContinue()) return
    if (focus()) return
    if (retry >= maxRetries) return

    timer = setTimeout(() => attempt(retry + 1), retryMs)
  }

  attempt(0)
  return () => {
    cancelled = true
    if (timer !== undefined) clearTimeout(timer)
  }
}

/**
 * Decides whether the Settings screen should move focus on a gamepad entry.
 * A real controller action (body.gamepad-active) lets the next entry refocus
 * even after a keyboard/mouse takeover; only the bare connected-controller
 * path respects the takeover. There is no resume on the takeover itself.
 */
export function shouldEnterSettingsGamepadFocus({
  gamepadActive,
  gamepadConnected,
  bodyFocused,
  userTookOver
}: {
  gamepadActive: boolean
  gamepadConnected: boolean
  bodyFocused: boolean
  userTookOver: boolean
}): boolean {
  if (gamepadActive) return true
  return !userTookOver && gamepadConnected && bodyFocused
}

/**
 * Runs the Settings gamepad entry: decides whether to focus, lets a real
 * controller action clear an earlier takeover, and retries while the pane
 * mounts. Returns the cancel handle, or null when this event is not an entry.
 * `beforeRetry` runs after the takeover is cleared and before the retry
 * starts, so the screen can cancel a previous retry and paint the ring class.
 */
export function beginSettingsGamepadFocus({
  gamepadActive,
  gamepadConnected,
  bodyFocused,
  userTookOver,
  clearTakeOver,
  isTakenOver,
  focusFirst,
  getActiveElement,
  isGamepadActive,
  beforeRetry,
  maxRetries,
  retryMs
}: {
  gamepadActive: boolean
  gamepadConnected: boolean
  bodyFocused: boolean
  userTookOver: boolean
  clearTakeOver: () => void
  isTakenOver: () => boolean
  focusFirst: () => boolean
  getActiveElement: () => HTMLElement | null
  isGamepadActive: () => boolean
  beforeRetry?: () => void
  maxRetries?: number
  retryMs?: number
}): (() => void) | null {
  if (
    !shouldEnterSettingsGamepadFocus({
      gamepadActive,
      gamepadConnected,
      bodyFocused,
      userTookOver
    })
  ) {
    return null
  }

  // A real controller action takes the wheel back from an earlier
  // keyboard/mouse takeover, so the retry below must not stop on the stale
  // flag.
  if (gamepadActive) clearTakeOver()

  beforeRetry?.()

  const requireBody = !gamepadActive
  return retrySettingsFocus(
    focusFirst,
    () =>
      !isTakenOver() &&
      canContinueSettingsFocusRetry(
        requireBody,
        getActiveElement(),
        isGamepadActive()
      ),
    { maxRetries, retryMs }
  )
}

/**
 * A pointer input always means the user took over. Keyboard input only counts
 * when the gamepad mode is already off, because gamepad actions replay
 * synthetic keys.
 */
export function isSettingsFocusTakeover(
  source: 'pointer' | 'keyboard',
  gamepadActive: boolean
): boolean {
  return source === 'pointer' || !gamepadActive
}