UNPKG

2.27 kBJavaScriptView Raw
1"use client";
2
3import * as React from 'react';
4import { useContext } from 'react';
5import classNames from 'classnames';
6import AccordionContext, { isAccordionItemSelected } from './AccordionContext';
7import AccordionItemContext from './AccordionItemContext';
8import { useBootstrapPrefix } from './ThemeProvider';
9import { jsx as _jsx } from "react/jsx-runtime";
10export function useAccordionButton(eventKey, onClick) {
11 const {
12 activeEventKey,
13 onSelect,
14 alwaysOpen
15 } = useContext(AccordionContext);
16 return e => {
17 /*
18 Compare the event key in context with the given event key.
19 If they are the same, then collapse the component.
20 */
21 let eventKeyPassed = eventKey === activeEventKey ? null : eventKey;
22 if (alwaysOpen) {
23 if (Array.isArray(activeEventKey)) {
24 if (activeEventKey.includes(eventKey)) {
25 eventKeyPassed = activeEventKey.filter(k => k !== eventKey);
26 } else {
27 eventKeyPassed = [...activeEventKey, eventKey];
28 }
29 } else {
30 // activeEventKey is undefined.
31 eventKeyPassed = [eventKey];
32 }
33 }
34 onSelect == null ? void 0 : onSelect(eventKeyPassed, e);
35 onClick == null ? void 0 : onClick(e);
36 };
37}
38const AccordionButton = /*#__PURE__*/React.forwardRef(({
39 // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595
40 as: Component = 'button',
41 bsPrefix,
42 className,
43 onClick,
44 ...props
45}, ref) => {
46 bsPrefix = useBootstrapPrefix(bsPrefix, 'accordion-button');
47 const {
48 eventKey
49 } = useContext(AccordionItemContext);
50 const accordionOnClick = useAccordionButton(eventKey, onClick);
51 const {
52 activeEventKey
53 } = useContext(AccordionContext);
54 if (Component === 'button') {
55 props.type = 'button';
56 }
57 return /*#__PURE__*/_jsx(Component, {
58 ref: ref,
59 onClick: accordionOnClick,
60 ...props,
61 "aria-expanded": Array.isArray(activeEventKey) ? activeEventKey.includes(eventKey) : eventKey === activeEventKey,
62 className: classNames(className, bsPrefix, !isAccordionItemSelected(activeEventKey, eventKey) && 'collapsed')
63 });
64});
65AccordionButton.displayName = 'AccordionButton';
66export default AccordionButton;
\No newline at end of file