2021-07-14 20:12:04 +02:00
|
|
|
|
import React from 'react'
|
2021-03-15 21:18:11 +01:00
|
|
|
|
import { useRouter } from './router'
|
|
|
|
|
|
|
|
|
|
export function RouteAnnouncer() {
|
|
|
|
|
const { asPath } = useRouter()
|
2021-07-14 20:12:04 +02:00
|
|
|
|
const [routeAnnouncement, setRouteAnnouncement] = React.useState('')
|
2021-03-15 21:18:11 +01:00
|
|
|
|
|
2021-11-08 15:58:21 +01:00
|
|
|
|
// Only announce the path change, but not for the first load because screen
|
|
|
|
|
// reader will do that automatically.
|
2022-02-14 20:18:39 +01:00
|
|
|
|
const previouslyLoadedPath = React.useRef(asPath)
|
2021-03-15 21:18:11 +01:00
|
|
|
|
|
2021-11-08 15:58:21 +01:00
|
|
|
|
// Every time the path changes, announce the new page’s title following this
|
|
|
|
|
// priority: first the document title (from head), otherwise the first h1, or
|
|
|
|
|
// if none of these exist, then the pathname from the URL. This methodology is
|
|
|
|
|
// inspired by Marcy Sutton’s accessible client routing user testing. More
|
|
|
|
|
// information can be found here:
|
2021-03-15 21:18:11 +01:00
|
|
|
|
// https://www.gatsbyjs.com/blog/2019-07-11-user-testing-accessible-client-routing/
|
2021-07-14 20:12:04 +02:00
|
|
|
|
React.useEffect(
|
2021-03-15 21:18:11 +01:00
|
|
|
|
() => {
|
2022-02-14 20:18:39 +01:00
|
|
|
|
// If the path hasn't change, we do nothing.
|
|
|
|
|
if (previouslyLoadedPath.current === asPath) return
|
|
|
|
|
previouslyLoadedPath.current = asPath
|
2021-03-15 21:18:11 +01:00
|
|
|
|
|
2021-11-08 15:58:21 +01:00
|
|
|
|
if (document.title) {
|
|
|
|
|
setRouteAnnouncement(document.title)
|
|
|
|
|
} else {
|
|
|
|
|
const pageHeader = document.querySelector('h1')
|
|
|
|
|
const content = pageHeader?.innerText ?? pageHeader?.textContent
|
2021-03-15 21:18:11 +01:00
|
|
|
|
|
2021-11-08 15:58:21 +01:00
|
|
|
|
setRouteAnnouncement(content || asPath)
|
2021-03-15 21:18:11 +01:00
|
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
// TODO: switch to pathname + query object of dynamic route requirements
|
|
|
|
|
[asPath]
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
return (
|
|
|
|
|
<p
|
|
|
|
|
aria-live="assertive" // Make the announcement immediately.
|
|
|
|
|
id="__next-route-announcer__"
|
|
|
|
|
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}
|
|
|
|
|
</p>
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export default RouteAnnouncer
|