<commit_before>var layout_physical_active=true;
var layout_hierarchical_active=false;

function layout_physical(){

	if(layout_physical_active != true){

	   document.getElementById("text_scenario").innerHTML="";
	   console.log(typeof $("#text_scenario")[0].innerHTML);

		redrawAll();
	}else if($("#text_scenario")[0].innerHTML.includes("You are already on the") == false){

	  		document.getElementById("text_scenario").innerHTML+="
" + "You are already on the physical layout !";
		}

}

function layout_hierarchical(){

	if(layout_hierarchical_active==false){
	   //var tempNodeDataset=nodesDataset;
	   //console.log(nodesDataset);
	   document.getElementById("text_scenario").innerHTML="";

	 // Create a new directed graph
	 var g = new dagre.graphlib.Graph();

	 // Set an object for the graph label
	 g.setGraph({
		nodestep:30,
		edgesep:40,
		ranksep:500
	 });

	 // Default to assigning a new object as a label for each new edge.
	 g.setDefaultEdgeLabel(function() { return {}; });

	 for (var nodeId in allNodes) {
		 g.setNode(allNodes[nodeId].id,    {  width: 200, height: 100 });
	 }

	 for (var edgeId in allEdges) {
		 g.setEdge(allEdges[edgeId].from,   allEdges[edgeId].to);
	 }

	 dagre.layout(g);

	 var i=0;

	g.nodes().forEach(function(v) {
		var string=JSON.stringify(g.node(v));

		var pos1=string.indexOf("x");
		var pos2=string.indexOf(",\"y\":");
		var stringx=string.substring(pos1+3,pos2);
		var x=parseInt(stringx);
		allNodes[i].x=x;

		var pos3=string.indexOf("y");
	    var pos4=string.indexOf("}");
		var stringy=string.substring(pos3+3,pos4);
		var y=parseInt(stringy);
		allNodes[i].y=y;

		i++;
		});

	var updateArray = [];
 	for (var nodeId in allNodes) {
 		if (allNodes.hasOwnProperty(nodeId)) {
 			updateArray.push(allNodes[nodeId]);
 		}
 	}
	nodesDataset.update(updateArray);

options = {
       layout:{
         improvedLayout: false
       },
      nodes: {
      	margin: 5,

        widthConstraint: {
        	maximum: 150
        },
        scaling: {
        	min: 10,
        	max: 30,

        	label: {
        		min: 6,
        		max: 30,
        		drawThreshold: 5,
        		maxVisible: 20
        	}
        },

        font: {
        	color:'#ffffff',
        	size: 16,
        	face: 'Tahoma'
        },
    },

    edges: {
    	smooth: {
    		enabled: false,
    		type:'continuous'
    	},
    	color:{
    		inherit:false,
    		color:'rgba(60,60,60,0.6)',
    		hover:'rgba(60,60,60,0.6)',
    		highlight:'rgba(60,60,60,0.6)',

    	},

    	width: 0.15,

    	font: {
    		size:30,
    		align: 'top'
    	},

    	arrows: 'to',
    },

    interaction: {
    	dragNodes:true,
    	hover:true,
    	hoverConnectedEdges:true,
    	hideEdgesOnDrag: true,
    	tooltipDelay: 200,
    	navigationButtons: true,
    	multiselect:true
      // keyboard: true

  },

  configure: {
  	container: document.getElementById('optionsContainer'),
  	showButton: false
  },

  physics:{
  	enabled: false,
  },

  manipulation: {
    enabled:true,
  	initiallyActive :true,

  addNode: function (data, callback) {
   document.getElementById('network-popUp').style.display = 'block';
   document.getElementById('node-label').value="";
	 document.getElementById('tag-input').value="";
   document.getElementById('node-label').focus();

   $('#node-description').html("");

	$('#tag-input').empty();
	for(var i=0; i<tabTag.length;i++)
	{

 		var tagList = document.getElementById("tag-input");
		var option = document.createElement("option");
		option.text = tabTag[i];
		tagList.add(option);

		$(document).ready(function() {
			$('#tag-input').select2({
				placeholder: "Select a Tag",
				allowClear: true,
				tags: true
			});
		});
	}

    document.getElementById('saveButton').onclick = function(){

	 	var tabTagNew=[];
		var selectedTag=($('#tag-input').val());
		for(var currentTag in selectedTag){
			tabTagNew.push(selectedTag[currentTag]);
		}

        	nodesDataset.add({
        		id:nodesDataset.length,
        		label: document.getElementById('node-label').value,
        		description: $('#node-description').html(),
        		shape:"ellipse",
        		color:'rgba(60,60,60,0.6)',
				    tags:tabTagNew
        	});

        	var location=network.DOMtoCanvas({x:locX,y:locY});

        	network.moveNode(nodesDataset.length-1,location.x,location.y);

        	allNodes=nodesDataset.get({returnType:"Object"});
        	document.getElementById('network-popUp').style.display = 'none';
   	        updateLeftPane();

	 	add_tag();
        };

        document.getElementById('cancelButton').onclick = function(){
        	document.getElementById('saveButton').onclick = null;
        	document.getElementById('cancelButton').onclick = null;
        	document.getElementById('network-popUp').style.display = 'none';
        };

        locX=0;
        locY=0;

        var updateArray = [];
        for (var nodeId in allNodes) {
        	if (allNodes.hasOwnProperty(nodeId)) {
        		updateArray.push(allNodes[nodeId]);
        	}
        }
        nodesDataset.update(updateArray);
    },

    addEdge: function (data, callback) {

    	var edge_label_value="";
    	if (data.from != data.to) {
    		//document.getElementById('operation').innerHTML = "Add Edge";
    		document.getElementById('network-popUp_edge').style.display = 'block';

    		$('input.boxplus').prop('checked',false);
    		$('input.boxminus').prop('checked',false);

    		$('input.boxplus').on('change', function() {
    			$('input.boxminus').prop('checked', false);
    		});
    		$('input.boxminus').on('change', function() {
    			$('input.boxplus').prop('checked', false);
    		});

			 function save_edge (){

    			if($('input.boxplus').prop('checked')){
    				// console.log("je passe");
    				edge_label_value= '+';
    			}else if($('input.boxminus').prop('checked')){
    				// console.log("je passe 2");
    				edge_label_value= '-';
    			}
    			else{
    				alert("Please select one of the influence directions before validating edge edtition");
    			}
    			// console.log(edge_label_value)

    			if(edge_label_value != ""){
    				allEdges=edgesDataset.get({returnType:"Object"});

    				edgesDataset.add({
    					id:edgesDataset.length,
    					from:data.from,
    					to:data.to,
    					label:edge_label_value
    				});

    				allEdges=edgesDataset.get({returnType:"Object"});
    				// console.log(edgesDataset);

    				document.getElementById('network-popUp_edge').style.display = 'none';
    			}
    		};

    		document.getElementById('saveButton_edge').onclick=function(e){
    			save_edge();
    		}

    		document.onkeydown=function(e){
    			if(e.keyCode === 13 ){
    				save_edge();
    			}
    		}

    		document.getElementById('cancelButton_edge').onclick = function(){
    			document.getElementById('saveButton_edge').onclick = null;
    			document.getElementById('cancelButton_edge').onclick = null;
    			document.getElementById('network-popUp_edge').style.display = 'none';
    		};

    		var updateArray = [];
    		for (var edgeId in allEdges) {
    			updateArray.push(allEdges[edgeId]);
    		}
    		edgesDataset.update(updateArray);
    	}

    },
    editNode:function(data,callback){

    editNode();

    network.setOptions(
    {
      manipulation:{
        initiallyActive :true
      }
    });
    },
    editEdge:function(data,callback){

     console.log("je suis dans editEdge");
    	var edge_label_value;

        edgesDataset.update({
              id:data.id,
              from:data.from,
              to:data.to
              // label:edge_label_value
            });

        var updateArray = [];
        for (var edgeId in allEdges) {
          updateArray.push(allEdges[edgeId]);
        }
        edgesDataset.update(updateArray);

    	if (typeof data.to == "number") {

    		// document.getElementById('operation').innerHTML = "Add Edge";
    		document.getElementById('network-popUp_edge').style.display = 'block';

    		$('input.boxplus').prop('checked',false);
    		$('input.boxminus').prop('checked',false);

    		$('input.boxplus').on('change', function() {
    			$('input.boxminus').prop('checked', false);
    		});
    		$('input.boxminus').on('change', function() {
    			$('input.boxplus').prop('checked', false);
    		});

    		document.getElementById('saveButton_edge').onclick = function(){
    			if($('input.boxplus').prop('checked')){
    				edge_label_value= '+';
    			}else if($('input.boxminus').prop('checked')){
    				edge_label_value= '-';
    			}
    			else{
    				alert("Please select one of the influence directions before validating edge edtition");
    				edge_label_value="";
    			}

    			if(edge_label_value != ""){

    				allEdges=edgesDataset.get({returnType:"Object"});

    				edgesDataset.update({
    					id:data.id,
    					from:data.from,
    					to:data.to,
    					label:edge_label_value
    				});

    				allEdges=edgesDataset.get({returnType:"Object"});

    				document.getElementById('network-popUp_edge').style.display = 'none';
    			}
    		};

    		document.getElementById('cancelButton_edge').onclick = function(){
    			document.getElementById('saveButton_edge').onclick = null;
    			document.getElementById('cancelButton_edge').onclick = null;
    			document.getElementById('network-popUp_edge').style.display = 'none';
    		};

    		var updateArray = [];
    		for (var edgeId in allEdges) {
    			updateArray.push(allEdges[edgeId]);
    		}
    		edgesDataset.update(updateArray);
        popUpEditEdges=1;
    	}else{

          document.getElementById('network-popUp_edge').style.display = 'block';

        $('input.boxplus').prop('checked',false);
        $('input.boxminus').prop('checked',false);

        $('input.boxplus').on('change', function() {
          $('input.boxminus').prop('checked', false);
        });
        $('input.boxminus').on('change', function() {
          $('input.boxplus').prop('checked', false);
        });

        document.getElementById('saveButton_edge').onclick = function(){
          if($('input.boxplus').prop('checked')){
            edge_label_value= '+';
          }else if($('input.boxminus').prop('checked')){
            edge_label_value= '-';
          }
          else{
            alert("Please select one of the influence directions before validating edge edtition");
            edge_label_value="";
          }

          if(edge_label_value != ""){

            allEdges=edgesDataset.get({returnType:"Object"});

            edgesDataset.update({
              id:data.id,
              from:allEdges[editEdgeId].to,
              to:allEdges[editEdgeId].from,
              label:edge_label_value
            });

            allEdges=edgesDataset.get({returnType:"Object"});

            document.getElementById('network-popUp_edge').style.display = 'none';
             }
          };

        document.getElementById('cancelButton_edge').onclick = function(){
          document.getElementById('saveButton_edge').onclick = null;
          document.getElementById('cancelButton_edge').onclick = null;
          document.getElementById('network-popUp_edge').style.display = 'none';
        };

        var updateArray = [];
        for (var edgeId in allEdges) {
          updateArray.push(allEdges[edgeId]);
        }
        edgesDataset.update(updateArray);
      }
    },
    deleteNode:function(data,callback){
    	remove();
    	neighbourhoodHighlight({nodes:[]});
    },
    deleteEdge:function(data,callback){
  		idselect=data.edges[0];
      console.log(idselect);
	   	removeEdge();
    }
  }
};

	data = {nodes: nodesDataset , edges:edgesDataset };
	network = new vis.Network(container, data, options);
	listener();
	    //console.log(tempNodeDataset);

		//nodesDataset=tempNodeDataset;
		layout_physical_active=false;
		layout_hierarchical_active=true;

    }

	else if($("#text_scenario")[0].innerHTML.includes("You are already on the") == false) {
	  		document.getElementById("text_scenario").innerHTML+="
" + "You are already on the hierarchical layout !";
		}

	}
<commit_msg>bug hierarchical layout<commit_after>var layout_physical_active=true;
var layout_hierarchical_active=false;

var temp;
var allNodesTemp;

function layout_physical(){

	if(layout_physical_active != true){

	   document.getElementById("text_scenario").innerHTML="";
	   console.log(typeof $("#text_scenario")[0].innerHTML);

		redrawAll();
	}else if($("#text_scenario")[0].innerHTML.includes("You are already on the") == false){

	  		document.getElementById("text_scenario").innerHTML+="
" + "You are already on the physical layout !";
		}

}

function layout_hierarchical(){

		console.log(JSON.stringify(allNodes));
	//allNodes=nodesDataset.get({returnType:"Object"});

		var updateArray = [];
 	for (var nodeId in allNodes) {
 		if (allNodes.hasOwnProperty(nodeId)) {
 			updateArray.push(allNodes[nodeId]);
 		}
 	}
	temp= new vis.DataSet(updateArray);

	console.log(JSON.stringify(temp));

	if(layout_hierarchical_active==false){

	   document.getElementById("text_scenario").innerHTML="";

	 // Create a new directed graph
	 var g = new dagre.graphlib.Graph();

	 // Set an object for the graph label
	 g.setGraph({
		nodestep:30,
		edgesep:40,
		ranksep:500
	 });

	 // Default to assigning a new object as a label for each new edge.
	 g.setDefaultEdgeLabel(function() { return {}; });

	 for (var nodeId in allNodes) {
		 g.setNode(allNodes[nodeId].id,    {  width: 200, height: 100 });
	 }

	 for (var edgeId in allEdges) {
		 g.setEdge(allEdges[edgeId].from,   allEdges[edgeId].to);
	 }

	 dagre.layout(g);

	 var i=0;

	g.nodes().forEach(function(v) {
		var string=JSON.stringify(g.node(v));

		var pos1=string.indexOf("x");
		var pos2=string.indexOf(",\"y\":");
		var stringx=string.substring(pos1+3,pos2);
		var x=parseInt(stringx);
		allNodes[i].x=x;

		var pos3=string.indexOf("y");
	    var pos4=string.indexOf("}");
		var stringy=string.substring(pos3+3,pos4);
		var y=parseInt(stringy);
		allNodes[i].y=y;

		i++;
		});

	var updateArray = [];
 	for (var nodeId in allNodes) {
 		if (allNodes.hasOwnProperty(nodeId)) {
 			updateArray.push(allNodes[nodeId]);
 		}
 	}
	nodesDataset.update(updateArray);

options = {
       layout:{
         improvedLayout: false
       },
      nodes: {
      	margin: 5,

        widthConstraint: {
        	maximum: 150
        },
        scaling: {
        	min: 10,
        	max: 30,

        	label: {
        		min: 6,
        		max: 30,
        		drawThreshold: 5,
        		maxVisible: 20
        	}
        },

        font: {
        	color:'#ffffff',
        	size: 16,
        	face: 'Tahoma'
        },
    },

    edges: {
    	smooth: {
    		enabled: false,
    		type:'continuous'
    	},
    	color:{
    		inherit:false,
    		color:'rgba(60,60,60,0.6)',
    		hover:'rgba(60,60,60,0.6)',
    		highlight:'rgba(60,60,60,0.6)',

    	},

    	width: 0.15,

    	font: {
    		size:30,
    		align: 'top'
    	},

    	arrows: 'to',
    },

    interaction: {
    	dragNodes:true,
    	hover:true,
    	hoverConnectedEdges:true,
    	hideEdgesOnDrag: true,
    	tooltipDelay: 200,
    	navigationButtons: true,
    	multiselect:true
      // keyboard: true

  },

  configure: {
  	container: document.getElementById('optionsContainer'),
  	showButton: false
  },

  physics:{
  	enabled: false,
  },

  manipulation: {
    enabled:true,
  	initiallyActive :true,

  addNode: function (data, callback) {
   document.getElementById('network-popUp').style.display = 'block';
   document.getElementById('node-label').value="";
	 document.getElementById('tag-input').value="";
   document.getElementById('node-label').focus();

   $('#node-description').html("");

	$('#tag-input').empty();
	for(var i=0; i<tabTag.length;i++)
	{

 		var tagList = document.getElementById("tag-input");
		var option = document.createElement("option");
		option.text = tabTag[i];
		tagList.add(option);

		$(document).ready(function() {
			$('#tag-input').select2({
				placeholder: "Select a Tag",
				allowClear: true,
				tags: true
			});
		});
	}

    document.getElementById('saveButton').onclick = function(){

	 	var tabTagNew=[];
		var selectedTag=($('#tag-input').val());
		for(var currentTag in selectedTag){
			tabTagNew.push(selectedTag[currentTag]);
		}

        	nodesDataset.add({
        		id:nodesDataset.length,
        		label: document.getElementById('node-label').value,
        		description: $('#node-description').html(),
        		shape:"ellipse",
        		color:'rgba(60,60,60,0.6)',
				    tags:tabTagNew
        	});

        	var location=network.DOMtoCanvas({x:locX,y:locY});

        	network.moveNode(nodesDataset.length-1,location.x,location.y);

        	allNodes=nodesDataset.get({returnType:"Object"});
        	document.getElementById('network-popUp').style.display = 'none';
   	        updateLeftPane();

	 	add_tag();
        };

        document.getElementById('cancelButton').onclick = function(){
        	document.getElementById('saveButton').onclick = null;
        	document.getElementById('cancelButton').onclick = null;
        	document.getElementById('network-popUp').style.display = 'none';
        };

        locX=0;
        locY=0;

        var updateArray = [];
        for (var nodeId in allNodes) {
        	if (allNodes.hasOwnProperty(nodeId)) {
        		updateArray.push(allNodes[nodeId]);
        	}
        }
        nodesDataset.update(updateArray);
    },

    addEdge: function (data, callback) {

    	var edge_label_value="";
    	if (data.from != data.to) {
    		//document.getElementById('operation').innerHTML = "Add Edge";
    		document.getElementById('network-popUp_edge').style.display = 'block';

    		$('input.boxplus').prop('checked',false);
    		$('input.boxminus').prop('checked',false);

    		$('input.boxplus').on('change', function() {
    			$('input.boxminus').prop('checked', false);
    		});
    		$('input.boxminus').on('change', function() {
    			$('input.boxplus').prop('checked', false);
    		});

			 function save_edge (){

    			if($('input.boxplus').prop('checked')){
    				// console.log("je passe");
    				edge_label_value= '+';
    			}else if($('input.boxminus').prop('checked')){
    				// console.log("je passe 2");
    				edge_label_value= '-';
    			}
    			else{
    				alert("Please select one of the influence directions before validating edge edtition");
    			}
    			// console.log(edge_label_value)

    			if(edge_label_value != ""){
    				allEdges=edgesDataset.get({returnType:"Object"});

    				edgesDataset.add({
    					id:edgesDataset.length,
    					from:data.from,
    					to:data.to,
    					label:edge_label_value
    				});

    				allEdges=edgesDataset.get({returnType:"Object"});
    				// console.log(edgesDataset);

    				document.getElementById('network-popUp_edge').style.display = 'none';
    			}
    		};

    		document.getElementById('saveButton_edge').onclick=function(e){
    			save_edge();
    		}

    		document.onkeydown=function(e){
    			if(e.keyCode === 13 ){
    				save_edge();
    			}
    		}

    		document.getElementById('cancelButton_edge').onclick = function(){
    			document.getElementById('saveButton_edge').onclick = null;
    			document.getElementById('cancelButton_edge').onclick = null;
    			document.getElementById('network-popUp_edge').style.display = 'none';
    		};

    		var updateArray = [];
    		for (var edgeId in allEdges) {
    			updateArray.push(allEdges[edgeId]);
    		}
    		edgesDataset.update(updateArray);
    	}

    },
    editNode:function(data,callback){

    editNode();

    network.setOptions(
    {
      manipulation:{
        initiallyActive :true
      }
    });
    },
    editEdge:function(data,callback){

     console.log("je suis dans editEdge");
    	var edge_label_value;

        edgesDataset.update({
              id:data.id,
              from:data.from,
              to:data.to
              // label:edge_label_value
            });

        var updateArray = [];
        for (var edgeId in allEdges) {
          updateArray.push(allEdges[edgeId]);
        }
        edgesDataset.update(updateArray);

    	if (typeof data.to == "number") {

    		// document.getElementById('operation').innerHTML = "Add Edge";
    		document.getElementById('network-popUp_edge').style.display = 'block';

    		$('input.boxplus').prop('checked',false);
    		$('input.boxminus').prop('checked',false);

    		$('input.boxplus').on('change', function() {
    			$('input.boxminus').prop('checked', false);
    		});
    		$('input.boxminus').on('change', function() {
    			$('input.boxplus').prop('checked', false);
    		});

    		document.getElementById('saveButton_edge').onclick = function(){
    			if($('input.boxplus').prop('checked')){
    				edge_label_value= '+';
    			}else if($('input.boxminus').prop('checked')){
    				edge_label_value= '-';
    			}
    			else{
    				alert("Please select one of the influence directions before validating edge edtition");
    				edge_label_value="";
    			}

    			if(edge_label_value != ""){

    				allEdges=edgesDataset.get({returnType:"Object"});

    				edgesDataset.update({
    					id:data.id,
    					from:data.from,
    					to:data.to,
    					label:edge_label_value
    				});

    				allEdges=edgesDataset.get({returnType:"Object"});

    				document.getElementById('network-popUp_edge').style.display = 'none';
    			}
    		};

    		document.getElementById('cancelButton_edge').onclick = function(){
    			document.getElementById('saveButton_edge').onclick = null;
    			document.getElementById('cancelButton_edge').onclick = null;
    			document.getElementById('network-popUp_edge').style.display = 'none';
    		};

    		var updateArray = [];
    		for (var edgeId in allEdges) {
    			updateArray.push(allEdges[edgeId]);
    		}
    		edgesDataset.update(updateArray);
        popUpEditEdges=1;
    	}else{

          document.getElementById('network-popUp_edge').style.display = 'block';

        $('input.boxplus').prop('checked',false);
        $('input.boxminus').prop('checked',false);

        $('input.boxplus').on('change', function() {
          $('input.boxminus').prop('checked', false);
        });
        $('input.boxminus').on('change', function() {
          $('input.boxplus').prop('checked', false);
        });

        document.getElementById('saveButton_edge').onclick = function(){
          if($('input.boxplus').prop('checked')){
            edge_label_value= '+';
          }else if($('input.boxminus').prop('checked')){
            edge_label_value= '-';
          }
          else{
            alert("Please select one of the influence directions before validating edge edtition");
            edge_label_value="";
          }

          if(edge_label_value != ""){

            allEdges=edgesDataset.get({returnType:"Object"});

            edgesDataset.update({
              id:data.id,
              from:allEdges[editEdgeId].to,
              to:allEdges[editEdgeId].from,
              label:edge_label_value
            });

            allEdges=edgesDataset.get({returnType:"Object"});

            document.getElementById('network-popUp_edge').style.display = 'none';
             }
          };

        document.getElementById('cancelButton_edge').onclick = function(){
          document.getElementById('saveButton_edge').onclick = null;
          document.getElementById('cancelButton_edge').onclick = null;
          document.getElementById('network-popUp_edge').style.display = 'none';
        };

        var updateArray = [];
        for (var edgeId in allEdges) {
          updateArray.push(allEdges[edgeId]);
        }
        edgesDataset.update(updateArray);
      }
    },
    deleteNode:function(data,callback){
    	remove();
    	neighbourhoodHighlight({nodes:[]});
    },
    deleteEdge:function(data,callback){
  		idselect=data.edges[0];
      console.log(idselect);
	   	removeEdge();
    }
  }
};

	data = {nodes: nodesDataset , edges:edgesDataset };
	network = new vis.Network(container, data, options);
	listener();
	    //console.log(tempNodeDataset);

		layout_physical_active=false;
		layout_hierarchical_active=true;

    }

	else if($("#text_scenario")[0].innerHTML.includes("You are already on the") == false) {
	  		document.getElementById("text_scenario").innerHTML+="
" + "You are already on the hierarchical layout !";
		}

	allNodes=temp.get({returnType:"Object"});

		  var updateArray = [];
 	for (var nodeId in allNodes) {
 		if (allNodes.hasOwnProperty(nodeId)) {
 			updateArray.push(allNodes[nodeId]);
 		}
 	}
	nodesDataset.update(updateArray);

	data.nodes.update(data.nodes.get().map(function(item) {
	  item.x = undefined;
	  item.y = undefined;
	  return item;
	}));

	console.log(JSON.stringify(allNodes));
	console.log(JSON.stringify(temp));
	console.log(JSON.stringify(nodesDataset));

	}
<|endoftext|>


<commit_before>import { lazy } from 'react'
import locales from './locales'
import routes from './routes'
import getMenuItems from './menuItems'
import themes from './themes'
import parseLanguages from 'base-shell/lib/utils/locale'

const config = {
  auth: {
    signInURL: '/signin',
  },
  routes,
  locale: {
    locales,
    defaultLocale: parseLanguages(['en', 'de', 'ru'], 'en'),
    onError: (e) => {
      //console.warn(e)
      return
    },
  },
  menu: {
    getMenuItems,
  },
  theme: {
    themes,
    defaultThemeID: 'default',
    defaultIsDarkMode: false,
    defaultIsRTL: false //change this to true for Right to Left Language support
  },
  pages: {
    LandingPage: lazy(() => import('../pages/LandingPage/LandingPage')),
    PageNotFound: lazy(() => import('../pages/PageNotFound/PageNotFound')),
  },
}

export default config
<commit_msg>making comment more clear on what the default variable does<commit_after>import { lazy } from 'react'
import locales from './locales'
import routes from './routes'
import getMenuItems from './menuItems'
import themes from './themes'
import parseLanguages from 'base-shell/lib/utils/locale'

const config = {
  auth: {
    signInURL: '/signin',
  },
  routes,
  locale: {
    locales,
    defaultLocale: parseLanguages(['en', 'de', 'ru'], 'en'),
    onError: (e) => {
      //console.warn(e)
      return
    },
  },
  menu: {
    getMenuItems,
  },
  theme: {
    themes,
    defaultThemeID: 'default',
    defaultIsDarkMode: false,
    defaultIsRTL: false //change this to true for default Right to Left Language support
  },
  pages: {
    LandingPage: lazy(() => import('../pages/LandingPage/LandingPage')),
    PageNotFound: lazy(() => import('../pages/PageNotFound/PageNotFound')),
  },
}

export default config
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react'
import DateField from './fields/date'
import Field from './fields/field'
import List from './list'
import NumberField from './fields/number'
import RadioField from './fields/radio'
import SelectField from './fields/select'
import Table from './table'
import TextareaField from './fields/textarea'

const fieldTypes = {
  'date': DateField,
  'number': NumberField,
  'string': Field,
}

function getField(property) {
  switch (property.type) {
    case 'date': return DateField
    case 'number': return NumberField
    case 'string':
      switch (property.display) {
        case 'radio': return RadioField
        case 'select': return SelectField
        case 'textarea': return TextareaField
        default: return Field
      }
  }

  throw Error(`Unsupported property type '${property.type}`)
}

export default class Fieldset extends Component {
  static get propTypes() {
    return {
      properties: PropTypes.array.isRequired,
      update: PropTypes.func,
    }
  }

  render() {
    return (

        {this.props.properties.map(property => {
          switch (property.type) {
            case 'array': return this.renderArray(property)
            case 'object': return this.renderObject(property)
            default: return this.renderField(property)
          }
        })}

    )
  }

  renderArray(property) {
    const firstItem = property.items[0]

    if (firstItem && firstItem.properties) {
      return

    }

    return <List key={property.id} />
  }

  renderField(property) {
    let Field = getField(property)

    return (

        {property.title}
        <Field property={property} update={this.props.update} />

    )
  }

  renderObject(property) {
    return (

        {property.title}
        <Fieldset properties={property.properties} update={this.props.update} />

    )
  }
}
<commit_msg>Cleanup.<commit_after>import React, { Component, PropTypes } from 'react'
import DateField from './fields/date'
import Field from './fields/field'
import List from './list'
import NumberField from './fields/number'
import RadioField from './fields/radio'
import SelectField from './fields/select'
import Table from './table'
import TextareaField from './fields/textarea'

function getField(property) {
  switch (property.type) {
    case 'date': return DateField
    case 'number': return NumberField
    case 'string':
      switch (property.display) {
        case 'radio': return RadioField
        case 'select': return SelectField
        case 'textarea': return TextareaField
        default: return Field
      }
  }

  throw Error(`Unsupported property type '${property.type}`)
}

export default class Fieldset extends Component {
  static get propTypes() {
    return {
      properties: PropTypes.array.isRequired,
      update: PropTypes.func,
    }
  }

  render() {
    return (

        {this.props.properties.map(property => {
          switch (property.type) {
            case 'array': return this.renderArray(property)
            case 'object': return this.renderObject(property)
            default: return this.renderField(property)
          }
        })}

    )
  }

  renderArray(property) {
    const firstItem = property.items[0]

    if (firstItem && firstItem.properties) {
      return

    }

    return <List key={property.id} />
  }

  renderField(property) {
    let Field = getField(property)

    return (

        {property.title}
        <Field property={property} update={this.props.update} />

    )
  }

  renderObject(property) {
    return (

        {property.title}
        <Fieldset properties={property.properties} update={this.props.update} />

    )
  }
}
<|endoftext|>


<commit_before>/**
 * @module timed
 * @submodule timed-components
 * @public
 */
import Component         from 'ember-component'
import ReportValidations from 'timed/validations/report'

/**
 * Custom modal for editing reports
 *
 * @class EditReportModalComponent
 * @extends Ember.Component
 * @public
 */
export default Component.extend({
  /**
   * Whether the modal is currently visible
   *
   * @property {Boolean} visible
   * @public
   */
  visible: true,

  /**
   * Validator for the changeset
   *
   * @property {Object} validator
   * @public
   */
  validator: ReportValidations,

  /**
   * Actions for the component
   *
   * @property {Object} actions
   * @public
   */
  actions: {
    /**
     * Close the modal and rollback the changes
     *
     * @method close
     * @param {Changeset} changeset The changeset to rollback
     * @public
     */
    close(changeset) {
      changeset.rollback()

      this.set('visible', false)

      this.get('attrs.on-close')()
    },

    /**
     * Validate the changeset and save if valid
     *
     * @method save
     * @param {Changeset} changeset The changeset to save
     * @public
     */
    save(changeset) {
      changeset.validate()

      if (changeset.get('isValid')) {
        changeset.execute()

        this.get('attrs.on-save')(this.get('report'))
      }
    },

    /**
     * Delete the report
     *
     * @method delete
     * @public
     */
    delete() {
      this.get('attrs.on-delete')(this.get('report'))
    }
  }
})
<commit_msg>Focus invalid fields after failed validation<commit_after>/**
 * @module timed
 * @submodule timed-components
 * @public
 */
import Component         from 'ember-component'
import ReportValidations from 'timed/validations/report'

/**
 * Custom modal for editing reports
 *
 * @class EditReportModalComponent
 * @extends Ember.Component
 * @public
 */
export default Component.extend({
  /**
   * Whether the modal is currently visible
   *
   * @property {Boolean} visible
   * @public
   */
  visible: true,

  /**
   * Validator for the changeset
   *
   * @property {Object} validator
   * @public
   */
  validator: ReportValidations,

  /**
   * Actions for the component
   *
   * @property {Object} actions
   * @public
   */
  actions: {
    /**
     * Close the modal and rollback the changes
     *
     * @method close
     * @param {Changeset} changeset The changeset to rollback
     * @public
     */
    close(changeset) {
      changeset.rollback()

      this.set('visible', false)

      this.get('attrs.on-close')()
    },

    /**
     * Validate the changeset and save if valid
     *
     * @method save
     * @param {Changeset} changeset The changeset to save
     * @public
     */
    save(changeset) {
      changeset.validate()

      if (changeset.get('isValid')) {
        changeset.execute()

        this.get('attrs.on-save')(this.get('report'))
      }
      else {
        this.$().find('.has-error input, .has-error textarea, .has-error select').first().focus()
      }
    },

    /**
     * Delete the report
     *
     * @method delete
     * @public
     */
    delete() {
      this.get('attrs.on-delete')(this.get('report'))
    }
  }
})
<|endoftext|>


<commit_before>/* eslint-env mocha */
'use strict'

const CID = require('cids')
const { spawnNodesWithId } = require('../utils/spawn')
const { getDescribe, getIt, expect } = require('../utils/mocha')
const { connect } = require('../utils/swarm')

module.exports = (createCommon, options) => {
  const describe = getDescribe(options)
  const it = getIt(options)
  const common = createCommon()

  describe('.dht.provide', function () {
    this.timeout(80 * 1000)

    let ipfs

    before(function (done) {
      // CI takes longer to instantiate the daemon, so we need to increase the
      // timeout for the before step
      this.timeout(60 * 1000)

      common.setup((err, factory) => {
        expect(err).to.not.exist()

        spawnNodesWithId(2, factory, (err, nodes) => {
          expect(err).to.not.exist()
          ipfs = nodes[0]
          connect(ipfs, nodes[1].peerId.addresses[0], done)
        })
      })
    })

    after(function (done) {
      this.timeout(50 * 1000)

      common.teardown(done)
    })

    it('should provide local CID', (done) => {
      ipfs.add(Buffer.from('test'), (err, res) => {
        if (err) return done(err)

        ipfs.dht.provide(new CID(res[0].hash), (err) => {
          expect(err).to.not.exist()
          done()
        })
      })
    })

    it('should not provide if block not found locally', (done) => {
      const cid = new CID('Qmd7qZS4T7xXtsNFdRoK1trfMs5zU94EpokQ9WFtxdPxsZ')

      ipfs.dht.provide(cid, (err) => {
        expect(err).to.exist()
        expect(err.message).to.include('not found locally')
        done()
      })
    })

    it('should allow multiple CIDs to be passed', (done) => {
      ipfs.add([
        { content: Buffer.from('t0') },
        { content: Buffer.from('t1') }
      ], (err, res) => {
        if (err) return done(err)

        ipfs.dht.provide([
          new CID(res[0].hash),
          new CID(res[1].hash)
        ], (err) => {
          expect(err).to.not.exist()
          done()
        })
      })
    })

    it('should provide a CIDv1', (done) => {
      ipfs.add(Buffer.from('test'), { cidVersion: 1 }, (err, res) => {
        if (err) return done(err)

        const cid = new CID(res[0].hash)

        ipfs.dht.provide(cid, (err) => {
          expect(err).to.not.exist()
          done()
        })
      })
    })

    it('should error on non CID arg', (done) => {
      ipfs.dht.provide({}, (err) => {
        expect(err).to.exist()
        done()
      })
    })

    it('should error on array containing non CID arg', (done) => {
      ipfs.dht.provide([{}], (err) => {
        expect(err).to.exist()
        done()
      })
    })
  })
}
<commit_msg>test: add dht.provide() test with string CID parameter (#555)<commit_after>/* eslint-env mocha */
'use strict'

const CID = require('cids')
const { spawnNodesWithId } = require('../utils/spawn')
const { getDescribe, getIt, expect } = require('../utils/mocha')
const { connect } = require('../utils/swarm')

module.exports = (createCommon, options) => {
  const describe = getDescribe(options)
  const it = getIt(options)
  const common = createCommon()

  describe('.dht.provide', function () {
    this.timeout(80 * 1000)

    let ipfs

    before(function (done) {
      // CI takes longer to instantiate the daemon, so we need to increase the
      // timeout for the before step
      this.timeout(60 * 1000)

      common.setup((err, factory) => {
        expect(err).to.not.exist()

        spawnNodesWithId(2, factory, (err, nodes) => {
          expect(err).to.not.exist()
          ipfs = nodes[0]
          connect(ipfs, nodes[1].peerId.addresses[0], done)
        })
      })
    })

    after(function (done) {
      this.timeout(50 * 1000)

      common.teardown(done)
    })

    it('should provide local CID', (done) => {
      ipfs.add(Buffer.from('test'), (err, res) => {
        if (err) return done(err)

        ipfs.dht.provide(new CID(res[0].hash), (err) => {
          expect(err).to.not.exist()
          done()
        })
      })
    })

    it('should not provide if block not found locally', (done) => {
      const cid = new CID('Qmd7qZS4T7xXtsNFdRoK1trfMs5zU94EpokQ9WFtxdPxsZ')

      ipfs.dht.provide(cid, (err) => {
        expect(err).to.exist()
        expect(err.message).to.include('not found locally')
        done()
      })
    })

    it('should allow multiple CIDs to be passed', (done) => {
      ipfs.add([
        { content: Buffer.from('t0') },
        { content: Buffer.from('t1') }
      ], (err, res) => {
        if (err) return done(err)

        ipfs.dht.provide([
          new CID(res[0].hash),
          new CID(res[1].hash)
        ], (err) => {
          expect(err).to.not.exist()
          done()
        })
      })
    })

    it('should provide a CIDv1', (done) => {
      ipfs.add(Buffer.from('test'), { cidVersion: 1 }, (err, res) => {
        if (err) return done(err)

        const cid = new CID(res[0].hash)

        ipfs.dht.provide(cid, (err) => {
          expect(err).to.not.exist()
          done()
        })
      })
    })
    it('should provide a CIDv1 string', (done) => {
      ipfs.add(Buffer.from('test'), { cidVersion: 1 }, (err, res) => {
        if (err) return done(err)

        const cid = res[0].hash

        ipfs.dht.provide(cid, (err) => {
          expect(err).to.not.exist()
          done()
        })
      })
    })
    it('should error on non CID arg', (done) => {
      ipfs.dht.provide({}, (err) => {
        expect(err).to.exist()
        done()
      })
    })

    it('should error on array containing non CID arg', (done) => {
      ipfs.dht.provide([{}], (err) => {
        expect(err).to.exist()
        done()
      })
    })
  })
}
<|endoftext|>


<commit_before>/* eslint-disable consistent-return, no-console */
const express = require('express');
const createWebpackMiddleware = require('webpack-express-middleware');
const path = require('path')
const app = express();
const pack = express();
const video = express();
const config = require('./webpack.config');

const ip = process.env.IP || require('ip').address()
const port = process.env.PORT || 8443

video.get('*', function(req, res) {
  res.sendFile(path.resolve(__dirname + '/build/video.html'))
});

const isDevelopment = process.env.NODE_ENV !== 'production';

if (isDevelopment) {
  const compiler = require('webpack')(config);
  const webpackMiddleware = createWebpackMiddleware(compiler, config);
  webpackMiddleware(pack);
} else {
  pack.use(express.static(config.output.path));
  pack.get('/', function(req, res) {
    res.sendFile(config.output.path + "/index.html");
  });
}

app.use('/video', video)
app.use('/', pack)

if (port === 8443) {
  const https = require('https')
  const fs = require('fs')
  const key = fs.readFileSync('config/ssl.key')
  const cert = fs.readFileSync('config/ssl.crt')
  https.createServer({ key: key, cert: cert }, app)
    .listen(port, function(err) {
      if (!err) {
        console.log('Listening at ' + 'https://' + ip + ':' + port + '/')
      } else {
        console.log(err)
      }
    })
} else {
  const http = require('http')
  http.createServer(app).listen(port)
}

<commit_msg>Replaces use for get for index.html<commit_after>/* eslint-disable consistent-return, no-console */
const express = require('express');
const createWebpackMiddleware = require('webpack-express-middleware');
const path = require('path')
const app = express();
const pack = express();
const video = express();
const config = require('./webpack.config');

const ip = process.env.IP || require('ip').address()
const port = process.env.PORT || 8443

video.get('*', function(req, res) {
  res.sendFile(path.resolve(__dirname + '/build/video.html'))
});

const isDevelopment = process.env.NODE_ENV !== 'production';

if (isDevelopment) {
  const compiler = require('webpack')(config);
  const webpackMiddleware = createWebpackMiddleware(compiler, config);
  webpackMiddleware(pack);
} else {
  pack.use(express.static(__dirname + '/build'));
  pack.get('/', function(req, res) {
    res.sendFile(__dirname + "/build/index.html");
  });
}

app.use('/video', video)
app.use('/', pack)

if (port === 8443) {
  const https = require('https')
  const fs = require('fs')
  const key = fs.readFileSync('config/ssl.key')
  const cert = fs.readFileSync('config/ssl.crt')
  https.createServer({ key: key, cert: cert }, app)
    .listen(port, function(err) {
      if (!err) {
        console.log('Listening at ' + 'https://' + ip + ':' + port + '/')
      } else {
        console.log(err)
      }
    })
} else {
  const http = require('http')
  http.createServer(app).listen(port)
}

<|endoftext|>


<commit_before>var imageGroups = [
    {a:"IMG_2753.JPG",b:"IMG_2765.JPG"},
    {a:"IMG_2684.JPG",b:"IMG_2793.JPG"}
];

function addCover(element, text, src){
    element.style.position="relative";

    var cover = document.createElement("div");
    cover.textContent = text;
    cover.className="img-cover";
    cover.setAttribute("data-img", src);
    cover.onclick=function(e){
        openModal(e.target.getAttribute("data-img"));
    }

    element.appendChild(cover);
}

function init(){

    var photoHolder = document.createElement("div");

    for(var i = 0; i < imageGroups.length; i++){
        var imgGrp = imageGroups[i];

        var imgGrpOuterDiv = document.createElement("div");
        imgGrpOuterDiv.className = "img-grp-outer-div";

        var imgGrpDiv = document.createElement("div");
        imgGrpDiv.className = "img-grp";

        var img1w = document.createElement("div");
        img1w.className="img-wrp";
        addCover(img1w, "before", "pics/"+imgGrp.a);

        var img1 = document.createElement("img");
        img1.src="pics/"+imgGrp.a;
        img1.height=150;

        img1w.appendChild(img1);
        imgGrpDiv.appendChild(img1w);

        var img2w = document.createElement("div");
        img2w.className="img-wrp";
        addCover(img2w, "after", "pics/"+imgGrp.b);

        var img2 = document.createElement("img");
        img2.src="pics/"+imgGrp.b;
        img2.height=150;

        img2w.appendChild(img2);
        imgGrpDiv.appendChild(img2w);

        imgGrpOuterDiv.appendChild(imgGrpDiv);

        photoHolder.appendChild(imgGrpOuterDiv);

    }

    var galleryBody = document.getElementById("gallery-body");
    galleryBody.appendChild(photoHolder);

}

function openModal(img){
    var galleryBody = document.getElementById("gallery-body");

    var modal = document.createElement("div");
    modal.className="modal";
    modal.id="the-modal";
    modal.style.background="url(" + img + ")";
    modal.style.backgroundSize="cover";

    var closeButton = document.createElement("div");
    closeButton.className="close";
    closeButton.onclick=closeModal;

    modal.appendChild(closeButton);

    galleryBody.appendChild(modal);

    var modalBg = document.getElementById("modal-bg");
    modalBg.className="";
}

function closeModal(){

    var modalBg = document.getElementById("modal-bg");
    modalBg.className="hidden";

    var modal = document.getElementById("the-modal");
    modal.className="hidden";
    modal.remove();

}

init();<commit_msg>2nd modal fix attempt<commit_after>var imageGroups = [
    {a:"IMG_2753.JPG",b:"IMG_2765.JPG"},
    {a:"IMG_2684.JPG",b:"IMG_2793.JPG"}
];

function addCover(element, text, src){
    element.style.position="relative";

    var cover = document.createElement("div");
    cover.textContent = text;
    cover.className="img-cover";
    cover.setAttribute("data-img", src);
    cover.onclick=function(e){
        openModal(e.target.getAttribute("data-img"));
    }

    element.appendChild(cover);
}

function init(){

    var photoHolder = document.createElement("div");

    for(var i = 0; i < imageGroups.length; i++){
        var imgGrp = imageGroups[i];

        var imgGrpOuterDiv = document.createElement("div");
        imgGrpOuterDiv.className = "img-grp-outer-div";

        var imgGrpDiv = document.createElement("div");
        imgGrpDiv.className = "img-grp";

        var img1w = document.createElement("div");
        img1w.className="img-wrp";
        addCover(img1w, "before", "pics/"+imgGrp.a);

        var img1 = document.createElement("img");
        img1.src="pics/"+imgGrp.a;
        img1.height=150;

        img1w.appendChild(img1);
        imgGrpDiv.appendChild(img1w);

        var img2w = document.createElement("div");
        img2w.className="img-wrp";
        addCover(img2w, "after", "pics/"+imgGrp.b);

        var img2 = document.createElement("img");
        img2.src="pics/"+imgGrp.b;
        img2.height=150;

        img2w.appendChild(img2);
        imgGrpDiv.appendChild(img2w);

        imgGrpOuterDiv.appendChild(imgGrpDiv);

        photoHolder.appendChild(imgGrpOuterDiv);

    }

    var galleryBody = document.getElementById("gallery-body");
    galleryBody.appendChild(photoHolder);

}

function openModal(img){
    var galleryBody = document.getElementById("gallery-body");

    var modal = document.createElement("div");
    modal.className="modal";
    modal.id="the-modal";
    modal.style.background="url(" + img + ")";
    modal.style.backgroundSize="cover";

    var closeButton = document.createElement("div");
    closeButton.className="close";
    closeButton.onclick=closeModal;

    modal.appendChild(closeButton);

    galleryBody.appendChild(modal);

    var modalBg = document.getElementById("modal-bg");
    modalBg.className="";
}

function closeModal(){

    var modalBg = document.getElementById("modal-bg");
    modalBg.className="hidden";

    var modal = document.getElementById("the-modal");
    modal.id="not-the-modal-any-more"
    modal.className="hidden";
    modal.remove();

}

init();<|endoftext|>


<commit_before>/*global Windows:true, URL:true */

var cordova = require('cordova'),
    Camera = require('cordova/plugin/CameraConstants');

module.exports = {

    // args will contain :
    //  ...  it is an array, so be careful
    // 0 quality:50,
    // 1 destinationType:Camera.DestinationType.FILE_URI,
    // 2 sourceType:Camera.PictureSourceType.CAMERA,
    // 3 targetWidth:-1,
    // 4 targetHeight:-1,
    // 5 encodingType:Camera.EncodingType.JPEG,
    // 6 mediaType:Camera.MediaType.PICTURE,
    // 7 allowEdit:false,
    // 8 correctOrientation:false,
    // 9 saveToPhotoAlbum:false,
    // 10 popoverOptions:null

    "takePicture": function (successCallback, errorCallback, args) {
        var encodingType = args[5];
        var targetWidth = args[3];
        var targetHeight = args[4];
        var sourceType = args[2];
        var destinationType = args[1];
        var mediaType = args[6];
        var saveToPhotoAlbum = args[9];

        var package = Windows.ApplicationModel.Package.current;
        var packageId = package.installedLocation;

        // resize method :)
        var resizeImage = function (file) {
            var tempPhotoFileName = "";
            if (encodingType == Camera.EncodingType.PNG) {
                tempPhotoFileName = "camera_cordova_temp_return.png";
            } else {
                tempPhotoFileName = "camera_cordova_temp_return.jpg";
            }
            var imgObj = new Image();
            var success = function (fileEntry) {
                var successCB = function (filePhoto) {
                    var filePhoto = filePhoto,
                        fileType = file.contentType,
                        reader = new FileReader();
                    reader.onloadend = function () {
                        var image = new Image();
                        image.src = reader.result;
                        image.onload = function () {
                            var imageWidth = targetWidth,
                                imageHeight = targetHeight;
                            var canvas = document.createElement('canvas');

                            canvas.width = imageWidth;
                            canvas.height = imageHeight;

                            var ctx = canvas.getContext("2d");
                            ctx.drawImage(this, 0, 0, imageWidth, imageHeight);

                            // The resized file ready for upload
                            var _blob = canvas.msToBlob();
                            var _stream = _blob.msDetachStream();
                            Windows.Storage.StorageFolder.getFolderFromPathAsync(packageId.path).done(function (storageFolder) {
                                storageFolder.createFileAsync(tempPhotoFileName, Windows.Storage.CreationCollisionOption.generateUniqueName).done(function (file) {
                                    file.openAsync(Windows.Storage.FileAccessMode.readWrite).done(function (fileStream) {
                                        Windows.Storage.Streams.RandomAccessStream.copyAndCloseAsync(_stream, fileStream).done(function () {
                                            successCallback(file.name);
                                        }, function () { errorCallback("Resize picture error."); })
                                    }, function () { errorCallback("Resize picture error."); })
                                }, function () { errorCallback("Resize picture error."); })
                            })

                        }
                    }

                    reader.readAsDataURL(filePhoto);

                }
                var failCB = function () {
                    errorCallback("File not found.")
                }
                fileEntry.file(successCB, failCB);
            }

            var fail = function (fileError) {
                errorCallback("FileError, code:" + fileError.code);
            }
            Windows.Storage.StorageFolder.getFolderFromPathAsync(packageId.path).done(function (storageFolder) {
                file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting).then(function (storageFile) {
                    success(new FileEntry(storageFile.name, storageFile.path));
                }, function () {
                    fail(FileError.INVALID_MODIFICATION_ERR);
                }, function () {
                    errorCallback("Folder not access.");
                });
            })

        }

        // because of asynchronous method, so let the successCallback be called in it.
        var resizeImageBase64 = function (file) {
            var imgObj = new Image();
            var success = function (fileEntry) {
                var successCB = function (filePhoto) {
                    var filePhoto = filePhoto,
                        fileType = file.contentType,
                        reader = new FileReader();
                    reader.onloadend = function () {
                        var image = new Image();
                        image.src = reader.result;

                        image.onload = function () {
                            var imageWidth = targetWidth,
                                imageHeight = targetHeight;
                            var canvas = document.createElement('canvas');

                            canvas.width = imageWidth;
                            canvas.height = imageHeight;

                            var ctx = canvas.getContext("2d");
                            ctx.drawImage(this, 0, 0, imageWidth, imageHeight);

                            // The resized file ready for upload
                            var finalFile = canvas.toDataURL(fileType);

                            // Remove the prefix such as "data:" + contentType + ";base64," , in order to meet the Cordova API.
                            var arr = finalFile.split(",");
                            var newStr = finalFile.substr(arr[0].length + 1);
                            successCallback(newStr);
                        }
                    }

                    reader.readAsDataURL(filePhoto);

                }
                var failCB = function () {
                    errorCallback("File not found.")
                }
                fileEntry.file(successCB, failCB);
            }

            var fail = function (fileError) {
                errorCallback("FileError, code:" + fileError.code);
            }
            Windows.Storage.StorageFolder.getFolderFromPathAsync(packageId.path).done(function (storageFolder) {
                file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting).then(function (storageFile) {
                    success(new FileEntry(storageFile.name, storageFile.path));
                }, function () {
                    fail(FileError.INVALID_MODIFICATION_ERR);
                }, function () {
                    errorCallback("Folder not access.");
                });
            })

        }

        if (sourceType != Camera.PictureSourceType.CAMERA) {
            var fileOpenPicker = new Windows.Storage.Pickers.FileOpenPicker();
            fileOpenPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.picturesLibrary;
            if (mediaType == Camera.MediaType.PICTURE) {
                fileOpenPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg"]);
            } else if (mediaType == Camera.MediaType.VIDEO) {
                fileOpenPicker.fileTypeFilter.replaceAll([".avi", ".flv", ".asx", ".asf", ".mov", ".mp4", ".mpg", ".rm", ".srt", ".swf", ".wmv", ".vob"]);
            } else {
                fileOpenPicker.fileTypeFilter.replaceAll(["*"]);
            }
            fileOpenPicker.pickSingleFileAsync().then(function (file) {
                if (file) {
                    if (destinationType == Camera.DestinationType.FILE_URI) {
                        if (targetHeight > 0 && targetWidth > 0) {
                            resizeImage(file);
                        } else {
                            Windows.Storage.StorageFolder.getFolderFromPathAsync(packageId.path).done(function (storageFolder) {
                                file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting).then(function (storageFile) {
                                    successCallback(storageFile.name);
                                }, function () {
                                    fail(FileError.INVALID_MODIFICATION_ERR);
                                }, function () {
                                    errorCallback("Folder not access.");
                                });
                            })

                        }
                    }
                    else {
                        if (targetHeight > 0 && targetWidth > 0) {
                            resizeImageBase64(file);
                        } else {
                            Windows.Storage.FileIO.readBufferAsync(file).done(function (buffer) {
                                var strBase64 = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(buffer);
                                successCallback(strBase64);
                            })
                        }

                    }

                } else {
                    errorCallback("User didn't choose a file.");
                }
            }, function () {
                errorCallback("User didn't choose a file.")
            })
        }
        else {

            var cameraCaptureUI = new Windows.Media.Capture.CameraCaptureUI();
            cameraCaptureUI.photoSettings.allowCropping = true;
            var allowCrop = !!args[7];
            if (!allowCrop) {
                cameraCaptureUI.photoSettings.allowCropping = false;
            }

            if (encodingType == Camera.EncodingType.PNG) {
                cameraCaptureUI.photoSettings.format = Windows.Media.Capture.CameraCaptureUIPhotoFormat.png;
            } else {
                cameraCaptureUI.photoSettings.format = Windows.Media.Capture.CameraCaptureUIPhotoFormat.jpeg;
            }
            // decide which max pixels should be supported by targetWidth or targetHeight.
            if (targetWidth >= 1280 || targetHeight >= 960) {
                cameraCaptureUI.photoSettings.maxResolution = Windows.Media.Capture.CameraCaptureUIMaxPhotoResolution.large3M;
            } else if (targetWidth >= 1024 || targetHeight >= 768) {
                cameraCaptureUI.photoSettings.maxResolution = Windows.Media.Capture.CameraCaptureUIMaxPhotoResolution.mediumXga;
            } else if (targetWidth >= 800 || targetHeight >= 600) {
                cameraCaptureUI.photoSettings.maxResolution = Windows.Media.Capture.CameraCaptureUIMaxPhotoResolution.mediumXga;
            } else if (targetWidth >= 640 || targetHeight >= 480) {
                cameraCaptureUI.photoSettings.maxResolution = Windows.Media.Capture.CameraCaptureUIMaxPhotoResolution.smallVga;
            } else if (targetWidth >= 320 || targetHeight >= 240) {
                cameraCaptureUI.photoSettings.maxResolution = Windows.Media.Capture.CameraCaptureUIMaxPhotoResolution.verySmallQvga;
            } else {
                cameraCaptureUI.photoSettings.maxResolution = Windows.Media.Capture.CameraCaptureUIMaxPhotoResolution.highestAvailable;
            }

            cameraCaptureUI.captureFileAsync(Windows.Media.Capture.CameraCaptureUIMode.photo).then(function (picture) {
                if (picture) {
                    // save to photo album successCallback
                    var success = function (fileEntry) {
                        if (destinationType == Camera.DestinationType.FILE_URI) {
                            if (targetHeight > 0 && targetWidth > 0) {
                                resizeImage(picture);
                            } else {
                                Windows.Storage.StorageFolder.getFolderFromPathAsync(packageId.path).done(function (storageFolder) {
                                    picture.copyAsync(storageFolder, picture.name, Windows.Storage.NameCollisionOption.replaceExisting).then(function (storageFile) {
                                        successCallback(storageFile.name);
                                    }, function () {
                                        fail(FileError.INVALID_MODIFICATION_ERR);
                                    }, function () {
                                        errorCallback("Folder not access.");
                                    });
                                })
                            }
                        } else {
                            if (targetHeight > 0 && targetWidth > 0) {
                                resizeImageBase64(picture);
                            } else {
                                Windows.Storage.FileIO.readBufferAsync(picture).done(function (buffer) {
                                    var strBase64 = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(buffer);
                                    successCallback(strBase64);
                                })
                            }
                        }
                    }
                    // save to photo album errorCallback
                    var fail = function () {
                        //errorCallback("FileError, code:" + fileError.code);
                        errorCallback("Save fail.");
                    }

                    if (saveToPhotoAlbum) {
                        Windows.Storage.StorageFile.getFileFromPathAsync(picture.path).then(function (storageFile) {
                            storageFile.copyAsync(Windows.Storage.KnownFolders.picturesLibrary, picture.name, Windows.Storage.NameCollisionOption.generateUniqueName).then(function (storageFile) {
                                success(storageFile);
                            }, function () {
                                fail();
                            })
                        })
                        //var directory = new DirectoryEntry("Pictures", parentPath);
                        //new FileEntry(picture.name, picture.path).copyTo(directory, null, success, fail);
                    } else {
                        if (destinationType == Camera.DestinationType.FILE_URI) {
                            if (targetHeight > 0 && targetWidth > 0) {
                                resizeImage(picture);
                            } else {
                                Windows.Storage.StorageFolder.getFolderFromPathAsync(packageId.path).done(function (storageFolder) {
                                    picture.copyAsync(storageFolder, picture.name, Windows.Storage.NameCollisionOption.replaceExisting).then(function (storageFile) {
                                        successCallback(storageFile.name);
                                    }, function () {
                                        fail(FileError.INVALID_MODIFICATION_ERR);
                                    }, function () {
                                        errorCallback("Folder not access.");
                                    });
                                })
                            }
                        } else {
                            if (targetHeight > 0 && targetWidth > 0) {
                                resizeImageBase64(picture);
                            } else {
                                Windows.Storage.FileIO.readBufferAsync(picture).done(function (buffer) {
                                    var strBase64 = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(buffer);
                                    successCallback(strBase64);
                                })
                            }
                        }
                    }
                } else {
                    errorCallback("User didn't capture a photo.");
                }
            }, function () {
                errorCallback("Fail to capture a photo.");
            })
        }
    }
};<commit_msg>Fixed URL Bug<commit_after>/*global Windows:true, URL:true */

var cordova = require('cordova'),
    Camera = require('cordova/plugin/CameraConstants');

module.exports = {

    // args will contain :
    //  ...  it is an array, so be careful
    // 0 quality:50,
    // 1 destinationType:Camera.DestinationType.FILE_URI,
    // 2 sourceType:Camera.PictureSourceType.CAMERA,
    // 3 targetWidth:-1,
    // 4 targetHeight:-1,
    // 5 encodingType:Camera.EncodingType.JPEG,
    // 6 mediaType:Camera.MediaType.PICTURE,
    // 7 allowEdit:false,
    // 8 correctOrientation:false,
    // 9 saveToPhotoAlbum:false,
    // 10 popoverOptions:null

    "takePicture": function (successCallback, errorCallback, args) {
        var encodingType = args[5];
        var targetWidth = args[3];
        var targetHeight = args[4];
        var sourceType = args[2];
        var destinationType = args[1];
        var mediaType = args[6];
        var saveToPhotoAlbum = args[9];

        var package = Windows.ApplicationModel.Package.current;
        var packageId = package.installedLocation;

        // resize method :)
        var resizeImage = function (file) {
            var tempPhotoFileName = "";
            if (encodingType == Camera.EncodingType.PNG) {
                tempPhotoFileName = "camera_cordova_temp_return.png";
            } else {
                tempPhotoFileName = "camera_cordova_temp_return.jpg";
            }
            var imgObj = new Image();
            var success = function (fileEntry) {
                var successCB = function (filePhoto) {
                    var filePhoto = filePhoto,
                        fileType = file.contentType,
                        reader = new FileReader();
                    reader.onloadend = function () {
                        var image = new Image();
                        image.src = reader.result;
                        image.onload = function () {
                            var imageWidth = targetWidth,
                                imageHeight = targetHeight;
                            var canvas = document.createElement('canvas');

                            canvas.width = imageWidth;
                            canvas.height = imageHeight;

                            var ctx = canvas.getContext("2d");
                            ctx.drawImage(this, 0, 0, imageWidth, imageHeight);

                            // The resized file ready for upload
                            var _blob = canvas.msToBlob();
                            var _stream = _blob.msDetachStream();
                            Windows.Storage.StorageFolder.getFolderFromPathAsync(packageId.path).done(function (storageFolder) {
                                storageFolder.createFileAsync(tempPhotoFileName, Windows.Storage.CreationCollisionOption.generateUniqueName).done(function (file) {
                                    file.openAsync(Windows.Storage.FileAccessMode.readWrite).done(function (fileStream) {
                                        Windows.Storage.Streams.RandomAccessStream.copyAndCloseAsync(_stream, fileStream).done(function () {
                                            var _imageUrl = URL.createObjectURL(file);
                                            successCallback(_imageUrl);
                                        }, function () { errorCallback("Resize picture error."); })
                                    }, function () { errorCallback("Resize picture error."); })
                                }, function () { errorCallback("Resize picture error."); })
                            })

                        }
                    }

                    reader.readAsDataURL(filePhoto);

                }
                var failCB = function () {
                    errorCallback("File not found.")
                }
                fileEntry.file(successCB, failCB);
            }

            var fail = function (fileError) {
                errorCallback("FileError, code:" + fileError.code);
            }
            Windows.Storage.StorageFolder.getFolderFromPathAsync(packageId.path).done(function (storageFolder) {
                file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting).then(function (storageFile) {
                    success(new FileEntry(storageFile.name, storageFile.path));
                }, function () {
                    fail(FileError.INVALID_MODIFICATION_ERR);
                }, function () {
                    errorCallback("Folder not access.");
                });
            })

        }

        // because of asynchronous method, so let the successCallback be called in it.
        var resizeImageBase64 = function (file) {
            var imgObj = new Image();
            var success = function (fileEntry) {
                var successCB = function (filePhoto) {
                    var filePhoto = filePhoto,
                        fileType = file.contentType,
                        reader = new FileReader();
                    reader.onloadend = function () {
                        var image = new Image();
                        image.src = reader.result;

                        image.onload = function () {
                            var imageWidth = targetWidth,
                                imageHeight = targetHeight;
                            var canvas = document.createElement('canvas');

                            canvas.width = imageWidth;
                            canvas.height = imageHeight;

                            var ctx = canvas.getContext("2d");
                            ctx.drawImage(this, 0, 0, imageWidth, imageHeight);

                            // The resized file ready for upload
                            var finalFile = canvas.toDataURL(fileType);

                            // Remove the prefix such as "data:" + contentType + ";base64," , in order to meet the Cordova API.
                            var arr = finalFile.split(",");
                            var newStr = finalFile.substr(arr[0].length + 1);
                            successCallback(newStr);
                        }
                    }

                    reader.readAsDataURL(filePhoto);

                }
                var failCB = function () {
                    errorCallback("File not found.")
                }
                fileEntry.file(successCB, failCB);
            }

            var fail = function (fileError) {
                errorCallback("FileError, code:" + fileError.code);
            }
            Windows.Storage.StorageFolder.getFolderFromPathAsync(packageId.path).done(function (storageFolder) {
                file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting).then(function (storageFile) {
                    success(new FileEntry(storageFile.name, storageFile.path));
                }, function () {
                    fail(FileError.INVALID_MODIFICATION_ERR);
                }, function () {
                    errorCallback("Folder not access.");
                });
            })

        }

        if (sourceType != Camera.PictureSourceType.CAMERA) {
            var fileOpenPicker = new Windows.Storage.Pickers.FileOpenPicker();
            fileOpenPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.picturesLibrary;
            if (mediaType == Camera.MediaType.PICTURE) {
                fileOpenPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg"]);
            } else if (mediaType == Camera.MediaType.VIDEO) {
                fileOpenPicker.fileTypeFilter.replaceAll([".avi", ".flv", ".asx", ".asf", ".mov", ".mp4", ".mpg", ".rm", ".srt", ".swf", ".wmv", ".vob"]);
            } else {
                fileOpenPicker.fileTypeFilter.replaceAll(["*"]);
            }
            fileOpenPicker.pickSingleFileAsync().then(function (file) {
                if (file) {
                    if (destinationType == Camera.DestinationType.FILE_URI) {
                        if (targetHeight > 0 && targetWidth > 0) {
                            resizeImage(file);
                        } else {
                            Windows.Storage.StorageFolder.getFolderFromPathAsync(packageId.path).done(function (storageFolder) {
                                file.copyAsync(storageFolder, file.name, Windows.Storage.NameCollisionOption.replaceExisting).then(function (storageFile) {
                                    var _imageUrl = URL.createObjectURL(storageFile);
                                    successCallback(_imageUrl);
                                }, function () {
                                    fail(FileError.INVALID_MODIFICATION_ERR);
                                }, function () {
                                    errorCallback("Folder not access.");
                                });
                            })

                        }
                    }
                    else {
                        if (targetHeight > 0 && targetWidth > 0) {
                            resizeImageBase64(file);
                        } else {
                            Windows.Storage.FileIO.readBufferAsync(file).done(function (buffer) {
                                var strBase64 = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(buffer);
                                successCallback(strBase64);
                            })
                        }

                    }

                } else {
                    errorCallback("User didn't choose a file.");
                }
            }, function () {
                errorCallback("User didn't choose a file.")
            })
        }
        else {

            var cameraCaptureUI = new Windows.Media.Capture.CameraCaptureUI();
            cameraCaptureUI.photoSettings.allowCropping = true;
            var allowCrop = !!args[7];
            if (!allowCrop) {
                cameraCaptureUI.photoSettings.allowCropping = false;
            }

            if (encodingType == Camera.EncodingType.PNG) {
                cameraCaptureUI.photoSettings.format = Windows.Media.Capture.CameraCaptureUIPhotoFormat.png;
            } else {
                cameraCaptureUI.photoSettings.format = Windows.Media.Capture.CameraCaptureUIPhotoFormat.jpeg;
            }
            // decide which max pixels should be supported by targetWidth or targetHeight.
            if (targetWidth >= 1280 || targetHeight >= 960) {
                cameraCaptureUI.photoSettings.maxResolution = Windows.Media.Capture.CameraCaptureUIMaxPhotoResolution.large3M;
            } else if (targetWidth >= 1024 || targetHeight >= 768) {
                cameraCaptureUI.photoSettings.maxResolution = Windows.Media.Capture.CameraCaptureUIMaxPhotoResolution.mediumXga;
            } else if (targetWidth >= 800 || targetHeight >= 600) {
                cameraCaptureUI.photoSettings.maxResolution = Windows.Media.Capture.CameraCaptureUIMaxPhotoResolution.mediumXga;
            } else if (targetWidth >= 640 || targetHeight >= 480) {
                cameraCaptureUI.photoSettings.maxResolution = Windows.Media.Capture.CameraCaptureUIMaxPhotoResolution.smallVga;
            } else if (targetWidth >= 320 || targetHeight >= 240) {
                cameraCaptureUI.photoSettings.maxResolution = Windows.Media.Capture.CameraCaptureUIMaxPhotoResolution.verySmallQvga;
            } else {
                cameraCaptureUI.photoSettings.maxResolution = Windows.Media.Capture.CameraCaptureUIMaxPhotoResolution.highestAvailable;
            }

            cameraCaptureUI.captureFileAsync(Windows.Media.Capture.CameraCaptureUIMode.photo).then(function (picture) {
                if (picture) {
                    // save to photo album successCallback
                    var success = function (fileEntry) {
                        if (destinationType == Camera.DestinationType.FILE_URI) {
                            if (targetHeight > 0 && targetWidth > 0) {
                                resizeImage(picture);
                            } else {
                                Windows.Storage.StorageFolder.getFolderFromPathAsync(packageId.path).done(function (storageFolder) {
                                    picture.copyAsync(storageFolder, picture.name, Windows.Storage.NameCollisionOption.replaceExisting).then(function (storageFile) {
                                        var _imageUrl = URL.createObjectURL(storageFile);
                                        successCallback(_imageUrl);
                                    }, function () {
                                        fail(FileError.INVALID_MODIFICATION_ERR);
                                    }, function () {
                                        errorCallback("Folder not access.");
                                    });
                                })
                            }
                        } else {
                            if (targetHeight > 0 && targetWidth > 0) {
                                resizeImageBase64(picture);
                            } else {
                                Windows.Storage.FileIO.readBufferAsync(picture).done(function (buffer) {
                                    var strBase64 = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(buffer);
                                    successCallback(strBase64);
                                })
                            }
                        }
                    }
                    // save to photo album errorCallback
                    var fail = function () {
                        //errorCallback("FileError, code:" + fileError.code);
                        errorCallback("Save fail.");
                    }

                    if (saveToPhotoAlbum) {
                        Windows.Storage.StorageFile.getFileFromPathAsync(picture.path).then(function (storageFile) {
                            storageFile.copyAsync(Windows.Storage.KnownFolders.picturesLibrary, picture.name, Windows.Storage.NameCollisionOption.generateUniqueName).then(function (storageFile) {
                                success(storageFile);
                            }, function () {
                                fail();
                            })
                        })
                        //var directory = new DirectoryEntry("Pictures", parentPath);
                        //new FileEntry(picture.name, picture.path).copyTo(directory, null, success, fail);
                    } else {
                        if (destinationType == Camera.DestinationType.FILE_URI) {
                            if (targetHeight > 0 && targetWidth > 0) {
                                resizeImage(picture);
                            } else {
                                Windows.Storage.StorageFolder.getFolderFromPathAsync(packageId.path).done(function (storageFolder) {
                                    picture.copyAsync(storageFolder, picture.name, Windows.Storage.NameCollisionOption.replaceExisting).then(function (storageFile) {
                                        var _imageUrl = URL.createObjectURL(storageFile);
                                        successCallback(_imageUrl);
                                    }, function () {
                                        fail(FileError.INVALID_MODIFICATION_ERR);
                                    }, function () {
                                        errorCallback("Folder not access.");
                                    });
                                })
                            }
                        } else {
                            if (targetHeight > 0 && targetWidth > 0) {
                                resizeImageBase64(picture);
                            } else {
                                Windows.Storage.FileIO.readBufferAsync(picture).done(function (buffer) {
                                    var strBase64 = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(buffer);
                                    successCallback(strBase64);
                                })
                            }
                        }
                    }
                } else {
                    errorCallback("User didn't capture a photo.");
                }
            }, function () {
                errorCallback("Fail to capture a photo.");
            })
        }
    }
};<|endoftext|>


<commit_before>(function($, corkboard) {
  // TODO: allow for and handle multiple matches.
  function Board(board) {
    if(board.length) {
      this.setup(board);
    }
  }

  // Surfaced as part of the corkboard namespace.
  corkboard.Board = Board;

  // TODO: consider making selectors configurable.
  // TODO: make the masonry configuration configurable.
  // TODO: add specs (and break up).
  Board.prototype.setup = function setup(board) {
    var selectors = {
      posts   : 'ul.corkboard.posts',
      entry   : 'li.entry',
      filters : 'nav.corkboard.filters'
    };
    var posts   = $(selectors.posts, board);
    var filters = $(selectors.filters);

    posts.imagesLoaded(function() {
      this.masonry({
        isAnimated   : true,
        isFitWidth   : true,
        itemSelector : selectors.entry + ':not(.hidden)',

        columnWidth : function columnWidth(containerWidth) {
          if(containerWidth <= 320) {
            return 160;
          }
          if(containerWidth <= 480) {
            return 182;
          }
          else if(containerWidth <= 768){
            return 140;
          }
          else {
            return 172;
          }
        }
      });

      // reveal tiles in a pseudo-scattered pattern.
      this.find([selectors.entry, ':nth-child(5n+1)'].join('')).fadeIn(function callback() {
        var next = $(this).next();

        if( ! next.is(':visible')) {
          next.fadeIn(corkboard.config('fade'), callback);
        };
      });
    });

    // TODO: generalize filter placement (to other-than-FAB)
    filters.on('click', 'a', function(e) {
      var link    = $(this);
      var filters = $('li', selectors.filters);
      var filter  = link.parent().toggleClass('active');
      var posts   = $(selectors.posts);
      var entries = posts.find(selectors.entry);
      var href    = link.attr('href');
      var tag     = href.replace('#', '');

      filters.not(filter).removeClass('active');

      if(link.hasClass('all') || ( ! filter.hasClass('active'))) {
        $('a.all').parent().addClass('active');
        posts.masonry('filter', entries, '*');
      }
      else {
        posts.masonry('filter', entries, '[data-tags~="' + tag + '"]');
      }

      return false;
    });

    new corkboard.Publisher(board, this.updated);
  };

  Board.prototype.updated = function updated(list, added) {
    list.masonry('reload');
    added.fadeIn(corkboard.config('fade'));
  };
})(jQuery, jQuery.corkboard);
<commit_msg>skip filter action if href is '#' or empty<commit_after>(function($, corkboard) {
  // TODO: allow for and handle multiple matches.
  function Board(board) {
    if(board.length) {
      this.setup(board);
    }
  }

  // Surfaced as part of the corkboard namespace.
  corkboard.Board = Board;

  // TODO: consider making selectors configurable.
  // TODO: make the masonry configuration configurable.
  // TODO: add specs (and break up).
  Board.prototype.setup = function setup(board) {
    var selectors = {
      posts   : 'ul.corkboard.posts',
      entry   : 'li.entry',
      filters : 'nav.corkboard.filters'
    };
    var posts   = $(selectors.posts, board);
    var filters = $(selectors.filters);

    posts.imagesLoaded(function() {
      this.masonry({
        isAnimated   : true,
        isFitWidth   : true,
        itemSelector : selectors.entry + ':not(.hidden)',

        columnWidth : function columnWidth(containerWidth) {
          if(containerWidth <= 320) {
            return 160;
          }
          if(containerWidth <= 480) {
            return 182;
          }
          else if(containerWidth <= 768){
            return 140;
          }
          else {
            return 172;
          }
        }
      });

      // reveal tiles in a pseudo-scattered pattern.
      this.find([selectors.entry, ':nth-child(5n+1)'].join('')).fadeIn(function callback() {
        var next = $(this).next();

        if( ! next.is(':visible')) {
          next.fadeIn(corkboard.config('fade'), callback);
        };
      });
    });

    // TODO: generalize filter placement (to other-than-FAB)
    filters.on('click', 'a', function(e) {
      var link    = $(this);
      var href    = link.attr('href');
      if (!href || href=='#') return false;  // do nothing if href empty
      var filters = $('li', selectors.filters);
      var filter  = link.parent().toggleClass('active');
      var posts   = $(selectors.posts);
      var entries = posts.find(selectors.entry);
      var tag     = href.replace('#', '');

      filters.not(filter).removeClass('active');

      if(link.hasClass('all') || ( ! filter.hasClass('active'))) {
        $('a.all').parent().addClass('active');
        posts.masonry('filter', entries, '*');
      }
      else {
        posts.masonry('filter', entries, '[data-tags~="' + tag + '"]');
      }

      return false;
    });

    new corkboard.Publisher(board, this.updated);
  };

  Board.prototype.updated = function updated(list, added) {
    list.masonry('reload');
    added.fadeIn(corkboard.config('fade'));
  };
})(jQuery, jQuery.corkboard);
<|endoftext|>


<commit_before>const model = new falcor.Model({
  source: new falcor.HttpDataSource('/model.json')});

const speciesColors = {
  Normal: '#9C9C63',
  Fighting: '#AE2A24',
  Flying: '#8E6FEB',
  Poison: '#923A92',
  Ground: '#DBB54D',
  Rock: '#A48F32',
  Bug: '#97A51D',
  Ghost: '#644E88',
  Steel: '#A0A0C0',
  Fire: '#ED6D12',
  Water: '#4578ED',
  Grass: '#69C23D',
  Electric: '#F6C913',
  Ice: '#7ECECE',
  Dragon: '#5E1DF7',
  Dark: '#644E40',
  Fairy: '#E87890',
  Unknown: '',
  Shadow: '',
  Psychic: '#F73670'
};

//model.get('pokemon["name", "species"]').then(pokemon   => console.log(pokemon));

model
  .get('pokemon[0..10].["name", "species", "image"]')
  .then((result) => {
    debugger;
    const pokemonObject = result.json.pokemon;
    const pokemonArray = Object.keys(pokemonObject)
      .map(key => pokemonObject[key]);
    console.log(pokemonArray);
    renderTiles(pokemonArray)
  });

function renderTiles(tiles) {
  const contentDiv = document.querySelector('#content');
  contentDiv.innerHTML = tiles
    .map(tile => tileToHtml(tile)).join('');
}

function showBadges(species) {
  return species.map(function (type) {
    return `<span class="label" style="background-color: ${speciesColors[type]}">${type}</span>`;
  }).join(' ');
}

function tileToHtml(tile) {
  // temp
  tile.src = 'https://zemanifesto.files.wordpress.com/2014/07/bravecor1.jpg';
  tile.species = ['Water', 'Fire', 'Normal', 'Fighting'];

  return `

${tile.name}

${showBadges(tile.species)}

Some quick example text to build on the card title and make up the bulk of the card's content.

        Details »

  `;
}
<commit_msg>defogger<commit_after>const model = new falcor.Model({
  source: new falcor.HttpDataSource('/model.json')});

const speciesColors = {
  Normal: '#9C9C63',
  Fighting: '#AE2A24',
  Flying: '#8E6FEB',
  Poison: '#923A92',
  Ground: '#DBB54D',
  Rock: '#A48F32',
  Bug: '#97A51D',
  Ghost: '#644E88',
  Steel: '#A0A0C0',
  Fire: '#ED6D12',
  Water: '#4578ED',
  Grass: '#69C23D',
  Electric: '#F6C913',
  Ice: '#7ECECE',
  Dragon: '#5E1DF7',
  Dark: '#644E40',
  Fairy: '#E87890',
  Unknown: '',
  Shadow: '',
  Psychic: '#F73670'
};

//model.get('pokemon["name", "species"]').then(pokemon   => console.log(pokemon));

model
  .get('pokemon[0..10].["name", "species", "image"]')
  .then((result) => {
    const pokemonObject = result.json.pokemon;
    const pokemonArray = Object.keys(pokemonObject)
      .map(key => pokemonObject[key]);
    console.log(pokemonArray);
    renderTiles(pokemonArray)
  });

function renderTiles(tiles) {
  const contentDiv = document.querySelector('#content');
  contentDiv.innerHTML = tiles
    .map(tile => tileToHtml(tile)).join('');
}

function showBadges(species) {
  return species.map(function (type) {
    return `<span class="label" style="background-color: ${speciesColors[type]}">${type}</span>`;
  }).join(' ');
}

function tileToHtml(tile) {
  // temp
  tile.src = 'https://zemanifesto.files.wordpress.com/2014/07/bravecor1.jpg';
  tile.species = ['Water', 'Fire', 'Normal', 'Fighting'];

  return `

${tile.name}

${showBadges(tile.species)}

Some quick example text to build on the card title and make up the bulk of the card's content.

        Details »

  `;
}
<|endoftext|>