import { Component } from 'react'; const getRegExpFor = function ( type, textToHighlight ) { const expressions = {}; expressions.username = '(^' + textToHighlight + ')(\\w*)\\s*'; expressions.fullname = '(^.*?)(\\b' + textToHighlight + ')(.*)'; return new RegExp( expressions[ type ], 'ig' ); }; const highlight = ( content, textToHighlight, type ) => { const lowerCaseSearch = textToHighlight.toLowerCase(); const matcher = getRegExpFor( type, textToHighlight ); const matches = matcher.exec( content ); if ( ! matches ) { return [ { type: 'text', text: content } ]; } return matches.slice( 1 ).reduce( ( [ result, alreadyHighlighted ], text ) => { // skip the first "complete match" string const shouldHighlight = ! alreadyHighlighted && lowerCaseSearch === text.toLowerCase(); // eslint-disable-next-line no-shadow const type = shouldHighlight ? 'strong' : 'text'; return [ [ ...result, { type, text } ], shouldHighlight ]; }, [ [], false ] )[ 0 ]; }; export class Suggestion extends Component { render() { const username = highlight( this.props.username, this.props.suggestionsQuery, 'username' ); username.unshift( { type: 'text', text: '@' } ); const fullName = highlight( this.props.fullName, this.props.suggestionsQuery, 'fullname' ); return ( // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-noninteractive-element-interactions
  • { /* eslint-disable-next-line jsx-a11y/alt-text */ } { username.map( ( { type, text }, index ) => 'strong' === type ? ( { text } ) : ( { text } ) ) } { fullName.map( ( { type, text }, index ) => 'strong' === type ? ( { text } ) : ( { text } ) ) }
  • ); } } export default Suggestion;