Skip to content

Allow preventing scroll in focusManager #2426

@felskov

Description

@felskov

🙋 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:

focusElement(nextNode, true);

🤔 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 <FocusScope autoFocus> 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<HTMLElement>) {
  const focusManager = useFocusManager();

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

      let autoFocussedElement = focusManager.focusFirst();

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions