<commit_before>angular.module('mushin').controller('InboxCtrl', function ($scope, $rootScope, $filter, $location, $q, things, Thing, lists) {

  var debug = new window.$debug('mushin:thing');
  var search = $location.search();

  // order of the things listed
  $scope.predicate = 'title';

  // state of the by due date filter
  $scope.dueSelect = 'all';

  debug('controllers/inbox.js: search params ' + JSON.stringify(search));

  $scope.saveListActive = false;

  $scope.inbox = [];

  /* this adds proxy functions to Thing class functions */
  things.extend($scope);

  // http://cubiq.org/add-to-home-screen
  addToHomescreen({
    maxDisplayCount: 3
  })

  function fetchThings() {

    var deferred = $q.defer();

    debug('fetchThings: calling getAll');
    things.getAll(Thing.ACTIVE)
      .then(function(things) {
        debug('fetchThings: called getAll');
        // at this time, the rootScope contexts/projects are set and thus
        // available through $scope too

        $scope.inbox = $filter('filter')(things, function(thing) {
          // FIXME: I'm filtering on complete/end in a filter func
          if (!thing.done && !thing.deleted) return true
        })

        // parse query params now
        if (search.query) {
            var parser = new window.Parser();
            var parsed = parser.parse(search.query);
            debug('controllers/inbox: parsed query ' + JSON.stringify(parsed));
            angular.forEach(parsed.contexts, function (context) {
                // it's possible we're asking for a non-existing context
                // FIXME: maybe extract to a contexts initter ?
                if ($scope.contexts[context] === undefined ) {
                  $scope.contexts[context] = {
                    'name': context,
                    'things': [],
                  };
                }
                $scope.contexts[context].active = true;
            });
            angular.forEach(parsed.projects, function (project) {
                if ($scope.projects[project] === undefined ) {
                  $scope.projects[project] = {
                    'name': project,
                    'things': [],
                  };
                }
                $scope.projects[project].active = true;
            });
            var i;
            if (parsed.importance) {
              for (i = 0; i < parsed.importance.length; ++i) {
                $scope.importance[parsed.importance.charAt(i)].active = true;
              }
            }
            if (parsed.urgency) {
              for (i = 0; i < parsed.urgency.length; ++i) {
                $scope.urgency[parsed.urgency.charAt(i)].active = true;
              }
            }
        }

        debug('fetchThings: finished');
        deferred.resolve(undefined);
      })
      debug('fetchThings: returning');
      return deferred.promise;
  }

  debug('inbox.js: calling fetchThings');
  fetchThings()
    .then(function() {
      $scope.$on('thingChange', function() {
        debug('thingChange, calling fetchThings');
        // FIXME: this is too expensive to redo every time;
        // figure out which thing chnaged instead
        fetchThings();
        debug('thingChange, called fetchThings');
      });

  });
  debug('inbox.js: called fetchThings');

  $scope.newThing = function() {

    var title = ($scope.thingTitle || '').trim()
    var parser = new window.Parser();
    var parsed = parser.parse(title);

    title = parsed.title;
    debug('parsed new thing ' + JSON.stringify(parsed, null, 4));

    if (!title) return;

    // see app/scripts/services/things.js
    things.add(title, '', parsed);

    $scope.thingTitle = '';
    $scope.thingInput.$setPristine();
  }

  // filter things by context/project
  // FIXME: this now loops over all contexts/projects for each thing;
  // would be faster to precalculate the selection once into an array on
  // each click event in a taglist, then compare here
    $scope.filterByTag = function(thing) {

      var keep;
      var selectedAll;

      // either taglist may reject a thing
      // don't convert to angular.forEach as that does not allow breaks
      var types = [ 'context', 'project' ];
      var type;
      var tags;

      for (var i = 0; i < types.length; ++i) {
        type = types[i];
        tags = $scope[type + 's'];

//        debug('filter: looking at type ' + type);
        keep = false;
        selectedAll = true; // guilty until proven innocent

        for (var name in tags) {
          var tag = tags[name];

//          debug('filter: looking at tag ' + tag.name);
          if (tag.active) {
//            debug('filter: tag.name active ' + tag.name);
            selectedAll = false;
//            debug('thing tags: ' + JSON.stringify(thing));
            if (thing[type + 's'] && thing[type + 's'].indexOf(tag.name) > -1) {
//              debug('filter: keeping ' + thing.title);
              keep = true;
            }
          }
        }
        /* also keep if no tag is selected, which means all are */
        if (selectedAll) keep = true;

        if (!keep) {
          return false;
        }

      }
      return true;
    }

    // filter things by importance/urgency
    $scope.filterByNumber = function(thing) {

      var keep;
      var selectedAll;

      // either numberlist may reject a thing
      // don't convert to angular.forEach as that does not allow breaks
      var types = [ 'importance', 'urgency' ];
      var type;
      var tags;

      for (var i = 0; i < types.length; ++i) {
        type = types[i];
        tags = $scope[type];

//        debug('filter: looking at type ' + type);
        keep = false;
        selectedAll = true; // guilty until proven innocent

        for (var number in tags) {
          var tag = tags[number];

//          debug('filter: looking at tag ' + tag.name);
          if (tag.active) {
//            debug('filter: tag.name active ' + tag.name);
            selectedAll = false;
//            debug('thing tags: ' + JSON.stringify(thing));
            if (thing[type] && thing[type] == number) {
//              debug('filter: keeping ' + thing.title);
              keep = true;
            }
          }
        }
        /* also keep if no tag is selected, which means all are */
        if (selectedAll) keep = true;

        if (!keep) {
          return false;
        }
      }

      return true;
    }

    // filter things based on due date
    $scope.filterByDueSelector = function(thing) {

      var now = new Date();
      var due = new Date(thing.due);

      var dayStart = new Date(now.valueOf());
      dayStart.setHours(0);
      dayStart.setMinutes(0);
      dayStart.setSeconds(0);
      dayStart.setMilliseconds(0);

      var dayEnd = new Date(dayStart.valueOf());
      dayEnd.setDate(dayStart.getDate() + 1);

      var ret = false;

      switch ($scope.dueSelect) {
        case 'all':
          ret = true;
          break;
        case 'overdue':
          if (now > due)
            ret = true;
          break;
        case 'today':
          if (dayStart <= due && due < dayEnd)
            ret = true;
            break;
        case 'due':
          if (now < due)
            ret = true;
            break;
        case 'no':
          if (!thing.due)
            ret = true;
            break;
      }

      return ret;
    }

    $scope.notRecentlyCompleted = function(thing) {
      if (thing.complete != 100) {
//        debug(thing.title + ' not complete, keeping');
        return true;
      }
      if (!thing.end) {
//        debug(thing.title + ' no complete date, dropping');
        return false;
      }

      var now = new Date();
      var then = new Date(thing.end);
      var diff = Math.abs(now - then);
      if (diff >= 1000 * 60) {
//        debug(thing.title + ' done too long, dropping, ms ' + diff);
        return false;
      }

//      debug(thing.title + ' done just now, keeping, ms' + diff);
      return true;
    }

   // save the current state of the list of things as a saved list
   $scope.saveList = function(name) {
       debug('saveList ' + name);
       $scope.saveListActive = false;

       // construct query from state of filtering
       var parts = [];

       angular.forEach($scope.contexts, function (context) {
         if (context.active) {
           parts.push('@' + context.name);
         }
       });
       angular.forEach($scope.projects, function (project) {
         if (project.active) {
           parts.push('p:' + project.name);
         }
       });
       /* collect importance and urgency lists as a single word so
        * that the normal parse, which only allows one value for them,
        * still works
        */
       var numbers;

       numbers = [];
       angular.forEach($scope.importance, function (importance) {
         if (importance.active) {
           numbers.push(importance.name);
         }
       });
       if (numbers.length > 0) {
         parts.push('I:' + numbers.join(''));
       }
       numbers = [];
       angular.forEach($scope.urgency, function (urgency) {
         if (urgency.active) {
           numbers.push(urgency.name);
         }
       });
       if (numbers.length > 0) {
         parts.push('U:' + numbers.join(''));
       }

       var query = parts.join(' ');

       debug('saveList: query ' + query);
       lists.add(name, query);
   }

    $scope.toggleOrder = function(type) {
        debug('toggleOrder: ' + type);
        if ($scope.predicate == type) {
           $scope.predicate = '-' + type;
        } else {
           $scope.predicate = type;
        }
    };

})
<commit_msg>fix debug type<commit_after>angular.module('mushin').controller('InboxCtrl', function ($scope, $rootScope, $filter, $location, $q, things, Thing, lists) {

  var debug = new window.$debug('mushin:InboxCtrl');
  var search = $location.search();

  // order of the things listed
  $scope.predicate = 'title';

  // state of the by due date filter
  $scope.dueSelect = 'all';

  debug('controllers/inbox.js: search params ' + JSON.stringify(search));

  $scope.saveListActive = false;

  $scope.inbox = [];

  /* this adds proxy functions to Thing class functions */
  things.extend($scope);

  // http://cubiq.org/add-to-home-screen
  addToHomescreen({
    maxDisplayCount: 3
  })

  function fetchThings() {

    var deferred = $q.defer();

    debug('fetchThings: calling getAll');
    things.getAll(Thing.ACTIVE)
      .then(function(things) {
        debug('fetchThings: called getAll');
        // at this time, the rootScope contexts/projects are set and thus
        // available through $scope too

        $scope.inbox = $filter('filter')(things, function(thing) {
          // FIXME: I'm filtering on complete/end in a filter func
          if (!thing.done && !thing.deleted) return true
        })

        // parse query params now
        if (search.query) {
            var parser = new window.Parser();
            var parsed = parser.parse(search.query);
            debug('controllers/inbox: parsed query ' + JSON.stringify(parsed));
            angular.forEach(parsed.contexts, function (context) {
                // it's possible we're asking for a non-existing context
                // FIXME: maybe extract to a contexts initter ?
                if ($scope.contexts[context] === undefined ) {
                  $scope.contexts[context] = {
                    'name': context,
                    'things': [],
                  };
                }
                $scope.contexts[context].active = true;
            });
            angular.forEach(parsed.projects, function (project) {
                if ($scope.projects[project] === undefined ) {
                  $scope.projects[project] = {
                    'name': project,
                    'things': [],
                  };
                }
                $scope.projects[project].active = true;
            });
            var i;
            if (parsed.importance) {
              for (i = 0; i < parsed.importance.length; ++i) {
                $scope.importance[parsed.importance.charAt(i)].active = true;
              }
            }
            if (parsed.urgency) {
              for (i = 0; i < parsed.urgency.length; ++i) {
                $scope.urgency[parsed.urgency.charAt(i)].active = true;
              }
            }
        }

        debug('fetchThings: finished');
        deferred.resolve(undefined);
      })
      debug('fetchThings: returning');
      return deferred.promise;
  }

  debug('inbox.js: calling fetchThings');
  fetchThings()
    .then(function() {
      $scope.$on('thingChange', function() {
        debug('thingChange, calling fetchThings');
        // FIXME: this is too expensive to redo every time;
        // figure out which thing chnaged instead
        fetchThings();
        debug('thingChange, called fetchThings');
      });

  });
  debug('inbox.js: called fetchThings');

  $scope.newThing = function() {

    var title = ($scope.thingTitle || '').trim()
    var parser = new window.Parser();
    var parsed = parser.parse(title);

    title = parsed.title;
    debug('parsed new thing ' + JSON.stringify(parsed, null, 4));

    if (!title) return;

    // see app/scripts/services/things.js
    things.add(title, '', parsed);

    $scope.thingTitle = '';
    $scope.thingInput.$setPristine();
  }

  // filter things by context/project
  // FIXME: this now loops over all contexts/projects for each thing;
  // would be faster to precalculate the selection once into an array on
  // each click event in a taglist, then compare here
    $scope.filterByTag = function(thing) {

      var keep;
      var selectedAll;

      // either taglist may reject a thing
      // don't convert to angular.forEach as that does not allow breaks
      var types = [ 'context', 'project' ];
      var type;
      var tags;

      for (var i = 0; i < types.length; ++i) {
        type = types[i];
        tags = $scope[type + 's'];

//        debug('filter: looking at type ' + type);
        keep = false;
        selectedAll = true; // guilty until proven innocent

        for (var name in tags) {
          var tag = tags[name];

//          debug('filter: looking at tag ' + tag.name);
          if (tag.active) {
//            debug('filter: tag.name active ' + tag.name);
            selectedAll = false;
//            debug('thing tags: ' + JSON.stringify(thing));
            if (thing[type + 's'] && thing[type + 's'].indexOf(tag.name) > -1) {
//              debug('filter: keeping ' + thing.title);
              keep = true;
            }
          }
        }
        /* also keep if no tag is selected, which means all are */
        if (selectedAll) keep = true;

        if (!keep) {
          return false;
        }

      }
      return true;
    }

    // filter things by importance/urgency
    $scope.filterByNumber = function(thing) {

      var keep;
      var selectedAll;

      // either numberlist may reject a thing
      // don't convert to angular.forEach as that does not allow breaks
      var types = [ 'importance', 'urgency' ];
      var type;
      var tags;

      for (var i = 0; i < types.length; ++i) {
        type = types[i];
        tags = $scope[type];

//        debug('filter: looking at type ' + type);
        keep = false;
        selectedAll = true; // guilty until proven innocent

        for (var number in tags) {
          var tag = tags[number];

//          debug('filter: looking at tag ' + tag.name);
          if (tag.active) {
//            debug('filter: tag.name active ' + tag.name);
            selectedAll = false;
//            debug('thing tags: ' + JSON.stringify(thing));
            if (thing[type] && thing[type] == number) {
//              debug('filter: keeping ' + thing.title);
              keep = true;
            }
          }
        }
        /* also keep if no tag is selected, which means all are */
        if (selectedAll) keep = true;

        if (!keep) {
          return false;
        }
      }

      return true;
    }

    // filter things based on due date
    $scope.filterByDueSelector = function(thing) {

      var now = new Date();
      var due = new Date(thing.due);

      var dayStart = new Date(now.valueOf());
      dayStart.setHours(0);
      dayStart.setMinutes(0);
      dayStart.setSeconds(0);
      dayStart.setMilliseconds(0);

      var dayEnd = new Date(dayStart.valueOf());
      dayEnd.setDate(dayStart.getDate() + 1);

      var ret = false;

      switch ($scope.dueSelect) {
        case 'all':
          ret = true;
          break;
        case 'overdue':
          if (now > due)
            ret = true;
          break;
        case 'today':
          if (dayStart <= due && due < dayEnd)
            ret = true;
            break;
        case 'due':
          if (now < due)
            ret = true;
            break;
        case 'no':
          if (!thing.due)
            ret = true;
            break;
      }

      return ret;
    }

    $scope.notRecentlyCompleted = function(thing) {
      if (thing.complete != 100) {
//        debug(thing.title + ' not complete, keeping');
        return true;
      }
      if (!thing.end) {
//        debug(thing.title + ' no complete date, dropping');
        return false;
      }

      var now = new Date();
      var then = new Date(thing.end);
      var diff = Math.abs(now - then);
      if (diff >= 1000 * 60) {
//        debug(thing.title + ' done too long, dropping, ms ' + diff);
        return false;
      }

//      debug(thing.title + ' done just now, keeping, ms' + diff);
      return true;
    }

   // save the current state of the list of things as a saved list
   $scope.saveList = function(name) {
       debug('saveList ' + name);
       $scope.saveListActive = false;

       // construct query from state of filtering
       var parts = [];

       angular.forEach($scope.contexts, function (context) {
         if (context.active) {
           parts.push('@' + context.name);
         }
       });
       angular.forEach($scope.projects, function (project) {
         if (project.active) {
           parts.push('p:' + project.name);
         }
       });
       /* collect importance and urgency lists as a single word so
        * that the normal parse, which only allows one value for them,
        * still works
        */
       var numbers;

       numbers = [];
       angular.forEach($scope.importance, function (importance) {
         if (importance.active) {
           numbers.push(importance.name);
         }
       });
       if (numbers.length > 0) {
         parts.push('I:' + numbers.join(''));
       }
       numbers = [];
       angular.forEach($scope.urgency, function (urgency) {
         if (urgency.active) {
           numbers.push(urgency.name);
         }
       });
       if (numbers.length > 0) {
         parts.push('U:' + numbers.join(''));
       }

       var query = parts.join(' ');

       debug('saveList: query ' + query);
       lists.add(name, query);
   }

    $scope.toggleOrder = function(type) {
        debug('toggleOrder: ' + type);
        if ($scope.predicate == type) {
           $scope.predicate = '-' + type;
        } else {
           $scope.predicate = type;
        }
    };

})
<|endoftext|>


<commit_before>describe('ax5.util.filter TEST', function () {
    /* ax5.util.filter */
    //example 01
    var array = [5, 4, 3, 2, 1];
    it('ax5.util.filter([5,4,3,2,1],function(){return this%2;})', function () {
        var result = ax5.util.filter(array, function () {
            return this % 2;
        });

        _.isEqual(result, [5, 3, 1]).should.equal(true);
    });

    //example 02
    var list = [
        {isdel: 1, name: "ax5-1"},
        {name: "ax5-2"},
        {isdel: 1, name: "ax5-3"},
        {name: "ax5-4"},
        {name: "ax5-5"}
    ];

    it('ax5.util.filter([{isdel : 1 , name : "ax5-1"},{name : "ax5-2"},{isdel : 1 , name : "ax5-3"},{name : "ax5-4"},{name : "ax5-5"}] , function(){return (this.isdel !=1)})', function () {
        var result = ax5.util.filter(list, function () {
            return (this.isdel != 1);
        });

        _.isEqual(result, [{name: "ax5-2"}, {name: "ax5-4"}, {name: "ax5-5"}]).should.equal(true);
    });

    //example03
    var filObject = {
        a: 1,
        s: "string",
        oa: {pickup: true, name: "AXISJ"},
        os: {pickup: true, name: "AX5"}
    };

    it('ax5.util.filter( {a : 1, s : "string", oa : {pickup:true, name:"AXISJ"}, os : {pickup:true, name:"AX5"}}, function(){return this.pickup;})', function () {
        var result = ax5.util.filter(filObject, function () {
            return this.pickup;
        });
        should(result).be.deepEqual([{"pickup": true, "name": "AXISJ"}, {"pickup": true, "name": "AX5"}]);
    });

    /* end ax5.util.filter */
});

describe('ax5.util.search TEST', function () {
    /*ax5.util.search */
    //example01
    var a = ["A", "X", "5"];

    it('ax5.util.search(["A" , "X" , "5"], function(){return this == "X"})', function () {
        var idx = ax5.util.search(a, function () {
            return this == "X";
        });

        _.isEqual(a[idx], "X").should.equal(true);
    });

    //example02
    var a = ["A", "X", "5"];

    it('["A" , "X" ,"5"][ax5.util.search(["A" , "X" ,"5"] , function(idx){return idx == 2;})]', function () {
        var result = a[ax5.util.search(a, function (idx) {
            return idx == 2;
        })
            ];

        _.isEqual(result, "5").should.equal(true);
    });

    //example03
    var b = {a: "AX5-0", x: "AX5-1", 5: "AX5-2"};

    it('{a:"AX5-0" , x:"AX5-1" , 5:"AX5-2"}[ax5.util.search(b , function(k){return k == "x"})]', function () {
        var result = b[ax5.util.search(b, function (k) {
            return k == "x";
        })];

        _.isEqual(result, "AX5-1").should.equal(true);
    });
    /*end ax5.util.search */
});

describe('ax5.util.map TEST', function () {
    /*ax5.util.map*/
    //Usage 01
    var map_a = [1, 2, 3, 4, 5];

    it('[1,2,3,4,5] = ax5.util.map([1,2,3,4,5] , function(){return {id : this}})', function () {
        map_a = ax5.util.map(map_a, function () {
            return {id: this}
        });

        _.isEqual(map_a, [{"id": 1}, {"id": 2}, {"id": 3}, {"id": 4}, {"id": 5}]).should.equal(true);
    });

    //Usage 02
    it('ax5.util.map({a: 1, b: 2}, function (k, v) {return {id: k, value: v};})', function () {

        _.isEqual(ax5.util.map({a: 1, b: 2}, function (k, v) {
            return {id: k, value: v};
        }), [{"id": "a", "value": 1}, {"id": "b", "value": 2}]).should.equal(true);
    });
    /*end ax5.util.map*/
});

describe('ax5.util.merge TEST', function () {
    /*ax5.util.merge*/
    it('ax5.util.merge([1,2,3],[7,8,9])', function () {
        _.isEqual(ax5.util.merge([1, 2, 3], [7, 8, 9]), [1, 2, 3, 7, 8, 9]).should.equal(true);
    });
    /*end ax5.util.merge*/
});

describe('ax5.util.reduce TEST', function () {
    /*ax5.util.reduce*/
    //Example01
    it('ax5.util.reduce([5,4,3,2,1]) , function(p , n){return p*n;}', function () {
        should.deepEqual(ax5.util.reduce([5, 4, 3, 2, 1], function (p, n) {
            return p * n;
        }), 120);
    });
    //Example02
    it('ax5.util.reduce({a:1,b:2} , function(p,n){ return parseInt(p || 0) + parseInt(n);})', function () {
        should.deepEqual(ax5.util.reduce({a: 1, b: 2}, function (p, n) {
            return parseInt(p || 0) + parseInt(n);
        }), 3);
    });
    /*end ax5.util.reduce*/
});

describe('ax5.util.reduceRight TEST', function () {
    /*ax5.util.reduceRight*/
    it('ax5.util.reduceRight([5,4,3,2,1] , function(p,n){return p-n;})', function () {
        should.deepEqual(ax5.util.reduceRight([5, 4, 3, 2, 1], function (p, n) {
            return p - n;
        }), -13);
    });
    /*end ax5.util.reduceRight*/
});

describe('ax5.util.sum TEST', function () {
    /*ax.util.Sum */
    //Usage 01
    it('ax5.util.sum([{name: "122", value: 9},{name: "122", value: 10},{name: "123", value: 11}] , function(){if(this.name == "122"){return this.value;}})', function () {
        var arr = [
            {name: "122", value: 9},
            {name: "122", value: 10},
            {name: "123", value: 11}
        ];

        var rs = ax5.util.sum(arr, function () {
            if (this.name == "122") {
                return this.value;
            }
        });

        should.deepEqual(rs, 19);
    });

    //Usage 02
    it('ax5.util.sum([{name: "122", value: 9},{name: "122", value: 10},{name: "123", value: 11}] , 10 , function(){return this.value;})', function () {
        var arr = [
            {name: "122", value: 9},
            {name: "122", value: 10},
            {name: "123", value: 11}
        ];

        var test = ax5.util.sum(arr, 10, function () {
            return this.value;
        });

        should.deepEqual(test, 40);
    });
    /*end ax.util.Sum */
});

describe('ax5.util.avg TEST', function () {
    /* ax.util.avg */
    it('ax5.util.avg(arr , function(){return this.value;})', function () {
        var arr = [
            {name: "122", value: 9},
            {name: "122", value: 10},
            {name: "123", value: 11}
        ];

        var rs = ax5.util.avg(arr, function () {
            return this.value;
        });

        should.deepEqual(rs, 10);
    });
    /* end ax.util.avg */
});

describe('ax5.util.first TEST', function () {
    /* ax.util.first */
    //Example 01
    it('ax5.util.first(["ax5", "axisj"])', function () {
        var _arr = ["ax5", "axisj"];
        var str = ax5.util.first(_arr);

        should.deepEqual(str, "ax5");
    });

    //Example 02
    //confirm 필요 (ax5.util.toJson을 넣으면 에러)
    it('ax5.util.first({k: "ax5", z: "axisj"})', function () {
        var _obj = {k: "ax5", z: "axisj"};

        should.deepEqual(ax5.util.first(_obj), {"k": "ax5"});
    });
    /* end ax.util.first */
});

describe('ax5.util.first TEST', function () {
    /* ax5.util.last */
    //Example01
    it('ax5.util.last(["ax5", "axisj"])', function () {
        var _arr = ["ax5", "axisj"];

        should.deepEqual(ax5.util.last(_arr), "axisj");
    });

    //Example 02
    //confirm 필요 (ax5.util.toJson을 넣으면 에러)
    it('ax5.util.last({k: "ax5", z: "axisj"})', function () {
        var _obj = {k: "ax5", z: "axisj"};

        should.deepEqual(ax5.util.last(_obj), {"z": "axisj"});
    });
    /* end ax5.util.last */
});

/* ax5.util.deepCopy */

/* end ax5.util.deepCopy */
<commit_msg>update test code<commit_after>describe('ax5.util.each TEST', function () {
    /* ax5.util.filter */
    //example 01
    it('ax5.util.each [object]', function () {
        var obj = {a: 1, b: 2, c: 3, d: 4, e: 5};
        var result = 0;
        ax5.util.each(obj, function (i, o) {
            result += o;
        });
        _.isEqual(result, 15).should.equal(true);
    });
});

describe('ax5.util.filter TEST', function () {
    /* ax5.util.filter */
    //example 01
    var array = [5, 4, 3, 2, 1];
    it('ax5.util.filter([5,4,3,2,1],function(){return this%2;})', function () {
        var result = ax5.util.filter(array, function () {
            return this % 2;
        });

        _.isEqual(result, [5, 3, 1]).should.equal(true);
    });

    //example 02
    var list = [
        {isdel: 1, name: "ax5-1"},
        {name: "ax5-2"},
        {isdel: 1, name: "ax5-3"},
        {name: "ax5-4"},
        {name: "ax5-5"}
    ];

    it('ax5.util.filter([{isdel : 1 , name : "ax5-1"},{name : "ax5-2"},{isdel : 1 , name : "ax5-3"},{name : "ax5-4"},{name : "ax5-5"}] , function(){return (this.isdel !=1)})', function () {
        var result = ax5.util.filter(list, function () {
            return (this.isdel != 1);
        });

        _.isEqual(result, [{name: "ax5-2"}, {name: "ax5-4"}, {name: "ax5-5"}]).should.equal(true);
    });

    //example03
    var filObject = {
        a: 1,
        s: "string",
        oa: {pickup: true, name: "AXISJ"},
        os: {pickup: true, name: "AX5"}
    };

    it('ax5.util.filter( {a : 1, s : "string", oa : {pickup:true, name:"AXISJ"}, os : {pickup:true, name:"AX5"}}, function(){return this.pickup;})', function () {
        var result = ax5.util.filter(filObject, function () {
            return this.pickup;
        });
        should(result).be.deepEqual([{"pickup": true, "name": "AXISJ"}, {"pickup": true, "name": "AX5"}]);
    });

    /* end ax5.util.filter */
});

describe('ax5.util.search TEST', function () {
    /*ax5.util.search */
    //example01
    var a = ["A", "X", "5"];

    it('ax5.util.search(["A" , "X" , "5"], function(){return this == "X"})', function () {
        var idx = ax5.util.search(a, function () {
            return this == "X";
        });

        _.isEqual(a[idx], "X").should.equal(true);
    });

    //example02
    var a = ["A", "X", "5"];

    it('["A" , "X" ,"5"][ax5.util.search(["A" , "X" ,"5"] , function(idx){return idx == 2;})]', function () {
        var result = a[ax5.util.search(a, function (idx) {
            return idx == 2;
        })
            ];

        _.isEqual(result, "5").should.equal(true);
    });

    //example03
    var b = {a: "AX5-0", x: "AX5-1", 5: "AX5-2"};

    it('{a:"AX5-0" , x:"AX5-1" , 5:"AX5-2"}[ax5.util.search(b , function(k){return k == "x"})]', function () {
        var result = b[ax5.util.search(b, function (k) {
            return k == "x";
        })];

        _.isEqual(result, "AX5-1").should.equal(true);
    });
    /*end ax5.util.search */
});

describe('ax5.util.map TEST', function () {
    /*ax5.util.map*/
    //Usage 01
    var map_a = [1, 2, 3, 4, 5];

    it('[1,2,3,4,5] = ax5.util.map([1,2,3,4,5] , function(){return {id : this}})', function () {
        map_a = ax5.util.map(map_a, function () {
            return {id: this}
        });

        _.isEqual(map_a, [{"id": 1}, {"id": 2}, {"id": 3}, {"id": 4}, {"id": 5}]).should.equal(true);
    });

    //Usage 02
    it('ax5.util.map({a: 1, b: 2}, function (k, v) {return {id: k, value: v};})', function () {

        _.isEqual(ax5.util.map({a: 1, b: 2}, function (k, v) {
            return {id: k, value: v};
        }), [{"id": "a", "value": 1}, {"id": "b", "value": 2}]).should.equal(true);
    });
    /*end ax5.util.map*/
});

describe('ax5.util.merge TEST', function () {
    /*ax5.util.merge*/
    it('ax5.util.merge([1,2,3],[7,8,9])', function () {
        _.isEqual(ax5.util.merge([1, 2, 3], [7, 8, 9]), [1, 2, 3, 7, 8, 9]).should.equal(true);
    });
    /*end ax5.util.merge*/
});

describe('ax5.util.reduce TEST', function () {
    /*ax5.util.reduce*/
    //Example01
    it('ax5.util.reduce([5,4,3,2,1]) , function(p , n){return p*n;}', function () {
        should.deepEqual(ax5.util.reduce([5, 4, 3, 2, 1], function (p, n) {
            return p * n;
        }), 120);
    });
    //Example02
    it('ax5.util.reduce({a:1,b:2} , function(p,n){ return parseInt(p || 0) + parseInt(n);})', function () {
        should.deepEqual(ax5.util.reduce({a: 1, b: 2}, function (p, n) {
            return parseInt(p || 0) + parseInt(n);
        }), 3);
    });
    /*end ax5.util.reduce*/
});

describe('ax5.util.reduceRight TEST', function () {
    /*ax5.util.reduceRight*/
    it('ax5.util.reduceRight([5,4,3,2,1] , function(p,n){return p-n;})', function () {
        should.deepEqual(ax5.util.reduceRight([5, 4, 3, 2, 1], function (p, n) {
            return p - n;
        }), -13);
    });
    /*end ax5.util.reduceRight*/
});

describe('ax5.util.sum TEST', function () {
    /*ax.util.Sum */
    //Usage 01
    it('ax5.util.sum([{name: "122", value: 9},{name: "122", value: 10},{name: "123", value: 11}] , function(){if(this.name == "122"){return this.value;}})', function () {
        var arr = [
            {name: "122", value: 9},
            {name: "122", value: 10},
            {name: "123", value: 11}
        ];

        var rs = ax5.util.sum(arr, function () {
            if (this.name == "122") {
                return this.value;
            }
        });

        should.deepEqual(rs, 19);
    });

    //Usage 02
    it('ax5.util.sum([{name: "122", value: 9},{name: "122", value: 10},{name: "123", value: 11}] , 10 , function(){return this.value;})', function () {
        var arr = [
            {name: "122", value: 9},
            {name: "122", value: 10},
            {name: "123", value: 11}
        ];

        var test = ax5.util.sum(arr, 10, function () {
            return this.value;
        });

        should.deepEqual(test, 40);
    });
    /*end ax.util.Sum */
});

describe('ax5.util.avg TEST', function () {
    /* ax.util.avg */
    it('ax5.util.avg(arr , function(){return this.value;})', function () {
        var arr = [
            {name: "122", value: 9},
            {name: "122", value: 10},
            {name: "123", value: 11}
        ];

        var rs = ax5.util.avg(arr, function () {
            return this.value;
        });

        should.deepEqual(rs, 10);
    });
    /* end ax.util.avg */
});

describe('ax5.util.first TEST', function () {
    /* ax.util.first */
    //Example 01
    it('ax5.util.first(["ax5", "axisj"])', function () {
        var _arr = ["ax5", "axisj"];
        var str = ax5.util.first(_arr);

        should.deepEqual(str, "ax5");
    });

    //Example 02
    //confirm 필요 (ax5.util.toJson을 넣으면 에러)
    it('ax5.util.first({k: "ax5", z: "axisj"})', function () {
        var _obj = {k: "ax5", z: "axisj"};

        should.deepEqual(ax5.util.first(_obj), {"k": "ax5"});
    });
    /* end ax.util.first */
});

describe('ax5.util.first TEST', function () {
    /* ax5.util.last */
    //Example01
    it('ax5.util.last(["ax5", "axisj"])', function () {
        var _arr = ["ax5", "axisj"];

        should.deepEqual(ax5.util.last(_arr), "axisj");
    });

    //Example 02
    //confirm 필요 (ax5.util.toJson을 넣으면 에러)
    it('ax5.util.last({k: "ax5", z: "axisj"})', function () {
        var _obj = {k: "ax5", z: "axisj"};

        should.deepEqual(ax5.util.last(_obj), {"z": "axisj"});
    });
    /* end ax5.util.last */
});

/* ax5.util.deepCopy */

/* end ax5.util.deepCopy */
<|endoftext|>


<commit_before>import React from 'react'
import { Link } from 'react-router-dom'
import PropTypes from 'prop-types';

import TotalFundAvailable from './TotalFundAvailable'
import ServiceFundsAvailable from './ServiceFundsAvailable'

import avatar from '../images/avatar.svg'
import back from '../images/back.svg'
import close from '../images/close.svg'

const Navigation = (props) => {
  const {
    showClose,
    showBack,
    showUser,
    showTotalFunds,
    showServiceFunds,
    funds,
    service,
    user,
  } = props

  return (

        {
          showBack &&
            <Link to="/dashboard" className="flex">

            </Link>
        }
        {
          showUser &&
            <Link to="/user" className="flex">

            </Link>
        }
        { showTotalFunds && <TotalFundAvailable funds={funds}/> }
        { showServiceFunds && <ServiceFundsAvailable service={service} /> }
        {
          showClose &&

{props.centerText}

        }

  )
}

export default Navigation

Navigation.propTypes = {
  showClose: PropTypes.bool,
  showBack: PropTypes.bool,
  showUser: PropTypes.bool,
  showTotalFunds: PropTypes.bool,
  showServiceFunds: PropTypes.bool,
  funds: PropTypes.shape({
    generalFund: PropTypes.number,
    servicesSum: PropTypes.number,
    generalFund2016: PropTypes.number,
  }),
  service: PropTypes.shape({
    title: PropTypes.string,
    amount: PropTypes.number,
  }),
  history: PropTypes.object,
  centerText: PropTypes.string,
};<commit_msg>Add user info to nav bar for Google<commit_after>import React from 'react'
import { Link } from 'react-router-dom'
import PropTypes from 'prop-types';

import TotalFundAvailable from './TotalFundAvailable'
import ServiceFundsAvailable from './ServiceFundsAvailable'

import avatar from '../images/avatar.svg'
import back from '../images/back.svg'
import close from '../images/close.svg'

const Navigation = (props) => {
  const {
    showClose,
    showBack,
    showUser,
    showTotalFunds,
    showServiceFunds,
    funds,
    service,
    user,
  } = props

  const { displayName, photoURL } = user

  return (

        {
          showBack &&
            <Link to="/dashboard" className="flex">

            </Link>
        }
        {
          showUser &&

              <Link to="/user" className="flex">

              </Link>

Welcome, {displayName}

        }
        { showTotalFunds && <TotalFundAvailable funds={funds}/> }
        { showServiceFunds && <ServiceFundsAvailable service={service} /> }
        {
          showClose &&

{props.centerText}

        }

  )
}

export default Navigation

Navigation.propTypes = {
  showClose: PropTypes.bool,
  showBack: PropTypes.bool,
  showUser: PropTypes.bool,
  showTotalFunds: PropTypes.bool,
  showServiceFunds: PropTypes.bool,
  funds: PropTypes.shape({
    generalFund: PropTypes.number,
    servicesSum: PropTypes.number,
    generalFund2016: PropTypes.number,
  }),
  service: PropTypes.shape({
    title: PropTypes.string,
    amount: PropTypes.number,
  }),
  history: PropTypes.object,
  centerText: PropTypes.string,
  user: PropTypes.object,
};<|endoftext|>


<commit_before>/// <reference path="../../Core/PropertyValueProviders/Enums.js"/>
/// <reference path="../../Core/PropertyValueProviders/FrameworkElementPropertyValueProvider.js"/>
/// CODE

//#region _TextBoxBaseDynamicPropertyValueProvider
var _TextBoxBaseDynamicPropertyValueProvider = Nullstone.Create("_TextBoxBaseDynamicPropertyValueProvider", FrameworkElementPropertyValueProvider, 5);

_TextBoxBaseDynamicPropertyValueProvider.Instance.Init = function (obj, propPrecedence, foregroundPropd, backgroundPropd, baselineOffsetPropd) {
    this.Init$FrameworkElementPropertyValueProvider(obj, propPrecedence,
        _ProviderFlags.RecomputesOnClear | _ProviderFlags.RecomputesOnLowerPriorityChange);
    this._ForegroundPropd = foregroundPropd;
    this._BackgroundPropd = backgroundPropd;
    this._BaselineOffsetPropd = baselineOffsetPropd;
    this._SelectionBackground = undefined;
    this._SelectionForeground = undefined;
    this._BaselineOffset = undefined;
};

_TextBoxBaseDynamicPropertyValueProvider.Instance.RecomputePropertyValue = function (propd, providerFlags, error) {
    if (propd == this._BackgroundPropd)
        this._SelectionBackground = undefined;
    else if (propd == this._ForegroundPropd)
        this._SelectionForeground = undefined;

    this.RecomputePropertyValue$FrameworkElementPropertyValueProvider(propd, providerFlags, error);
};
_TextBoxBaseDynamicPropertyValueProvider.Instance.GetPropertyValue = function (propd) {
    var v;
    if (propd._ID === this._BackgroundPropd._ID) {
        v = this._Object._GetValue(propd, this._PropertyPrecedence + 1);
        if (!v)
            v = this._SelectionBackground;
    } else if (propd._ID === this._ForegroundPropd._ID) {
        v = this._Object._GetValue(propd, this._PropertyPrecedence + 1);
        if (!v)
            v = this._SelectionForeground;
    } else if (propd._ID === this._BaselineOffsetPropd._ID) {
        var _TextBoxView = this._Object._View;
        this._BaselineOffset = !_TextBoxView ? 0 : _TextBoxView.GetBaselineOffset();
        v = this._BaselineOffset;
    }
    if (v != undefined)
        return v;
    return this.GetPropertyValue$FrameworkElementPropertyValueProvider(propd);
};

_TextBoxBaseDynamicPropertyValueProvider.Instance._InitializeSelectionBrushes = function () {
    if (!this._SelectionBackground)
        this._SelectionBackground = new SolidColorBrush(Color.FromHex("#FF444444"));
    if (!this._SelectionForeground)
        this._SelectionForeground = new SolidColorBrush(Color.FromHex("#FFFFFFFF"));
};

Nullstone.FinishCreate(_TextBoxBaseDynamicPropertyValueProvider);
//#endregion<commit_msg>Fixed property check.<commit_after>/// <reference path="../../Core/PropertyValueProviders/Enums.js"/>
/// <reference path="../../Core/PropertyValueProviders/FrameworkElementPropertyValueProvider.js"/>
/// CODE

//#region _TextBoxBaseDynamicPropertyValueProvider
var _TextBoxBaseDynamicPropertyValueProvider = Nullstone.Create("_TextBoxBaseDynamicPropertyValueProvider", FrameworkElementPropertyValueProvider, 5);

_TextBoxBaseDynamicPropertyValueProvider.Instance.Init = function (obj, propPrecedence, foregroundPropd, backgroundPropd, baselineOffsetPropd) {
    this.Init$FrameworkElementPropertyValueProvider(obj, propPrecedence,
        _ProviderFlags.RecomputesOnClear | _ProviderFlags.RecomputesOnLowerPriorityChange);
    this._ForegroundPropd = foregroundPropd;
    this._BackgroundPropd = backgroundPropd;
    this._BaselineOffsetPropd = baselineOffsetPropd;
    this._SelectionBackground = undefined;
    this._SelectionForeground = undefined;
    this._BaselineOffset = undefined;
};

_TextBoxBaseDynamicPropertyValueProvider.Instance.RecomputePropertyValue = function (propd, providerFlags, error) {
    if (propd._ID === this._BackgroundPropd._ID)
        this._SelectionBackground = undefined;
    else if (propd._ID === this._ForegroundPropd._ID)
        this._SelectionForeground = undefined;
    this.RecomputePropertyValue$FrameworkElementPropertyValueProvider(propd, providerFlags, error);
};
_TextBoxBaseDynamicPropertyValueProvider.Instance.GetPropertyValue = function (propd) {
    var v;
    if (propd._ID === this._BackgroundPropd._ID) {
        v = this._Object._GetValue(propd, this._PropertyPrecedence + 1);
        if (!v)
            v = this._SelectionBackground;
    } else if (propd._ID === this._ForegroundPropd._ID) {
        v = this._Object._GetValue(propd, this._PropertyPrecedence + 1);
        if (!v)
            v = this._SelectionForeground;
    } else if (propd._ID === this._BaselineOffsetPropd._ID) {
        var _TextBoxView = this._Object._View;
        this._BaselineOffset = !_TextBoxView ? 0 : _TextBoxView.GetBaselineOffset();
        v = this._BaselineOffset;
    }
    if (v != undefined)
        return v;
    return this.GetPropertyValue$FrameworkElementPropertyValueProvider(propd);
};

_TextBoxBaseDynamicPropertyValueProvider.Instance._InitializeSelectionBrushes = function () {
    if (!this._SelectionBackground)
        this._SelectionBackground = new SolidColorBrush(Color.FromHex("#FF444444"));
    if (!this._SelectionForeground)
        this._SelectionForeground = new SolidColorBrush(Color.FromHex("#FFFFFFFF"));
};

Nullstone.FinishCreate(_TextBoxBaseDynamicPropertyValueProvider);
//#endregion<|endoftext|>


<commit_before>let childProcess = require('child_process');
let File = require('../src/File');
let argv = require('yargs').argv;

class Dependencies {
    /**
     * Create a new Dependencies instance.
     *
     * @param {Object} dependencies
     */
    constructor(dependencies) {
        this.dependencies = dependencies;
    }

    /**
     * Install all dependencies that aren't available.
     *
     * @param {Boolean} abortOnComplete
     */
    install(abortOnComplete = false) {
        this.dependencies
            .reject(dependency => {
                try {
                    return require.resolve(
                        dependency.replace(/(?!^@)@.+$/, '')
                    );
                } catch (e) {}
            })
            .tap(dependencies => {
                this.execute(
                    this.buildInstallCommand(dependencies),
                    abortOnComplete
                );
            });
    }

    /**
     * Execute the provided console command.
     *
     * @param {string}  command
     * @param {Boolean} abortOnComplete
     */
    execute(command, abortOnComplete) {
        console.log(
            'Additional dependencies must be installed. ' +
                'This will only take a moment.'
        );

        console.log('Running: ' + command);

        childProcess.execSync(command);

        this.respond(abortOnComplete);
    }

    /**
     * Build the dependency install command.
     *
     * @param {Object} dependencies
     */
    buildInstallCommand(dependencies) {
        dependencies = [].concat(dependencies).join(' ');

        if (File.exists('yarn.lock')) {
            return `yarn add ${dependencies} --dev --production=false`;
        }

        return `npm install ${dependencies} --save-dev --production=false`;
    }

    /**
     * Complete the install process.
     *
     * @param {Boolean} abortOnComplete
     */
    respond(abortOnComplete) {
        console.log(
            typeof abortOnComplete === 'string'
                ? abortOnComplete
                : 'Finished. Please run Mix again.'
        );

        if (!argv['$0'].includes('ava')) {
            process.exit();
        }
    }
}

module.exports = Dependencies;
<commit_msg>Fix dependency installs aborting incorrectly<commit_after>let childProcess = require('child_process');
let File = require('../src/File');
let argv = require('yargs').argv;

class Dependencies {
    /**
     * Create a new Dependencies instance.
     *
     * @param {Object} dependencies
     */
    constructor(dependencies) {
        this.dependencies = dependencies;
    }

    /**
     * Install all dependencies that aren't available.
     *
     * @param {Boolean} abortOnComplete
     */
    install(abortOnComplete = false) {
        this.dependencies
            .reject(dependency => {
                try {
                    return require.resolve(
                        dependency.replace(/(?!^@)@.+$/, '')
                    );
                } catch (e) {}
            })
            .tap(dependencies => {
                this.execute(
                    this.buildInstallCommand(dependencies),
                    abortOnComplete
                );
            });
    }

    /**
     * Execute the provided console command.
     *
     * @param {string}  command
     * @param {Boolean} abortOnComplete
     */
    execute(command, abortOnComplete) {
        console.log(
            'Additional dependencies must be installed. ' +
                'This will only take a moment.'
        );

        console.log('Running: ' + command);

        childProcess.execSync(command);

        this.respond(abortOnComplete);
    }

    /**
     * Build the dependency install command.
     *
     * @param {Object} dependencies
     */
    buildInstallCommand(dependencies) {
        dependencies = [].concat(dependencies).join(' ');

        if (File.exists('yarn.lock')) {
            return `yarn add ${dependencies} --dev --production=false`;
        }

        return `npm install ${dependencies} --save-dev --production=false`;
    }

    /**
     * Complete the install process.
     *
     * @param {Boolean} abortOnComplete
     */
    respond(abortOnComplete) {
        if (abortOnComplete) {
            console.log(
                typeof abortOnComplete === 'string'
                    ? abortOnComplete
                    : 'Finished. Please run Mix again.'
            );

            if (!argv['$0'].includes('ava')) {
                process.exit();
            }
        }
    }
}

module.exports = Dependencies;
<|endoftext|>


<commit_before>/* global ngDefine: false */
ngDefine('cockpit.directives', [ 'angular', 'require' ], function(module, angular, require) {
  'use strict';

  var TEMPLATE_URL = require.toUrl('./activity-instance-tree.html');

  var Directive = [ '$compile', '$http', '$templateCache',
            function ($compile, $http, $templateCache) {

    return {
      restrict: 'EAC',
      scope: {
        node: '=activityInstanceTree',
        onElementClick: '&',
        selection: '=',
        quickFilters: '='
      },
      link: function(scope, element /*, attrs, processDiagram */ ) {

        var $nodeElement = element,
            nodeSelectedEventName = 'node.selected',
            nodeOpenedEventName = 'node.opened';

        function withTemplate(fn) {
          $http.get(TEMPLATE_URL, { cache: $templateCache })
            .success(function(content) {
              fn(content);
            }).error(function(response, code, headers, config) {
              throw new Error('Failed to load template: ' + config.url);
            });
        }

        scope.$watch('node', function (newValue) {
          if (!newValue || newValue.$loaded === false) {
            return;
          }

          newValue.children = (newValue.childActivityInstances || []).concat(newValue.childTransitionInstances || []);

          createTreeNode(newValue);
        });

        scope.$on(nodeOpenedEventName, function ($event, value) {
          handleNodeEvents($event, value);
        });

        scope.$on(nodeSelectedEventName, function ($event, value) {
          handleNodeEvents($event, value);
        });

        function handleNodeEvents($event, value) {
          var node = scope.node,
              eventName = $event.name;

          if (!node) {
            return;
          }

          if (eventName === nodeOpenedEventName || eventName === nodeSelectedEventName) {
            if (node.id === value.parentActivityInstanceId) {
              node.isOpen = true;
              if (node.parentActivityInstanceId) {
                fireNodeEvent(nodeOpenedEventName, node);
              }
            }
          }
        }

        function fireNodeEvent(name, node) {
          var id = node.id,
              parentActivityInstanceId = node.parentActivityInstanceId;

          scope.$emit(name, {
            id: id,
            parentActivityInstanceId: parentActivityInstanceId
          });
        }

        scope.$watch('selection.activityInstanceIds', function(newValue, oldValue) {
          var node = scope.node;

          if (!node) {
            return;
          }

          if (oldValue && oldValue.indexOf(node.id) != -1) {
            node.isSelected = false;
          }

          if (newValue && newValue.indexOf(node.id) != -1) {
            node.isSelected = true;

            if (node.parentActivityInstanceId) {
              fireNodeEvent(nodeSelectedEventName, node);
            }
          }
        });

        scope.deselect = function($event) {
          $event.ctrlKey = true;
          scope.select($event);
        };

        scope.select = function($event) {
          var node = scope.node;

          $event.stopPropagation();

          // propagate the change for other directives/controllers
          scope.$emit('instance-tree-selection-change');

          scope.onElementClick({
            id: node.id,
            activityId: node.activityId || node.targetActivityId,
            $event: $event
          });
        };

        function createTreeNode(node) {

          withTemplate(function(template) {
            // if finished, show collapsed
            node.isOpen = node.endTime ? false : true;

            var newElement = angular.element(template);
            $compile(newElement)(scope);
            $nodeElement.replaceWith(newElement);
            $nodeElement = newElement;
          });
        }

        scope.propogateSelection = function (id, activityId, $event) {
          scope.onElementClick({
            id: id,
            activityId: activityId,
            $event: $event
          });
        };

        scope.toggleOpen = function() {
          var node = scope.node;
          node.isOpen = !node.isOpen;
        };

        scope.orderPropertyValue = function (elem) {
          var id = elem.id,
              idx = id.indexOf(':');

          return idx !== -1 ? id.substr(idx + 1, id.length) : id;
        };

      }
    };
  }];

  module
    .directive('activityInstanceTree', Directive);

});
<commit_msg>chore(cockpit/tree): prevent stackoverlow on instance selection<commit_after>/* global ngDefine: false */
ngDefine('cockpit.directives', [ 'angular', 'require' ], function(module, angular, require) {
  'use strict';

  var TEMPLATE_URL = require.toUrl('./activity-instance-tree.html');

  var Directive = [ '$compile', '$http', '$templateCache',
            function ($compile, $http, $templateCache) {

    return {
      restrict: 'EAC',
      scope: {
        node: '=activityInstanceTree',
        onElementClick: '&',
        selection: '=',
        quickFilters: '='
      },
      link: function(scope, element /*, attrs, processDiagram */ ) {

        var $nodeElement = element,
            nodeSelectedEventName = 'node.selected',
            nodeOpenedEventName = 'node.opened';

        function withTemplate(fn) {
          $http.get(TEMPLATE_URL, { cache: $templateCache })
            .success(function(content) {
              fn(content);
            }).error(function(response, code, headers, config) {
              throw new Error('Failed to load template: ' + config.url);
            });
        }

        scope.$watch('node', function (newValue) {
          if (!newValue || newValue.$loaded === false) {
            return;
          }

          newValue.children = (newValue.childActivityInstances || []).concat(newValue.childTransitionInstances || []);

          createTreeNode(newValue);
        });

        scope.$on(nodeOpenedEventName, function ($event, value) {
          handleNodeEvents($event, value);
        });

        scope.$on(nodeSelectedEventName, function ($event, value) {
          handleNodeEvents($event, value);
        });

        function handleNodeEvents($event, value) {
          var node = scope.node,
              eventName = $event.name;

          if (!node) {
            return;
          }

          if (eventName === nodeOpenedEventName || eventName === nodeSelectedEventName) {
            if (node.id === value.parentActivityInstanceId) {
              node.isOpen = true;
              if (node.parentActivityInstanceId && node.id !== node.parentActivityInstanceId) {
                fireNodeEvent(nodeOpenedEventName, node);
              }
            }
          }
        }

        function fireNodeEvent(name, node) {
          var id = node.id,
              parentActivityInstanceId = node.parentActivityInstanceId;

          scope.$emit(name, {
            id: id,
            parentActivityInstanceId: parentActivityInstanceId
          });
        }

        scope.$watch('selection.activityInstanceIds', function(newValue, oldValue) {
          var node = scope.node;

          if (!node) {
            return;
          }

          if (oldValue && oldValue.indexOf(node.id) != -1) {
            node.isSelected = false;
          }

          if (newValue && newValue.indexOf(node.id) != -1) {
            node.isSelected = true;

            if (node.parentActivityInstanceId) {
              fireNodeEvent(nodeSelectedEventName, node);
            }
          }
        });

        scope.deselect = function($event) {
          $event.ctrlKey = true;
          scope.select($event);
        };

        scope.select = function($event) {
          var node = scope.node;

          $event.stopPropagation();

          // propagate the change for other directives/controllers
          scope.$emit('instance-tree-selection-change');

          scope.onElementClick({
            id: node.id,
            activityId: node.activityId || node.targetActivityId,
            $event: $event
          });
        };

        function createTreeNode(node) {

          withTemplate(function(template) {
            // if finished, show collapsed
            node.isOpen = node.endTime ? false : true;

            var newElement = angular.element(template);
            $compile(newElement)(scope);
            $nodeElement.replaceWith(newElement);
            $nodeElement = newElement;
          });
        }

        scope.propogateSelection = function (id, activityId, $event) {
          scope.onElementClick({
            id: id,
            activityId: activityId,
            $event: $event
          });
        };

        scope.toggleOpen = function() {
          var node = scope.node;
          node.isOpen = !node.isOpen;
        };

        scope.orderPropertyValue = function (elem) {
          var id = elem.id,
              idx = id.indexOf(':');

          return idx !== -1 ? id.substr(idx + 1, id.length) : id;
        };

      }
    };
  }];

  module
    .directive('activityInstanceTree', Directive);

});
<|endoftext|>


<commit_before>var React = require('react');
var MovieStore = require('../stores/movieStore');
var config = require('../../config');

var MoviePlayer = React.createClass({
    getInitialState: function(){
        return {
            movie: undefined
        }
    },
    componentDidMount: function(){
        MovieStore.addChangeListener(this._onChange);
    },
    _onChange: function(){
        this.setState({
            movie: MovieStore.getPlayedMovie()
        })
    },
    render: function() {
        var videoSource = this.state.movie !== undefined
            ? '/movies/' + encodeURIComponent(this.state.movie.title)
            : '';

        var className = this.state.movie !== undefined
            ? 'row'
            : 'hidden';
        return (

                    <video autoPlay controls src={videoSource} />

        );
    }
});

module.exports = MoviePlayer;<commit_msg>Using absolute url for video.<commit_after>var React = require('react');
var MovieStore = require('../stores/movieStore');
var config = require('../../config');

var MoviePlayer = React.createClass({
    getInitialState: function(){
        return {
            movie: undefined
        }
    },
    componentDidMount: function(){
        MovieStore.addChangeListener(this._onChange);
    },
    _onChange: function(){
        this.setState({
            movie: MovieStore.getPlayedMovie()
        })
    },
    getVideoUrl: function(){
        return config.apiUrl + '/movies/' + encodeURIComponent(this.state.movie.title);
    },
    render: function() {
        var videoSource = this.state.movie !== undefined
            ? this.getVideoUrl()
            : '';

        var className = this.state.movie !== undefined
            ? 'row'
            : 'hidden';
        return (

                    <video autoPlay controls src={videoSource} />

        );
    }
});

module.exports = MoviePlayer;<|endoftext|>


<commit_before>import isEventSupported from './isEventSupported';
import createSyntheticEvent from './createSyntheticEvent';
import getDomNodeId from '../getDomNodeId';
import SimpleMap from '../../utils/SimpleMap';
import { isIos } from '../utils/ua';

const MOUSE_NATIVE_EVENTS = ['click', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup'];
let BUBBLEABLE_NATIVE_EVENTS = [
        'blur', 'change', 'contextmenu', 'copy', 'cut',
        'dblclick', 'drag', 'dragend', 'dragenter', 'dragleave', 'dragover', 'dragstart', 'drop',
        'focus', 'input', 'keydown', 'keypress', 'keyup',
        'paste', 'submit', 'touchcancel', 'touchend', 'touchmove', 'touchstart', 'wheel'
    ],
    NON_BUBBLEABLE_NATIVE_EVENTS = [
        'canplay', 'canplaythrough', 'complete', 'durationchange', 'emptied', 'ended', 'error',
        'load', 'loadeddata', 'loadedmetadata', 'loadstart', 'mouseenter', 'mouseleave',
        'pause', 'play', 'playing', 'progress', 'ratechange',
        'scroll', 'seeked', 'seeking', 'select', 'stalled', 'suspend',
        'timeupdate', 'volumechange', 'waiting'
    ];

if(isIos) {
    NON_BUBBLEABLE_NATIVE_EVENTS = [...NON_BUBBLEABLE_NATIVE_EVENTS, ...MOUSE_NATIVE_EVENTS];
}
else {
    BUBBLEABLE_NATIVE_EVENTS = [...BUBBLEABLE_NATIVE_EVENTS, ...MOUSE_NATIVE_EVENTS];
}

const listenersStorage = new SimpleMap(),
    eventsCfg = {};
let areListenersEnabled = true;

function globalEventListener(e, type) {
    if(!areListenersEnabled) {
        return;
    }

    type || (type = e.type);

    const cfg = eventsCfg[type];

    let target = e.target,
        listenersCount = cfg.listenersCounter,
        listeners,
        listener,
        domNodeId,
        syntheticEvent;

    while(listenersCount > 0 && target && target !== document) {
        if(domNodeId = getDomNodeId(target, true)) {
            listeners = listenersStorage.get(domNodeId);
            if(listeners && (listener = listeners[type])) {
                listener(syntheticEvent || (syntheticEvent = createSyntheticEvent(type, e)));
                if(syntheticEvent.isPropagationStopped()) {
                    break;
                }

                --listenersCount;
            }
        }

        target = target.parentNode;
    }
}

function eventListener(e) {
    if(areListenersEnabled) {
        listenersStorage.get(getDomNodeId(e.currentTarget))[e.type](createSyntheticEvent(e.type, e));
    }
}

if(typeof document !== 'undefined') {
    const focusEvents = {
        focus : 'focusin',
        blur : 'focusout'
    };

    let i = 0,
        type;

    while(i < BUBBLEABLE_NATIVE_EVENTS.length) {
        type = BUBBLEABLE_NATIVE_EVENTS[i++];
        eventsCfg[type] = {
            type : type,
            bubbles : true,
            listenersCounter : 0,
            set : false,
            setup : focusEvents[type]?
                isEventSupported(focusEvents[type])?
                    function() {
                        const type = this.type;
                        document.addEventListener(
                            focusEvents[type],
                            e => { globalEventListener(e, type); });
                    } :
                    function() {
                        document.addEventListener(
                            this.type,
                            globalEventListener,
                            true);
                    } :
                null
        };
    }

    i = 0;
    while(i < NON_BUBBLEABLE_NATIVE_EVENTS.length) {
        eventsCfg[NON_BUBBLEABLE_NATIVE_EVENTS[i++]] = {
            type : type,
            bubbles : false,
            set : false
        };
    }
}

function addListener(domNode, type, listener) {
    const cfg = eventsCfg[type];

    if(cfg) {
        if(!cfg.set) {
            cfg.setup?
                cfg.setup() :
                cfg.bubbles && document.addEventListener(type, globalEventListener, false);
            cfg.set = true;
        }

        const domNodeId = getDomNodeId(domNode);
        let listeners = listenersStorage.get(domNodeId);

        if(!listeners) {
            listenersStorage.set(domNodeId, listeners = {});
        }

        if(!listeners[type]) {
            cfg.bubbles?
                ++cfg.listenersCounter :
                domNode.addEventListener(type, eventListener, false);
        }

        listeners[type] = listener;
    }
}

function doRemoveListener(domNode, type) {
    const cfg = eventsCfg[type];

    if(cfg) {
        if(cfg.bubbles) {
            --cfg.listenersCounter;
        }
        else {
            domNode.removeEventListener(type, eventListener);
        }
    }
}

function removeListener(domNode, type) {
    const domNodeId = getDomNodeId(domNode, true);

    if(domNodeId) {
        const listeners = listenersStorage.get(domNodeId);

        if(listeners && listeners[type]) {
            listeners[type] = null;
            doRemoveListener(domNode, type);
        }
    }
}

function removeListeners(domNode) {
    const domNodeId = getDomNodeId(domNode, true);

    if(domNodeId) {
        const listeners = listenersStorage.get(domNodeId);

        if(listeners) {
            for(const type in listeners) {
                if(listeners[type]) {
                    doRemoveListener(domNode, type);
                }
            }

            listenersStorage.delete(domNodeId);
        }
    }
}

function disableListeners() {
    areListenersEnabled = false;
}

function enableListeners() {
    areListenersEnabled = true;
}

export {
    addListener,
    removeListener,
    removeListeners,
    disableListeners,
    enableListeners
};
<commit_msg>Don't touch parentNode if listeners count becomes 0<commit_after>import isEventSupported from './isEventSupported';
import createSyntheticEvent from './createSyntheticEvent';
import getDomNodeId from '../getDomNodeId';
import SimpleMap from '../../utils/SimpleMap';
import { isIos } from '../utils/ua';

const MOUSE_NATIVE_EVENTS = ['click', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup'];
let BUBBLEABLE_NATIVE_EVENTS = [
        'blur', 'change', 'contextmenu', 'copy', 'cut',
        'dblclick', 'drag', 'dragend', 'dragenter', 'dragleave', 'dragover', 'dragstart', 'drop',
        'focus', 'input', 'keydown', 'keypress', 'keyup',
        'paste', 'submit', 'touchcancel', 'touchend', 'touchmove', 'touchstart', 'wheel'
    ],
    NON_BUBBLEABLE_NATIVE_EVENTS = [
        'canplay', 'canplaythrough', 'complete', 'durationchange', 'emptied', 'ended', 'error',
        'load', 'loadeddata', 'loadedmetadata', 'loadstart', 'mouseenter', 'mouseleave',
        'pause', 'play', 'playing', 'progress', 'ratechange',
        'scroll', 'seeked', 'seeking', 'select', 'stalled', 'suspend',
        'timeupdate', 'volumechange', 'waiting'
    ];

if(isIos) {
    NON_BUBBLEABLE_NATIVE_EVENTS = [...NON_BUBBLEABLE_NATIVE_EVENTS, ...MOUSE_NATIVE_EVENTS];
}
else {
    BUBBLEABLE_NATIVE_EVENTS = [...BUBBLEABLE_NATIVE_EVENTS, ...MOUSE_NATIVE_EVENTS];
}

const listenersStorage = new SimpleMap(),
    eventsCfg = {};
let areListenersEnabled = true;

function globalEventListener(e, type = e.type) {
    if(!areListenersEnabled) {
        return;
    }

    let { target } = e,
        { listenersCount } = eventsCfg[type],
        listeners,
        listener,
        domNodeId,
        syntheticEvent;

    while(listenersCount && target && target !== document) { // need to check target for detached dom
        if(domNodeId = getDomNodeId(target, true)) {
            listeners = listenersStorage.get(domNodeId);
            if(listeners && (listener = listeners[type])) {
                listener(syntheticEvent || (syntheticEvent = createSyntheticEvent(type, e)));
                if(!--listenersCount || syntheticEvent.isPropagationStopped()) {
                    return;
                }
            }
        }

        target = target.parentNode;
    }
}

function eventListener(e) {
    if(areListenersEnabled) {
        listenersStorage.get(getDomNodeId(e.currentTarget))[e.type](createSyntheticEvent(e.type, e));
    }
}

if(typeof document !== 'undefined') {
    const focusEvents = {
        focus : 'focusin',
        blur : 'focusout'
    };

    let i = 0,
        type;

    while(i < BUBBLEABLE_NATIVE_EVENTS.length) {
        type = BUBBLEABLE_NATIVE_EVENTS[i++];
        eventsCfg[type] = {
            type : type,
            bubbles : true,
            listenersCount : 0,
            set : false,
            setup : focusEvents[type]?
                isEventSupported(focusEvents[type])?
                    function() {
                        const type = this.type;
                        document.addEventListener(
                            focusEvents[type],
                            e => { globalEventListener(e, type); });
                    } :
                    function() {
                        document.addEventListener(
                            this.type,
                            globalEventListener,
                            true);
                    } :
                null
        };
    }

    i = 0;
    while(i < NON_BUBBLEABLE_NATIVE_EVENTS.length) {
        eventsCfg[NON_BUBBLEABLE_NATIVE_EVENTS[i++]] = {
            type : type,
            bubbles : false,
            set : false
        };
    }
}

function addListener(domNode, type, listener) {
    const cfg = eventsCfg[type];

    if(cfg) {
        if(!cfg.set) {
            cfg.setup?
                cfg.setup() :
                cfg.bubbles && document.addEventListener(type, globalEventListener, false);
            cfg.set = true;
        }

        const domNodeId = getDomNodeId(domNode);
        let listeners = listenersStorage.get(domNodeId);

        if(!listeners) {
            listenersStorage.set(domNodeId, listeners = {});
        }

        if(!listeners[type]) {
            cfg.bubbles?
                ++cfg.listenersCount :
                domNode.addEventListener(type, eventListener, false);
        }

        listeners[type] = listener;
    }
}

function doRemoveListener(domNode, type) {
    const cfg = eventsCfg[type];

    if(cfg) {
        if(cfg.bubbles) {
            --cfg.listenersCount;
        }
        else {
            domNode.removeEventListener(type, eventListener);
        }
    }
}

function removeListener(domNode, type) {
    const domNodeId = getDomNodeId(domNode, true);

    if(domNodeId) {
        const listeners = listenersStorage.get(domNodeId);

        if(listeners && listeners[type]) {
            listeners[type] = null;
            doRemoveListener(domNode, type);
        }
    }
}

function removeListeners(domNode) {
    const domNodeId = getDomNodeId(domNode, true);

    if(domNodeId) {
        const listeners = listenersStorage.get(domNodeId);

        if(listeners) {
            for(const type in listeners) {
                if(listeners[type]) {
                    doRemoveListener(domNode, type);
                }
            }

            listenersStorage.delete(domNodeId);
        }
    }
}

function disableListeners() {
    areListenersEnabled = false;
}

function enableListeners() {
    areListenersEnabled = true;
}

export {
    addListener,
    removeListener,
    removeListeners,
    disableListeners,
    enableListeners
};
<|endoftext|>


<commit_before>Components.utils.import('resource://greasemonkey/prefmanager.js');
Components.utils.import('resource://greasemonkey/util.js');

function GM_loadOptions() {
  document.getElementById('check-uninstall')
      .checked = GM_prefRoot.getValue('uninstallPreferences');
  document.getElementById('check-sync')
  .checked = GM_prefRoot.getValue('sync.enabled');
  document.getElementById('secure-update')
      .checked = GM_prefRoot.getValue('requireSecureUpdates');
  document.getElementById('submit-stats')
      .checked = GM_prefRoot.getValue('stats.optedin');
  document.getElementById('globalExcludes')
      .pages = GM_util.getService().config.globalExcludes;
  document.getElementById('newScript-removeUnused')
      .checked = GM_prefRoot.getValue('newScript.removeUnused');
  document.getElementById('newScript-template')
      .value = GM_prefRoot.getValue('newScript.template');
}

function GM_saveOptions(checkbox) {
  GM_prefRoot.setValue('sync.enabled',
      !!document.getElementById('check-sync').checked);
  GM_prefRoot.setValue('uninstallPreferences',
      !!document.getElementById('check-uninstall').checked);
  GM_prefRoot.setValue('requireSecureUpdates',
      !!document.getElementById('secure-update').checked);
  GM_prefRoot.setValue('stats.optedin',
      !!document.getElementById('submit-stats').checked);
  GM_util.getService().config.globalExcludes =
      document.getElementById('globalExcludes').pages;
  GM_prefRoot.setValue('newScript.removeUnused',
      !!document.getElementById('newScript-removeUnused').checked);
  GM_prefRoot.getValue('newScript.template',
      document.getElementById('newScript-template').value);
}
<commit_msg>Fixed correct setting value for newScript template<commit_after>Components.utils.import('resource://greasemonkey/prefmanager.js');
Components.utils.import('resource://greasemonkey/util.js');

function GM_loadOptions() {
  document.getElementById('check-uninstall')
      .checked = GM_prefRoot.getValue('uninstallPreferences');
  document.getElementById('check-sync')
  .checked = GM_prefRoot.getValue('sync.enabled');
  document.getElementById('secure-update')
      .checked = GM_prefRoot.getValue('requireSecureUpdates');
  document.getElementById('submit-stats')
      .checked = GM_prefRoot.getValue('stats.optedin');
  document.getElementById('globalExcludes')
      .pages = GM_util.getService().config.globalExcludes;
  document.getElementById('newScript-removeUnused')
      .checked = GM_prefRoot.getValue('newScript.removeUnused');
  document.getElementById('newScript-template')
      .value = GM_prefRoot.getValue('newScript.template');
}

function GM_saveOptions(checkbox) {
  GM_prefRoot.setValue('sync.enabled',
      !!document.getElementById('check-sync').checked);
  GM_prefRoot.setValue('uninstallPreferences',
      !!document.getElementById('check-uninstall').checked);
  GM_prefRoot.setValue('requireSecureUpdates',
      !!document.getElementById('secure-update').checked);
  GM_prefRoot.setValue('stats.optedin',
      !!document.getElementById('submit-stats').checked);
  GM_util.getService().config.globalExcludes =
      document.getElementById('globalExcludes').pages;
  GM_prefRoot.setValue('newScript.removeUnused',
      !!document.getElementById('newScript-removeUnused').checked);
  GM_prefRoot.setValue('newScript.template',
      document.getElementById('newScript-template').value);
}
<|endoftext|>


<commit_before>define(function(require, exports, module) {
    main.consumes = ["Plugin", "installer", "c9"];
    main.provides = ["installer.darwin"];
    return main;

    function main(options, imports, register) {
        var Plugin = imports.Plugin;
        var installer = imports.installer;
        var c9 = imports.c9;

        var bashBin = options.bashBin || "bash";

        var plugin = new Plugin("Ajax.org", main.consumes);

        /**
         * Installs a .deb package
         */
        function execute(task, options, onData, callback) {
            installer.ptyExec({
                name: "Darwin",
                bash: bashBin,
                code: require("text!./brew.sh"),
                args: [task],
                cwd: options.cwd,
            }, onData, callback);
        }

        function isAvailable(callback){
            return callback(c9.platform == "darwin");
        }

        plugin.on("load", function() {
            installer.addPackageManager("darwin", plugin);
            installer.addPackageManagerAlias("darwin", "osx");
        });
        plugin.on("unload", function() {
            installer.removePackageManager("darwin");
        });

        plugin.freezePublicAPI({ execute: execute, isAvailable: isAvailable });

        register(null, {
            "installer.darwin": plugin
        });
    }
});<commit_msg>Fix css and fix small typo in installer<commit_after>define(function(require, exports, module) {
    main.consumes = ["Plugin", "installer", "c9"];
    main.provides = ["installer.darwin"];
    return main;

    function main(options, imports, register) {
        var Plugin = imports.Plugin;
        var installer = imports.installer;
        var c9 = imports.c9;

        var bashBin = options.bashBin || "bash";

        var plugin = new Plugin("Ajax.org", main.consumes);

        /**
         * Installs a .deb package
         */
        function execute(task, options, onData, callback) {
            installer.ptyExec({
                name: "Darwin",
                bash: bashBin,
                code: require("text!./darwin.sh"),
                args: [task],
                cwd: options.cwd,
            }, onData, callback);
        }

        function isAvailable(callback){
            return callback(c9.platform == "darwin");
        }

        plugin.on("load", function() {
            installer.addPackageManager("darwin", plugin);
            installer.addPackageManagerAlias("darwin", "osx");
        });
        plugin.on("unload", function() {
            installer.removePackageManager("darwin");
        });

        plugin.freezePublicAPI({ execute: execute, isAvailable: isAvailable });

        register(null, {
            "installer.darwin": plugin
        });
    }
});<|endoftext|>


<commit_before>const { SlashCommandBuilder } = require('@discordjs/builders');
const config = require('../config.json');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('insult')
        .setDescription('sends help message'),
    async execute(interaction) {

        let url = config.mainURL;
        url += "lange=EN&type=json";

        let response = await fetch(url);
        console.log(response)
        await interaction.reply('INSERT INSULT HERE');
    },
};<commit_msg>fix description<commit_after>const { SlashCommandBuilder } = require('@discordjs/builders');
const config = require('../config.json');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('insult')
        .setDescription('generate an evil insult'),
    async execute(interaction) {

        let url = config.mainURL;
        url += "lange=EN&type=json";

        let response = await fetch(url);
        console.log(response)
        await interaction.reply('INSERT INSULT HERE');
    },
};<|endoftext|>


<commit_before>
// eslint-disable-next-line
import React, { Component } from 'react';

import Autosuggest from 'react-autosuggest';

// eslint-disable-next-line
import 'element-theme-default';

import { ipcRenderer } from 'electron';

import './App.css';

import { BottomItem } from './components/helper';
import Caret from './components/caret';
import PastItems from './components/pastItems';

// const getPercentage = (start, end, base = 28800000) => Math.round(base / (new Date(end) - new Date(start)));

function putOngoing(obj) {
  window.localStorage.setItem('ongoing-item', JSON.stringify(obj));
}
function getOngoing() {
  const ongoing = window.localStorage.getItem('ongoing-item');
  if (ongoing) {
    return JSON.parse(ongoing);
  }
  return null;
}

function renderSuggestion(suggestion) {
  return (

      {suggestion.hint}
      {suggestion.description}

  );
}

const hrStyle = {
  display: 'block',
  height: '1px',
  border: 0,
  borderTop: '1px solid rgb(173, 173, 173)',
  margin: '0 0 -1px',
  padding: 0,
};

const slashHints = [{
  hint: '/hi',
  description: 'start working',
  id: 'hi',
  create: name => ({ k: `${Date.now()}hi`, name, created: new Date().toISOString(), type: 'hi' }),
}, {
  hint: '/bye',
  description: 'end working',
  id: 'bye',
  create: name => ({ k: `${Date.now()}bye`, name, created: new Date().toISOString(), type: 'bye' }),
}, {
  hint: '/break',
  description: 'take a break from working',
  id: 'break',
  create: name => ({ k: `${Date.now()}bye`, name, created: new Date().toISOString(), type: 'break' }),
}];

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      timeInput: '',
      pastItems: [],
      hints: slashHints,
      interval: null,
      h: 0,
    };

    this.addTime = this.addTime.bind(this);
    this.onInputChange = this.onInputChange.bind(this);
    this.onSuggestionsClearRequested = this.onSuggestionsClearRequested.bind(this);
    this.stopIntervalUpdate = this.stopIntervalUpdate.bind(this);
    this.startIntervalUpdate = this.startIntervalUpdate.bind(this);
  }

  componentWillMount() {
    this.startIntervalUpdate();
  }

  componentDidMount() {
    if (this.inputField) {
      this.inputField.focus();
    }
    window.addEventListener('focus', () => this.inputField && this.inputField.focus());
    document.addEventListener('keydown', (event) => {
      // ESC
      if (event.keyCode === 27) {
        event.stopPropagation();
        event.preventDefault();
        ipcRenderer.send('hide-app');
      }
    });

    console.log('sending', 'get-entries');

    // load possible latest ongoing
    const ongoing = getOngoing();

    ipcRenderer.on('get-entries-resp', (event, data) => {
      console.log({ data });
      if (ongoing) {
        data.push(ongoing);
      }
      this.setState({
        pastItems: data,
      });
    });
    ipcRenderer.send('get-entries');

    ipcRenderer.on('app-isgoingto-hide', () => {
      console.log('received app-isgoingto-hide');
      if (this.state.interval) {
        this.stopIntervalUpdate();
      }
    });
    ipcRenderer.on('app-isgoingto-show', () => {
      console.log('received app-isgoingto-show');
      if (!this.state.interval) {
        this.startIntervalUpdate();
      }
    });
  }

  componentWillUnmount() {
    this.stopIntervalUpdate();
  }

  onInputChange(event, { newValue, method }) {
    const changeHintList = method !== 'down' && method !== 'up';
    this.setState(prevState => ({
      ...prevState,
      hints: newValue && changeHintList ? slashHints.filter(hint => hint.hint.startsWith(newValue)) : prevState.hints,
      timeInput: newValue,
    }));
    // setTimeout(() => this.messagesEnd.scrollIntoView({behavior: 'smooth' }), 1000)
  }

  onSuggestionsClearRequested() {
    this.setState({
      hints: [],
    });
  }

  stopIntervalUpdate() {
    this.setState(prevState => ({
      interval: clearInterval(prevState.interval),
    }));
  }

  startIntervalUpdate() {
    this.setState(prevState => ({
      interval: setInterval(() => this.setState({ h: prevState.h + 1 }), 1000),
    }));
  }

  addTime(event) {
    event.preventDefault();
    event.stopPropagation();

    const text = this.state.timeInput;

    if (!text) {
      return;
    }

    this.setState((prevState) => {
      const now = new Date().toISOString();
      // ongoing item
      const last = JSON.parse(JSON.stringify(prevState.pastItems.pop()));

      if (last) {
        // finish it
        last.finished = now;
        ipcRenderer.send('new-entry', last);
      }

      // thats the new ongoing item
      let newItem = {};

      // check for special commands
      if (slashHints.some(hint => text.startsWith(hint.hint))) {
        newItem = slashHints.find(hint => text.startsWith(hint.hint)).create(text);
      } else {
        newItem = {
          // TODO: ID creation, rename variable
          k: prevState.pastItems.length + 2 + Date.now(),
          name: text,
          created: now,
        };
      }
      // add new ongoing
      putOngoing(newItem);

      setTimeout(() => this.messagesEnd.scrollIntoView({ behavior: 'smooth' }), 0);

      return {
        ...prevState,
        // put back the now completed ongoing and the new ongoing
        pastItems: [...prevState.pastItems, last, newItem],
        // reset hint list
        // hints: [],
        // reset text input
        timeInput: '',
      };
    });
  }

  render() {
    // Autosuggest will pass through all these props to the input.
    const inputProps = {
      placeholder: 'Type what you are doing...',
      value: this.state.timeInput,
      onChange: this.onInputChange,
    };
    return (

          <Caret />

        TIJD

        <PastItems
          bottomitem={<BottomItem inputRef={(input) => { this.messagesEnd = input; }} />}
          items={this.state.pastItems}
        />

        <form onSubmit={this.addTime} style={{ position: 'absolute', left: 0, bottom: 0, width: '100%' }}>

          <Autosuggest
            suggestions={this.state.hints}
            onSuggestionsFetchRequested={() => { }}
            onSuggestionsClearRequested={this.onSuggestionsClearRequested}
            getSuggestionValue={val => val.hint}
            renderSuggestion={renderSuggestion}
            ref={(value) => { this.inputField = value && value.input ? value.input : null; }}
            inputProps={inputProps}
            className="main-input"
          />
        </form>

    );
  }
}

export default App;
<commit_msg>chore<commit_after>import React, { Component } from 'react';

import Autosuggest from 'react-autosuggest';

// eslint-disable-next-line
import 'element-theme-default';

import { ipcRenderer } from 'electron';

import './App.css';

import { BottomItem } from './components/helper';
import Caret from './components/caret';
import PastItems from './components/pastItems';

// const getPercentage = (start, end, base = 28800000) => Math.round(base / (new Date(end) - new Date(start)));

function putOngoing(obj) {
  window.localStorage.setItem('ongoing-item', JSON.stringify(obj));
}
function getOngoing() {
  const ongoing = window.localStorage.getItem('ongoing-item');
  if (ongoing) {
    return JSON.parse(ongoing);
  }
  return null;
}

function renderSuggestion(suggestion) {
  return (

      {suggestion.hint}
      {suggestion.description}

  );
}

const hrStyle = {
  display: 'block',
  height: '1px',
  border: 0,
  borderTop: '1px solid rgb(173, 173, 173)',
  margin: '0 0 -1px',
  padding: 0,
};

const slashHints = [{
  hint: '/hi',
  description: 'start working',
  id: 'hi',
  create: name => ({ k: `${Date.now()}hi`, name, created: new Date().toISOString(), type: 'hi' }),
}, {
  hint: '/bye',
  description: 'end working',
  id: 'bye',
  create: name => ({ k: `${Date.now()}bye`, name, created: new Date().toISOString(), type: 'bye' }),
}, {
  hint: '/break',
  description: 'take a break from working',
  id: 'break',
  create: name => ({ k: `${Date.now()}bye`, name, created: new Date().toISOString(), type: 'break' }),
}];

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      timeInput: '',
      pastItems: [],
      hints: slashHints,
      interval: null,
      h: 0,
    };

    this.addTime = this.addTime.bind(this);
    this.onInputChange = this.onInputChange.bind(this);
    this.onSuggestionsClearRequested = this.onSuggestionsClearRequested.bind(this);
    this.stopIntervalUpdate = this.stopIntervalUpdate.bind(this);
    this.startIntervalUpdate = this.startIntervalUpdate.bind(this);
  }

  componentWillMount() {
    this.startIntervalUpdate();
  }

  componentDidMount() {
    if (this.inputField) {
      this.inputField.focus();
    }
    window.addEventListener('focus', () => this.inputField && this.inputField.focus());
    document.addEventListener('keydown', (event) => {
      // ESC
      if (event.keyCode === 27) {
        event.stopPropagation();
        event.preventDefault();
        ipcRenderer.send('hide-app');
      }
    });

    console.log('sending', 'get-entries');

    // load possible latest ongoing
    const ongoing = getOngoing();

    ipcRenderer.on('get-entries-resp', (event, data) => {
      console.log({ data });
      if (ongoing) {
        data.push(ongoing);
      }
      this.setState({
        pastItems: data,
      });
    });
    ipcRenderer.send('get-entries');

    ipcRenderer.on('app-isgoingto-hide', () => {
      console.log('received app-isgoingto-hide');
      if (this.state.interval) {
        this.stopIntervalUpdate();
      }
    });
    ipcRenderer.on('app-isgoingto-show', () => {
      console.log('received app-isgoingto-show');
      if (!this.state.interval) {
        this.startIntervalUpdate();
      }
    });
  }

  componentWillUnmount() {
    this.stopIntervalUpdate();
  }

  onInputChange(event, { newValue, method }) {
    const changeHintList = method !== 'down' && method !== 'up';
    this.setState(prevState => ({
      ...prevState,
      hints: newValue && changeHintList ? slashHints.filter(hint => hint.hint.startsWith(newValue)) : prevState.hints,
      timeInput: newValue,
    }));
    // setTimeout(() => this.messagesEnd.scrollIntoView({behavior: 'smooth' }), 1000)
  }

  onSuggestionsClearRequested() {
    this.setState({
      hints: [],
    });
  }

  stopIntervalUpdate() {
    this.setState(prevState => ({
      interval: clearInterval(prevState.interval),
    }));
  }

  startIntervalUpdate() {
    this.setState(prevState => ({
      interval: setInterval(() => this.setState({ h: prevState.h + 1 }), 1000),
    }));
  }

  addTime(event) {
    event.preventDefault();
    event.stopPropagation();

    const text = this.state.timeInput;

    if (!text) {
      return;
    }

    this.setState((prevState) => {
      const now = new Date().toISOString();
      // ongoing item
      const last = JSON.parse(JSON.stringify(prevState.pastItems.pop()));

      if (last) {
        // finish it
        last.finished = now;
        ipcRenderer.send('new-entry', last);
      }

      // thats the new ongoing item
      let newItem = {};

      // check for special commands
      if (slashHints.some(hint => text.startsWith(hint.hint))) {
        newItem = slashHints.find(hint => text.startsWith(hint.hint)).create(text);
      } else {
        newItem = {
          // TODO: ID creation, rename variable
          k: prevState.pastItems.length + 2 + Date.now(),
          name: text,
          created: now,
        };
      }
      // add new ongoing
      putOngoing(newItem);

      setTimeout(() => this.messagesEnd.scrollIntoView({ behavior: 'smooth' }), 0);

      return {
        ...prevState,
        // put back the now completed ongoing and the new ongoing
        pastItems: [...prevState.pastItems, last, newItem],
        // reset hint list
        // hints: [],
        // reset text input
        timeInput: '',
      };
    });
  }

  render() {
    // Autosuggest will pass through all these props to the input.
    const inputProps = {
      placeholder: 'Type what you are doing...',
      value: this.state.timeInput,
      onChange: this.onInputChange,
    };
    return (

          <Caret />

        TIJD

        <PastItems
          bottomitem={<BottomItem inputRef={(input) => { this.messagesEnd = input; }} />}
          items={this.state.pastItems}
        />

        <form onSubmit={this.addTime} style={{ position: 'absolute', left: 0, bottom: 0, width: '100%' }}>

          <Autosuggest
            suggestions={this.state.hints}
            onSuggestionsFetchRequested={() => { }}
            onSuggestionsClearRequested={this.onSuggestionsClearRequested}
            getSuggestionValue={val => val.hint}
            renderSuggestion={renderSuggestion}
            ref={(value) => { this.inputField = value && value.input ? value.input : null; }}
            inputProps={inputProps}
            className="main-input"
          />
        </form>

    );
  }
}

export default App;
<|endoftext|>


<commit_before>const fs = require('fs')
const winston = require('winston')
const Promise = require('bluebird')

var PluginManager = {
    plugin_dir: "",
    totalPluginsList: [],
    availablePlugins: [],

    getPluginById: function (id){
        // TODO: Implement getPluginFromID properly
        return Promise.try(function(){
            //return PluginManager.availablePlugins[id]
            if (id == 0){
                return PluginManager.availablePlugins[0]}
            else{throw new Error("Plugin with id "+id+" does not exist")}
        })
    }
}

/**
 * Set the plugin directory and load all of the plugins in it.
 * @param {string} plugin_dir The path to the directory containing the plugins that Voluble should use.
 */
PluginManager.initAllPlugins = function (plugin_dir) {
    winston.debug("Attempting to load plugins")
    this.plugin_dir = plugin_dir
    this.loadAllPlugins()
}

/**
 * For all of the existent plugins in the plugin directory, try and init each one
 * If this is successful, add the plugin to the list `availablePLugins`.
 */
PluginManager.loadAllPlugins = function () {
    // Cycle through plugin directory and try to init all available plugins
    // FIXME: make loadAllPlugins actually work, and loop through stuff! #1
    let esendexPlugin = require("../plugins/esendex/plugin")
    let plug = esendexPlugin.createPlugin()
    this.availablePlugins.push(plug)
    plug.init()

    /**
     * Logic - the plugin's directory is something we should be able to identify it by.
     * SO: We should loop through all of the directories under the plugin directory and see if a plugin exists in the database with that directory.
     * If so, update it's status to not initialized. Otherwise, create it as not initialized.
     * The point of this is so that when plugins are added, they aren't removed and re-added on startup, which could likely lead to a change in ID number in the database when a new plugin is added or an existing one removed.
     */

    /*try {
        this.availablePlugins.forEach(function (plugin) {
            winston.debug(plugin.createPlugin().init())
        });
    } catch (e) {
        console.log(e)
    }
    */
}

/**
 * For each loaded plugin, call it's `shutdown()` function.
 */
PluginManager.shutdownAllPlugins = function () {
    try {
        this.availablePlugins.forEach(function (plugin) {
            plugin.shutdown()
        })
    } catch (e) {
        console.log(e)
    }
}

module.exports = PluginManager<commit_msg>loadAllPlugins does technically work, but only with the array bodge<commit_after>const fs = require('fs')
const path = require('path');
const winston = require('winston')
const Promise = require('bluebird')

var PluginManager = {
    plugin_dir: "",
    totalPluginsList: [],
    availablePlugins: [],

    getPluginById: function (id) {
        // TODO: Implement getPluginFromID properly
        return Promise.try(function () {
            //return PluginManager.availablePlugins[id]
            if (id == 0) {
                return PluginManager.availablePlugins[0]
            }
            else { throw new Error("Plugin with id " + id + " does not exist") }
        })
    },

    /**
    * For all of the existent plugins in the plugin directory, try and init each one
    * If this is successful, add the plugin to the list `availablePLugins`.
    */

    loadAllPlugins: function () {
        // Cycle through plugin directory and try to init all available plugins
        // FIXME: make loadAllPlugins actually work, and loop through stuff! #1

        /**
         * Logic - the plugin's directory is something we should be able to identify it by.
         * SO: We should loop through all of the directories under the plugin directory and see if a plugin exists in the database with that directory.
         * If so, update it's status to not initialized. Otherwise, create it as not initialized.
         * The point of this is so that when plugins are added, they aren't removed and re-added on startup, which could likely lead to a change in ID number in the database when a new plugin is added or an existing one removed.
         */

        // Get a list of all of the directories under the plugin directory
        let plugin_subdirs = fs.readdirSync(PluginManager.plugin_dir).filter(function (element) {
            let plugin_subdir_fullpath = path.join(PluginManager.plugin_dir, element)

            if (fs.statSync(plugin_subdir_fullpath).isDirectory()) { return true }
            else { return false }
        })

        winston.debug("Found plugins at:\n\t" + plugin_subdirs)

        // Loop through each directory and try to init a plugin if there is one
        plugin_subdirs.forEach(function (plugin_subir_rel) {
            let plugin_file_abs = path.join(PluginManager.plugin_dir, plugin_subir_rel, "plugin.js")
            if (fs.existsSync(plugin_file_abs)) {
                try {
                    let plug = require(plugin_file_abs)
                    let plug_obj = plug.createPlugin()
                    winston.info("Loaded plugin:\n\t" + plug_obj.name)
                    PluginManager.totalPluginsList.push(plug_obj)
                    plug_obj.init()
                    PluginManager.availablePlugins.push(plug_obj)
                } catch (err) {
                    winston.error("Failed to load plugin: " + plugin_file_abs + "\nMessage: " + err.message)
                }
            } else {
                winston.info("No plugin in\n\t" + path.join(PluginManager.plugin_dir, plugin_subir_rel))
            }
        })

    }
}

/**
 * Set the plugin directory and load all of the plugins in it.
 * @param {string} plugin_dir The path to the directory containing the plugins that Voluble should use.
 */
PluginManager.initAllPlugins = function (plugin_dir) {
    winston.debug("Attempting to load plugins")
    this.plugin_dir = plugin_dir
    this.loadAllPlugins()
}

/**
 * For each loaded plugin, call it's `shutdown()` function.
 */
PluginManager.shutdownAllPlugins = function () {
    try {
        this.availablePlugins.forEach(function (plugin) {
            plugin.shutdown()
        })
    } catch (e) {
        console.log(e)
    }
}

module.exports = PluginManager<|endoftext|>