import _ from 'lodash' ; import { v4 as uuid } from '@lukeed/uuid' ; const message = { } ; const messageMap = new Map ( ) ; const quequ = [ ] ; let generate = null ; window . addEventListener ( 'message' , async ( event ) => { console . log ( 'sparrow-online-view' , event ) ; const { data } = event ; const handlerArr = data . handler && data . handler . split ( '.' ) ; if ( data && data . uniqueId ) { if ( messageMap . has ( data . uniqueId ) ) { const curMessage = messageMap . get ( data . uniqueId ) ; curMessage . resolve ( data ) ; } else if ( handlerArr [ 0 ] === 'generator' && generate ) { const res = await generate [ handlerArr [ 1 ] ] [ handlerArr [ 2 ] ] ( data ) ; window . parent . postMessage ( { handler : 'callback' , uniqueId : data . uniqueId , data : res } , '*' ) ; } } if ( data . codesandbox === true ) { window . parent . postMessage ( { handler : 'codesandbox' , data , } , '*' ) ; } const findMessage = quequ . find ( ( item ) => item . handler === data . handler ) ; if ( findMessage ) { findMessage . callback ( data ) ; } } , false ) ; message . emit = ( handler , data = { } ) => { data . uniqueId = uuid ( ) ; data . handler = handler || '' ; return new Promise ( ( resolve , reject ) => { window . parent . postMessage ( data , '*' ) ; messageMap . set ( data . uniqueId , { resolve , reject } ) ; } ) ; } ; message . on = ( handler , callback ) => { quequ . push ( { handler , callback , } ) ; } ; message . init = ( generateIns ) => { generate = generateIns ; } ; export default message ;