mirror of
https://github.com/SlimeVR/SlimeVR-Server.git
synced 2026-11-24 02:51:20 -08:00
Controller navigation
This commit is contained in:
1 parent
280d5f8c1c
commit
c829bdc06e
25 files changed
+1060
-210
No files matched your search
@@ -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
|
||||
|
||||
@@ -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 (
|
||||
<>
|
||||
|
||||
@@ -5,10 +5,18 @@ import './EmptyLayout.scss';
|
||||
export function EmptyLayout({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<div className="empty-layout h-full">
|
||||
<div style={{ gridArea: 't' }}>
|
||||
<div
|
||||
data-nav-region="shell"
|
||||
data-nav-area="topbar"
|
||||
style={{ gridArea: 't' }}
|
||||
>
|
||||
<TopBar />
|
||||
</div>
|
||||
<div style={{ gridArea: 'c' }} className="mt-2 relative">
|
||||
<div
|
||||
data-nav-region="page"
|
||||
style={{ gridArea: 'c' }}
|
||||
className="mt-2 relative"
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -63,14 +63,24 @@ export function MainLayout({
|
||||
'checklist-ok': completion === 'complete',
|
||||
})}
|
||||
>
|
||||
<div style={{ gridArea: 't' }}>
|
||||
<div
|
||||
data-nav-region="shell"
|
||||
data-nav-area="topbar"
|
||||
style={{ gridArea: 't' }}
|
||||
>
|
||||
<TopBar />
|
||||
</div>
|
||||
<div style={{ gridArea: 'n' }} className="overflow-y-auto">
|
||||
<div
|
||||
data-nav-region="shell"
|
||||
data-nav-area="navbar"
|
||||
style={{ gridArea: 'n' }}
|
||||
className="overflow-y-auto"
|
||||
>
|
||||
<Navbar />
|
||||
</div>
|
||||
|
||||
<div
|
||||
data-nav-region="page"
|
||||
style={{ gridArea: 'c' }}
|
||||
className={classNames(
|
||||
'overflow-auto mr-2 my-2 mobile:m-0 [container-type:inline-size]',
|
||||
@@ -85,12 +95,12 @@ export function MainLayout({
|
||||
<TrackingChecklistMobile />
|
||||
)}
|
||||
{full && (
|
||||
<div style={{ gridArea: 'b' }}>
|
||||
<div data-nav-region="page" style={{ gridArea: 'b' }}>
|
||||
<Toolbar />
|
||||
</div>
|
||||
)}
|
||||
{!isMobile && full && (
|
||||
<div style={{ gridArea: 's' }} className="mr-2">
|
||||
<div data-nav-region="page" style={{ gridArea: 's' }} className="mr-2">
|
||||
<Sidebar />
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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 (
|
||||
<ReactModal
|
||||
{...props}
|
||||
onAfterOpen={(obj) => {
|
||||
props.onAfterOpen?.(obj);
|
||||
if (obj?.contentEl) focusFirstControl(obj.contentEl);
|
||||
}}
|
||||
shouldCloseOnOverlayClick={closeable}
|
||||
shouldCloseOnEsc={closeable}
|
||||
overlayClassName={
|
||||
|
||||
@@ -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
|
||||
* `<button>` submitting a surrounding form.
|
||||
* the semantics: tab focus, Enter/Space, and a default `type="button"` so a
|
||||
* `<button>` does not submit a surrounding form unless asked to.
|
||||
*
|
||||
* Pass `to` and it renders a router `NavLink` instead, so the same call site
|
||||
* covers both an action and a navigation.
|
||||
@@ -49,10 +49,10 @@ type LinkProps = CommonProps &
|
||||
* Reach for this anywhere you would have put `onClick` on a `<div>`. Use
|
||||
* `Button` for the styled variants and `IconButton` for icon-only controls.
|
||||
*
|
||||
* No tooltip by default — the children are already the label. Pass `tooltipId`
|
||||
* where the extra explanation earns its place.
|
||||
* No tooltip by default, since the children are already the label. Pass
|
||||
* `tooltipId` where the extra explanation earns its place.
|
||||
*
|
||||
* It cannot wrap another button or link — if the surface already contains one,
|
||||
* It cannot wrap another button or link. If the surface already contains one,
|
||||
* leave the container inert and make the inner control the real button.
|
||||
*/
|
||||
export function Clickable({
|
||||
@@ -75,8 +75,8 @@ export function Clickable({
|
||||
/>
|
||||
) : (
|
||||
<button
|
||||
{...(props as ButtonProps)}
|
||||
type="button"
|
||||
{...(props as ButtonProps)}
|
||||
aria-pressed={pressed}
|
||||
aria-expanded={expanded}
|
||||
aria-current={current}
|
||||
|
||||
@@ -137,7 +137,8 @@ function DropdownItem({
|
||||
className={classNames(
|
||||
'py-2 px-2 min-w-max cursor-pointer transition-colors select-none',
|
||||
variantStyles[variant],
|
||||
innerFocusValue === item.value && 'ring-inset ring-4'
|
||||
innerFocusValue === item.value &&
|
||||
'ring-inset ring-2 ring-accent-background-10'
|
||||
)}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
@@ -373,6 +374,9 @@ export function DropdownInside(
|
||||
const anchorName = `--dropdown-anchor-${useId().replace(/:/g, '')}`;
|
||||
|
||||
const [innerFocusIndex, setInnerFocusIndex] = useState<number | null>(null);
|
||||
// Index may point past the array (items changed, empty list) - resolve safely.
|
||||
const focusedItem =
|
||||
innerFocusIndex === null ? null : (items[innerFocusIndex] ?? null);
|
||||
const getCurrentActiveIndex = () => {
|
||||
return props.multiple
|
||||
? items.findIndex((item) => props.value.includes(item.value))
|
||||
@@ -433,36 +437,35 @@ export function DropdownInside(
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.key === 'ArrowDown') {
|
||||
setInnerFocusIndex(0);
|
||||
// Up/Down opens the list (APG combobox pattern).
|
||||
if (
|
||||
items.length > 0 &&
|
||||
(e.key === 'ArrowDown' || e.key === 'ArrowUp')
|
||||
) {
|
||||
setInnerFocusIndex(e.key === 'ArrowDown' ? 0 : items.length - 1);
|
||||
setIsOpen(true);
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.key === 'ArrowUp') {
|
||||
setInnerFocusIndex(items.length - 1);
|
||||
setIsOpen(true);
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
return;
|
||||
} else {
|
||||
if (a11yClick(e)) {
|
||||
e.preventDefault();
|
||||
if (innerFocusIndex === null) {
|
||||
if (!focusedItem) {
|
||||
setIsOpen(false);
|
||||
return;
|
||||
}
|
||||
|
||||
selectItem(items[innerFocusIndex]);
|
||||
selectItem(focusedItem);
|
||||
if (!props.multiple) setIsOpen(false);
|
||||
}
|
||||
switch (e.key) {
|
||||
case 'ArrowUp':
|
||||
case 'ArrowLeft':
|
||||
innerFocusPrev();
|
||||
e.preventDefault();
|
||||
return;
|
||||
case 'ArrowDown':
|
||||
case 'ArrowRight':
|
||||
innerFocusNext();
|
||||
e.preventDefault();
|
||||
return;
|
||||
@@ -502,10 +505,11 @@ export function DropdownInside(
|
||||
ref={ref}
|
||||
style={{ anchorName } as CSSProperties}
|
||||
aria-controls={`__dropdownList-${name}`}
|
||||
aria-expanded={isOpen}
|
||||
aria-activedescendant={
|
||||
innerFocusIndex === null
|
||||
? ''
|
||||
: `__dropdownList-${name}-item-${items[innerFocusIndex].value}`
|
||||
focusedItem
|
||||
? `__dropdownList-${name}-item-${focusedItem.value}`
|
||||
: ''
|
||||
}
|
||||
role="combobox"
|
||||
>
|
||||
@@ -554,9 +558,7 @@ export function DropdownInside(
|
||||
isSelected={(value) => isItemSelected(props, value)}
|
||||
ref={listRef}
|
||||
anchorName={anchorName}
|
||||
innerFocusValue={
|
||||
innerFocusIndex === null ? null : items[innerFocusIndex].value
|
||||
}
|
||||
innerFocusValue={focusedItem?.value ?? null}
|
||||
name={name}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -10,8 +10,8 @@ type DistributiveOmit<T, K extends PropertyKey> = 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`.
|
||||
*/
|
||||
|
||||
@@ -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<T extends FieldValues = FieldValues>({
|
||||
label,
|
||||
@@ -67,33 +68,15 @@ export function NumberSelector<T extends FieldValues = FieldValues>({
|
||||
!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<T extends FieldValues = FieldValues>({
|
||||
{hasLabel && <FieldCaption>{label}</FieldCaption>}
|
||||
<div
|
||||
role="spinbutton"
|
||||
data-nav-edit
|
||||
tabIndex={disabled ? -1 : 0}
|
||||
aria-label={label}
|
||||
aria-disabled={disabled || undefined}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import classNames from 'classnames';
|
||||
import { Control, Controller, FieldPath, FieldValues } from 'react-hook-form';
|
||||
import { stepKeys } from '@/utils/a11y';
|
||||
|
||||
export function Range<T extends FieldValues = FieldValues>({
|
||||
control,
|
||||
@@ -22,51 +23,70 @@ export function Range<T extends FieldValues = FieldValues>({
|
||||
<Controller
|
||||
control={control}
|
||||
name={name}
|
||||
render={({ field: { onChange, ref, name, value } }) => (
|
||||
<label className="text-standard w-full text-center flex items-center flex-col">
|
||||
<input
|
||||
type="range"
|
||||
className="text-background-10 border-accent-background-30"
|
||||
style={{
|
||||
width: 'calc(88% - 0.5vw)',
|
||||
}}
|
||||
name={name}
|
||||
ref={ref}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
list={`${name}-datalist`}
|
||||
min={min}
|
||||
max={max}
|
||||
step={step}
|
||||
{...props}
|
||||
/>
|
||||
<datalist id={`${name}-datalist`} className="">
|
||||
{values.map(({ value }, i) => (
|
||||
<option key={i}>{value}</option>
|
||||
))}
|
||||
</datalist>
|
||||
<div className="w-full flex flex-nowrap overflow-clip">
|
||||
{Array((max - min) / step + 1)
|
||||
.fill(0)
|
||||
.map((_v, i) => {
|
||||
const value = values.find(
|
||||
({ value }) => i * step + min === value
|
||||
);
|
||||
return (
|
||||
<span
|
||||
key={i}
|
||||
className={classNames(
|
||||
'flex-1',
|
||||
value?.defaultValue && 'text-status-success'
|
||||
)}
|
||||
>
|
||||
{value?.label}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</label>
|
||||
)}
|
||||
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 (
|
||||
<label className="text-standard w-full text-center flex items-center flex-col">
|
||||
<input
|
||||
type="range"
|
||||
className="text-background-10 border-accent-background-30"
|
||||
style={{
|
||||
width: 'calc(88% - 0.5vw)',
|
||||
}}
|
||||
{...props}
|
||||
data-nav-edit
|
||||
name={name}
|
||||
ref={ref}
|
||||
value={value}
|
||||
onChange={(e) => emit(e.target.valueAsNumber)}
|
||||
onKeyDown={onKeyDown}
|
||||
list={`${name}-datalist`}
|
||||
min={min}
|
||||
max={max}
|
||||
step={step}
|
||||
/>
|
||||
<datalist id={`${name}-datalist`} className="">
|
||||
{values.map(({ value }, i) => (
|
||||
<option key={i}>{value}</option>
|
||||
))}
|
||||
</datalist>
|
||||
<div className="w-full flex flex-nowrap overflow-clip">
|
||||
{Array((max - min) / step + 1)
|
||||
.fill(0)
|
||||
.map((_v, i) => {
|
||||
const value = values.find(
|
||||
({ value }) => i * step + min === value
|
||||
);
|
||||
return (
|
||||
<span
|
||||
key={i}
|
||||
className={classNames(
|
||||
'flex-1',
|
||||
value?.defaultValue && 'text-status-success'
|
||||
)}
|
||||
>
|
||||
{value?.label}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</label>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<div
|
||||
role="radiogroup"
|
||||
aria-label={radiogroupLabel}
|
||||
className={className}
|
||||
onKeyDown={handleRadioKeys}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!onClick) return <div className={className}>{children}</div>;
|
||||
|
||||
const name = label && value ? `${label}: ${value}` : label;
|
||||
|
||||
return (
|
||||
<Clickable
|
||||
onClick={onClick}
|
||||
pressed={pressed}
|
||||
label={label}
|
||||
label={name}
|
||||
className={className}
|
||||
>
|
||||
{children}
|
||||
@@ -51,50 +40,18 @@ export function TogglePill({
|
||||
);
|
||||
}
|
||||
|
||||
function handleRadioKeys(e: KeyboardEvent<HTMLDivElement>) {
|
||||
const step: Record<string, number> = {
|
||||
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<HTMLElement>(
|
||||
'[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 <div className={className}>{content}</div>;
|
||||
|
||||
if (radio) {
|
||||
return (
|
||||
<Clickable
|
||||
onClick={onClick}
|
||||
role="radio"
|
||||
aria-checked={active}
|
||||
tabIndex={active ? 0 : -1}
|
||||
className={className}
|
||||
>
|
||||
{content}
|
||||
</Clickable>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Clickable onClick={onClick} pressed={active} className={className}>
|
||||
{content}
|
||||
|
||||
@@ -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<HTMLDivElement>(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}
|
||||
/>
|
||||
|
||||
<div className="relative z-50 w-full max-h-full bg-background-70 p-6 rounded-lg text-background-10 border border-background-50/50 overflow-y-auto flex flex-col gap-4">
|
||||
<div
|
||||
ref={panelRef}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={groupName}
|
||||
tabIndex={-1}
|
||||
className="relative z-50 w-full max-h-full bg-background-70 p-6 rounded-lg text-background-10 border border-background-50/50 overflow-y-auto flex flex-col gap-4"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<ConnectionGroupIcon
|
||||
|
||||
@@ -14,7 +14,11 @@ export function OnboardingLayout({ children }: { children: ReactNode }) {
|
||||
|
||||
return !state.alonePage ? (
|
||||
<div className="onboarding-layout h-full">
|
||||
<div style={{ gridArea: 't' }}>
|
||||
<div
|
||||
data-nav-region="shell"
|
||||
data-nav-area="topbar"
|
||||
style={{ gridArea: 't' }}
|
||||
>
|
||||
<TopBar
|
||||
progress={state.progress}
|
||||
actions={
|
||||
@@ -26,7 +30,11 @@ export function OnboardingLayout({ children }: { children: ReactNode }) {
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ gridArea: 'c' }} className="mt-2 relative">
|
||||
<div
|
||||
data-nav-region="page"
|
||||
style={{ gridArea: 'c' }}
|
||||
className="mt-2 relative"
|
||||
>
|
||||
<div className="h-full w-full overflow-y-auto">{children}</div>
|
||||
<SkipSetupWarningModal
|
||||
accept={skipSetup}
|
||||
|
||||
@@ -1,13 +1,7 @@
|
||||
import classNames from 'classnames';
|
||||
import { useLocalization } from '@fluent/react';
|
||||
import { Clickable } from '@/components/commons/Clickable';
|
||||
import {
|
||||
HTMLAttributes,
|
||||
MouseEvent,
|
||||
ReactNode,
|
||||
useCallback,
|
||||
useMemo,
|
||||
} from 'react';
|
||||
import { HTMLAttributes, ReactNode, useCallback, useMemo } from 'react';
|
||||
import { BodyPart } from 'solarxr-protocol';
|
||||
import { MirrorLegend } from '@/components/onboarding/BodyAssignment';
|
||||
import {
|
||||
@@ -262,7 +256,7 @@ function Tab({
|
||||
}) {
|
||||
return (
|
||||
<Clickable
|
||||
disabled={disabled || active}
|
||||
disabled={disabled}
|
||||
pressed={active}
|
||||
onClick={onClick}
|
||||
className={classNames(
|
||||
@@ -299,10 +293,8 @@ export function ExtremitySideToggle({
|
||||
const option = (value: ExtremitySide, dotClass: string) => (
|
||||
<TogglePillOption
|
||||
compact={compact}
|
||||
radio
|
||||
dotClass={dotClass}
|
||||
active={side === value}
|
||||
onClick={() => onChange(value)}
|
||||
labelId={'body_part-' + BodyPart[descriptor.sides[value].root]}
|
||||
/>
|
||||
);
|
||||
@@ -310,7 +302,11 @@ export function ExtremitySideToggle({
|
||||
return (
|
||||
<TogglePill
|
||||
compact={compact}
|
||||
radiogroupLabel={l10n.getString('onboarding-assign_trackers-side')}
|
||||
onClick={() => 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<HTMLDivElement>) => {
|
||||
dragProps.onClick(event);
|
||||
if (event.defaultPrevented) return;
|
||||
selectPart(role);
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
{...bodyPartDropProps(role)}
|
||||
{...dragProps}
|
||||
{...tapProps}
|
||||
id={BodyPart[role]}
|
||||
data-connector={connector ? undefined : 'off'}
|
||||
onClick={onClick}
|
||||
aria-pressed={armedPart === role}
|
||||
className={classNames(
|
||||
'flex flex-col control rounded-md relative touch-none select-none',
|
||||
'transition-colors duration-150 ease-linear',
|
||||
@@ -378,7 +372,7 @@ function DragBodyPartCard({
|
||||
? 'bg-background-50'
|
||||
: armedPart === role
|
||||
? 'bg-accent-background-30/40'
|
||||
: isDragActive
|
||||
: isTargeting
|
||||
? 'bg-background-50/50'
|
||||
: 'hover:bg-background-50'
|
||||
)}
|
||||
|
||||
@@ -38,6 +38,8 @@ export function TrackerAssignmentList() {
|
||||
assignedPartsCount,
|
||||
expectedTrackersCount,
|
||||
handleDropTracker,
|
||||
selectTracker,
|
||||
pendingTrackerId,
|
||||
} = useAssignment();
|
||||
const assignedCount = assignedTrackers.length;
|
||||
const groups = useMemo(
|
||||
@@ -108,6 +110,8 @@ export function TrackerAssignmentList() {
|
||||
tracker={td.tracker}
|
||||
device={td.device}
|
||||
variant={variant}
|
||||
selected={pendingTrackerId === td.tracker.trackerId}
|
||||
onSelect={() => 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 (
|
||||
<div
|
||||
{...dragProps}
|
||||
{...tapProps}
|
||||
aria-pressed={onSelect ? selected : undefined}
|
||||
className={classNames(
|
||||
'touch-none cursor-grab active:cursor-grabbing select-none',
|
||||
'touch-none cursor-grab active:cursor-grabbing select-none rounded-lg',
|
||||
'transition-[transform,opacity] hover:scale-[1.02] hover:animate-wiggle',
|
||||
isBeingDragged && 'opacity-40',
|
||||
selected && 'ring-2 ring-accent-background-30',
|
||||
className
|
||||
)}
|
||||
style={style}
|
||||
@@ -382,16 +397,22 @@ function DraggableTrackerCard({
|
||||
device,
|
||||
variant,
|
||||
onDrop,
|
||||
onSelect,
|
||||
selected,
|
||||
}: {
|
||||
tracker: TrackerDataT;
|
||||
device?: DeviceDataT;
|
||||
variant: 'primary' | 'secondary' | 'tertiary';
|
||||
onDrop: (bodyPart: BodyPart) => void;
|
||||
onSelect?: () => void;
|
||||
selected?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<DraggableTracker
|
||||
trackerId={tracker.trackerId}
|
||||
label={getTrackerName(tracker.info) || 'unknown'}
|
||||
onSelect={onSelect}
|
||||
selected={selected}
|
||||
onDrop={(bodyPart) => {
|
||||
if (bodyPart !== null && bodyPart !== BodyPart.NONE) onDrop(bodyPart);
|
||||
}}
|
||||
|
||||
@@ -103,16 +103,30 @@ export function SettingsLayout({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<>
|
||||
<div className="settings-layout h-full">
|
||||
<div style={{ gridArea: 't' }}>
|
||||
<div
|
||||
data-nav-region="shell"
|
||||
data-nav-area="topbar"
|
||||
style={{ gridArea: 't' }}
|
||||
>
|
||||
<TopBar />
|
||||
</div>
|
||||
<div style={{ gridArea: 'n' }}>
|
||||
<div
|
||||
data-nav-region="shell"
|
||||
data-nav-area="navbar"
|
||||
style={{ gridArea: 'n' }}
|
||||
>
|
||||
<Navbar />
|
||||
</div>
|
||||
<div style={{ gridArea: 's' }} className="my-2 mobile:hidden">
|
||||
<div
|
||||
data-nav-region="shell"
|
||||
data-nav-area="settings-nav"
|
||||
style={{ gridArea: 's' }}
|
||||
className="my-2 mobile:hidden"
|
||||
>
|
||||
<SettingsSidebar />
|
||||
</div>
|
||||
<div
|
||||
data-nav-region="page"
|
||||
style={{ gridArea: 'c' }}
|
||||
className="xs:pl-2 xs:pb-2 xs:mt-2 mobile:mt-7 overflow-y-auto"
|
||||
>
|
||||
|
||||
@@ -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() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-interface-behavior-controller_nav')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pt-1 pb-2">
|
||||
<Typography>
|
||||
{l10n.getString(
|
||||
'settings-interface-behavior-controller_nav-description'
|
||||
)}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="grid sm:grid-cols-2 pb-4">
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
control={control}
|
||||
outlined
|
||||
name="behavior.controllerNav"
|
||||
label={l10n.getString(
|
||||
'settings-interface-behavior-controller_nav-label'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-general-interface-dev_mode')}
|
||||
</Typography>
|
||||
|
||||
@@ -70,6 +70,7 @@ export interface Config {
|
||||
lastUsedProportions: 'manual' | 'autobone' | 'scaled' | null;
|
||||
dontShowUdevModal: boolean;
|
||||
collapsedConnectionGroups: Record<string, boolean>;
|
||||
controllerNav: boolean;
|
||||
}
|
||||
|
||||
export interface ConfigContext {
|
||||
@@ -105,6 +106,7 @@ export const defaultConfig: Config = {
|
||||
lastUsedProportions: null,
|
||||
dontShowUdevModal: false,
|
||||
collapsedConnectionGroups: {},
|
||||
controllerNav: true,
|
||||
};
|
||||
|
||||
const localStore: CrossStorage = {
|
||||
|
||||
@@ -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<Direction, { firedAt: number; repeating: boolean }>(),
|
||||
prevButtons: new Set<number>(),
|
||||
stickDir: null as Direction | null,
|
||||
pads: new Set<number>(),
|
||||
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<HTMLElement>(`${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<HTMLElement>('[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]);
|
||||
}
|
||||
@@ -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 = <P, T>(codec: DropTargetCodec<T>) => {
|
||||
[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 = <P, T>(codec: DropTargetCodec<T>) => {
|
||||
suppressNextClickRef.current = false;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
return;
|
||||
}
|
||||
onTap?.();
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
@@ -115,6 +135,17 @@ export const createPointerDrag = <P, T>(codec: DropTargetCodec<T>) => {
|
||||
onPointerCancel,
|
||||
onClick,
|
||||
},
|
||||
tapProps: onTap
|
||||
? {
|
||||
role: 'button',
|
||||
tabIndex: 0,
|
||||
onKeyDown: (e: ReactKeyboardEvent) => {
|
||||
if (!a11yClick(e)) return;
|
||||
e.preventDefault();
|
||||
onTap();
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
isDragging,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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<Direction, string> = {
|
||||
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<HTMLElement>(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<HTMLElement>('[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<HTMLElement>('[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;
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { Direction } from './focus-nav';
|
||||
|
||||
export const BUTTON_A = 0;
|
||||
export const BUTTON_B = 1;
|
||||
|
||||
const DPAD: Record<number, Direction> = {
|
||||
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<number>;
|
||||
axX: number;
|
||||
axY: number;
|
||||
}
|
||||
|
||||
export function decodeInput(pads: (Gamepad | null)[]): GamepadFrame {
|
||||
const buttons = new Set<number>();
|
||||
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<Direction> {
|
||||
const dirs = new Set<Direction>();
|
||||
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';
|
||||
}
|
||||
@@ -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',
|
||||
},
|
||||
});
|
||||
}),
|
||||
],
|
||||
|
||||
Reference in new issue
Block a user