adobe / adobe/react-spectrum

Allow preventing scroll in focusManager

Open
#2,426 5 comments 1 reaction 0 assignees View on GitHub
bug needs investigation
Dominant language
TypeScript
Stars
15.9k
Forks
1.6k
Avg merge
3d 9m
Merged PRs (30d)
59

Description

# 🙋 Feature Request

I'd like to be able to prevent scroll when using the focus manager imperatively. Currently the FocusManagerOptions don't include this option, and scrolling is a hardcoded setting - e.g. here in focusFirst:

https://github.com/adobe/react-spectrum/blob/b4a3821acce160a0013587b6891e864390a33efe/packages/%40react-aria/focus/src/FocusScope.tsx#L187

## 🤔 Expected Behavior

You have the option to prevent scroll when focussing elements through the focusManager.

## 😯 Current Behavior

It's impossible to disable scrolling when focusing elements using focusManager.

## 💁 Possible Solution

If we could simply pass an option { preventScroll: true } to focusFirst/-Last/-Next/-Prev this would provide us with the added flexibility to support our use case without needing too many workarounds. I'm guessing it would be relatively easy to add this option to the focusManager interface looking at the code?

## 🔦 Context

Our experience is that FocusScopes don't nest well. We have an overlay that opens up a sort of wizard containing multiple steps. The overlay has a FocusScope with `contain restoreFocus autoFocus` which works well when the overlay opens. But when navigating between steps, we'd like to autoFocus first input inside the next step.

We initially tried using a nested `` which technically provided the autoFocus, but meant that the `contain restoreFocus` settings from the parent scope ended up being ignored.

Instead we've tried implementing the autoFocus behaviour ourselves, using a mount effect and imperatively applying focus using useFocusManager(). This worked well until we implemented a transition between the steps - this transition is killed because the browser now tries to perform automatic scrolling while we're transitioning the UI.

## 💻 Examples

Simplified version of the code used to implement the auto focus behaviour when changing steps:

```
function useStepAutoFocus(stepRef: React.RefObject) {
const focusManager = useFocusManager();

useEffect(
() => {
if (!stepRef.current) {
return;
}

let autoFocussedElement = focusManager.focusFirst();

while (
autoFocussedElement &&
!stepRef.current.contains(autoFocussedElement)
) {
autoFocussedElement = focusManager.focusNext();
}
},
[]
);
}

```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.