/**
* WordPress dependencies
*/
import { DropdownMenu, MenuGroup, MenuItem } from '@safe-wordpress/components';
import { useDispatch } from '@safe-wordpress/data';
import { _x } from '@safe-wordpress/i18n';
/**
* External dependencies
*/
import { trim } from 'lodash';
import type { SocialTemplate } from '@nelio-content/types';
/**
* Internal dependencies
*/
import { store as NC_SOCIAL_EDITOR } from '../../store';
import {
useDoesActiveNetworkSupport,
useRelatedPost,
usePostTemplates,
} from '../../hooks';
// NOTE. This is a workaround because, for some reason, clicking outside the dropdown doesn’t work if the click is still inside the modal window.
let doCloseMenu: () => void;
const closeMenuOnBlur = () => {
if ( 'function' === typeof doCloseMenu ) {
doCloseMenu();
}
};
export type TemplateSelectorProps = {
readonly disabled?: boolean;
};
export const TemplateSelector = ( {
disabled,
}: TemplateSelectorProps ): JSX.Element | null => {
const supportsText = useDoesActiveNetworkSupport( 'text' );
const [ post ] = useRelatedPost();
const { recommendedTemplates, otherTemplates } = usePostTemplates( post );
const { setText } = useDispatch( NC_SOCIAL_EDITOR );
if ( ! supportsText ) {
return null;
}
const hasRecommendedTemplates = !! recommendedTemplates.length;
const hasOtherTemplates = !! otherTemplates.length;
const hasTemplates = hasRecommendedTemplates || hasOtherTemplates;
if ( ! hasTemplates ) {
return null;
}
return (
}
label={ _x( 'Templates', 'command', 'nelio-content' ) }
toggleProps={ {
disabled: !! disabled,
tooltipPosition: 'bottom center',
} }
popoverProps={ { onFocusOutside: closeMenuOnBlur } }
>
{ ( { onClose }: { onClose: () => void } ) => {
// NOTE. This is part of the workaround mentioned before.
doCloseMenu = onClose;
return (
{
onClose();
void setText( text );
} }
/>
{
onClose();
void setText( text );
} }
/>
);
} }
);
};
// ============
// HELPER VIEWS
// ============
type TemplateListProps = {
readonly title: string;
readonly templates: ReadonlyArray< SocialTemplate >;
readonly onClick: ( text: string ) => void;
};
const TemplateList = ( {
title,
templates,
onClick,
}: TemplateListProps ): JSX.Element | null => {
if ( ! templates.length ) {
return null;
}
if ( ! title ) {
return (
<>
{ templates.map( ( { id, text } ) => (
) ) }
>
);
}
return (
{ templates.map( ( { id, text } ) => (
) ) }
);
};
const TemplateIcon = () => (
);
// =======
// HELPERS
// =======
const shorten = ( t: string ) =>
80 < t.length ? trim( t.substring( 0, 75 ) ) + '…' : t;