Unverified Commit b59fae04 authored by Joseph's avatar Joseph Committed by GitHub

[fragment-scroll] Stop blurring on navigations (#96113)

Dynamic pages (all pages in dev), blur and select the body as
`activeElement`.

- [x] e2e for https://github.com/vercel/next.js/issues/96050
- [ ] attempt a fix that prevents blur
parent 67f16a52
...@@ -291,21 +291,8 @@ function InnerScrollHandlerNew(props: ScrollAndMaybeFocusHandlerProps) { ...@@ -291,21 +291,8 @@ function InnerScrollHandlerNew(props: ScrollAndMaybeFocusHandlerProps) {
// Mark as scrolled so no other segment scrolls for this navigation. // Mark as scrolled so no other segment scrolls for this navigation.
scrollRef.current = false scrollRef.current = false
const activeElement = document.activeElement // This handler intentionally leaves focus untouched; resetting focus on
if ( // navigation is deferred.
activeElement !== null &&
'blur' in activeElement &&
typeof activeElement.blur === 'function'
) {
// Trying to match hard navigations.
// Ideally we'd move the internal focus cursor either to the top
// or at least before the segment. But there's no DOM API to do that,
// so we just blur.
// We could workaround this by moving focus to a temporary element in
// the body. But adding elements might trigger layout or other effects
// so it should be well motivated.
activeElement.blur()
}
disableSmoothScrollDuringRouteTransition( disableSmoothScrollDuringRouteTransition(
() => { () => {
......
import { isNextDev, nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
// Typing into an input that pushes `?q=` per keystroke should keep focus. On a
// dynamic page focus was lost after the first character; a static page is fine.
describe('app-new-scroll-handler-focus', () => {
const { next } = nextTestSetup({
files: __dirname,
})
// Use the page keyboard, not element.type() (which re-focuses and hides the
// bug). If focus is lost, the second key never lands and the URL stays `q=a`.
async function typeTwoKeysBothMustLand(path: string, testId: string) {
const browser = await next.browser(path)
const activeTestId = () =>
browser.eval(() => document.activeElement?.getAttribute('data-testid'))
// Focus explicitly — autoFocus timing isn't reliable across bundlers.
await browser.elementByCss(`[data-testid="${testId}"]`).click()
await retry(async () => {
expect(await activeTestId()).toBe(testId)
})
await browser.keydown('a')
await browser.keyup('a')
await retry(async () => {
expect(await browser.url()).toContain('q=a')
})
await browser.keydown('b')
await browser.keyup('b')
await retry(async () => {
expect(await browser.url()).toContain('q=ab')
})
await retry(async () => {
expect(await activeTestId()).toBe(testId)
})
}
it('dynamic page: keeps focus across search-param keystrokes (all modes)', async () => {
await typeTwoKeysBothMustLand('/', 'search-input')
})
// Static pages are immune; only assertable outside dev (dev renders dynamically).
if (!isNextDev) {
it('static page: unaffected by the new scroll handler (start/deploy only)', async () => {
await typeTwoKeysBothMustLand('/static', 'static-search-input')
})
}
// The navigation should still scroll to top while keeping focus.
it('dynamic page: still scrolls to top on a search-param nav, focus preserved', async () => {
const browser = await next.browser('/')
await browser.elementByCss('[data-testid="search-input"]').click()
await retry(async () => {
expect(
await browser.eval(() =>
document.activeElement?.getAttribute('data-testid')
)
).toBe('search-input')
})
await browser.eval(() => window.scrollTo(0, 800))
await retry(async () => {
expect(await browser.eval(() => window.scrollY)).toBeGreaterThan(400)
})
await browser.keydown('a')
await browser.keyup('a')
await retry(async () => {
expect(await browser.url()).toContain('q=a')
})
await retry(async () => {
expect(await browser.eval(() => window.scrollY)).toBe(0)
})
expect(
await browser.eval(() =>
document.activeElement?.getAttribute('data-testid')
)
).toBe('search-input')
})
// Focus is left alone, so a route+search change keeps focus on an input that
// survives in a parent layout.
it('route + search change keeps focus (all modes)', async () => {
const browser = await next.browser('/combo')
const activeTestId = () =>
browser.eval(() => document.activeElement?.getAttribute('data-testid'))
await browser.elementByCss('[data-testid="combo-input"]').click()
await retry(async () => {
expect(await activeTestId()).toBe('combo-input')
})
await browser.keydown('a')
await browser.keyup('a')
await retry(async () => {
expect(await browser.url()).toContain('/combo/next?q=a')
})
// The layout input survives the navigation and keeps focus.
expect(
await browser.eval(
() => !!document.querySelector('[data-testid="combo-input"]')
)
).toBe(true)
expect(await activeTestId()).toBe('combo-input')
})
})
'use client'
import { useState } from 'react'
import { useRouter } from 'next/navigation'
// Input lives in a PARENT layout so it survives navigations that only change a
// child segment. Typing pushes a child path + search param.
export default function ComboLayout({
children,
}: {
children: React.ReactNode
}) {
const router = useRouter()
const [value, setValue] = useState('')
return (
<>
<input
autoFocus
data-testid="combo-input"
placeholder="Search"
value={value}
onChange={(event) => {
const nextValue = event.target.value
setValue(nextValue)
router.push('/combo/next?q=' + encodeURIComponent(nextValue))
}}
/>
{children}
</>
)
}
export default function ComboNext() {
return <p data-testid="combo-next">next</p>
}
export default function ComboStart() {
return <p data-testid="combo-start">start</p>
}
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
import { SearchBox } from './search-box'
// Dynamic via connection() (works in plain and Cache Components builds; unlike
// `export const dynamic`, which Cache Components rejects). A search-param nav is
// then a SearchParamOnlyChange, which is what allocates a scroll target.
async function Dynamic() {
await connection()
return <SearchBox testId="search-input" />
}
export default function Page() {
return (
<>
<Suspense>
<Dynamic />
</Suspense>
{/* Tall enough to scroll, so the scroll-to-top assertion is meaningful. */}
<div data-testid="spacer" style={{ height: 3000 }} />
</>
)
}
'use client'
import { useState } from 'react'
import { useRouter } from 'next/navigation'
export function SearchBox({ testId }: { testId: string }) {
const router = useRouter()
const [value, setValue] = useState('')
return (
<input
autoFocus
data-testid={testId}
placeholder="Search"
value={value}
onChange={(event) => {
const nextValue = event.target.value
setValue(nextValue)
router.push('?q=' + encodeURIComponent(nextValue))
}}
/>
)
}
import { SearchBox } from '../search-box'
// Same input as `/`, but prerendered static (no force-dynamic).
export default function StaticPage() {
return <SearchBox testId="static-search-input" />
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
...@@ -4,6 +4,8 @@ import { retry } from 'next-test-utils' ...@@ -4,6 +4,8 @@ import { retry } from 'next-test-utils'
const enableNewScrollHandler = const enableNewScrollHandler =
process.env.__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER !== 'false' process.env.__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER !== 'false'
// The new handler leaves focus on the clicked link; the old handler focuses the
// navigated segment.
describe('navigation-focus', () => { describe('navigation-focus', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
...@@ -17,9 +19,9 @@ describe('navigation-focus', () => { ...@@ -17,9 +19,9 @@ describe('navigation-focus', () => {
// Good debug info is a moving target. Use Playwright traces to find out // Good debug info is a moving target. Use Playwright traces to find out
// what was focused if this fails // what was focused if this fails
if (enableNewScrollHandler) { if (enableNewScrollHandler) {
expect(await browser.eval(() => document.activeElement.localName)).toBe( expect(
'body' await browser.eval(() => document.activeElement.getAttribute('href'))
) ).toBe('/interactive-segment')
} else { } else {
expect( expect(
await browser.eval(() => await browser.eval(() =>
...@@ -36,9 +38,9 @@ describe('navigation-focus', () => { ...@@ -36,9 +38,9 @@ describe('navigation-focus', () => {
await retry(async () => { await retry(async () => {
if (enableNewScrollHandler) { if (enableNewScrollHandler) {
expect(await browser.eval(() => document.activeElement.localName)).toBe( expect(
'body' await browser.eval(() => document.activeElement.getAttribute('href'))
) ).toBe('/scrollable-segment')
} else { } else {
expect( expect(
await browser.eval(() => await browser.eval(() =>
...@@ -56,17 +58,10 @@ describe('navigation-focus', () => { ...@@ -56,17 +58,10 @@ describe('navigation-focus', () => {
.click() .click()
await retry(async () => { await retry(async () => {
if (enableNewScrollHandler) { // Focus stays on the original link in both handlers.
// Focus goes to the focusable descendant, not the segment itself expect(
expect(await browser.eval(() => document.activeElement.localName)).toBe( await browser.eval(() => document.activeElement.getAttribute('href'))
'body' ).toBe('/segment-with-focusable-descendant')
)
} else {
// Focus stays on the original link
expect(
await browser.eval(() => document.activeElement.getAttribute('href'))
).toBe('/segment-with-focusable-descendant')
}
}) })
}) })
...@@ -75,16 +70,10 @@ describe('navigation-focus', () => { ...@@ -75,16 +70,10 @@ describe('navigation-focus', () => {
await browser.elementByCss('a[href="/uri-fragments#section-2"]').click() await browser.elementByCss('a[href="/uri-fragments#section-2"]').click()
await retry(async () => { await retry(async () => {
if (enableNewScrollHandler) { // Focus stays on the anchor unlike native behavior.
expect(await browser.eval(() => document.activeElement.localName)).toBe( expect(
'body' await browser.eval(() => document.activeElement.getAttribute('href'))
) ).toEqual('/uri-fragments#section-2')
} else {
// Focus stays on the anchor unlike native behavior
expect(
await browser.eval(() => document.activeElement.getAttribute('href'))
).toEqual('/uri-fragments#section-2')
}
}) })
// Fragment URI not targetted unlike native behavior // Fragment URI not targetted unlike native behavior
expect(await browser.locator(':target').isVisible()).toEqual(false) expect(await browser.locator(':target').isVisible()).toEqual(false)
...@@ -95,16 +84,10 @@ describe('navigation-focus', () => { ...@@ -95,16 +84,10 @@ describe('navigation-focus', () => {
await browser.elementByCss('a[href="#section-1"]').click() await browser.elementByCss('a[href="#section-1"]').click()
await retry(async () => { await retry(async () => {
if (enableNewScrollHandler) { // Focus stays on the anchor unlike native behavior.
expect(await browser.eval(() => document.activeElement.localName)).toBe( expect(
'body' await browser.eval(() => document.activeElement.getAttribute('href'))
) ).toEqual('#section-1')
} else {
// Focus stays on the anchor unlike native behavior
expect(
await browser.eval(() => document.activeElement.getAttribute('href'))
).toEqual('#section-1')
}
}) })
// Fragment URI not targetted unlike native behavior // Fragment URI not targetted unlike native behavior
expect(await browser.locator(':target').isVisible()).toEqual(false) expect(await browser.locator(':target').isVisible()).toEqual(false)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment