/** * External dependencies */ import { map, values } from 'lodash'; import { EMPTY_ARRAY } from '@nelio-content/constants'; import { createIndexedSelector, isDefined } from '@nelio-content/utils'; import type { Maybe, PostId, SocialMessage, SocialMessageSummary, Uuid, } from '@nelio-content/types'; /** * Internal dependencies */ import type { State } from '../../config'; export function getSocialMessage( state: State, id?: Uuid ): Maybe< SocialMessage > { return id ? state.entities.messages.byId[ id ] : undefined; } export const getSocialMessagesRelatedToPost = createIndexedSelector( ( state: State, postId?: PostId ): ReadonlyArray< SocialMessage > => { const summaries = !! postId && state.entities.messages.byRelatedPost[ postId ]; if ( ! summaries ) { return EMPTY_ARRAY; } const validMessages = filterOutInvalidAutoMessages( state, summaries ); return map( validMessages, ( { id } ) => getSocialMessage( state, id ) ).filter( isDefined ); }, ( state: State, postId?: PostId ) => ( { key: postId || 0, dependants: [ !! postId && state.entities.messages.byRelatedPost[ postId ], state.entities.messages.byId, state.social.profiles.byId, ], } ) ); export const getSocialMessageIdsRelatedToPost = createIndexedSelector( ( state: State, postId?: PostId ): ReadonlyArray< Uuid > => { return map( getSocialMessagesRelatedToPost( state, postId ), 'id' ); }, ( state: State, postId?: PostId ) => ( { key: postId || 0, dependants: [ getSocialMessagesRelatedToPost( state, postId ) ], } ) ); export const getRecurringMessages = createIndexedSelector( ( state: State, recurrenceGroup?: Uuid ): ReadonlyArray< SocialMessage > => { return recurrenceGroup ? values( state.entities.messages.byId ).filter( ( m ) => m.recurrenceGroup === recurrenceGroup ) : []; }, ( state: State, recurrenceGroup?: Uuid ) => ( { key: recurrenceGroup || 0, dependants: [ state.entities.messages.byId ], } ) ); // ======= // HELPERS // ======= function filterOutInvalidAutoMessages( state: State, items: ReadonlyArray< SocialMessageSummary > ): ReadonlyArray< SocialMessageSummary > { return items.filter( ( sum ): sum is SocialMessageSummary => { if ( 'social' !== sum.type ) { return true; } const item = state.entities.messages.byId[ sum.id ]; if ( ! item ) { return false; } const profile = state.social.profiles.byId[ item.profileId ]; if ( ! profile ) { return false; } if ( 'publication' === item.auto && 0 >= profile.publicationFrequency ) { return false; } if ( [ 'timeline', 'reshare' ].includes( item.auto ?? '' ) && 0 >= profile.reshareFrequency ) { return false; } return true; } ); }