import { EditorState } from 'draft-js' ; import { Map } from 'immutable' ; import decodeOffsetKey from './decodeOffsetKey' ; interface TriggerForMentionResult { activeOffsetKey : string ; activeTrigger : string ; } function filterUndefineds ( value ) { return value !== undefined ; } export default function getTriggerForMention ( editorState , searches , mentionTriggers ) { const selection = editorState . getSelection ( ) ; const anchorKey = selection . getAnchorKey ( ) ; const anchorOffset = selection . getAnchorOffset ( ) ; if ( ! selection . isCollapsed ( ) || ! selection . getHasFocus ( ) ) { return null ; } const offsetDetails = searches . map ( ( offsetKey ) => decodeOffsetKey ( offsetKey ! ) ) ; const leaves = offsetDetails . filter ( ( offsetDetail ) => offsetDetail ! . blockKey === anchorKey ) . map ( ( offsetDetail ) => editorState . getBlockTree ( offsetDetail ! . blockKey ) . getIn ( [ offsetDetail ! . decoratorKey ] ) ) ; if ( leaves . every ( ( leave ) => leave === undefined ) ) { return null ; } const blockText = editorState . getCurrentContent ( ) . getBlockForKey ( anchorKey ) . getText ( ) ; const triggerForSelectionInsideWord = leaves . filter ( filterUndefineds ) . map ( ( { start , end } ) => mentionTriggers . map ( ( trigger ) => ( start === 0 && anchorOffset >= start + trigger . length && blockText . substr ( 0 , trigger . length ) === trigger && anchorOffset <= end ) || ( mentionTriggers . length > 1 && anchorOffset >= start + trigger . length && ( blockText . substr ( start + 1 , trigger . length ) === trigger || blockText . substr ( start , trigger . length ) === trigger ) && anchorOffset <= end ) || ( mentionTriggers . length === 1 && anchorOffset >= start + trigger . length && anchorOffset <= end ) ? trigger : undefined ) . filter ( filterUndefineds ) [ 0 ] ) . filter ( filterUndefineds ) ; if ( triggerForSelectionInsideWord . isEmpty ( ) ) { return null ; } const [ activeOffsetKey , activeTrigger , ] = triggerForSelectionInsideWord . entrySeq ( ) . first ( ) ; return { activeOffsetKey , activeTrigger , } ; }