Unverified Commit 5509e1bf authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[fragment-scroll] Stop focusing the first focusable host descendant (#89903)

Flagged behind `experimental.appNewScrollHandler`

`focus()` on Fragment refs works different than `findDOMNode(this).focus()`.

`findDOMNode` will return an actual host element so it's effectively `HTMLElement.focus()`. If the element isn't focuseable, `focus()` will do nothing. By spec, there's also no way to determine if an element is focusable. It's up to user agents (e.g. sometimes scrollable containers are considered focusable). 

`FragmentInstance.focus` will focus the first focusable descendant. That could be a focusable element deep within the fragment e.g. `<Fragment><section><p>A lot of text</p><a href="">Next page</a></Fragment>`. Focusing such a deep element may sometimes be counter productive.

Now we just blur the active element. This is how a hard navigation already works today and ensures we don't skip past content of the new segment.

This means you potentially stay a long way before the actual Segment (e.g. in a preceding nav) with the focus cursor which could be annoying. We could be clever and temporarily insert a focusable element at the start of the Segment, focus it, and then immediately remove. That would leave the focus cursor right before the Segment. However, this requires knowledge about the parent content (can we just insert an element of our choosing?) and relies on knowing what's focusable (a button would be a good bet). That's a bit too clever for a fix without concrete motivation so I'm waiting somebody to complain about the new behavior.
parent e17b1152
...@@ -139,12 +139,12 @@ function getHashFragmentDomNode(hashFragment: string) { ...@@ -139,12 +139,12 @@ function getHashFragmentDomNode(hashFragment: string) {
document.getElementsByName(hashFragment)[0] document.getElementsByName(hashFragment)[0]
) )
} }
interface ScrollAndFocusHandlerProps { interface ScrollAndMaybeFocusHandlerProps {
focusAndScrollRef: FocusAndScrollRef focusAndScrollRef: FocusAndScrollRef
children: React.ReactNode children: React.ReactNode
segmentPath: FlightSegmentPath segmentPath: FlightSegmentPath
} }
class InnerScrollAndFocusHandlerOld extends React.Component<ScrollAndFocusHandlerProps> { class InnerScrollAndFocusHandlerOld extends React.Component<ScrollAndMaybeFocusHandlerProps> {
handlePotentialScroll = () => { handlePotentialScroll = () => {
// Handle scroll and focus, it's only applied once. // Handle scroll and focus, it's only applied once.
const { focusAndScrollRef, segmentPath } = this.props const { focusAndScrollRef, segmentPath } = this.props
...@@ -265,7 +265,11 @@ class InnerScrollAndFocusHandlerOld extends React.Component<ScrollAndFocusHandle ...@@ -265,7 +265,11 @@ class InnerScrollAndFocusHandlerOld extends React.Component<ScrollAndFocusHandle
} }
} }
function InnerScrollAndFocusHandlerNew(props: ScrollAndFocusHandlerProps) { /**
* Fork of InnerScrollAndFocusHandlerOld using Fragment refs for scrolling.
* No longer focuses the first host descendant.
*/
function InnerScrollHandlerNew(props: ScrollAndMaybeFocusHandlerProps) {
const childrenRef = React.useRef<FragmentInstance>(null) const childrenRef = React.useRef<FragmentInstance>(null)
useLayoutEffect( useLayoutEffect(
...@@ -309,6 +313,22 @@ function InnerScrollAndFocusHandlerNew(props: ScrollAndFocusHandlerProps) { ...@@ -309,6 +313,22 @@ function InnerScrollAndFocusHandlerNew(props: ScrollAndFocusHandlerProps) {
focusAndScrollRef.hashFragment = null focusAndScrollRef.hashFragment = null
focusAndScrollRef.segmentPaths = [] focusAndScrollRef.segmentPaths = []
const activeElement = document.activeElement
if (
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(
() => { () => {
// In case of hash scroll, we only need to scroll the element into view // In case of hash scroll, we only need to scroll the element into view
...@@ -348,11 +368,6 @@ function InnerScrollAndFocusHandlerNew(props: ScrollAndFocusHandlerProps) { ...@@ -348,11 +368,6 @@ function InnerScrollAndFocusHandlerNew(props: ScrollAndFocusHandlerProps) {
// Mutate after scrolling so that it can be read by `disableSmoothScrollDuringRouteTransition` // Mutate after scrolling so that it can be read by `disableSmoothScrollDuringRouteTransition`
focusAndScrollRef.onlyHashChange = false focusAndScrollRef.onlyHashChange = false
// Set focus on the element but don't scroll since we already did that.
// The focus might have targetted a deep element outside of the instances
// top edge.
instance.focus({ preventScroll: true })
} }
}, },
// Used to run on every commit. We may be able to be smarter about this // Used to run on every commit. We may be able to be smarter about this
...@@ -363,11 +378,11 @@ function InnerScrollAndFocusHandlerNew(props: ScrollAndFocusHandlerProps) { ...@@ -363,11 +378,11 @@ function InnerScrollAndFocusHandlerNew(props: ScrollAndFocusHandlerProps) {
return <Fragment ref={childrenRef}>{props.children}</Fragment> return <Fragment ref={childrenRef}>{props.children}</Fragment>
} }
const InnerScrollAndFocusHandler = enableNewScrollHandler const InnerScrollAndMaybeFocusHandler = enableNewScrollHandler
? InnerScrollAndFocusHandlerNew ? InnerScrollHandlerNew
: InnerScrollAndFocusHandlerOld : InnerScrollAndFocusHandlerOld
function ScrollAndFocusHandler({ function ScrollAndMaybeFocusHandler({
segmentPath, segmentPath,
children, children,
}: { }: {
...@@ -380,12 +395,12 @@ function ScrollAndFocusHandler({ ...@@ -380,12 +395,12 @@ function ScrollAndFocusHandler({
} }
return ( return (
<InnerScrollAndFocusHandler <InnerScrollAndMaybeFocusHandler
segmentPath={segmentPath} segmentPath={segmentPath}
focusAndScrollRef={context.focusAndScrollRef} focusAndScrollRef={context.focusAndScrollRef}
> >
{children} {children}
</InnerScrollAndFocusHandler> </InnerScrollAndMaybeFocusHandler>
) )
} }
...@@ -768,7 +783,7 @@ export default function OuterLayoutRouter({ ...@@ -768,7 +783,7 @@ export default function OuterLayoutRouter({
<TemplateContext.Provider <TemplateContext.Provider
key={stateKey} key={stateKey}
value={ value={
<ScrollAndFocusHandler segmentPath={segmentPath}> <ScrollAndMaybeFocusHandler segmentPath={segmentPath}>
<ErrorBoundary <ErrorBoundary
errorComponent={error} errorComponent={error}
errorStyles={errorStyles} errorStyles={errorStyles}
...@@ -809,7 +824,7 @@ export default function OuterLayoutRouter({ ...@@ -809,7 +824,7 @@ export default function OuterLayoutRouter({
</LoadingBoundary> </LoadingBoundary>
</ErrorBoundary> </ErrorBoundary>
{segmentViewStateNode} {segmentViewStateNode}
</ScrollAndFocusHandler> </ScrollAndMaybeFocusHandler>
} }
> >
{templateStyles} {templateStyles}
......
...@@ -8,8 +8,8 @@ import { retry } from 'next-test-utils' ...@@ -8,8 +8,8 @@ import { retry } from 'next-test-utils'
const bundlerName = process.env.IS_TURBOPACK_TEST ? 'Turbopack' : 'Webpack' const bundlerName = process.env.IS_TURBOPACK_TEST ? 'Turbopack' : 'Webpack'
const enableNewScrollHandler = const enableNewScrollHandler =
process.env.__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER === 'true' process.env.__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER === 'true'
const innerScrollAndFocusHandlerName = enableNewScrollHandler const innerScrollAndMaybeFocusHandlerName = enableNewScrollHandler
? 'InnerScrollAndFocusHandlerNew' ? 'InnerScrollHandlerNew'
: 'InnerScrollAndFocusHandlerOld' : 'InnerScrollAndFocusHandlerOld'
function setupLogCapture() { function setupLogCapture() {
...@@ -336,8 +336,8 @@ describe(`Terminal Logging (${bundlerName})`, () => { ...@@ -336,8 +336,8 @@ describe(`Terminal Logging (${bundlerName})`, () => {
... ...
<RenderFromTemplateContext> <RenderFromTemplateContext>
<ScrollAndFocusHandler segmentPath={[...]}> <ScrollAndMaybeFocusHandler segmentPath={[...]}>
<${innerScrollAndFocusHandlerName} segmentPath={[...]} focusAndScrollRef={{apply:false, ...}}> <${innerScrollAndMaybeFocusHandlerName} segmentPath={[...]} focusAndScrollRef={{apply:false, ...}}>
<ErrorBoundary errorComponent={undefined} errorStyles={undefined} errorScripts={undefined}> <ErrorBoundary errorComponent={undefined} errorStyles={undefined} errorScripts={undefined}>
<LoadingBoundary name="hydration-..." loading={null}> <LoadingBoundary name="hydration-..." loading={null}>
<HTTPAccessFallbackBoundary notFound={undefined} forbidden={undefined} unauthorized={undefined}> <HTTPAccessFallbackBoundary notFound={undefined} forbidden={undefined} unauthorized={undefined}>
......
...@@ -16,11 +16,17 @@ describe('navigation-focus', () => { ...@@ -16,11 +16,17 @@ describe('navigation-focus', () => {
await retry(async () => { await retry(async () => {
// 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) {
expect(await browser.eval(() => document.activeElement.localName)).toBe(
'body'
)
} else {
expect( expect(
await browser.eval(() => await browser.eval(() =>
document.activeElement.getAttribute('data-testid') document.activeElement.getAttribute('data-testid')
) )
).toBe('segment-container') ).toBe('segment-container')
}
}) })
}) })
...@@ -29,11 +35,17 @@ describe('navigation-focus', () => { ...@@ -29,11 +35,17 @@ describe('navigation-focus', () => {
await browser.elementByCss('a[href="/scrollable-segment"]').click() await browser.elementByCss('a[href="/scrollable-segment"]').click()
await retry(async () => { await retry(async () => {
if (enableNewScrollHandler) {
expect(await browser.eval(() => document.activeElement.localName)).toBe(
'body'
)
} else {
expect( expect(
await browser.eval(() => await browser.eval(() =>
document.activeElement.getAttribute('data-testid') document.activeElement.getAttribute('data-testid')
) )
).toBe('segment-container') ).toBe('segment-container')
}
}) })
}) })
...@@ -46,9 +58,9 @@ describe('navigation-focus', () => { ...@@ -46,9 +58,9 @@ describe('navigation-focus', () => {
await retry(async () => { await retry(async () => {
if (enableNewScrollHandler) { if (enableNewScrollHandler) {
// Focus goes to the focusable descendant, not the segment itself // Focus goes to the focusable descendant, not the segment itself
expect( expect(await browser.eval(() => document.activeElement.localName)).toBe(
await browser.eval(() => document.activeElement.textContent) 'body'
).toBe('Focusable Button') )
} else { } else {
// Focus stays on the original link // Focus stays on the original link
expect( expect(
...@@ -63,10 +75,16 @@ describe('navigation-focus', () => { ...@@ -63,10 +75,16 @@ 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) {
expect(await browser.eval(() => document.activeElement.localName)).toBe(
'body'
)
} else {
// Focus stays on the anchor unlike native behavior // Focus stays on the anchor unlike native behavior
expect( expect(
await browser.eval(() => document.activeElement.getAttribute('href')) await browser.eval(() => document.activeElement.getAttribute('href'))
).toEqual('/uri-fragments#section-2') ).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)
...@@ -77,10 +95,16 @@ describe('navigation-focus', () => { ...@@ -77,10 +95,16 @@ 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) {
expect(await browser.eval(() => document.activeElement.localName)).toBe(
'body'
)
} else {
// Focus stays on the anchor unlike native behavior // Focus stays on the anchor unlike native behavior
expect( expect(
await browser.eval(() => document.activeElement.getAttribute('href')) await browser.eval(() => document.activeElement.getAttribute('href'))
).toEqual('#section-1') ).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)
......
...@@ -1487,12 +1487,12 @@ const nextjsClientComponentNames = [ ...@@ -1487,12 +1487,12 @@ const nextjsClientComponentNames = [
'HTTPAccessFallbackErrorBoundary', 'HTTPAccessFallbackErrorBoundary',
'InnerLayoutRouter', 'InnerLayoutRouter',
'InnerScrollAndFocusHandlerOld', 'InnerScrollAndFocusHandlerOld',
'InnerScrollAndFocusHandlerNew', 'InnerScrollHandlerNew',
'RedirectBoundary', 'RedirectBoundary',
'RedirectErrorBoundary', 'RedirectErrorBoundary',
'RenderFromTemplateContext', 'RenderFromTemplateContext',
'Root', 'Root',
'ScrollAndFocusHandler', 'ScrollAndMaybeFocusHandler',
'SegmentViewNode', 'SegmentViewNode',
'SegmentTrieNode', 'SegmentTrieNode',
// These are added due to user actions e.g. loading.js -> LoadingBoundary // These are added due to user actions e.g. loading.js -> LoadingBoundary
......
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