Skip to content

bugfix(Dialog): Fixing issue where page shifts when dialog is open #6266

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jul 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .changeset/empty-experts-glow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
"@primer/react": patch
---
Bug fix: Fixing issue where page shifts when Dialog is open
1 change: 1 addition & 0 deletions packages/react/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ module.exports = {
'<rootDir>/src/CircleBadge/',
'<rootDir>/src/CircleOcticon/',
'<rootDir>/src/DataTable/',
'<rootDir>/src/Dialog/',
'<rootDir>/src/FeatureFlags/',
'<rootDir>/src/Flash/',
'<rootDir>/src/FormControl/__tests__/FormControl.Validation.test.tsx',
Expand Down
41 changes: 40 additions & 1 deletion packages/react/src/Dialog/Dialog.dev.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type React from 'react'
import {useState, useCallback} from 'react'
import {useState, useCallback, useRef} from 'react'
import {Text, Button} from '..'
import type {DialogProps, DialogWidth, DialogHeight} from './Dialog'
import {Dialog} from './Dialog'
Expand Down Expand Up @@ -193,3 +193,42 @@ export const WithSxAndCss = ({width, height, subtitle}: DialogStoryProps) => {
</>
)
}

export const WithScrollBody = () => {
const [isOpen, setIsOpen] = useState(false)
const buttonRef = useRef<HTMLButtonElement>(null)
const onDialogClose = useCallback(() => setIsOpen(false), [])
return (
<>
<Button ref={buttonRef} onClick={() => setIsOpen(!isOpen)}>
Show dialog
</Button>
{lipsum}
{lipsum}
{lipsum}
{lipsum}
{lipsum}
{lipsum}
{lipsum}
{lipsum}
{lipsum}
{lipsum}
{lipsum}
{isOpen && (
<Dialog
title="My Dialog"
onClose={onDialogClose}
footerButtons={[
{buttonType: 'danger', content: 'Delete the universe', onClick: onDialogClose},
{buttonType: 'primary', content: 'Proceed', onClick: onDialogClose},
]}
>
{lipsum}
</Dialog>
)}
</>
)
}
WithScrollBody.parameters = {
layout: 'fullscreen',
}
19 changes: 19 additions & 0 deletions packages/react/src/Dialog/Dialog.module.css
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
/* The --dialog-scrollgutter property is used only on the body element to
* simulate scrollbar-gutter:stable. This property is not and should not
* be used elsewhere in the DOM. There is a performance penalty to
* setting inherited properties which can cause a large style recalc to
* occur, so it benefits us to prevent inheritance for this property.
* See https://web.dev/blog/at-property-performance
*/
@property --dialog-scrollgutter {
initial-value: 0;
inherits: false;
syntax: '<length>';
}

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Most of this implementation was taken from what we did in PVC primer/view_components#2542

@keyframes dialog-backdrop-appear {
0% {
opacity: 0;
Expand Down Expand Up @@ -216,6 +229,12 @@
}
}

body:has(.Dialog.DisableScroll) {
/* stylelint-disable-next-line primer/spacing */
padding-right: var(--dialog-scrollgutter) !important;
overflow: hidden !important;
}

.DialogOverflowWrapper {
flex-grow: 1;
}
Expand Down
41 changes: 10 additions & 31 deletions packages/react/src/Dialog/Dialog.test.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import React from 'react'
import {fireEvent, render, waitFor} from '@testing-library/react'
import {render, fireEvent, waitFor} from '@testing-library/react'
import {describe, expect, it, beforeEach, afterEach, vi} from 'vitest'
import userEvent from '@testing-library/user-event'
import {Dialog} from './Dialog'
import MatchMediaMock from 'jest-matchmedia-mock'
import {behavesAsComponent, checkExports} from '../utils/testing'
import axe from 'axe-core'
import {Button} from '../Button'

let matchMedia: MatchMediaMock
Expand All @@ -18,21 +17,6 @@ describe('Dialog', () => {
matchMedia.clear()
})

behavesAsComponent({
Component: Dialog,
options: {skipAs: true, skipSx: true, skipClassName: true},
toRender: () => (
<Dialog onClose={() => {}}>
<div>Hidden when narrow</div>
</Dialog>
),
})

checkExports('Dialog/Dialog', {
default: undefined,
Dialog,
})

it('renders with role "dialog" by default', () => {
const {getByRole} = render(<Dialog onClose={() => {}}>Pay attention to me</Dialog>)

Expand Down Expand Up @@ -60,7 +44,7 @@ describe('Dialog', () => {

it('calls `onClose` when clicking the close button', async () => {
const user = userEvent.setup()
const onClose = jest.fn()
const onClose = vi.fn()
const {getByLabelText} = render(<Dialog onClose={onClose}>Pay attention to me</Dialog>)

expect(onClose).not.toHaveBeenCalled()
Expand All @@ -73,7 +57,7 @@ describe('Dialog', () => {

it('calls `onClose` when clicking the backdrop', async () => {
const user = userEvent.setup()
const onClose = jest.fn()
const onClose = vi.fn()
const {getByRole} = render(<Dialog onClose={onClose}>Pay attention to me</Dialog>)

expect(onClose).not.toHaveBeenCalled()
Expand All @@ -86,7 +70,7 @@ describe('Dialog', () => {
})

it('does not call `onClose` when click was not originated from backdrop', async () => {
const onClose = jest.fn()
const onClose = vi.fn()

const {getByRole} = render(<Dialog onClose={onClose}>Pay attention to me</Dialog>)

Expand All @@ -105,13 +89,14 @@ describe('Dialog', () => {

it('calls `onClose` when keying "Escape"', async () => {
const user = userEvent.setup()
const onClose = jest.fn()
const onClose = vi.fn()

render(<Dialog onClose={onClose}>Pay attention to me</Dialog>)

expect(onClose).not.toHaveBeenCalled()

await user.keyboard('{Escape}')
await user.keyboard('{Escape}') // escape once to remove focus from the close button
await user.keyboard('{Escape}') // escape again to trigger the onClose

expect(onClose).toHaveBeenCalledWith('escape')
})
Expand All @@ -121,21 +106,15 @@ describe('Dialog', () => {

const {container} = render(<Dialog onClose={() => {}}>Pay attention to me</Dialog>)

expect(container.ownerDocument.body.style.overflow).toBe('hidden')
expect(container.ownerDocument.body).toHaveStyle('overflow: hidden')
})

it('does not attempt to change the <body> style for `overflow` if it is already set to "hidden"', () => {
document.body.style.overflow = 'hidden'

const {container} = render(<Dialog onClose={() => {}}>Pay attention to me</Dialog>)

expect(container.ownerDocument.body.style.overflow).toBe('hidden')
})

it('should have no axe violations', async () => {
const {container} = render(<Dialog onClose={() => {}}>Pay attention to me</Dialog>)
const results = await axe.run(container)
expect(results).toHaveNoViolations()
expect(container.ownerDocument.body).toHaveStyle('overflow: hidden')
})

it('renders with data-position-regular="left" when position="left"', () => {
Expand Down
16 changes: 2 additions & 14 deletions packages/react/src/Dialog/Dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -288,19 +288,7 @@ const _Dialog = React.forwardRef<HTMLDivElement, React.PropsWithChildren<DialogP
)

React.useEffect(() => {
const bodyOverflowStyle = document.body.style.overflow || ''
// If the body is already set to overflow: hidden, it likely means
// that there is already a modal open. In that case, we should bail
// so we don't re-enable scroll after the second dialog is closed.
if (bodyOverflowStyle === 'hidden') {
return
}

document.body.style.overflow = 'hidden'

return () => {
document.body.style.overflow = bodyOverflowStyle
}
document.body.style.setProperty('--dialog-scrollgutter', `${window.innerWidth - document.body.clientWidth}px`)
Copy link
Member Author

@jonrohan jonrohan Jul 2, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I cleared up this overflow style setting since we can include it in the class. The property I'm setting here is identical to what we have in PVC https://github.com/primer/view_components/blob/2677324d35cac1ce5ebf9aede851fa4267f7c6e2/app/components/primer/dialog_helper.ts#L81

But I want to know if useEffect is the correct callback to have this in?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jonrohan I think that's the right place to have it 👍

}, [])

const header = (renderHeader ?? DefaultHeader)(defaultedProps)
Expand Down Expand Up @@ -339,7 +327,7 @@ const _Dialog = React.forwardRef<HTMLDivElement, React.PropsWithChildren<DialogP
data-width={width}
data-height={height}
sx={sx}
className={clsx(className, classes.Dialog)}
className={clsx(className, classes.Dialog, classes.DisableScroll)}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Opted to add a separate class here in case we wanted to make this a prop in the future, which is what we do in PVC

>
{header}
<ScrollableRegion aria-labelledby={dialogLabelId} className={classes.DialogOverflowWrapper}>
Expand Down
1 change: 1 addition & 0 deletions packages/react/vitest.config.browser.mts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export default defineConfig({
'src/CircleBadge/**/*.test.?(c|m)[jt]s?(x)',
'src/CircleOcticon/**/*.test.?(c|m)[jt]s?(x)',
'src/DataTable/**/*.test.?(c|m)[jt]s?(x)',
'src/Dialog/**/*.test.?(c|m)[jt]s?(x)',
'src/FeatureFlags/**/*.test.?(c|m)[jt]s?(x)',
'src/Flash/**/*.test.?(c|m)[jt]s?(x)',
'src/FormControl/__tests__/FormControl.Validation.test.tsx',
Expand Down
Loading