import { Fragment , FunctionComponent } from 'react' ; import { PrismicDocument } from '@prismicio/types' ; import { isNotUndefined } from '@weco/common/utils/array' ; import Space from '@weco/common/views/components/styled/Space' ; import Contributor from './Contributor' ; import { WithContributors } from '../../services/prismic/types' ; import { transformContributors } from '../../services/prismic/transformers/contributors' ; import { transformRichTextFieldToString } from '../../services/prismic/transformers' ; type Props = { titlePrefix ? : string ; document : PrismicDocument < WithContributors > ; } ; export function dedupeAndPluraliseRoles ( roles ) { const dedupedWithCount = roles . filter ( Boolean ) . reduce ( ( acc , role ) => { if ( ! acc . hasOwnProperty ( role ) ) { acc [ role ] = 0 ; } acc [ role ] ++ ; return acc ; } , { } ) ; const pluralised = Object . keys ( dedupedWithCount ) . map ( role => { const count = dedupedWithCount [ role ] ; return count > 1 ? `${ role }s` : role ; } , [ ] ) ; return pluralised ; } export function getContributorsTitle ( roles , titlePrefix = 'About the' ) { const lowerCaseRoles = roles . map ( role => role . toLowerCase ( ) ) ; if ( roles . indexOf ( 'Partner' ) !== - 1 ) { return 'In partnership with' ; } const rolesString = lowerCaseRoles . length === 1 ? lowerCaseRoles [ 0 ] : 'contributors' ; return `${ titlePrefix } ${ rolesString }` ; } const Contributors = ( { titlePrefix = 'About the' , document , } ) => { const contributors = transformContributors ( document ) ; if ( contributors . length === 0 ) { return null ; } const titleOverride = transformRichTextFieldToString ( document . data . contributorsTitle ) ; const roles = dedupeAndPluraliseRoles ( contributors . map ( contributor => contributor ?. role ?. title ) . filter ( isNotUndefined ) ) ; return ( < Fragment > { titleOverride && < h2 className = "h2" > { titleOverride } < /h2>} { ! titleOverride && ( < h2 className = "h2" > { `${ getContributorsTitle ( roles , titlePrefix ) }` } < /h2>)} { contributors . map ( ( { contributor , role , description } ) => ( < Space v = { { size : 'l' , properties : [ 'margin-bottom' ] } } key = { contributor . id } > { } < Contributor contributor = { contributor } role = { roles . length > 1 ? role : undefined } description = { description } / > < /Space>))} < /Fragment>); } ; export default Contributors ;