Skip to content
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

[a11y] Route Announcements #20428

Merged
merged 31 commits into from
Mar 15, 2021
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
eafdb89
Add two client-navigation accessibility improvements:
kyleboss Dec 23, 2020
323a952
Merge branch 'canary' into client-nav-a11y
kyleboss Dec 23, 2020
e22817b
Merge branch 'canary' into client-nav-a11y
kyleboss Dec 28, 2020
9a48bca
Merge branch 'canary' into client-nav-a11y
kyleboss Dec 28, 2020
333ab3d
Merge branch 'canary' into client-nav-a11y
kyleboss Dec 28, 2020
7156183
Merge branch 'canary' into client-nav-a11y
kyleboss Dec 28, 2020
991cd67
Merge branch 'canary' of git://github.com/vercel/next.js into client-…
kyleboss Dec 28, 2020
ac60dcc
Merge branch 'canary' of git://github.com/vercel/next.js into client-…
kyleboss Dec 30, 2020
1c4bf60
Merge remote-tracking branch 'upstream/canary' into client-nav-a11y
Timer Jan 21, 2021
8cc9a83
Fix hydration mismatch
Timer Jan 21, 2021
c15507b
Relocate focus handling to router
Timer Jan 21, 2021
5c2dbe1
tweak build output numbers
Timer Jan 21, 2021
0080959
Update visually hidden styles
Timer Jan 21, 2021
8adf039
Fix import
Timer Jan 21, 2021
845063c
Merge branch 'canary' into client-nav-a11y
kyleboss Mar 9, 2021
9db8424
Remove logic for focusing on main or h1 if one exists. It's
kyleboss Mar 9, 2021
39ccbde
Apply suggestions from code review
shuding Mar 10, 2021
54dcfa3
simplify portal; fix the case where h1 is empty
shuding Mar 10, 2021
85ef996
do not announce on initial load
shuding Mar 10, 2021
b437b2e
Remove focus improvements. We will add these in a future PR.
kyleboss Mar 14, 2021
8884236
Merge branch 'client-nav-a11y' of https://github.com/kyleboss/next.js…
kyleboss Mar 14, 2021
902426a
I do not know why this was deleted?
kyleboss Mar 14, 2021
5293465
Trying to bring router back to the way it was?
kyleboss Mar 14, 2021
2b15725
Another attempt at bringing router back to normal
kyleboss Mar 14, 2021
8c28dd9
Merge remote-tracking branch 'upstream/canary' into client-nav-a11y
kyleboss Mar 14, 2021
0ce69dc
Another attempt at fixing router
kyleboss Mar 14, 2021
596ae18
fix tests
shuding Mar 15, 2021
9b21d10
fix tests
shuding Mar 15, 2021
54b5721
fix tests
shuding Mar 15, 2021
b70aa27
fix test
shuding Mar 15, 2021
8fc903e
Merge branch 'canary' into client-nav-a11y
kodiakhq[bot] Mar 15, 2021
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
5 changes: 5 additions & 0 deletions packages/next/client/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,11 @@ import {
NEXT_DATA,
ST,
} from '../next-server/lib/utils'
import { Portal } from './portal'
import initHeadManager from './head-manager'
import PageLoader, { StyleSheetTuple } from './page-loader'
import measureWebVitals from './performance-relayer'
import { RouteAnnouncer } from './route-announcer'
import { createRouter, makePublicRouterInstance } from './router'

/// <reference types="react-dom/experimental" />
Expand Down Expand Up @@ -777,6 +779,9 @@ function doRender(input: RenderRouteInfo): Promise<any> {
<Head callback={onHeadCommit} />
<AppContainer>
<App {...appProps} />
<Portal type="next-route-announcer">
<RouteAnnouncer />
</Portal>
</AppContainer>
</Root>
)
Expand Down
6 changes: 0 additions & 6 deletions packages/next/client/link.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,12 +103,6 @@ function linkClicked(
shallow,
locale,
scroll,
}).then((success: boolean) => {
if (!success) return
if (scroll) {
// FIXME: proper route announcing at Router level, not Link:
document.body.focus()
}
})
}

Expand Down
9 changes: 9 additions & 0 deletions packages/next/client/portal/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
The MIT License (MIT)

Copyright (c) 2018-present, React Training LLC

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
39 changes: 39 additions & 0 deletions packages/next/client/portal/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import * as React from 'react'
import { createPortal } from 'react-dom'

type PortalProps = {
children: React.ReactNode
type: string
}

export const Portal: React.FC<PortalProps> = ({ children, type }) => {
let [isMounted, setMounted] = React.useState(false)
let mountNode = React.useRef<HTMLDivElement | null>(null)
let portalNode = React.useRef<HTMLElement | null>(null)
let [, forceUpdate] = React.useState<{}>()
React.useEffect(() => {
setMounted(true)
}, [])
shuding marked this conversation as resolved.
Show resolved Hide resolved
React.useEffect(() => {
if (!isMounted) return
// This ref may be null when a hot-loader replaces components on the page
if (!mountNode.current) return
// It's possible that the content of the portal has, itself, been portaled.
// In that case, it's important to append to the correct document element.
const ownerDocument = mountNode.current!.ownerDocument
portalNode.current = ownerDocument?.createElement(type)!
ownerDocument!.body.appendChild(portalNode.current)
forceUpdate({})
return () => {
if (portalNode.current && portalNode.current.ownerDocument) {
portalNode.current.ownerDocument.body.removeChild(portalNode.current)
}
}
}, [type, forceUpdate, isMounted])
shuding marked this conversation as resolved.
Show resolved Hide resolved

return portalNode.current ? (
createPortal(children, portalNode.current)
) : isMounted ? (
<span ref={mountNode} />
) : null
}
58 changes: 58 additions & 0 deletions packages/next/client/route-announcer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import React, { useEffect, useState } from 'react'
import { useRouter } from './router'

export function RouteAnnouncer() {
const router = useRouter()
const [routeAnnouncement, setRouteAnnouncement] = useState('')

const { asPath } = router

// Every time the path changes, announce the route change. The announcement will be prioritized by h1, then title
// (from metadata), and finally if those don't exist, then the pathName that is in the URL. This methodology is
// inspired by Marcy Sutton's accessible client routing user testing. More information can be found here:
// https://www.gatsbyjs.com/blog/2019-07-11-user-testing-accessible-client-routing/
useEffect(
() => {
let newRouteAnnouncement
const pageHeader = document.querySelector('h1')

if (pageHeader) {
newRouteAnnouncement = pageHeader.innerText
shuding marked this conversation as resolved.
Show resolved Hide resolved
} else if (document.title) {
newRouteAnnouncement = document.title
} else {
newRouteAnnouncement = asPath
}

setRouteAnnouncement(newRouteAnnouncement)
},
// TODO: switch to pathname + query object of dynamic route requirements
[asPath]
)

return (
<div
Copy link
Contributor

Choose a reason for hiding this comment

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

A paragraph would be a little better semantically. :)

aria-atomic // Always announce the entire path.
aria-live="assertive" // Make the announcement immediately.
role="alert"
style={{
border: 0,
clip: 'rect(0 0 0 0)',
height: '1px',
margin: '-1px',
overflow: 'hidden',
padding: 0,
position: 'absolute',
width: '1px',

// https://medium.com/@jessebeach/beware-smushed-off-screen-accessible-text-5952a4c2cbfe
whiteSpace: 'nowrap',
wordWrap: 'normal',
}}
>
{routeAnnouncement}
</div>
)
}

export default RouteAnnouncer
35 changes: 35 additions & 0 deletions packages/next/next-server/lib/router/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,36 @@ function prepareUrlAs(router: NextRouter, url: Url, as?: Url) {
}
}

// Focus a user's attention to the beginning of new content. This is done by focusing the first h1 tag. If an h1 does
// not exist, focus the main semantic tag. If this does not exist, focus the cursor on the body. This methodology is
// inspired by Marcy Sutton's accessible client routing user testing. More information can be found here:
// https://www.gatsbyjs.com/blog/2019-07-11-user-testing-accessible-client-routing/
function a11ySmartFocus() {
Copy link
Contributor

@KittyGiraudel KittyGiraudel Mar 8, 2021

Choose a reason for hiding this comment

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

So I did not test it yet, but I am pretty sure this is going to announce the document’s title twice. Once from RouteAnnouncer, since it’s an assertive live region, and then a second time when focusing the document’s main title.

I’m not entirely certain, but it feels like you are mixing two approaches here:

  1. Focusing the main heading. Upon route change, and provided you can guarantee there will be a <h1> element regardless of state such as loading, move the focus to the main heading. As a result, its content will be announced.

  2. Announcing the page title. If the presence of a <h1> cannot be guaranteed for any reason (because left to the implementor who might not know, or because depending on loading states for instance), move the focus to a visually hidden node as <body>’s first child containing the new document title (which doesn‘t have to be a region whatsoever).

Both are equally good as far as I know. The main difference is where the focus ends up being. In the first approach, the focus is moved to the main page title, which could be anywhere in the page, really. Some sites have it in the title, some have it in the main container, some have it after the navigation, some before… In the second case, the focus is consistently moved at the top of the body (where the RouteAnnouncer DOM node lives), just like a regular href link would after a page load.

Because you appear to be essentially doing both, I am pretty certain this will announce the document’s main title twice, which is probably not what you want. I might be entirely mistaken though, so feel free to correct me. :)

Edit: a little more information in that article.

Edit 2: Finding the first <h1> element on the page could lead to issues if a hidden dialog with a <h1> element is being rendered high up the body element. That heading will be queried because it’s the first, but attempting to focus it would not work because it is within a hidden dialog.

Copy link

Choose a reason for hiding this comment

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

I agree with the last point about the h1 selector which is a bit dangerous because it contains an assumption about the website structure.

Also the explanation about how the title is now announced twice sounds reasonable to me, but haven't tried what happens.

Copy link
Contributor Author

@kyleboss kyleboss Mar 9, 2021

Choose a reason for hiding this comment

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

Hey! Thank you so much for taking the time to look at this, and more importantly, for the feedback! ❤️

I think your judgement is 100% valid. The intent here was to bring focus to the most important part of the page; however, this makes quite a few assumptions about the user's site. For example, the heading might be visually hidden. This alone makes me think that, while focusing on the top-most heading might be helpful for many sites, just focusing on the body will be best. So I will remove the logic for querying the header for the purpose of focusing.

The following is probably a moot point, but because the <RouteAnnouncer /> uses aria-live="assertive", the screen reader is expected to stop what it's doing and announce the new page name. Since the focus & route announcement happen at the same time, most screen readers will give priority to the <RouteAnnouncer /> and not announce the focused element. I've tested this on a few screen readers.

Look out for a commit soon with this change 😉

Copy link
Contributor

Choose a reason for hiding this comment

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

Hey Kyle! Thank you for taking the time to reply. 😊

My personal suggestion—which was recommended to me by @goetsu when he conducted an audit of the N26 platform a few years back—is to have this small visually hidden text node containing the up-to-date page title at the top of the body element, and moving the focus to it on page change.

<body>
  <p class="sr-only" tabindex="-1">Careers</p>

By focusing this element—which is ultimately similar to focusing the body—you can skip the whole aria region thing. When this element receives the focus, its content is read out loud. Done and simple.

Copy link
Contributor Author

@kyleboss kyleboss Mar 10, 2021

Choose a reason for hiding this comment

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

Oh, I absolutely love this idea! It's really elegant. I can already tell that this will decrease the complexity significantly. Thanks @KittyGiraudel!

I am putting this into a commit now!

Copy link
Member

Choose a reason for hiding this comment

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

I don't know if it's solvable here, but I don't see that being discussed—this refocus behavior breaks autoFocus elements as they won't be focused on page transition anymore. However the autoFocus attribute itself might be a bad thing for a11y, so I'm not sure what the best solution is.

Copy link
Contributor Author

@kyleboss kyleboss Mar 13, 2021

Choose a reason for hiding this comment

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

@shuding, that's a very good point. autoFocus is broken with this PR. As to not break any functionality, I'll hold off on the focusing-side of this PR and dedicate a new PR for it in the near-future.

Copy link
Member

Choose a reason for hiding this comment

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

Thank you @kyleboss, I'll land the Route Announcer part then 👍

const elementToFocus =
document.querySelector('h1') ||
document.querySelector('main') ||
document.body

if (elementToFocus) {
const didTabIndexExist = elementToFocus.getAttribute('tabIndex')

// Only elements with a tabIndex are focusable. So we add a tabIndex here just to make it focusable.
if (!didTabIndexExist) {
elementToFocus.setAttribute('tabIndex', '-1')
}

elementToFocus.focus()

// Once the focus leaves the element, we should clean up the tabIndex, if we added one. This is so the screen-reader
// does not try to focus the element for purposes other than the initial client-navigation.
if (!didTabIndexExist) {
elementToFocus.addEventListener('blur', () => {
elementToFocus.removeAttribute('tabIndex')
})
}
}
}

export type BaseRouter = {
route: string
pathname: string
Expand Down Expand Up @@ -1129,6 +1159,11 @@ export default class Router implements BaseRouter {
document.documentElement.lang = this.locale
}
}

if (!options.shallow) {
a11ySmartFocus()
}

Router.events.emit('routeChangeComplete', as, routeProps)

return true
Expand Down
10 changes: 5 additions & 5 deletions test/integration/build-output/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,17 +94,17 @@ describe('Build Output', () => {
expect(parseFloat(indexSize) - 266).toBeLessThanOrEqual(0)
expect(indexSize.endsWith('B')).toBe(true)

// should be no bigger than 63.8 kb
expect(parseFloat(indexFirstLoad)).toBeCloseTo(63.8, 1)
// should be no bigger than 64.4 kb
expect(parseFloat(indexFirstLoad)).toBeCloseTo(64.4, 1)
expect(indexFirstLoad.endsWith('kB')).toBe(true)

expect(parseFloat(err404Size) - 3.7).toBeLessThanOrEqual(0)
expect(err404Size.endsWith('kB')).toBe(true)

expect(parseFloat(err404FirstLoad)).toBeCloseTo(67, 1)
expect(parseFloat(err404FirstLoad)).toBeCloseTo(67.6, 1)
expect(err404FirstLoad.endsWith('kB')).toBe(true)

expect(parseFloat(sharedByAll)).toBeCloseTo(63.5, 1)
expect(parseFloat(sharedByAll)).toBeCloseTo(64.1, 1)
expect(sharedByAll.endsWith('kB')).toBe(true)

if (_appSize.endsWith('kB')) {
Expand Down Expand Up @@ -168,7 +168,7 @@ describe('Build Output', () => {
expect(parseFloat(indexSize)).toBeGreaterThanOrEqual(2)
expect(indexSize.endsWith('kB')).toBe(true)

expect(parseFloat(indexFirstLoad)).toBeLessThanOrEqual(66.6)
expect(parseFloat(indexFirstLoad)).toBeLessThanOrEqual(67.2)
expect(parseFloat(indexFirstLoad)).toBeGreaterThanOrEqual(60)
expect(indexFirstLoad.endsWith('kB')).toBe(true)
})
Expand Down
1 change: 1 addition & 0 deletions test/integration/client-navigation-a11y/next.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = {}
20 changes: 20 additions & 0 deletions test/integration/client-navigation-a11y/pages/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import Link from 'next/link'

export default () => (
<>
<Link href="/with-h1">
<a id="with-h1-link">With h1 element</a>
</Link>
<Link href="/with-h1-and-tab-index">
<a id="with-h1-and-tab-index-link">
With h1 element that has a tab index
</a>
</Link>
<Link href="/with-main">
<a id="with-main-link">With main element</a>
</Link>
<Link href="/without-main">
<a id="without-main-link">Without main element</a>
</Link>
</>
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export default () => (
<main id="navigation-result-container">
<h1 tabIndex="2">My heading</h1>
<div>Extraneous stuff</div>
</main>
)
6 changes: 6 additions & 0 deletions test/integration/client-navigation-a11y/pages/with-h1.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export default () => (
<main id="navigation-result-container">
<h1>My heading</h1>
<div>Extraneous stuff</div>
</main>
)
6 changes: 6 additions & 0 deletions test/integration/client-navigation-a11y/pages/with-main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export default () => (
<main id="navigation-result-container">
<div>My heading</div>
<div>Extraneous stuff</div>
</main>
)
6 changes: 6 additions & 0 deletions test/integration/client-navigation-a11y/pages/without-main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export default () => (
<div id="navigation-result-container">
<div>My heading</div>
<div>Extraneous stuff</div>
</div>
)
115 changes: 115 additions & 0 deletions test/integration/client-navigation-a11y/test/index.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/* eslint-env jest */

import {
findPort,
killApp,
launchApp,
renderViaHTTP,
} from '../../../lib/next-test-utils'
import webdriver from 'next-webdriver'
import { join } from 'path'

const context = {}
jest.setTimeout(1000 * 60 * 5)

describe('Client Navigation accessibility', () => {
beforeAll(async () => {
context.appPort = await findPort()
context.server = await launchApp(join(__dirname, '../'), context.appPort, {
env: { __NEXT_TEST_WITH_DEVTOOL: 1 },
})

const prerender = [
'/with-h1',
'/with-h1-and-tab-index',
'/with-main',
'/without-main',
]

await Promise.all(
prerender.map((route) => renderViaHTTP(context.appPort, route))
)
})

afterAll(() => killApp(context.server))

describe('the next route has an h1 element', () => {
it('brings focus to the h1 element', async () => {
const browser = await webdriver(context.appPort, '/')
await browser
.waitForElementByCss('#with-h1-link')
.click()
.waitForElementByCss('#navigation-result-container')

const isH1Focused = await browser.eval(
'document.activeElement === document.querySelector("h1")'
)
expect(isH1Focused).toBe(true)

await browser.close()
})
})

describe('the next route has a main element', () => {
it('brings focus to the main element', async () => {
const browser = await webdriver(context.appPort, '/')
await browser
.waitForElementByCss('#with-main-link')
.click()
.waitForElementByCss('#navigation-result-container')

const isMainFocused = await browser.eval(
'document.activeElement === document.querySelector("main")'
)
expect(isMainFocused).toBe(true)

await browser.close()
})
})

describe('the next route has neither a main nor h1 element', () => {
it('brings focus to the body', async () => {
const browser = await webdriver(context.appPort, '/')
await browser
.waitForElementByCss('#without-main-link')
.click()
.waitForElementByCss('#navigation-result-container')

const isBodyFocused = await browser.eval(
'document.activeElement === document.body'
)
expect(isBodyFocused).toBe(true)
})
})

describe('tabIndex of focused element does not exist', () => {
it('is set to -1', async () => {
const browser = await webdriver(context.appPort, '/')
const tabIndex = await browser
.waitForElementByCss('#with-h1-link')
.click()
.waitForElementByCss('#navigation-result-container')
.elementByCss('h1')
.getAttribute('tabIndex')

expect(tabIndex).toBe('-1')
await browser.close()
})
})

describe('tabIndex of focused element exists', () => {
it('does not change', async () => {
const browser = await webdriver(context.appPort, '/')
const tabIndex = await browser
.waitForElementByCss('#with-h1-and-tab-index-link')
.click()
.waitForElementByCss('#navigation-result-container')
.elementByCss('h1')
.getAttribute('tabIndex')

expect(tabIndex).toBe('2')

await browser.close()
})
})
})