[docs] Manage focus on Open in Chat button click - #48942
Conversation
Deploy previewBundle size
Check out the code infra dashboard for more information about this PR. |
There was a problem hiding this comment.
Pull request overview
This PR improves the docs “Edit in Chat” (Open in MUI Chat) experience by addressing focus loss after clicking the button, and by ensuring the button is re-enabled as soon as the request completes (even when an error toast is shown).
Changes:
- Add logic to restore focus to the “Edit in Chat” button after the loading state completes.
- Stop disabling the button based solely on the presence of an error toast.
- Add unit tests covering focus restoration on success, failure, and when the user moves focus elsewhere.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
| packages-internal/core-docs/src/Demo/OpenInMUIChatButton.tsx | Adds focus-management logic tied to the loading lifecycle and adjusts ref handling. |
| packages-internal/core-docs/src/Demo/OpenInMUIChatButton.test.tsx | Introduces tests verifying focus restoration behavior across success/failure and user-driven focus changes. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| beforeEach(() => { | ||
| mocks.openSandbox.mockReset(); | ||
| vi.stubEnv('MUI_CHAT_API_BASE_URL', 'https://chat.example.com'); | ||
| vi.stubEnv('MUI_CHAT_SCOPES', 'material-ui'); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| vi.unstubAllEnvs(); | ||
| }); |
There was a problem hiding this comment.
We use vi functions in our tests, we should be fine with these as well.
| const rainbowButtonRef = React.useRef<HTMLButtonElement | null>(null); | ||
| const handleRef = useForkRef<HTMLButtonElement>(ref, rainbowButtonRef); | ||
| const wasLoadingRef = React.useRef(false); | ||
|
|
||
| React.useEffect(() => { | ||
| if (wasLoadingRef.current && !loading) { | ||
| const rainbowButton = rainbowButtonRef.current; | ||
| const document = ownerDocument(rainbowButton); | ||
| const activeElement = getActiveElement(document); | ||
|
|
||
| if ( | ||
| activeElement === document.body || | ||
| activeElement === null || | ||
| activeElement === document.documentElement | ||
| ) { | ||
| rainbowButtonRef.current?.focus(); | ||
| } | ||
| } | ||
| wasLoadingRef.current = loading; | ||
| }, [loading]); |
There was a problem hiding this comment.
should be fine, if the user uses the mouse to interact, they don't care about focus being management at that point.
When clicking Open in Chat button in the docs, the focus is lost to the body. Restore the focus to the button once the button is not loading anymore, and if the user did not move focus elsewhere.
Also, there is no reason to disable the button while showing the error toast. Button should be enabled as soon as possible, when the request returns.