MediaWiki:VisNetwork.js

From KIproBatt Wiki
Revision as of 08:38, 26 October 2021 by Simon Stier (talk | contribs)

Note: After saving, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Go to Menu → Settings (Opera → Preferences on a Mac) and then to Privacy & security → Clear browsing data → Cached images and files.
$(document).ready(function() {
    $.getScript('https://unpkg.com/vis-network/standalone/umd/vis-network.min.js').done(function() {
      if( $('#visNetworkGraph').length ) {//check if div element(s) exist
      var input = JSON.parse($("#visNetworkGraph").text());
      wikiUrl = "";
      
      // create an array with nodes
      var nodes = new vis.DataSet([]);
      // create an array with edges
      var edges = new vis.DataSet([]);
      
      var colors = ['#ff7878', '#73ff77', '#e878ff', '#ffae57', '#80f8ff', '#ffff75', '#adadad', '#b482ff'];
	
      var id = 1;
      nodes.add({id: id, label: input.root});
      id++;

      function createUrl(root, properties){
      var url = `${wikiUrl}/w/api.php?action=ask&query=[[${root}]]`;
      var propertiesVar ='';
      for (var i = 0; i < properties.length; i++) {
      	propertiesVar += '|?'+ properties[i];
      	
      }
	
      url = url + propertiesVar + '&format=json';
      return url;
      }



      function fetchData(root, properties, nodeID){
      fetch(createUrl(root, properties))
        .then(response => response.json())
        .then(data => {
        	
        	
        	
        	for (var i = 0; i < properties.length; i++) {
        		for (var j = 0; j < data.query.results[root].printouts[properties[i]].length; j++) {
        			if(data.query.results[root].printouts[properties[i]].length == 1){
        				if(data.query.results[root].printouts[properties[i]][j].fulltext){
        					nodes.add({id: id, label: data.query.results[root].printouts[properties[i]][j].fulltext, color: colors[i], group: properties[i], hidden:false});
        					if(nodeID){edges.add({from: nodeID, to: id, label: properties[i], color: colors[i], group: properties[i]});}
        					else{
        					edges.add({from: 1, to: id, label: properties[i], color: colors[i], group: properties[i]});}
        					id++;
        					
        				}else{
        				
        				nodes.add({id: id, label: data.query.results[root].printouts[properties[i]][0].toString(), color: colors[i], group: properties[i], hidden:false});
        				if(nodeID){edges.add({from: nodeID, to: id, label: properties[i], color: colors[i], group: properties[i]});}else{
        				edges.add({from: 1, to: id, label: properties[i], color: colors[i], group: properties[i]});}
        				id++;}
        			}else if(!data.query.results[root].printouts[properties[i]][j].fulltext){
        				nodes.add({id: id, label: data.query.results[root].printouts[properties[i]][j], color: colors[i], group: properties[i], hidden:false});
        				if(nodeID){edges.add({from: nodeID, to: id, label: properties[i], color: colors[i], group: properties[i]});}else{
        				edges.add({from: 1, to: id, label: properties[i], color: colors[i], group: properties[i]});}
        				id++;
        			
        				
        			}else{
        				nodes.add({id: id, label: data.query.results[root].printouts[properties[i]][j].fulltext, color: colors[i], group: properties[i], hidden:false});
        				if(nodeID){edges.add({from: nodeID, to: id, label: properties[i], color: colors[i], group: properties[i]});}else{
        				edges.add({from: 1, to: id, label: properties[i], color: colors[i], group: properties[i]});}
        				id++;
        				
        				
        			}
        			
        		
        		}
        	}
        	
        });
      } 
       fetchData(input.root, input.properties);
      // create a network
      var container = document.getElementById("visNetworkGraph");
      var data = {
        nodes: nodes,
        edges: edges,
      };
      
      
      var options = {width: "100%", height: "100%", interaction: { hover: true },
  manipulation: {
    enabled: true,
  }, /*layout:{improvedLayout:false},*/
  groups: {
  	useDefaultGroups: false
  	},
  	physics:{
  	stabilization: {
      enabled: true,
      /*iterations: 1,
      updateInterval: 25,
      onlyDynamicEdges: false,
      fit: true*/
    },
  		barnesHut: {
      gravitationalConstant: -40000,
      centralGravity: 0,
      springLength: 0,
      springConstant: 0.5,
      damping: 1,
      avoidOverlap: 0
    },
    maxVelocity: 5
  	},
      	
      };
      
    for(var i=0;i<input.properties.length;i++){
    	options.groups[input.properties[i]] = {hidden: false};
    }
      console.log(options);
     
      var network = new vis.Network(container, data, options);
      	var x = -visNetworkGraph.clientWidth / 2 + 50;
		var y = -visNetworkGraph.clientHeight / 2 + 50;
		var step = 70;
		var legendID = 1000;
		for (var i = 0; i < input.properties.length; i++) {
	        		if(i<1){
        			
        		nodes.add({
    					id: legendID,
    					x: x,
    					y: y,
    					label: input.properties[i],
    					/*group: input.properties[i],*/
    					value: 1,
    					fixed: true,
    					physics: false,
    					color: colors[i],
				});legendID++;
        			
        		}else{
						
					    nodes.add({
    					id: legendID,
    					x: x,
    					y: y + i * step,
    					label: input.properties[i],
    					/*group: input.properties[i],*/
    					value: 1,
    					fixed: true,
    					physics: false,
					    color: colors[i],
					    });
    					legendID++;
					
				}
		}
      function deleteNodes(node){
      	
      	var deleteNode = network.getConnectedNodes(node);
      	for(var i = 1; i < deleteNode.length;i++){
      		if(network.getConnectedNodes(deleteNode[i]).length > 1){
      			deleteNodes(deleteNode[i]);
      			
      			
      			
      		}else{
      			
      		nodes.remove([deleteNode[i]]);
      		if(node === 1){
      			
      			deleteNodes(deleteNode[0]);
      			nodes.remove([deleteNode[0]]);
      		}
      		
      		}
      		
      	}
      	for( i = 1; i < deleteNode.length;i++){
      		nodes.remove([deleteNode[i]]);
      	}
      	
      }
      
      
      var nodesArray = [];
      //var isInArray = false;
      var legendClicked = false;

		 

var oldGroups = [];
      
      network.on("click", function (params) {
      	if(params.nodes[0]){
 ////////////////////////////////////////////////////////// 
		var legendGroup;
		var group;
		var nodeChildren;
		
if(params.nodes[0] > 999){
legendGroup = nodes.get(params.nodes[0]).label;			
			if(options.groups[legendGroup].hidden === false){
				
				group = nodes.get({
				filter: function (item) {
    			return item.group == legendGroup;
				}
			});
			console.log(options.groups);
			for(var i = 0; i<group.length;i++){
				
				
				//nodes.update({id:group[i].id, hidden:true});
				nodeChildren = network.getConnectedNodes(group[i].id, 'to');
					options.groups[legendGroup].hidden = true;
      				//console.log(options.groups[legendGroup]);
      				network.body.emitter.emit('_dataChanged');
      				network.redraw();
					

				if(nodeChildren.length === 0){
					
					continue;
				}else{
					
					for(var j = 0; j<nodeChildren.length;j++){
						console.log(nodes.get(nodeChildren[j]).group);
						oldGroups.push({id: nodes.get(nodeChildren[j]).id, group:nodes.get(nodeChildren[j]).group});
						
					nodes.update({id: nodeChildren[j], group:legendGroup});
					console.log(nodes.get(nodeChildren[j]));
					network.body.emitter.emit('_dataChanged');
      				network.redraw();
					
					
					
					
				}console.log(oldGroups);
				}
				
				
				
			}
			network.body.emitter.emit('_dataChanged');
      		network.redraw();

      	
      		
      		
      		
      		
      	}else{
      			
				group = nodes.get({
				filter: function (item) {
    			return item.group == legendGroup;
				}
			});
			console.log(options.groups);
      			for( i = 0; i<group.length;i++){
      		
				
				nodeChildren = network.getConnectedNodes(group[i].id, 'to');
					options.groups[legendGroup].hidden = false;
      				//options.groups[legendGroup].hidden = false;
      				network.body.emitter.emit('_dataChanged');
      				network.redraw();
				console.log(nodeChildren.length);
				if(nodeChildren.length === 0){
					continue;
				}else{
					for( j = 0; j<oldGroups.length;j++){
						console.log(oldGroups[j],id);
					nodes.update({id: oldGroups[j].id, group:oldGroups[j].group});
					network.body.emitter.emit('_dataChanged');
      				network.redraw();
					
					
				}
				}
				
				
				
			}
			network.body.emitter.emit('_dataChanged');
      		network.redraw();
      		oldGroups = [];
      		
      		
      	}}
/////////////////////////////////////////////////////////////////////////////////////      	
      	
      	/*for( i = 0; i < nodesArray.length; i++){
      		if(params.nodes[0] == nodesArray[i]){
      			isInArray = true;
      		}}*/
      	if(network.getConnectedNodes(params.nodes[0]).length >1 ){
      		deleteNodes(params.nodes[0]);
      		nodesArray.splice(nodesArray.indexOf(params.nodes[0]),1);
      		//|| (params.nodes[0]===1)
      		
      		//isInArray = false;
      	}else{
      		var nodeById = nodes.get(params.nodes[0]);
      		fetchData(nodeById.label, input.properties, params.nodes[0]);
      		nodesArray.push(params.nodes[0]);
      		
      	}

      }

      });
      
      
    
    }  	
    });
});

/*groups: {
  	useDefaultGroups: false,
'Kategorie': {},
  	'-IsLocatedIn': {}
  }*/


/*for (var key in data.query.results[input.root].printouts) {
    			if (data.query.results[input.root].printouts.hasOwnProperty(key)) {
    				for(var key2 in data.query.results[input.root].printouts[key]){
        			console.log(data.query.results[input.root].printouts[key][key2].fulltext);
    				}
    			}
			}*/