import type { AriaRole } from 'react'; import { Button } from '@wordpress/components'; import { useDispatch, useSelect } from '@wordpress/data'; import { usePluginContext } from '@wordpress/plugins'; import { store as interfaceStore } from '../../store'; import type { ComplementaryAreaToggleProps } from './types'; /** * Whether the role supports checked state. * * @see https://www.w3.org/TR/wai-aria-1.1/#aria-checked * @param role Role. * @return Whether the role supports checked state. */ function roleSupportsCheckedState( role?: AriaRole ): boolean { return [ 'checkbox', 'option', 'radio', 'switch', 'menuitemcheckbox', 'menuitemradio', 'treeitem', ].includes( role as string ); } export default function ComplementaryAreaToggle( { as = Button, scope, identifier: identifierProp, icon: iconProp, selectedIcon, name, shortcut, ...props }: ComplementaryAreaToggleProps ) { const ComponentToUse = as; const context = usePluginContext(); const icon = iconProp || context.icon; const identifier = identifierProp || `${ context.name }/${ name }`; const isSelected = useSelect( ( select ) => select( interfaceStore ).getActiveComplementaryArea( scope ) === identifier, [ identifier, scope ] ); const { enableComplementaryArea, disableComplementaryArea } = useDispatch( interfaceStore ); return ( { if ( isSelected ) { disableComplementaryArea( scope ); } else { enableComplementaryArea( scope, identifier ); } } } shortcut={ shortcut } { ...props } /> ); }