<commit_before>$( document ).ready(function() {

    affectEvent();

    loadAllTags();

    loadAllNote();

});

function affectEvent() {
    $("#create-note-button").click( function(e) {
        $("#edit-panel").toggleClass("edit-panel-enabled");
    });
}

function loadAllTags() {
    $.ajax({
        url: "/api/tags.json",
        method: "GET",
        dataType: "json"

    }).done(function (data) {
        $("#tags-list").empty();

        data.forEach(function (elemnt, index, array) {
            $("#tags-list").append(
                '<button type="button" class="btn btn-default tag">' + elemnt +
                '</button>');
            $(".tag:contains(" + elemnt + ")").click(function () {
                $( this ).toggleClass("active");
            });
        });

    });
}

function loadAllNote() {
    $.ajax({
        url: "/api/notes.json",
        method: "GET",
        dataType: "json"

    }).done(function (data) {
        $("#notes-list").empty();

        data.forEach(function (elemnt, index, array) {
            $("#notes-list").append(
                '
  \

 \

' + elemnt.name + '
 \

 \

 \

 \

 \
                                         \

 \

 \
                                ' + elemnt.uuid + ' \

 \

 \
                                <button type="button" class="btn btn-default action-button pull-left" > \
                                     \
                                </button> \
                                <button type="button" class="btn btn-default action-button pull-right" > \
                                     \
                                </button> \

 \

 \

');
        });

    });
}<commit_msg>Formattage correct de la string<commit_after>$( document ).ready(function() {

    affectEvent();

    loadAllTags();

    loadAllNote();

});

function affectEvent() {
    $("#create-note-button").click( function(e) {
        $("#edit-panel").toggleClass("edit-panel-enabled");
    });
}

function loadAllTags() {
    $.ajax({
        url: "/api/tags.json",
        method: "GET",
        dataType: "json"

    }).done(function (data) {
        $("#tags-list").empty();

        data.forEach(function (elemnt, index, array) {
            $("#tags-list").append(
                '<button type="button" class="btn btn-default tag">' + elemnt +
                '</button>');
            $(".tag:contains(" + elemnt + ")").click(function () {
                $( this ).toggleClass("active");
            });
        });

    });
}

function loadAllNote() {
    $.ajax({
        url: "/api/notes.json",
        method: "GET",
        dataType: "json"

    }).done(function (data) {
        $("#notes-list").empty();

        data.forEach(function (elemnt, index, array) {
            $("#notes-list").append(
                '
' +
                        '
 ' +
                            '
' +
                                '
' + elemnt.name + '
 ' +
                            '
' +
                            '
' +
                                '
' +
                                    '
' +
                                        '' +
                                    '
' +
                                '
' +
                                '' + elemnt.uuid + '' +
                            '
' +
                            '
' +
                                '<button type="button" class="btn btn-default action-button pull-left" >' +
                                    '' +
                                '</button>' +
                                '<button type="button" class="btn btn-default action-button pull-right" >' +
                                    '' +
                                '</button>' +
                            '
' +
                        '
' +
                    '
');
        });

    });
}<|endoftext|>


<commit_before>/* Provided under the MIT license. See LICENSE for details */

(function ($) {
	$.fn.pagering = function (options) {
		var settings = {};
		var defaults = {
			chapterClass: "entry-content",
			columnGap: 20,
			columnWidth: 300
		};
		if (options) {
			settings = $.extend(defaults, options);
		} else {
			settings = defaults;
		}

		/* UTILITY FUNCTIONS */
		// http://gist.github.com/405856/
		var vendorPrefixes = ["", "-webkit-", "-moz-"];
		var test = document.createElement("div");
		// http://unscriptable.com/index.php/2009/05/01/a-better-javascript-memoizer/
		var cssSupport = (function () {
			var cache = {};
			return function (property, value) {
				if (undefined === cache[property]) {
					if (null === value) {
						value = 1;
					}
					for (var i = 0; i < vendorPrefixes.length; ++i) {
						var composedName = vendorPrefixes[i] + property;
						test.style.composedName = value;
						var cStyle = document.defaultView.getComputedStyle(test, null);
						if (null !== cStyle.getPropertyValue(composedName)) {
							cache[property] = vendorPrefixes[i];
							break;
						}
					}
				}
				return cache[property];
			};
		})();
		// http://gist.github.com/406015
		var cssDimensionInPx = (function () {
			return function ($element, property) {
				var dimension = $element.css(property);
				var dimensionInt = parseInt(dimension, 10);
				var fontSize = parseInt($element.css("font-size"), 10);
				if (dimension && !isNaN(dimensionInt)) {
					// no unit
					if ("" + dimensionInt === dimension) {
						return dimensionInt;
					// px
					} else if (dimension.length - 2 === dimension.indexOf("px")) {
						return dimensionInt;
					// em
					} else if (dimension.length - 2 === dimension.indexOf("em")) {
						return dimensionInt * fontSize;
					// %
					} else if (dimension.length - 1 === dimension.indexOf("%")) {
						return (dimensionInt * 0.01) * fontSize;
					}
				} else {
					return 0;
				}
			};
		})();

		var columnSupport = cssSupport("column-gap");
		if (undefined !== columnSupport) {
			// navigation elements
			var $dummyPageNav = $("
");
			var $dummyPageLeft = $("←");
			var $dummyPageRight = $("→");
			var $dummyPageCount = $("
");
			var $dummyCurrentPage = $("1");
			var $dummyTotalPages = $("1");

			this.each(function () {
				var $pagerings = $(this);
				$pagerings.addClass("pageringed");
				$pagerings.each(function () {
					// this is lame
					var $pageNav = $dummyPageNav.clone();
					var $pageLeft = $dummyPageLeft.clone();
					var $pageRight = $dummyPageRight.clone();
					var $pageCount = $dummyPageCount.clone();
					var $currentPage = $dummyCurrentPage.clone();
					var $totalPages = $dummyTotalPages.clone();

					var $pagering = $(this);
					var $pageringContent = $pagering.find("." + settings.chapterClass);
					var unpagedHeight = $pageringContent.height();
					$pageringContent.addClass("pageringedChapter");
					var pagedHeight = $pageringContent.height();
					var totalPagesEstimate = Math.ceil(unpagedHeight / pagedHeight);

					// http://forum.jquery.com/topic/how-to-pass-variables-in-jquery-css
					$pageringContent
							.css(columnSupport + "column-gap", settings.columnGap)
							.css(columnSupport + "column-width", settings.columnWidth);

					var columnGap = cssDimensionInPx($pageringContent,
							columnSupport + "column-gap");
					var contentViewportWidth = cssDimensionInPx($pageringContent,
							"width");

					$pagering.append($pageCount.append($currentPage).append("/")
							.append($totalPages));
					$totalPages.text(totalPagesEstimate);

					if (1 < totalPagesEstimate) {
						$pagering.append($pageNav.append($pageLeft).append($pageRight));

						var currentPage = 1;
						var currentOffset = 0;
						var newOffset = 0;

						var slidePage = function (multiplier) {
							currentOffset = cssDimensionInPx($pageringContent, "left");
							newOffset = multiplier * (contentViewportWidth + columnGap);
							$pageringContent.animate({ left : currentOffset + newOffset },
									500);
						};
						var updateNavClickability = function () {
							if (1 < currentPage) {
								$pageLeft.removeClass("disabled");
							} else {
								$pageLeft.addClass("disabled");
							}
							if (currentPage < totalPagesEstimate) {
								$pageRight.removeClass("disabled");
							} else {
								$pageRight.addClass("disabled");
							}
						};
						updateNavClickability(); // run once on load

						$pageLeft.click(function () {
							if (1 < currentPage) {
								currentPage -= 1;
								slidePage(1);
								$currentPage.text(currentPage);
							}
							updateNavClickability();
						});
						$pageRight.click(function () {
							if (currentPage < totalPagesEstimate) {
								slidePage(-1);
								currentPage += 1;
								$currentPage.text(currentPage);
							}
							updateNavClickability();
						});
					}
				});
			});
		}
		return this;
	};
})(jQuery);
<commit_msg>adjust option name to reflect final terminology<commit_after>/* Provided under the MIT license. See LICENSE for details */

(function ($) {
	$.fn.pagering = function (options) {
		var settings = {};
		var defaults = {
			columnGap: 20,
			columnWidth: 300,
			contentClass: "entry-content"
		};
		if (options) {
			settings = $.extend(defaults, options);
		} else {
			settings = defaults;
		}

		/* UTILITY FUNCTIONS */
		// http://gist.github.com/405856/
		var vendorPrefixes = ["", "-webkit-", "-moz-"];
		var test = document.createElement("div");
		// http://unscriptable.com/index.php/2009/05/01/a-better-javascript-memoizer/
		var cssSupport = (function () {
			var cache = {};
			return function (property, value) {
				if (undefined === cache[property]) {
					if (null === value) {
						value = 1;
					}
					for (var i = 0; i < vendorPrefixes.length; ++i) {
						var composedName = vendorPrefixes[i] + property;
						test.style.composedName = value;
						var cStyle = document.defaultView.getComputedStyle(test, null);
						if (null !== cStyle.getPropertyValue(composedName)) {
							cache[property] = vendorPrefixes[i];
							break;
						}
					}
				}
				return cache[property];
			};
		})();
		// http://gist.github.com/406015
		var cssDimensionInPx = (function () {
			return function ($element, property) {
				var dimension = $element.css(property);
				var dimensionInt = parseInt(dimension, 10);
				var fontSize = parseInt($element.css("font-size"), 10);
				if (dimension && !isNaN(dimensionInt)) {
					// no unit
					if ("" + dimensionInt === dimension) {
						return dimensionInt;
					// px
					} else if (dimension.length - 2 === dimension.indexOf("px")) {
						return dimensionInt;
					// em
					} else if (dimension.length - 2 === dimension.indexOf("em")) {
						return dimensionInt * fontSize;
					// %
					} else if (dimension.length - 1 === dimension.indexOf("%")) {
						return (dimensionInt * 0.01) * fontSize;
					}
				} else {
					return 0;
				}
			};
		})();

		var columnSupport = cssSupport("column-gap");
		if (undefined !== columnSupport) {
			// navigation elements
			var $dummyPageNav = $("
");
			var $dummyPageLeft = $("←");
			var $dummyPageRight = $("→");
			var $dummyPageCount = $("
");
			var $dummyCurrentPage = $("1");
			var $dummyTotalPages = $("1");

			this.each(function () {
				var $pagerings = $(this);
				$pagerings.addClass("pageringed");
				$pagerings.each(function () {
					// this is lame
					var $pageNav = $dummyPageNav.clone();
					var $pageLeft = $dummyPageLeft.clone();
					var $pageRight = $dummyPageRight.clone();
					var $pageCount = $dummyPageCount.clone();
					var $currentPage = $dummyCurrentPage.clone();
					var $totalPages = $dummyTotalPages.clone();

					var $pagering = $(this);
					var $pageringContent = $pagering.find("." + settings.contentClass);
					var unpagedHeight = $pageringContent.height();
					$pageringContent.addClass("pageringedChapter");
					var pagedHeight = $pageringContent.height();
					var totalPagesEstimate = Math.ceil(unpagedHeight / pagedHeight);

					// http://forum.jquery.com/topic/how-to-pass-variables-in-jquery-css
					$pageringContent
							.css(columnSupport + "column-gap", settings.columnGap)
							.css(columnSupport + "column-width", settings.columnWidth);

					var columnGap = cssDimensionInPx($pageringContent,
							columnSupport + "column-gap");
					var contentViewportWidth = cssDimensionInPx($pageringContent,
							"width");

					$pagering.append($pageCount.append($currentPage).append("/")
							.append($totalPages));
					$totalPages.text(totalPagesEstimate);

					if (1 < totalPagesEstimate) {
						$pagering.append($pageNav.append($pageLeft).append($pageRight));

						var currentPage = 1;
						var currentOffset = 0;
						var newOffset = 0;

						var slidePage = function (multiplier) {
							currentOffset = cssDimensionInPx($pageringContent, "left");
							newOffset = multiplier * (contentViewportWidth + columnGap);
							$pageringContent.animate({ left : currentOffset + newOffset },
									500);
						};
						var updateNavClickability = function () {
							if (1 < currentPage) {
								$pageLeft.removeClass("disabled");
							} else {
								$pageLeft.addClass("disabled");
							}
							if (currentPage < totalPagesEstimate) {
								$pageRight.removeClass("disabled");
							} else {
								$pageRight.addClass("disabled");
							}
						};
						updateNavClickability(); // run once on load

						$pageLeft.click(function () {
							if (1 < currentPage) {
								currentPage -= 1;
								slidePage(1);
								$currentPage.text(currentPage);
							}
							updateNavClickability();
						});
						$pageRight.click(function () {
							if (currentPage < totalPagesEstimate) {
								slidePage(-1);
								currentPage += 1;
								$currentPage.text(currentPage);
							}
							updateNavClickability();
						});
					}
				});
			});
		}
		return this;
	};
})(jQuery);
<|endoftext|>


<commit_before>/*
* @Author: ChalrieHwang
* @Date:   2015-06-05 17:38:31
* @Last Modified by:   ChalrieHwang
* @Last Modified time: 2015-06-12 22:36:48
*/

'use strict';
(function (angular) {

// ---------------------------------------------------------
// RightClickDirective - Right click deletion
// ---------------------------------------------------------
  var RightClickCtrl = function ($scope, GraphService) {
    $scope.graph = GraphService;
    $scope.show = false;
  };

  var link = function($scope, element){

    element.bind('contextmenu', function($event){
      $event.preventDefault();
      var clickObjType = $event.path[0].tagName;
      var nodeClasses = ['cluster', 'issue'];
      var nodeId,
          nodeClass,
          promise,
          upNodeId,
          downNodeId;
      if (clickObjType === 'circle'){
        nodeId = Number($event.target.__data__);
        nodeClass = $scope.g.node(nodeId).class;
      } else if (clickObjType === 'tspan'){
        nodeId = Number($event.path[4].__data__);
        nodeClass = $scope.g.node(nodeId).class;
      } else if (clickObjType === 'path'){
        upNodeId = Number($event.target.__data__.v);
        downNodeId = Number($event.target.__data__.w);
      } else if (clickObjType === 'svg'){

      }

      // Pop up window
      var menu1 = [
        {
          title: 'Add New Dependency',
          action: function() {
            d3.selectAll('.node')
              .attr('class', 'cluster pick')
              .on('click', function(clickId){
                promise = $scope.graph.addNewDependency(nodeId, clickId);
                if(promise){
                  promise.then(function(result){
                    if(result){
                      $scope.graphData = $scope.graph.graphObj.graph;
                      $scope.graph.postGraph();
                      d3.selectAll('.cluster').remove();
                      $scope.buildGraph($scope.graphData);
                    }
                  }, function(err){
                      console.log('error', err);
                  });
                }
              });
          }
        },
        {
          title: 'Delete',
          action: function() {
            //Click circle
            if(nodeClasses.indexOf(nodeClass) !== -1){
              if(nodeClass === 'cluster'){
                promise = $scope.graph.deleteNode(nodeId);
              } else if (nodeClass === 'issue'){
                promise = $scope.graph.deleteNode(nodeId);
              }
            }
            //Click Path
            if(clickObjType === 'path'){
              promise = $scope.graph.deleteEdge(upNodeId, downNodeId);
            }
            if(promise){
              promise.then(function(result){
                if(result){
                  $scope.graphData = $scope.graph.graphObj.graph;
                  $scope.buildGraph($scope.graphData);
                  // $scope.graph.postGraph();
                }
              }, function(err){
                console.log('error', err);
              });
            }
          }
        }
      ];

      var obj = {
        id: 300,
        type: 'cluster',
        parent_cluster: 1,
        cluster_id: 100,
        issue_id: null,
        upstream_nodes: null,
        downstream_nodes: null,
        cluster: {
          id: 100,
          abbrev: 'NewCluster',
          name: 'Add New cluster',
          description: 'Add New Cluster',
          endpoints: [
            32,
            33
          ],
          creator: 7910250,
          children_count: 2,
          children_complete: 0
        }
      };

      var menu2 = [
        {
          title: 'Add New Cluster',
          action: function() {
            promise = $scope.graph.addCluster(obj);
            if(promise){
              promise.then(function(result){
                if(result){
                  $scope.graphData = $scope.graph.graphObj.graph;
                  $scope.graph.postGraph();
                  $scope.buildGraph($scope.graphData);
                }
              }, function(err){
                console.log('error', err);
              });
            }
          }
        }
      ];

      //Append the menu div
      if(clickObjType){
        d3.selectAll('.context-menu').data([1])
          .enter()
          .append('div')
          .attr('class', 'context-menu');
        d3.selectAll('.context-menu').html('');
        var list = d3.selectAll('.context-menu').append('ul');
        if(clickObjType === 'cluster' || clickObjType === 'circle' || clickObjType === 'tspan'){
          list.selectAll('li').data(menu1).enter()
            .append('li')
            .html(function(d) {
              return d.title;
            })
            .on('click', function(d) {
              d.action(d);
              d3.select('.context-menu').style('display', 'none');
            });
        } else if (clickObjType === 'path') {
          list.selectAll('li')
              .data(menu1[1]).enter()
              .append('li')
              .html(function(d) {
                return d.title;
              })
              .on('click', function(d) {
                d.action(d);
                d3.select('.context-menu').style('display', 'none');
              });
        } else if (clickObjType === 'svg'){
          list.selectAll('li').data(menu2).enter()
            .append('li')
            .html(function(d) {
              return d.title;
            })
            .on('click', function(d) {
              d.action(d);
              d3.select('.context-menu').style('display', 'none');
            });
        }
        d3.select('.context-menu')
        .style('left', ($event.pageX - 2) + 'px')
        .style('top', ($event.pageY - 2) + 'px')
        .style('display', 'block');

        //Close the contextmenu once it got clicked
        d3.select('body').on('click.context-menu', function() {
          d3.select('.context-menu').style('display', 'none');
        });

      }
    });
  };

  var RighClickDirective = function () {
    return {
      restrict: 'EA',
      controller: RightClickCtrl,
      link: link,
      scope: true
    };
  };

// ---------------------------------------------------------
// Entry Point
// ---------------------------------------------------------

  angular
    .module('cd-app.common')
    .directive('ngRightClick', RighClickDirective);

})(angular);
<commit_msg>(fix) Fix the right click path unshown contextmenu<commit_after>/*
* @Author: ChalrieHwang
* @Date:   2015-06-05 17:38:31
* @Last Modified by:   ChalrieHwang
* @Last Modified time: 2015-06-12 22:41:28
*/

'use strict';
(function (angular) {

// ---------------------------------------------------------
// RightClickDirective - Right click deletion
// ---------------------------------------------------------
  var RightClickCtrl = function ($scope, GraphService) {
    $scope.graph = GraphService;
    $scope.show = false;
  };

  var link = function($scope, element){

    element.bind('contextmenu', function($event){
      $event.preventDefault();
      var clickObjType = $event.path[0].tagName;
      var nodeClasses = ['cluster', 'issue'];
      var nodeId,
          nodeClass,
          promise,
          upNodeId,
          downNodeId;
      if (clickObjType === 'circle'){
        nodeId = Number($event.target.__data__);
        nodeClass = $scope.g.node(nodeId).class;
      } else if (clickObjType === 'tspan'){
        nodeId = Number($event.path[4].__data__);
        nodeClass = $scope.g.node(nodeId).class;
      } else if (clickObjType === 'path'){
        upNodeId = Number($event.target.__data__.v);
        downNodeId = Number($event.target.__data__.w);
      } else if (clickObjType === 'svg'){

      }

      // Pop up window
      var menu1 = [
        {
          title: 'Add New Dependency',
          action: function() {
            d3.selectAll('.node')
              .attr('class', 'cluster pick')
              .on('click', function(clickId){
                promise = $scope.graph.addNewDependency(nodeId, clickId);
                if(promise){
                  promise.then(function(result){
                    if(result){
                      $scope.graphData = $scope.graph.graphObj.graph;
                      $scope.graph.postGraph();
                      d3.selectAll('.cluster').remove();
                      $scope.buildGraph($scope.graphData);
                    }
                  }, function(err){
                      console.log('error', err);
                  });
                }
              });
          }
        },
        {
          title: 'Delete',
          action: function() {
            //Click circle
            if(nodeClasses.indexOf(nodeClass) !== -1){
              if(nodeClass === 'cluster'){
                promise = $scope.graph.deleteNode(nodeId);
              } else if (nodeClass === 'issue'){
                promise = $scope.graph.deleteNode(nodeId);
              }
            }
            //Click Path
            if(clickObjType === 'path'){
              promise = $scope.graph.deleteEdge(upNodeId, downNodeId);
            }
            if(promise){
              promise.then(function(result){
                if(result){
                  $scope.graphData = $scope.graph.graphObj.graph;
                  $scope.buildGraph($scope.graphData);
                  // $scope.graph.postGraph();
                }
              }, function(err){
                console.log('error', err);
              });
            }
          }
        }
      ];

      var obj = {
        id: 300,
        type: 'cluster',
        parent_cluster: 1,
        cluster_id: 100,
        issue_id: null,
        upstream_nodes: null,
        downstream_nodes: null,
        cluster: {
          id: 100,
          abbrev: 'NewCluster',
          name: 'Add New cluster',
          description: 'Add New Cluster',
          endpoints: [
            32,
            33
          ],
          creator: 7910250,
          children_count: 2,
          children_complete: 0
        }
      };

      var menu2 = [
        {
          title: 'Add New Cluster',
          action: function() {
            promise = $scope.graph.addCluster(obj);
            if(promise){
              promise.then(function(result){
                if(result){
                  $scope.graphData = $scope.graph.graphObj.graph;
                  $scope.graph.postGraph();
                  $scope.buildGraph($scope.graphData);
                }
              }, function(err){
                console.log('error', err);
              });
            }
          }
        }
      ];

      //Append the menu div
      if(clickObjType){
        d3.selectAll('.context-menu').data([1])
          .enter()
          .append('div')
          .attr('class', 'context-menu');
        d3.selectAll('.context-menu').html('');
        var list = d3.selectAll('.context-menu').append('ul');
        if(clickObjType === 'cluster' || clickObjType === 'circle' || clickObjType === 'tspan'){
          list.selectAll('li').data(menu1).enter()
            .append('li')
            .html(function(d) {
              return d.title;
            })
            .on('click', function(d) {
              d.action(d);
              d3.select('.context-menu').style('display', 'none');
            });
        } else if (clickObjType === 'path') {
          list.selectAll('li')
              .data([menu1[1]]).enter()
              .append('li')
              .html(function(d) {
                return d.title;
              })
              .on('click', function(d) {
                d.action(d);
                d3.select('.context-menu').style('display', 'none');
              });
        } else if (clickObjType === 'svg'){
          list.selectAll('li').data(menu2).enter()
            .append('li')
            .html(function(d) {
              return d.title;
            })
            .on('click', function(d) {
              d.action(d);
              d3.select('.context-menu').style('display', 'none');
            });
        }
        d3.select('.context-menu')
        .style('left', ($event.pageX - 2) + 'px')
        .style('top', ($event.pageY - 2) + 'px')
        .style('display', 'block');

        //Close the contextmenu once it got clicked
        d3.select('body').on('click.context-menu', function() {
          d3.select('.context-menu').style('display', 'none');
        });

      }
    });
  };

  var RighClickDirective = function () {
    return {
      restrict: 'EA',
      controller: RightClickCtrl,
      link: link,
      scope: true
    };
  };

// ---------------------------------------------------------
// Entry Point
// ---------------------------------------------------------

  angular
    .module('cd-app.common')
    .directive('ngRightClick', RighClickDirective);

})(angular);
<|endoftext|>


<commit_before>import angular from 'angular';
import getUniqueName from './getUniqueName';
import DI from './DependencyManager';
import Provider from './AutoLookupProvider';

let stringOfClass = x => typeof x === 'function' ? x.$name : x;
let crawlPrototypes = clazz => {
  let classes = [];
  while (clazz.$name) {
    classes.push(clazz);
    clazz = Object.getPrototypeOf(clazz);
  }
  return classes;
};

export function Service(input = []) {
  let func = dependencies => clazz => {
    clazz.$name = getUniqueName() + clazz.name;   // name leading to a proxy provider
    clazz.$internal = getUniqueName();   // name that actually leads to the instance

    clazz.$inject = dependencies.map(stringOfClass);
    clazz.$overrides = crawlPrototypes(clazz);
    clazz.$applyOverride = module => {
      clazz.$overrides.forEach(iface => {
        DI.bind(iface).to(clazz);
        // Register every interface/implementation in angular
        // Will figure out exact implementation later
        module.provider(iface.$name, new Provider(module, iface));
      });
      // Register real instance with internal name
      module.service(clazz.$internal, clazz);
    };
    clazz.$registerOn = clazz.$applyOverride;
    return clazz;
  };
  // Unwrapping
  if (input.constructor !== Array) {
    return func([])(input);
  } else {
    return func(input);
  }
}

export let Default = defVal => clazz => { clazz.$default = defVal; return clazz; };

export function Value(clazz) {
  clazz.$name = getUniqueName() + clazz.name;
  if (clazz.$default) DI.bind(clazz).toValue(clazz.$default);
}

export function Controller(input = []) {
  let func = dependencies => clazz => {
    clazz.$name = getUniqueName() + clazz.name;
    clazz.$inject = dependencies.map(stringOfClass);
    clazz.$registerOn = module =>
      module.config(['$controllerProvider', x => x.register(clazz.$name, clazz)]);
    return clazz;
  };
  // Unwrapping
  if (input.constructor !== Array) {
    return func([])(input);
  } else {
    return func(input);
  }
}

// Extend Angular modules with `.use`
let origModuleCall = angular.module;
angular.module = function () {
  let module = origModuleCall.apply(angular, arguments);
  module.use = (...components) =>
    components.forEach(component => component.$registerOn(module));
  // Add in our module for default values
  module.requires.push(DI.getDefaultModuleName());
  // Extend Angular `.value` calls to process annotated values
  let origValueCall = module.value;
  module.value = function () {
    // Calling with annotated value class?
    if (arguments[0].constructor !== String) arguments[0] = arguments[0].$name;
    return origValueCall.apply(module, arguments);
  };
  return module;
};
<commit_msg>Support for Directives<commit_after>import angular from 'angular';
import getUniqueName from './getUniqueName';
import DI from './DependencyManager';
import Provider from './AutoLookupProvider';

let stringOfClass = x => typeof x === 'function' ? x.$name : x;
let crawlPrototypes = clazz => {
  let classes = [];
  while (clazz.$name) {
    classes.push(clazz);
    clazz = Object.getPrototypeOf(clazz);
  }
  return classes;
};

export function Service(input = []) {
  let func = dependencies => clazz => {
    clazz.$name = getUniqueName() + clazz.name;   // name leading to a proxy provider
    clazz.$internal = getUniqueName();   // name that actually leads to the instance

    clazz.$inject = dependencies.map(stringOfClass);
    clazz.$overrides = crawlPrototypes(clazz);
    clazz.$applyOverride = module => {
      clazz.$overrides.forEach(iface => {
        DI.bind(iface).to(clazz);
        // Register every interface/implementation in angular
        // Will figure out exact implementation later
        module.provider(iface.$name, new Provider(module, iface));
      });
      // Register real instance with internal name
      module.service(clazz.$internal, clazz);
    };
    clazz.$registerOn = clazz.$applyOverride;
    return clazz;
  };
  // Unwrapping
  if (input.constructor !== Array) {
    return func([])(input);
  } else {
    return func(input);
  }
}

export let Default = defVal => clazz => { clazz.$default = defVal; return clazz; };

export function Value(clazz) {
  clazz.$name = getUniqueName() + clazz.name;
  if (clazz.$default) DI.bind(clazz).toValue(clazz.$default);
}

export function Controller(input = []) {
  let func = dependencies => clazz => {
    clazz.$name = getUniqueName() + clazz.name;
    clazz.$inject = dependencies.map(stringOfClass);
    clazz.$registerOn = module =>
      module.config(['$controllerProvider', x => x.register(clazz.$name, clazz)]);
    return clazz;
  };
  // Unwrapping
  if (input.constructor !== Array) {
    return func([])(input);
  } else {
    return func(input);
  }
}

export function Directive(clazz) {
  let func = dependencies => clazz => {
    clazz.$name = getUniqueName() + clazz.name;
    clazz.$inject = dependencies.map(stringOfClass);
    clazz.$registerOn = module =>
      module.directive(clazz.$name, clazz);
  }
  // Unwrapping
  if (input.constructor !== Array) {
    return func([])(input);
  } else {
    return func(input);
  }
}

// Extend Angular modules with `.use`
let origModuleCall = angular.module;
angular.module = function () {
  let module = origModuleCall.apply(angular, arguments);
  module.use = (...components) =>
    components.forEach(component => component.$registerOn(module));
  // Add in our module for default values
  module.requires.push(DI.getDefaultModuleName());
  // Extend Angular `.value` calls to process annotated values
  let origValueCall = module.value;
  module.value = function () {
    // Calling with annotated value class?
    if (arguments[0].constructor !== String) arguments[0] = arguments[0].$name;
    return origValueCall.apply(module, arguments);
  };
  return module;
};
<|endoftext|>


<commit_before>const isTravis = process.env.TRAVIS;
const isSaucelabs = process.argv.indexOf('--saucelabs') !== -1 || (isTravis && process.env.TRAVIS_PULL_REQUEST === 'false');

if (isSaucelabs && !process.env.SAUCE_USERNAME) {
  try {
    const credentials = require('./saucelabs.json');
    process.env.SAUCE_USERNAME = credentials.username;
    process.env.SAUCE_ACCESS_KEY = credentials.accessKey;
  } catch (err) {
    console.log('Please, create a valid "saucelabs.json" with your credentials.');
    process.exit(1);
  }
}

module.exports = function(config) {
  const cfg = {
    basePath: '',

    frameworks: ['jasmine'],

    files: [
        // For travis
        'node_modules/es6-shim/es6-shim.js',
        // paths loaded by Karma
        {pattern: 'node_modules/systemjs/dist/system.src.js', included: true, watched: false},
        {pattern: 'node_modules/angular2/bundles/angular2-polyfills.js', included: true, watched: false},
        {pattern: 'node_modules/rxjs/bundles/Rx.js', included: true, watched: false},
        {pattern: 'node_modules/angular2/bundles/angular2.js', included: true, watched: false},
        {pattern: 'node_modules/angular2/bundles/testing.dev.js', included: true, watched: false},
        {pattern: 'node_modules/tether/dist/js/tether.min.js', included: true, watched: false},
        {pattern: 'karma-shim.js', included: true, watched: true},

        // paths loaded via module imports
        {pattern: 'temp/**/*.js', included: false, watched: true},

        // paths to support debugging with source maps in dev tools
        {pattern: 'src/**/*.ts', included: false, watched: false},
        {pattern: 'temp/**/*.js.map', included: false, watched: false},

        // fixtures
        {pattern: 'test/fixtures/**', watched: false, included: false, served: true},
    ],

    proxies: {
      '/assets/icons/utility-sprite/svg/symbols.svg': '/base/test/fixtures/fake.svg',
      '/tether': '/base/node_modules/tether/dist/js/tether.min.js'
    },

    preprocessors: {
      'temp/**/*.js': ['sourcemap'],
      'temp/src/**/!(*spec|*mock).js': ['coverage'],
    },

    coverageReporter: {
      dir: 'coverage/',
      reporters: [{type: 'text-summary'}, {type: 'html'}],
    },

    reporters: isTravis ? ['dots'] : ['progress', 'coverage'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: [isTravis ? 'Firefox' : 'Chrome'],
    singleRun: false,
  };

  if (isSaucelabs) {
    cfg.customLaunchers =  require('./test/browser-providers');
    cfg.browsers = Object.keys(cfg.customLaunchers);
    cfg.reporters.push('saucelabs');
    cfg.sauceLabs = {
      tunnelIdentifier: 'ng-lightning',
      connectOptions: {
        logfile: './saucelabs.log',
      },
    };
    cfg.captureTimeout = 120000;
    cfg.browserNoActivityTimeout = 120000;
  }

  config.set(cfg);
};
<commit_msg>chore(build): user travis job number as identifier on Saucelabs<commit_after>const isTravis = process.env.TRAVIS;
const isSaucelabs = process.argv.indexOf('--saucelabs') !== -1 || (isTravis && process.env.TRAVIS_PULL_REQUEST === 'false');

if (isSaucelabs && !process.env.SAUCE_USERNAME) {
  try {
    const credentials = require('./saucelabs.json');
    process.env.SAUCE_USERNAME = credentials.username;
    process.env.SAUCE_ACCESS_KEY = credentials.accessKey;
  } catch (err) {
    console.log('Please, create a valid "saucelabs.json" with your credentials.');
    process.exit(1);
  }
}

module.exports = function(config) {
  const cfg = {
    basePath: '',

    frameworks: ['jasmine'],

    files: [
        // For travis
        'node_modules/es6-shim/es6-shim.js',
        // paths loaded by Karma
        {pattern: 'node_modules/systemjs/dist/system.src.js', included: true, watched: false},
        {pattern: 'node_modules/angular2/bundles/angular2-polyfills.js', included: true, watched: false},
        {pattern: 'node_modules/rxjs/bundles/Rx.js', included: true, watched: false},
        {pattern: 'node_modules/angular2/bundles/angular2.js', included: true, watched: false},
        {pattern: 'node_modules/angular2/bundles/testing.dev.js', included: true, watched: false},
        {pattern: 'node_modules/tether/dist/js/tether.min.js', included: true, watched: false},
        {pattern: 'karma-shim.js', included: true, watched: true},

        // paths loaded via module imports
        {pattern: 'temp/**/*.js', included: false, watched: true},

        // paths to support debugging with source maps in dev tools
        {pattern: 'src/**/*.ts', included: false, watched: false},
        {pattern: 'temp/**/*.js.map', included: false, watched: false},

        // fixtures
        {pattern: 'test/fixtures/**', watched: false, included: false, served: true},
    ],

    proxies: {
      '/assets/icons/utility-sprite/svg/symbols.svg': '/base/test/fixtures/fake.svg',
      '/tether': '/base/node_modules/tether/dist/js/tether.min.js'
    },

    preprocessors: {
      'temp/**/*.js': ['sourcemap'],
      'temp/src/**/!(*spec|*mock).js': ['coverage'],
    },

    coverageReporter: {
      dir: 'coverage/',
      reporters: [{type: 'text-summary'}, {type: 'html'}],
    },

    reporters: isTravis ? ['dots'] : ['progress', 'coverage'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: [isTravis ? 'Firefox' : 'Chrome'],
    singleRun: false,
  };

  if (isSaucelabs) {
    cfg.customLaunchers =  require('./test/browser-providers');
    cfg.browsers = Object.keys(cfg.customLaunchers);
    cfg.reporters.push('saucelabs');
    cfg.sauceLabs = {
      tunnelIdentifier: isTravis ? process.env.TRAVIS_JOB_NUMBER : 'ng-lightning',
      connectOptions: {
        logfile: './saucelabs.log',
      },
    };
    cfg.captureTimeout = 120000;
    cfg.browserNoActivityTimeout = 120000;
  }

  config.set(cfg);
};
<|endoftext|>


<commit_before>// Based on: https://github.com/cypress-io/cypress/issues/416#issuecomment-337400871
// Runs Cypress runner per integration test. Mitigates memory hogging issues.
// Once a Cypress version is released that clears renderer
// between tests this hack (entire file) can be removed.

const cypress = require('cypress')
const Promise = require('bluebird')

const glob = Promise.promisify(require('glob'))

const started = new Date()
let numFailed = 0
const summary = []

const SCRIPTS_FOLDER =  process.env.SCRIPTS_FOLDER || 'cypress/integration';

return glob(SCRIPTS_FOLDER + '/**/*', {
  nodir: true,
  realpath: true,
})
.tap((specs) => {
  console.log('Found ', specs.length, ' specs:\n\n', specs)
})
.each((spec) => {
  console.log('\nRunning spec:', spec)

  return cypress.run({
    spec: spec,
    config: {
      integrationFolder: SCRIPTS_FOLDER
    },
    env: {
      API_ROOT: process.env.API_ROOT,
      USERNAME_EMPLOYEE: process.env.USERNAME_EMPLOYEE,
      USERNAME_EMPLOYEE_PLUS: process.env.USERNAME_EMPLOYEE_PLUS,
      PASSWORD_EMPLOYEE: process.env.PASSWORD_EMPLOYEE,
      PASSWORD_EMPLOYEE_PLUS: process.env.PASSWORD_EMPLOYEE_PLUS
    }
  })
  .then((results) => {
    numFailed += results.totalFailed;
    summary.push({
      name: spec.split("/")[spec.split("/").length - 1 ],
      totalDuration: results.totalDuration,
      totalSuites: results.totalSuites,
      totalTests: results.totalTests,
      totalFailed: results.totalFailed,
      totalPassed: results.totalPassed,
      totalPending: results.totalPending,
      totalSkipped: results.totalSkipped
    })
  })
})
.then(() => {
  console.log('\n-----------------------------\n')
  console.log(`Cypress end to end tests summary:`)
  summary.forEach((item) => {
    console.log(`${item.name}\n
  - Total Suites: ${item.totalSuites}\n
  - Total Tests: ${item.totalTests}\n
  - Total Failed: ${item.totalFailed}\n
  - Total Passed: ${item.totalPassed}\n
  - Total Pending: ${item.totalPending}\n
  - Total Screenshots: ${item.totalScreenshots}\n
  - Total Duration: ${item.totalDuration/1000} seconds\n
  `)
  })
  console.log('\n-----------------------------\n')

  const duration = new Date() - started

  console.log('\n--All Done--\n')
  console.log('Total duration:', duration) // format this however you like
  console.log('Exiting with final code:', numFailed)

  process.exit(numFailed)
})
.catch((err) => {
  console.error(err)
  throw err
})
<commit_msg>DP-6835 improvements in the log layout<commit_after>// Based on: https://github.com/cypress-io/cypress/issues/416#issuecomment-337400871
// Runs Cypress runner per integration test. Mitigates memory hogging issues.
// Once a Cypress version is released that clears renderer
// between tests this hack (entire file) can be removed.

const cypress = require('cypress')
const Promise = require('bluebird')

const glob = Promise.promisify(require('glob'))

const started = new Date()
let numFailed = 0
const summary = []

const SCRIPTS_FOLDER =  process.env.SCRIPTS_FOLDER || 'cypress/integration';

return glob(SCRIPTS_FOLDER + '/**/*', {
  nodir: true,
  realpath: true,
})
.tap((specs) => {
  console.log('Found ', specs.length, ' specs:\n\n', specs)
})
.each((spec) => {
  console.log('\nRunning spec:', spec)

  return cypress.run({
    spec: spec,
    config: {
      integrationFolder: SCRIPTS_FOLDER
    },
    env: {
      API_ROOT: process.env.API_ROOT,
      USERNAME_EMPLOYEE: process.env.USERNAME_EMPLOYEE,
      USERNAME_EMPLOYEE_PLUS: process.env.USERNAME_EMPLOYEE_PLUS,
      PASSWORD_EMPLOYEE: process.env.PASSWORD_EMPLOYEE,
      PASSWORD_EMPLOYEE_PLUS: process.env.PASSWORD_EMPLOYEE_PLUS
    }
  })
  .then((results) => {
    numFailed += results.totalFailed;
    summary.push({
      name: spec.split("/")[spec.split("/").length - 1 ],
      totalDuration: results.totalDuration,
      totalSuites: results.totalSuites,
      totalTests: results.totalTests,
      totalFailed: results.totalFailed,
      totalPassed: results.totalPassed,
      totalPending: results.totalPending,
      totalSkipped: results.totalSkipped
    })
  })
})
.then(() => {
  console.log('\n-----------------------------')
  console.log(`Cypress end to end tests summary:`)
  summary.forEach((item) => {
    console.log(`\n${item.name}
  - Total Suites: ${item.totalSuites}
  - Total Tests: ${item.totalTests}
  - Total Failed: ${item.totalFailed}
  - Total Passed: ${item.totalPassed}
  - Total Pending: ${item.totalPending}
  - Total Skipped: ${item.totalSkipped}
  - Total Duration: ${item.totalDuration/1000} seconds
  `)
  })
  console.log('\n-----------------------------')

  const duration = new Date() - started

  console.log('\n--All Done--\n')
  console.log('Total duration:', duration) // format this however you like
  console.log('Exiting with final code (=total tests failed):', numFailed)
  console.log('\n-----------------------------\n')

  process.exit(numFailed)
})
.catch((err) => {
  console.error(err)
  throw err
})
<|endoftext|>


<commit_before>'use strict';

module.exports = {
	db: 'mongodb://' + (process.env.DB_1_PORT_27017_TCP_ADDR || 'localhost') + '/plmprofiles',
	assets: {
		lib: {
			css: [
				'public/lib/bootstrap/dist/css/bootstrap.min.css',
				'public/lib/bootstrap/dist/css/bootstrap-theme.min.css',
			],
			js: [
				'public/lib/angular/angular.min.js',
				'public/lib/angular-resource/angular-resource.js',
				'public/lib/angular-cookies/angular-cookies.js',
				'public/lib/angular-animate/angular-animate.js',
				'public/lib/angular-touch/angular-touch.js',
				'public/lib/angular-sanitize/angular-sanitize.js',
				'public/lib/angular-ui-router/release/angular-ui-router.min.js',
				'public/lib/angular-ui-utils/ui-utils.min.js',
				'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js'
			]
		},
		css: 'public/dist/application.min.css',
		js: 'public/dist/application.min.js'
	},
  mailer: {
    from: process.env.MAILER_FROM || 'MAILER_FROM',
    options: {
      service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
      auth: {
        user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
        pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
      }
    }
  }
};
<commit_msg>Update config to be compatible with new docker-compose<commit_after>'use strict';

module.exports = {
	db: 'mongodb://' + (process.env.DB_ADDR || 'localhost') + '/plmprofiles',
	assets: {
		lib: {
			css: [
				'public/lib/bootstrap/dist/css/bootstrap.min.css',
				'public/lib/bootstrap/dist/css/bootstrap-theme.min.css',
			],
			js: [
				'public/lib/angular/angular.min.js',
				'public/lib/angular-resource/angular-resource.js',
				'public/lib/angular-cookies/angular-cookies.js',
				'public/lib/angular-animate/angular-animate.js',
				'public/lib/angular-touch/angular-touch.js',
				'public/lib/angular-sanitize/angular-sanitize.js',
				'public/lib/angular-ui-router/release/angular-ui-router.min.js',
				'public/lib/angular-ui-utils/ui-utils.min.js',
				'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js'
			]
		},
		css: 'public/dist/application.min.css',
		js: 'public/dist/application.min.js'
	},
  mailer: {
    from: process.env.MAILER_FROM || 'MAILER_FROM',
    options: {
      service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
      auth: {
        user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
        pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
      }
    }
  }
};
<|endoftext|>


<commit_before>var fs = require('fs')
  , test = require('tape')
  , logRotate = require('../');

test('rotates based on file size option', function(t) {
  var file = __dirname+"/test.log" +Date.now();
  var s = logRotate({ file: file, size: 600 });

  var bytes = 0;
  var done = 100;
  var files = [];

  s.on('finish',function() {
    t.equals(files.length, 2, 'should have 2 files');
    // TODO clean up files
    t.end();
  })

  s.on('rotated', function(file) {
    files.push(file);
  });

  var data;
  data = setInterval(function() {
    var chunk = Date.now() +"\n";// 14 bytes
    s.write(chunk);
    bytes += chunk.length;

    if (!--done) {
      clearInterval(data);
      s.end();
    }
  }, 1);
});
<commit_msg>add test for kept logs<commit_after>var fs = require('fs')
  , test = require('tape')
  , path = require('path')
  , logRotate = require('../');

function fileName() { return __dirname +"/test.log_"+ Date.now(); }
function writes(s, ct) {
  var done = ct || 100
    , inv;

  inv = setInterval(function() {
    var chunk = Date.now() + "\n"; // 14 bytes
    s.write(chunk);
    if (! --done) {
      clearInterval(inv);
      s.end();
    }
  }, 1);
}

test('rotates based on file size option', function(t) {
  var files = []
    , file = fileName();

  var s = logRotate({ file: file, size: 600 });

  s.on('finish', function() {
    t.equals(files.length, 2, 'should have 2 files');
    // TODO clean up files
    t.end();
  })

  s.on('rotated', function(file) {
    files.push(file);
  });

  // start writing
  writes(s, 100);
});

test('keeps the appropriate number of rotated logs', function(t) {
  var file = fileName()
    , s = logRotate({ file: file, size: 600, keep: 5 });

  s.on('finish', function() {
    console.log('finished');
    fs.readdir(__dirname, function(err, files) {
      var kept = 0;
      for (var i = 0, l = files.length; i < l; i++) {
        if (files[i].indexOf(path.basename(file)) !== -1) kept++;
      }

      t.equals(kept, 5, 'should keep 5 files');
      // TODO clean up files
      t.end();
    });
  })

  // start writing
  writes(s, 200);
});
<|endoftext|>


<commit_before>Editors.controller('testModalCtrl', ['$scope', function($scope) {
    /*$scope.assessmentVariable = {
        id: null,
        answerId: null,
        measureId: null,
        measureTypeId: null,
        typeId: null,
        name: null,
        displayName: null,
        getName: function () {
            return (Object.isDefined(this.name))? this.name : (Object.isDefined(this.displayName)? this.displayName: 'var' + this.id);
        },
        setType: function () {
            switch (this.typeId) {
                case 1:
                    this.type = "Measure";
                    break;
                case 2:
                    this.type = "Measure Answer"
                    break;
                case 3:
                    this.type = "Custom";
                    break;
                case 4:
                    this.type = "Formula";
                    break;
                default:
                    this.type = "Other";
            }
        },
        toString: function () {
            return "AssessmentVariable [id: " + this.id +
                ", answerId: " + this.answerId +
                ", measureId: " + this.measureId +
                ", measureTypeId: " + this.measureTypeId +
                ", typeId: " + this.typeId +
                ", name: " + this.name +
                ", displayName: " + this.displayName + "]";
        }
    };*/

    // Passing in true to third param of $watch for deep collection checking
    $scope.$watch('assessmentVariable', function(newValue, oldValue) {
        if(newValue === oldValue) {
            console.log("Inside testModalCtrl: assessmentVariable: newValue === oldValue:\n" + oldValue.toString());
        } else {
            console.log('Inside testModalCtrl: assessmentVariable newValue: ', newValue.toString());
            console.log('Inside testModalCtrl: assessmentVariable oldValue: ', oldValue.toString());
        }
    }, true);
}]);
Editors.controller('templateEditorController', ['$scope', '$state', '$stateParams', '$modal', 'AssessmentVariableService', 'template', function($scope, $state, $stateParams, $modal, AssessmentVariableService, template) {

    console.log("In templateEditorController");

    $scope.template = template;
    $scope.hasChanged = false;
    $scope.assessmentVariables = [];

    //TODO: change $stateParams to be more abstract (i.e. use relObj, relObjName, relObjType) so this can be reused for battery templates
    $scope.relatedObj = {
        id: $stateParams.selectedSurveyId,
        name: decodeURIComponent($stateParams.selectedSurveyName),
        type: "module"
    };

    if ($scope.relatedObj.type === "module") {
        $scope.assessmentVariables = AssessmentVariableService.query({surveyId: $scope.relatedObj.id})/*.then(function(assessmentVariables) {
            $scope.assessmentVariables = assessmentVariables;
        });*/
    }

    $scope.save = function () {
        console.log("Save clicked");

        $scope.template.saveFor($scope.relatedObj).then(function (response) {
            $scope.done(true);
        });
    };

    $scope.done = function (wasSaved) {
        console.log("Cancel edit");
        if ($scope.relatedObj.type == "module") {
            var stateParams = angular.copy($stateParams);
            if (wasSaved) {
                stateParams.saved = wasSaved;
            }
            $state.go('modules.templates', stateParams);
        }
    };

    /**
     * @param parent is optional. If undefined then the block is added to the bottom of the template.
     */
    $scope.addBlock = function (parentScope) {
        if (Object.isDefined(parentScope)) {
            var parent = parentScope.$modelValue;
            console.log("Add block under parent block: " + parent.title);
        }
        else {
            console.log("Add block to bottom of template");
        }
        $scope.templateChanged();
    };

    $scope.removeBlock = function (blockScope) {
        var block = blockScope.$modelValue;
        console.log("remove block: " + block.title);
        $scope.templateChanged();
    };

    $scope.editBlock = function (blockScope) {
        var block = blockScope.$modelValue;
        console.log("edit block: " + block.title);
    };

    //ng-tree options
    $scope.treeOptions = {

    };

    //this could use $watch but this might be overkill for large templates since there are
    //only a couple of places that a change occurs and afer one has happened we don't care about new updates
    $scope.templateChanged = function () {
        console.log("template changed");
        $scope.hasChanged = true;
    };

	$scope.deleteBlock = function (index) {
		$scope.template.blocks.splice(index, 1);
	};

	$scope.updateBlock = function(selectedBlock){

		// Defaulting to hasChanged for now
		$scope.templateChanged();

		// Create the modal
		var modalInstance = $modal.open({
			templateUrl: 'resources/editors/views/templates/templateblockmodal.html',
            scope: $scope,
            resolve: {
	            template:  function() {
		            return $scope.template;
	            }
			},
			controller: function($scope, $modalInstance, template) {

				$scope.templateName = template.name;

				// Copy the selected or new block so that potential changes in modal don't update object in page
				$scope.block = (selectedBlock) ? angular.copy(selectedBlock) : {};

				// Dismiss modal
				$scope.cancel = function() {
					$modalInstance.dismiss('cancel');
				};

				// Close modal and pass updated block to the page
				$scope.close = function() {

					if (selectedBlock) {
						selectedBlock = $scope.block;
					} else {
						template.blocks.push($scope.block)
					}
					$modalInstance.close();
				};
			}

		});
	};

}]);
<commit_msg>#660 - Integrated the selected assessment variable with the editor; as this template needs the controller in order for the 2-way binding to work.  Removed unnecessary comments.<commit_after>Editors.controller('testModalCtrl', ['$scope', function($scope) {
}]);
Editors.controller('templateEditorController', ['$scope', '$state', '$stateParams', '$modal', 'AssessmentVariableService', 'template', function($scope, $state, $stateParams, $modal, AssessmentVariableService, template) {

    console.log("In templateEditorController");

    $scope.template = template;
    $scope.hasChanged = false;
    $scope.assessmentVariables = [];

    //TODO: change $stateParams to be more abstract (i.e. use relObj, relObjName, relObjType) so this can be reused for battery templates
    $scope.relatedObj = {
        id: $stateParams.selectedSurveyId,
        name: decodeURIComponent($stateParams.selectedSurveyName),
        type: "module"
    };

    if ($scope.relatedObj.type === "module") {
        $scope.assessmentVariables = AssessmentVariableService.query({surveyId: $scope.relatedObj.id})/*.then(function(assessmentVariables) {
            $scope.assessmentVariables = assessmentVariables;
        });*/
    }

    $scope.save = function () {
        console.log("Save clicked");

        $scope.template.saveFor($scope.relatedObj).then(function (response) {
            $scope.done(true);
        });
    };

    $scope.done = function (wasSaved) {
        console.log("Cancel edit");
        if ($scope.relatedObj.type == "module") {
            var stateParams = angular.copy($stateParams);
            if (wasSaved) {
                stateParams.saved = wasSaved;
            }
            $state.go('modules.templates', stateParams);
        }
    };

    /**
     * @param parent is optional. If undefined then the block is added to the bottom of the template.
     */
    $scope.addBlock = function (parentScope) {
        if (Object.isDefined(parentScope)) {
            var parent = parentScope.$modelValue;
            console.log("Add block under parent block: " + parent.title);
        }
        else {
            console.log("Add block to bottom of template");
        }
        $scope.templateChanged();
    };

    $scope.removeBlock = function (blockScope) {
        var block = blockScope.$modelValue;
        console.log("remove block: " + block.title);
        $scope.templateChanged();
    };

    $scope.editBlock = function (blockScope) {
        var block = blockScope.$modelValue;
        console.log("edit block: " + block.title);
    };

    //ng-tree options
    $scope.treeOptions = {

    };

    //this could use $watch but this might be overkill for large templates since there are
    //only a couple of places that a change occurs and afer one has happened we don't care about new updates
    $scope.templateChanged = function () {
        console.log("template changed");
        $scope.hasChanged = true;
    };

	$scope.deleteBlock = function (index) {
		$scope.template.blocks.splice(index, 1);
	};

	$scope.updateBlock = function(selectedBlock){

		// Defaulting to hasChanged for now
		$scope.templateChanged();

		// Create the modal
		var modalInstance = $modal.open({
			templateUrl: 'resources/editors/views/templates/templateblockmodal.html',
            scope: $scope,
            resolve: {
	            template:  function() {
		            return $scope.template;
	            }
			},
			controller: function($scope, $modalInstance, template) {

				$scope.templateName = template.name;

				// Copy the selected or new block so that potential changes in modal don't update object in page
				$scope.block = (selectedBlock) ? angular.copy(selectedBlock) : {};

				// Dismiss modal
				$scope.cancel = function() {
					$modalInstance.dismiss('cancel');
				};

				// Close modal and pass updated block to the page
				$scope.close = function() {

					if (selectedBlock) {
						selectedBlock = $scope.block;
					} else {
						template.blocks.push($scope.block)
					}
					$modalInstance.close();
				};
			}

		});
	};

}]);
<|endoftext|>


<commit_before>// TODO: We do not consider forks and joins here: We need to

var errors = require('../errors')

module.exports = function filterSafeDeletes (osm, batch, cb) {
  // A mapping of ids of ways and relations to
  // the ids of elements that they reference
  var pendingRefs = {}
  // A list of all references to each element within the changeset itself
  // It seems possible that a changeset could modify an element to reference
  // an element that was not previously referenced, and is then deleted
  // later in the changeset. This logic checks for that
  var reverseRefs = {}
  var filtered = []
  var inUseErrors = []
  var pending = batch.length

  batch.forEach(function (change) {
    var id = change.id
    if (change.action !== 'delete' && change.type !== 'node') {
      // Remove previous reverse refs to this element
      ;(pendingRefs[id] || []).forEach(function (ref) {
        reverseRefs[ref] = (reverseRefs[ref] || []).filter(function (ref) {
          return id !== ref
        })
      })
      // If a way or relation is modified, keep a list of the elements
      // they reference, since this overrides what is in the db
      if (change.type === 'way') {
        pendingRefs[id] = change.nodes || []
      } else if (change.type === 'relation') {
        pendingRefs[id] = change.members
          ? change.members.map(function (m) { return m.ref }) : []
      }
      // Add new reverse refs
      ;(pendingRefs[id] || []).forEach(function (ref) {
        reverseRefs[ref] = reverseRefs[ref] || []
        reverseRefs[ref].push(id)
      })
    }
    // If action is not delete it is always included
    if (change.action !== 'delete') {
      filtered.push(change)
      return onCheck()
    }

    /** We only get here for change.action === 'delete' */

    // If a way or relation that appeared in the create or modified block
    // is subsequently deleted, we can remove the references to it
    if (change.type !== 'node') {
      // Remove reverse refs to this element
      ;(pendingRefs[id] || []).forEach(function (ref) {
        reverseRefs[ref] = (reverseRefs[ref] || []).filter(function (ref) {
          return id !== ref
        })
      })
      pendingRefs[id] = []
    }

    // Check whether the element to be deleted is referenced by any
    // existing ways or relations in the database
    refList(osm, id, function (err, refs) {
      if (err) return cb(err)
      // Update the refs from the database with pending refs from the changeset
      var mergedRefs = refs.filter(function (ref) {
        // If the element is referenced in the database by an element
        // that is earlier in the changeset, what is important is
        // whether the new version of the element still references it
        if (pendingRefs[ref.id]) {
          return pendingRefs[ref.id].indexOf(id) > -1
        } else {
          return true
        }
      })
      if (mergedRefs.length || reverseRefs[id] && reverseRefs[id].length) {
        // If there are any references in mergedRefs, then element is in use
        // and cannot be deleted without ...
        if (change.ifUnused) {
          // If the ifUnused prop is set, silently skip and continue
          onCheck()
        } else {
          refs.forEach(function (ref) {
            inUseErrors.push({id: id, usedBy: ref.id})
          })
          onCheck()
        }
      } else {
        // If the element is not referenced anywhere, we can safely delete it
        filtered.push(change)
        onCheck()
      }
    })
  })

  function onCheck () {
    if (--pending > 0) return
    if (!inUseErrors.length) return cb(null, filtered)
    var msg = ''
    inUseErrors.forEach(function (inUse) {
      msg += 'Element #' + inUse.id + ' is still used by element #' + inUse.usedBy + '.'
    })
    cb(new errors.InUse(msg))
  }
}

// work-around to ensure that reference counts are accurate for ifUnused calculation
// TODO: Why do we need this?
function refList (osm, id, cb) {
  var res = []
  osm.core.api.refs.get(id, function (err, refs) {
    if (err) return cb(err)
    var pending = 1
    refs.forEach(function (r) {
      pending++
      osm.get(r.id, function (err, docs) {
        if (err && !notFound(err)) return cb(err)
        var contained = false
        docs.forEach(function (d) {
          if (!d) return
          if (d.refs && d.refs.indexOf(id) >= 0) {
            contained = true
          } else if (d.nodes && d.nodes.indexOf(id) >= 0) {
            contained = true
          } else if (d.members && d.members.map(refid).indexOf(id) >= 0) {
            contained = true
          }
        })
        if (contained) res.push(r)
        if (--pending === 0) cb(null, res)
      })
    })
    if (--pending === 0) cb(null, res)
  })
}

function refid (m) { return m.ref || m.id }

function notFound (err) {
  return err && (/^notfound/i.test(err) || err.notFound)
}
<commit_msg>use public osm.refs instead of osm.core.api.refs.get<commit_after>// TODO: We do not consider forks and joins here: We need to

var errors = require('../errors')

module.exports = function filterSafeDeletes (osm, batch, cb) {
  // A mapping of ids of ways and relations to
  // the ids of elements that they reference
  var pendingRefs = {}
  // A list of all references to each element within the changeset itself
  // It seems possible that a changeset could modify an element to reference
  // an element that was not previously referenced, and is then deleted
  // later in the changeset. This logic checks for that
  var reverseRefs = {}
  var filtered = []
  var inUseErrors = []
  var pending = batch.length

  batch.forEach(function (change) {
    var id = change.id
    if (change.action !== 'delete' && change.type !== 'node') {
      // Remove previous reverse refs to this element
      ;(pendingRefs[id] || []).forEach(function (ref) {
        reverseRefs[ref] = (reverseRefs[ref] || []).filter(function (ref) {
          return id !== ref
        })
      })
      // If a way or relation is modified, keep a list of the elements
      // they reference, since this overrides what is in the db
      if (change.type === 'way') {
        pendingRefs[id] = change.nodes || []
      } else if (change.type === 'relation') {
        pendingRefs[id] = change.members
          ? change.members.map(function (m) { return m.ref }) : []
      }
      // Add new reverse refs
      ;(pendingRefs[id] || []).forEach(function (ref) {
        reverseRefs[ref] = reverseRefs[ref] || []
        reverseRefs[ref].push(id)
      })
    }
    // If action is not delete it is always included
    if (change.action !== 'delete') {
      filtered.push(change)
      return onCheck()
    }

    /** We only get here for change.action === 'delete' */

    // If a way or relation that appeared in the create or modified block
    // is subsequently deleted, we can remove the references to it
    if (change.type !== 'node') {
      // Remove reverse refs to this element
      ;(pendingRefs[id] || []).forEach(function (ref) {
        reverseRefs[ref] = (reverseRefs[ref] || []).filter(function (ref) {
          return id !== ref
        })
      })
      pendingRefs[id] = []
    }

    // Check whether the element to be deleted is referenced by any
    // existing ways or relations in the database
    refList(osm, id, function (err, refs) {
      if (err) return cb(err)
      // Update the refs from the database with pending refs from the changeset
      var mergedRefs = refs.filter(function (ref) {
        // If the element is referenced in the database by an element
        // that is earlier in the changeset, what is important is
        // whether the new version of the element still references it
        if (pendingRefs[ref.id]) {
          return pendingRefs[ref.id].indexOf(id) > -1
        } else {
          return true
        }
      })
      if (mergedRefs.length || reverseRefs[id] && reverseRefs[id].length) {
        // If there are any references in mergedRefs, then element is in use
        // and cannot be deleted without ...
        if (change.ifUnused) {
          // If the ifUnused prop is set, silently skip and continue
          onCheck()
        } else {
          refs.forEach(function (ref) {
            inUseErrors.push({id: id, usedBy: ref.id})
          })
          onCheck()
        }
      } else {
        // If the element is not referenced anywhere, we can safely delete it
        filtered.push(change)
        onCheck()
      }
    })
  })

  function onCheck () {
    if (--pending > 0) return
    if (!inUseErrors.length) return cb(null, filtered)
    var msg = ''
    inUseErrors.forEach(function (inUse) {
      msg += 'Element #' + inUse.id + ' is still used by element #' + inUse.usedBy + '.'
    })
    cb(new errors.InUse(msg))
  }
}

// work-around to ensure that reference counts are accurate for ifUnused calculation
// TODO: Why do we need this?
function refList (osm, id, cb) {
  var res = []
  osm.refs(id, function (err, refs) {
    if (err) return cb(err)
    var pending = 1
    refs.forEach(function (r) {
      pending++
      osm.get(r.id, function (err, docs) {
        if (err && !notFound(err)) return cb(err)
        var contained = false
        docs.forEach(function (d) {
          if (!d) return
          if (d.refs && d.refs.indexOf(id) >= 0) {
            contained = true
          } else if (d.nodes && d.nodes.indexOf(id) >= 0) {
            contained = true
          } else if (d.members && d.members.map(refid).indexOf(id) >= 0) {
            contained = true
          }
        })
        if (contained) res.push(r)
        if (--pending === 0) cb(null, res)
      })
    })
    if (--pending === 0) cb(null, res)
  })
}

function refid (m) { return m.ref || m.id }

function notFound (err) {
  return err && (/^notfound/i.test(err) || err.notFound)
}
<|endoftext|>


<commit_before>var
  bify = require('browserify'),
  rs = require('readable-stream'),
  util = require('util'),
  pathmodify = require('../'),
  path = require('path'),
  assert = require('assert'),
  vm = require('vm'),
  // Like core paths module, but tailored for the purposes of these tests.
  tests_path = {},
  b;

tests_path.join = function join () {
  return path.join.apply(path, arguments).replace('\\', this.sep);
};

// Transform stream to test programatic transforms.
function Xform () {
  rs.Transform.apply(this, arguments);
}

util.inherits(Xform, rs.Transform);

Xform.prototype._transform = function (chunk, enc, cb) {
  this.push(chunk.toString().replace("lowercase", "UPPERCASE"));
  cb();
};

describe('Plugin', function () {
  var
    bify_opts,
    paths = {};

  bify_opts =  {
    entries: ['./src/entry'],
    basedir: __dirname,
  };

  paths.sep = '/';
  tests_path.sep = paths.sep;

  paths.src = tests_path.join(__dirname, 'src');
  paths.prefix = 'app';
  paths.subdir = 'a';
  paths.basename = paths.subdir;
  paths.ext = '.js';
  paths.require_id = tests_path.join(
    paths.prefix, paths.subdir, paths.basename
  );
  paths.alias_id = tests_path.join(paths.src, paths.subdir, paths.basename + paths.ext);

  function aliaser (input) {
    var
      prefix = [paths.prefix, paths.sep].join(''),
      output = {};

    if (input.id.indexOf(prefix) === 0) {
      output.id = tests_path.join(
        paths.src,
        input.id.substr(prefix.length)
      );

      if (input.opts && input.opts.filename) {
        output.id = './' + path.relative(
          path.dirname(input.opts.filename),
          output.id
        );
      }

      output.expose = "whatever";
    }
    return output;
  }
  // aliaser

  function run_test (plugin_opts, opts, done) {
    bify(bify_opts)
      .plugin(pathmodify(), plugin_opts)
      .transform(function (file) { return new Xform; })
      .bundle(function (err, src) {
        if (err) throw err;

        var c = {};
        vm.runInNewContext(src.toString(), c);

        if (opts.require_id) {
          assert.equal(
            c.require(opts.require_id),
            'UPPERCASE ' + paths.require_id + paths.ext
          );
        }

        done();
      });
  }
  // run_test

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via function, expose as 'whatever', and apply programmatic transform.",
    function (done) {
      run_test({
        mods: [aliaser]
      }, {require_id: 'whatever'}, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `id` type modification, expose as 'app/a/a' via bool, and apply programmatic transform.",
    function (done) {
      var opts = {
        require_id: tests_path.join(paths.prefix, paths.subdir, paths.basename)
      };
      run_test({
        mods: [pathmodify.mod.id(
          opts.require_id,
          paths.alias_id,
          true
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `id` type modification, expose as 'whatever' via string, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: 'whatever'};
      run_test({
        mods: [pathmodify.mod.id(
          paths.require_id,
          paths.alias_id,
          opts.require_id
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `id` type modification with function replacement, expose as 'whatever' via string, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: 'whatever'};
      run_test({
        mods: [pathmodify.mod.id(
          paths.require_id,
          function (rec) {
            assert.notStrictEqual(rec, undefined);
            assert.strictEqual(typeof rec.id, 'string');
            assert.ok(rec.id.length > 0);

            return {id: tests_path.join(
              paths.src, paths.subdir, paths.basename + paths.ext
            )};
          },
          opts.require_id
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `id` type modification, expose as 'whatever' via function, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: 'whatever'};
      run_test({
        mods: [pathmodify.mod.id(
          paths.require_id,
          paths.alias_id,
          function (rec, alias) {
            assert.notStrictEqual(rec, undefined);
            assert.strictEqual(typeof rec.id, 'string');
            assert.ok(rec.id.length > 0);

            assert.notStrictEqual(alias, undefined);
            assert.strictEqual(typeof alias.id, 'string');
            assert.ok(alias.id.length > 0);

            return opts.require_id;
          }
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `dir` type modification, expose as 'app/a/a' via bool, and apply programmatic transform.",
    function (done) {
      var
        expose_prefix = 'whatever',
        opts = {
          require_id: tests_path.join(
            paths.prefix,
            paths.subdir,
            paths.basename
          ),
        };

      run_test({
        mods: [pathmodify.mod.dir(
          paths.prefix,
          paths.src,
          true
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `dir` type modification, expose as 'whatever/a/a' via function, and apply programmatic transform.",
    function (done) {
      var
        expose_prefix = 'whatever',
        opts = {
          require_id: tests_path.join(
            expose_prefix,
            paths.subdir,
            paths.basename
          ),
        };

      run_test({
        mods: [pathmodify.mod.dir(
          paths.prefix,
          paths.src,
          function (rec, alias) {
            return tests_path.join(
              expose_prefix,
              rec.id.substr(paths.prefix.length)
            );
          }
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `dir` type modification with function replacement, expose as 'app/a/a' via bool, and apply programmatic transform.",
    function (done) {
      var
        expose_prefix = 'whatever',
        opts = {
          require_id: tests_path.join(
            paths.prefix,
            paths.subdir,
            paths.basename
          ),
        };

      run_test({
        mods: [pathmodify.mod.dir(
          paths.prefix,
          function (rec) {
            assert.notStrictEqual(rec, undefined);
            assert.strictEqual(typeof rec.id, 'string');
            assert.ok(rec.id.length > 0);

            return {id: tests_path.join(
              paths.src, paths.subdir, paths.basename + paths.ext
            )};
          },
          true
        )]
      }, opts, done);
    }
  );

  var from_re = /^app\/(a\/a)$/;

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `re` type modification, expose as 'app/a/a' via bool, and apply programmatic transform.",
    function (done) {
      var opts = {
        require_id: tests_path.join(paths.prefix, paths.subdir, paths.basename)
      };
      run_test({
        mods: [pathmodify.mod.re(
          from_re,
          tests_path.join(paths.src, '$1' + paths.ext),
          true
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `re` type modification, expose as 'whatever' via string, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: 'whatever'};
      run_test({
        mods: [pathmodify.mod.re(
          from_re,
          tests_path.join(paths.src, '$1' + paths.ext),
          opts.require_id
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `re` type modification with function replacement, expose as 'whatever' via string, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: 'whatever'};
      run_test({
        mods: [pathmodify.mod.re(
          from_re,
          function (rec, opts) {
            assert.notStrictEqual(rec, undefined);
            assert.strictEqual(typeof rec.id, 'string');
            assert.ok(rec.id.length > 0);

            return {id: tests_path.join(
              paths.src, opts.matches[1] + paths.ext
            )};
          },
          opts.require_id
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `re` type modification, expose as 'whatever' via function, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: 'whatever'};
      run_test({
        mods: [pathmodify.mod.re(
          from_re,
          tests_path.join(paths.src, '$1' + paths.ext),
          function (rec, alias) {
            assert.notStrictEqual(rec, undefined);
            assert.strictEqual(typeof rec.id, 'string');
            assert.ok(rec.id.length > 0);

            assert.notStrictEqual(alias, undefined);
            assert.strictEqual(typeof alias.id, 'string');
            assert.ok(alias.id.length > 0);

            return opts.require_id;
          }
        )]
      }, opts, done);
    }
  );

  it(
    "Should reset `rec` props for each iteration of the mods loop.",
    function (done) {
      var opts = {};
      run_test({
        mods: [
          function (rec, opts) {
            rec.id = 'bogus';
          },
          pathmodify.mod.id(paths.require_id, function (rec) {
            assert.strictEqual(rec.id, paths.require_id);

            return {id: tests_path.join(
              paths.src, paths.subdir, paths.basename + paths.ext
            )};
          })
        ]
      }, opts, done);
    }
  );

  it(
    "Should iterate mods loop until an alias is emitted.",
    function (done) {
      var
        opts = {},
        i = 0;
      run_test({
        mods: [
          // Matches from but doesn't modify so shouldn't terminate loop.
          pathmodify.mod.re(from_re, function (rec) {}),

          // Should be iterated to and emit alias.
          pathmodify.mod.re(
            from_re,
            tests_path.join(paths.src, '$1' + paths.ext)
          )
        ]
      }, opts, done);
    }
  );
});
<commit_msg>Add failing test.<commit_after>var
  bify = require('browserify'),
  rs = require('readable-stream'),
  util = require('util'),
  pathmodify = require('../'),
  path = require('path'),
  assert = require('assert'),
  vm = require('vm'),
  // Like core paths module, but tailored for the purposes of these tests.
  tests_path = {},
  b;

tests_path.join = function join () {
  return path.join.apply(path, arguments).replace('\\', this.sep);
};

// Transform stream to test programatic transforms.
function Xform () {
  rs.Transform.apply(this, arguments);
}

util.inherits(Xform, rs.Transform);

Xform.prototype._transform = function (chunk, enc, cb) {
  this.push(chunk.toString().replace("lowercase", "UPPERCASE"));
  cb();
};

describe('Plugin', function () {
  var
    bify_opts,
    paths = {};

  bify_opts =  {
    entries: ['./src/entry'],
    basedir: __dirname,
  };

  paths.sep = '/';
  tests_path.sep = paths.sep;

  paths.src = tests_path.join(__dirname, 'src');
  paths.prefix = 'app';
  paths.subdir = 'a';
  paths.basename = paths.subdir;
  paths.ext = '.js';
  paths.require_id = tests_path.join(
    paths.prefix, paths.subdir, paths.basename
  );
  paths.alias_id = tests_path.join(paths.src, paths.subdir, paths.basename + paths.ext);

  function aliaser (input) {
    var
      prefix = [paths.prefix, paths.sep].join(''),
      output = {};

    if (input.id.indexOf(prefix) === 0) {
      output.id = tests_path.join(
        paths.src,
        input.id.substr(prefix.length)
      );

      if (input.opts && input.opts.filename) {
        output.id = './' + path.relative(
          path.dirname(input.opts.filename),
          output.id
        );
      }

      output.expose = "whatever";
    }
    return output;
  }
  // aliaser

  function run_test (plugin_opts, opts, done) {
    bify(bify_opts)
      .plugin(pathmodify(), plugin_opts)
      .transform(function (file) { return new Xform; })
      .bundle(function (err, src) {
        if (err) throw err;

        var c = {};
        vm.runInNewContext(src.toString(), c);

        if (opts.require_id) {
          assert.equal(
            c.require(opts.require_id),
            'UPPERCASE ' + paths.require_id + paths.ext
          );
        }

        done();
      });
  }
  // run_test

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via function, expose as 'whatever', and apply programmatic transform.",
    function (done) {
      run_test({
        mods: [aliaser]
      }, {require_id: 'whatever'}, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `id` type modification, expose as 'app/a/a' via bool, and apply programmatic transform.",
    function (done) {
      var opts = {
        require_id: tests_path.join(paths.prefix, paths.subdir, paths.basename)
      };
      run_test({
        mods: [pathmodify.mod.id(
          opts.require_id,
          paths.alias_id,
          true
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `id` type modification, expose as 'whatever' via string, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: 'whatever'};
      run_test({
        mods: [pathmodify.mod.id(
          paths.require_id,
          paths.alias_id,
          opts.require_id
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `id` type modification with function replacement, expose as 'whatever' via string, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: 'whatever'};
      run_test({
        mods: [pathmodify.mod.id(
          paths.require_id,
          function (rec) {
            assert.notStrictEqual(rec, undefined);
            assert.strictEqual(typeof rec.id, 'string');
            assert.ok(rec.id.length > 0);

            return {id: tests_path.join(
              paths.src, paths.subdir, paths.basename + paths.ext
            )};
          },
          opts.require_id
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `id` type modification, expose as 'whatever' via function, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: 'whatever'};
      run_test({
        mods: [pathmodify.mod.id(
          paths.require_id,
          paths.alias_id,
          function (rec, alias) {
            assert.notStrictEqual(rec, undefined);
            assert.strictEqual(typeof rec.id, 'string');
            assert.ok(rec.id.length > 0);

            assert.notStrictEqual(alias, undefined);
            assert.strictEqual(typeof alias.id, 'string');
            assert.ok(alias.id.length > 0);

            return opts.require_id;
          }
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `dir` type modification, expose as 'app/a/a' via bool, and apply programmatic transform.",
    function (done) {
      var
        expose_prefix = 'whatever',
        opts = {
          require_id: tests_path.join(
            paths.prefix,
            paths.subdir,
            paths.basename
          ),
        };

      run_test({
        mods: [pathmodify.mod.dir(
          paths.prefix,
          paths.src,
          true
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `dir` type modification, expose as 'whatever/a/a' via function, and apply programmatic transform.",
    function (done) {
      var
        expose_prefix = 'whatever',
        opts = {
          require_id: tests_path.join(
            expose_prefix,
            paths.subdir,
            paths.basename
          ),
        };

      run_test({
        mods: [pathmodify.mod.dir(
          paths.prefix,
          paths.src,
          function (rec, alias) {
            return tests_path.join(
              expose_prefix,
              rec.id.substr(paths.prefix.length)
            );
          }
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `dir` type modification with function replacement, expose as 'app/a/a' via bool, and apply programmatic transform.",
    function (done) {
      var
        expose_prefix = 'whatever',
        opts = {
          require_id: tests_path.join(
            paths.prefix,
            paths.subdir,
            paths.basename
          ),
        };

      run_test({
        mods: [pathmodify.mod.dir(
          paths.prefix,
          function (rec) {
            assert.notStrictEqual(rec, undefined);
            assert.strictEqual(typeof rec.id, 'string');
            assert.ok(rec.id.length > 0);

            return {id: tests_path.join(
              paths.src, paths.subdir, paths.basename + paths.ext
            )};
          },
          true
        )]
      }, opts, done);
    }
  );

  var from_re = /^app\/(a\/a)$/;

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `re` type modification, expose as 'app/a/a' via bool, and apply programmatic transform.",
    function (done) {
      var opts = {
        require_id: tests_path.join(paths.prefix, paths.subdir, paths.basename)
      };
      run_test({
        mods: [pathmodify.mod.re(
          from_re,
          tests_path.join(paths.src, '$1' + paths.ext),
          true
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `re` type modification, expose as 'whatever' via string, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: 'whatever'};
      run_test({
        mods: [pathmodify.mod.re(
          from_re,
          tests_path.join(paths.src, '$1' + paths.ext),
          opts.require_id
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `re` type modification with function replacement, expose as 'whatever' via string, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: 'whatever'};
      run_test({
        mods: [pathmodify.mod.re(
          from_re,
          function (rec, opts) {
            assert.notStrictEqual(rec, undefined);
            assert.strictEqual(typeof rec.id, 'string');
            assert.ok(rec.id.length > 0);

            return {id: tests_path.join(
              paths.src, opts.matches[1] + paths.ext
            )};
          },
          opts.require_id
        )]
      }, opts, done);
    }
  );

  it(
    "Should resolve 'app/a/a' as 'src/a/a.js' via `re` type modification, expose as 'whatever' via function, and apply programmatic transform.",
    function (done) {
      var opts = {require_id: 'whatever'};
      run_test({
        mods: [pathmodify.mod.re(
          from_re,
          tests_path.join(paths.src, '$1' + paths.ext),
          function (rec, alias) {
            assert.notStrictEqual(rec, undefined);
            assert.strictEqual(typeof rec.id, 'string');
            assert.ok(rec.id.length > 0);

            assert.notStrictEqual(alias, undefined);
            assert.strictEqual(typeof alias.id, 'string');
            assert.ok(alias.id.length > 0);

            return opts.require_id;
          }
        )]
      }, opts, done);
    }
  );

  it(
    "Should reset `rec` props for each iteration of the mods loop.",
    function (done) {
      var opts = {};
      run_test({
        mods: [
          function (rec, opts) {
            rec.id = 'bogus';
          },
          pathmodify.mod.id(paths.require_id, function (rec) {
            assert.strictEqual(rec.id, paths.require_id);

            return {id: tests_path.join(
              paths.src, paths.subdir, paths.basename + paths.ext
            )};
          })
        ]
      }, opts, done);
    }
  );

  it(
    "Should iterate mods loop until an alias is emitted.",
    function (done) {
      var
        opts = {},
        i = 0;
      run_test({
        mods: [
          // Matches from but doesn't modify so shouldn't terminate loop.
          pathmodify.mod.re(from_re, function (rec) {}),

          // Should be iterated to and emit alias.
          pathmodify.mod.re(
            from_re,
            tests_path.join(paths.src, '$1' + paths.ext)
          )
        ]
      }, opts, done);
    }
  );

  it(
    "Should call user mod functions in context of mod.",
    function (done) {
      var
        opts = {},
        i = 0;

      run_test({
        mods: [
          pathmodify.mod.id(paths.require_id, function (rec) {
            assert.strictEqual(this.from, paths.require_id);
          }),

          function mod () {
            assert.strictEqual(this, mod);
          },

          // Update ID so test doesn't fail for that
          pathmodify.mod.id(paths.require_id, paths.alias_id)
        ]
      }, opts, done);
    }
  );
});
<|endoftext|>