import React , { useState , useEffect , useRef } from 'react' ; import storage from '@app/common/storage' ; import { useStore } from 'react-redux' ; import { addMessage } from '@app/redux/actions/message' ; import Device from '@app/common/device' ; import Editor from '@app/components/editor' ; import './styles/index.scss' ; interface Props { addressee_id : string ; placeholder : string ; } export default function ( { addressee_id = '' , placeholder = '写评论...' } ) { const [ controller , setController ] = useState ( null ) ; const [ contentHTML , setContentHTML ] = useState ( '' ) ; const store = useStore ( ) ; const _addMessage = ( args ) => addMessage ( args ) ( store . dispatch , store . getState ) ; const submit = async function ( ) { return new Promise ( async ( resolve ) => { let html = decodeURIComponent ( contentHTML ) ; html = html . replace ( /<img(.*)>/g , "1" ) ; html = html . replace ( /<[^>]+>/g , "" ) ; html = html . replace ( /(^\s*)|(\s*$)/g , "" ) ; if ( ! html ) { controller . focus ( ) ; resolve ( ) ; return ; } let [ err , res ] = await _addMessage ( { addressee_id : addressee_id , type : 1 , content_html : contentHTML , device : Device . getCurrentDeviceId ( ) } ) ; if ( ! err ) { syncContent ( '' ) ; controller . clearContent ( ) ; } else if ( err ) { $ . toast ( { text : err . message , position : 'top-center' , showHideTransition : 'slide' , icon : 'error' , loader : false , allowToastClose : false } ) ; } resolve ( ) ; } ) ; } ; const syncContent = async function ( contentHTML ) { setContentHTML ( contentHTML ) ; let commentsDraft = await storage . load ( { key : 'comment-draft' } ) || { } ; if ( ! commentsDraft || typeof commentsDraft != 'object' ) commentsDraft = { } ; commentsDraft [ addressee_id ] = contentHTML ; storage . save ( { key : 'comment-draft' , data : commentsDraft } ) ; } ; let onEditorLoad = async function ( controller ) { let editComment = '' ; let commentsDraft = { } ; try { commentsDraft = await storage . load ( { key : 'comment-draft' } ) || { } ; } catch ( err ) { commentsDraft = { } ; } controller . innterHTML ( editComment || commentsDraft [ addressee_id ] || '' ) ; setContentHTML ( editComment || commentsDraft [ addressee_id ] || '' ) ; setController ( controller ) ; } ; return ( < div styleName = "content" > < Editor onChange = { syncContent } onSubmit = { submit } placeholder = { placeholder } onLoad = { onEditorLoad } / > < /div>); }