import G6 from '@antv/g6' ; import { Shape } from '@antv/g-canvas' ; import { Item } from '@antv/g6/lib/types' ; import { ExtendNodeShape , ShapeComponent } from '../../types' ; const reset = ( shapes , shapeComponents ) => { shapes . forEach ( ( shape , index ) => { if ( ! shapeComponents [ index ] . noReset ) shape . attr ( { ... shapeComponents [ index ] . attrs , } ) ; } ) ; } ; const compiler = ( extendNodeShape ) => { const { name : registerName , render : renderNodeShape } = extendNodeShape ; if ( ! renderNodeShape ) { return ; } /** 设置初始化shapeComponent，按照节点ID进行分类 */ const initShapeComponentMap = { } ; const initStateMap = { } ; G6 . registerNode ( registerName , { draw ( inputCfg , group ) { /** 得到用户返回的shapeComponents，然后拼装 */ const { shapeComponents , state : RenderState } = renderNodeShape ( inputCfg ) ; /** 每次draw后的shape就是初始化shape，这个在节点update后，用于setstate的reset */ initShapeComponentMap [ inputCfg . data . id ] = shapeComponents ; initStateMap [ inputCfg . data . id ] = RenderState ; let keyshapeIndex = 0 ; const g6Shapes = shapeComponents . map ( ( component , index ) => { if ( component . isKeyShape ) keyshapeIndex = index ; return group . addShape ( component . type || component . shape , { attrs : { ... component . attrs , } , draggable : true , name : component . attrs ?. id , } ) ; } ) ; return g6Shapes [ keyshapeIndex ] ; } , setState ( name , value , node ) { const { id } = node . get ( 'model' ) . data ; const initShapeComponent = initShapeComponentMap [ id ] ; const initState = initStateMap [ id ] ; const shapes = node . getContainer ( ) . get ( 'children' ) ; if ( ! value || ! name ) { reset ( shapes , initShapeComponent ) ; return ; } Object . keys ( initState ) . forEach ( ( key ) => { if ( name === key ) { shapes . forEach ( ( g6Shape ) => { const originAttrs = g6Shape . attr ( ) ; const customAttrs = initState [ key ] [ originAttrs . id ] ; if ( customAttrs ) { const { animate , ... otherAttrs } = customAttrs ; g6Shape . attr ( otherAttrs ) ; if ( animate ) { const { attrs , duration , easing , callback , delay } = animate ; g6Shape . animate ( attrs , duration , easing , callback , delay ) ; } } } ) ; } } ) ; } , } ) ; } ; export default compiler ;