diff --git a/gui/app/public/i18n/en/translation.ftl b/gui/app/public/i18n/en/translation.ftl index 2de194a04..11cb9988e 100644 --- a/gui/app/public/i18n/en/translation.ftl +++ b/gui/app/public/i18n/en/translation.ftl @@ -791,6 +791,9 @@ settings-interface-behavior-bvh_directory-label = Directory for BVH recordings settings-interface-behavior-skeleton_mesh = Skeleton preview style settings-interface-behavior-skeleton_mesh-description = Draw the body preview with solid 3D shapes instead of simple lines. Turn this off on low-end machines. settings-interface-behavior-skeleton_mesh-label = Use 3D shapes +settings-interface-behavior-controller_nav = Game controller navigation +settings-interface-behavior-controller_nav-description = Move focus around the interface with a game controller. The D-pad or left stick move between controls, A activates, B goes back. Only active while a controller is connected. +settings-interface-behavior-controller_nav-label = Navigate with a controller ## Serial settings settings-serial = USB Serial Console diff --git a/gui/app/src/App.tsx b/gui/app/src/App.tsx index 09e3a8ea7..1659cab90 100644 --- a/gui/app/src/App.tsx +++ b/gui/app/src/App.tsx @@ -44,6 +44,7 @@ import { AppLayout } from './AppLayout'; import { Preload } from './components/Preload'; import { UnknownDeviceModal } from './components/UnknownDeviceModal'; import { useDiscordPresence } from './hooks/discord-presence'; +import { useControllerNav } from './hooks/controller-nav'; import { withSentryReactRouterV6Routing } from '@sentry/react'; import { ScaledProportionsPage } from './components/onboarding/pages/body-proportions/ScaledProportions'; import { AdvancedSettings } from './components/settings/pages/AdvancedSettings'; @@ -74,6 +75,7 @@ const SentryRoutes = withSentryReactRouterV6Routing(Routes); function Layout() { const { isMobile } = useBreakpoint('mobile'); useDiscordPresence(); + useControllerNav(); return ( <> diff --git a/gui/app/src/components/EmptyLayout.tsx b/gui/app/src/components/EmptyLayout.tsx index 1b3de9483..142b3a642 100644 --- a/gui/app/src/components/EmptyLayout.tsx +++ b/gui/app/src/components/EmptyLayout.tsx @@ -5,10 +5,18 @@ import './EmptyLayout.scss'; export function EmptyLayout({ children }: { children: ReactNode }) { return (
-
+
-
+
{children}
diff --git a/gui/app/src/components/MainLayout.tsx b/gui/app/src/components/MainLayout.tsx index 321a730a6..7f7ea256a 100644 --- a/gui/app/src/components/MainLayout.tsx +++ b/gui/app/src/components/MainLayout.tsx @@ -63,14 +63,24 @@ export function MainLayout({ 'checklist-ok': completion === 'complete', })} > -
+
-
+
)} {full && ( -
+
)} {!isMobile && full && ( -
+
)} diff --git a/gui/app/src/components/Toolbar.tsx b/gui/app/src/components/Toolbar.tsx index 1eb0bf9b5..755706657 100644 --- a/gui/app/src/components/Toolbar.tsx +++ b/gui/app/src/components/Toolbar.tsx @@ -48,7 +48,10 @@ function ButtonProgress({ ); } -function BasicResetButton(options: UseResetOptions & { customName?: string }) { +function BasicResetButton({ + customName, + ...options +}: UseResetOptions & { customName?: string }) { const { isMd } = useBreakpoint('md'); const { triggerReset, @@ -63,7 +66,7 @@ function BasicResetButton(options: UseResetOptions & { customName?: string }) { const progress = status === 'counting' ? resetProress / duration : 0; - const name = options.customName || resetName; + const name = customName || resetName; const skiReset = options.type === ResetType.POSE_MOUNTING && options.group === 'default'; diff --git a/gui/app/src/components/commons/BaseModal.tsx b/gui/app/src/components/commons/BaseModal.tsx index 0d6f707bf..1e0cdcca2 100644 --- a/gui/app/src/components/commons/BaseModal.tsx +++ b/gui/app/src/components/commons/BaseModal.tsx @@ -1,6 +1,22 @@ import classNames from 'classnames'; import { ReactNode } from 'react'; import ReactModal from 'react-modal'; +import { collectFocusables } from '@/utils/focus-nav'; + +/** + * `react-modal` parks focus on its own `tabindex="-1"` content node, which is + * not something a user can act on. Runs a frame late to land after react-modal's + * own focus call, and leaves an explicit `autoFocus` in the content alone. + * + * FIXME: replace react-modal; its focus handling keeps forcing workarounds. + */ +function focusFirstControl(contentEl: HTMLDivElement) { + requestAnimationFrame(() => { + const active = document.activeElement; + if (active && active !== contentEl && contentEl.contains(active)) return; + collectFocusables(contentEl)[0]?.focus(); + }); +} export function BaseModal({ children, @@ -17,6 +33,10 @@ export function BaseModal({ return ( { + props.onAfterOpen?.(obj); + if (obj?.contentEl) focusFirstControl(obj.contentEl); + }} shouldCloseOnOverlayClick={closeable} shouldCloseOnEsc={closeable} overlayClassName={ diff --git a/gui/app/src/components/commons/Clickable.tsx b/gui/app/src/components/commons/Clickable.tsx index d48f5fd1e..634d3e84d 100644 --- a/gui/app/src/components/commons/Clickable.tsx +++ b/gui/app/src/components/commons/Clickable.tsx @@ -6,7 +6,7 @@ import { Typography } from './Typography'; type NativeButtonProps = Omit< ComponentProps<'button'>, - 'type' | 'aria-pressed' | 'aria-expanded' | 'aria-current' | 'aria-label' + 'aria-pressed' | 'aria-expanded' | 'aria-current' | 'aria-label' >; type CommonProps = { @@ -40,8 +40,8 @@ type LinkProps = CommonProps & /** * A clickable surface that keeps whatever styling you give it and only adds - * the semantics: tab focus, Enter/Space, and the `type="button"` that stops a - * `
diff --git a/gui/app/src/components/commons/IconButton.tsx b/gui/app/src/components/commons/IconButton.tsx index 13454ea0e..4cadbf1f4 100644 --- a/gui/app/src/components/commons/IconButton.tsx +++ b/gui/app/src/components/commons/IconButton.tsx @@ -10,8 +10,8 @@ type DistributiveOmit = T extends unknown * Icon-only button. `labelId` does double duty: it names the control for screen * readers and renders as the tooltip, so an icon never ships unlabelled. * - * The tooltip is on by default here — unlike `Clickable`, there is no visible - * text to fall back on. Pass `tooltip={false}` where it would just be noise. + * The tooltip is on by default here, since unlike `Clickable` there is no + * visible text to fall back on. Pass `tooltip={false}` where it would be noise. * * Inherits `Clickable`'s link mode: pass `to` and it renders a `NavLink`. */ diff --git a/gui/app/src/components/commons/NumberSelector.tsx b/gui/app/src/components/commons/NumberSelector.tsx index 631c6b624..395781908 100644 --- a/gui/app/src/components/commons/NumberSelector.tsx +++ b/gui/app/src/components/commons/NumberSelector.tsx @@ -2,8 +2,9 @@ import { Control, Controller, FieldPath, FieldValues } from 'react-hook-form'; import { Clickable } from './Clickable'; import { FieldCaption } from './FloatingLabel'; import { Typography } from './Typography'; -import { KeyboardEvent, useCallback, useMemo } from 'react'; +import { useCallback, useMemo } from 'react'; import { useLocaleConfig } from '@/i18n/config'; +import { stepKeys } from '@/utils/a11y'; export function NumberSelector({ label, @@ -67,33 +68,15 @@ export function NumberSelector({ !disabled && onChange(clamp(big ? doubleStepFn(value, add) : stepFn(value, add))); - const onKeyDown = (e: KeyboardEvent) => { - switch (e.key) { - case 'ArrowUp': - case 'ArrowRight': - bump(true); - break; - case 'ArrowDown': - case 'ArrowLeft': - bump(false); - break; - case 'PageUp': - bump(true, doubleStep !== undefined); - break; - case 'PageDown': - bump(false, doubleStep !== undefined); - break; - case 'Home': - if (!disabled) onChange(min); - break; - case 'End': - if (!disabled) onChange(max); - break; - default: - return; - } - e.preventDefault(); - }; + const onKeyDown = stepKeys({ + value: Number(value), + min, + max, + step: stepFn, + bigStep: doubleStep !== undefined ? doubleStepFn : undefined, + onChange, + disabled, + }); // Flat full-height stepper segments hugging the box edges. const segment = @@ -103,6 +86,7 @@ export function NumberSelector({ {hasLabel && {label}}
({ control, @@ -22,51 +23,70 @@ export function Range({ ( - - )} + render={({ field: { onChange, ref, name, value } }) => { + const emit = (v: number) => + onChange( + Math.min( + max, + Math.max(min, min + Math.round((v - min) / step) * step) + ) + ); + + const onKeyDown = stepKeys({ + value: Number(value), + min, + max, + step, + onChange: emit, + }); + return ( + + ); + }} /> ); } diff --git a/gui/app/src/components/commons/TogglePill.tsx b/gui/app/src/components/commons/TogglePill.tsx index 8e2c79f56..e5a2a2ad5 100644 --- a/gui/app/src/components/commons/TogglePill.tsx +++ b/gui/app/src/components/commons/TogglePill.tsx @@ -1,6 +1,6 @@ import classNames from 'classnames'; import { Clickable } from './Clickable'; -import { KeyboardEvent, ReactNode } from 'react'; +import { ReactNode } from 'react'; import { Typography } from './Typography'; export function TogglePill({ @@ -8,14 +8,14 @@ export function TogglePill({ onClick, pressed, label, - radiogroupLabel, + value, children, }: { compact?: boolean; onClick?: () => void; pressed?: boolean; label?: string; - radiogroupLabel?: string; + value?: string; children: ReactNode; }) { const className = classNames( @@ -24,26 +24,15 @@ export function TogglePill({ compact ? 'p-0.5' : 'p-1' ); - if (radiogroupLabel !== undefined) { - return ( -
- {children} -
- ); - } - if (!onClick) return
{children}
; + const name = label && value ? `${label}: ${value}` : label; + return ( {children} @@ -51,50 +40,18 @@ export function TogglePill({ ); } -function handleRadioKeys(e: KeyboardEvent) { - const step: Record = { - ArrowRight: 1, - ArrowDown: 1, - ArrowLeft: -1, - ArrowUp: -1, - }; - if (!(e.key in step) && e.key !== 'Home' && e.key !== 'End') return; - - const radios = Array.from( - e.currentTarget.querySelectorAll( - '[role="radio"]:not([disabled])' - ) - ); - const current = radios.indexOf(document.activeElement as HTMLElement); - if (current < 0) return; - - e.preventDefault(); - const last = radios.length - 1; - const next = - e.key === 'Home' - ? 0 - : e.key === 'End' - ? last - : (current + step[e.key] + radios.length) % radios.length; - - radios[next].focus(); - radios[next].click(); -} - export function TogglePillOption({ compact, dotClass, labelId, active, onClick, - radio, }: { compact?: boolean; dotClass: string; labelId: string; active?: boolean; onClick?: () => void; - radio?: boolean; }) { const className = classNames( 'flex items-center rounded-full', @@ -118,20 +75,6 @@ export function TogglePillOption({ if (!onClick) return
{content}
; - if (radio) { - return ( - - {content} - - ); - } - return ( {content} diff --git a/gui/app/src/components/home/GroupTelemetryOverlay.tsx b/gui/app/src/components/home/GroupTelemetryOverlay.tsx index d5d16a6e1..cd59552a3 100644 --- a/gui/app/src/components/home/GroupTelemetryOverlay.tsx +++ b/gui/app/src/components/home/GroupTelemetryOverlay.tsx @@ -5,7 +5,8 @@ import { useLocalization } from '@fluent/react'; import { ConnectionGroupIcon } from '@/components/tracker/TrackerConnectionGroup'; import { DongleStatus } from 'solarxr-protocol'; import { CrossIcon } from '@/components/commons/icon/CrossIcon'; -import { useEffect } from 'react'; +import { useEffect, useRef } from 'react'; +import { collectFocusables } from '@/utils/focus-nav'; export function GroupTelemetryOverlay({ group, @@ -15,6 +16,8 @@ export function GroupTelemetryOverlay({ onClose: () => void; }) { const { l10n } = useLocalization(); + const panelRef = useRef(null); + const isOpen = !!group; useEffect(() => { const handleKeyDown = (e: KeyboardEvent) => { @@ -26,6 +29,14 @@ export function GroupTelemetryOverlay({ return () => window.removeEventListener('keydown', handleKeyDown); }, [onClose]); + useEffect(() => { + if (!isOpen) return; + const restoreTo = document.activeElement as HTMLElement | null; + const panel = panelRef.current; + if (panel) (collectFocusables(panel)[0] ?? panel).focus(); + return () => restoreTo?.focus(); + }, [isOpen]); + if (!group) return null; const trackers = [...group.assigned, ...group.unassigned]; @@ -44,7 +55,14 @@ export function GroupTelemetryOverlay({ onClick={onClose} /> -
+
-
+
-
+
{children}
( onChange(value)} labelId={'body_part-' + BodyPart[descriptor.sides[value].root]} /> ); @@ -310,7 +302,11 @@ export function ExtremitySideToggle({ return ( onChange(side === 'left' ? 'right' : 'left')} + label={l10n.getString('onboarding-assign_trackers-side')} + value={l10n.getString( + 'body_part-' + BodyPart[descriptor.sides[side].root] + )} > {option('left', 'outline-assign-left')} {option('right', 'outline-assign-right')} @@ -338,10 +334,12 @@ function DragBodyPartCard({ connector = true, labelId, }: PartCardProps) { - const { armedPart, selectPart, handleDropTracker } = useAssignment(); + const { armedPart, selectPart, handleDropTracker, pendingTrackerId } = + useAssignment(); const isHovering = trackerDrag.useIsDragHovering(role); - const isDragActive = trackerDrag.useIsDragActive(); - const { dragProps, isDragging } = trackerDrag.useDraggable( + const isTargeting = + trackerDrag.useIsDragActive() || pendingTrackerId !== null; + const { dragProps, tapProps, isDragging } = trackerDrag.useDraggable( td ? { trackerId: td.tracker.trackerId, @@ -351,22 +349,18 @@ function DragBodyPartCard({ (bodyPart) => { if (td) handleDropTracker(td.tracker.trackerId, bodyPart ?? BodyPart.NONE); - } + }, + () => selectPart(role) ); - const onClick = (event: MouseEvent) => { - dragProps.onClick(event); - if (event.defaultPrevented) return; - selectPart(role); - }; - return (
selectTracker(td.tracker.trackerId)} onDrop={(bodyPart) => handleDropTracker(td.tracker.trackerId, bodyPart) } @@ -347,6 +351,8 @@ export function DraggableTracker({ trackerId, label, onDrop, + onSelect, + selected, className, style, children, @@ -354,20 +360,29 @@ export function DraggableTracker({ trackerId: number; label: string; onDrop: (bodyPart: BodyPart | null) => void; + onSelect?: () => void; + selected?: boolean; className?: string; style?: CSSProperties; children: ReactNode; }) { const isBeingDragged = useIsTrackerBeingDragged(trackerId); - const { dragProps } = trackerDrag.useDraggable({ trackerId, label }, onDrop); + const { dragProps, tapProps } = trackerDrag.useDraggable( + { trackerId, label }, + onDrop, + onSelect + ); return (
void; + onSelect?: () => void; + selected?: boolean; }) { return ( { if (bodyPart !== null && bodyPart !== BodyPart.NONE) onDrop(bodyPart); }} diff --git a/gui/app/src/components/settings/SettingsLayout.tsx b/gui/app/src/components/settings/SettingsLayout.tsx index 2c564097a..c37d8409f 100644 --- a/gui/app/src/components/settings/SettingsLayout.tsx +++ b/gui/app/src/components/settings/SettingsLayout.tsx @@ -103,16 +103,30 @@ export function SettingsLayout({ children }: { children: ReactNode }) { return ( <>
-
+
-
+
-
+
diff --git a/gui/app/src/components/settings/pages/InterfaceSettings.tsx b/gui/app/src/components/settings/pages/InterfaceSettings.tsx index 1529b55d0..08126ab04 100644 --- a/gui/app/src/components/settings/pages/InterfaceSettings.tsx +++ b/gui/app/src/components/settings/pages/InterfaceSettings.tsx @@ -34,6 +34,7 @@ interface InterfaceSettingsForm { errorTracking: boolean; bvhDirectory: string | null; skeletonMesh: boolean; + controllerNav: boolean; }; notifications: { watchNewDevices: boolean; @@ -77,6 +78,7 @@ export function InterfaceSettings() { skeletonMesh: (config?.skeletonPreviewStyle ?? defaultConfig.skeletonPreviewStyle) === 'mesh', + controllerNav: config?.controllerNav ?? defaultConfig.controllerNav, }, developer: { enabled: config?.debug ?? defaultConfig.debug, @@ -153,6 +155,7 @@ export function InterfaceSettings() { errorTracking: values.behavior.errorTracking, bvhDirectory: values.behavior.bvhDirectory, skeletonPreviewStyle: values.behavior.skeletonMesh ? 'mesh' : 'lines', + controllerNav: values.behavior.controllerNav, debug: values.developer.enabled, devSettings: values.developer, @@ -360,6 +363,28 @@ export function InterfaceSettings() { />
+ + {l10n.getString('settings-interface-behavior-controller_nav')} + +
+ + {l10n.getString( + 'settings-interface-behavior-controller_nav-description' + )} + +
+
+ +
+ {l10n.getString('settings-general-interface-dev_mode')} diff --git a/gui/app/src/hooks/config.ts b/gui/app/src/hooks/config.ts index 3ea5ac9d6..25b1cc2b8 100644 --- a/gui/app/src/hooks/config.ts +++ b/gui/app/src/hooks/config.ts @@ -70,6 +70,7 @@ export interface Config { lastUsedProportions: 'manual' | 'autobone' | 'scaled' | null; dontShowUdevModal: boolean; collapsedConnectionGroups: Record; + controllerNav: boolean; } export interface ConfigContext { @@ -105,6 +106,7 @@ export const defaultConfig: Config = { lastUsedProportions: null, dontShowUdevModal: false, collapsedConnectionGroups: {}, + controllerNav: true, }; const localStore: CrossStorage = { diff --git a/gui/app/src/hooks/controller-nav.ts b/gui/app/src/hooks/controller-nav.ts new file mode 100644 index 000000000..cd48dc148 --- /dev/null +++ b/gui/app/src/hooks/controller-nav.ts @@ -0,0 +1,324 @@ +import { useEffect } from 'react'; +import { useLocation } from 'react-router-dom'; +import { + ARROW_KEY, + firstFocusable, + pickBest, + scrollableToward, + synthKey, + type Direction, +} from '@/utils/focus-nav'; +import { + BUTTON_A, + BUTTON_B, + decodeInput, + pressedDirections, + resolveStick, +} from '@/utils/gamepad'; +import { useConfig } from './config'; + +const ACTIVE_CLASS = 'controller-active'; +const EDIT_CLASS = 'nav-editing'; + +const ARROW_OWNER = '[aria-expanded="true"],[data-nav-arrows]'; +const EDIT_WIDGET = '[data-nav-edit]'; + +const REPEAT_DELAY_MS = 400; +const REPEAT_INTERVAL_MS = 120; +/** How long to keep looking for a control to start on after a page change. */ +const SEED_TIMEOUT_MS = 1500; +/** How long to wait for a swapped-in layout to bring its navbar back. */ +const SHELL_RESTORE_GRACE_MS = 400; + +const nav = { + origin: null as DOMRect | null, + /** Shell link the cursor followed, so a remount can put it back on it. */ + shellHref: null as string | null, + shellArea: null as string | null, + editing: null as HTMLElement | null, + held: new Map(), + prevButtons: new Set(), + stickDir: null as Direction | null, + pads: new Set(), + rafId: 0, + listening: false, + starts: 0, +}; + +function markActive() { + document.documentElement.classList.add(ACTIVE_CLASS); +} + +function isActive() { + return document.documentElement.classList.contains(ACTIVE_CLASS); +} + +function enterEdit(el: HTMLElement) { + nav.editing = el; + el.classList.add(EDIT_CLASS); +} + +function exitEdit() { + nav.editing?.classList.remove(EDIT_CLASS); + nav.editing = null; +} + +function clearActive() { + document.documentElement.classList.remove(ACTIVE_CLASS); + exitEdit(); +} + +function resetHeld() { + nav.held.clear(); + nav.prevButtons.clear(); + nav.stickDir = null; +} + +/** Whether the cursor is already somewhere real. */ +function placed(): boolean { + const active = document.activeElement; + return !!active && active !== document.body; +} + +/** + * The link `href` in shell area `area`. Scoped to the area because an href is + * not unique: the top bar logo and the navbar's Home entry both point at the + * root, and the logo comes first in the DOM. + */ +function shellLink(href: string, area: string | null): HTMLElement | null { + const escaped = href.replace(/["\\]/g, '\\$&'); + const scope = area + ? `[data-nav-area="${area.replace(/["\\]/g, '\\$&')}"]` + : '[data-nav-region="shell"]'; + return document.querySelector(`${scope} a[href="${escaped}"]`); +} + +/** + * Put the cursor somewhere sensible after arriving on a page. + * + * It has to wait a bit to try to look for the same component just in case a page load happen + * Usually is needed for the navbar, since a change of layout would destroy and re-create + * the whole navbar + */ +function placeCursorSoon(start = performance.now(), previous?: HTMLElement) { + if (placed()) return; + const elapsed = performance.now() - start; + + if (nav.shellHref) { + const link = shellLink(nav.shellHref, nav.shellArea); + if (link) { + link.focus({ preventScroll: true }); + return; + } + if (elapsed < SHELL_RESTORE_GRACE_MS) { + requestAnimationFrame(() => placeCursorSoon(start, previous)); + return; + } + } + + const target = firstFocusable(); + const expired = elapsed >= SEED_TIMEOUT_MS; + if (target && (target === previous || expired)) { + target.focus({ preventScroll: true }); + return; + } + if (expired) return; + requestAnimationFrame(() => placeCursorSoon(start, target)); +} + +function doMove(dir: Direction) { + markActive(); + const active = document.activeElement as HTMLElement | null; + + if (nav.editing) { + if (active === nav.editing) { + synthKey(nav.editing, ARROW_KEY[dir]); + return; + } + exitEdit(); + } + + if (!active || active === document.body) { + const resumed = nav.origin && pickBest(nav.origin, dir); + (resumed || firstFocusable())?.focus({ preventScroll: true }); + return; + } + + if (active.closest(ARROW_OWNER) && synthKey(active, ARROW_KEY[dir])) return; + + const target = pickBest(active.getBoundingClientRect(), dir, active); + + // Scroll the region the cursor sits in rather than leaving it early. + const scroller = scrollableToward(active, dir); + if (scroller && (!target || !scroller.contains(target))) { + const vertical = dir === 'up' || dir === 'down'; + const span = vertical ? scroller.clientHeight : scroller.clientWidth; + const by = (dir === 'up' || dir === 'left' ? -1 : 1) * (span * 0.6); + scroller.scrollBy(vertical ? { top: by } : { left: by }); + return; + } + + if (target) { + target.focus({ preventScroll: true }); + target.scrollIntoView({ block: 'nearest', inline: 'nearest' }); + } +} + +function doActivate() { + markActive(); + const active = document.activeElement as HTMLElement | null; + if (!active) return; + if (nav.editing) return exitEdit(); + if (active.matches(EDIT_WIDGET)) return enterEdit(active); + if (active.getAttribute('aria-disabled') === 'true') return; + + const shell = active.closest('[data-nav-region="shell"]'); + nav.shellHref = shell ? active.getAttribute('href') : null; + nav.shellArea = shell?.dataset.navArea ?? null; + + if (!synthKey(active, 'Enter')) active.click(); +} + +function doBack() { + markActive(); + if (nav.editing) return exitEdit(); + synthKey(document.activeElement, 'Escape'); +} + +function pressDir(dir: Direction, now: number) { + const state = nav.held.get(dir); + if (!state) { + nav.held.set(dir, { firedAt: now, repeating: false }); + doMove(dir); + } else if (!state.repeating && now - state.firedAt >= REPEAT_DELAY_MS) { + state.repeating = true; + state.firedAt = now; + doMove(dir); + } else if (state.repeating && now - state.firedAt >= REPEAT_INTERVAL_MS) { + state.firedAt = now; + doMove(dir); + } +} + +function poll() { + const now = performance.now(); + const frame = decodeInput(navigator.getGamepads()); + + nav.stickDir = resolveStick(frame.axX, frame.axY, nav.stickDir); + const pressedDirs = pressedDirections(frame, nav.stickDir); + + const { buttons } = frame; + if (buttons.has(BUTTON_A) && !nav.prevButtons.has(BUTTON_A)) doActivate(); + if (buttons.has(BUTTON_B) && !nav.prevButtons.has(BUTTON_B)) doBack(); + nav.prevButtons = buttons; + + for (const dir of pressedDirs) pressDir(dir, now); + for (const dir of Array.from(nav.held.keys())) { + if (!pressedDirs.has(dir)) nav.held.delete(dir); + } + + nav.rafId = nav.pads.size > 0 ? requestAnimationFrame(poll) : 0; +} + +function startLoop() { + if (!nav.rafId) nav.rafId = requestAnimationFrame(poll); +} + +function onConnect(e: GamepadEvent) { + const wasEmpty = nav.pads.size === 0; + nav.pads.add(e.gamepad.index); + if (wasEmpty) activateListeners(); + startLoop(); + markActive(); + nav.shellHref = null; + placeCursorSoon(); +} + +function onDisconnect(e: GamepadEvent) { + nav.pads.delete(e.gamepad.index); + if (nav.pads.size === 0) deactivateListeners(); +} + +function onInterrupt() { + resetHeld(); +} + +function onUserInput(e: Event) { + if (!e.isTrusted) return; + clearActive(); +} + +/** Focus is still measurable during the blur, so a later move can resume. */ +function onFocusOut(e: FocusEvent) { + const el = e.target as HTMLElement | null; + if (!el || el === document.body || !el.getClientRects().length) return; + nav.origin = el.getBoundingClientRect(); +} + +function activateListeners() { + if (nav.listening) return; + nav.listening = true; + document.addEventListener('focusout', onFocusOut, true); + window.addEventListener('pointerdown', onUserInput, true); + window.addEventListener('keydown', onUserInput, true); +} + +function deactivateListeners() { + if (!nav.listening) return; + nav.listening = false; + document.removeEventListener('focusout', onFocusOut, true); + window.removeEventListener('pointerdown', onUserInput, true); + window.removeEventListener('keydown', onUserInput, true); + clearActive(); +} + +function start() { + if (++nav.starts > 1) return; + if (typeof navigator === 'undefined' || !navigator.getGamepads) return; + + window.addEventListener('gamepadconnected', onConnect); + window.addEventListener('gamepaddisconnected', onDisconnect); + window.addEventListener('blur', onInterrupt); + document.addEventListener('visibilitychange', onInterrupt); + + for (const pad of navigator.getGamepads()) { + if (pad) nav.pads.add(pad.index); + } + if (nav.pads.size) { + activateListeners(); + startLoop(); + } +} + +function stop() { + if (--nav.starts > 0) return; + + if (nav.rafId) cancelAnimationFrame(nav.rafId); + nav.rafId = 0; + window.removeEventListener('gamepadconnected', onConnect); + window.removeEventListener('gamepaddisconnected', onDisconnect); + window.removeEventListener('blur', onInterrupt); + document.removeEventListener('visibilitychange', onInterrupt); + deactivateListeners(); + resetHeld(); + nav.pads.clear(); + nav.origin = null; +} + +export function useControllerNav() { + const { config } = useConfig(); + const location = useLocation(); + const enabled = config?.controllerNav !== false; + + useEffect(() => { + if (!enabled) return; + start(); + return stop; + }, [enabled]); + + useEffect(() => { + nav.origin = null; + if (!enabled || !isActive()) return; + placeCursorSoon(); + }, [location.pathname, enabled]); +} diff --git a/gui/app/src/hooks/pointer-drag.ts b/gui/app/src/hooks/pointer-drag.ts index 584a815a6..de4e9016f 100644 --- a/gui/app/src/hooks/pointer-drag.ts +++ b/gui/app/src/hooks/pointer-drag.ts @@ -1,6 +1,14 @@ import { atom, useAtomValue, useSetAtom } from 'jotai'; import { selectAtom } from 'jotai/utils'; -import { MouseEvent, PointerEvent, useEffect, useRef, useState } from 'react'; +import { + KeyboardEvent as ReactKeyboardEvent, + MouseEvent, + PointerEvent, + useEffect, + useRef, + useState, +} from 'react'; +import { a11yClick } from '@/utils/a11y'; const DRAG_THRESHOLD = 6; @@ -38,8 +46,18 @@ export const createPointerDrag = (codec: DropTargetCodec) => { [codec.attribute]: codec.serialize(target), }); - /** A null payload means there is nothing to drag here. */ - const useDraggable = (payload: P | null, onDrop: (target: T | null) => void) => { + /** + * A null payload means there is nothing to drag here. + * + * Passing `onTap` also makes the surface activatable: it fires on a click + * that was not the tail of a drag, and on Enter or Space via the returned + * `tapProps` (spread those onto the element alongside `dragProps`). + */ + const useDraggable = ( + payload: P | null, + onDrop: (target: T | null) => void, + onTap?: () => void + ) => { const setDrag = useSetAtom(stateAtom); const [start, setStart] = useState<{ x: number; y: number } | null>(null); const [isDragging, setIsDragging] = useState(false); @@ -94,7 +112,9 @@ export const createPointerDrag = (codec: DropTargetCodec) => { suppressNextClickRef.current = false; e.preventDefault(); e.stopPropagation(); + return; } + onTap?.(); }; useEffect(() => { @@ -115,6 +135,17 @@ export const createPointerDrag = (codec: DropTargetCodec) => { onPointerCancel, onClick, }, + tapProps: onTap + ? { + role: 'button', + tabIndex: 0, + onKeyDown: (e: ReactKeyboardEvent) => { + if (!a11yClick(e)) return; + e.preventDefault(); + onTap(); + }, + } + : undefined, isDragging, }; }; diff --git a/gui/app/src/utils/a11y.ts b/gui/app/src/utils/a11y.ts index 084f246b8..444df5253 100644 --- a/gui/app/src/utils/a11y.ts +++ b/gui/app/src/utils/a11y.ts @@ -4,18 +4,85 @@ import { error } from './logging'; // :focus-visible outline). These two cover cases that a global rule can't: // FOCUS_RING_PEER - the real focus target is a visually-hidden `peer` input. // FOCUS_RING_WITHIN - the ring belongs on a wrapper, keyed off a focused child. +// The `.controller-active` variants drop the `-visible` requirement, since +// gamepad navigation focuses programmatically and never sets :focus-visible. export const FOCUS_RING_PEER = - 'peer-focus:ring-0 peer-focus-visible:outline-none peer-focus-visible:ring-2 peer-focus-visible:ring-accent-background-10'; + 'peer-focus:ring-0 peer-focus-visible:outline-none peer-focus-visible:ring-2 peer-focus-visible:ring-accent-background-10 ' + + '[.controller-active_&]:peer-focus:ring-2 [.controller-active_&]:peer-focus:ring-accent-background-10'; export const FOCUS_RING_WITHIN = - 'has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-accent-background-10'; + 'has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-accent-background-10 ' + + '[.controller-active_&]:has-[:focus]:ring-2 [.controller-active_&]:has-[:focus]:ring-accent-background-10'; -export function a11yClick(event: React.KeyboardEvent | React.MouseEvent) { +export function a11yClick(event: React.KeyboardEvent | React.MouseEvent): boolean { if (event.type === 'click') { return true; } else if (event.type === 'keydown') { const keyboard = event as React.KeyboardEvent; return keyboard.key === 'Enter' || keyboard.key === ' '; } + return false; +} + +/** Number, or a custom stepper returning the next value from the current one. */ +export type Step = number | ((value: number, add: boolean) => number); + +/** + * Arrow / Home / End / PageUp / PageDown handling for numeric widgets. Clamps + * to `[min, max]` and only ever hands `onChange` a number. Without a `bigStep`, + * PageUp and PageDown fall back to `step`. + */ +export function stepKeys({ + value, + min, + max, + step, + bigStep, + onChange, + disabled, +}: { + value: number; + min: number; + max: number; + step: Step; + bigStep?: Step; + onChange: (value: number) => void; + disabled?: boolean; +}) { + const apply = (by: Step, add: boolean) => + typeof by === 'number' ? value + (add ? by : -by) : by(value, add); + + return (e: React.KeyboardEvent) => { + if (disabled) return; + + let next: number; + switch (e.key) { + case 'ArrowUp': + case 'ArrowRight': + next = apply(step, true); + break; + case 'ArrowDown': + case 'ArrowLeft': + next = apply(step, false); + break; + case 'PageUp': + next = apply(bigStep ?? step, true); + break; + case 'PageDown': + next = apply(bigStep ?? step, false); + break; + case 'Home': + next = min; + break; + case 'End': + next = max; + break; + default: + return; + } + + e.preventDefault(); + onChange(Math.min(max, Math.max(min, +next.toFixed(4)))); + }; } export function waitUntil( diff --git a/gui/app/src/utils/focus-nav.ts b/gui/app/src/utils/focus-nav.ts new file mode 100644 index 000000000..081cbf74e --- /dev/null +++ b/gui/app/src/utils/focus-nav.ts @@ -0,0 +1,262 @@ +/** + * Spatial focus navigation over the DOM: which elements can take focus, and + * which one lies nearest in a given direction. No input-device knowledge and no + * state, so it is driven by whatever wants to move a cursor around. + */ + +export type Direction = 'up' | 'down' | 'left' | 'right'; + +/** Everything a user can put focus on. */ +export const FOCUSABLE_SELECTOR = [ + 'a[href]', + 'button', + 'input:not([type="hidden"])', + 'select', + 'textarea', + '[tabindex]:not([tabindex="-1"])', + '[role="button"]', + '[role="link"]', + '[role="menuitem"]', + '[role="radio"]', + '[role="tab"]', + '[role="checkbox"]', + '[role="switch"]', + '[role="combobox"]', + '[role="spinbutton"]', + '[role="slider"]', +].join(','); + +export const ARROW_KEY: Record = { + up: 'ArrowUp', + down: 'ArrowDown', + left: 'ArrowLeft', + right: 'ArrowRight', +}; + +export function isFocusable(el: HTMLElement): boolean { + // Natively disabled elements cannot take focus at all, so there is nothing to + // aim at. `aria-disabled` ones can, and should: a control that is off for a + // reason usually carries a tooltip saying why, and that is worth reaching. + if ((el as HTMLButtonElement).disabled) return false; + // Radios are exempt from the tabindex check: a browser reports -1 for the + // unchecked members of a group, but the cursor still has to reach them. + const isRadio = el.tagName === 'INPUT' && (el as HTMLInputElement).type === 'radio'; + if (el.tabIndex < 0 && !isRadio) return false; + if (el.closest('[aria-hidden="true"], [inert]')) return false; + if (el.hasAttribute('hidden')) return false; + if (el.getClientRects().length === 0) return false; + const cs = getComputedStyle(el); + if (cs.visibility === 'hidden' || cs.visibility === 'collapse') return false; + if (cs.display === 'contents') return false; + return true; +} + +export function collectFocusables(root: ParentNode = document): HTMLElement[] { + return Array.from(root.querySelectorAll(FOCUSABLE_SELECTOR)).filter( + isFocusable + ); +} + +/** + * A layout marks each of its areas `data-nav-region="page"` or `"shell"`, shell + * meaning the furniture around the content: top bar, navbar, settings sidebar. + * + * Two things come from that. The cursor starts in a page region rather than in + * the shell, and a move prefers to stay in the region it began in. Areas are + * marked one by one because a grid places them as siblings, so there is no + * wrapper to point at, and because the navbar and the top bar have to count as + * different regions even though both are shell. + */ +export function pageRegions(): HTMLElement[] { + return Array.from(document.querySelectorAll('[data-nav-region="page"]')); +} + +/** + * Visible right now, as opposed to merely present. Something scrolled above the + * viewport reports a negative `top` and would win "topmost"; something inside a + * collapsed panel still reports a full-size rect while clipped to nothing. + */ +function onScreen(el: HTMLElement, r: DOMRect): boolean { + if (r.bottom <= 0 || r.right <= 0) return false; + if (r.top >= window.innerHeight || r.left >= window.innerWidth) return false; + + for (let n = el.parentElement; n; n = n.parentElement) { + const cs = getComputedStyle(n); + if (cs.overflowX === 'visible' && cs.overflowY === 'visible') continue; + const b = n.getBoundingClientRect(); + if (b.width < 1 || b.height < 1) return false; + if (r.bottom <= b.top || r.top >= b.bottom) return false; + if (r.right <= b.left || r.left >= b.right) return false; + } + return true; +} + +/** + * Where the cursor starts. `data-nav-entry` is how a page says so, because the + * starting control is a design decision rather than something derivable. + * + * Without one, fall back to topmost then leftmost of the page's visible + * controls. Geometric rather than DOM order, since a grid places its areas in + * whatever order the template says: in the main layout the toolbar renders + * after the content yet sits above it. + * + * Returns nothing when the page has no visible controls yet, meaning it is + * still rendering. + */ +export function firstFocusable(): HTMLElement | undefined { + const entry = document.querySelector('[data-nav-entry]'); + if (entry) { + if (isFocusable(entry)) return entry; + const inside = collectFocusables(entry)[0]; + if (inside) return inside; + } + + const regions = pageRegions(); + const visible = ( + regions.length + ? regions.flatMap((region) => collectFocusables(region)) + : collectFocusables() + ) + .map((el) => ({ el, r: el.getBoundingClientRect() })) + .filter(({ el, r }) => onScreen(el, r)); + if (!visible.length) return undefined; + + // The topmost control need not be the first one: a header row is usually + // `items-center`, so a taller right-aligned action sits a few pixels above + // the rest of its row. Rows are found by vertical overlap for that reason, + // never by a pixel threshold, and the leftmost of the first row wins. + const highest = visible.reduce((a, b) => (b.r.top < a.r.top ? b : a)); + const firstRow = visible.filter( + ({ r }) => r.top < highest.r.bottom && r.bottom > highest.r.top + ); + return firstRow.reduce((a, b) => (b.r.left < a.r.left ? b : a)).el; +} + +/** + * Best focus target from origin rect `o` moving in `dir`, or null. `from` is the + * element the move starts at, excluded from the results. + * + * Candidates are ranked by region before distance: the region the move started + * in, then any page region, then the shell. The top bar spans the window and the + * navbar runs its full height, so on distance alone either one steals moves that + * had a perfectly good target in the page. Every region stays reachable, just + * only once the better-ranked ones have nothing left in the travel direction. + */ +export function pickBest( + o: DOMRect, + dir: Direction, + from?: Element | null +): HTMLElement | null { + const oCx = o.left + o.width / 2; + const oCy = o.top + o.height / 2; + const horizontal = dir === 'left' || dir === 'right'; + + const regionOf = (el: Element) => el.closest('[data-nav-region]'); + // Null origin region means there is nothing to compare against, as when + // resuming from a remembered rect whose element is long gone. + const originRegion = from ? regionOf(from) : null; + const rankOf = (el: Element) => { + const region = regionOf(el); + if (originRegion && region === originRegion) return 0; + return region?.getAttribute('data-nav-region') === 'page' ? 1 : 2; + }; + + let best: HTMLElement | null = null; + let bestScore = Infinity; + let bestRank = Infinity; + + for (const el of collectFocusables()) { + if (el === from) continue; + const c = el.getBoundingClientRect(); + if (c.width === 0 && c.height === 0) continue; + const cCx = c.left + c.width / 2; + const cCy = c.top + c.height / 2; + + // Must lie strictly in the travel direction. + let primaryGap: number; + if (dir === 'right') { + if (c.left < o.right - 2 || cCx <= oCx) continue; + primaryGap = c.left - o.right; + } else if (dir === 'left') { + if (c.right > o.left + 2 || cCx >= oCx) continue; + primaryGap = o.left - c.right; + } else if (dir === 'down') { + if (c.top < o.bottom - 2 || cCy <= oCy) continue; + primaryGap = c.top - o.bottom; + } else { + if (c.bottom > o.top + 2 || cCy >= oCy) continue; + primaryGap = o.top - c.bottom; + } + primaryGap = Math.max(0, primaryGap); + + const [oStart, oEnd, cStart, cEnd] = horizontal + ? [o.top, o.bottom, c.top, c.bottom] + : [o.left, o.right, c.left, c.right]; + const overlapLen = Math.max(0, Math.min(oEnd, cEnd) - Math.max(oStart, cStart)); + const crossGap = + overlapLen > 0 ? 0 : Math.max(oStart, cStart) - Math.min(oEnd, cEnd); + const overlapRatio = + overlapLen / Math.max(1, Math.min(oEnd - oStart, cEnd - cStart)); + + // Candidates that only touch at a corner. + if (primaryGap <= 2 && overlapRatio === 0) continue; + + const euclid = Math.hypot(cCx - oCx, cCy - oCy); + const score = + primaryGap * 1 + crossGap * 2 + euclid * 0.25 + (1 - overlapRatio) * 100; + + const rank = rankOf(el); + if (rank > bestRank) continue; + if (rank === bestRank && score >= bestScore) continue; + best = el; + bestScore = score; + bestRank = rank; + } + + return best; +} + +/** + * Nearest ancestor of `el` that scrolls along `dir`'s axis and is not already + * at its edge that way. + */ +export function scrollableToward(el: HTMLElement, dir: Direction): HTMLElement | null { + const vertical = dir === 'up' || dir === 'down'; + for (let n = el.parentElement; n; n = n.parentElement) { + const overflow = vertical + ? getComputedStyle(n).overflowY + : getComputedStyle(n).overflowX; + if (overflow !== 'auto' && overflow !== 'scroll') continue; + const pos = vertical ? n.scrollTop : n.scrollLeft; + const span = vertical ? n.clientHeight : n.clientWidth; + const max = vertical + ? n.scrollHeight - n.clientHeight + : n.scrollWidth - n.clientWidth; + // `overflow-y: auto` makes the computed `overflow-x` auto as well, so a + // plain vertical column looks sideways-scrollable for the few pixels a + // scrollbar or a scaled child adds. Require real distance, or the column + // swallows every horizontal move made inside it. + if (max <= Math.max(8, span * 0.1)) continue; + const atEdge = dir === 'up' || dir === 'left' ? pos <= 1 : pos >= max - 1; + if (!atEdge) return n; + } + return null; +} + +/** + * Dispatch a real keydown so widgets run their own logic. `code` matters to + * handlers that read it, such as the keybind recorder. + * + * @returns whether something consumed it. + */ +export function synthKey(target: EventTarget | null, key: string): boolean { + if (!target) return false; + const ev = new KeyboardEvent('keydown', { + key, + code: key, + bubbles: true, + cancelable: true, + }); + target.dispatchEvent(ev); + return ev.defaultPrevented; +} diff --git a/gui/app/src/utils/gamepad.ts b/gui/app/src/utils/gamepad.ts new file mode 100644 index 000000000..3754b87c5 --- /dev/null +++ b/gui/app/src/utils/gamepad.ts @@ -0,0 +1,71 @@ +import type { Direction } from './focus-nav'; + +export const BUTTON_A = 0; +export const BUTTON_B = 1; + +const DPAD: Record = { + 12: 'up', + 13: 'down', + 14: 'left', + 15: 'right', +}; + +const DEADZONE_ENTER = 0.35; +const DEADZONE_EXIT = 0.25; +/** How far the other axis must lead before a diagonal hold switches axis. */ +const AXIS_SWITCH_RATIO = 1.4; + +export interface GamepadFrame { + buttons: Set; + axX: number; + axY: number; +} + +export function decodeInput(pads: (Gamepad | null)[]): GamepadFrame { + const buttons = new Set(); + const stronger = (a: number, b: number) => (Math.abs(a) > Math.abs(b) ? a : b); + let axX = 0; + let axY = 0; + + for (const pad of pads) { + if (!pad) continue; + pad.buttons.forEach((b, i) => b.pressed && buttons.add(i)); + axX = stronger(pad.axes[0] ?? 0, axX); + axY = stronger(pad.axes[1] ?? 0, axY); + } + return { buttons, axX, axY }; +} + +export function pressedDirections( + frame: GamepadFrame, + stickDir: Direction | null +): Set { + const dirs = new Set(); + for (const i of frame.buttons) if (DPAD[i]) dirs.add(DPAD[i]); + if (stickDir) dirs.add(stickDir); + return dirs; +} + +export function resolveStick( + axX: number, + axY: number, + prev: Direction | null +): Direction | null { + const ax = Math.abs(axX); + const ay = Math.abs(axY); + const mag = Math.max(ax, ay); + + if (mag < DEADZONE_EXIT) return null; + // Between the deadzones: hold what is committed, commit to nothing new. + if (mag < DEADZONE_ENTER && !prev) return null; + + const wasHoriz = prev === 'left' || prev === 'right'; + const wasVert = prev === 'up' || prev === 'down'; + const horiz = wasHoriz + ? ax * AXIS_SWITCH_RATIO >= ay + : wasVert + ? ax >= ay * AXIS_SWITCH_RATIO + : ax > ay; + + return horiz ? (axX > 0 ? 'right' : 'left') : axY > 0 ? 'down' : 'up'; +} diff --git a/gui/app/tailwind.config.ts b/gui/app/tailwind.config.ts index 329f16dfd..679b39767 100644 --- a/gui/app/tailwind.config.ts +++ b/gui/app/tailwind.config.ts @@ -371,6 +371,24 @@ const config = { outline: '2px solid rgb(var(--accent-background-10))', outlineOffset: '2px', }, + // Gamepad navigation: programmatic .focus() doesn't trigger + // :focus-visible, so force the same ring while a controller is driving. + 'html.controller-active :focus': { + outline: '2px solid rgb(var(--accent-background-10))', + outlineOffset: '2px', + }, + [`html.controller-active :is(${formEls}):focus`]: { + boxShadow: 'none', + outline: '2px solid rgb(var(--accent-background-10))', + outlineOffset: '2px', + }, + // "Edit mode": the cursor has stepped into a value widget and arrows + // now change its value. The extra `:focus` keeps this ahead of the + // plain focus rule above. + 'html.controller-active .nav-editing:focus': { + outline: '3px solid rgb(var(--accent-background-10))', + outlineOffset: '3px', + }, }); }), ],