import { useEventListener } from '../hooks' ; import { isContentEditableDiv } from '../utils/is' ; import { usePlugin } from './plugin' ; import { createRangeLink } from '../utils/find-blocks' ; import { useRef } from 'react' ; import type LinkifyIt from 'linkify-it' ; function findLastText ( node ) { if ( ! node ) return null ; if ( node instanceof Text ) { return node ; } return findLastText ( node . lastChild ) ; } example export function LinkifyItPlugin ( props ) { const linkifyRef = useRef ( props . linkifyIt ) ; const { wrapperRef } = usePlugin ( ) ; useEventListener ( 'keyup' , ( e ) => { if ( e . key === ' ' && isContentEditableDiv ( e . target ) ) { const text = findLastText ( e . target . lastChild ) ; if ( text ?. textContent ) { const match = linkifyRef . current . match ( text . textContent ) ; if ( match ) { const lastMatch = match [ match . length - 1 ] ; const range = document . createRange ( ) ; range . setStart ( text , lastMatch . index ) ; range . setEnd ( text , lastMatch . lastIndex ) ; createRangeLink ( range , lastMatch . url ) ; document . execCommand ( 'selectAll' , false ) ; document . getSelection ( ) ?. collapseToEnd ( ) ; } } } } , wrapperRef ) ; return null ; }