Skip to content

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

[Feat] Better gamepad navigation in the settings (#6213)

Flávio Fearnc8ea273f34ab
diff --git a/public/locales/en/translation.json b/public/locales/en/translation.json
index 61c7b9508..933be04bf 100644
--- a/public/locales/en/translation.json
+++ b/public/locales/en/translation.json
@@ -449,6 +449,8 @@
"search": "Search",
"select": "Select",
"space": "Space",
+ "switch_tab": "Switch tab",
+ "toggle": "Toggle",
"update_game": "Update game",
"url_bar": "URL bar"
}
@@ -1712,7 +1714,9 @@
"guide": "Console mode",
"main": "Confirm / select",
"nextPage": "Page down",
+ "nextTab": "Next tab",
"prevPage": "Page up",
+ "prevTab": "Previous tab",
"reset": "Reset to defaults",
"unbound": "Not bound"
},
diff --git a/src/common/types.ts b/src/common/types.ts
index f055faef2..cec46af54 100644
--- a/src/common/types.ts
+++ b/src/common/types.ts
@@ -712,6 +712,8 @@ export type RemappableGamepadAction =
| 'rightClick'
| 'prevPage'
| 'nextPage'
+ | 'prevTab'
+ | 'nextTab'
| 'enter'
| 'guide'
@@ -756,6 +758,8 @@ interface GamepadActionArgsWithoutMetadata {
| 'rightStickDown'
| 'rightStickLeft'
| 'rightStickRight'
+ | 'prevTab'
+ | 'nextTab'
| 'mainAction'
| 'back'
| 'altAction'
diff --git a/src/frontend/components/UI/ControllerHints/index.css b/src/frontend/components/UI/ControllerHints/index.css
index 11bbbdd80..87adfed16 100644
--- a/src/frontend/components/UI/ControllerHints/index.css
+++ b/src/frontend/components/UI/ControllerHints/index.css
@@ -162,3 +162,26 @@
.controller-hints .buttonImage.right-stick {
--imageUrl: var(--right-stick);
}
+
+/* Narrow bar: let the hints shrink and wrap instead of overflowing. The
+ d-pad block is already hidden when the tab hint is shown. */
+@media (max-width: 700px) {
+ .controller-hints {
+ flex-wrap: wrap;
+ justify-content: flex-start;
+ gap: var(--space-2xs-fixed) var(--space-xs-fixed);
+ overflow: visible;
+ }
+
+ .controller-hints .hint {
+ flex-basis: auto;
+ flex-shrink: 1;
+ min-width: 0;
+ white-space: normal;
+ }
+
+ .controller-hints .buttonImage {
+ width: 28px;
+ height: 28px;
+ }
+}
diff --git a/src/frontend/components/UI/ControllerHints/index.tsx b/src/frontend/components/UI/ControllerHints/index.tsx
index 8192fa7d5..e3e778d07 100644
--- a/src/frontend/components/UI/ControllerHints/index.tsx
+++ b/src/frontend/components/UI/ControllerHints/index.tsx
@@ -3,9 +3,14 @@ import { useTranslation } from 'react-i18next'
import { useLocation } from 'react-router-dom'
import ContextProvider from 'frontend/state/ContextProvider'
import {
+ detectGamepadLayout,
GAMEPAD_MAPPING_CHANGED_EVENT,
getMappedButton
} from 'frontend/helpers/gamepad'
+import {
+ GAMEPAD_TABLIST_EVENT,
+ hasSwitchableTablist
+} from 'frontend/helpers/settingsFocus'
import './index.css'
@@ -16,7 +21,9 @@ const readBoundButtons = () => ({
context: getMappedButton('rightClick'),
alt: getMappedButton('altAction'),
prev: getMappedButton('prevPage'),
- next: getMappedButton('nextPage')
+ next: getMappedButton('nextPage'),
+ prevTab: getMappedButton('prevTab'),
+ nextTab: getMappedButton('nextTab')
})
function ButtonGlyph({ index }: { index: number | null }) {
@@ -36,6 +43,7 @@ export default function ControllerHints() {
const [nextPageHint, setNextPageHint] = useState('') // R1 / RB
const [moveHint, setMoveHint] = useState('')
const [scrollHint, setScrollHint] = useState('')
+ const [hasTablist, setHasTablist] = useState(false)
const location = useLocation()
const { t } = useTranslation()
@@ -48,6 +56,15 @@ export default function ControllerHints() {
window.removeEventListener(GAMEPAD_MAPPING_CHANGED_EVENT, refresh)
}
}, [])
+
+ useEffect(() => {
+ const refresh = () => setHasTablist(hasSwitchableTablist())
+ refresh()
+ window.addEventListener(GAMEPAD_TABLIST_EVENT, refresh)
+ return () => {
+ window.removeEventListener(GAMEPAD_TABLIST_EVENT, refresh)
+ }
+ }, [])
const inWebview =
location.pathname.startsWith('/store/') ||
location.pathname.startsWith('/loginweb/') ||
@@ -88,6 +105,8 @@ export default function ControllerHints() {
main = t('controller.hints.game_details', 'Game details')
alt2 = t('controller.hints.install_game', 'Install game')
}
+ } else if (target.closest('.ToggleSwitch')) {
+ main = t('controller.hints.toggle', 'Toggle')
} else if (target.id === 'search') {
// focusing the search bar
main = t(
@@ -154,6 +173,7 @@ export default function ControllerHints() {
// must not be overridden by host focus changes (URL bar, sidebar, ...).
if (inWebview) return
const tgt = !e.target ? null : (e.target as HTMLElement)
+ setHasTablist(hasSwitchableTablist())
setHints(tgt)
}
@@ -175,6 +195,7 @@ export default function ControllerHints() {
if (inWebview) {
applyWebviewHints()
} else {
+ setHasTablist(hasSwitchableTablist())
setPrevPageHint('')
setNextPageHint('')
setMoveHint('')
@@ -206,6 +227,15 @@ export default function ControllerHints() {
return <></>
}
+ const cloneLayout = ['gamecube', 'ps3-clone', 'n64-clone', 'genius'].includes(
+ detectGamepadLayout(activeController)
+ )
+ const showTabHint =
+ !inWebview &&
+ !cloneLayout &&
+ hasTablist &&
+ (boundButtons.prevTab !== null || boundButtons.nextTab !== null)
+
return (
<div
className={`controller-hints ${layout}${inWebview ? ' in-webview' : ''}`}
@@ -250,13 +280,26 @@ export default function ControllerHints() {
)}
</>
)}
- <div className="hint">
- <i className="buttonImage d-pad" />
- <i className="buttonImage left-stick" />
- {inWebview
- ? moveHint || t('controller.hints.move_focus', 'Move focus')
- : t('controller.hints.move_cursor', 'Move cursor')}
- </div>
+ {showTabHint && (
+ <div className="hint">
+ {boundButtons.prevTab !== null && (
+ <ButtonGlyph index={boundButtons.prevTab} />
+ )}
+ {boundButtons.nextTab !== null && (
+ <ButtonGlyph index={boundButtons.nextTab} />
+ )}
+ {t('controller.hints.switch_tab', 'Switch tab')}
+ </div>
+ )}
+ {!showTabHint && (
+ <div className="hint">
+ <i className="buttonImage d-pad" />
+ <i className="buttonImage left-stick" />
+ {inWebview
+ ? moveHint || t('controller.hints.move_focus', 'Move focus')
+ : t('controller.hints.move_cursor', 'Move cursor')}
+ </div>
+ )}
<div className="hint">
<i className="buttonImage right-stick" />
{scrollHint || t('controller.hints.scroll', 'Scroll')}
diff --git a/src/frontend/components/UI/InfoTooltip/index.tsx b/src/frontend/components/UI/InfoTooltip/index.tsx
index bdce345ca..b7494af40 100644
--- a/src/frontend/components/UI/InfoTooltip/index.tsx
+++ b/src/frontend/components/UI/InfoTooltip/index.tsx
@@ -26,6 +26,7 @@ export default function InfoTooltip({
>
<span
className={classNames('InfoTooltip', className)}
+ data-gamepad-skip="true"
tabIndex={0}
role="note"
aria-label={label}
diff --git a/src/frontend/components/UI/SettingRow/index.css b/src/frontend/components/UI/SettingRow/index.css
index a3a078bdd..b172aa14c 100644
--- a/src/frontend/components/UI/SettingRow/index.css
+++ b/src/frontend/components/UI/SettingRow/index.css
@@ -1,3 +1,19 @@
+:root {
+ --gamepad-focus-ring: var(--accent, var(--navbar-accent));
+}
+
+/* Themes set --accent on the body; declare the ring there so Hexa and high
+ contrast keep their own accent. :root stays as a fallback. */
+body {
+ --gamepad-focus-ring: var(--accent, var(--navbar-accent));
+}
+
+/* The yellow accent loses contrast on the warm light theme. Use its dark
+ counterpart for the controller ring there. */
+body.heroicHexaLight {
+ --gamepad-focus-ring: var(--color-hexa-yellow-700, var(--accent));
+}
+
.SettingRow {
display: flex;
width: 100%;
@@ -79,3 +95,56 @@
.SettingRow--stacked > .SettingRow__control > .Button {
flex: 0 0 auto;
}
+
+/* Gamepad navigation paints the focused row and its control. The row class is
+ only added by the controller focus helpers, so keyboard focus keeps its own
+ ring without the accent tint. */
+body.gamepad-active .SettingRow.gamepad-focus {
+ border-radius: var(--radius-sm);
+ background-color: color-mix(
+ in oklab,
+ var(--accent, var(--navbar-accent)) 8%,
+ transparent
+ );
+}
+
+body.gamepad-active [data-gamepad-focused] {
+ outline: 3px solid var(--gamepad-focus-ring);
+ outline-offset: 2px;
+}
+
+body.gamepad-active
+ .SettingRow.gamepad-focus
+ .ToggleSwitch__input:focus
+ + .ToggleSwitch__track {
+ outline: 3px solid var(--gamepad-focus-ring);
+ outline-offset: 2px;
+}
+
+/* Shared by the Settings page and the eager settings modal: stack the manual
+ sync row when its container is narrow (the modal is narrower than the
+ viewport). */
+.settingsManualSyncRowContainer {
+ container-type: inline-size;
+ width: 100%;
+}
+
+@container (max-width: 600px) {
+ .SettingRow.settingsManualSyncRow {
+ flex-direction: column;
+ align-items: stretch;
+ gap: var(--space-xs);
+ }
+
+ .SettingRow.settingsManualSyncRow > .SettingRow__control {
+ width: 100%;
+ justify-content: flex-start;
+ flex-wrap: wrap;
+ }
+
+ .SettingRow.settingsManualSyncRow .SettingRow__description {
+ min-width: 0;
+ max-width: 100%;
+ overflow-wrap: anywhere;
+ }
+}
diff --git a/src/frontend/components/UI/Tabs/__tests__/Tabs.test.tsx b/src/frontend/components/UI/Tabs/__tests__/Tabs.test.tsx
index 74bf6f816..b25964d9a 100644
--- a/src/frontend/components/UI/Tabs/__tests__/Tabs.test.tsx
+++ b/src/frontend/components/UI/Tabs/__tests__/Tabs.test.tsx
@@ -1,8 +1,9 @@
/**
* @jest-environment jsdom
*/
-import { fireEvent, render, screen } from '@testing-library/react'
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import Tabs from '..'
+import { GAMEPAD_TAB_EVENT } from 'frontend/helpers/settingsFocus'
jest.mock('../index.css', () => ({}))
jest.mock('../../Icon/index.css', () => ({}))
@@ -13,6 +14,14 @@ const items = [
{ value: 'three', label: 'Three' }
]
+const rects = [{ width: 10, height: 10 }] as unknown as DOMRectList
+
+const dispatchTab = (direction: 1 | -1) => {
+ window.dispatchEvent(
+ new CustomEvent(GAMEPAD_TAB_EVENT, { detail: { direction } })
+ )
+}
+
describe('Tabs keyboard navigation', () => {
it('moves focus and activates with arrows in auto mode', () => {
const onChange = jest.fn()
@@ -87,3 +96,118 @@ describe('Tabs keyboard navigation', () => {
expect(document.activeElement).toBe(second)
})
})
+
+describe('Tabs gamepad navigation', () => {
+ beforeEach(() => {
+ jest.spyOn(HTMLElement.prototype, 'getClientRects').mockReturnValue(rects)
+ })
+
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
+ it('moves to the next and previous tab with wrap-around', () => {
+ const onChange = jest.fn()
+ const { rerender } = render(
+ <Tabs items={items} value="one" onChange={onChange} gamepadNavigation />
+ )
+
+ document.querySelector<HTMLElement>('[role="tab"]')?.focus()
+ act(() => dispatchTab(1))
+ expect(onChange).toHaveBeenLastCalledWith('two')
+
+ rerender(
+ <Tabs items={items} value="three" onChange={onChange} gamepadNavigation />
+ )
+ act(() => dispatchTab(1))
+ expect(onChange).toHaveBeenLastCalledWith('one')
+
+ rerender(
+ <Tabs items={items} value="one" onChange={onChange} gamepadNavigation />
+ )
+ act(() => dispatchTab(-1))
+ expect(onChange).toHaveBeenLastCalledWith('three')
+ })
+
+ it('does nothing by default without opting in', () => {
+ const onChange = jest.fn()
+ render(<Tabs items={items} value="one" onChange={onChange} />)
+
+ act(() => dispatchTab(1))
+
+ expect(onChange).not.toHaveBeenCalled()
+ })
+
+ it('does nothing while console launch is active', () => {
+ const onChange = jest.fn()
+ render(
+ <Tabs items={items} value="one" onChange={onChange} gamepadNavigation />
+ )
+ document.querySelector<HTMLElement>('[role="tab"]')?.focus()
+
+ document.body.classList.add('console-launching')
+ act(() => dispatchTab(1))
+ document.body.classList.remove('console-launching')
+
+ expect(onChange).not.toHaveBeenCalled()
+ })
+
+ it('does nothing when there is a single tab', () => {
+ const onChange = jest.fn()
+ render(
+ <Tabs
+ items={items.slice(0, 1)}
+ value="one"
+ onChange={onChange}
+ gamepadNavigation
+ />
+ )
+
+ document.querySelector<HTMLElement>('[role="tab"]')?.focus()
+ act(() => dispatchTab(1))
+
+ expect(onChange).not.toHaveBeenCalled()
+ })
+
+ it('moves focus and scrolls the new panel after switching', async () => {
+ const onChange = jest.fn()
+ render(
+ <>
+ <Tabs items={items} value="one" onChange={onChange} gamepadNavigation />
+ <div id="tabpanel-two" role="tabpanel">
+ <button id="panel-control">Panel control</button>
+ </div>
+ </>
+ )
+
+ const panel = document.getElementById('tabpanel-two')!
+ panel.scrollTop = 120
+ document.querySelector<HTMLElement>('[role="tab"]')?.focus()
+
+ act(() => dispatchTab(1))
+
+ await waitFor(() => {
+ expect(document.activeElement?.id).toBe('panel-control')
+ })
+ expect(panel.scrollTop).toBe(0)
+ })
+
+ it('ignores the event when another tablist is preferred', () => {
+ const onChange = jest.fn()
+ document.body.innerHTML = `
+ <div role="tablist" data-gamepad-tabs="true">
+ <button role="tab" aria-selected="true">Other one</button>
+ <button role="tab">Other two</button>
+ </div>
+ `
+
+ document.querySelector<HTMLElement>('[role="tab"]')?.focus()
+ render(
+ <Tabs items={items} value="one" onChange={onChange} gamepadNavigation />
+ )
+
+ act(() => dispatchTab(1))
+
+ expect(onChange).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/frontend/components/UI/Tabs/index.css b/src/frontend/components/UI/Tabs/index.css
index 53ae66052..9a938480d 100644
--- a/src/frontend/components/UI/Tabs/index.css
+++ b/src/frontend/components/UI/Tabs/index.css
@@ -46,3 +46,11 @@
font-weight: var(--semibold);
border-bottom-color: var(--selected, var(--navbar-accent, var(--accent)));
}
+
+/* Empty panels fall back to the tab itself, using the tab focus style rather
+ than the 3px control ring. */
+body.gamepad-active .Tabs__tab[data-gamepad-tab-focused] {
+ outline: 2px solid var(--gamepad-focus-ring, var(--accent));
+ outline-offset: -2px;
+ border-radius: 8px 8px 0 0;
+}
diff --git a/src/frontend/components/UI/Tabs/index.tsx b/src/frontend/components/UI/Tabs/index.tsx
index 1d718614f..aed805eed 100644
--- a/src/frontend/components/UI/Tabs/index.tsx
+++ b/src/frontend/components/UI/Tabs/index.tsx
@@ -1,7 +1,19 @@
-import { KeyboardEvent, useRef } from 'react'
+import { KeyboardEvent, useEffect, useRef } from 'react'
import type { LucideIcon } from 'lucide-react'
import classNames from 'classnames'
import Icon from '../Icon'
+import {
+ focusFirstControlIn,
+ focusTabControl,
+ forgetGamepadTabList,
+ GAMEPAD_TAB_EVENT,
+ GAMEPAD_TABLIST_EVENT,
+ getPreferredTabList,
+ isTabSwitchingBlocked,
+ getVisibleTabButtons,
+ rememberGamepadTabListForFocus,
+ scrollTabPanelToTop
+} from 'frontend/helpers/settingsFocus'
import './index.css'
export interface TabItem<T extends string> {
@@ -22,6 +34,9 @@ interface TabsProps<T extends string> {
idPrefix?: string
// `auto` activates a tab when arrowing to it; `manual` only moves focus.
activation?: TabActivation
+ // Opt in to L2/R2 tab switching. Off by default so existing tablists keep
+ // their current keyboard/mouse behaviour.
+ gamepadNavigation?: boolean
}
export default function Tabs<T extends string>({
@@ -31,9 +46,11 @@ export default function Tabs<T extends string>({
className,
idPrefix = 'tab',
activation = 'auto',
+ gamepadNavigation = false,
'aria-label': ariaLabel
}: TabsProps<T>) {
const tabsRef = useRef<Array<HTMLButtonElement | null>>([])
+ const rootRef = useRef<HTMLDivElement>(null)
const focusTab = (index: number) => {
const next = items[index]
@@ -80,10 +97,75 @@ export default function Tabs<T extends string>({
focusTab(next)
}
+ useEffect(() => {
+ if (!gamepadNavigation) return
+
+ window.dispatchEvent(new Event(GAMEPAD_TABLIST_EVENT))
+ return () => {
+ window.dispatchEvent(new Event(GAMEPAD_TABLIST_EVENT))
+ }
+ }, [items.length, gamepadNavigation])
+
+ useEffect(() => {
+ if (!gamepadNavigation) return
+
+ const root = rootRef.current
+ return () => forgetGamepadTabList(root)
+ }, [gamepadNavigation])
+
+ useEffect(() => {
+ if (!gamepadNavigation) return
+
+ const onFocusIn = (event: FocusEvent) => {
+ rememberGamepadTabListForFocus(event.target as HTMLElement)
+ }
+
+ document.addEventListener('focusin', onFocusIn, true)
+ return () => document.removeEventListener('focusin', onFocusIn, true)
+ }, [gamepadNavigation])
+
+ useEffect(() => {
+ if (!gamepadNavigation) return
+
+ const onGamepadTab = (event: Event) => {
+ const root = rootRef.current
+ if (!root || isTabSwitchingBlocked() || getPreferredTabList() !== root)
+ return
+
+ const buttons = getVisibleTabButtons(root)
+ if (buttons.length <= 1) return
+
+ const direction = (event as CustomEvent<{ direction: number }>).detail
+ ?.direction
+ if (direction !== 1 && direction !== -1) return
+
+ const current = buttons.findIndex(
+ (button) => button.getAttribute('aria-selected') === 'true'
+ )
+ const next =
+ buttons[(current + direction + buttons.length) % buttons.length]
+ if (!next) return
+
+ rememberGamepadTabListForFocus(root)
+ next.click()
+ requestAnimationFrame(() => {
+ const panelId = next.getAttribute('aria-controls')
+ const panel = panelId ? document.getElementById(panelId) : null
+ if (!panel || !focusFirstControlIn(panel)) focusTabControl(next)
+ scrollTabPanelToTop(next)
+ })
+ }
+
+ window.addEventListener(GAMEPAD_TAB_EVENT, onGamepadTab)
+ return () => window.removeEventListener(GAMEPAD_TAB_EVENT, onGamepadTab)
+ }, [gamepadNavigation])
+
return (
<div
+ ref={rootRef}
className={classNames('Tabs', 'scrollbar--none', className)}
role="tablist"
+ data-gamepad-tabs={gamepadNavigation ? 'true' : undefined}
aria-label={ariaLabel}
onKeyDown={onKeyDown}
>
diff --git a/src/frontend/helpers/__tests__/gamepadLayouts.test.ts b/src/frontend/helpers/__tests__/gamepadLayouts.test.ts
new file mode 100644
index 000000000..b540dd402
--- /dev/null
+++ b/src/frontend/helpers/__tests__/gamepadLayouts.test.ts
@@ -0,0 +1,54 @@
+import { ValidGamepadAction } from 'common/types'
+import { checkStandard } from '../gamepad_layouts/standard'
+import { DEFAULT_GAMEPAD_BUTTONS, getMappedButtonFrom } from '../gamepadMapping'
+
+const buttonsWith = (pressed: number[]) =>
+ Array.from(
+ { length: 17 },
+ (_, index) =>
+ ({
+ pressed: pressed.includes(index),
+ value: pressed.includes(index) ? 1 : 0
+ }) as GamepadButton
+ )
+
+const collect = (
+ pressed: number[],
+ overrides: Parameters<typeof checkStandard>[4] = {}
+) => {
+ const actions: ValidGamepadAction[] = []
+ checkStandard(
+ buttonsWith(pressed),
+ [],
+ 0,
+ (action, isPressed) => {
+ if (isPressed) actions.push(action)
+ },
+ overrides
+ )
+ return actions
+}
+
+describe('standard gamepad tab triggers', () => {
+ it('uses L2/R2 when there are no overrides', () => {
+ expect(collect([6])).toContain('prevTab')
+ expect(collect([7])).toContain('nextTab')
+ })
+
+ it('respects an explicit override', () => {
+ expect(collect([7], { prevTab: 7, nextTab: null })).toContain('prevTab')
+ expect(collect([6], { prevTab: null, nextTab: null })).not.toContain(
+ 'prevTab'
+ )
+ })
+})
+
+describe('gamepad tab mapping', () => {
+ it('defaults to L2/R2 and respects saved overrides', () => {
+ expect(DEFAULT_GAMEPAD_BUTTONS.prevTab).toBe(6)
+ expect(DEFAULT_GAMEPAD_BUTTONS.nextTab).toBe(7)
+ expect(getMappedButtonFrom({}, 'prevTab')).toBe(6)
+ expect(getMappedButtonFrom({ prevTab: 3 }, 'prevTab')).toBe(3)
+ expect(getMappedButtonFrom({ prevTab: null }, 'prevTab')).toBeNull()
+ })
+})
diff --git a/src/frontend/helpers/__tests__/settingsFocus.test.ts b/src/frontend/helpers/__tests__/settingsFocus.test.ts
new file mode 100644
index 000000000..1cb61eb6b
--- /dev/null
+++ b/src/frontend/helpers/__tests__/settingsFocus.test.ts
@@ -0,0 +1,650 @@
+/**
+ * @jest-environment jsdom
+ */
+import {
+ focusFirstControlIn,
+ focusFirstSettingsControl,
+ GAMEPAD_SKIP_ATTR,
+ getActiveSettingsScope,
+ getFocusableControls,
+ getPreferredTabList,
+ beginSettingsGamepadFocus,
+ canContinueSettingsFocusRetry,
+ hasSwitchableTablist,
+ isSettingsFocusTakeover,
+ isTabSwitchingBlocked,
+ retrySettingsFocus,
+ shouldEnterSettingsGamepadFocus,
+ moveSettingsFocus,
+ moveSettingsFocusHorizontal,
+ moveFocusSequentially,
+ rememberGamepadTabListForFocus,
+ scrollTabPanelToTop
+} from '../settingsFocus'
+
+const rects = [{ width: 10, height: 10 }] as unknown as DOMRectList
+
+const mockRects = () => {
+ jest.spyOn(HTMLElement.prototype, 'getClientRects').mockReturnValue(rects)
+}
+
+const buildSettings = () => {
+ document.body.innerHTML = `
+ <div class="settingsPane">
+ <div role="tablist" data-gamepad-tabs="true">
+ <button role="tab" aria-selected="false" aria-controls="tabpanel-wine">Wine</button>
+ <button role="tab" aria-selected="true" aria-controls="tabpanel-advanced">Advanced</button>
+ </div>
+ <div role="tabpanel" id="tabpanel-wine" hidden>
+ <div class="SettingRow"><div class="SettingRow__control">
+ <button id="hidden-button">Hidden</button>
+ </div></div>
+ </div>
+ <div role="tabpanel" id="tabpanel-advanced">
+ <div class="SettingRow" id="row-toggle">
+ <div class="SettingRow__text"><span class="SettingRow__label">Toggle</span></div>
+ <div class="SettingRow__control">
+ <span class="InfoTooltip" data-gamepad-skip="true" tabindex="0">i</span>
+ <span class="ToggleSwitch">
+ <input class="ToggleSwitch__input" id="toggle" type="checkbox" />
+ <label class="ToggleSwitch__track"></label>
+ </span>
+ </div>
+ </div>
+ <div class="SettingRow" id="row-buttons">
+ <div class="SettingRow__control">
+ <button id="first-button">First</button>
+ <button id="second-button">Second</button>
+ </div>
+ </div>
+ <button id="disabled" disabled>Disabled</button>
+ </div>
+ </div>
+ `
+}
+
+describe('settingsFocus', () => {
+ beforeEach(() => {
+ mockRects()
+ buildSettings()
+ })
+
+ afterEach(() => {
+ jest.restoreAllMocks()
+ document.body.innerHTML = ''
+ })
+
+ it('scopes focus to the active tabpanel and skips the info icon', () => {
+ const scope = getActiveSettingsScope()
+ expect(scope?.id).toBe('tabpanel-advanced')
+
+ const controls = getFocusableControls(scope!)
+ const ids = controls.map((element) => element.id)
+
+ expect(ids).toContain('toggle')
+ expect(ids).toContain('first-button')
+ expect(ids).not.toContain('hidden-button')
+ expect(ids).not.toContain('disabled')
+ expect(
+ controls.some((element) => element.matches(`[${GAMEPAD_SKIP_ATTR}]`))
+ ).toBe(false)
+ })
+
+ it('focuses the first toggle before other controls', () => {
+ expect(focusFirstSettingsControl()).toBe(true)
+ expect(document.activeElement?.id).toBe('toggle')
+ expect(document.querySelector('#row-toggle')?.classList).toContain(
+ 'gamepad-focus'
+ )
+ })
+
+ it('walks controls vertically and horizontally', () => {
+ focusFirstControlIn(document.getElementById('tabpanel-advanced')!)
+ expect(document.activeElement?.id).toBe('toggle')
+
+ moveSettingsFocus(1)
+ expect(document.activeElement?.id).toBe('first-button')
+
+ moveSettingsFocus(1)
+ expect(document.activeElement?.id).toBe('second-button')
+
+ moveSettingsFocus(-1)
+ expect(document.activeElement?.id).toBe('first-button')
+
+ moveSettingsFocusHorizontal(1)
+ expect(document.activeElement?.id).toBe('second-button')
+ })
+
+ it('lets focus leave the panel at the first and last control', () => {
+ focusFirstSettingsControl()
+ expect(document.activeElement?.id).toBe('toggle')
+
+ expect(moveSettingsFocus(-1)).toBe(false)
+ expect(document.activeElement?.id).toBe('toggle')
+
+ document.getElementById('second-button')?.focus()
+ expect(moveSettingsFocus(1)).toBe(false)
+ })
+
+ it('does not swallow horizontal moves on a single-control row', () => {
+ document.getElementById('toggle')?.focus()
+
+ expect(moveSettingsFocusHorizontal(1)).toBe(false)
+ expect(moveSettingsFocusHorizontal(-1)).toBe(false)
+ })
+
+ it('walks the focus order out of a slider outside the settings', () => {
+ document.body.innerHTML = `
+ <div class="discountFilters">
+ <button id="before">Before</button>
+ <div class="rangeSlider">
+ <span class="MuiSlider-root">
+ <span class="MuiSlider-thumb" id="thumb" tabindex="0"></span>
+ </span>
+ </div>
+ <button id="after">After</button>
+ </div>
+ `
+
+ document.getElementById('thumb')?.focus()
+
+ expect(moveSettingsFocus(1)).toBe(false)
+ expect(moveFocusSequentially(1)).toBe(true)
+ expect(document.activeElement?.id).toBe('after')
+
+ expect(moveFocusSequentially(-1)).toBe(true)
+ expect(document.activeElement?.id).toBe('thumb')
+ })
+
+ it('keeps the sequential walk inside the settings pane', () => {
+ document.body.innerHTML = `
+ <button id="page-control">Page</button>
+ <div class="settingsPane"><button id="pane-control">Pane</button></div>
+ `
+
+ document.getElementById('pane-control')?.focus()
+
+ expect(moveFocusSequentially(-1)).toBe(false)
+ expect(document.activeElement?.id).toBe('pane-control')
+ })
+
+ it('does not switch the page tabs from inside a dialog', () => {
+ document.body.innerHTML = `
+ <div role="tablist" data-gamepad-tabs="true">
+ <button role="tab" aria-selected="true" aria-controls="tabpanel-library">Library</button>
+ <button role="tab" aria-controls="tabpanel-store">Store</button>
+ </div>
+ <div role="tabpanel" id="tabpanel-library"><button id="card">Card</button></div>
+ <div class="MuiDialog-root">
+ <div class="MuiDialog-container">
+ <div class="MuiDialog-paper Modal" role="dialog">
+ <button id="confirm">Uninstall</button>
+ </div>
+ </div>
+ </div>
+ `
+
+ rememberGamepadTabListForFocus(
+ document.querySelector<HTMLElement>('[role="tab"]')
+ )
+ document.getElementById('confirm')?.focus()
+
+ expect(getPreferredTabList()).toBeNull()
+ })
+
+ it('keeps switching the tabs owned by the open dialog', () => {
+ document.body.innerHTML = `
+ <div role="tablist" data-gamepad-tabs="true">
+ <button role="tab" aria-selected="true" aria-controls="tabpanel-page">Library</button>
+ <button role="tab" aria-controls="tabpanel-page-two">Store</button>
+ </div>
+ <div class="MuiDialog-root">
+ <div role="dialog" class="MuiDialog-paper">
+ <div role="tablist" id="dialog-tabs" data-gamepad-tabs="true">
+ <button role="tab" aria-selected="true" aria-controls="tabpanel-game">Game</button>
+ <button role="tab" aria-controls="tabpanel-saves">Saves</button>
+ </div>
+ <div role="tabpanel" id="tabpanel-game">
+ <button id="dialog-control">Control</button>
+ </div>
+ </div>
+ </div>
+ `
+
+ document.getElementById('dialog-control')?.focus()
+
+ expect(getPreferredTabList()?.id).toBe('dialog-tabs')
+ })
+
+ it('forgets the page tablist when another dialog takes the focus', () => {
+ document.body.innerHTML = `
+ <div role="tablist" data-gamepad-tabs="true">
+ <button role="tab" aria-selected="true" aria-controls="tabpanel-library">Library</button>
+ <button role="tab" aria-controls="tabpanel-store">Store</button>
+ </div>
+ <div class="MuiDialog-root">
+ <div role="dialog" class="MuiDialog-paper">
+ <button id="confirm">Uninstall</button>
+ </div>
+ </div>
+ `
+
+ rememberGamepadTabListForFocus(
+ document.querySelector<HTMLElement>('[role="tab"]')
+ )
+ rememberGamepadTabListForFocus(document.getElementById('confirm'))
+
+ document.querySelector('.MuiDialog-root')?.remove()
+ expect(getPreferredTabList()).toBeNull()
+ })
+
+ it('focuses the controlling tablist for the active panel', () => {
+ document.getElementById('first-button')?.focus()
+
+ expect(getPreferredTabList()).toBe(
+ document.querySelector('[role="tablist"]')
+ )
+ expect(hasSwitchableTablist()).toBe(true)
+ })
+
+ it('prefers the inner tablist when legacy ids collide with the sidebar', () => {
+ document.body.innerHTML = `
+ <div class="settingsSidebar">
+ <div role="tablist" id="sidebar-list" data-gamepad-tabs="true">
+ <button role="tab" aria-selected="false" aria-controls="tabpanel-advanced">Games</button>
+ <button role="tab" aria-selected="true" aria-controls="tabpanel-advanced">Advanced</button>
+ </div>
+ </div>
+ <div class="settingsPane">
+ <div role="tablist" id="inner-list" data-gamepad-tabs="true">
+ <button role="tab" aria-selected="false" aria-controls="tabpanel-wine">Wine</button>
+ <button role="tab" aria-selected="true" aria-controls="tabpanel-advanced">Advanced</button>
+ </div>
+ <div role="tabpanel" id="tabpanel-advanced">
+ <button id="inner-focus">Focus</button>
+ </div>
+ </div>
+ `
+
+ document.getElementById('inner-focus')?.focus()
+
+ expect(getPreferredTabList()?.id).toBe('inner-list')
+ })
+
+ it('is a no-op when nothing has focused a tablist yet', () => {
+ expect(getPreferredTabList()).toBeNull()
+ })
+
+ it('keeps the last focused tablist after focus leaves it', () => {
+ const tab = document.querySelector<HTMLElement>('[role="tab"]')!
+ const list = document.querySelector<HTMLElement>('[role="tablist"]')!
+
+ rememberGamepadTabListForFocus(tab)
+
+ const outside = document.createElement('button')
+ document.body.append(outside)
+ outside.focus()
+
+ expect(getPreferredTabList()).toBe(list)
+
+ list.remove()
+ expect(getPreferredTabList()).toBeNull()
+ })
+
+ it('associates a route-based settings pane with the sidebar tabs', () => {
+ document.body.innerHTML = `
+ <div class="settingsSidebar">
+ <div role="tablist" data-gamepad-tabs="true" id="section-tabs">
+ <button role="tab" id="tab-general" aria-selected="true" aria-controls="tabpanel-general">General</button>
+ <button role="tab" id="tab-gamepad" aria-controls="tabpanel-gamepad">Gamepad</button>
+ </div>
+ </div>
+ <div class="settingsPane" id="tabpanel-general" role="tabpanel" aria-labelledby="tab-general">
+ <div class="SettingRow"><div class="SettingRow__control">
+ <span class="ToggleSwitch">
+ <input class="ToggleSwitch__input" id="pane-toggle" type="checkbox" />
+ <label class="ToggleSwitch__track"></label>
+ </span>
+ </div></div>
+ </div>
+ `
+
+ document.getElementById('pane-toggle')?.focus()
+
+ expect(getPreferredTabList()?.id).toBe('section-tabs')
+ expect(hasSwitchableTablist()).toBe(true)
+ })
+
+ it('does not fall back when focus is in a non-opted tablist', () => {
+ document.body.innerHTML = `
+ <div role="tablist" data-gamepad-tabs="true" id="opted">
+ <button role="tab" aria-selected="true">Opted one</button>
+ <button role="tab">Opted two</button>
+ </div>
+ <div role="tablist" id="plain">
+ <button role="tab" aria-selected="true">Plain one</button>
+ <button role="tab">Plain two</button>
+ </div>
+ `
+
+ rememberGamepadTabListForFocus(
+ document.querySelector<HTMLElement>('#opted [role="tab"]')
+ )
+ document.querySelector<HTMLElement>('#plain [role="tab"]')?.focus()
+
+ expect(getPreferredTabList()).toBeNull()
+ })
+
+ it('blocks tab switching in console launch and overlays', () => {
+ expect(isTabSwitchingBlocked()).toBe(false)
+
+ document.body.classList.add('console-launching')
+ expect(isTabSwitchingBlocked()).toBe(true)
+ document.body.classList.remove('console-launching')
+
+ const overlay = document.createElement('div')
+ overlay.className = 'consoleLaunchOverlay'
+ document.body.append(overlay)
+ expect(isTabSwitchingBlocked()).toBe(true)
+ overlay.remove()
+ })
+
+ it('lets an empty search enter the active panel with Down', () => {
+ document.body.innerHTML = `
+ <div class="settingsPane">
+ <div class="settingsSearchRow"><input id="search" type="text" /></div>
+ <div id="panel"><button id="panel-first">First</button></div>
+ </div>
+ `
+
+ document.getElementById('search')?.focus()
+
+ expect(moveSettingsFocus(1)).toBe(true)
+ expect(document.activeElement?.id).toBe('panel-first')
+
+ expect(moveSettingsFocus(-1)).toBe(true)
+ expect(document.activeElement?.id).toBe('search')
+ expect(moveSettingsFocus(-1)).toBe(false)
+ })
+
+ it('does not switch tabs while a field has focus', () => {
+ document.body.innerHTML = `
+ <div role="tablist" data-gamepad-tabs="true">
+ <button role="tab" aria-selected="true" aria-controls="tabpanel-fields">Fields</button>
+ <button role="tab" aria-controls="tabpanel-other">Other</button>
+ </div>
+ <div role="tabpanel" id="tabpanel-fields">
+ <input id="field" type="text" />
+ </div>
+ `
+
+ document.getElementById('field')?.focus()
+
+ expect(getPreferredTabList()).toBeNull()
+ expect(hasSwitchableTablist()).toBe(false)
+ })
+
+ it('does not fall back to the outer tabs for a single inner tab', () => {
+ document.body.innerHTML = `
+ <div class="settingsSidebar">
+ <div role="tablist" data-gamepad-tabs="true">
+ <button role="tab" aria-selected="true" aria-controls="tabpanel-advanced">General</button>
+ <button role="tab" aria-controls="tabpanel-gamepad">Gamepad</button>
+ </div>
+ </div>
+ <div class="settingsPane">
+ <div role="tablist" data-gamepad-tabs="true">
+ <button role="tab" aria-selected="true" aria-controls="tabpanel-advanced">Only</button>
+ </div>
+ <div role="tabpanel" id="tabpanel-advanced">
+ <button id="single-control">Control</button>
+ </div>
+ </div>
+ `
+
+ document.getElementById('single-control')?.focus()
+
+ expect(getPreferredTabList()).toBeNull()
+ })
+
+ it('does not consider a single-tab list switchable', () => {
+ document.body.innerHTML = `
+ <div role="tablist"><button role="tab" aria-selected="true">Only</button></div>
+ `
+
+ expect(getPreferredTabList()).toBeNull()
+ expect(hasSwitchableTablist()).toBe(false)
+ })
+
+ it('scrolls the controlled panel back to the top', () => {
+ const tab = document.querySelector<HTMLElement>(
+ '[role="tab"][aria-controls="tabpanel-advanced"]'
+ )!
+ const panel = document.getElementById('tabpanel-advanced')!
+ panel.scrollTop = 240
+
+ scrollTabPanelToTop(tab)
+
+ expect(panel.scrollTop).toBe(0)
+ })
+})
+
+describe('settings focus retry', () => {
+ afterEach(() => {
+ jest.useRealTimers()
+ })
+
+ it('stops once focus succeeds', () => {
+ jest.useFakeTimers()
+ const focus = jest
+ .fn()
+ .mockReturnValueOnce(false)
+ .mockReturnValueOnce(false)
+ .mockReturnValue(true)
+
+ retrySettingsFocus(focus, () => true, { retryMs: 50 })
+
+ expect(focus).toHaveBeenCalledTimes(1)
+ jest.advanceTimersByTime(100)
+ expect(focus).toHaveBeenCalledTimes(3)
+ jest.advanceTimersByTime(500)
+ expect(focus).toHaveBeenCalledTimes(3)
+ })
+
+ it('stops when the stop condition becomes false', () => {
+ jest.useFakeTimers()
+ const focus = jest.fn().mockReturnValue(false)
+ let canContinue = true
+
+ retrySettingsFocus(focus, () => canContinue, { retryMs: 50 })
+ canContinue = false
+
+ jest.advanceTimersByTime(500)
+ expect(focus).toHaveBeenCalledTimes(1)
+ })
+
+ it('keeps retrying while the body or nav is still valid', () => {
+ expect(canContinueSettingsFocusRetry(false, document.body, true)).toBe(true)
+ expect(canContinueSettingsFocusRetry(false, document.body, false)).toBe(
+ false
+ )
+ expect(canContinueSettingsFocusRetry(true, document.body, false)).toBe(true)
+
+ document.body.innerHTML = `
+ <div class="settingsNav" id="nav">nav</div>
+ <div class="settingsSearchRow"><input id="search" /></div>
+ <button id="control">control</button>
+ `
+
+ expect(
+ canContinueSettingsFocusRetry(false, document.getElementById('nav'), true)
+ ).toBe(true)
+ expect(
+ canContinueSettingsFocusRetry(
+ false,
+ document.getElementById('search'),
+ true
+ )
+ ).toBe(false)
+ expect(
+ canContinueSettingsFocusRetry(
+ false,
+ document.getElementById('control'),
+ true
+ )
+ ).toBe(false)
+ })
+})
+
+describe('settings gamepad entry after a takeover', () => {
+ it('lets the next entry refocus after a real controller action', () => {
+ expect(
+ shouldEnterSettingsGamepadFocus({
+ gamepadActive: true,
+ gamepadConnected: true,
+ bodyFocused: true,
+ userTookOver: true
+ })
+ ).toBe(true)
+ })
+
+ it('stays out of the way for reconnects and config reloads', () => {
+ expect(
+ shouldEnterSettingsGamepadFocus({
+ gamepadActive: false,
+ gamepadConnected: true,
+ bodyFocused: true,
+ userTookOver: true
+ })
+ ).toBe(false)
+ })
+
+ it('enters on mount with a connected controller and body focused', () => {
+ expect(
+ shouldEnterSettingsGamepadFocus({
+ gamepadActive: false,
+ gamepadConnected: true,
+ bodyFocused: true,
+ userTookOver: false
+ })
+ ).toBe(true)
+ expect(
+ shouldEnterSettingsGamepadFocus({
+ gamepadActive: false,
+ gamepadConnected: true,
+ bodyFocused: false,
+ userTookOver: false
+ })
+ ).toBe(false)
+ })
+
+ it('counts real keyboard input but not the synthetic gamepad keys', () => {
+ expect(isSettingsFocusTakeover('pointer', true)).toBe(true)
+ expect(isSettingsFocusTakeover('keyboard', true)).toBe(false)
+ expect(isSettingsFocusTakeover('keyboard', false)).toBe(true)
+ })
+})
+
+describe('settings gamepad entry retry', () => {
+ afterEach(() => {
+ jest.useRealTimers()
+ document.body.innerHTML = ''
+ })
+
+ const createEntry = (
+ overrides: Partial<Parameters<typeof beginSettingsGamepadFocus>[0]> = {}
+ ) => {
+ let userTookOver = overrides.userTookOver ?? false
+ const focusFirst = jest.fn().mockReturnValue(false)
+ const clearTakeOver = jest.fn(() => {
+ userTookOver = false
+ })
+
+ const start = beginSettingsGamepadFocus({
+ gamepadActive: true,
+ gamepadConnected: true,
+ bodyFocused: true,
+ focusFirst,
+ clearTakeOver,
+ isTakenOver: () => userTookOver,
+ getActiveElement: () => document.body,
+ isGamepadActive: () => true,
+ retryMs: 50,
+ ...overrides,
+ userTookOver
+ })
+
+ return {
+ start,
+ focusFirst,
+ clearTakeOver,
+ isTakenOver: () => userTookOver,
+ setTakenOver: (value: boolean) => {
+ userTookOver = value
+ }
+ }
+ }
+
+ it('refocuses after a retake with gamepad-active and a delayed pane', () => {
+ jest.useFakeTimers()
+ const { start, focusFirst, clearTakeOver, isTakenOver } = createEntry({
+ userTookOver: true
+ })
+
+ expect(start).not.toBeNull()
+ // The first attempt runs while the pane is still missing. Without the
+ // clear, the retry would stop on the stale takeover flag instead.
+ expect(focusFirst).toHaveBeenCalledTimes(1)
+ expect(clearTakeOver).toHaveBeenCalledTimes(1)
+ expect(isTakenOver()).toBe(false)
+
+ focusFirst.mockReturnValue(true)
+ jest.advanceTimersByTime(50)
+ expect(focusFirst).toHaveBeenCalledTimes(2)
+
+ // Once the focus lands, the retry stops.
+ jest.advanceTimersByTime(500)
+ expect(focusFirst).toHaveBeenCalledTimes(2)
+ })
+
+ it('does not start or clear the flag for a bare connected controller', () => {
+ const { start, focusFirst, clearTakeOver, isTakenOver } = createEntry({
+ gamepadActive: false,
+ userTookOver: true
+ })
+
+ expect(start).toBeNull()
+ expect(focusFirst).not.toHaveBeenCalled()
+ expect(clearTakeOver).not.toHaveBeenCalled()
+ expect(isTakenOver()).toBe(true)
+ })
+
+ it('stops the retry when the search takes focus during the entry', () => {
+ jest.useFakeTimers()
+ document.body.innerHTML = `
+ <div class="settingsSearchRow"><input id="search" /></div>
+ <div class="settingsNav" id="nav">nav</div>
+ `
+ const search = document.getElementById('search')
+ const { start, focusFirst } = createEntry({
+ getActiveElement: () => search
+ })
+
+ expect(start).not.toBeNull()
+ jest.advanceTimersByTime(500)
+ expect(focusFirst).not.toHaveBeenCalled()
+ })
+
+ it('stops the retry when the user takes over mid-entry', () => {
+ jest.useFakeTimers()
+ const { start, focusFirst, setTakenOver } = createEntry()
+
+ expect(start).not.toBeNull()
+ jest.advanceTimersByTime(50)
+ expect(focusFirst).toHaveBeenCalledTimes(2)
+
+ setTakenOver(true)
+ jest.advanceTimersByTime(500)
+ expect(focusFirst).toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/src/frontend/helpers/gamepad.ts b/src/frontend/helpers/gamepad.ts
index 042aea6b8..55e787ef5 100644
--- a/src/frontend/helpers/gamepad.ts
+++ b/src/frontend/helpers/gamepad.ts
@@ -13,6 +13,17 @@ import {
checkNintendo
} from './gamepad_layouts'
import { VirtualKeyboardController } from './virtualKeyboard'
+import {
+ clearGamepadRowFocus,
+ GAMEPAD_TAB_EVENT,
+ getActiveSettingsScope,
+ isTabSwitchingBlocked,
+ moveFocusSequentially,
+ moveSettingsFocus,
+ moveSettingsFocusHorizontal,
+ MODAL_SELECTOR
+} from './settingsFocus'
+import { DEFAULT_GAMEPAD_BUTTONS, getMappedButtonFrom } from './gamepadMapping'
const SCROLL_REPEAT_DELAY = 50
@@ -23,11 +34,19 @@ const SCROLL_REPEAT_DELAY = 50
let controllerIsDisabled = false
let controllerEnabledInConsole = true
let currentController = -1
+let connectedControllers = 0
let webviewHasFocus = false
let gamepadPassthrough = false
+let lastGamepadActionAt = 0
+
+const clearGamepadActive = () => {
+ document.body.classList.remove('gamepad-active')
+ clearGamepadRowFocus()
+}
export const toggleWebviewFocus = (focused: boolean) => {
webviewHasFocus = focused
+ if (focused) clearGamepadActive()
}
export const setGamepadPassthrough = (enabled: boolean) => {
@@ -35,6 +54,10 @@ export const setGamepadPassthrough = (enabled: boolean) => {
}
export const isUsingGamepad = () => currentController !== -1
+export const isGamepadConnected = () =>
+ connectedControllers > 0 ||
+ (typeof navigator !== 'undefined' &&
+ Array.from(navigator.getGamepads()).some(Boolean))
export type NavigateDirection = 'up' | 'down' | 'left' | 'right'
type ScrollDirection = 'up' | 'down'
@@ -207,25 +230,11 @@ export const detectGamepadLayout = (id: string): GamepadLayout => {
return 'standard'
}
-export const DEFAULT_GAMEPAD_BUTTONS: Record<
- RemappableGamepadAction,
- number | null
-> = {
- mainAction: 0,
- back: 1,
- rightClick: 2,
- altAction: 3,
- prevPage: 4,
- nextPage: 5,
- enter: 10,
- guide: 16
-}
-
// physical button currently bound to an action (user mapping over defaults)
-export const getMappedButton = (action: RemappableGamepadAction) => {
- const override = buttonMapping[action]
- return override === undefined ? DEFAULT_GAMEPAD_BUTTONS[action] : override
-}
+export const getMappedButton = (action: RemappableGamepadAction) =>
+ getMappedButtonFrom(buttonMapping, action)
+
+export { DEFAULT_GAMEPAD_BUTTONS }
const NAVIGATION_ACTIONS: ValidGamepadAction[] = [
'padUp',
@@ -300,6 +309,8 @@ export const updateGamepadActions = async () => {
rightClick: { triggeredAt: {}, repeatDelay: false },
prevPage: { triggeredAt: {}, repeatDelay: false },
nextPage: { triggeredAt: {}, repeatDelay: false },
+ prevTab: { triggeredAt: {}, repeatDelay: false },
+ nextTab: { triggeredAt: {}, repeatDelay: false },
esc: { triggeredAt: {}, repeatDelay: false },
tab: { triggeredAt: {}, repeatDelay: false },
shiftTab: { triggeredAt: {}, repeatDelay: false },
@@ -329,6 +340,7 @@ export const initGamepad = () => {
for (const gamepad of navigator.getGamepads()) {
if (gamepad) controllers.push(gamepad.index)
}
+ connectedControllers = controllers.length
isPolling = controllers.length > 0
if (isPolling) requestAnimationFrame(updateStatus)
@@ -394,6 +406,7 @@ export const initGamepad = () => {
// Lets CSS draw focus rings for programmatic focus, which does not
// necessarily match `:focus-visible`.
document.body.classList.add('gamepad-active')
+ lastGamepadActionAt = now
const el = currentElement()
// Guide / PS button toggles Console Mode. Many OSes (Steam, Game Bar)
@@ -433,6 +446,18 @@ export const initGamepad = () => {
return
}
+ // L2/R2 switch tabs. Console Mode owns R2 for sort/quit, so never take
+ // those presses there.
+ if (action === 'prevTab' || action === 'nextTab') {
+ if (isTabSwitchingBlocked()) return
+ window.dispatchEvent(
+ new CustomEvent(GAMEPAD_TAB_EVENT, {
+ detail: { direction: action === 'nextTab' ? 1 : -1 }
+ })
+ )
+ return
+ }
+
// check special cases for the different actions, more details on the wiki
switch (action) {
case 'mainAction':
@@ -506,13 +531,17 @@ export const initGamepad = () => {
document.getElementById('app')?.focus()
} else {
switch (action) {
+ case 'padLeft':
+ case 'leftStickLeft':
+ if (isSettingsRow() && moveSettingsFocusHorizontal(-1)) return
+ break
+ case 'padRight':
+ case 'leftStickRight':
+ if (isSettingsRow() && moveSettingsFocusHorizontal(1)) return
+ break
case 'padDown':
case 'leftStickDown':
- if (insideMuiSlider() || isSettingsRow()) {
- moveFocusSequentially(1)
- scrollFocusedIntoView()
- return
- }
+ if (moveVerticalFocus(1)) return
// MUI Selects open on arrow down, which is usually not your intention
// when navigating down with the stick, so we change the action to tab
if (isMuiSelect()) {
@@ -524,11 +553,7 @@ export const initGamepad = () => {
break
case 'padUp':
case 'leftStickUp':
- if (insideMuiSlider() || isSettingsRow()) {
- moveFocusSequentially(-1)
- scrollFocusedIntoView()
- return
- }
+ if (moveVerticalFocus(-1)) return
if (isMuiSelect()) {
action = 'shiftTab'
}
@@ -667,7 +692,26 @@ export const initGamepad = () => {
*/
function isSettingsRow() {
const el = currentElement()
- if (!el || !el.closest('.Settings')) return false
+ if (!el || !el.closest('.Settings, .settingsDialogContent')) return false
+
+ // An empty search field must not become a dead end: Down enters the
+ // active panel, Up leaves it to the spatial navigation. With a query the
+ // suggestions own the arrows.
+ if (el.closest('.settingsSearchRow')) {
+ return el.tagName === 'INPUT' && (el as HTMLInputElement).value === ''
+ }
+
+ // Nav and the tab bar keep their own/spatial navigation; only the active
+ // settings pane should walk the form sequentially.
+ if (
+ el.closest('.settingsNav, .settingsSidebar') ||
+ el.closest('[role="tablist"]')
+ ) {
+ return false
+ }
+
+ const scope = getActiveSettingsScope()
+ if (!scope || !scope.contains(el)) return false
// Multi-line fields and sliders keep the arrow keys. Single-line text
// fields navigate vertically: up/down only moves the caret there, which
@@ -677,41 +721,29 @@ export const initGamepad = () => {
return false
}
- // The settings search navigates its suggestion list with the arrows, but
- // only while there is a query; an empty field must not become a dead end.
- if (el.closest('.settingsSearchRow')) {
- return el.tagName !== 'INPUT' || (el as HTMLInputElement).value === ''
- }
-
return !insideMuiSlider()
}
- const FOCUSABLE_SELECTOR =
- 'a[href], button:not([disabled]), input:not([disabled]), ' +
- 'select:not([disabled]), textarea:not([disabled]), ' +
- '[tabindex]:not([tabindex="-1"]), .MuiSelect-select'
-
/**
- * Focus order step. `Tab` alone is not enough here: the MUI slider root is a
- * dead stop (it takes focus but the arrows do nothing) that sits between a
- * slider and its neighbours. MUI selects are listed explicitly because they
- * carry `tabIndex={-1}` yet must be reachable to be opened with confirm.
+ * Vertical focus step for the settings form and for MUI sliders. Returns
+ * true when the press belongs to the focus order (whether or not it moved)
+ * so the caller does not send the arrow key to the control.
*/
- function moveFocusSequentially(direction: 1 | -1) {
- const scope = document.querySelector<HTMLElement>('.Settings') ?? document
-
- const candidates = Array.from(
- scope.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)
- ).filter(
- (el) =>
- (el.tabIndex >= 0 || el.classList.contains('MuiSelect-select')) &&
- el.getClientRects().length > 0
- )
+ function moveVerticalFocus(direction: 1 | -1): boolean {
+ const onSlider = insideMuiSlider()
+ if (!onSlider && !isSettingsRow()) return false
- const index = candidates.indexOf(document.activeElement as HTMLElement)
- if (index === -1) return
+ if (moveSettingsFocus(direction)) {
+ scrollFocusedIntoView()
+ return true
+ }
+ if (!onSlider) return false
- candidates[index + direction]?.focus()
+ // A slider outside the settings (the Discounts price and rating filters)
+ // has no pane to walk and the arrow keys belong to the slider: keep the
+ // sequential focus move, or the value changes and the focus stays trapped.
+ if (moveFocusSequentially(direction)) scrollFocusedIntoView()
+ return true
}
function isMuiDialogCloseButton() {
@@ -989,6 +1021,7 @@ export const initGamepad = () => {
function addgamepad(gamepad: Gamepad) {
console.log(`Gamepad added: ${JSON.stringify(gamepad.id)}`)
if (!controllers.includes(gamepad.index)) controllers.push(gamepad.index)
+ connectedControllers = controllers.length
if (!isPolling) {
isPolling = true
requestAnimationFrame(updateStatus)
@@ -1004,13 +1037,37 @@ export const initGamepad = () => {
// remove disconnected controller
controllers = controllers.filter((idx) => idx !== gamepad.index)
+ connectedControllers = controllers.length
- // if controller was the current controller, reset and emit
+ // if controller was the current controller, reset, emit and drop the
+ // controller focus styling even when another pad is still connected
if (gamepad.index === currentController) {
+ clearGamepadActive()
emitControllerEvent(-1)
}
+
+ if (!controllers.length) clearGamepadActive()
+ }
+
+ const onKeyboardInput = () => {
+ // Ignore the synthetic keys Heroic sends right after a controller press.
+ if (Date.now() - lastGamepadActionAt > 500) clearGamepadActive()
}
+ const onModalFocus = (event: FocusEvent) => {
+ const target = event.target as HTMLElement | null
+ if (
+ target?.closest(MODAL_SELECTOR) &&
+ !target.closest('.settingsDialogContent')
+ ) {
+ clearGamepadActive()
+ }
+ }
+
+ window.addEventListener('blur', clearGamepadActive)
+ window.addEventListener('keydown', onKeyboardInput, true)
+ document.addEventListener('focusin', onModalFocus, true)
+
function dispatchControllerEvent(id: string) {
const controllerEvent = new CustomEvent('controller-changed', {
detail: {
@@ -1048,6 +1105,7 @@ export const initGamepad = () => {
'mousemove',
() => {
currentController = -1
+ clearGamepadActive()
dispatchControllerEvent('')
},
{ once: true }
@@ -1057,11 +1115,7 @@ export const initGamepad = () => {
window.addEventListener('gamepadconnected', connecthandler)
window.addEventListener('gamepaddisconnected', disconnecthandler)
- window.addEventListener(
- 'pointerdown',
- () => document.body.classList.remove('gamepad-active'),
- true
- )
+ window.addEventListener('pointerdown', clearGamepadActive, true)
}
// True when controller nav is blocked
diff --git a/src/frontend/helpers/gamepadMapping.ts b/src/frontend/helpers/gamepadMapping.ts
new file mode 100644
index 000000000..81c49a160
--- /dev/null
+++ b/src/frontend/helpers/gamepadMapping.ts
@@ -0,0 +1,25 @@
+import type { RemappableGamepadAction } from 'common/types'
+
+export const DEFAULT_GAMEPAD_BUTTONS: Record<
+ RemappableGamepadAction,
+ number | null
+> = {
+ mainAction: 0,
+ back: 1,
+ rightClick: 2,
+ altAction: 3,
+ prevPage: 4,
+ nextPage: 5,
+ prevTab: 6,
+ nextTab: 7,
+ enter: 10,
+ guide: 16
+}
+
+export const getMappedButtonFrom = (
+ mapping: Partial<Record<RemappableGamepadAction, number | null>>,
+ action: RemappableGamepadAction
+) => {
+ const override = mapping[action]
+ return override === undefined ? DEFAULT_GAMEPAD_BUTTONS[action] : override
+}
diff --git a/src/frontend/helpers/gamepad_layouts/nintendo.ts b/src/frontend/helpers/gamepad_layouts/nintendo.ts
index 989e8a5c8..f5f59bc1b 100644
--- a/src/frontend/helpers/gamepad_layouts/nintendo.ts
+++ b/src/frontend/helpers/gamepad_layouts/nintendo.ts
@@ -1,6 +1,7 @@
// Holds layouts for different Nintendo official and clone controllers
import { RemappableGamepadAction, ValidGamepadAction } from 'common/types'
+import { getMappedButtonFrom } from '../gamepadMapping'
type ButtonOverrides = Partial<Record<RemappableGamepadAction, number | null>>
@@ -88,6 +89,14 @@ export function checkNintendo(
return override === undefined ? fallback : buttons[override]
}
+ const pressed = (button: GamepadButton | undefined) =>
+ !!button && (button.pressed || button.value > 0.5)
+
+ const mappedButton = (action: RemappableGamepadAction) => {
+ const index = getMappedButtonFrom(overrides, action)
+ return index === null ? undefined : buttons[index]
+ }
+
checkAction(
'mainAction',
button('mainAction', A)?.pressed ?? false,
@@ -109,6 +118,8 @@ export function checkNintendo(
button('enter', buttons[10])?.pressed ?? false,
controllerIndex
) // L3
+ checkAction('prevTab', pressed(mappedButton('prevTab')), controllerIndex)
+ checkAction('nextTab', pressed(mappedButton('nextTab')), controllerIndex)
checkAction('leftStickLeft', leftAxisX < -0.5, controllerIndex)
checkAction('leftStickRight', leftAxisX > 0.5, controllerIndex)
checkAction('leftStickUp', leftAxisY < -0.5, controllerIndex)
diff --git a/src/frontend/helpers/gamepad_layouts/standard.ts b/src/frontend/helpers/gamepad_layouts/standard.ts
index 363787c23..3a697b5ca 100644
--- a/src/frontend/helpers/gamepad_layouts/standard.ts
+++ b/src/frontend/helpers/gamepad_layouts/standard.ts
@@ -1,4 +1,5 @@
import { RemappableGamepadAction, ValidGamepadAction } from 'common/types'
+import { getMappedButtonFrom } from '../gamepadMapping'
// Holds layouts for different XBox official an clone controllers
type ButtonOverrides = Partial<Record<RemappableGamepadAction, number | null>>
@@ -20,8 +21,6 @@ export function checkStandard(
altButton = buttons[3], // Xbox: Y, PS: Triangle
leftBumper = buttons[4], // Xbox: LB, PS: L1
rightBumper = buttons[5], // Xbox: RB, PS: R1
- // LT = buttons[6], // has .value
- // RT = buttons[7], // has .value
// view = buttons[8],
// menu = buttons[9],
// L3 = buttons[10], // press left stick
@@ -48,6 +47,14 @@ export function checkStandard(
return override === undefined ? fallback : buttons[override]
}
+ const pressed = (button: GamepadButton | undefined) =>
+ !!button && (button.pressed || button.value > 0.5)
+
+ const mappedButton = (action: RemappableGamepadAction) => {
+ const index = getMappedButtonFrom(overrides, action)
+ return index === null ? undefined : buttons[index]
+ }
+
checkAction(
'mainAction',
button('mainAction', mainButton)?.pressed ?? false,
@@ -73,6 +80,8 @@ export function checkStandard(
button('nextPage', rightBumper)?.pressed ?? false,
controllerIndex
)
+ checkAction('prevTab', pressed(mappedButton('prevTab')), controllerIndex)
+ checkAction('nextTab', pressed(mappedButton('nextTab')), controllerIndex)
checkAction('leftStickLeft', leftAxisX < -0.5, controllerIndex)
checkAction('leftStickRight', leftAxisX > 0.5, controllerIndex)
checkAction('leftStickUp', leftAxisY < -0.5, controllerIndex)
diff --git a/src/frontend/helpers/settingsFocus.ts b/src/frontend/helpers/settingsFocus.ts
new file mode 100644
index 000000000..14f6e2f87
--- /dev/null
+++ b/src/frontend/helpers/settingsFocus.ts
@@ -0,0 +1,512 @@
+/*
+ * 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
+}
diff --git a/src/frontend/screens/Game/GamePage/index.tsx b/src/frontend/screens/Game/GamePage/index.tsx
index 4a3c4bae0..177a16ed7 100644
--- a/src/frontend/screens/Game/GamePage/index.tsx
+++ b/src/frontend/screens/Game/GamePage/index.tsx
@@ -781,6 +781,7 @@ export default React.memo(function GamePage(): JSX.Element | null {
value={activeTab}
onChange={setCurrentTab}
aria-label={t('game.tabs', 'Game information')}
+ gamepadNavigation
/>
<TabPanel
diff --git a/src/frontend/screens/Library/components/InstallModal/DownloadDialog/index.tsx b/src/frontend/screens/Library/components/InstallModal/DownloadDialog/index.tsx
index df9f7eb85..3ec23f44f 100644
--- a/src/frontend/screens/Library/components/InstallModal/DownloadDialog/index.tsx
+++ b/src/frontend/screens/Library/components/InstallModal/DownloadDialog/index.tsx
@@ -52,6 +52,11 @@ import {
getPreferredInstallLanguage
} from 'frontend/helpers'
import { install } from 'frontend/helpers/library'
+import { isUsingGamepad } from 'frontend/helpers/gamepad'
+import {
+ GAMEPAD_TABLIST_EVENT,
+ rememberGamepadTabListForFocus
+} from 'frontend/helpers/settingsFocus'
import ContextProvider from 'frontend/state/ContextProvider'
import { InstallProgress } from 'frontend/types'
import React, {
@@ -858,6 +863,25 @@ export default function DownloadDialog({
}
}, [activeTab, installTabs])
+ // Hand the install tabs to the controller when the dialog opens with one in
+ // use. Focus may sit on the close button, so seed the tablist instead of
+ // moving focus: the first L2/R2 works and the hint shows right away.
+ useEffect(() => {
+ if (installTabs.length <= 1 || !isUsingGamepad()) return
+
+ const frame = requestAnimationFrame(() => {
+ const tablist = document.querySelector<HTMLElement>(
+ '.InstallModal__tabs[role="tablist"]'
+ )
+ if (!tablist) return
+
+ rememberGamepadTabListForFocus(tablist)
+ window.dispatchEvent(new Event(GAMEPAD_TABLIST_EVENT))
+ })
+
+ return () => cancelAnimationFrame(frame)
+ }, [installTabs.length])
+
const changeTab = (value: InstallTab) => {
setActiveTab(value)
panelAreaRef.current?.scrollTo({ top: 0 })
@@ -1106,6 +1130,7 @@ export default function DownloadDialog({
aria-label={t('install.tabs.ariaLabel', 'Install sections')}
idPrefix="install-tab"
className="InstallModal__tabs"
+ gamepadNavigation
/>
)}
<div className="InstallModal__panelArea" ref={panelAreaRef}>
diff --git a/src/frontend/screens/Settings/components/GamepadButtonMapping.tsx b/src/frontend/screens/Settings/components/GamepadButtonMapping.tsx
index 651d6052e..e383ef8b1 100644
--- a/src/frontend/screens/Settings/components/GamepadButtonMapping.tsx
+++ b/src/frontend/screens/Settings/components/GamepadButtonMapping.tsx
@@ -15,6 +15,8 @@ const ACTIONS: RemappableGamepadAction[] = [
'rightClick',
'prevPage',
'nextPage',
+ 'prevTab',
+ 'nextTab',
'enter',
'guide'
]
@@ -47,6 +49,8 @@ const GamepadButtonMapping = () => {
rightClick: t('settings.gamepad.button.context', 'Options menu'),
prevPage: t('settings.gamepad.button.prevPage', 'Page up'),
nextPage: t('settings.gamepad.button.nextPage', 'Page down'),
+ prevTab: t('settings.gamepad.button.prevTab', 'Previous tab'),
+ nextTab: t('settings.gamepad.button.nextTab', 'Next tab'),
enter: t('settings.gamepad.button.enter', 'Submit / open keyboard'),
guide: t('settings.gamepad.button.guide', 'Console mode')
}
diff --git a/src/frontend/screens/Settings/index.tsx b/src/frontend/screens/Settings/index.tsx
index d8c67c046..b0b72fdc4 100644
--- a/src/frontend/screens/Settings/index.tsx
+++ b/src/frontend/screens/Settings/index.tsx
@@ -1,6 +1,6 @@
import './index.css'
-import React, { useContext, useEffect, useState } from 'react'
+import React, { useContext, useEffect, useRef, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
@@ -33,6 +33,12 @@ import {
import type { NavListItem } from 'frontend/components/UI/NavList'
import type { TabItem } from 'frontend/components/UI/Tabs'
import useMediaQuery from 'frontend/hooks/useMediaQuery'
+import {
+ beginSettingsGamepadFocus,
+ focusFirstSettingsControl,
+ isSettingsFocusTakeover
+} from 'frontend/helpers/settingsFocus'
+import { isGamepadConnected } from 'frontend/helpers/gamepad'
import {
ArchiveRestore,
Boxes,
@@ -55,6 +61,8 @@ function Settings() {
const { platform } = useContext(ContextProvider)
const navigate = useNavigate()
const isNarrow = useMediaQuery('(max-width: 1100px)')
+ const userTookOverFocus = useRef(false)
+ const lastEntryKey = useRef('')
const isWin = platform === 'win32'
const [currentConfig, setCurrentConfig] =
@@ -149,6 +157,76 @@ function Settings() {
<p>{helpContent}</p>
)
+ useEffect(() => {
+ let cancelFocus: (() => void) | undefined
+
+ // A new route or app is a new entry: the takeover only silences the entry
+ // the user interrupted, not the next one.
+ const entryKey = `${type}:${appName}`
+ if (lastEntryKey.current !== entryKey) {
+ lastEntryKey.current = entryKey
+ userTookOverFocus.current = false
+ }
+
+ const focusOnGamepadEntry = () => {
+ const active = document.activeElement as HTMLElement | null
+ const gamepadActive = document.body.classList.contains('gamepad-active')
+ const bodyFocused =
+ !active ||
+ active === document.body ||
+ active === document.documentElement ||
+ active.id === 'app'
+ const start = beginSettingsGamepadFocus({
+ gamepadActive,
+ gamepadConnected: isGamepadConnected(),
+ bodyFocused,
+ userTookOver: userTookOverFocus.current,
+ clearTakeOver: () => {
+ userTookOverFocus.current = false
+ },
+ isTakenOver: () => userTookOverFocus.current,
+ focusFirst: focusFirstSettingsControl,
+ getActiveElement: () => document.activeElement as HTMLElement | null,
+ isGamepadActive: () =>
+ document.body.classList.contains('gamepad-active'),
+ beforeRetry: () => {
+ cancelFocus?.()
+ document.body.classList.add('gamepad-active')
+ }
+ })
+ if (!start) return
+ cancelFocus = start
+ }
+
+ const markTakeover = (source: 'pointer' | 'keyboard') => {
+ if (
+ isSettingsFocusTakeover(
+ source,
+ document.body.classList.contains('gamepad-active')
+ )
+ ) {
+ userTookOverFocus.current = true
+ }
+ }
+
+ const markPointerTakeover = () => markTakeover('pointer')
+ const markKeyboardTakeover = () => markTakeover('keyboard')
+
+ focusOnGamepadEntry()
+ // A controller connected after this screen loaded still gets the same
+ // behaviour, as long as the user has not focused something else.
+ window.addEventListener('gamepadconnected', focusOnGamepadEntry)
+ window.addEventListener('pointerdown', markPointerTakeover, true)
+ window.addEventListener('keydown', markKeyboardTakeover, true)
+
+ return () => {
+ cancelFocus?.()
+ window.removeEventListener('gamepadconnected', focusOnGamepadEntry)
+ window.removeEventListener('pointerdown', markPointerTakeover, true)
+ window.removeEventListener('keydown', markKeyboardTakeover, true)
+ }
+ }, [type, appName, currentConfig])
+
// Load Heroic's or game's config, only if not loaded already
useEffect(() => {
const getSettings = async () => {
@@ -359,6 +437,7 @@ function Settings() {
className="settingsNav settingsNav--tabs"
idPrefix="settings-nav"
activation="manual"
+ gamepadNavigation
/>
{settingsSearchRow}
</>
@@ -370,7 +449,12 @@ function Settings() {
/>
)}
</div>
- <div className="settingsPane">
+ <div
+ className="settingsPane"
+ id={isNarrow ? `settings-navpanel-${type}` : undefined}
+ role={isNarrow ? 'tabpanel' : undefined}
+ aria-labelledby={isNarrow ? `settings-nav-${type}` : undefined}
+ >
{!isNarrow && settingsSearchRow}
{isGeneralSettings && <GeneralSettings />}
{isGamesSettings && <GamesSettings />}
diff --git a/src/frontend/screens/Settings/search/gamepad.ts b/src/frontend/screens/Settings/search/gamepad.ts
index ee659c34e..83ff683cc 100644
--- a/src/frontend/screens/Settings/search/gamepad.ts
+++ b/src/frontend/screens/Settings/search/gamepad.ts
@@ -67,6 +67,18 @@ export const gamepadSearchEntries: SettingsSearchEntry[] = [
sectionKey: 'settings.gamepad.buttonMapping.title',
titleKey: 'settings.gamepad.button.nextPage'
},
+ {
+ id: 'gamepad-binding-prevTab',
+ tab: 'gamepad',
+ sectionKey: 'settings.gamepad.buttonMapping.title',
+ titleKey: 'settings.gamepad.button.prevTab'
+ },
+ {
+ id: 'gamepad-binding-nextTab',
+ tab: 'gamepad',
+ sectionKey: 'settings.gamepad.buttonMapping.title',
+ titleKey: 'settings.gamepad.button.nextTab'
+ },
{
id: 'gamepad-binding-enter',
tab: 'gamepad',
diff --git a/src/frontend/screens/Settings/sections/GamesSettings/index.tsx b/src/frontend/screens/Settings/sections/GamesSettings/index.tsx
index 730564caf..a7aeab9f4 100644
--- a/src/frontend/screens/Settings/sections/GamesSettings/index.tsx
+++ b/src/frontend/screens/Settings/sections/GamesSettings/index.tsx
@@ -71,6 +71,7 @@ import FooterInfo from '../FooterInfo'
import { GameInfo } from 'common/types'
import DisableUMU from '../../components/DisableUMU'
import VerboseLogs from '../../components/VerboseLogs'
+import { focusFirstSettingsControl } from 'frontend/helpers/settingsFocus'
const windowsPlatforms = ['Win32', 'Windows', 'windows']
function getStartingTab(platform: string, gameInfo?: GameInfo | null): string {
@@ -103,6 +104,13 @@ export default function GamesSettings({ initialTab }: Props = {}) {
const [wineVersion] = useSetting('wineVersion', defaultWineVersion)
const [disableUMU] = useSetting('disableUMU', false)
const [nativeFromApi, setIsNative] = useState(false)
+
+ useEffect(() => {
+ if (!document.body.classList.contains('gamepad-active')) return
+
+ const frame = requestAnimationFrame(() => focusFirstSettingsControl())
+ return () => cancelAnimationFrame(frame)
+ }, [])
const isLinux = platform === 'linux'
const isWin = platform === 'win32'
const isMac = platform === 'darwin'
@@ -232,6 +240,7 @@ export default function GamesSettings({ initialTab }: Props = {}) {
className="settingsTabs"
idPrefix="settings-games"
activation="manual"
+ gamepadNavigation
/>
{isDefault && (
diff --git a/src/frontend/screens/Settings/sections/SyncSaves/gog.tsx b/src/frontend/screens/Settings/sections/SyncSaves/gog.tsx
index 33cad8697..6e34b03ef 100644
--- a/src/frontend/screens/Settings/sections/SyncSaves/gog.tsx
+++ b/src/frontend/screens/Settings/sections/SyncSaves/gog.tsx
@@ -213,7 +213,6 @@ export default function GOGSyncSaves({
<ul>
<li>{t('help.sync.part1')}</li>
{!isWin && <li>{t('help.sync.part2')}</li>}
- <li>{t('help.sync.part3')}</li>
<li>{t('help.sync.part4')}</li>
</ul>
}
@@ -243,35 +242,41 @@ export default function GOGSyncSaves({
</div>
))}
- <SettingRow
- label={t('setting.manualsync.title')}
- htmlFor="selectSyncType"
- >
- <SelectField
- htmlId="selectSyncType"
- onChange={(event) => setSyncType(event.target.value as SyncType)}
- value={syncType}
- disabled={!gogSaves.every((value) => value.location.length)}
+ <div className="settingsManualSyncRowContainer">
+ <SettingRow
+ className="settingsManualSyncRow"
+ label={t('setting.manualsync.title')}
+ description={t('help.sync.part3')}
+ htmlFor="selectSyncType"
>
- {syncCommands.map((el, i) => (
- <MenuItem value={el.value} key={i}>
- {el.name}
- </MenuItem>
- ))}
- </SelectField>
- <Button
- variant="ghost"
- data-testid="setSync"
- onClick={async () => handleSync()}
- disabled={
- isSyncing || !gogSaves.every((value) => value.location.length)
- }
- >
- {isSyncing
- ? t('setting.manualsync.syncing')
- : t('setting.manualsync.sync')}
- </Button>
- </SettingRow>
+ <SelectField
+ htmlId="selectSyncType"
+ onChange={(event) =>
+ setSyncType(event.target.value as SyncType)
+ }
+ value={syncType}
+ disabled={!gogSaves.every((value) => value.location.length)}
+ >
+ {syncCommands.map((el, i) => (
+ <MenuItem value={el.value} key={i}>
+ {el.name}
+ </MenuItem>
+ ))}
+ </SelectField>
+ <Button
+ variant="ghost"
+ data-testid="setSync"
+ onClick={async () => handleSync()}
+ disabled={
+ isSyncing || !gogSaves.every((value) => value.location.length)
+ }
+ >
+ {isSyncing
+ ? t('setting.manualsync.syncing')
+ : t('setting.manualsync.sync')}
+ </Button>
+ </SettingRow>
+ </div>
<ToggleSwitch
htmlId="autosync"
value={autoSyncSaves}
diff --git a/src/frontend/screens/Settings/sections/SyncSaves/legendary.tsx b/src/frontend/screens/Settings/sections/SyncSaves/legendary.tsx
index bc0b38460..90e6713d3 100644
--- a/src/frontend/screens/Settings/sections/SyncSaves/legendary.tsx
+++ b/src/frontend/screens/Settings/sections/SyncSaves/legendary.tsx
@@ -170,7 +170,6 @@ export default function LegendarySyncSaves({
<ul>
<li>{t('help.sync.part1')}</li>
{!isWin && <li>{t('help.sync.part2')}</li>}
- <li>{t('help.sync.part3')}</li>
<li>{t('help.sync.part4')}</li>
</ul>
}
@@ -200,33 +199,39 @@ export default function LegendarySyncSaves({
</Alert>
</div>
- <SettingRow
- label={t('setting.manualsync.title')}
- htmlFor="selectSyncType"
- >
- <SelectField
- htmlId="selectSyncType"
- onChange={(event) => setSyncType(event.target.value as SyncType)}
- value={syncType}
- disabled={!savesPath.length}
+ <div className="settingsManualSyncRowContainer">
+ <SettingRow
+ className="settingsManualSyncRow"
+ label={t('setting.manualsync.title')}
+ description={t('help.sync.part3')}
+ htmlFor="selectSyncType"
>
- {syncCommands.map((el, i) => (
- <MenuItem value={el.value} key={i}>
- {el.name}
- </MenuItem>
- ))}
- </SelectField>
- <Button
- variant="ghost"
- data-testid="setSync"
- onClick={async () => handleSync()}
- disabled={isSyncing || !savesPath.length}
- >
- {isSyncing
- ? t('setting.manualsync.syncing')
- : t('setting.manualsync.sync')}
- </Button>
- </SettingRow>
+ <SelectField
+ htmlId="selectSyncType"
+ onChange={(event) =>
+ setSyncType(event.target.value as SyncType)
+ }
+ value={syncType}
+ disabled={!savesPath.length}
+ >
+ {syncCommands.map((el, i) => (
+ <MenuItem value={el.value} key={i}>
+ {el.name}
+ </MenuItem>
+ ))}
+ </SelectField>
+ <Button
+ variant="ghost"
+ data-testid="setSync"
+ onClick={async () => handleSync()}
+ disabled={isSyncing || !savesPath.length}
+ >
+ {isSyncing
+ ? t('setting.manualsync.syncing')
+ : t('setting.manualsync.sync')}
+ </Button>
+ </SettingRow>
+ </div>
<ToggleSwitch
htmlId="autosync"
diff --git a/src/frontend/screens/WineManager/index.tsx b/src/frontend/screens/WineManager/index.tsx
index 357a32f63..bbb36d41a 100644
--- a/src/frontend/screens/WineManager/index.tsx
+++ b/src/frontend/screens/WineManager/index.tsx
@@ -248,6 +248,7 @@ export default function WineManager(): JSX.Element | null {
value={repository.value}
onChange={handleChangeTab}
aria-label={t('wine.manager.title', 'Wine manager')}
+ gamepadNavigation
/>
{wineVersionExplanation && (