Skip to content

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

6.2 KB
Raw Blame
import {
  useCallback,
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
  type RefObject
} from 'react'

import { isControllerNavDisabled } from 'frontend/helpers/gamepad'
import { detectControllerLayout, type ControllerLayout } from './controller'

function isPressed(btn: GamepadButton | undefined) {
  return !!btn && (btn.pressed || btn.value > 0.5)
}

// Same gate the global gamepad helper applies: ignore input while the window
// is in the background (e.g. a game is running) or the user disabled it.
function gamepadInputEnabled() {
  return !isControllerNavDisabled() && document.hasFocus()
}

export function useGamepadButtonPress(
  buttonIndex: number,
  onPress: () => void,
  enabled = true
) {
  const handlerRef = useRef(onPress)
  handlerRef.current = onPress

  useEffect(() => {
    if (!enabled) return
    const prev = new Map<number, boolean>()
    // Seed with current state so a button still held from the press that
    // mounted this hook (e.g. the A press that opened an overlay) does not
    // immediately fire the new handler — only real press-down edges should.
    for (const gp of navigator.getGamepads()) {
      if (gp) prev.set(gp.index, isPressed(gp.buttons[buttonIndex]))
    }
    let raf = 0
    const tick = () => {
      const inputEnabled = gamepadInputEnabled()
      for (const gp of navigator.getGamepads()) {
        if (!gp) continue
        const pressed = isPressed(gp.buttons[buttonIndex])
        if (pressed && !prev.get(gp.index) && inputEnabled) handlerRef.current()
        prev.set(gp.index, pressed)
      }
      raf = requestAnimationFrame(tick)
    }
    raf = requestAnimationFrame(tick)
    return () => cancelAnimationFrame(raf)
  }, [buttonIndex, enabled])
}

export function useGamepadButtonHold(
  buttonIndex: number,
  onChange: (held: boolean) => void,
  enabled = true
) {
  const handlerRef = useRef(onChange)
  handlerRef.current = onChange

  useEffect(() => {
    if (!enabled) return
    let held = Array.from(navigator.getGamepads()).some(
      (gp) => gp && isPressed(gp.buttons[buttonIndex])
    )
    let raf = 0
    const tick = () => {
      // Disabled controllers report nothing held
      let anyHeld = false
      if (gamepadInputEnabled()) {
        for (const gp of navigator.getGamepads()) {
          if (gp && isPressed(gp.buttons[buttonIndex])) {
            anyHeld = true
            break
          }
        }
      }
      if (anyHeld !== held) {
        held = anyHeld
        handlerRef.current(anyHeld)
      }
      raf = requestAnimationFrame(tick)
    }
    raf = requestAnimationFrame(tick)
    return () => cancelAnimationFrame(raf)
  }, [buttonIndex, enabled])
}

export function useGamepadComboHold(
  buttonIndices: number[],
  onChange: (held: boolean) => void,
  enabled = true,
  // Live guard, checked every tick
  isBlocked: () => boolean = isControllerNavDisabled
) {
  const handlerRef = useRef(onChange)
  handlerRef.current = onChange

  // Stable key avoids re-running on rerenders
  const comboKey = buttonIndices.join(',')

  useEffect(() => {
    if (!enabled) return
    const indices = comboKey.split(',').map(Number)
    const comboPressed = (gp: Gamepad) =>
      indices.every((i) => isPressed(gp.buttons[i]))
    // Blocked controllers report nothing held
    const anyComboHeld = () =>
      !isBlocked() &&
      Array.from(navigator.getGamepads()).some((gp) => gp && comboPressed(gp))
    let held = anyComboHeld()
    let raf = 0
    const tick = () => {
      const anyHeld = anyComboHeld()
      if (anyHeld !== held) {
        held = anyHeld
        handlerRef.current(anyHeld)
      }
      raf = requestAnimationFrame(tick)
    }
    raf = requestAnimationFrame(tick)
    return () => cancelAnimationFrame(raf)
  }, [comboKey, enabled, isBlocked])
}

// One-off check outside hook ticks
export function isGamepadButtonHeld(buttonIndex: number) {
  if (isControllerNavDisabled()) return false
  return Array.from(navigator.getGamepads()).some(
    (gp) => gp && isPressed(gp.buttons[buttonIndex])
  )
}

export function useGamepadInfo() {
  const [connected, setConnected] = useState(false)
  const [layout, setLayout] = useState<ControllerLayout>('xbox')

  useEffect(() => {
    const refresh = () => {
      const first = Array.from(navigator.getGamepads()).find(
        (gp): gp is Gamepad => !!gp
      )
      setConnected(!!first)
      if (first) setLayout(detectControllerLayout(first.id))
    }
    refresh()
    window.addEventListener('gamepadconnected', refresh)
    window.addEventListener('gamepaddisconnected', refresh)
    return () => {
      window.removeEventListener('gamepadconnected', refresh)
      window.removeEventListener('gamepaddisconnected', refresh)
    }
  }, [])

  return { connected, layout }
}

export function useColumnCount(
  cardRefs: RefObject<Array<HTMLElement | null>>,
  cardsLength: number
) {
  const [columns, setColumns] = useState(1)

  useLayoutEffect(() => {
    const compute = () => {
      const cards = (cardRefs.current ?? []).filter(
        (el): el is HTMLElement => !!el
      )

      if (cards.length < 2) {
        setColumns(1)
        return
      }
      const firstTop = cards[0].offsetTop

      let count = 1
      for (let i = 1; i < cards.length; i++) {
        if (cards[i].offsetTop !== firstTop) break
        count++
      }
      setColumns(Math.max(1, count))
    }
    compute()
    window.addEventListener('resize', compute)
    return () => window.removeEventListener('resize', compute)
  }, [cardRefs, cardsLength])

  return columns
}

export function useCancelOnHold({
  active,
  holdMs,
  onCancel
}: {
  active: boolean
  holdMs: number
  onCancel: () => void
}) {
  const [holdStart, setHoldStart] = useState<number | null>(null)
  const onCancelRef = useRef(onCancel)
  onCancelRef.current = onCancel

  const startHold = useCallback(() => {
    setHoldStart((v) => v ?? Date.now())
  }, [])
  const stopHold = useCallback(() => setHoldStart(null), [])

  useEffect(() => {
    if (!active) setHoldStart(null)
  }, [active])

  useEffect(() => {
    if (holdStart == null || !active) return
    const t = window.setTimeout(() => {
      onCancelRef.current()
      setHoldStart(null)
    }, holdMs)
    return () => window.clearTimeout(t)
  }, [holdStart, active, holdMs])

  return { holdStart, startHold, stopHold }
}