-
Notifications
You must be signed in to change notification settings - Fork 68.3k
Expand file tree
/
Copy pathInArticlePicker.tsx
More file actions
199 lines (182 loc) · 7.06 KB
/
Copy pathInArticlePicker.tsx
File metadata and controls
199 lines (182 loc) · 7.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'
import Cookies from '@/frame/components/lib/cookies'
import { UnderlineNav } from '@primer/react'
import { sendEvent } from '@/events/components/events'
import { EventType } from '@/events/types'
import { useRouter } from 'next/router'
import styles from './InArticlePicker.module.scss'
const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect
type Option = {
value: string
label: string
}
type Props = {
// Use this if not specified on the query string
defaultValue?: string
// Use this if not specified on the query string or no cookie
fallbackValue: string
cookieKey: string
queryStringKey: string
onValue: (value: string) => void
preferenceName: string
options: Option[]
ariaLabel: string
}
export const InArticlePicker = ({
defaultValue,
fallbackValue,
cookieKey,
queryStringKey,
onValue,
preferenceName,
options,
ariaLabel,
}: Props) => {
const router = useRouter()
const { query, locale } = router
const [currentValue, setCurrentValue] = useState('')
// Tracks whether the last currentValue change was triggered by a user click
// (as opposed to initial mount or external navigation). When true, we move
// focus to the newly-selected tab so keyboard users don't lose their place.
const focusAfterNavRef = useRef(false)
// Run on mount for client-side only features
useEffect(() => {
const raw = query[queryStringKey]
let value = ''
if (raw) {
if (Array.isArray(raw)) value = raw[0]
else value = raw
}
// Only pick it up from the possible query string if its value
// is a valid option.
const possibleValues = options.map((option) => option.value)
if (!value || !possibleValues.includes(value)) {
const cookieValue = Cookies.get(cookieKey)
if (defaultValue) {
value = defaultValue
} else if (cookieValue && possibleValues.includes(cookieValue)) {
value = cookieValue
} else {
value = fallbackValue
}
}
setCurrentValue(value)
}, [query, fallbackValue, defaultValue, options])
const [asPathRoot, asPathQuery = ''] = router.asPath.split('#')[0].split('?')
// Use a layout effect so the DOM mutation (hiding non-matching .ghd-tool
// content) happens before the browser paints. With React 19's stricter
// effect timing, a regular useEffect could leave non-matching content
// visible on initial page load until after first paint.
useIsomorphicLayoutEffect(() => {
// This will make the hook run this callback on mount and on change.
// That's important because even though the user hasn't interacted
// and made an overriding choice, we still want to run this callback
// because the page might need to be corrected based on *a* choice
// independent of whether it's a change.
if (currentValue) {
onValue(currentValue)
}
}, [
currentValue,
// This is important because we can't otherwise rely on the firing
// of this effect on initial mount. It also needs to fire when the
// URL (i.e. route) changes.
// Don't use `router.asPath` because that contains the query string
// which we handle in the other useEffect above.
asPathRoot,
])
// This is exclusively for local development.
// If you're in local development, you have the <ClientSideRefresh>
// causing a XHR refresh of the content triggered by the Page Visibility
// API (implemented in the uswSWR hook). That means that on the pages that
// contain these `.ghd-tool` classes, any DOM changes we might
// have previously made are lost and started over.
useEffect(() => {
let mounted = true
const toggleVisibility = () => {
if (document.visibilityState === 'visible') {
// We don't need to track this timer, and possibly cancel it on
// dismount, because within the callback we use the `mounted`
// boolean which means we can know to do nothing if the parent
// component has been dismounted.
// The reason this is wrapped in a short timeout is because the
// React rendering might not actually have fully updated the DOM
// (from the XHR HTML it receives) so allow the DOM to refresh
// first before asking it to change. The number can be quite low
// (which is sufficient for human eyes) but must be at least
// in the lower hundreds of milliseconds.
setTimeout(() => {
if (mounted) {
onValue(currentValue)
}
}, 100)
}
}
if (process.env.NODE_ENV === 'development') {
document.addEventListener('visibilitychange', toggleVisibility)
}
return () => {
mounted = false
if (process.env.NODE_ENV === 'development') {
document.removeEventListener('visibilitychange', toggleVisibility)
}
}
}, [currentValue])
function onClickChoice(value: string) {
focusAfterNavRef.current = true
const params = new URLSearchParams(asPathQuery)
params.set(queryStringKey, value)
const newPath = `/${locale}${asPathRoot}?${params}`
router.push(newPath, undefined, { shallow: true, locale })
sendEvent({
type: EventType.preference,
preference_name: preferenceName,
preference_value: value,
})
Cookies.set(cookieKey, value)
}
// After a user clicks a tab, the shallow route change updates `currentValue`.
// Once the DOM reflects the new selection (aria-current="page" is on the new
// tab), move keyboard focus there so the user's context is preserved.
// WCAG 2.4.3 Focus Order — focus must land on the triggered control.
useEffect(() => {
if (!focusAfterNavRef.current || !currentValue) return
focusAfterNavRef.current = false
const container = document.querySelector<HTMLElement>(
`[data-testid="${queryStringKey}-picker"]`,
)
const selectedTab = container?.querySelector<HTMLElement>('[aria-current="page"]')
selectedTab?.focus()
}, [currentValue, queryStringKey])
const sharedContainerProps = {
'aria-label': ariaLabel,
}
const params = new URLSearchParams(asPathQuery)
return (
<div data-testid={`${queryStringKey}-picker`} className={styles.container}>
{/* The key attribute is required for a bug in UnderlineNav that doesn't render the component when there are changes to the items. */}
<UnderlineNav key={router.asPath} {...sharedContainerProps}>
{options.map((option) => {
params.set(queryStringKey, option.value)
const linkProps = {
[`data-${queryStringKey}`]: option.value,
}
return (
<UnderlineNav.Item
href={`?${params}`}
key={option.value}
aria-current={option.value === currentValue ? 'page' : undefined}
onSelect={(event: React.MouseEvent | React.KeyboardEvent) => {
event.preventDefault()
onClickChoice(option.value)
}}
{...linkProps}
>
{option.label}
</UnderlineNav.Item>
)
})}
</UnderlineNav>
</div>
)
}