♻️ Make generic Accordion more generic

This commit is contained in:
Philipp Stracker 2024-12-09 14:03:07 +01:00
parent 7146163301
commit 1b557f1619
No known key found for this signature in database
3 changed files with 106 additions and 59 deletions

View file

@ -0,0 +1,39 @@
import { useEffect, useState } from '@wordpress/element';
const checkIfCurrentTab = ( id ) => {
return id && window.location.hash === `#${ id }`;
};
const determineInitialState = ( id, initiallyOpen ) => {
if ( initiallyOpen !== null ) {
return initiallyOpen;
}
return checkIfCurrentTab( id );
};
export function useAccordionState( { id = '', initiallyOpen = null } ) {
const [ isOpen, setIsOpen ] = useState(
determineInitialState( id, initiallyOpen )
);
useEffect( () => {
const handleHashChange = () => {
if ( checkIfCurrentTab( id ) ) {
setIsOpen( true );
}
};
window.addEventListener( 'hashchange', handleHashChange );
return () => {
window.removeEventListener( 'hashchange', handleHashChange );
};
}, [ id ] );
const toggleOpen = ( ev ) => {
setIsOpen( ! isOpen );
ev?.preventDefault();
return false;
};
return { isOpen, toggleOpen };
}