import { NodeKey , TreeNodeOptions } from "./types" ; import { ref } from "vue" ; import { SelectionModel } from "../selections" ; const selectedNodes = ref ( new SelectionModel < Required < TreeNodeOptions > > ( ) ) ; const checkedNodes = ref ( new SelectionModel < Required < TreeNodeOptions > > ( true ) ) ; const expandedKeys = ref ( new SelectionModel < NodeKey > ( true ) ) ; const disabledKeys = ref ( new SelectionModel < NodeKey > ( true ) ) ; function flattenTree ( source , defaultCheckedKeys , defaultExpandedKeys ) { const result = [ ] ; function recursion ( list , level = 0 , parent = null ) { return list . map ( item => { const flatNode = { ... item , level , loading : false , hasChildren : item . hasChildren || false , parentKey : parent ?. nodeKey || null , children : item . children || [ ] } ; result . push ( flatNode ) ; if ( defaultCheckedKeys . includes ( item . nodeKey ) ) { checkedNodes . value . select ( flatNode ) ; } if ( defaultExpandedKeys . includes ( item . nodeKey ) && item . children ?. length ) { expandedKeys . value . select ( item . nodeKey ) ; flatNode . children = recursion ( item . children , level + 1 , flatNode ) ; } return flatNode ; } ) ; } recursion ( source ) ; return result ; } function updateDownwards ( checked , node ) { const update = ( children ) => { if ( children . length ) { children . forEach ( child => { const checkFunc = checked ? 'select' : 'deselect' ; checkedNodes . value [ checkFunc ] ( child ) ; if ( child . children ?. length ) { update ( child . children as Required < TreeNodeOptions > [ ] ) ; } } ) ; } } ; update ( node . children as Required < TreeNodeOptions > [ ] ) ; } function updateUpwards ( targetNode , flatList ) { const update = ( node ) => { if ( node . parentKey != null ) { const parentNode = flatList . find ( item => item . nodeKey == node . parentKey ) ! ; const parentChecked = ( parentNode . children as Required < TreeNodeOptions > [ ] ) . every ( ( child ) => checkedNodes . value . isSelected ( child ) ) ; if ( parentChecked !== checkedNodes . value . isSelected ( parentNode ) ) { checkedNodes . value . toggle ( parentNode ) ; update ( parentNode ) ; } } } ; update ( targetNode ) ; } export { selectedNodes , checkedNodes , expandedKeys , disabledKeys , flattenTree , updateUpwards , updateDownwards } ;