/** * WordPress dependencies */ import { useSelect } from '@safe-wordpress/data'; /** * External dependencies */ import { castArray, filter, isFunction } from 'lodash'; import { store as NAB_DATA } from '@nab/data'; import { store as NAB_EXPERIMENTS } from '@nab/experiments'; import { EMPTY_ARRAY } from '@nab/utils'; import type { ExperimentTypeName, EntityKind } from '@nab/types'; export const usePostTypes = ( experimentType: ExperimentTypeName ): { readonly postTypes: ReadonlyArray< EntityKind >; readonly showSinglePostType: boolean; readonly isLoadingPostTypes: boolean; } => { const data = useSelect( ( select ) => { const { hasExperimentSupport, getExperimentSupport } = select( NAB_EXPERIMENTS ); const { getKindEntities, hasFinishedResolution } = select( NAB_DATA ); const kindEntities = getKindEntities() || EMPTY_ARRAY; if ( hasExperimentSupport( experimentType, 'postTypes' ) ) { return { type: 'accepted' as const, kindEntities, acceptedPostTypes: getExperimentSupport( experimentType, 'postTypes' ), isLoadingPostTypes: ! hasFinishedResolution( 'getKindEntities' ), }; } if ( hasExperimentSupport( experimentType, 'postTypeExceptions' ) ) { const postTypeExceptions = getExperimentSupport( experimentType, 'postTypeExceptions' ); const excludedPostTypes = isFunction( postTypeExceptions ) ? postTypeExceptions( select ) : castArray( postTypeExceptions ); return { type: 'exclusions' as const, excludedPostTypes, kindEntities, isLoadingPostTypes: ! hasFinishedResolution( 'getKindEntities' ), }; } return { type: 'default' as const, isLoadingPostTypes: ! hasFinishedResolution( 'getKindEntities' ), }; }, [ experimentType ] ); switch ( data.type ) { case 'accepted': { const acceptedPostTypes = castArray( data.acceptedPostTypes ); const postTypes = filter( data.kindEntities.filter( ( pt ) => 'entity' === pt.kind ), ( { name } ) => acceptedPostTypes.includes( name ) ); return { postTypes, showSinglePostType: 1 !== acceptedPostTypes.length, isLoadingPostTypes: data.isLoadingPostTypes, }; } case 'exclusions': { const postTypes = filter( data.kindEntities.filter( ( pt ) => 'entity' === pt.kind ), ( { name } ) => ! data.excludedPostTypes.includes( name ) ); return { postTypes, showSinglePostType: true, isLoadingPostTypes: data.isLoadingPostTypes, }; } case 'default': return { postTypes: EMPTY_ARRAY, showSinglePostType: true, isLoadingPostTypes: data.isLoadingPostTypes, }; } };