<commit_before>var theList;

$(document).ready(function(){
	setPageSwitcher();
	setAllBars();
    checkCurrentUser();
	setUpMaxWidth();
	setActionOnFooterClick();
	setActionOnHeaderClick();
});

function checkCurrentUser(){
	if(getCurrent() == undefined) {
		view.push("login");
	}
}

function setUpMaxWidth(){
	if(!isSteroids()) {
		$("*").css("max-width", "340px");
	}
}

function setAllBars(){
	$("#linklistleft").empty();
	$("#linklistright").empty();

	leftbarCreateLinks();
	setActionOnSwipeLeft();

	rightbarCreateLinks();
	setActionOnSwipeRight();

	bar.init();
}

function setActionOnFooterClick(){
	$("#index footer").click(function() {
		document.removeEventListener("menuButton");
		document.removeEventListener("backButton");
		$.mobile.changePage( "#message", {transition: "none", changeHash: false , showLoadMsg: true, allowSamePageTransition: true});
	});
}

function setActionOnHeaderClick(){
	$("#message header a").click(function() {
		resetMessageFieldsEPage();
		document.addEventListener("menuButton", onMenuButton, false);
		document.addEventListener("backButton", onBackButton, false);
		$.mobile.changePage( "#index", {transition: "none", changeHash: false , showLoadMsg: true, allowSamePageTransition: true});
	});
}

function setActionOnSwipeRight(){
	jQuery( window ).on( "swiperight", function() {
		if(getCurrent()['name'] != 'login') {
			if($("#rightpanel").hasClass("ui-panel-closed")) {
				$( "#leftpanel" ).panel( "open" );
			}
		}
	});
}

function setActionOnSwipeLeft(){
	jQuery( window ).on( "swipeleft", function() {
		if(getCurrent()['name'] != 'login') {
			if($("#leftpanel").hasClass("ui-panel-closed")) {
				$( "#rightpanel" ).panel( "open" );
			}
		}
	});
}

function setPageSwitcher(){
		$("#main").on('pageswitch', function(){
		$("#main *").off();
		switch(getCurrent()['name']) {
			case "login":
				initlogin();
				break;
			case "frontpage":
				initfrontpage();
				break;
			case "BPage":
				initBPage();
				break;
			case "EPage":
				initEPage();
				break;
			case "IPage":
				initIPage();
				break;
			case "RPage":
				initRPage();
				break;
			case "search":
				initsearch();
				break;
			default:
		}
		appInit();
	});
}

function inMonths(diff){
	var one_month = 1000*60*60*24*30;
	var months = Math.floor(diff/one_month);
    if (months>=2){
    	return '' + months + ' ago';
    } else if (months>=1){
    	return 'one month ago';
    }
    return ''
}

function inDays(diff){
	var one_day = 1000*60*60*24;
	var days = Math.floor(diff/one_day);
    if (days>=2){
         return '' + days + ' days';
    } else if (days>=1) {
        return "1 day";
    }
    return '';
}

function inWeeks(diff){
	var one_week = 1000*60*60*24*7;
	var weeks = Math.floor(diff/one_week);
    if (weeks>=2){
         return '' + weeks + ' weeks';
    }
    return '';
}

function inHours(diff){
	var one_hour = 1000*60*60;
    var hours = Math.floor(diff/one_hour);
    var timeRemain = diff - (one_hour*hours);
    if (hours>=2) return '' + hours + " hours";
    if (hours>=1) return "1 hour";

    return '';
}

function inMinutes(diff){
	var one_minute = 1000*60;
	var minutes = Math.floor(diff/one_minute);
	if (minutes>=2) return '' + minutes + ' minutes';
    return '1 minunte';
}

function getTimeDiffMili(sendedTime){
	var date = sendedTime.replace(/-/g, '/');
    var d = new Date();
    var diff = Math.abs(d - new Date(date));
	var n = d.getTimezoneOffset() * 1000 * 60;

	return (diff + n);
}

function getTimeDiff(sendedTime){
	var diff = getTimeDiffMili(sendedTime);

	var months = inMonths(diff);
	if (months !='') return months;

	var weeks = inWeeks(diff);
	if (weeks !='') return weeks;

	var days = inDays(diff);
	if (days !='') return days;

	var hours = inHours(diff);
	if (hours != '') return hours;

	return inMinutes(diff);
}

function onBackButton(){
	view.pop();
}

function onMenuButton(){
	if($("#settingsList").css("display")=="table")
		bar.hideSettingsList();
	else{
		bar.showSettingsList();
	}
}

function appInit(){
	if(isToken()) {

		var	dlid = getParameter('dlid');

		if (dlid==undefined){
			dlid = getDL_id();
		}

		getInfo(dlid,function(info){
			sidebarsSetInfo(info);
			updateUrls(dlid);
			setEntityInformation(info);

		});

		setActive(getParameter('type'));

		var streamType = getStreamType();
		showRightForm(streamType);
		attachEvents();

		document.addEventListener("menuButton", onMenuButton, false);
		document.addEventListener("backButton", onBackButton, false);

	}
}

var scroll_object;

function scrollerInit() {
    scroll_object = $("#scroller");
    scroll_object.iscrollview({'hScroll' : false, 'hScrollbar' : false, 'vScrollbar' : false});
    $(document).delegate("div.iscroll-wrapper", "iscroll_onpulldown" , function() {
    	if(getCurrent().name == "frontpage") {
	        getOwnStream("message,cal,note", 0, function(stream) {
	            if(stream != null && stream != "") {
	                theList.html(stream.join('') );
	                scroll_object.iscrollview("refresh");
	                addLiListener();
	                offset=0;
	            }
	        });
	    }
	    if(getCurrent().name == "EPage") {
	        getStreamUrl(0, function(stream) {
	            if(stream != null && stream != "") {
	                theList.html(stream.join('') );
	                scroll_object.iscrollview("refresh");
	                addLiListener();
	                offset=0;
	            }
	        });

	    }
    });
    $(document).delegate("div.iscroll-wrapper", "iscroll_onpullup" , function() {
        appendStream();
    });
}

function setEntityInformation(dlid){
		$("#nameAndTypeBar img").attr("src",dlid.img);
}

function whenToLoadMore() {
	if($(theList).children().length < 15) {
        return false;
    }
    return scroll_object.iscrollview("y") - scroll_object.iscrollview("maxScrollY") < 100;
}

function getUserData(dlid,done, error){
	var info = getUserDataCache(dlid);
	if(!info) {
		var opts={'dl_id':dlid,'auth':getToken(),'uid':getDL_id(),'table_name':"dl_user"};
    	var url="dliddata";
    	rest(opts,url,
        function(data) {
            result = data;
            success(data);
            setUserDataCache(data);
            done(data);
        },
        error);
	} else {
		done(info);
	}
}

var offset=0;
var intheend = false;
var onChange = false;

function appendStream(){

    if((!intheend) && (!onChange)) {

    	offset += 15;
        $("#thelist + div + img").show();
        onChange = true;
        getStreamUrl(offset,function(stream){
            if((stream.length < 1) || (!stream)) {
                intheend = true;
                $("#thelist + div + img").hide();
             } else {
                theList.append( stream.join('') );
                scroll_object.iscrollview("refresh");
                addLiListener();
            }
            onChange = false;
        });
    }
}

function addLiListener(){
	$(".listEL").off();
    $(".listEL").click(function(){
        var id = $(this).attr('id');
        var uid = $(this).attr('uid');
        var dlid = getParameter('dlid');
        var listElement= $(this);
        view.push("IPage", {'dlid':dlid, 'iPageID': id, 'uid': uid});
    });

    $(".listEL").mousedown(function() {
    	$(this).addClass("active");
    });

    $(".listEL").mouseup(function() {
    	$(this).removeClass("active");
    });
    $(".listEL").mouseout(function() {
    	$(this).removeClass("active");
    });
}

function getMessageInfo(id){
	var itemR= "";
	$.each(getSavedStream(),function(i,item){
		if(item.id==id){
			itemR=item;
		}
	});
	return itemR;
}

function getInfo(dl_id,done,update){
	var info = getInfoCache(dl_id);
	if(!info || update) {
		var opts={'dl_id':dl_id,'auth':getToken(),'uid':getDL_id()};
	    var url="dlid"
	    rest(opts,url,
	        function(data) {
	            result = data;
	            success(data);
	            setInfoCache(data);
	            done(data);
	        },
	        function(data) {
	            result = data;
	            error(data);
	            done(data);
	        });
	} else {
		success(info);
		done(info);
	}
}

function setupPage(settings) {
	if (settings === undefined)
		settings = {};

	if (settings.bar)
		bar.show();
	else
		bar.hide();

	if (settings.barBackButton){
		bar.showBackButton();
	}else{
		bar.hideBackButton();
	}
	if(settings.searchPage){
		bar.showSearch();
	}else{
		bar.hideSearch();
	}
	if(settings.footer) {
		footer.show();
	} else {
		footer.hide();
	}
}

function getHistory(done){
	var opts={'dl_id':getDL_id(),'auth':getToken(),'uid':getDL_id()};
	var url="gethistory";
	rest(opts,url,
		function(data) {
			result = data;
			success(data);
			done(data);
		},
		function(data) {
			result = data;
			error(data);
			done(data);
		});
}

function search(searchWord,done){
	var opts={'q':searchWord,'auth':getToken(),'uid':getDL_id()};
	var url="search";
	return rest(opts,url,
		function(data) {
			result = data;
			success(data);
			done(data);
		},
		function(data) {
			result = data;
			error(data);
			done(data);
		});
}

function getActivityStream(opts,done) {
	var url = "stream";
	rest(opts,url,function(data) {
			result = data;
			success(data);
			done(data);
		},
		function(data) {
			error(data);
			done(data);
		});
}

function setActivityCompleted(completed, done) {
    if (completed === false){
    	var opts = {'uid':getDL_id(),'auth':getToken(),'dl_id':getParameter("uid"),'activity_id':getParameter("iPageID"),'remove':"1"};
    	remove = "&remove=1";
    }else {
    	var opts = {'uid':getDL_id(),'auth':getToken(),'dl_id':getParameter("uid"),'activity_id':getParameter("iPageID")};
    }

    var url = "setactivitycompleted";

    rest(opts,
        url,
        function(data) {
			success(data);
			if (done != null)
				done(data);
		},
		function(data) {
			error(data);
			if (done != null)
				done(data);
		}
	);
}

function createRelation(dl_id_from, dl_id_to, role, done) {
	if (role == null)
		role = "";

	var url = "addrelation";

	var opts = {
		'uid': getDL_id(),
		'auth': getToken(),
		'dl_id_from': dl_id_from,
		'dl_id_to': dl_id_to,
		'role': role
	};

	rest(opts,
		url,
		function(data) {
			success(data);
			if (done != null)
				done(data);
		},
		function(data) {
			error(data);
			if (done != null)
				done(data);
		}
	);
}

function getUserArray(dlids,done) {
	var opts = {'uid': getDL_id(), 'auth':getToken(), 'dl_ids':dlids};
	var arr = dlids.split(",");
	arr = $.unique(arr);
	var cached  = new Array();

	arr = $.grep(arr, function(item, i) {
		var info = getInfoCache(item);
		if(info == undefined) {
			info == false;
		}

		if(info !== false) {
			cached.push(info);
		}
		return (info == false);
	});

	if(arr.length !== 0) {
	   opts["dl_ids"] = arr.join();
	   var url = "dlid";
	      rest(opts, url, function(data) {
	          result=data;
	          success(data);
	          $.each(data, function(i, item) {
	            setInfoCache(item);
	         });
	          data = data.concat(cached);
	          done(data);
	      },
	     function(data) {
	          result=data;
	          error(data);
	          done(data);
	      });
	} else {
		done(cached);
	}
}

function isToken() {
	return (getToken() != null) && (getToken() != undefined);
}

function isSteroids() {
	if (navigator.userAgent.indexOf("AppGyverSteroids") !== -1)
		return true;
	else
		return false;
}
<commit_msg>fixin fixi<commit_after>var theList;

$(document).ready(function(){
	setPageSwitcher();
	setAllBars();
    checkCurrentUser();
	setUpMaxWidth();
	setActionOnFooterClick();
	setActionOnHeaderClick();
});

function checkCurrentUser(){
	if(getCurrent() == undefined) {
		view.push("login");
	}
}

function setUpMaxWidth(){
	if(!isSteroids()) {
		$("*").css("max-width", "340px");
	}
}

function setAllBars(){
	$("#linklistleft").empty();
	$("#linklistright").empty();

	leftbarCreateLinks();
	setActionOnSwipeLeft();

	rightbarCreateLinks();
	setActionOnSwipeRight();

	bar.init();
}

function setActionOnFooterClick(){
	$("#index footer").click(function() {
		document.removeEventListener("menuButton", onMenuButton, false);
		document.removeEventListener("backButton", onBackButton, false);
		document.addEventListener("backButton", changeBackToIndex, false);
		$.mobile.changePage( "#message", {transition: "none", changeHash: false , showLoadMsg: true, allowSamePageTransition: true});
	});
}

function changeBackToIndex(){
	resetMessageFieldsEPage();
	$.mobile.changePage( "#index", {transition: "none", changeHash: false , showLoadMsg: true, allowSamePageTransition: true});
}

function setActionOnHeaderClick(){
	$("#message header a").click(function() {
		resetMessageFieldsEPage();
		document.removeEventListener("backButton", onBackButton, false);
		document.addEventListener("menuButton", onMenuButton, false);
		document.addEventListener("backButton", onBackButton, false);
		$.mobile.changePage( "#index", {transition: "none", changeHash: false , showLoadMsg: true, allowSamePageTransition: true});
	});
}

function setActionOnSwipeRight(){
	jQuery( window ).on( "swiperight", function() {
		if(getCurrent()['name'] != 'login') {
			if($("#rightpanel").hasClass("ui-panel-closed")) {
				$( "#leftpanel" ).panel( "open" );
			}
		}
	});
}

function setActionOnSwipeLeft(){
	jQuery( window ).on( "swipeleft", function() {
		if(getCurrent()['name'] != 'login') {
			if($("#leftpanel").hasClass("ui-panel-closed")) {
				$( "#rightpanel" ).panel( "open" );
			}
		}
	});
}

function setPageSwitcher(){
		$("#main").on('pageswitch', function(){
		$("#main *").off();
		switch(getCurrent()['name']) {
			case "login":
				initlogin();
				break;
			case "frontpage":
				initfrontpage();
				break;
			case "BPage":
				initBPage();
				break;
			case "EPage":
				initEPage();
				break;
			case "IPage":
				initIPage();
				break;
			case "RPage":
				initRPage();
				break;
			case "search":
				initsearch();
				break;
			default:
		}
		appInit();
	});
}

function inMonths(diff){
	var one_month = 1000*60*60*24*30;
	var months = Math.floor(diff/one_month);
    if (months>=2){
    	return '' + months + ' ago';
    } else if (months>=1){
    	return 'one month ago';
    }
    return ''
}

function inDays(diff){
	var one_day = 1000*60*60*24;
	var days = Math.floor(diff/one_day);
    if (days>=2){
         return '' + days + ' days';
    } else if (days>=1) {
        return "1 day";
    }
    return '';
}

function inWeeks(diff){
	var one_week = 1000*60*60*24*7;
	var weeks = Math.floor(diff/one_week);
    if (weeks>=2){
         return '' + weeks + ' weeks';
    }
    return '';
}

function inHours(diff){
	var one_hour = 1000*60*60;
    var hours = Math.floor(diff/one_hour);
    var timeRemain = diff - (one_hour*hours);
    if (hours>=2) return '' + hours + " hours";
    if (hours>=1) return "1 hour";

    return '';
}

function inMinutes(diff){
	var one_minute = 1000*60;
	var minutes = Math.floor(diff/one_minute);
	if (minutes>=2) return '' + minutes + ' minutes';
    return '1 minunte';
}

function getTimeDiffMili(sendedTime){
	var date = sendedTime.replace(/-/g, '/');
    var d = new Date();
    var diff = Math.abs(d - new Date(date));
	var n = d.getTimezoneOffset() * 1000 * 60;

	return (diff + n);
}

function getTimeDiff(sendedTime){
	var diff = getTimeDiffMili(sendedTime);

	var months = inMonths(diff);
	if (months !='') return months;

	var weeks = inWeeks(diff);
	if (weeks !='') return weeks;

	var days = inDays(diff);
	if (days !='') return days;

	var hours = inHours(diff);
	if (hours != '') return hours;

	return inMinutes(diff);
}

function onBackButton(){
	view.pop();
}

function onMenuButton(){
	if($("#settingsList").css("display")=="table")
		bar.hideSettingsList();
	else{
		bar.showSettingsList();
	}
}

function appInit(){
	if(isToken()) {

		var	dlid = getParameter('dlid');

		if (dlid==undefined){
			dlid = getDL_id();
		}

		getInfo(dlid,function(info){
			sidebarsSetInfo(info);
			updateUrls(dlid);
			setEntityInformation(info);

		});

		setActive(getParameter('type'));

		var streamType = getStreamType();
		showRightForm(streamType);
		attachEvents();

		document.removeEventListener("menuButton", onMenuButton, false);
		document.removeEventListener("backButton", onBackButton, false);
		document.addEventListener("menuButton", onMenuButton, false);
		document.addEventListener("backButton", onBackButton, false);

	}
}

var scroll_object;

function scrollerInit() {
    scroll_object = $("#scroller");
    scroll_object.iscrollview({'hScroll' : false, 'hScrollbar' : false, 'vScrollbar' : false});
    $(document).delegate("div.iscroll-wrapper", "iscroll_onpulldown" , function() {
    	if(getCurrent().name == "frontpage") {
	        getOwnStream("message,cal,note", 0, function(stream) {
	            if(stream != null && stream != "") {
	                theList.html(stream.join('') );
	                scroll_object.iscrollview("refresh");
	                addLiListener();
	                offset=0;
	            }
	        });
	    }
	    if(getCurrent().name == "EPage") {
	        getStreamUrl(0, function(stream) {
	            if(stream != null && stream != "") {
	                theList.html(stream.join('') );
	                scroll_object.iscrollview("refresh");
	                addLiListener();
	                offset=0;
	            }
	        });

	    }
    });
    $(document).delegate("div.iscroll-wrapper", "iscroll_onpullup" , function() {
        appendStream();
    });
}

function setEntityInformation(dlid){
		$("#nameAndTypeBar img").attr("src",dlid.img);
}

function whenToLoadMore() {
	if($(theList).children().length < 15) {
        return false;
    }
    return scroll_object.iscrollview("y") - scroll_object.iscrollview("maxScrollY") < 100;
}

function getUserData(dlid,done, error){
	var info = getUserDataCache(dlid);
	if(!info) {
		var opts={'dl_id':dlid,'auth':getToken(),'uid':getDL_id(),'table_name':"dl_user"};
    	var url="dliddata";
    	rest(opts,url,
        function(data) {
            result = data;
            success(data);
            setUserDataCache(data);
            done(data);
        },
        error);
	} else {
		done(info);
	}
}

var offset=0;
var intheend = false;
var onChange = false;

function appendStream(){

    if((!intheend) && (!onChange)) {

    	offset += 15;
        $("#thelist + div + img").show();
        onChange = true;
        getStreamUrl(offset,function(stream){
            if((stream.length < 1) || (!stream)) {
                intheend = true;
                $("#thelist + div + img").hide();
             } else {
                theList.append( stream.join('') );
                scroll_object.iscrollview("refresh");
                addLiListener();
            }
            onChange = false;
        });
    }
}

function addLiListener(){
	$(".listEL").off();
    $(".listEL").click(function(){
        var id = $(this).attr('id');
        var uid = $(this).attr('uid');
        var dlid = getParameter('dlid');
        var listElement= $(this);
        view.push("IPage", {'dlid':dlid, 'iPageID': id, 'uid': uid});
    });

    $(".listEL").mousedown(function() {
    	$(this).addClass("active");
    });

    $(".listEL").mouseup(function() {
    	$(this).removeClass("active");
    });
    $(".listEL").mouseout(function() {
    	$(this).removeClass("active");
    });
}

function getMessageInfo(id){
	var itemR= "";
	$.each(getSavedStream(),function(i,item){
		if(item.id==id){
			itemR=item;
		}
	});
	return itemR;
}

function getInfo(dl_id,done,update){
	var info = getInfoCache(dl_id);
	if(!info || update) {
		var opts={'dl_id':dl_id,'auth':getToken(),'uid':getDL_id()};
	    var url="dlid"
	    rest(opts,url,
	        function(data) {
	            result = data;
	            success(data);
	            setInfoCache(data);
	            done(data);
	        },
	        function(data) {
	            result = data;
	            error(data);
	            done(data);
	        });
	} else {
		success(info);
		done(info);
	}
}

function setupPage(settings) {
	if (settings === undefined)
		settings = {};

	if (settings.bar)
		bar.show();
	else
		bar.hide();

	if (settings.barBackButton){
		bar.showBackButton();
	}else{
		bar.hideBackButton();
	}
	if(settings.searchPage){
		bar.showSearch();
	}else{
		bar.hideSearch();
	}
	if(settings.footer) {
		footer.show();
	} else {
		footer.hide();
	}
}

function getHistory(done){
	var opts={'dl_id':getDL_id(),'auth':getToken(),'uid':getDL_id()};
	var url="gethistory";
	rest(opts,url,
		function(data) {
			result = data;
			success(data);
			done(data);
		},
		function(data) {
			result = data;
			error(data);
			done(data);
		});
}

function search(searchWord,done){
	var opts={'q':searchWord,'auth':getToken(),'uid':getDL_id()};
	var url="search";
	return rest(opts,url,
		function(data) {
			result = data;
			success(data);
			done(data);
		},
		function(data) {
			result = data;
			error(data);
			done(data);
		});
}

function getActivityStream(opts,done) {
	var url = "stream";
	rest(opts,url,function(data) {
			result = data;
			success(data);
			done(data);
		},
		function(data) {
			error(data);
			done(data);
		});
}

function setActivityCompleted(completed, done) {
    if (completed === false){
    	var opts = {'uid':getDL_id(),'auth':getToken(),'dl_id':getParameter("uid"),'activity_id':getParameter("iPageID"),'remove':"1"};
    	remove = "&remove=1";
    }else {
    	var opts = {'uid':getDL_id(),'auth':getToken(),'dl_id':getParameter("uid"),'activity_id':getParameter("iPageID")};
    }

    var url = "setactivitycompleted";

    rest(opts,
        url,
        function(data) {
			success(data);
			if (done != null)
				done(data);
		},
		function(data) {
			error(data);
			if (done != null)
				done(data);
		}
	);
}

function createRelation(dl_id_from, dl_id_to, role, done) {
	if (role == null)
		role = "";

	var url = "addrelation";

	var opts = {
		'uid': getDL_id(),
		'auth': getToken(),
		'dl_id_from': dl_id_from,
		'dl_id_to': dl_id_to,
		'role': role
	};

	rest(opts,
		url,
		function(data) {
			success(data);
			if (done != null)
				done(data);
		},
		function(data) {
			error(data);
			if (done != null)
				done(data);
		}
	);
}

function getUserArray(dlids,done) {
	var opts = {'uid': getDL_id(), 'auth':getToken(), 'dl_ids':dlids};
	var arr = dlids.split(",");
	arr = $.unique(arr);
	var cached  = new Array();

	arr = $.grep(arr, function(item, i) {
		var info = getInfoCache(item);
		if(info == undefined) {
			info == false;
		}

		if(info !== false) {
			cached.push(info);
		}
		return (info == false);
	});

	if(arr.length !== 0) {
	   opts["dl_ids"] = arr.join();
	   var url = "dlid";
	      rest(opts, url, function(data) {
	          result=data;
	          success(data);
	          $.each(data, function(i, item) {
	            setInfoCache(item);
	         });
	          data = data.concat(cached);
	          done(data);
	      },
	     function(data) {
	          result=data;
	          error(data);
	          done(data);
	      });
	} else {
		done(cached);
	}
}

function isToken() {
	return (getToken() != null) && (getToken() != undefined);
}

function isSteroids() {
	if (navigator.userAgent.indexOf("AppGyverSteroids") !== -1)
		return true;
	else
		return false;
}
<|endoftext|>


<commit_before>'use strict';

import config from './variables.es6.js';

let functions = {
  // Convert to percentage
  percentage(value = 0) {
    value = +value;
    return `${value < 1 ? (value * 100).toFixed(8) : value}%`;
  },

  // Simple clearfix
  clearfix() {
    return {
      '*zoom': 1,
      '&:before, &:after': {
        'content': '" "',
        'display': 'table'
      },
      '&:after': {
        'clear': 'both'
      }
    };
  }
};

functions = Object.assign(functions, {
  // Sets layout direction and layout opposite direction to `@direction`
  // and `@opposite-direction` accordingly.
  getDirection(layout = 'LTR') {
    return {
      direction: layout === 'LTR' ? 'right' : 'left',
      oppositeDirection: layout === 'LTR' ? 'left' : 'right'
    };
  },

  // Sets neat grid column's width to `@column-width`.
  flexWidth(columns, containerColumns, column = config.neatColumnWidth, gutter = config.neatGutterWidth) {
    columns = +columns;
    containerColumns = +containerColumns;
    column = +column.replace('em', '');
    gutter = +gutter.replace('em', '');

    var tmpWidth = columns * column + (columns - 1) * gutter;
    var tmpContainerWidth = containerColumns * column + (containerColumns - 1) * gutter;

    return tmpWidth / tmpContainerWidth; // columnWidth
  },

  // Sets neat grid column's gutter (the white space between two columns) to `@column-gutter`.
  flexGutter(containerColumns = config.neatGridColumns, column = config.neatColumnWidth, gutter = config.neatGutterWidth) {
    containerColumns = +containerColumns;
    column = +column.replace('em', '');
    gutter = +gutter.replace('em', '');

    var tmpContainerWidth = containerColumns * column + (containerColumns - 1) * gutter;

    return gutter / tmpContainerWidth; // columnGutter
  }
});

export default functions;
<commit_msg>Fixes #2 - function now checks for =< 1 instead of <1<commit_after>'use strict';

import config from './variables.es6.js';

let functions = {
  // Convert to percentage
  percentage(value = 0) {
    value = +value;
    return `${value <= 1 ? (value * 100).toFixed(8) : value}%`;
  },

  // Simple clearfix
  clearfix() {
    return {
      '*zoom': 1,
      '&:before, &:after': {
        'content': '" "',
        'display': 'table'
      },
      '&:after': {
        'clear': 'both'
      }
    };
  }
};

functions = Object.assign(functions, {
  // Sets layout direction and layout opposite direction to `@direction`
  // and `@opposite-direction` accordingly.
  getDirection(layout = 'LTR') {
    return {
      direction: layout === 'LTR' ? 'right' : 'left',
      oppositeDirection: layout === 'LTR' ? 'left' : 'right'
    };
  },

  // Sets neat grid column's width to `@column-width`.
  flexWidth(columns, containerColumns, column = config.neatColumnWidth, gutter = config.neatGutterWidth) {
    columns = +columns;
    containerColumns = +containerColumns;
    column = +column.replace('em', '');
    gutter = +gutter.replace('em', '');

    var tmpWidth = columns * column + (columns - 1) * gutter;
    var tmpContainerWidth = containerColumns * column + (containerColumns - 1) * gutter;

    return tmpWidth / tmpContainerWidth; // columnWidth
  },

  // Sets neat grid column's gutter (the white space between two columns) to `@column-gutter`.
  flexGutter(containerColumns = config.neatGridColumns, column = config.neatColumnWidth, gutter = config.neatGutterWidth) {
    containerColumns = +containerColumns;
    column = +column.replace('em', '');
    gutter = +gutter.replace('em', '');

    var tmpContainerWidth = containerColumns * column + (containerColumns - 1) * gutter;

    return gutter / tmpContainerWidth; // columnGutter
  }
});

export default functions;
<|endoftext|>


<commit_before>const os = require('os')
const path = require('path')
const fs = require('fs-extra')
const resolveFrom = require('resolve-from')
const cac = require('cac')
const chalk = require('chalk')
const merge = require('lodash.merge')
const logger = require('@poi/logger')
const Hooks = require('./Hooks')
const WebpackUtils = require('./WebpackUtils')
const createConfigLoader = require('./utils/createConfigLoader')
const loadEnvs = require('./utils/loadEnvs')
const parseArgs = require('./utils/parseArgs')
const PoiError = require('./utils/PoiError')
const spinner = require('./utils/spinner')
const validateConfig = require('./utils/validateConfig')
const { normalizePlugins, mergePlugins } = require('./utils/plugins')

module.exports = class PoiCore {
  constructor(
    rawArgs = process.argv,
    {
      defaultConfigFiles = [
        'poi.config.js',
        'poi.config.ts',
        'package.json',
        '.poirc',
        '.poirc.json',
        '.poirc.js'
      ],
      extendConfigLoader,
      config: externalConfig
    } = {}
  ) {
    this.rawArgs = rawArgs
    this.logger = logger
    this.spinner = spinner
    this.PoiError = PoiError
    // For plugins, it's only used in plugin.cli export
    this.args = parseArgs(rawArgs)
    this.hooks = new Hooks()
    this.testRunners = new Map()

    if (this.args.has('debug')) {
      logger.setOptions({ debug: true })
    }

    this.mode = this.args.get('mode')
    if (!this.mode) {
      this.mode = 'development'
    }

    if (this.args.has('prod') || this.args.has('production')) {
      this.mode = 'production'
    }

    if (this.args.has('test')) {
      this.mode = 'test'
    }

    if (this.args.args[0] && /^test(:|$)/.test(this.args.args[0])) {
      this.mode = 'test'
    }

    logger.debug(`Running in ${this.mode} mode`)

    this.cwd = this.args.get('cwd')
    if (!this.cwd) {
      this.cwd = process.cwd()
    }

    // Load modules from --require flag
    this.loadRequiredModules()

    this.configLoader = createConfigLoader(this.cwd)

    // For other tools that use Poi under the hood
    if (extendConfigLoader) {
      extendConfigLoader(this.configLoader)
    }

    // Load .env files
    loadEnvs(this.mode, this.resolveCwd('.env'))

    if (!process.env.NODE_ENV) {
      process.env.NODE_ENV = this.mode
    }

    this.webpackUtils = new WebpackUtils(this)

    // Try to load config file
    const configFlag =
      this.args.get('config') === undefined
        ? this.args.get('c')
        : this.args.get('config')
    if (externalConfig || configFlag === false) {
      logger.debug('Poi config file was disabled')
      this.config = externalConfig || {}
    } else {
      const configFiles =
        typeof configFlag === 'string' ? [configFlag] : defaultConfigFiles
      const { path: configPath, data: configFn } = this.configLoader.load({
        files: configFiles,
        packageKey: 'poi'
      })
      if (configPath) {
        logger.debug(`Using Poi config file:`, configPath)
      } else {
        logger.debug(`Not using any Poi config file`)
      }
      this.configPath = configPath
      this.config =
        typeof configFn === 'function' ? configFn(this.args.options) : configFn
      this.config = this.config || {}
    }

    this.pkg = this.configLoader.load({
      files: ['package.json']
    })
    this.pkg.data = this.pkg.data || {}

    // Initialize plugins
    this.initPlugins()
    // Init CLI instance, call plugin.cli, parse CLI args
    this.initCLI()
    // Merge cli config with config file
    this.mergeConfig()
    // Call plugin.apply
    this.applyPlugins()
    this.hooks.invoke('createConfig', this.config)
  }

  get isProd() {
    return this.mode === 'production'
  }

  initCLI() {
    const cli = (this.cli = cac())
    this.command = cli
      .command('[...entries]', 'Entry files to start bundling', {
        ignoreOptionDefaultValue: true
      })
      .usage('[...entries] [options]')
      .action(async () => {
        logger.debug(`Using default handler`)
        const chain = this.createWebpackChain()
        const compiler = this.createWebpackCompiler(chain.toConfig())
        await this.runCompiler(compiler)
      })

    this.extendCLI()

    // Global options
    cli
      .option('--mode <mode>', 'Set mode', 'development')
      .option('--prod, --production', 'Alias for --mode production')
      .option('--test', 'Alias for --mode test')
      .option('--no-config', 'Disable config file')
      .option('-c, --config <path>', 'Set the path to config file')
      .option('-r, --require <module>', 'Require a module before bootstrapping')
      .option(
        '--plugin, --plugins <plugin>',
        'Add a plugin (can be used for multiple times)'
      )
      .option('--debug', 'Show debug logs')
      .option('--inspect-webpack', 'Inspect webpack config in your editor')
      .version(require('../package').version)
      .help(sections => {
        for (const section of sections) {
          if (section.title && section.title.includes('For more info')) {
            const body = section.body.split('\n')
            body.shift()
            body.unshift(
              `  $ ${cli.name} --help`,
              `  $ ${cli.name} --serve --help`,
              `  $ ${cli.name} --prod --help`
            )
            section.body = body.join('\n')
          }
        }
      })

    this.cli.parse(this.rawArgs, { run: false })

    logger.debug('Command args', this.cli.args)
    logger.debug('Command options', this.cli.options)
  }

  loadRequiredModules() {
    const requiredModules = this.args.get('require') || this.args.get('r')
    if (requiredModules) {
      ;[].concat(requiredModules).forEach(name => {
        const m = this.localRequire(name)
        if (!m) {
          throw new PoiError({
            message: `Cannot find module "${name}" in current directory!`
          })
        }
      })
    }
  }

  hasDependency(name) {
    return [
      ...Object.keys(this.pkg.data.dependencies || {}),
      ...Object.keys(this.pkg.data.devDependencies || {})
    ].includes(name)
  }

  /**
   * @private
   * @returns {void}
   */
  initPlugins() {
    const cwd = this.configPath
      ? path.dirname(this.configPath)
      : this.resolveCwd()
    const cliPlugins = normalizePlugins(
      this.args.get('plugin') || this.args.get('plugins'),
      cwd
    )
    const configPlugins = normalizePlugins(this.config.plugins, cwd)

    this.plugins = [
      { resolve: require.resolve('./plugins/command-options') },
      { resolve: require.resolve('./plugins/config-babel') },
      { resolve: require.resolve('./plugins/config-vue') },
      { resolve: require.resolve('./plugins/config-css') },
      { resolve: require.resolve('./plugins/config-font') },
      { resolve: require.resolve('./plugins/config-image') },
      { resolve: require.resolve('./plugins/config-eval') },
      { resolve: require.resolve('./plugins/config-html') },
      { resolve: require.resolve('./plugins/config-electron') },
      { resolve: require.resolve('./plugins/config-misc-loaders') },
      { resolve: require.resolve('./plugins/config-reason') },
      { resolve: require.resolve('./plugins/config-yarn-pnp') },
      { resolve: require.resolve('./plugins/config-jsx-import') },
      { resolve: require.resolve('./plugins/watch') },
      { resolve: require.resolve('./plugins/serve') },
      { resolve: require.resolve('./plugins/eject-html') },
      { resolve: require.resolve('@poi/plugin-html-entry') }
    ]
      .concat(mergePlugins(configPlugins, cliPlugins))
      .map(plugin => {
        if (typeof plugin.resolve === 'string') {
          plugin._resolve = plugin.resolve
          plugin.resolve = require(plugin.resolve)
        }
        return plugin
      })
  }

  extendCLI() {
    for (const plugin of this.plugins) {
      if (plugin.resolve.cli) {
        plugin.resolve.cli(this, plugin.options)
      }
    }
  }

  /**
   * @private
   * @returns {void}
   */
  applyPlugins() {
    let plugins = this.plugins.filter(plugin => {
      return !plugin.resolve.when || plugin.resolve.when(this)
    })

    // Run plugin's `filterPlugins` method
    for (const plugin of plugins) {
      if (plugin.resolve.filterPlugins) {
        plugins = plugin.resolve.filterPlugins(this.plugins, plugin.options)
      }
    }

    // Run plugin's `apply` method
    for (const plugin of plugins) {
      if (plugin.resolve.apply) {
        logger.debug(`Apply plugin: \`${chalk.bold(plugin.resolve.name)}\``)
        if (plugin._resolve) {
          logger.debug(`location: ${plugin._resolve}`)
        }
        plugin.resolve.apply(this, plugin.options)
      }
    }
  }

  hasPlugin(name) {
    return (
      this.plugins &&
      this.plugins.find(plugin => {
        return plugin.resolve.name === name
      })
    )
  }

  mergeConfig() {
    const cliConfig = this.createConfigFromCLIOptions()
    logger.debug(`Config from command options`, cliConfig)

    this.config = validateConfig(this, merge({}, this.config, cliConfig))
  }

  hook(name, fn) {
    this.hooks.add(name, fn)
    return this
  }

  registerTestRunner(name, runner) {
    if (this.testRunners.has(name)) {
      throw new PoiError({
        message: `Test runner "${name}" has already been registered!`
      })
    }
    this.testRunners.set(name, runner)
    return this
  }

  resolveCwd(...args) {
    return path.resolve(this.cwd, ...args)
  }

  resolveOutDir(...args) {
    return this.resolveCwd(this.config.output.dir, ...args)
  }

  async run() {
    await this.hooks.invokePromise('beforeRun')

    await this.cli.runMatchedCommand()

    await this.hooks.invokePromise('afterRun')
  }

  createConfigFromCLIOptions() {
    const {
      minimize,
      sourceMap,
      format,
      moduleName,
      outDir,
      publicUrl,
      target,
      clean,
      parallel,
      cache,
      jsx,
      extractCss,
      hot,
      host,
      port,
      open,
      proxy,
      fileNames,
      html,
      publicFolder
    } = this.cli.options
    return {
      entry: this.cli.args.length > 0 ? this.cli.args : undefined,
      output: {
        minimize,
        sourceMap,
        format,
        moduleName,
        dir: outDir,
        publicUrl,
        target,
        clean,
        fileNames,
        html
      },
      parallel,
      cache,
      publicFolder,
      babel: {
        jsx
      },
      css: {
        extract: extractCss
      },
      devServer: {
        hot,
        host,
        port,
        open,
        proxy
      }
    }
  }

  createWebpackChain(opts) {
    const WebpackChain = require('./utils/WebpackChain')

    opts = Object.assign({ type: 'client', mode: this.mode }, opts)

    const config = new WebpackChain({
      configureWebpack: this.config.configureWebpack,
      opts
    })

    require('./webpack/webpack.config')(config, this)

    this.hooks.invoke('createWebpackChain', config, opts)

    if (this.config.chainWebpack) {
      this.config.chainWebpack(config, opts)
    }

    if (this.cli.options.inspectWebpack) {
      const inspect = () => {
        const id = Math.random()
          .toString(36)
          .substring(7)
        const outFile = path.join(
          os.tmpdir(),
          `poi-inspect-webpack-config-${id}.js`
        )
        const configString = `// ${JSON.stringify(
          opts
        )}\nvar config = ${config.toString()}\n\n`
        fs.writeFileSync(outFile, configString, 'utf8')
        require('@poi/dev-utils/open')(outFile, {
          wait: false
        })
      }

      config.plugin('inspect-webpack').use(
        class InspectWebpack {
          apply(compiler) {
            compiler.hooks.afterEnvironment.tap('inspect-webpack', inspect)
          }
        }
      )
    }

    return config
  }

  runCompiler(compiler, watch) {
    return new Promise((resolve, reject) => {
      if (watch) {
        compiler.watch({}, err => {
          if (err) return reject(err)
          resolve()
        })
      } else {
        compiler.run((err, stats) => {
          if (err) return reject(err)
          resolve(stats)
        })
      }
    })
  }

  createWebpackCompiler(config) {
    const compiler = require('webpack')(config)

    // Override the .watch method so we can handle error here instead of letting WDM handle it
    // And in fact we disabled WDM logger so errors will never show displayed there
    const originalWatch = compiler.watch.bind(compiler)
    compiler.watch = (options, cb) => {
      return originalWatch(options, (err, stats) => {
        if (err) {
          throw err
        }
        cb(null, stats)
      })
    }

    return compiler
  }

  getCacheConfig(dir, keys, files) {
    let content = ''
    if (files) {
      const file = this.configLoader.resolve({ files: [].concat(files) })
      if (file) {
        content = fs.readFileSync(file, 'utf8')
      }
    }

    return {
      cacheDirectory: this.resolveCwd('node_modules/.cache', dir),
      cacheIdentifier: `${JSON.stringify(keys)}::${content}`
    }
  }

  localResolve(name, cwd = this.cwd) {
    return resolveFrom.silent(cwd, name)
  }

  localRequire(name, cwd) {
    const resolved = this.localResolve(name, cwd)
    return resolved ? require(resolved) : null
  }
}
<commit_msg>fix: ensure that ts-node returns a commonjs module, closes #563<commit_after>const os = require('os')
const path = require('path')
const fs = require('fs-extra')
const resolveFrom = require('resolve-from')
const cac = require('cac')
const chalk = require('chalk')
const merge = require('lodash.merge')
const logger = require('@poi/logger')
const Hooks = require('./Hooks')
const WebpackUtils = require('./WebpackUtils')
const createConfigLoader = require('./utils/createConfigLoader')
const loadEnvs = require('./utils/loadEnvs')
const parseArgs = require('./utils/parseArgs')
const PoiError = require('./utils/PoiError')
const spinner = require('./utils/spinner')
const validateConfig = require('./utils/validateConfig')
const { normalizePlugins, mergePlugins } = require('./utils/plugins')

module.exports = class PoiCore {
  constructor(
    rawArgs = process.argv,
    {
      defaultConfigFiles = [
        'poi.config.js',
        'poi.config.ts',
        'package.json',
        '.poirc',
        '.poirc.json',
        '.poirc.js'
      ],
      extendConfigLoader,
      config: externalConfig
    } = {}
  ) {
    this.rawArgs = rawArgs
    this.logger = logger
    this.spinner = spinner
    this.PoiError = PoiError
    // For plugins, it's only used in plugin.cli export
    this.args = parseArgs(rawArgs)
    this.hooks = new Hooks()
    this.testRunners = new Map()

    if (this.args.has('debug')) {
      logger.setOptions({ debug: true })
    }

    this.mode = this.args.get('mode')
    if (!this.mode) {
      this.mode = 'development'
    }

    if (this.args.has('prod') || this.args.has('production')) {
      this.mode = 'production'
    }

    if (this.args.has('test')) {
      this.mode = 'test'
    }

    if (this.args.args[0] && /^test(:|$)/.test(this.args.args[0])) {
      this.mode = 'test'
    }

    logger.debug(`Running in ${this.mode} mode`)

    this.cwd = this.args.get('cwd')
    if (!this.cwd) {
      this.cwd = process.cwd()
    }

    // Load modules from --require flag
    this.loadRequiredModules()

    this.configLoader = createConfigLoader(this.cwd)

    // For other tools that use Poi under the hood
    if (extendConfigLoader) {
      extendConfigLoader(this.configLoader)
    }

    // Load .env files
    loadEnvs(this.mode, this.resolveCwd('.env'))

    if (!process.env.NODE_ENV) {
      process.env.NODE_ENV = this.mode
    }

    this.webpackUtils = new WebpackUtils(this)

    // Try to load config file
    const configFlag =
      this.args.get('config') === undefined
        ? this.args.get('c')
        : this.args.get('config')
    if (externalConfig || configFlag === false) {
      logger.debug('Poi config file was disabled')
      this.config = externalConfig || {}
    } else {
      const configFiles =
        typeof configFlag === 'string' ? [configFlag] : defaultConfigFiles
      const { path: configPath, data: configFn } = this.configLoader.load({
        files: configFiles,
        packageKey: 'poi'
      })
      if (configPath) {
        logger.debug(`Using Poi config file:`, configPath)
      } else {
        logger.debug(`Not using any Poi config file`)
      }
      this.configPath = configPath
      this.config =
        typeof configFn === 'function' ? configFn(this.args.options) : configFn
      this.config = this.config || {}
    }

    this.pkg = this.configLoader.load({
      files: ['package.json']
    })
    this.pkg.data = this.pkg.data || {}

    // Initialize plugins
    this.initPlugins()
    // Init CLI instance, call plugin.cli, parse CLI args
    this.initCLI()
    // Merge cli config with config file
    this.mergeConfig()
    // Call plugin.apply
    this.applyPlugins()
    this.hooks.invoke('createConfig', this.config)
  }

  get isProd() {
    return this.mode === 'production'
  }

  initCLI() {
    const cli = (this.cli = cac())
    this.command = cli
      .command('[...entries]', 'Entry files to start bundling', {
        ignoreOptionDefaultValue: true
      })
      .usage('[...entries] [options]')
      .action(async () => {
        logger.debug(`Using default handler`)
        const chain = this.createWebpackChain()
        const compiler = this.createWebpackCompiler(chain.toConfig())
        await this.runCompiler(compiler)
      })

    this.extendCLI()

    // Global options
    cli
      .option('--mode <mode>', 'Set mode', 'development')
      .option('--prod, --production', 'Alias for --mode production')
      .option('--test', 'Alias for --mode test')
      .option('--no-config', 'Disable config file')
      .option('-c, --config <path>', 'Set the path to config file')
      .option('-r, --require <module>', 'Require a module before bootstrapping')
      .option(
        '--plugin, --plugins <plugin>',
        'Add a plugin (can be used for multiple times)'
      )
      .option('--debug', 'Show debug logs')
      .option('--inspect-webpack', 'Inspect webpack config in your editor')
      .version(require('../package').version)
      .help(sections => {
        for (const section of sections) {
          if (section.title && section.title.includes('For more info')) {
            const body = section.body.split('\n')
            body.shift()
            body.unshift(
              `  $ ${cli.name} --help`,
              `  $ ${cli.name} --serve --help`,
              `  $ ${cli.name} --prod --help`
            )
            section.body = body.join('\n')
          }
        }
      })

    this.cli.parse(this.rawArgs, { run: false })

    logger.debug('Command args', this.cli.args)
    logger.debug('Command options', this.cli.options)
  }

  loadRequiredModules() {
    // Ensure that ts-node returns a commonjs module
    process.env.TS_NODE_COMPILER_OPTIONS = JSON.stringify({
      module: 'commonjs'
    })

    const requiredModules = this.args.get('require') || this.args.get('r')
    if (requiredModules) {
      ;[].concat(requiredModules).forEach(name => {
        const m = this.localRequire(name)
        if (!m) {
          throw new PoiError({
            message: `Cannot find module "${name}" in current directory!`
          })
        }
      })
    }
  }

  hasDependency(name) {
    return [
      ...Object.keys(this.pkg.data.dependencies || {}),
      ...Object.keys(this.pkg.data.devDependencies || {})
    ].includes(name)
  }

  /**
   * @private
   * @returns {void}
   */
  initPlugins() {
    const cwd = this.configPath
      ? path.dirname(this.configPath)
      : this.resolveCwd()
    const cliPlugins = normalizePlugins(
      this.args.get('plugin') || this.args.get('plugins'),
      cwd
    )
    const configPlugins = normalizePlugins(this.config.plugins, cwd)

    this.plugins = [
      { resolve: require.resolve('./plugins/command-options') },
      { resolve: require.resolve('./plugins/config-babel') },
      { resolve: require.resolve('./plugins/config-vue') },
      { resolve: require.resolve('./plugins/config-css') },
      { resolve: require.resolve('./plugins/config-font') },
      { resolve: require.resolve('./plugins/config-image') },
      { resolve: require.resolve('./plugins/config-eval') },
      { resolve: require.resolve('./plugins/config-html') },
      { resolve: require.resolve('./plugins/config-electron') },
      { resolve: require.resolve('./plugins/config-misc-loaders') },
      { resolve: require.resolve('./plugins/config-reason') },
      { resolve: require.resolve('./plugins/config-yarn-pnp') },
      { resolve: require.resolve('./plugins/config-jsx-import') },
      { resolve: require.resolve('./plugins/watch') },
      { resolve: require.resolve('./plugins/serve') },
      { resolve: require.resolve('./plugins/eject-html') },
      { resolve: require.resolve('@poi/plugin-html-entry') }
    ]
      .concat(mergePlugins(configPlugins, cliPlugins))
      .map(plugin => {
        if (typeof plugin.resolve === 'string') {
          plugin._resolve = plugin.resolve
          plugin.resolve = require(plugin.resolve)
        }
        return plugin
      })
  }

  extendCLI() {
    for (const plugin of this.plugins) {
      if (plugin.resolve.cli) {
        plugin.resolve.cli(this, plugin.options)
      }
    }
  }

  /**
   * @private
   * @returns {void}
   */
  applyPlugins() {
    let plugins = this.plugins.filter(plugin => {
      return !plugin.resolve.when || plugin.resolve.when(this)
    })

    // Run plugin's `filterPlugins` method
    for (const plugin of plugins) {
      if (plugin.resolve.filterPlugins) {
        plugins = plugin.resolve.filterPlugins(this.plugins, plugin.options)
      }
    }

    // Run plugin's `apply` method
    for (const plugin of plugins) {
      if (plugin.resolve.apply) {
        logger.debug(`Apply plugin: \`${chalk.bold(plugin.resolve.name)}\``)
        if (plugin._resolve) {
          logger.debug(`location: ${plugin._resolve}`)
        }
        plugin.resolve.apply(this, plugin.options)
      }
    }
  }

  hasPlugin(name) {
    return (
      this.plugins &&
      this.plugins.find(plugin => {
        return plugin.resolve.name === name
      })
    )
  }

  mergeConfig() {
    const cliConfig = this.createConfigFromCLIOptions()
    logger.debug(`Config from command options`, cliConfig)

    this.config = validateConfig(this, merge({}, this.config, cliConfig))
  }

  hook(name, fn) {
    this.hooks.add(name, fn)
    return this
  }

  registerTestRunner(name, runner) {
    if (this.testRunners.has(name)) {
      throw new PoiError({
        message: `Test runner "${name}" has already been registered!`
      })
    }
    this.testRunners.set(name, runner)
    return this
  }

  resolveCwd(...args) {
    return path.resolve(this.cwd, ...args)
  }

  resolveOutDir(...args) {
    return this.resolveCwd(this.config.output.dir, ...args)
  }

  async run() {
    await this.hooks.invokePromise('beforeRun')

    await this.cli.runMatchedCommand()

    await this.hooks.invokePromise('afterRun')
  }

  createConfigFromCLIOptions() {
    const {
      minimize,
      sourceMap,
      format,
      moduleName,
      outDir,
      publicUrl,
      target,
      clean,
      parallel,
      cache,
      jsx,
      extractCss,
      hot,
      host,
      port,
      open,
      proxy,
      fileNames,
      html,
      publicFolder
    } = this.cli.options
    return {
      entry: this.cli.args.length > 0 ? this.cli.args : undefined,
      output: {
        minimize,
        sourceMap,
        format,
        moduleName,
        dir: outDir,
        publicUrl,
        target,
        clean,
        fileNames,
        html
      },
      parallel,
      cache,
      publicFolder,
      babel: {
        jsx
      },
      css: {
        extract: extractCss
      },
      devServer: {
        hot,
        host,
        port,
        open,
        proxy
      }
    }
  }

  createWebpackChain(opts) {
    const WebpackChain = require('./utils/WebpackChain')

    opts = Object.assign({ type: 'client', mode: this.mode }, opts)

    const config = new WebpackChain({
      configureWebpack: this.config.configureWebpack,
      opts
    })

    require('./webpack/webpack.config')(config, this)

    this.hooks.invoke('createWebpackChain', config, opts)

    if (this.config.chainWebpack) {
      this.config.chainWebpack(config, opts)
    }

    if (this.cli.options.inspectWebpack) {
      const inspect = () => {
        const id = Math.random()
          .toString(36)
          .substring(7)
        const outFile = path.join(
          os.tmpdir(),
          `poi-inspect-webpack-config-${id}.js`
        )
        const configString = `// ${JSON.stringify(
          opts
        )}\nvar config = ${config.toString()}\n\n`
        fs.writeFileSync(outFile, configString, 'utf8')
        require('@poi/dev-utils/open')(outFile, {
          wait: false
        })
      }

      config.plugin('inspect-webpack').use(
        class InspectWebpack {
          apply(compiler) {
            compiler.hooks.afterEnvironment.tap('inspect-webpack', inspect)
          }
        }
      )
    }

    return config
  }

  runCompiler(compiler, watch) {
    return new Promise((resolve, reject) => {
      if (watch) {
        compiler.watch({}, err => {
          if (err) return reject(err)
          resolve()
        })
      } else {
        compiler.run((err, stats) => {
          if (err) return reject(err)
          resolve(stats)
        })
      }
    })
  }

  createWebpackCompiler(config) {
    const compiler = require('webpack')(config)

    // Override the .watch method so we can handle error here instead of letting WDM handle it
    // And in fact we disabled WDM logger so errors will never show displayed there
    const originalWatch = compiler.watch.bind(compiler)
    compiler.watch = (options, cb) => {
      return originalWatch(options, (err, stats) => {
        if (err) {
          throw err
        }
        cb(null, stats)
      })
    }

    return compiler
  }

  getCacheConfig(dir, keys, files) {
    let content = ''
    if (files) {
      const file = this.configLoader.resolve({ files: [].concat(files) })
      if (file) {
        content = fs.readFileSync(file, 'utf8')
      }
    }

    return {
      cacheDirectory: this.resolveCwd('node_modules/.cache', dir),
      cacheIdentifier: `${JSON.stringify(keys)}::${content}`
    }
  }

  localResolve(name, cwd = this.cwd) {
    return resolveFrom.silent(cwd, name)
  }

  localRequire(name, cwd) {
    const resolved = this.localResolve(name, cwd)
    return resolved ? require(resolved) : null
  }
}
<|endoftext|>


<commit_before>/* @flow */

/*::
import type { RemoteDoc, RemoteDeletion } from './document'
import type { Metadata } from '../metadata'
*/

const path = require('path')

const { isFile } = require('../metadata')

/*::
export type RemoteFileAddition = {sideName: 'remote', type: 'FileAddition', doc: Metadata}
export type RemoteFileDeletion = {sideName: 'remote', type: 'FileDeletion', doc: Metadata}
export type RemoteFileDissociation = {sideName: 'remote', type: 'FileDissociation', doc: Metadata, was: Metadata}
export type RemoteFileMove = {sideName: 'remote', type: 'FileMove', doc: Metadata, was: Metadata, needRefetch?: true, update?: true}
export type RemoteFileRestoration = {sideName: 'remote', type: 'FileRestoration', doc: Metadata, was: Metadata}
export type RemoteFileTrashing = {sideName: 'remote', type: 'FileTrashing', doc: Metadata, was: Metadata}
export type RemoteFileUpdate = {sideName: 'remote', type: 'FileUpdate', doc: Metadata}
export type RemoteDirAddition = {sideName: 'remote', type: 'DirAddition', doc: Metadata, was: Metadata}
export type RemoteDirDeletion = {sideName: 'remote', type: 'DirDeletion', doc: Metadata}
export type RemoteDirDissociation = {sideName: 'remote', type: 'DirDissociation', doc: Metadata, was: Metadata}
export type RemoteDirMove = {sideName: 'remote', type: 'DirMove', doc: Metadata, was: Metadata, needRefetch?: true}
export type RemoteDirRestoration = {sideName: 'remote', type: 'DirRestoration', doc: Metadata, was: Metadata}
export type RemoteDirTrashing = {sideName: 'remote', type: 'DirTrashing', doc: Metadata, was: Metadata}

export type RemoteChange =
  | RemoteDirAddition
  | RemoteDirDeletion
  | RemoteDirDissociation
  | RemoteDirMove
  | RemoteDirRestoration
  | RemoteDirTrashing
  | RemoteFileAddition
  | RemoteFileDeletion
  | RemoteFileDissociation
  | RemoteFileMove
  | RemoteFileRestoration
  | RemoteFileTrashing
  | RemoteFileUpdate

export type RemoteIgnoredChange = {type: 'RemoteIgnoredChange', doc: Metadata|RemoteDoc|RemoteDeletion, detail: string}
export type RemoteInvalidChange = {type: 'RemoteInvalidChange', doc: *, error: Error}
export type RemoteUpToDate = {type: 'RemoteUpToDate', doc: Metadata, was: Metadata}

export type RemoteNoise =
  | RemoteIgnoredChange
  | RemoteInvalidChange
  | RemoteUpToDate
*/

module.exports = {
  added,
  trashed,
  deleted,
  restored,
  upToDate,
  updated,
  dissociated,
  isChildMove,
  isOnlyChildMove,
  applyMoveToPath,
  sort
}

const sideName = 'remote'

// FIXME: return types
function added (doc /*: Metadata */) /*: * */ {
  return {sideName, type: (isFile(doc) ? 'FileAddition' : 'DirAddition'), doc}
}

function trashed (doc /*: Metadata */, was /*: Metadata */) /*: * */ {
  return {sideName, type: (isFile(doc) ? 'FileTrashing' : 'DirTrashing'), doc, was}
}

function deleted (doc /*: Metadata */) /*: * */ {
  return {sideName, type: (isFile(doc) ? 'FileDeletion' : 'DirDeletion'), doc}
}

function restored (doc /*: Metadata */, was /*: Metadata */) /*: * */ {
  return {sideName, type: (isFile(doc) ? 'FileRestoration' : 'DirRestoration'), doc, was}
}

function upToDate (doc /*: Metadata */, was /*: Metadata */) /*: * */ {
  return {sideName, type: 'RemoteUpToDate', doc, was}
}

function updated (doc /*: Metadata */) /*: * */ {
  return {sideName, type: (isFile(doc) ? 'FileUpdate' : 'DirAddition'), doc}
}

function dissociated (doc /*: Metadata */, was /*: Metadata */) /*: * */ {
  return {sideName, type: (isFile(doc) ? 'FileDissociation' : 'DirDissociation'), doc, was}
}

// TODO: Rename args
function isChildMove (a /*: RemoteChange|RemoteNoise */, b /*: RemoteChange|RemoteNoise */) /*: boolean %checks */ {
  return a.type === 'DirMove' &&
        (b.type === 'DirMove' || b.type === 'FileMove') &&
        (b.doc.path.indexOf(a.doc.path + path.sep) === 0) &&
        a.was && b.was &&
        (b.was.path.indexOf(a.was.path + path.sep) === 0) &&
        a.type === 'DirMove' &&
        (b.type === 'DirMove' || b.type === 'FileMove')
}

/*     was           doc
 a    /a     ->    /a2
 b    /a/b   ->    /a2/b
*/
function isOnlyChildMove (a /*: RemoteDirMove */, b /*: RemoteFileMove|RemoteDirMove */) /*: boolean %checks */ {
  return isChildMove(a, b) && b.doc.path.replace(a.doc.path, '') === b.was.path.replace(a.was.path, '')
}

function applyMoveToPath (a /*: RemoteDirMove */, p /*: string */) /*: string */ {
  return p.replace(a.was.path, a.doc.path)
}

const isDelete = (a /*: RemoteChange|RemoteNoise */) /*: boolean %checks */ => a.type === 'DirDeletion' || a.type === 'FileDeletion'
const isAdd = (a /*: RemoteChange|RemoteNoise */) /*: boolean %checks */ => a.type === 'DirAddition' || a.type === 'FileAddition'
const isMove = (a /*: RemoteChange|RemoteNoise */) /*: boolean %checks */ => a.type === 'DirMove' || a.type === 'FileMove'
const isTrash = (a /*: RemoteChange|RemoteNoise */) /*: boolean %checks */ => a.type === 'DirTrashing' || a.type === 'FileTrashing'
const isRestore = (a /*: RemoteChange|RemoteNoise */) /*: boolean %checks */ => a.type === 'DirRestoration' || a.type === 'FileRestoration'
const isDissociate = (a /*: RemoteChange|RemoteNoise */) /*: boolean %checks */ => a.type === 'DirDissociation' || a.type === 'FileDissociation'

const addPath = (a /*: RemoteChange|RemoteNoise */) /*: ?string */ => isAdd(a) || isMove(a) || isRestore(a) || isDissociate(a) ? a.doc.path : null
const delPath = (a /*: RemoteChange|RemoteNoise */) /*: ?string */ => isDelete(a) ? a.doc.path : isMove(a) || isTrash(a) ? a.was.path : null
const childOf = (p1 /*: ?string */, p2 /*: ?string */)/*: boolean */ => p1 != null && p2 != null && p2 !== p1 && p2.startsWith(p1 + path.sep)
const lower = (p1 /*: ?string */, p2 /*: ?string */)/*: boolean */ => p1 != null && p2 != null && p2 !== p1 && p1 < p2

const isChildDelete = (a /*: RemoteChange|RemoteNoise */, b /*: RemoteChange|RemoteNoise */) => childOf(delPath(a), delPath(b))
const isChildAdd = (a /*: RemoteChange|RemoteNoise */, b /*: RemoteChange|RemoteNoise */) => childOf(addPath(a), addPath(b))

const sorter = (a, b) => {
  if (childOf(addPath(a), delPath(b))) return -1
  if (childOf(addPath(b), delPath(a))) return 1

  // if one action is a child of another, it takes priority
  if (isChildAdd(a, b)) return -1
  if (isChildDelete(b, a)) return -1
  if (isChildAdd(b, a)) return 1
  if (isChildDelete(a, b)) return 1

  // otherwise, order by add path
  if (lower(addPath(a), addPath(b))) return -1
  if (lower(addPath(b), addPath(a))) return 1

  // if there isnt 2 add paths, sort by del path
  if (lower(delPath(b), delPath(a))) return -1

  return 1
}

function sort (changes /*: Array<RemoteChange|RemoteNoise> */) /*: void */ {
  changes.sort(sorter)
}
<commit_msg>Fix remote move and replace<commit_after>/* @flow */

/*::
import type { RemoteDoc, RemoteDeletion } from './document'
import type { Metadata } from '../metadata'
*/

const path = require('path')

const { isFile } = require('../metadata')

/*::
export type RemoteFileAddition = {sideName: 'remote', type: 'FileAddition', doc: Metadata}
export type RemoteFileDeletion = {sideName: 'remote', type: 'FileDeletion', doc: Metadata}
export type RemoteFileDissociation = {sideName: 'remote', type: 'FileDissociation', doc: Metadata, was: Metadata}
export type RemoteFileMove = {sideName: 'remote', type: 'FileMove', doc: Metadata, was: Metadata, needRefetch?: true, update?: true}
export type RemoteFileRestoration = {sideName: 'remote', type: 'FileRestoration', doc: Metadata, was: Metadata}
export type RemoteFileTrashing = {sideName: 'remote', type: 'FileTrashing', doc: Metadata, was: Metadata}
export type RemoteFileUpdate = {sideName: 'remote', type: 'FileUpdate', doc: Metadata}
export type RemoteDirAddition = {sideName: 'remote', type: 'DirAddition', doc: Metadata, was: Metadata}
export type RemoteDirDeletion = {sideName: 'remote', type: 'DirDeletion', doc: Metadata}
export type RemoteDirDissociation = {sideName: 'remote', type: 'DirDissociation', doc: Metadata, was: Metadata}
export type RemoteDirMove = {sideName: 'remote', type: 'DirMove', doc: Metadata, was: Metadata, needRefetch?: true}
export type RemoteDirRestoration = {sideName: 'remote', type: 'DirRestoration', doc: Metadata, was: Metadata}
export type RemoteDirTrashing = {sideName: 'remote', type: 'DirTrashing', doc: Metadata, was: Metadata}

export type RemoteChange =
  | RemoteDirAddition
  | RemoteDirDeletion
  | RemoteDirDissociation
  | RemoteDirMove
  | RemoteDirRestoration
  | RemoteDirTrashing
  | RemoteFileAddition
  | RemoteFileDeletion
  | RemoteFileDissociation
  | RemoteFileMove
  | RemoteFileRestoration
  | RemoteFileTrashing
  | RemoteFileUpdate

export type RemoteIgnoredChange = {type: 'RemoteIgnoredChange', doc: Metadata|RemoteDoc|RemoteDeletion, detail: string}
export type RemoteInvalidChange = {type: 'RemoteInvalidChange', doc: *, error: Error}
export type RemoteUpToDate = {type: 'RemoteUpToDate', doc: Metadata, was: Metadata}

export type RemoteNoise =
  | RemoteIgnoredChange
  | RemoteInvalidChange
  | RemoteUpToDate
*/

module.exports = {
  added,
  trashed,
  deleted,
  restored,
  upToDate,
  updated,
  dissociated,
  isChildMove,
  isOnlyChildMove,
  applyMoveToPath,
  sort
}

const sideName = 'remote'

// FIXME: return types
function added (doc /*: Metadata */) /*: * */ {
  return {sideName, type: (isFile(doc) ? 'FileAddition' : 'DirAddition'), doc}
}

function trashed (doc /*: Metadata */, was /*: Metadata */) /*: * */ {
  return {sideName, type: (isFile(doc) ? 'FileTrashing' : 'DirTrashing'), doc, was}
}

function deleted (doc /*: Metadata */) /*: * */ {
  return {sideName, type: (isFile(doc) ? 'FileDeletion' : 'DirDeletion'), doc}
}

function restored (doc /*: Metadata */, was /*: Metadata */) /*: * */ {
  return {sideName, type: (isFile(doc) ? 'FileRestoration' : 'DirRestoration'), doc, was}
}

function upToDate (doc /*: Metadata */, was /*: Metadata */) /*: * */ {
  return {sideName, type: 'RemoteUpToDate', doc, was}
}

function updated (doc /*: Metadata */) /*: * */ {
  return {sideName, type: (isFile(doc) ? 'FileUpdate' : 'DirAddition'), doc}
}

function dissociated (doc /*: Metadata */, was /*: Metadata */) /*: * */ {
  return {sideName, type: (isFile(doc) ? 'FileDissociation' : 'DirDissociation'), doc, was}
}

// TODO: Rename args
function isChildMove (a /*: RemoteChange|RemoteNoise */, b /*: RemoteChange|RemoteNoise */) /*: boolean %checks */ {
  return a.type === 'DirMove' &&
        (b.type === 'DirMove' || b.type === 'FileMove') &&
        (b.doc.path.indexOf(a.doc.path + path.sep) === 0) &&
        a.was && b.was &&
        (b.was.path.indexOf(a.was.path + path.sep) === 0) &&
        a.type === 'DirMove' &&
        (b.type === 'DirMove' || b.type === 'FileMove')
}

/*     was           doc
 a    /a     ->    /a2
 b    /a/b   ->    /a2/b
*/
function isOnlyChildMove (a /*: RemoteDirMove */, b /*: RemoteFileMove|RemoteDirMove */) /*: boolean %checks */ {
  return isChildMove(a, b) && b.doc.path.replace(a.doc.path, '') === b.was.path.replace(a.was.path, '')
}

function applyMoveToPath (a /*: RemoteDirMove */, p /*: string */) /*: string */ {
  return p.replace(a.was.path, a.doc.path)
}

const isDelete = (a /*: RemoteChange|RemoteNoise */) /*: boolean %checks */ => a.type === 'DirDeletion' || a.type === 'FileDeletion'
const isAdd = (a /*: RemoteChange|RemoteNoise */) /*: boolean %checks */ => a.type === 'DirAddition' || a.type === 'FileAddition'
const isMove = (a /*: RemoteChange|RemoteNoise */) /*: boolean %checks */ => a.type === 'DirMove' || a.type === 'FileMove'
const isTrash = (a /*: RemoteChange|RemoteNoise */) /*: boolean %checks */ => a.type === 'DirTrashing' || a.type === 'FileTrashing'
const isRestore = (a /*: RemoteChange|RemoteNoise */) /*: boolean %checks */ => a.type === 'DirRestoration' || a.type === 'FileRestoration'
const isDissociate = (a /*: RemoteChange|RemoteNoise */) /*: boolean %checks */ => a.type === 'DirDissociation' || a.type === 'FileDissociation'

const addPath = (a /*: RemoteChange|RemoteNoise */) /*: ?string */ => isAdd(a) || isMove(a) || isRestore(a) || isDissociate(a) ? a.doc.path : null
const delPath = (a /*: RemoteChange|RemoteNoise */) /*: ?string */ => isDelete(a) ? a.doc.path : isMove(a) || isTrash(a) ? a.was.path : null
const childOf = (p1 /*: ?string */, p2 /*: ?string */)/*: boolean */ => p1 != null && p2 != null && p2 !== p1 && p2.startsWith(p1 + path.sep)
const lower = (p1 /*: ?string */, p2 /*: ?string */)/*: boolean */ => p1 != null && p2 != null && p2 !== p1 && p1 < p2

const isChildDelete = (a /*: RemoteChange|RemoteNoise */, b /*: RemoteChange|RemoteNoise */) => childOf(delPath(a), delPath(b))
const isChildAdd = (a /*: RemoteChange|RemoteNoise */, b /*: RemoteChange|RemoteNoise */) => childOf(addPath(a), addPath(b))

const sorter = (a, b) => {
  if (childOf(addPath(a), delPath(b))) return -1
  if (childOf(addPath(b), delPath(a))) return 1

  // if one action is a child of another, it takes priority
  if (isChildAdd(a, b)) return -1
  if (isChildDelete(b, a)) return -1
  if (isChildAdd(b, a)) return 1
  if (isChildDelete(a, b)) return 1

  // otherwise, order by add path
  if (lower(addPath(a), addPath(b))) return -1
  if (lower(addPath(b), addPath(a))) return 1

  if (delPath(a) === addPath(b)) return -1
  if (delPath(b) === addPath(a)) return 1

  // if there isnt 2 add paths, sort by del path
  if (lower(delPath(b), delPath(a))) return -1

  return 1
}

function sort (changes /*: Array<RemoteChange|RemoteNoise> */) /*: void */ {
  changes.sort(sorter)
}
<|endoftext|>


<commit_before>/*jshint undef: false, unused: false, indent: 2*/
/*global angular: false */

'use strict';

angular.module('hopsWorksApp')
    .controller('ProjectCtrl', ['$scope', '$rootScope','$modalStack', '$location', '$routeParams', 'UtilsService',
      'growl', 'ProjectService', 'ModalService', 'ActivityService', '$cookies', 'DataSetService', 'EndpointService',
      function ($scope, $rootScope,$modalStack, $location, $routeParams, UtilsService, growl, ProjectService, ModalService, ActivityService, $cookies, DataSetService, EndpointService) {

        var self = this;
        self.working = false;
        self.currentProject = [];
        self.activities = [];
        self.currentPage = 1;
        self.card = {};
        self.cards = [];
        self.projectMembers = [];

        self.endpoint = '...';

        // We could instead implement a service to get all the available types but this will do it for now
        self.projectTypes = ['JOBS', 'ZEPPELIN', 'BIOBANKING', 'CHARON'];
        self.alreadyChoosenServices = [];
        self.selectionProjectTypes = [];
        self.pId = $routeParams.projectID;

        self.projectFile = {
          description : null,
          id : null,
          name : null,
          parentId : null,
          path : null,
        };

        var getEndpoint = function () {
          EndpointService.findEndpoint().then(
              function (success) {
                console.log(success);
                self.endpoint = success.data.data.value;
              }, function (error) {
            self.endpoint = '...';
          });
        };

        getEndpoint();

        var getCurrentProject = function () {
          ProjectService.get({}, {'id': self.pId}).$promise.then(
              function (success) {
                self.currentProject = success;
                self.projectFile.id = self.currentProject.inodeid;
                self.projectFile.name = self.currentProject.projectName;
                self.projectFile.parentId = self.currentProject.projectTeam[0].project.inode.inodePK.parentId;
                self.projectFile.path = "/Projects/"+self.currentProject.projectName;
                self.projectFile.description = self.currentProject.description;
                self.projectFile.retentionPeriod = self.currentProject.retentionPeriod;
                $rootScope.$broadcast('setMetadata', { file:
                   {id : self.projectFile.id,
                    name : self.projectFile.name,
                    parentId : self.projectFile.parentId,
                    path : self.projectFile.path} });

                self.projectMembers = self.currentProject.projectTeam;
                self.alreadyChoosenServices = [];
                self.currentProject.services.forEach(function (entry) {
                  self.alreadyChoosenServices.push(entry);
                });

                // Remove already choosen services from the service selection
                self.alreadyChoosenServices.forEach(function (entry) {
                  var index = self.projectTypes.indexOf(entry.toUpperCase());
                  self.projectTypes.splice(index, 1);
                });

                $cookies.projectID = self.pId;
                //set the project name under which the search is performed
                UtilsService.setProjectName(self.currentProject.projectName);

              }, function (error) {
            $location.path('/');
          }
          );
        };

        var getAllActivities = function () {
          ActivityService.getByProjectId(self.pId).then(function (success) {
            self.activities = success.data;
            self.pageSize = 10;
            self.totalPages = Math.floor(self.activities.length / self.pageSize);
            self.totalItems = self.activities.length;
          }, function (error) {
            growl.info("Error" + error.data.errorMsg, {title: 'Error', ttl: 5000});
          });
        };

        //we only need to load the activities if the path is project (endswith pId).
        var locationPath = $location.path();
        if (locationPath.substring(locationPath.length - self.pId.length, locationPath.length) === self.pId) {
          getAllActivities();
        }

        getCurrentProject();

        // Check if the service exists and otherwise add it or remove it depending on the previous choice
        self.exists = function (projectType) {
          var idx = self.selectionProjectTypes.indexOf(projectType);
          if (idx > -1) {
            self.selectionProjectTypes.splice(idx, 1);
          } else {
            self.selectionProjectTypes.push(projectType);
          }
        };

        self.projectSettingModal = function () {
          ModalService.projectSettings('md').then(
              function (success) {
                getAllActivities();
                getCurrentProject();

                // Check if the service exists and otherwise add it or remove it depending on the previous choice
                self.exists = function (projectType) {
                  var idx = self.selectionProjectTypes.indexOf(projectType);
                  if (idx > -1) {
                    self.selectionProjectTypes.splice(idx, 1);
                  } else {
                    self.selectionProjectTypes.push(projectType);
                  }
                };
              });
        };

        self.projectSettingModal = function () {
          ModalService.projectSettings('md').then(
              function (success) {
                getAllActivities();
                getCurrentProject();
              }, function (error) {
            growl.info("You closed without saving.", {title: 'Info', ttl: 5000});
          });
        };

        self.membersModal = function () {
          ModalService.projectMembers('lg', self.pId).then(
              function (success) {
              }, function (error) {
          });
        };

        self.saveProject = function () {
          self.working = true;
          $scope.newProject = {
            'projectName': self.currentProject.projectName,
            'description': self.currentProject.description,
            'services': self.selectionProjectTypes,
            'retentionPeriod': self.currentProject.retentionPeriod,
            'ethicalStatus': self.currentProject.ethicalStatus
          };

          ProjectService.update({id: self.currentProject.projectId}, $scope.newProject)
              .$promise.then(
                  function (success) {
                    self.working = false;
                    growl.success("Success: " + success.successMessage, {title: 'Success', ttl: 5000});
                    if (success.errorMsg) {
                      growl.warning(success.errorMsg, {title: 'Error', ttl: 15000});
                    }
                    $modalStack.getTop().key.close();
                  }, function (error) {
                self.working = false;
                growl.warning("Error: " + error.data.errorMsg, {title: 'Error', ttl: 5000});
              }
              );
        };

        self.close = function () {
          $modalStack.getTop().key.dismiss();
        };

        $scope.showHamburger = $location.path().indexOf("project") > -1;

        self.goToDatasets = function () {
          $location.path('project/' + self.pId + '/datasets');
        };

        self.goToJobs = function () {
          $location.path('project/' + self.pId + '/jobs');
        };

        self.goToSsh = function () {
          $location.path('project/' + self.pId + '/ssh');
        };

        self.goToCharon = function () {
          $location.path('project/' + self.pId + '/charon');
        };

        self.goToBiobanking = function () {
          $location.path('project/' + self.pId + '/biobanking');
        };

        self.goToService = function (service) {
          $location.path('project/' + self.pId + '/' + service.toLowerCase());
        };

        self.goToSpecificDataset = function (name) {
          $location.path($location.path() + '/' + name);
        };

        self.goToMetadataDesigner = function () {
          $location.path('project/' + self.pId + '/metadata');
        };

        /**
         * Checks if the file has been accepted before opening.
         * @param dataset
         */
        self.browseDataset = function (dataset) {

          if (dataset.status === true) {
            UtilsService.setDatasetName(dataset.name);
            $location.path($location.path() + '/' + dataset.name);
          } else {
            ModalService.confirmShare('sm', 'Confirm', 'Do you want to accept this dataset, and add it to this project?')
                .then(function (success) {
                  DataSetService(self.pId).acceptDataset(dataset.id).then(
                      function (success) {
                        $location.path($location.path() + '/' + dataset.name);
                      }, function (error) {
                    growl.warning("Error: " + error.data.errorMsg, {title: 'Error', ttl: 5000});
                  });
                }, function (error) {
                  if (error === 'reject') {
                    DataSetService(self.pId).rejectDataset(dataset.id).then(
                        function (success) {
                          $location.path($location.path() + '/');
                          growl.success("Success: " + success.data.successMessage, {title: 'Success', ttl: 5000});
                        }, function (error) {
                      growl.warning("Error: " + error.data.errorMsg, {title: 'Error', ttl: 5000});
                    });
                  }
                });
          }

        };

        self.sizeOnDisk = function (fileSizeInBytes) {
          return convertSize(fileSizeInBytes);
        };

        self.showZeppelin = function () {
          return showService("Zeppelin");
        };

        self.showJobs = function () {
          return showService("Jobs");
        };

        self.showSsh = function () {
          return showService("Ssh");
        };

        self.showCharon = function () {
          return showService("Charon");
        };

        self.showBiobanking = function () {
          return showService("Biobanking");
        };

        var showService = function (serviceName) {
          var len = self.alreadyChoosenServices.length;
          for (var i = 0; i < len; i++) {
            if (self.alreadyChoosenServices[i] === serviceName) {
              return true;
            }
          }
          return false;
        };

        self.saveAllowed = function () {
          if (self.currentProject.projectName.length === 0) {
            return true;
          }
        };

        $scope.data = [
          [65, 59, 90, 81, 56, 55, 40],
          [28, 48, 40, 19, 96, 27, 100]
        ];

        $scope.labels2 = ["January", "February", "March", "April", "May", "June", "July"];
        $scope.series = ['Fileoperations', 'Querys'];
        $scope.data2 = [
          [65, 59, 80, 81, 56, 55, 40],
          [28, 48, 40, 19, 86, 27, 90]
        ];
        $scope.onClick = function (points, evt) {
          console.log(points, evt);
        };

      }]);<commit_msg>disable charon/bbc in project settings modal<commit_after>/*jshint undef: false, unused: false, indent: 2*/
/*global angular: false */

'use strict';

angular.module('hopsWorksApp')
    .controller('ProjectCtrl', ['$scope', '$rootScope','$modalStack', '$location', '$routeParams', 'UtilsService',
      'growl', 'ProjectService', 'ModalService', 'ActivityService', '$cookies', 'DataSetService', 'EndpointService',
      function ($scope, $rootScope,$modalStack, $location, $routeParams, UtilsService, growl, ProjectService, ModalService, ActivityService, $cookies, DataSetService, EndpointService) {

        var self = this;
        self.working = false;
        self.currentProject = [];
        self.activities = [];
        self.currentPage = 1;
        self.card = {};
        self.cards = [];
        self.projectMembers = [];

        self.endpoint = '...';

        // We could instead implement a service to get all the available types but this will do it for now
//        self.projectTypes = ['JOBS', 'ZEPPELIN', 'BIOBANKING', 'CHARON'];
        self.projectTypes = ['JOBS', 'ZEPPELIN'];
        self.alreadyChoosenServices = [];
        self.selectionProjectTypes = [];
        self.pId = $routeParams.projectID;

        self.projectFile = {
          description : null,
          id : null,
          name : null,
          parentId : null,
          path : null,
        };

        var getEndpoint = function () {
          EndpointService.findEndpoint().then(
              function (success) {
                console.log(success);
                self.endpoint = success.data.data.value;
              }, function (error) {
            self.endpoint = '...';
          });
        };

        getEndpoint();

        var getCurrentProject = function () {
          ProjectService.get({}, {'id': self.pId}).$promise.then(
              function (success) {
                self.currentProject = success;
                self.projectFile.id = self.currentProject.inodeid;
                self.projectFile.name = self.currentProject.projectName;
                self.projectFile.parentId = self.currentProject.projectTeam[0].project.inode.inodePK.parentId;
                self.projectFile.path = "/Projects/"+self.currentProject.projectName;
                self.projectFile.description = self.currentProject.description;
                self.projectFile.retentionPeriod = self.currentProject.retentionPeriod;
                $rootScope.$broadcast('setMetadata', { file:
                   {id : self.projectFile.id,
                    name : self.projectFile.name,
                    parentId : self.projectFile.parentId,
                    path : self.projectFile.path} });

                self.projectMembers = self.currentProject.projectTeam;
                self.alreadyChoosenServices = [];
                self.currentProject.services.forEach(function (entry) {
                  self.alreadyChoosenServices.push(entry);
                });

                // Remove already choosen services from the service selection
                self.alreadyChoosenServices.forEach(function (entry) {
                  var index = self.projectTypes.indexOf(entry.toUpperCase());
                  self.projectTypes.splice(index, 1);
                });

                $cookies.projectID = self.pId;
                //set the project name under which the search is performed
                UtilsService.setProjectName(self.currentProject.projectName);

              }, function (error) {
            $location.path('/');
          }
          );
        };

        var getAllActivities = function () {
          ActivityService.getByProjectId(self.pId).then(function (success) {
            self.activities = success.data;
            self.pageSize = 10;
            self.totalPages = Math.floor(self.activities.length / self.pageSize);
            self.totalItems = self.activities.length;
          }, function (error) {
            growl.info("Error" + error.data.errorMsg, {title: 'Error', ttl: 5000});
          });
        };

        //we only need to load the activities if the path is project (endswith pId).
        var locationPath = $location.path();
        if (locationPath.substring(locationPath.length - self.pId.length, locationPath.length) === self.pId) {
          getAllActivities();
        }

        getCurrentProject();

        // Check if the service exists and otherwise add it or remove it depending on the previous choice
        self.exists = function (projectType) {
          var idx = self.selectionProjectTypes.indexOf(projectType);
          if (idx > -1) {
            self.selectionProjectTypes.splice(idx, 1);
          } else {
            self.selectionProjectTypes.push(projectType);
          }
        };

        self.projectSettingModal = function () {
          ModalService.projectSettings('md').then(
              function (success) {
                getAllActivities();
                getCurrentProject();

                // Check if the service exists and otherwise add it or remove it depending on the previous choice
                self.exists = function (projectType) {
                  var idx = self.selectionProjectTypes.indexOf(projectType);
                  if (idx > -1) {
                    self.selectionProjectTypes.splice(idx, 1);
                  } else {
                    self.selectionProjectTypes.push(projectType);
                  }
                };
              });
        };

        self.projectSettingModal = function () {
          ModalService.projectSettings('md').then(
              function (success) {
                getAllActivities();
                getCurrentProject();
              }, function (error) {
            growl.info("You closed without saving.", {title: 'Info', ttl: 5000});
          });
        };

        self.membersModal = function () {
          ModalService.projectMembers('lg', self.pId).then(
              function (success) {
              }, function (error) {
          });
        };

        self.saveProject = function () {
          self.working = true;
          $scope.newProject = {
            'projectName': self.currentProject.projectName,
            'description': self.currentProject.description,
            'services': self.selectionProjectTypes,
            'retentionPeriod': self.currentProject.retentionPeriod,
            'ethicalStatus': self.currentProject.ethicalStatus
          };

          ProjectService.update({id: self.currentProject.projectId}, $scope.newProject)
              .$promise.then(
                  function (success) {
                    self.working = false;
                    growl.success("Success: " + success.successMessage, {title: 'Success', ttl: 5000});
                    if (success.errorMsg) {
                      growl.warning(success.errorMsg, {title: 'Error', ttl: 15000});
                    }
                    $modalStack.getTop().key.close();
                  }, function (error) {
                self.working = false;
                growl.warning("Error: " + error.data.errorMsg, {title: 'Error', ttl: 5000});
              }
              );
        };

        self.close = function () {
          $modalStack.getTop().key.dismiss();
        };

        $scope.showHamburger = $location.path().indexOf("project") > -1;

        self.goToDatasets = function () {
          $location.path('project/' + self.pId + '/datasets');
        };

        self.goToJobs = function () {
          $location.path('project/' + self.pId + '/jobs');
        };

        self.goToSsh = function () {
          $location.path('project/' + self.pId + '/ssh');
        };

        self.goToCharon = function () {
          $location.path('project/' + self.pId + '/charon');
        };

        self.goToBiobanking = function () {
          $location.path('project/' + self.pId + '/biobanking');
        };

        self.goToService = function (service) {
          $location.path('project/' + self.pId + '/' + service.toLowerCase());
        };

        self.goToSpecificDataset = function (name) {
          $location.path($location.path() + '/' + name);
        };

        self.goToMetadataDesigner = function () {
          $location.path('project/' + self.pId + '/metadata');
        };

        /**
         * Checks if the file has been accepted before opening.
         * @param dataset
         */
        self.browseDataset = function (dataset) {

          if (dataset.status === true) {
            UtilsService.setDatasetName(dataset.name);
            $location.path($location.path() + '/' + dataset.name);
          } else {
            ModalService.confirmShare('sm', 'Confirm', 'Do you want to accept this dataset, and add it to this project?')
                .then(function (success) {
                  DataSetService(self.pId).acceptDataset(dataset.id).then(
                      function (success) {
                        $location.path($location.path() + '/' + dataset.name);
                      }, function (error) {
                    growl.warning("Error: " + error.data.errorMsg, {title: 'Error', ttl: 5000});
                  });
                }, function (error) {
                  if (error === 'reject') {
                    DataSetService(self.pId).rejectDataset(dataset.id).then(
                        function (success) {
                          $location.path($location.path() + '/');
                          growl.success("Success: " + success.data.successMessage, {title: 'Success', ttl: 5000});
                        }, function (error) {
                      growl.warning("Error: " + error.data.errorMsg, {title: 'Error', ttl: 5000});
                    });
                  }
                });
          }

        };

        self.sizeOnDisk = function (fileSizeInBytes) {
          return convertSize(fileSizeInBytes);
        };

        self.showZeppelin = function () {
          return showService("Zeppelin");
        };

        self.showJobs = function () {
          return showService("Jobs");
        };

        self.showSsh = function () {
          return showService("Ssh");
        };

        self.showCharon = function () {
          return showService("Charon");
        };

        self.showBiobanking = function () {
          return showService("Biobanking");
        };

        var showService = function (serviceName) {
          var len = self.alreadyChoosenServices.length;
          for (var i = 0; i < len; i++) {
            if (self.alreadyChoosenServices[i] === serviceName) {
              return true;
            }
          }
          return false;
        };

        self.saveAllowed = function () {
          if (self.currentProject.projectName.length === 0) {
            return true;
          }
        };

        $scope.data = [
          [65, 59, 90, 81, 56, 55, 40],
          [28, 48, 40, 19, 96, 27, 100]
        ];

        $scope.labels2 = ["January", "February", "March", "April", "May", "June", "July"];
        $scope.series = ['Fileoperations', 'Querys'];
        $scope.data2 = [
          [65, 59, 80, 81, 56, 55, 40],
          [28, 48, 40, 19, 86, 27, 90]
        ];
        $scope.onClick = function (points, evt) {
          console.log(points, evt);
        };

      }]);<|endoftext|>