diff --git a/.changeset/lock-page-scroll.md b/.changeset/lock-page-scroll.md new file mode 100644 index 0000000..bfd821d --- /dev/null +++ b/.changeset/lock-page-scroll.md @@ -0,0 +1,47 @@ +--- +'react-spring-lightbox': patch +--- + +The page behind the open lightbox no longer scrolls. + +- With 1.9.0, a swipe up or down on the lightbox's header or footer on a touchscreen scrolled the page behind it, because only the image stage set `touch-action: none`. +- Now the modal lightbox sets `overflow: hidden` on `` while it is open. Neither touch nor the keys that a text field or a menu portaled to `` leaves to the browser scroll the page behind it. When the last open lightbox closes, it puts back the inline `overflow` and `padding-right` that `` had when the first one opened, and the page is where it was. +- If the page's scrollbar took up space, as classic scrollbars on Windows do, the lightbox adds that width to the `padding-right` of `` while it is open, so the page's content doesn't shift when the scrollbar goes away. An element with `position: fixed` and `right: 0` still moves right by the scrollbar's width while the lightbox is open, 15px in a WebKit test. A scrollbar that overlays the page, as on macOS with a trackpad, takes up no space and adds no padding. +- An `inline` carousel leaves the page alone. +- Tested with the unit tests on React 19 and React 18.3.1, the Playwright tests in Chromium, Firefox, WebKit, and mobile Chromium on React 19, and the Chromium Playwright tests on React 18.3.1. The check that the page doesn't shift runs in WebKit only, because Playwright's Chromium hides scrollbars and Firefox ignores `::-webkit-scrollbar`. Not tested in Safari on iOS, or on a real touchscreen. + +Upgrade notes: + +- If your app sets `overflow` or `padding-right` on `` while the lightbox is open, for example to stop the page from scrolling, you can remove that code. If you keep it, set it before `isOpen` turns true, and remove it after the lightbox closes. When the last open lightbox closes, it puts back the inline values that `` had when the first one opened, so a value that your app sets while a lightbox is open doesn't stay. + + Before: + + ```jsx + useEffect(() => { + if (!isOpen) { + return undefined; + } + document.documentElement.style.overflow = 'hidden'; + return () => { + document.documentElement.style.overflow = ''; + }; + }, [isOpen]); + + return ( + + ); + ``` + + After: + + ```jsx + return ( + + ); + ``` diff --git a/.changeset/scope-keys.md b/.changeset/scope-keys.md index 859b89f..4381b04 100644 --- a/.changeset/scope-keys.md +++ b/.changeset/scope-keys.md @@ -10,7 +10,7 @@ The lightbox's keys now act only while focus is inside it, so text fields, selec - ← and → leave text fields, selects, and other editable elements alone. Escape still closes the lightbox from a text field, unless the field calls `preventDefault()` in its own `onKeyDown`. - ←, →, and Escape do nothing with Alt, Ctrl, or Cmd held, so browser and system shortcuts such as Alt+← keep working. Keys pressed while an input method composes text do nothing at all. That includes the Escape that cancels a composition in Safari, which fires `compositionend` first and marks that `keydown` only with `keyCode` 229. With 1.9.0, the lightbox didn't check for composition, so the Escape that cancels a Chinese or Japanese composition could close it. - The keys act when they go down instead of when they come up. Holding an arrow key still pages once. -- While the modal lightbox is open, ↑, ↓, PageUp, PageDown, Home, and End pressed in it don't scroll the page behind it, with or without Alt, Ctrl, or Cmd, unless a text field has focus. Space doesn't scroll it either, unless Space presses a focused button. With 1.9.0, Space scrolled the page behind the lightbox. Keys pressed in content portaled out of the lightbox, such as a menu that a header button renders into ``, are left to that content, so they scroll the page behind unless that content prevents them. An `inline` carousel never blocks these keys. +- While the modal lightbox is open, it blocks ↑, ↓, PageUp, PageDown, Home, and End pressed in it, with or without Alt, Ctrl, or Cmd, except in a text field, which keeps them. It blocks Space too, unless Space presses a focused button. With 1.9.0, Space scrolled the page behind the lightbox. Keys pressed in content portaled out of the lightbox, such as a menu that a header button renders into ``, are left to that content. An `inline` carousel never blocks these keys. - Tested with the unit tests on React 19 and React 18.3.1, the Playwright tests in Chromium, Firefox, and mobile Chromium on React 19, and the Chromium Playwright tests on React 18.3.1. CI runs the WebKit projects. A unit test covers the Safari input-method case with the `keydown` that Safari sends. It was not tested in Safari with an input method. Upgrade notes: diff --git a/README.md b/README.md index 0a913a8..736acf0 100644 --- a/README.md +++ b/README.md @@ -143,13 +143,13 @@ export default CoolLightbox; ## Accessibility -The lightbox opens as a modal dialog with `role="dialog"` and `aria-modal="true"`. When it opens, focus moves into it, and Tab and Shift+Tab cycle through its controls. Until it closes, the other children of `` are `inert`, so neither the keyboard nor a screen reader reaches the page behind it. When it closes, focus goes back to the element that had focus before it opened. With `inline`, the lightbox is part of the page and none of this applies. +The lightbox opens as a modal dialog with `role="dialog"` and `aria-modal="true"`. When it opens, focus moves into it, and Tab and Shift+Tab cycle through its controls. Until it closes, the other children of `` are `inert`, so neither the keyboard nor a screen reader reaches the page behind it, and `` has `overflow: hidden`, so the page behind it doesn't scroll. When it closes, focus goes back to the element that had focus before it opened. With `inline`, the lightbox is part of the page and none of this applies. - Name the dialog with `aria-label`, or with `aria-labelledby` and the `id` of a title in your header. - Give each button that you render a text label or an `aria-label`. An icon alone gives a screen reader nothing to announce. - Elements that you add to `` after the lightbox opens, such as a menu that a header button portals to ``, stay usable. Elements that were in `` before it opened stay inert until it closes. -The lightbox handles ←, →, and Esc only while focus is inside it, or while the modal lightbox is open and nothing has focus, as after a focused Next button turns disabled on the last image. Text fields and selects inside it keep their arrow, Home, and End keys. While the modal lightbox is open, the keys that scroll a page don't scroll the page behind it when pressed in the lightbox. +The lightbox handles ←, →, and Esc only while focus is inside it, or while the modal lightbox is open and nothing has focus, as after a focused Next button turns disabled on the last image. Text fields and selects inside it keep their arrow, Home, and End keys. - To keep the lightbox open when a control inside it handles Esc, call `event.preventDefault()` in that control's `onKeyDown`. - An `inline` carousel takes ← and → only while focus is inside it. Render buttons with `renderPrevButton` and `renderNextButton`, so keyboard users can move focus there. A button that turns `disabled` while it has focus, as at the first or last image, drops focus to the page, and the carousel then takes no keys until focus is back inside it. diff --git a/e2e/harness/main.tsx b/e2e/harness/main.tsx index 7cf7bdb..a82900c 100644 --- a/e2e/harness/main.tsx +++ b/e2e/harness/main.tsx @@ -12,6 +12,13 @@ import Lightbox from '../../src/index'; const params = new URLSearchParams(window.location.search); const flag = (name: string) => params.has(name); +// A styled scrollbar takes up space in Chromium and WebKit, as classic scrollbars on Windows and Linux do +if (flag('classicScrollbar')) { + const style = document.createElement('style'); + style.textContent = '::-webkit-scrollbar { width: 15px; } ::-webkit-scrollbar-thumb { background: #888; }'; + document.head.append(style); +} + const images: ImagesListType = flag('variety') ? [ { alt: 'Tiny image', src: '/images/tiny.svg' }, diff --git a/e2e/opening-and-closing.spec.ts b/e2e/opening-and-closing.spec.ts index fb9d1dc..14fada8 100644 --- a/e2e/opening-and-closing.spec.ts +++ b/e2e/opening-and-closing.spec.ts @@ -149,6 +149,47 @@ test.describe('with a mouse and keyboard', () => { expect(prevented).toEqual([false, false]); }); + + test('keys in a menu portaled out of the lightbox do not scroll the page behind', async ({ page }) => { + await openHarness(page, 'portalMenu'); + await page.getByRole('button', { name: 'Menu' }).click(); + await page.getByRole('button', { name: 'Portaled item' }).focus(); + + for (const key of ['ArrowDown', 'PageDown', 'End']) { + await page.keyboard.press(key); + } + await page.waitForTimeout(300); + + expect(await scrollY(page)).toBe(0); + }); + + test('keys in a text field in the footer do not scroll the page behind', async ({ page }) => { + await openHarness(page, 'footerInput'); + await page.getByRole('textbox', { name: 'Caption' }).click(); + + for (const key of ['End', 'PageDown', 'ArrowDown']) { + await page.keyboard.press(key); + } + await page.waitForTimeout(300); + + expect(await scrollY(page)).toBe(0); + }); + + test('opening keeps the page behind in place when its scrollbar takes up space', async ({ browserName, page }) => { + test.skip( + browserName !== 'webkit', + "Playwright's Chromium hides scrollbars, and Firefox ignores ::-webkit-scrollbar, so only WebKit gets one that takes up space" + ); + await openHarness(page, 'closed&classicScrollbar'); + const pageWidth = () => page.evaluate(() => document.querySelector('h1')?.getBoundingClientRect().width); + const before = await pageWidth(); + + await page.getByRole('button', { name: 'Open Image 3' }).click(); + await settle(page); + + expect(before).toBe((page.viewportSize()?.width ?? 0) - 15); + expect(await pageWidth()).toBe(before); + }); }); test.describe('on a touchscreen', () => { @@ -185,7 +226,6 @@ test.describe('on a touchscreen', () => { await page.waitForTimeout(600); const scrolled = await scrollY(page); - test.fail(true, 'Only the image stage sets touch-action: none'); expect(scrolled).toBe(0); }); }); diff --git a/src/__tests__/opening-and-closing.test.tsx b/src/__tests__/opening-and-closing.test.tsx index 407e393..fd7c037 100644 --- a/src/__tests__/opening-and-closing.test.tsx +++ b/src/__tests__/opening-and-closing.test.tsx @@ -415,6 +415,88 @@ describe('the page behind it', () => { expect(pressKey('Home', caption).defaultPrevented).toBe(false); expect(pressKey('End', caption).defaultPrevented).toBe(false); }); + + test('cannot scroll while it is open, and can again once it closes', async () => { + const root = document.documentElement; + const props = lightboxProps(); + const { rerender } = render(); + await settle(); + expect(root.style.overflow).toBe('hidden'); + + rerender( + + ); + await settle(); + + expect(root.style.overflow).toBe(''); + }); + + test('gets back the overflow and padding that the page set on ', async () => { + const root = document.documentElement; + root.style.overflow = 'scroll'; + root.style.paddingRight = '3px'; + const { unmount } = render(); + await settle(); + + unmount(); + + expect(root.style.overflow).toBe('scroll'); + expect(root.style.paddingRight).toBe('3px'); + root.removeAttribute('style'); + }); + + test('stays in place when the scrollbar it hides took up space', async () => { + const root = document.documentElement; + // A classic scrollbar takes 15px from the page until overflow: hidden removes it + vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockImplementation(function (this: HTMLElement) { + return this === root && root.style.overflow !== 'hidden' ? 785 : 800; + }); + const { unmount } = render(); + await settle(); + expect(root.style.paddingRight).toBe('15px'); + + unmount(); + + expect(root.style.paddingRight).toBe(''); + }); + + test('stays locked until the last of two open lightboxes closes, whichever closes first', async () => { + const root = document.documentElement; + const first = lightboxProps(); + const second = lightboxProps(); + const page = (firstIsOpen: boolean, secondIsOpen: boolean) => ( + <> + + + + ); + const { rerender } = render(page(true, true)); + await settle(); + + rerender(page(false, true)); + await settle(); + expect(root.style.overflow).toBe('hidden'); + + rerender(page(false, false)); + await settle(); + expect(root.style.overflow).toBe(''); + }); + + test('is left alone by an inline carousel', async () => { + render(); + await settle(); + + expect(document.documentElement.style.overflow).toBe(''); + }); }); test('reopens on the new currentIndex at full size', async () => { diff --git a/src/components/PageContainer/useModalDialog.ts b/src/components/PageContainer/useModalDialog.ts index 60c1264..6e246e0 100644 --- a/src/components/PageContainer/useModalDialog.ts +++ b/src/components/PageContainer/useModalDialog.ts @@ -20,6 +20,36 @@ const makePageBehindInert = (dialog: Element) => { return () => madeInert.forEach((element) => element.removeAttribute('inert')); }; +// Every open modal shares one lock, so the page gets its own styles back only when the last one closes, +// in whatever order they close +const pageLock = { openModals: 0, overflow: '', paddingRight: '' }; + +// Inert content still scrolls, as with the keys that a text field or a menu portaled to leaves +// to the browser, and with touches outside the image stage. Hiding the page's overflow stops them all. +const lockPageScroll = () => { + const root = document.documentElement; + if (pageLock.openModals === 0) { + pageLock.overflow = root.style.overflow; + pageLock.paddingRight = root.style.paddingRight; + const widthWithScrollbar = root.clientWidth; + root.style.overflow = 'hidden'; + // A scrollbar that took up space goes away with the overflow, so padding takes its place + const scrollbarWidth = root.clientWidth - widthWithScrollbar; + if (scrollbarWidth > 0) { + const padding = parseFloat(getComputedStyle(root).paddingRight) || 0; + root.style.paddingRight = `${padding + scrollbarWidth}px`; + } + } + pageLock.openModals += 1; + return () => { + pageLock.openModals -= 1; + if (pageLock.openModals === 0) { + root.style.overflow = pageLock.overflow; + root.style.paddingRight = pageLock.paddingRight; + } + }; +}; + // With the page inert, Tab from the last control would land on const keepTabInside = (event: Pick, dialog: HTMLElement) => { if (event.key !== 'Tab') { @@ -60,6 +90,7 @@ const useModalDialog = (isOpen: boolean) => { const dialog = dialogRef.current!; const returnFocusTo = focusedBeforeOpen as HTMLElement; const freePageBehind = makePageBehindInert(dialog); + const unlockPageScroll = lockPageScroll(); if (!dialog.contains(document.activeElement)) { dialog.focus(); } @@ -76,6 +107,7 @@ const useModalDialog = (isOpen: boolean) => { return () => { document.removeEventListener('keydown', takeFocusBack); freePageBehind(); + unlockPageScroll(); returnFocusTo.focus(); }; }, [focusedBeforeOpen, isOpen]);