Accordion = props => {
    const { id, children, style, className, activeSectionNames, multiple, onToggleSection } = props;
    const containerRef = useRef();

    const [activeNames, setActiveNames] = useState(activeSectionNames);
    const [currentSection, setCurrentSection] = useState();

    const { childrenRegistered, register, unregister } = useChildrenRegisterRef({
        containerRef,
        selector: SELECTOR,
    });

    useEffect(() => {
        if (activeSectionNames !== activeNames) {
            setActiveNames(activeSectionNames);
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [activeSectionNames]);

    const handleToggleSection = (event, name) => {
        if (typeof onToggleSection === 'function') {
            return onToggleSection(event, name);
        }
        return setActiveNames(name);
    };

    const setAsSelectAccordionSection = accordionSectionIndex => {
        childrenRegistered[accordionSectionIndex].focusButton();
    };

    const selectAccordionSection = side => {
        const accordionSectionIndex = childrenRegistered.findIndex(
            section => section.id === currentSection,
        );

        if (accordionSectionIndex === childrenRegistered.length - 1 && side === RIGHT_SIDE) {
            setAsSelectAccordionSection(0);
        } else if (accordionSectionIndex === 0 && side === LEFT_SIDE) {
            setAsSelectAccordionSection(childrenRegistered.length - 1);
        } else {
            setAsSelectAccordionSection(accordionSectionIndex + side);
        }
    };

    const keyHandlerMap = {
        [RIGHT_KEY]: () => selectAccordionSection(RIGHT_SIDE),
        [LEFT_KEY]: () => selectAccordionSection(LEFT_SIDE),
        [DOWN_KEY]: () => selectAccordionSection(RIGHT_SIDE),
        [UP_KEY]: () => selectAccordionSection(LEFT_SIDE),
    };

    const handleKeyPressed = event => {
        if (keyHandlerMap[event.keyCode]) {
            event.preventDefault();
            return keyHandlerMap[event.keyCode]();
        }
        return null;
    };

    const context = {
        activeNames,
        multiple,
        privateOnToggleSection: handleToggleSection,
        privateOnFocusSection: setCurrentSection,
        privateRegisterAccordionSection: register,
        privateUnregisterAccordionSection: unregister,
        privateOnKeyPressed: handleKeyPressed,
    };

    return (
        <StyledUl ref={containerRef} id={id} className={className} style={style}>
            <Provider value={context}>{children}</Provider>
        </StyledUl>
    );
}
An Accordion is a collection of vertically stacked sections with multiple content areas.
Allows a user to toggle the display of a section of content.
@category Layout