import { Seq , Set } from 'immutable' ; import { Item , ItemId , PolygonItem , PolylineItem , State } from '../interfaces' ; import { isPolygonItem , isPolylineItem } from './common' ; import ImgItem from './ImgItem' ; function getImgTypeString ( item ) { if ( isPolygonItem ( item ) ) return 'PolygonItem' ; if ( isPolylineItem ( item ) ) return 'PolylineItem' ; throw new Error ( 'Invalid item.' ) ; } function getItemConstructor ( name ) { if ( name === 'PolygonItem' ) return PolygonItem ; if ( name === 'PolylineItem' ) return PolylineItem ; if ( name === 'ImgItem' ) return ImgItem ; throw new Error ( 'Invalid type name.' ) ; } const serializeUtils = { toJS ( state ) { const items = state . items . filter ( item => isPolygonItem ( item ) || isPolylineItem ( item ) ) . map ( item => ( { type : getImgTypeString ( item ) , ... item . toObject ( ) , } ) ) . valueSeq ( ) . toArray ( ) ; const validItemIdSet = Set ( items . map ( ( item ) => item . id ) ) ; const zlist = state . zlist . filter ( ( itemId ) => validItemIdSet . has ( itemId ) ) . toArray ( ) ; return { items , zlist } ; } , fromJS ( object ) { const items = Seq ( object . items ) . toIndexedSeq ( ) . map ( ( item ) => getItemConstructor ( item . type ) . fromJS ( item ) ) . toMap ( ) . mapKeys ( ( _ , item ) => item . id ) ; const zlist = Seq ( object . zlist ) . toIndexedSeq ( ) . toList ( ) ; return new State ( { items , zlist } ) ; } , } ; export default serializeUtils ;