/** * WordPress dependencies */ import { useSelect } from '@safe-wordpress/data'; import { useMemo } from '@safe-wordpress/element'; /** * External dependencies */ import { EMPTY_ARRAY } from '@nelio-content/constants'; import { store as NC_DATA } from '@nelio-content/data'; import type { Maybe, SocialNetworkName, SocialProfileTarget, SocialTargetName, Uuid, } from '@nelio-content/types'; /** * Internal dependencies */ import { store as NC_SOCIAL_EDITOR } from '../store'; import type { State } from '../store/types'; export const useSelectedTargets = (): State[ 'attributes' ][ 'targetNamesByProfile' ] => useSelect( ( select ) => select( NC_SOCIAL_EDITOR ).getSelectedTargets(), [] ); export const useSelectedTargetsInProfile = ( profileId: Maybe< Uuid > ): ReadonlyArray< SocialTargetName > => useSelect( ( select ) => { const { getSelectedTargetsInProfile } = select( NC_SOCIAL_EDITOR ); return profileId ? getSelectedTargetsInProfile( profileId ) : EMPTY_ARRAY; }, [ profileId ] ); type UseTargetSelectorPropsResult = | { readonly isVisible: false; } | { readonly isVisible: true; readonly profileId: Uuid; readonly network: SocialNetworkName; readonly isLoading: boolean; readonly selectedTargetNames: ReadonlyArray< SocialTargetName >; readonly targets: ReadonlyArray< SocialProfileTarget >; }; const INVISIBLE: UseTargetSelectorPropsResult = { isVisible: false }; export const useTargetSelectorProps = (): UseTargetSelectorPropsResult => { const { profileId, visible, profile, selected, targets } = useSelect( ( select ) => { const data = select( NC_DATA ); const editor = select( NC_SOCIAL_EDITOR ); const pid = editor.getProfileIdInTargetSelector(); return { profileId: pid, visible: editor.isTargetSelectorVisible(), profile: pid ? data.getSocialProfile( pid ) : undefined, selected: editor.getSelectedTargetsInTargetSelector(), targets: pid ? data.getTargetsInProfile( pid ) : undefined, }; }, [] ); return useMemo( () => { if ( ! profileId ) { return INVISIBLE; } if ( ! visible || ! profile ) { return INVISIBLE; } return { isVisible: true, profileId, network: profile.network, isLoading: targets === undefined, selectedTargetNames: selected, targets: targets ?? EMPTY_ARRAY, }; }, [ profileId, visible, profile, selected, targets ] ); };