import state from '../state/state' ; import { getUniqueFilename } from './file' ; param freeplaneDocContents export default function importFreeplane ( freeplaneDocContents ) { const parser = new DOMParser ( ) ; const doc = parser . parseFromString ( freeplaneDocContents , 'application/xml' ) ; if ( doc . querySelector ( 'parsererror' ) ) { console . log ( 'error while parsing' ) ; } else { processImportedFreeplaneDoc ( doc ) ; } } function getFreeplaneChildNodes ( parentNode ) { const childDisplayNodes = [ ] ; for ( let i = 0 ; i < parentNode . children . length ; i += 1 ) { const childXmlNode = parentNode . children . item ( i ) ; if ( childXmlNode && childXmlNode . nodeName === 'node' ) { childDisplayNodes . push ( childXmlNode ) ; } } return childDisplayNodes ; } function getFreeplaneTextContent ( freeplaneNode ) { return freeplaneNode . attributes . getNamedItem ( 'TEXT' ) ?. value || '' ; } function processImportedFreeplaneDoc ( xmlDoc ) { const importMapElement = xmlDoc . documentElement ; if ( importMapElement . nodeName !== 'map' ) { console . log ( 'Doesn\'t look like a Freeplane map' ) ; return ; } state . doc . replaceCurrentDocWithNewEmptyDoc ( ) ; state . doc . setDocName ( getUniqueFilename ( 'Imported Freeplane Document' ) ) ; const freeplaneRootNode = getFreeplaneChildNodes ( importMapElement ) [ 0 ] ; const m3RootId = state . doc . getRootNodeId ( ) ; state . doc . replaceNodeContents ( m3RootId , getFreeplaneTextContent ( freeplaneRootNode ) ) ; getFreeplaneChildNodes ( freeplaneRootNode ) . forEach ( ( child ) => { addFreeplaneNodeToCurrentM3Doc ( child , m3RootId ) ; } ) ; state . doc . toggleChildrenVisibility ( m3RootId ) ; } function addFreeplaneNodeToCurrentM3Doc ( freeplaneNode , parentNodeId ) { const thisNodeId = state . doc . addChild ( parentNodeId , getFreeplaneTextContent ( freeplaneNode ) ) ; const childNodes = getFreeplaneChildNodes ( freeplaneNode ) ; childNodes . forEach ( ( child ) => { addFreeplaneNodeToCurrentM3Doc ( child , thisNodeId ) ; } ) ; state . doc . toggleChildrenVisibility ( thisNodeId ) ; }