import originPolyPhrases from './dict/polyphone-phrase-simple.json' ; import { ICnChar , ISpell , SpellArg } from 'cnchar-types/main/index' ; import { ICncharTool } from 'cnchar-types/main/tool' ; import { IInitPoly , ISetPolyPhrase } from 'cnchar-types/plugin/poly' ; import { Json } from 'cnchar-types/main/common' ; const polyPhrases = originPolyPhrases as Json < string > ; let _cnchar ; let _ ; const arg = { poly : 'poly' } ; let _spell ; function _poly ( str , ... args ) { _ . checkArgs ( 'spell' , args , true ) ; if ( _ . has ( args , _ . arg . poly ) ) return _spell ( str , ... args ) ; const newArgs = [ _ . arg . array ] ; const tone = _ . has ( args , _ . arg . tone ) ; if ( tone ) { newArgs . push ( _ . arg . tone ) ; } const res = _spell ( str , ... newArgs ) as Array < string > ; for ( const k in polyPhrases ) { const index = str . indexOf ( k ) ; if ( index !== - 1 ) { const pa = polyPhrases [ k ] . split ( ' ' ) ; for ( let i = 0 ; i < pa . length ; i ++ ) { res [ index + i ] = _ . removeTone ( pa [ i ] , tone ) . spell ; } } } _ . dealUpLowFirst ( res , args ) ; if ( ! _ . has ( args , _ . arg . array ) ) { return res . join ( '' ) ; } return res ; } const setPolyPhrase = ( word , spell ? ) : void => { if ( typeof word === 'object' ) { for ( const k in word ) { setPolyPhrase ( k , word [ k ] ) ; } return ; } if ( typeof spell !== 'string' ) return ; polyPhrases [ word ] = spell . split ( ' ' ) . map ( s => { return _cnchar . shapeSpell ( s ) ; } ) . join ( ' ' ) ; } ; function main ( cnchar ) { if ( cnchar . plugins . indexOf ( 'poly' ) !== - 1 ) { return ; } cnchar . setPolyPhrase = setPolyPhrase ; cnchar . plugins . push ( 'poly' ) ; _spell = cnchar . _origin . spell ; _ = cnchar . _ ; _cnchar = cnchar ; const _new = ( str , ... args ) => { if ( _ . has ( args , arg . poly ) ) { return _spell ( str , ... args ) ; } return _poly ( str , ... args ) ; } ; cnchar . spell = _new ; String . prototype . spell = function ( ... args ) { return _new ( this as string , ... args ) ; } ; cnchar . _ . poly = true ; if ( cnchar . _ . _reinitSpellPoly ) { cnchar . _ . _reinitSpellPoly ( ) ; delete cnchar . _ . _reinitSpellPoly ; } } const init = ( cnchar ? ) : void => { if ( typeof window === 'object' && window . CnChar ) { main ( window . CnChar ) ; } else if ( typeof cnchar !== 'undefined' ) { main ( cnchar ) ; } } ; init ( ) ; export default init ;