/
use-accordion.ts
375 lines (327 loc) · 10 KB
/
use-accordion.ts
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
import { createContext } from "@chakra-ui/react-context"
import { useControllableState } from "@chakra-ui/react-use-controllable-state"
import { mergeRefs } from "@chakra-ui/react-use-merge-refs"
import { callAllHandlers, warn } from "@chakra-ui/shared-utils"
import { useCallback, useEffect, useId, useRef, useState } from "react"
import {
useAccordionDescendant,
useAccordionDescendants,
} from "./accordion-context"
/* -------------------------------------------------------------------------------------------------
* useAccordion - The root react hook that manages all accordion items
* -----------------------------------------------------------------------------------------------*/
export type ExpandedIndex = number | number[]
export interface UseAccordionProps {
/**
* If `true`, multiple accordion items can be expanded at once.
*/
allowMultiple?: boolean
/**
* If `true`, any expanded accordion item can be collapsed again.
*/
allowToggle?: boolean
/**
* The index(es) of the expanded accordion item
*/
index?: ExpandedIndex
/**
* The initial index(es) of the expanded accordion item
*/
defaultIndex?: ExpandedIndex
/**
* The callback invoked when accordion items are expanded or collapsed.
*/
onChange?(expandedIndex: ExpandedIndex): void
}
/**
* useAccordion hook provides all the state and focus management logic
* for accordion items.
*
* @see WAI-ARIA https://www.w3.org/WAI/ARIA/apg/patterns/accordion/
*/
export function useAccordion(props: UseAccordionProps) {
const {
onChange,
defaultIndex,
index: indexProp,
allowMultiple,
allowToggle,
...htmlProps
} = props
// validate the props and `warn` if used incorrectly
allowMultipleWarning(props)
allowMultipleAndAllowToggleWarning(props)
/**
* Think of this as the register to each accordion item.
* We used to manage focus between accordion item buttons.
*
* Every accordion item, registers their button refs in this context
*/
const descendants = useAccordionDescendants()
/**
* This state is used to track the index focused accordion
* button when click on the button, tab on the button, or
* use the down/up arrow to navigate.
*/
const [focusedIndex, setFocusedIndex] = useState(-1)
/**
* Reset focused index when accordion unmounts
* or descendants change
*/
useEffect(() => {
return () => {
setFocusedIndex(-1)
}
}, [])
/**
* Hook that manages the controlled and un-controlled state
* for the accordion.
*/
const [index, setIndex] = useControllableState({
value: indexProp,
defaultValue() {
if (allowMultiple) return defaultIndex ?? []
return defaultIndex ?? -1
},
onChange,
})
/**
* Gets the `isOpen` and `onChange` props for a child accordion item based on
* the child's index.
*
* @param idx {number} The index of the child accordion item
*/
const getAccordionItemProps = (idx: number | null) => {
let isOpen = false
if (idx !== null) {
isOpen = Array.isArray(index) ? index.includes(idx) : index === idx
}
const onChange = (isOpen: boolean) => {
if (idx === null) return
if (allowMultiple && Array.isArray(index)) {
//
const nextState = isOpen
? index.concat(idx)
: index.filter((i) => i !== idx)
setIndex(nextState)
//
} else if (isOpen) {
setIndex(idx)
} else if (allowToggle) {
setIndex(-1)
}
}
return { isOpen, onChange }
}
return {
index,
setIndex,
htmlProps,
getAccordionItemProps,
focusedIndex,
setFocusedIndex,
descendants,
}
}
export type UseAccordionReturn = ReturnType<typeof useAccordion>
/* -------------------------------------------------------------------------------------------------
* Create context for the root accordion logic
* -----------------------------------------------------------------------------------------------*/
interface AccordionContext
extends Omit<UseAccordionReturn, "htmlProps" | "descendants"> {
reduceMotion: boolean
}
export const [AccordionProvider, useAccordionContext] =
createContext<AccordionContext>({
name: "AccordionContext",
hookName: "useAccordionContext",
providerName: "Accordion",
})
/* -------------------------------------------------------------------------------------------------
* Hook for a single accordion item
* -----------------------------------------------------------------------------------------------*/
export interface UseAccordionItemProps {
/**
* If `true`, the accordion item will be disabled.
*/
isDisabled?: boolean
/**
* If `true`, the accordion item will be focusable.
*/
isFocusable?: boolean
/**
* A unique id for the accordion item.
*/
id?: string
}
/**
* useAccordionItem
*
* React hook that provides the open/close functionality
* for an accordion item and its children
*/
export function useAccordionItem(props: UseAccordionItemProps) {
const { isDisabled, isFocusable, id, ...htmlProps } = props
const { getAccordionItemProps, setFocusedIndex } = useAccordionContext()
const buttonRef = useRef<HTMLElement>(null)
/**
* Generate unique ids for all accordion item components (button and panel)
*/
const reactId = useId()
const uid = id ?? reactId
const buttonId = `accordion-button-${uid}`
const panelId = `accordion-panel-${uid}`
focusableNotDisabledWarning(props)
/**
* Think of this as a way to register this accordion item
* with its parent `useAccordion`
*/
const { register, index, descendants } = useAccordionDescendant({
disabled: isDisabled && !isFocusable,
})
const { isOpen, onChange } = getAccordionItemProps(
index === -1 ? null : index,
)
warnIfOpenAndDisabled({ isOpen, isDisabled })
const onOpen = () => {
onChange?.(true)
}
const onClose = () => {
onChange?.(false)
}
/**
* Toggle the visibility of the accordion item
*/
const onClick = useCallback(() => {
onChange?.(!isOpen)
setFocusedIndex(index)
}, [index, setFocusedIndex, isOpen, onChange])
/**
* Manage keyboard navigation between accordion items.
*/
const onKeyDown = useCallback(
(event: React.KeyboardEvent) => {
const keyMap: Record<string, React.KeyboardEventHandler> = {
ArrowDown: () => {
const next = descendants.nextEnabled(index)
next?.node.focus()
},
ArrowUp: () => {
const prev = descendants.prevEnabled(index)
prev?.node.focus()
},
Home: () => {
const first = descendants.firstEnabled()
first?.node.focus()
},
End: () => {
const last = descendants.lastEnabled()
last?.node.focus()
},
}
const action = keyMap[event.key]
if (action) {
event.preventDefault()
action(event)
}
},
[descendants, index],
)
/**
* Since each accordion item's button still remains tabbable, let's
* update the focusedIndex when it receives focus
*/
const onFocus = useCallback(() => {
setFocusedIndex(index)
}, [setFocusedIndex, index])
const getButtonProps = useCallback(
function getButtonProps(
props: Omit<React.HTMLAttributes<HTMLElement>, "color"> = {},
ref: React.Ref<HTMLButtonElement> | null = null,
): React.ComponentProps<"button"> {
return {
...props,
type: "button",
ref: mergeRefs(register, buttonRef, ref),
id: buttonId,
disabled: !!isDisabled,
"aria-expanded": !!isOpen,
"aria-controls": panelId,
onClick: callAllHandlers(props.onClick, onClick),
onFocus: callAllHandlers(props.onFocus, onFocus),
onKeyDown: callAllHandlers(props.onKeyDown, onKeyDown),
}
},
[
buttonId,
isDisabled,
isOpen,
onClick,
onFocus,
onKeyDown,
panelId,
register,
],
)
const getPanelProps = useCallback(
function getPanelProps<T>(
props: Omit<React.HTMLAttributes<T>, "color"> = {},
ref: React.Ref<T> | null = null,
): React.HTMLAttributes<T> & React.RefAttributes<T> {
return {
...props,
ref,
role: "region",
id: panelId,
"aria-labelledby": buttonId,
hidden: !isOpen,
}
},
[buttonId, isOpen, panelId],
)
return {
isOpen,
isDisabled,
isFocusable,
onOpen,
onClose,
getButtonProps,
getPanelProps,
htmlProps,
}
}
export type UseAccordionItemReturn = ReturnType<typeof useAccordionItem>
/* -------------------------------------------------------------------------------------------------
* Validate accordion and accordion item props, and emit warnings.
* -----------------------------------------------------------------------------------------------*/
function allowMultipleWarning(props: UseAccordionProps) {
const index = props.index || props.defaultIndex
const condition =
index == null && !Array.isArray(index) && props.allowMultiple
warn({
condition: !!condition,
message: `If 'allowMultiple' is passed, then 'index' or 'defaultIndex' must be an array. You passed: ${typeof index},`,
})
}
function allowMultipleAndAllowToggleWarning(props: UseAccordionProps) {
warn({
condition: !!(props.allowMultiple && props.allowToggle),
message: `If 'allowMultiple' is passed, 'allowToggle' will be ignored. Either remove 'allowToggle' or 'allowMultiple' depending on whether you want multiple accordions visible or not`,
})
}
function focusableNotDisabledWarning(props: UseAccordionItemProps) {
warn({
condition: !!(props.isFocusable && !props.isDisabled),
message: `Using only 'isFocusable', this prop is reserved for situations where you pass 'isDisabled' but you still want the element to receive focus (A11y). Either remove it or pass 'isDisabled' as well.
`,
})
}
function warnIfOpenAndDisabled(props: {
isOpen: boolean
isDisabled?: boolean
}) {
warn({
condition: props.isOpen && !!props.isDisabled,
message: "Cannot open a disabled accordion item",
})
}