<commit_before>var util = require('./util');
var test = util.test;
var compare = util.compare;
var expect = util.expect;

describe('mode:"hash"', function() {

  describe('matching the right files', function() {

    describe('without recursion', function() {

      it('should contain a file that matches the glob', function(done) {
        test(
          './dummies/module.js',
          'var deps = require("./include/*", {mode: "hash"});',
          function(data) {
            expect(data).to.contain('./include/INCLUDED.js');
            expect(data).to.not.contain('./include/nesting/NESTED_INCLUDE.js');
          }, done);
      });

      it('should return an empty object if it doesn\'t match anything', function(done) {
        test(
          './dummies/module.js',
          'var deps = require("./*", {mode: "hash"});',
          function(data) {
            expect(data).to.not.contain('./module.js');
            expect(data).to.not.match(/require\(\s?("")|('')\)/);
          }, done);
      });

      it('should not contain itself, even if it matches the glob', function(done) {
        test(
          './dummies/include/module.js',
          'var deps = require("./*", {mode: "hash"});',
          function(data) {
            expect(data).to.not.contain('./module.js');
            expect(data).to.contain('./INCLUDED.js');
          }, done);
      });

      it('should be able to match non-js files', function(done) {
        test(
          './dummies/module.js',
          'var deps = require("./template/*", {mode: "hash"});',
          function(data) {
            expect(data).to.not.contain('./module.js');
            expect(data).to.contain('./template/TEMPLATED.hbs');
          }, done);
      });

    });

    describe('with recursion', function() {

      describe('starting from current directory', function() {

        it('should contain a file that matches the glob', function(done) {
          test(
            './dummies/module.js',
            'var deps = require("./**/*.js", {mode: "hash"});',
            function(data) {
              expect(data).to.contain('./include/INCLUDED.js');
              expect(data).to.contain('./include/nesting/NESTED_INCLUDE.js');
              expect(data).to.contain('./ignore/IGNORED.js');
            }, done);
        });

        it('should pass on options to node-glob', function(done) {
          test(
            './dummies/module.js',
            'var deps = require("./**/*.js", {mode: "hash", options: {ignore: \'./ignore/**/*\'}});',
            function(data) {
              expect(data).to.contain('./include/INCLUDED.js');
              expect(data).to.contain('./include/nesting/NESTED_INCLUDE.js');
              expect(data).to.not.contain('./ignore/IGNORED.js');
            }, done);
        });

        it('should return an empty object if it doesn\'t match anything', function(done) {
          test(
            './dummies/module.js',
            'var deps = require("./**/*.bogus", {mode: "hash"});',
            function(data) {
              expect(data).to.not.match(/require\(\s?("")|('')\)/);
            }, done);
        });

        it('should not contain itself, even if it matches the glob', function(done) {
          test(
            './dummies/include/module.js',
            'var deps = require("./*", {mode: "hash"});',
            function(data) {
              expect(data).to.not.contain('./module.js');
              expect(data).to.contain('./INCLUDED.js');
            }, done);
        });

        it('should be able to match non-js files', function(done) {
          test(
            './dummies/module.js',
            'var deps = require("./template/*", {mode: "hash"});',
            function(data) {
              expect(data).to.not.contain('./module.js');
              expect(data).to.contain('./template/TEMPLATED.hbs');
            }, done);
        });

      });

      describe('starting from an ancestor directory', function() {

        it('should contain a file that matches the glob', function(done) {
          test(
            './dummies/include/module.js',
            'var deps = require("../**/*.js", {mode: "hash"});',
            function(data) {
              expect(data).to.contain('../include/INCLUDED.js');
              expect(data).to.contain('../include/nesting/NESTED_INCLUDE.js');
              expect(data).to.contain('../ignore/IGNORED.js');
              expect(data).to.not.contain('../template/TEMPLATED.hbs');
            }, done);
        });

        it('should pass on options to node-glob', function(done) {
          test(
            './dummies/include/module.js',
            'var deps = require("../**/*.js", {mode: "hash", options: {ignore: \'../ignore/**/*\'}});',
            function(data) {
              expect(data).to.contain('../include/INCLUDED.js');
              expect(data).to.contain('../include/nesting/NESTED_INCLUDE.js');
              expect(data).to.not.contain('../ignore/IGNORED.js');
              expect(data).to.not.contain('../template/TEMPLATED.hbs');
            }, done);
        });

        it('should return an empty object if it doesn\'t match anything', function(done) {
          test(
            './dummies/include/module.js',
            'var deps = require("../**/*.bogus", {mode: "hash"});',
            function(data) {
              expect(data).to.not.match(/require\(\s?("")|('')\)/);
              expect(data).to.equal('var deps = {};');
            }, done);
        });

        it('should not contain itself, even if it matches the glob', function(done) {
          test(
            './dummies/include/nesting/module.js',
            'var deps = require("../*", {mode: "hash"});',
            function(data) {
              expect(data).to.not.contain('./module.js');
              expect(data).to.contain('../INCLUDED.js');
            }, done);
        });

        it('should be able to match non-js files', function(done) {
          test(
            './dummies/include/module.js',
            'var deps = require("../template/*", {mode: "hash"});',
            function(data) {
              expect(data).to.not.contain('./module.js');
              expect(data).to.contain('../template/TEMPLATED.hbs');
            }, done);
        });

      });

    });

  });

  describe('with resolver option', function() {

    // - path
    // - strip-ext
    // - path-reduce
    // - reduce-prefix
    // - reduce-postfix
    // - reduce

    describe('default', function() {

      it('should use ["path-reduce", "strip-ext"] as default', function(done) {
        compare('./dummies/module.js',
          'require("./include/**", {mode: "hash"});',
          'require("./include/**", {mode: "hash", resolve:["path-reduce", "strip-ext"]});',
          done);
      });

    });

    describe('resolve:"path-reduce"', function() {

      it('should remove common path', function(done) {
        test(
          './dummies/module.js',
          'var deps = require("./include/**/*", {mode: "hash", resolve: "path-reduce"});',
          function(data) {
            expect(data).to.contain("'INCLUDED.js': require(");
            expect(data).to.contain("'INCLUDED2.js': require(");
            expect(data).to.contain("'nesting/NESTED_INCLUDE.js': require(");
          }, done);
      });

    });

    describe('resolve:"path"', function() {

      it('should use relative path as key', function(done) {
        test(
          './dummies/module.js',
          'var deps = require("./include/**/*", {mode: "hash", resolve: "path", ext:true});',
          function(data) {
            expect(data).to.contain("'include/INCLUDED.js': require(");
            expect(data).to.contain("'include/INCLUDED2.js': require(");
            expect(data).to.contain("'include/nesting/NESTED_INCLUDE.js': require(");
          }, done);
      });

      it('should use relative path as key, when referring to a sibling', function(done) {
        test(
          './dummies/ignore/module.js',
          'var deps = require("../**/*", {mode: "hash", resolve: "path", ext:true});',
          function(data) {
            expect(data).to.contain("'../include/INCLUDED.js': require(");
            expect(data).to.contain("'../include/INCLUDED2.js': require(");
            expect(data).to.contain("'../include/nesting/NESTED_INCLUDE.js': require(");
          }, done);
      });

    });

    describe('resolve:"reduce-postfix"', function() {

      it('should remove common postfix', function(done) {
        test(
          './dummies/module.js',
          'var deps = require("./include/**/*", {mode: "hash", resolve: "reduce-postfix", ext:true});',
          function(data) {
            expect(data).to.contain("'./include/INCLUDED': require(");
            expect(data).to.contain("'./include/INCLUDED2': require(");
            expect(data).to.contain("'./include/nesting/NESTED_INCLUDE': require(");
          }, done);
      });

    });

    describe('resolve:"reduce-prefix"', function() {

      it('should remove common prefix', function(done) {
        test(
          './dummies/module.js',
          'var deps = require("./include/*", {mode: "hash", resolve: "reduce-prefix", ext:true});',
          function(data) {
            expect(data).to.contain("'.js': require(");
            expect(data).to.contain("'2.js': require(");
          }, done);
      });

    });

    describe('resolve:"reduce"', function() {

      it('should remove common pre- and postfix', function(done) {
        test(
          './dummies/module.js',
          'var deps = require("./include/*", {mode: "hash", resolve: "reduce", ext:true});',
          function(data) {
            expect(data).to.contain("'': require(");
            expect(data).to.contain("'2': require(");
          }, done);
      });

    });

    describe('resolve:"strip-ext"', function() {

      it('should remove extension', function(done) {
        test(
          './dummies/module.js',
          'var deps = require("./include/*", {mode: "hash", resolve: "strip-ext"});',
          function(data) {
            expect(data).to.contain("'./include/INCLUDED': require(");
            expect(data).to.contain("'./include/INCLUDED2': require(");
          }, done);
      });

      it('should not remove extension if it causes naming collisions', function(done) {
        test(
          './dummies/template/module.js',
          'var deps = require("./*", {mode: "hash", resolve: "strip-ext"});',
          function(data) {
            expect(data).to.contain("'./TEMPLATED.hbs': require(");
            expect(data).to.contain("'./TEMPLATED.js': require(");
          }, done);
      });

    });

  });

});

describe('backwards compatibility', function() {

  describe('hash:true', function() { // default ext:false

    describe('[default]', function() {
      it('should equal {mode:"hash"}', function(done) {
        compare('./dummies/module.js',
          'require("./include/**/*", {hash: true});',
          'require("./include/**/*", {mode: "hash"});',
          done);
      });

    });

    describe(', ext:false', function() {

      it('should equal {mode:"hash"}', function(done) {
        compare('./dummies/module.js',
          'require("./include/**/*", {hash: true, ext: false});',
          'require("./include/**/*", {mode: "hash"});',
          done);
      });

    });

    describe(', ext:true', function() {

      it('should equal {mode:"hash", resolve:"path-reduce"}', function(done) {
        compare('./dummies/module.js',
          'require("./include/**/*", {hash: true, ext: true});',
          'require("./include/**/*", {mode: "hash", resolve:"path-reduce"});',
          done);
      });

    });

  });

  describe('hash:"path"', function() { // default ext:false

    describe('[default]', function() {
      it('should equal {mode:"hash", resolve:["path", "strip-ext"]}', function(done) {
        compare('./dummies/module.js',
          'require("./include/**/*", {hash: "path"});',
          'require("./include/**/*", {mode: "hash", resolve:["path", "strip-ext"]});',
          done);
      });

    });

    describe(', ext:false', function() {

      it('should equal {mode:"hash", resolve:["path", "strip-ext"]}', function(done) {
        compare('./dummies/module.js',
          'require("./include/**/*", {hash: "path", ext: false});',
          'require("./include/**/*", {mode: "hash", resolve:["path", "strip-ext"]});',
          done);
      });

    });

    describe(', ext:true', function() {

      it('should equal {mode:"hash", resolve:"path"}', function(done) {
        compare('./dummies/module.js',
          'require("./include/**/*", {hash: "path", ext: true});',
          'require("./include/**/*", {mode: "hash", resolve:"path"});',
          done);
      });

    });

  });

});
<commit_msg>Added check for empty object to hash spec.<commit_after>var util = require('./util');
var test = util.test;
var compare = util.compare;
var expect = util.expect;

describe('mode:"hash"', function() {

  describe('matching the right files', function() {

    describe('without recursion', function() {

      it('should contain a file that matches the glob', function(done) {
        test(
          './dummies/module.js',
          'var deps = require("./include/*", {mode: "hash"});',
          function(data) {
            expect(data).to.contain('./include/INCLUDED.js');
            expect(data).to.not.contain('./include/nesting/NESTED_INCLUDE.js');
          }, done);
      });

      it('should return an empty object if it doesn\'t match anything', function(done) {
        test(
          './dummies/module.js',
          'var deps = require("./*", {mode: "hash"});',
          function(data) {
            expect(data).to.not.contain('./module.js');
            expect(data).to.contain('{}');
            expect(data).to.not.match(/require\(\s?("")|('')\)/);
          }, done);
      });

      it('should not contain itself, even if it matches the glob', function(done) {
        test(
          './dummies/include/module.js',
          'var deps = require("./*", {mode: "hash"});',
          function(data) {
            expect(data).to.not.contain('./module.js');
            expect(data).to.contain('./INCLUDED.js');
          }, done);
      });

      it('should be able to match non-js files', function(done) {
        test(
          './dummies/module.js',
          'var deps = require("./template/*", {mode: "hash"});',
          function(data) {
            expect(data).to.not.contain('./module.js');
            expect(data).to.contain('./template/TEMPLATED.hbs');
          }, done);
      });

    });

    describe('with recursion', function() {

      describe('starting from current directory', function() {

        it('should contain a file that matches the glob', function(done) {
          test(
            './dummies/module.js',
            'var deps = require("./**/*.js", {mode: "hash"});',
            function(data) {
              expect(data).to.contain('./include/INCLUDED.js');
              expect(data).to.contain('./include/nesting/NESTED_INCLUDE.js');
              expect(data).to.contain('./ignore/IGNORED.js');
            }, done);
        });

        it('should pass on options to node-glob', function(done) {
          test(
            './dummies/module.js',
            'var deps = require("./**/*.js", {mode: "hash", options: {ignore: \'./ignore/**/*\'}});',
            function(data) {
              expect(data).to.contain('./include/INCLUDED.js');
              expect(data).to.contain('./include/nesting/NESTED_INCLUDE.js');
              expect(data).to.not.contain('./ignore/IGNORED.js');
            }, done);
        });

        it('should return an empty object if it doesn\'t match anything', function(done) {
          test(
            './dummies/module.js',
            'var deps = require("./**/*.bogus", {mode: "hash"});',
            function(data) {
              expect(data).to.contain('{}');
              expect(data).to.not.match(/require\(\s?("")|('')\)/);
            }, done);
        });

        it('should not contain itself, even if it matches the glob', function(done) {
          test(
            './dummies/include/module.js',
            'var deps = require("./*", {mode: "hash"});',
            function(data) {
              expect(data).to.not.contain('./module.js');
              expect(data).to.contain('./INCLUDED.js');
            }, done);
        });

        it('should be able to match non-js files', function(done) {
          test(
            './dummies/module.js',
            'var deps = require("./template/*", {mode: "hash"});',
            function(data) {
              expect(data).to.not.contain('./module.js');
              expect(data).to.contain('./template/TEMPLATED.hbs');
            }, done);
        });

      });

      describe('starting from an ancestor directory', function() {

        it('should contain a file that matches the glob', function(done) {
          test(
            './dummies/include/module.js',
            'var deps = require("../**/*.js", {mode: "hash"});',
            function(data) {
              expect(data).to.contain('../include/INCLUDED.js');
              expect(data).to.contain('../include/nesting/NESTED_INCLUDE.js');
              expect(data).to.contain('../ignore/IGNORED.js');
              expect(data).to.not.contain('../template/TEMPLATED.hbs');
            }, done);
        });

        it('should pass on options to node-glob', function(done) {
          test(
            './dummies/include/module.js',
            'var deps = require("../**/*.js", {mode: "hash", options: {ignore: \'../ignore/**/*\'}});',
            function(data) {
              expect(data).to.contain('../include/INCLUDED.js');
              expect(data).to.contain('../include/nesting/NESTED_INCLUDE.js');
              expect(data).to.not.contain('../ignore/IGNORED.js');
              expect(data).to.not.contain('../template/TEMPLATED.hbs');
            }, done);
        });

        it('should return an empty object if it doesn\'t match anything', function(done) {
          test(
            './dummies/include/module.js',
            'var deps = require("../**/*.bogus", {mode: "hash"});',
            function(data) {
              expect(data).to.not.match(/require\(\s?("")|('')\)/);
              expect(data).to.equal('var deps = {};');
            }, done);
        });

        it('should not contain itself, even if it matches the glob', function(done) {
          test(
            './dummies/include/nesting/module.js',
            'var deps = require("../*", {mode: "hash"});',
            function(data) {
              expect(data).to.not.contain('./module.js');
              expect(data).to.contain('../INCLUDED.js');
            }, done);
        });

        it('should be able to match non-js files', function(done) {
          test(
            './dummies/include/module.js',
            'var deps = require("../template/*", {mode: "hash"});',
            function(data) {
              expect(data).to.not.contain('./module.js');
              expect(data).to.contain('../template/TEMPLATED.hbs');
            }, done);
        });

      });

    });

  });

  describe('with resolver option', function() {

    // - path
    // - strip-ext
    // - path-reduce
    // - reduce-prefix
    // - reduce-postfix
    // - reduce

    describe('default', function() {

      it('should use ["path-reduce", "strip-ext"] as default', function(done) {
        compare('./dummies/module.js',
          'require("./include/**", {mode: "hash"});',
          'require("./include/**", {mode: "hash", resolve:["path-reduce", "strip-ext"]});',
          done);
      });

    });

    describe('resolve:"path-reduce"', function() {

      it('should remove common path', function(done) {
        test(
          './dummies/module.js',
          'var deps = require("./include/**/*", {mode: "hash", resolve: "path-reduce"});',
          function(data) {
            expect(data).to.contain("'INCLUDED.js': require(");
            expect(data).to.contain("'INCLUDED2.js': require(");
            expect(data).to.contain("'nesting/NESTED_INCLUDE.js': require(");
          }, done);
      });

    });

    describe('resolve:"path"', function() {

      it('should use relative path as key', function(done) {
        test(
          './dummies/module.js',
          'var deps = require("./include/**/*", {mode: "hash", resolve: "path", ext:true});',
          function(data) {
            expect(data).to.contain("'include/INCLUDED.js': require(");
            expect(data).to.contain("'include/INCLUDED2.js': require(");
            expect(data).to.contain("'include/nesting/NESTED_INCLUDE.js': require(");
          }, done);
      });

      it('should use relative path as key, when referring to a sibling', function(done) {
        test(
          './dummies/ignore/module.js',
          'var deps = require("../**/*", {mode: "hash", resolve: "path", ext:true});',
          function(data) {
            expect(data).to.contain("'../include/INCLUDED.js': require(");
            expect(data).to.contain("'../include/INCLUDED2.js': require(");
            expect(data).to.contain("'../include/nesting/NESTED_INCLUDE.js': require(");
          }, done);
      });

    });

    describe('resolve:"reduce-postfix"', function() {

      it('should remove common postfix', function(done) {
        test(
          './dummies/module.js',
          'var deps = require("./include/**/*", {mode: "hash", resolve: "reduce-postfix", ext:true});',
          function(data) {
            expect(data).to.contain("'./include/INCLUDED': require(");
            expect(data).to.contain("'./include/INCLUDED2': require(");
            expect(data).to.contain("'./include/nesting/NESTED_INCLUDE': require(");
          }, done);
      });

    });

    describe('resolve:"reduce-prefix"', function() {

      it('should remove common prefix', function(done) {
        test(
          './dummies/module.js',
          'var deps = require("./include/*", {mode: "hash", resolve: "reduce-prefix", ext:true});',
          function(data) {
            expect(data).to.contain("'.js': require(");
            expect(data).to.contain("'2.js': require(");
          }, done);
      });

    });

    describe('resolve:"reduce"', function() {

      it('should remove common pre- and postfix', function(done) {
        test(
          './dummies/module.js',
          'var deps = require("./include/*", {mode: "hash", resolve: "reduce", ext:true});',
          function(data) {
            expect(data).to.contain("'': require(");
            expect(data).to.contain("'2': require(");
          }, done);
      });

    });

    describe('resolve:"strip-ext"', function() {

      it('should remove extension', function(done) {
        test(
          './dummies/module.js',
          'var deps = require("./include/*", {mode: "hash", resolve: "strip-ext"});',
          function(data) {
            expect(data).to.contain("'./include/INCLUDED': require(");
            expect(data).to.contain("'./include/INCLUDED2': require(");
          }, done);
      });

      it('should not remove extension if it causes naming collisions', function(done) {
        test(
          './dummies/template/module.js',
          'var deps = require("./*", {mode: "hash", resolve: "strip-ext"});',
          function(data) {
            expect(data).to.contain("'./TEMPLATED.hbs': require(");
            expect(data).to.contain("'./TEMPLATED.js': require(");
          }, done);
      });

    });

  });

});

describe('backwards compatibility', function() {

  describe('hash:true', function() { // default ext:false

    describe('[default]', function() {
      it('should equal {mode:"hash"}', function(done) {
        compare('./dummies/module.js',
          'require("./include/**/*", {hash: true});',
          'require("./include/**/*", {mode: "hash"});',
          done);
      });

    });

    describe(', ext:false', function() {

      it('should equal {mode:"hash"}', function(done) {
        compare('./dummies/module.js',
          'require("./include/**/*", {hash: true, ext: false});',
          'require("./include/**/*", {mode: "hash"});',
          done);
      });

    });

    describe(', ext:true', function() {

      it('should equal {mode:"hash", resolve:"path-reduce"}', function(done) {
        compare('./dummies/module.js',
          'require("./include/**/*", {hash: true, ext: true});',
          'require("./include/**/*", {mode: "hash", resolve:"path-reduce"});',
          done);
      });

    });

  });

  describe('hash:"path"', function() { // default ext:false

    describe('[default]', function() {
      it('should equal {mode:"hash", resolve:["path", "strip-ext"]}', function(done) {
        compare('./dummies/module.js',
          'require("./include/**/*", {hash: "path"});',
          'require("./include/**/*", {mode: "hash", resolve:["path", "strip-ext"]});',
          done);
      });

    });

    describe(', ext:false', function() {

      it('should equal {mode:"hash", resolve:["path", "strip-ext"]}', function(done) {
        compare('./dummies/module.js',
          'require("./include/**/*", {hash: "path", ext: false});',
          'require("./include/**/*", {mode: "hash", resolve:["path", "strip-ext"]});',
          done);
      });

    });

    describe(', ext:true', function() {

      it('should equal {mode:"hash", resolve:"path"}', function(done) {
        compare('./dummies/module.js',
          'require("./include/**/*", {hash: "path", ext: true});',
          'require("./include/**/*", {mode: "hash", resolve:"path"});',
          done);
      });

    });

  });

});
<|endoftext|>


<commit_before>var vm = require('vm');
var fs = require('fs');

include = function (file) {
	var code = fs.readFileSync(file, 'utf-8');
	vm.runInThisContext(code, {filename: file});
};
<commit_msg>Delete unused include.js<commit_after><|endoftext|>


<commit_before>/*jshint node:true*/

var fs          = require('fs');
var path        = require('path');
var walkSync    = require('walk-sync');
var stringUtil  = require('../../lib/utilities/string');
var uniq        = require('lodash/array/uniq');
var Blueprint   = require('../../lib/models/blueprint');
var SilentError = require('../../lib/errors/silent');
var date        = new Date();

module.exports = {
  description: 'The default blueprint for ember-cli addons.',

  generatePackageJson: function() {
    var packagePath = path.join(this._appBlueprint.path, 'files', 'package.json');
    var contents    = JSON.parse(fs.readFileSync(packagePath, { encoding: 'utf8' }));

    delete contents.private;
    contents.name = this.project.name();
    contents.description = this.description;
    contents.keywords = contents.keywords || [];
    contents.dependencies = contents.dependencies || {};

    // npm doesn't like it when we have something in both deps and devDeps
    // and dummy app still uses it when in deps
    contents.dependencies['ember-cli-babel'] = contents.devDependencies['ember-cli-babel'];
    delete contents.devDependencies['ember-cli-babel'];

    if (contents.keywords.indexOf('ember-addon') === -1) {
      contents.keywords.push('ember-addon');
    }

    // add `ember-disable-prototype-extensions` to addons by default
    contents.devDependencies['ember-disable-prototype-extensions'] = '^1.0.0';

    // add `ember-try` to addons by default
    contents.devDependencies['ember-try'] = '0.0.4';
    contents.scripts.test = "ember try:testall";

    contents['ember-addon'] = contents['ember-addon'] || {};
    contents['ember-addon'].configPath = 'tests/dummy/config';

    fs.writeFileSync(path.join(this.path, 'files', 'package.json'), JSON.stringify(contents, null, 2));
  },

  generateBowerJson: function() {
    var bowerPath = path.join(this._appBlueprint.path, 'files', 'bower.json');
    var contents  = JSON.parse(fs.readFileSync(bowerPath, { encoding: 'utf8' }));

    contents.name = this.project.name();

    fs.writeFileSync(path.join(this.path, 'files', 'bower.json'), JSON.stringify(contents, null, 2));
  },

  afterInstall: function() {
    var packagePath = path.join(this.path, 'files', 'package.json');
    var bowerPath = path.join(this.path, 'files', 'bower.json');

    [packagePath, bowerPath].forEach(function(filePath) {
      if (fs.existsSync(filePath)) {
        fs.unlinkSync(filePath);
      }
    });
  },

  locals: function(options) {
    var entity    = { name: 'dummy' };
    var rawName   = entity.name;
    var name      = stringUtil.dasherize(rawName);
    var namespace = stringUtil.classify(rawName);

    var addonEntity    = options.entity;
    var addonRawName   = addonEntity.name;
    var addonName      = stringUtil.dasherize(addonRawName);
    var addonNamespace = stringUtil.classify(addonRawName);

    return {
      name: name,
      modulePrefix: name,
      namespace: namespace,
      addonName: addonName,
      addonModulePrefix: addonName,
      addonNamespace: addonNamespace,
      emberCLIVersion: require('../../package').version,
      year: date.getFullYear()
    };
  },

  files: function() {
    if (this._files) { return this._files; }

    this._appBlueprint   = this.lookupBlueprint('app');
    var appFiles       = this._appBlueprint.files();

    this.generatePackageJson();
    this.generateBowerJson();

    var addonFiles   = walkSync(path.join(this.path, 'files'));

    return this._files = uniq(appFiles.concat(addonFiles));
  },

  mapFile: function(file, locals) {
    var result = this._super.mapFile.call(this, file, locals);
    return this.fileMapper(result);
  },

  fileMap: {
    '^app/.gitkeep': 'app/.gitkeep',
    '^app.*':        'tests/dummy/:path',
    '^config.*':     'tests/dummy/:path',
    '^public.*':     'tests/dummy/:path',

    '^addon-config/environment.js': 'config/environment.js',
    '^addon-config/ember-try.js'  : 'config/ember-try.js',

    '^npmignore': '.npmignore'
  },

  fileMapper: function(path) {
    for (var pattern in this.fileMap) {
      if ((new RegExp(pattern)).test(path)) {
        return this.fileMap[pattern].replace(':path', path);
      }
    }

    return path;
  },

  srcPath: function(file) {
    var filePath = path.resolve(this.path, 'files', file);
    if (fs.existsSync(filePath)) {
      return filePath;
    } else {
      return path.resolve(this._appBlueprint.path, 'files', file);
    }
  },

  normalizeEntityName: function(entityName) {
    entityName = Blueprint.prototype.normalizeEntityName.apply(this, arguments);

    if(this.project.isEmberCLIProject() && !this.project.isEmberCLIAddon()) {
      throw new SilentError('Generating an addon in an existing ember-cli project is not supported.');
    }

    return entityName;
  }
};
<commit_msg>Upgrade ember-try dependency in addon blueprint<commit_after>/*jshint node:true*/

var fs          = require('fs');
var path        = require('path');
var walkSync    = require('walk-sync');
var stringUtil  = require('../../lib/utilities/string');
var uniq        = require('lodash/array/uniq');
var Blueprint   = require('../../lib/models/blueprint');
var SilentError = require('../../lib/errors/silent');
var date        = new Date();

module.exports = {
  description: 'The default blueprint for ember-cli addons.',

  generatePackageJson: function() {
    var packagePath = path.join(this._appBlueprint.path, 'files', 'package.json');
    var contents    = JSON.parse(fs.readFileSync(packagePath, { encoding: 'utf8' }));

    delete contents.private;
    contents.name = this.project.name();
    contents.description = this.description;
    contents.keywords = contents.keywords || [];
    contents.dependencies = contents.dependencies || {};

    // npm doesn't like it when we have something in both deps and devDeps
    // and dummy app still uses it when in deps
    contents.dependencies['ember-cli-babel'] = contents.devDependencies['ember-cli-babel'];
    delete contents.devDependencies['ember-cli-babel'];

    if (contents.keywords.indexOf('ember-addon') === -1) {
      contents.keywords.push('ember-addon');
    }

    // add `ember-disable-prototype-extensions` to addons by default
    contents.devDependencies['ember-disable-prototype-extensions'] = '^1.0.0';

    // add `ember-try` to addons by default
    contents.devDependencies['ember-try'] = '0.0.6';
    contents.scripts.test = "ember try:testall";

    contents['ember-addon'] = contents['ember-addon'] || {};
    contents['ember-addon'].configPath = 'tests/dummy/config';

    fs.writeFileSync(path.join(this.path, 'files', 'package.json'), JSON.stringify(contents, null, 2));
  },

  generateBowerJson: function() {
    var bowerPath = path.join(this._appBlueprint.path, 'files', 'bower.json');
    var contents  = JSON.parse(fs.readFileSync(bowerPath, { encoding: 'utf8' }));

    contents.name = this.project.name();

    fs.writeFileSync(path.join(this.path, 'files', 'bower.json'), JSON.stringify(contents, null, 2));
  },

  afterInstall: function() {
    var packagePath = path.join(this.path, 'files', 'package.json');
    var bowerPath = path.join(this.path, 'files', 'bower.json');

    [packagePath, bowerPath].forEach(function(filePath) {
      if (fs.existsSync(filePath)) {
        fs.unlinkSync(filePath);
      }
    });
  },

  locals: function(options) {
    var entity    = { name: 'dummy' };
    var rawName   = entity.name;
    var name      = stringUtil.dasherize(rawName);
    var namespace = stringUtil.classify(rawName);

    var addonEntity    = options.entity;
    var addonRawName   = addonEntity.name;
    var addonName      = stringUtil.dasherize(addonRawName);
    var addonNamespace = stringUtil.classify(addonRawName);

    return {
      name: name,
      modulePrefix: name,
      namespace: namespace,
      addonName: addonName,
      addonModulePrefix: addonName,
      addonNamespace: addonNamespace,
      emberCLIVersion: require('../../package').version,
      year: date.getFullYear()
    };
  },

  files: function() {
    if (this._files) { return this._files; }

    this._appBlueprint   = this.lookupBlueprint('app');
    var appFiles       = this._appBlueprint.files();

    this.generatePackageJson();
    this.generateBowerJson();

    var addonFiles   = walkSync(path.join(this.path, 'files'));

    return this._files = uniq(appFiles.concat(addonFiles));
  },

  mapFile: function(file, locals) {
    var result = this._super.mapFile.call(this, file, locals);
    return this.fileMapper(result);
  },

  fileMap: {
    '^app/.gitkeep': 'app/.gitkeep',
    '^app.*':        'tests/dummy/:path',
    '^config.*':     'tests/dummy/:path',
    '^public.*':     'tests/dummy/:path',

    '^addon-config/environment.js': 'config/environment.js',
    '^addon-config/ember-try.js'  : 'config/ember-try.js',

    '^npmignore': '.npmignore'
  },

  fileMapper: function(path) {
    for (var pattern in this.fileMap) {
      if ((new RegExp(pattern)).test(path)) {
        return this.fileMap[pattern].replace(':path', path);
      }
    }

    return path;
  },

  srcPath: function(file) {
    var filePath = path.resolve(this.path, 'files', file);
    if (fs.existsSync(filePath)) {
      return filePath;
    } else {
      return path.resolve(this._appBlueprint.path, 'files', file);
    }
  },

  normalizeEntityName: function(entityName) {
    entityName = Blueprint.prototype.normalizeEntityName.apply(this, arguments);

    if(this.project.isEmberCLIProject() && !this.project.isEmberCLIAddon()) {
      throw new SilentError('Generating an addon in an existing ember-cli project is not supported.');
    }

    return entityName;
  }
};
<|endoftext|>


<commit_before>/* export something */
module.exports = new Kutility;

/* constructor does nothing at this point */
function Kutility() {

}

/**
 * get a random object from the array arr
 *
 * @api public
 */

Kutility.prototype.choice = function(arr) {
    var i = Math.floor(Math.random() * arr.length);
    return arr[i];
}

/**
 * returns a random color as an 'rgb(x, y, z)' string
 *
 * @api public
 */
Kutility.prototype.randColor = function() {
    var r = Math.floor(Math.random() * 256);
    var g = Math.floor(Math.random() * 256);
    var b = Math.floor(Math.random() * 256);
    return 'rgb(' + r + ',' + g + ',' + b + ')';
}

/**
 * Color wheel 1 -> 1536.
 *
 * Written by Henry Van Dusen, all attribution to the big boy.
 * Slightly modified by Kev.
 *
 * @api public
 */
 Kutility.prototype.colorWheel = function(num) {
    var text = "rgb(";
    var entry = num % 1536;
    var num = entry % 256;

    if(entry < 256 * 1)
    	return text + "0,255," + num + ")";
    else if(entry < 256 * 2)
    	return text + "0," + (255 - num) + ",255)";
    else if(entry < 256 * 3)
      return text + num + ",0,255)";
    else if(entry < 256 * 4)
      return text + "255,0," + (255 - num) + ")";
    else if(entry < 256 * 5)
      return text + "255," + num + ",0)";
    else
      return text + (255 - num) + ",255,0)";
 }

 /**
  * Make an rbg() color string an rgba() color string
  *
  * @api public
  */
Kutility.prototype.alphize = function(color, alpha) {
  color.replace('rgb', 'rgba');
  color.replace(')', ', ' + alpha + ')');
  return color;
}

/**
 * Get an array of two random contrasting colors.
 *
 * @api public
 */
Kutility.prototype.contrasters = function() {
  var num = Math.floor(Math.random() * 1536);
  var fg = this.colorWheel(num);
  var bg = this.colorWheel(num + 650);
  return [fg, bg];
}

/**
 * Add a random shadow to a jquery element
 *
 * @api public
 */
Kutility.prototype.addShadow = function(el, size) {
  var s = size + 'px';
  var shadow = '0px 0px ' + s + ' ' + s + ' ' + this.randColor();
  el.css('-webkit-box-shadow', shadow);
  el.css('-moz-box-shadow', shadow);
  el.css('box-shadow', shadow);
}

/**
 * Add transform to element with all the lame browser prefixes.
 *
 * @api public
 */
Kutility.prototype.addTransform = function(el, transform) {
  var curTransform = this.getTransform(el);
  curTransform = curTransform.replace('none', '');
  var newTransform = curTransform + transform;
  this.setTransform(el, newTransform);
}

/**
 * Set transform of element with all the lame browser prefixes.
 *
 * @api public
 */
Kutility.prototype.setTransform = function(el, transform) {
  el.css('-webkit-transform', transform);
  el.css('-moz-transform', transform);
  el.css('-ms-transform', transform);
  el.css('-o-transform', transform);
  el.css('transform', transform);
}

/**
 * Check an elements tansform.
 *
 * @api public
 */
Kutility.prototype.getTransform = function(el) {
  var possible = ['transform', '-webkit-transform', '-moz-transform', '-ms-transform', '-o-transform'];

  for (var i = 0; i < possible.length; i++) {
    var f = el.css(possible[i]);
    if (f == 'none' && i + 1 < possible.length) {
      var pf = el.css(possible[i + 1]);
      if (pf)
        continue;
    }
    return f;
  }
}

/**
 * Remove all transforms from element.
 *
 * @api public
 */
Kutility.prototype.clearTransforms = function(el) {
  el.css('-webkit-transform', '');
  el.css('-moz-transform', '');
  el.css('-ms-transform', '');
  el.css('-o-transform', '');
  el.css('transform', '');
}

/**
 * Rotate an element by x degrees.
 *
 * @api public
 */
Kutility.prototype.rotate = function(el, x) {
  var ct = this.getTransform(el);
  ct = ct.replace(/matrix\(.*\)/, '').replace('none', '');

  var t = ' rotate(' + x + 'deg)';
  this.setTransform(el, ct  + t);
}

/**
 * Scale an element by x (no units);
 *
 * @api public
 */
Kutility.prototype.scale = function(el, x) {
  var ct = this.getTransform(el);
  ct = ct.replace(/scale\(.*\)/, '').replace('none', '');

  var t = ' scale(' + x + ')';
  this.setTransform(el, ct + t);
}

/**
 * Translate an element by x, y (include your own units);
 *
 * @api public
 */
Kutility.prototype.translate = function(el, x, y) {
  var ct = this.getTransform(el);
  ct = ct.replace(/translate\(.*\)/, '').replace('none', '');

  var t = ' translate(' + x + ', '  + y + ')';
  this.setTransform(el, ct + t);
}

/**
 * Skew an element by x, y degrees;
 *
 * @api public
 */
Kutility.prototype.skew = function(el, x, y) {
  var ct = this.getTransform(el);
  ct = ct.replace(/skew\(.*\)/, '').replace('none', '');

  var xd = x + 'deg';
  var yd = y + 'deg';
  var t = ' skew(' + xd + ', ' + yd + ')';
  this.setTransform(el, ct + t);
}

/**
 * Warp an element by a random amount by rotating and skewing it.
 *
 * @api public
 */
Kutility.prototype.warp = function(el) {
  var r = Math.floor(Math.random() * 360);
  var x = Math.floor(Math.random() * 360);
  var y = Math.floor(Math.random() * 360);

  this.rotate(el, r);
  this.skew(el, x, y);
}

/**
 * Add filter to element with all the lame browser prefixes.
 *
 * @api public
 */
Kutility.prototype.addFilter = function(el, filter) {
  var curFilter = this.getFilter(el);
  curFilter = curFilter.replace('none', '');
  var newFilter = curFilter + ' ' + filter;
  this.setFilter(el, newFilter);
}

/**
 * Set filter to element with all lame prefixes.
 *
 * @api public
 */
Kutility.prototype.setFilter = function(el, filter) {
  el.css('-webkit-filter', filter);
  el.css('-moz-filter', filter);
  el.css('-ms-filter', filter);
  el.css('-o-filter', filter);
  el.css('filter', filter);
}

/**
 * Check an elements filter.
 *
 * @api public
 */
Kutility.prototype.getFilter = function(el) {
  var possible = ['filter', '-webkit-filter', '-moz-filter', '-ms-filter', '-o-filter'];

  for (var i = 0; i < possible.length; i++) {
    var f = el.css(possible[i]);
    if (f == 'none' && i + 1 < possible.length) {
      var pf = el.css(possible[i + 1]);
      if (pf)
        continue;
    }
    return f;
  }
}

/**
 * Remove all filters from element.
 *
 * @api public
 */
Kutility.prototype.clearFilters = function(el) {
  el.css('-webkit-filter', '');
  el.css('-moz-filter', '');
  el.css('-ms-filter', '');
  el.css('-o-filter', '');
  el.css('filter', '');
}

/**

/**
 * Grayscale an element by x percent.
 *
 * @api public
 */
Kutility.prototype.grayscale = function(el, x) {
  var cf = this.getFilter(el);
  cf = cf.replace(/grayscale\(.*\)/, '').replace('none', '');

  var f = ' grayscale(' + x + '%)';
  this.setFilter(el, cf  + f);
}

/**
 * Sepia an element by x percent.
 *
 * @api public
 */
Kutility.prototype.sepia = function(el, x) {
  var cf = this.getFilter(el);
  cf = cf.replace(/sepia\(.*\)/, '').replace('none', '');

  var f = ' sepia(' + x + '%)';
  this.setFilter(el, cf + f);
}

/**
 * Saturate an element by x percent.
 *
 * @api public
 */
Kutility.prototype.saturate = function(el, x) {
  var cf = this.getFilter(el);
  cf = cf.replace(/saturate\(.*\)/, '').replace('none', '');

  var f = ' saturate(' + x + '%)';
  this.setFilter(el, cf + f);
}

/**
 * Invert an element by x percent.
 *
 * @api public
 */
Kutility.prototype.invert = function(el, x) {
  var cf = this.getFilter(el);
  cf = cf.replace(/invert\(.*\)/, '').replace('none', '');

  var f = ' invert(' + x + '%)';
  this.setFilter(el, cf + f);
}

/**
 * Hue-rotate an element by x degrees.
 *
 * @api public
 */
Kutility.prototype.hutate = function(el, x) {
  var cf = this.getFilter(el);
  cf = cf.replace(/hue-rotate\(.*\)/, '').replace('none', '');

  var f = ' hue-rotate(' + x + 'deg)';
  this.setFilter(el, cf + f);
}

/**
 * Set opacity of an element to x percent.
 *
 * @api public
 */
Kutility.prototype.opace = function(el, x) {
  var cf = this.getFilter(el);
  cf = cf.replace(/opacity\(.*\)/, '').replace('none', '');

  var f = ' opacity(' + x + '%)';
  this.setFilter(el, cf + f);
}

/**
 * Set brightness of an element to x percent.
 *
 * @api public
 */
Kutility.prototype.brightness = function(el, x) {
  var cf = this.getFilter(el);
  cf = cf.replace(/brightness\(.*\)/, '').replace('none', '');

  var f = ' brightness(' + x + '%)';
  this.setFilter(el, cf + f);
}

/**
 * Set contrast of an element to x percent.
 *
 * @api public
 */
Kutility.prototype.contrast = function(el, x) {
  var cf = this.getFilter(el);
  cf = cf.replace(/contrast\(.*\)/, '').replace('none', '');

  var f = ' contrast(' + x + '%)';
  this.setFilter(el, cf + f);
}

/**
 * Blur an element by x pixels.
 *
 * @api public
 */
Kutility.prototype.blur = function(el, x) {
  var cf = this.getFilter(el);
  cf = cf.replace(/blur\(.*\)/, '').replace('none', '');

  var f = ' blur(' + x + 'px)';
  this.setFilter(el, cf + f);
}
<commit_msg>new kutility<commit_after>/* export something */
module.exports = new Kutility;

/* constructor does nothing at this point */
function Kutility() {

}

/**
 * get a random object from the array arr
 *
 * @api public
 */

Kutility.prototype.choice = function(arr) {
    var i = Math.floor(Math.random() * arr.length);
    return arr[i];
}

/**
 * returns a random color as an 'rgb(x, y, z)' string
 *
 * @api public
 */
Kutility.prototype.randColor = function() {
    var r = Math.floor(Math.random() * 256);
    var g = Math.floor(Math.random() * 256);
    var b = Math.floor(Math.random() * 256);
    return 'rgb(' + r + ',' + g + ',' + b + ')';
}

Kutility.prototype.randInt = function(max, min) {
  if (min)
    return Math.floor(Math.random() * (max - min)) + min;
  else
    return Math.floor(Math.random() * (max));
}

/**
 * Color wheel 1 -> 1536.
 *
 * Written by Henry Van Dusen, all attribution to the big boy.
 * Slightly modified by Kev.
 *
 * @api public
 */
 Kutility.prototype.colorWheel = function(num) {
    var text = "rgb(";
    var entry = num % 1536;
    var num = entry % 256;

    if(entry < 256 * 1)
    	return text + "0,255," + num + ")";
    else if(entry < 256 * 2)
    	return text + "0," + (255 - num) + ",255)";
    else if(entry < 256 * 3)
      return text + num + ",0,255)";
    else if(entry < 256 * 4)
      return text + "255,0," + (255 - num) + ")";
    else if(entry < 256 * 5)
      return text + "255," + num + ",0)";
    else
      return text + (255 - num) + ",255,0)";
 }

 /**
  * Make an rbg() color string an rgba() color string
  *
  * @api public
  */
Kutility.prototype.alphize = function(color, alpha) {
  color.replace('rgb', 'rgba');
  color.replace(')', ', ' + alpha + ')');
  return color;
}

/**
 * Get an array of two random contrasting colors.
 *
 * @api public
 */
Kutility.prototype.contrasters = function() {
  var num = Math.floor(Math.random() * 1536);
  var fg = this.colorWheel(num);
  var bg = this.colorWheel(num + 650);
  return [fg, bg];
}

/**
 * Add a random shadow to a jquery element
 *
 * @api public
 */
Kutility.prototype.addShadow = function(el, size) {
  var s = size + 'px';
  var shadow = '0px 0px ' + s + ' ' + s + ' ' + this.randColor();
  el.css('-webkit-box-shadow', shadow);
  el.css('-moz-box-shadow', shadow);
  el.css('box-shadow', shadow);
}

/**
 * Add transform to element with all the lame browser prefixes.
 *
 * @api public
 */
Kutility.prototype.addTransform = function(el, transform) {
  var curTransform = this.getTransform(el);
  curTransform = curTransform.replace('none', '');
  var newTransform = curTransform + transform;
  this.setTransform(el, newTransform);
}

/**
 * Set transform of element with all the lame browser prefixes.
 *
 * @api public
 */
Kutility.prototype.setTransform = function(el, transform) {
  el.css('-webkit-transform', transform);
  el.css('-moz-transform', transform);
  el.css('-ms-transform', transform);
  el.css('-o-transform', transform);
  el.css('transform', transform);
}

/**
 * Check an elements tansform.
 *
 * @api public
 */
Kutility.prototype.getTransform = function(el) {
  var possible = ['transform', '-webkit-transform', '-moz-transform', '-ms-transform', '-o-transform'];

  for (var i = 0; i < possible.length; i++) {
    var f = el.css(possible[i]);
    if (f == 'none' && i + 1 < possible.length) {
      var pf = el.css(possible[i + 1]);
      if (pf)
        continue;
    }
    return f;
  }
}

/**
 * Remove all transforms from element.
 *
 * @api public
 */
Kutility.prototype.clearTransforms = function(el) {
  el.css('-webkit-transform', '');
  el.css('-moz-transform', '');
  el.css('-ms-transform', '');
  el.css('-o-transform', '');
  el.css('transform', '');
}

/**
 * Rotate an element by x degrees.
 *
 * @api public
 */
Kutility.prototype.rotate = function(el, x) {
  var ct = this.getTransform(el);
  ct = ct.replace(/matrix\(.*?\)/, '').replace('none', '');

  var t = ' rotate(' + x + 'deg)';
  this.setTransform(el, ct  + t);
}

/**
 * Scale an element by x (no units);
 *
 * @api public
 */
Kutility.prototype.scale = function(el, x) {
  var ct = this.getTransform(el);
  ct = ct.replace(/scale\(.*?\)/, '').replace('none', '');

  var t = ' scale(' + x + ')';
  this.setTransform(el, ct + t);
}

/**
 * Translate an element by x, y (include your own units);
 *
 * @api public
 */
Kutility.prototype.translate = function(el, x, y) {
  var ct = this.getTransform(el);
  ct = ct.replace(/translate\(.*?\)/, '').replace('none', '');

  var t = ' translate(' + x + ', '  + y + ')';
  this.setTransform(el, ct + t);
}

/**
 * Skew an element by x, y degrees;
 *
 * @api public
 */
Kutility.prototype.skew = function(el, x, y) {
  var ct = this.getTransform(el);
  ct = ct.replace(/skew\(.*?\)/, '').replace('none', '');

  var xd = x + 'deg';
  var yd = y + 'deg';
  var t = ' skew(' + xd + ', ' + yd + ')';
  this.setTransform(el, ct + t);
}

/**
 * Warp an element by a random amount by rotating and skewing it.
 *
 * @api public
 */
Kutility.prototype.warp = function(el) {
  var r = Math.floor(Math.random() * 360);
  var x = Math.floor(Math.random() * 360);
  var y = Math.floor(Math.random() * 360);

  this.rotate(el, r);
  this.skew(el, x, y);
}

/**
 * Add filter to element with all the lame browser prefixes.
 *
 * @api public
 */
Kutility.prototype.addFilter = function(el, filter) {
  var curFilter = this.getFilter(el);
  curFilter = curFilter.replace('none', '');
  var newFilter = curFilter + ' ' + filter;
  this.setFilter(el, newFilter);
}

/**
 * Set filter to element with all lame prefixes.
 *
 * @api public
 */
Kutility.prototype.setFilter = function(el, filter) {
  el.css('-webkit-filter', filter);
  el.css('-moz-filter', filter);
  el.css('-ms-filter', filter);
  el.css('-o-filter', filter);
  el.css('filter', filter);
}

/**
 * Check an elements filter.
 *
 * @api public
 */
Kutility.prototype.getFilter = function(el) {
  var possible = ['filter', '-webkit-filter', '-moz-filter', '-ms-filter', '-o-filter'];

  for (var i = 0; i < possible.length; i++) {
    var f = el.css(possible[i]);
    if (f == 'none' && i + 1 < possible.length) {
      var pf = el.css(possible[i + 1]);
      if (pf)
        continue;
    }
    return f;
  }
}

/**
 * Remove all filters from element.
 *
 * @api public
 */
Kutility.prototype.clearFilters = function(el) {
  el.css('-webkit-filter', '');
  el.css('-moz-filter', '');
  el.css('-ms-filter', '');
  el.css('-o-filter', '');
  el.css('filter', '');
}

/**

/**
 * Grayscale an element by x percent.
 *
 * @api public
 */
Kutility.prototype.grayscale = function(el, x) {
  var cf = this.getFilter(el);
  cf = cf.replace(/grayscale\(.*?\)/, '').replace('none', '');

  var f = ' grayscale(' + x + '%)';
  this.setFilter(el, cf  + f);
}

/**
 * Sepia an element by x percent.
 *
 * @api public
 */
Kutility.prototype.sepia = function(el, x) {
  var cf = this.getFilter(el);
  cf = cf.replace(/sepia\(.*?\)/, '').replace('none', '');

  var f = ' sepia(' + x + '%)';
  this.setFilter(el, cf + f);
}

/**
 * Saturate an element by x percent.
 *
 * @api public
 */
Kutility.prototype.saturate = function(el, x) {
  var cf = this.getFilter(el);
  cf = cf.replace(/saturate\(.*?\)/, '').replace('none', '');

  var f = ' saturate(' + x + '%)';
  this.setFilter(el, cf + f);
}

/**
 * Invert an element by x percent.
 *
 * @api public
 */
Kutility.prototype.invert = function(el, x) {
  var cf = this.getFilter(el);
  cf = cf.replace(/invert\(.*?\)/, '').replace('none', '');

  var f = ' invert(' + x + '%)';
  this.setFilter(el, cf + f);
}

/**
 * Hue-rotate an element by x degrees.
 *
 * @api public
 */
Kutility.prototype.hutate = function(el, x) {
  var cf = this.getFilter(el);
  cf = cf.replace(/hue-rotate\(.*?\)/, '').replace('none', '');

  var f = ' hue-rotate(' + x + 'deg)';
  this.setFilter(el, cf + f);
}

/**
 * Set opacity of an element to x percent.
 *
 * @api public
 */
Kutility.prototype.opace = function(el, x) {
  var cf = this.getFilter(el);
  cf = cf.replace(/opacity\(.*?\)/, '').replace('none', '');

  var f = ' opacity(' + x + '%)';
  this.setFilter(el, cf + f);
}

/**
 * Set brightness of an element to x percent.
 *
 * @api public
 */
Kutility.prototype.brightness = function(el, x) {
  var cf = this.getFilter(el);
  cf = cf.replace(/brightness\(.*?\)/, '').replace('none', '');

  var f = ' brightness(' + x + '%)';
  this.setFilter(el, cf + f);
}

/**
 * Set contrast of an element to x percent.
 *
 * @api public
 */
Kutility.prototype.contrast = function(el, x) {
  var cf = this.getFilter(el);
  cf = cf.replace(/contrast\(.*?\)/, '').replace('none', '');

  var f = ' contrast(' + x + '%)';
  this.setFilter(el, cf + f);
}

/**
 * Blur an element by x pixels.
 *
 * @api public
 */
Kutility.prototype.blur = function(el, x) {
  var cf = this.getFilter(el);
  cf = cf.replace(/blur\(.*?\)/, '').replace('none', '');

  var f = ' blur(' + x + 'px)';
  this.setFilter(el, cf + f);
}
<|endoftext|>


<commit_before>'use strict';

// modules dependencies
var mongoat = require('../../index');

var _this;

// test insert method
describe('Insert', function() {
  // connect to db before all tests
  beforeAll(function(done) {
    _this = this;

    mongoat.MongoClient.connect('mongodb://localhost:27017/test')
    .then(function (db) {
      db.dropDatabase();
      _this.testDb = db;
      _this.testCol = db.collection('Person');
      done();
    });
  });

  // close db after all tests
  afterAll(function (done) {
    _this.testCol.find()
    .toArray()
    .then(function (mongoArray) {
      expect(mongoArray.length).toBe(6);

      for (var i = 0; i < mongoArray.length; ++i) {
        expect(mongoArray[i].firstName).toBe('Yacine');
        expect(mongoArray[i].lastName).toBe('KHATAl');
        expect(mongoArray[i].age).toBe(25);

        if (i === 1) {
          expect(mongoArray[i].job).toBe('software engineer');
        } else if (i > 1) {
          expect(mongoArray[i].job).toBe('software engineer');
          expect(mongoArray[i].email).toBe('khatal.yacine@gmail.com');
          expect(mongoArray[i].company).toBe('Dial Once');
        }
      }

      _this.testDb.dropDatabase();
      _this.testDb.close();
      done();
    })
    .catch(function (err) {
      console.error(err);
      _this.testDb.close();
      done();
    });
  });

  // test insert without hooks
  describe('Insert without hooks', function() {
    it('should insert new document to Person collection',
      function (done) {
        _this.testCol.insert({
          firstName: 'Yacine',
          lastName: 'KHATAl',
          age: 25
        }).then(function (mongObject) {
          expect(typeof mongObject).toBe('object');
          expect(typeof mongObject.result).toBe('object');
          expect(mongObject.result.ok).toBe(1);
          expect(mongObject.result.n).toBe(1);
          done();
        });
      });
  });

  // test only with one before insert hook
  describe('Insert with before hooks', function() {
    it('should insert new document to Person collection and handle before insert hook',
    function (done) {
      // add before insert hook
      _this.testCol.before('insert', function (object) {
        expect(object.firstName).toBe('Yacine');
        expect(object.lastName).toBe('KHATAl');
        expect(object.age).toBe(25);
        object.job = 'software engineer';
        return object;
      });

      _this.testCol.insert({
        firstName: 'Yacine',
        lastName: 'KHATAl',
        age: 25
      }).then(function (mongObject) {
        expect(typeof mongObject).toBe('object');
        expect(typeof mongObject.result).toBe('object');
        expect(mongObject.result.ok).toBe(1);
        expect(mongObject.result.n).toBe(1);
        done();
      });
    });

    // test with multiple before insert hooks
    it('should insert new document to Person collection and handle before insert hooks',
    function (done) {
      // add before insert hooks
      _this.testCol.before('insert', function (object) {
        expect(object.firstName).toBe('Yacine');
        expect(object.lastName).toBe('KHATAl');
        expect(object.age).toBe(25);
        object.email = 'khatal.yacine@gmail.com';
        return object;
      });

      _this.testCol.before('insert', function (object) {
        expect(object.firstName).toBe('Yacine');
        expect(object.lastName).toBe('KHATAl');
        expect(object.age).toBe(25);
        expect(object.email).toBe('khatal.yacine@gmail.com');
        object.company = 'Dial Once';
        return object;
      });

      _this.testCol.insert({
        firstName: 'Yacine',
        lastName: 'KHATAl',
        age: 25
      }).then(function (mongObject) {
        expect(typeof mongObject).toBe('object');
        expect(typeof mongObject.result).toBe('object');
        expect(mongObject.result.ok).toBe(1);
        expect(mongObject.result.n).toBe(1);
        done();
      });
    });
  });

  // test only with one after insert hook
  describe('Insert with after hooks', function() {
    it('should insert new document to Person collection and handle after insert hook',
    function (done) {
      // add after insert hook
      _this.testCol.after('insert', function (object) {
        expect(object.firstName).toBe('Yacine');
        expect(object.lastName).toBe('KHATAl');
        expect(object.age).toBe(25);
        return object;
      });

      _this.testCol.insert({
        firstName: 'Yacine',
        lastName: 'KHATAl',
        age: 25
      }).then(function (mongObject) {
        expect(typeof mongObject).toBe('object');
        expect(typeof mongObject.result).toBe('object');
        expect(mongObject.result.ok).toBe(1);
        expect(mongObject.result.n).toBe(1);
        done();
      });
    });

    // test with multiple after insert hooks
    it('should insert new document to Person collection and handle after insert hooks',
    function (done) {
      // add after insert hooks
      _this.testCol.after('insert', function (object) {
        expect(object.firstName).toBe('Yacine');
        expect(object.lastName).toBe('KHATAl');
        expect(object.age).toBe(25);
        return object;
      });

      _this.testCol.after('insert', function (object) {
        expect(object.firstName).toBe('Yacine');
        expect(object.lastName).toBe('KHATAl');
        expect(object.age).toBe(25);
        return object;
      });

      _this.testCol.insert({
        firstName: 'Yacine',
        lastName: 'KHATAl',
        age: 25
      }).then(function (mongObject) {
        expect(typeof mongObject).toBe('object');
        expect(typeof mongObject.result).toBe('object');
        expect(mongObject.result.ok).toBe(1);
        expect(mongObject.result.n).toBe(1);
        done();
      });
    });
  });

  // test with multiple before and after insert hooks
  describe('Insert with before and after hooks', function() {
    it('should insert new document to Person collection and handle before and after insert hooks',
    function (done) {
      // add before insert hooks
      _this.testCol.before('insert', function (object) {
        expect(object.firstName).toBe('Yacine');
        expect(object.lastName).toBe('KHATAl');
        expect(object.age).toBe(25);
        object.email = 'khatal.yacine@gmail.com';
        return object;
      });

      _this.testCol.before('insert', function (object) {
        expect(object.firstName).toBe('Yacine');
        expect(object.lastName).toBe('KHATAl');
        expect(object.age).toBe(25);
        expect(object.email).toBe('khatal.yacine@gmail.com');
        object.company = 'Dial Once';
        return object;
      });

      // add after insert hooks
      _this.testCol.after('insert', function (object) {
        expect(object.firstName).toBe('Yacine');
        expect(object.lastName).toBe('KHATAl');
        expect(object.age).toBe(25);
        expect(object.email).toBe('khatal.yacine@gmail.com');
        expect(object.company).toBe('Dial Once');
        return object;
      });

      _this.testCol.after('insert', function (object) {
        expect(object.firstName).toBe('Yacine');
        expect(object.lastName).toBe('KHATAl');
        expect(object.age).toBe(25);
        expect(object.email).toBe('khatal.yacine@gmail.com');
        expect(object.company).toBe('Dial Once');
        return object;
      });

      _this.testCol.insert({
        firstName: 'Yacine',
        lastName: 'KHATAl',
        age: 25
      }).then(function (mongObject) {
        expect(typeof mongObject).toBe('object');
        expect(typeof mongObject.result).toBe('object');
        expect(mongObject.result.ok).toBe(1);
        expect(mongObject.result.n).toBe(1);
        done();
      });
    });
  });
});
<commit_msg>Cosmetic change - add space<commit_after>'use strict';

// modules dependencies
var mongoat = require('../../index');

var _this;

// test insert method
describe('Insert', function() {
  // connect to db before all tests
  beforeAll(function (done) {
    _this = this;

    mongoat.MongoClient.connect('mongodb://localhost:27017/test')
    .then(function (db) {
      db.dropDatabase();
      _this.testDb = db;
      _this.testCol = db.collection('Person');
      done();
    });
  });

  // close db after all tests
  afterAll(function (done) {
    _this.testCol.find()
    .toArray()
    .then(function (mongoArray) {
      expect(mongoArray.length).toBe(6);

      for (var i = 0; i < mongoArray.length; ++i) {
        expect(mongoArray[i].firstName).toBe('Yacine');
        expect(mongoArray[i].lastName).toBe('KHATAl');
        expect(mongoArray[i].age).toBe(25);

        if (i === 1) {
          expect(mongoArray[i].job).toBe('software engineer');
        } else if (i > 1) {
          expect(mongoArray[i].job).toBe('software engineer');
          expect(mongoArray[i].email).toBe('khatal.yacine@gmail.com');
          expect(mongoArray[i].company).toBe('Dial Once');
        }
      }

      _this.testDb.dropDatabase();
      _this.testDb.close();
      done();
    })
    .catch(function (err) {
      console.error(err);
      _this.testDb.close();
      done();
    });
  });

  // test insert without hooks
  describe('Insert without hooks', function() {
    it('should insert new document to Person collection',
      function (done) {
        _this.testCol.insert({
          firstName: 'Yacine',
          lastName: 'KHATAl',
          age: 25
        }).then(function (mongObject) {
          expect(typeof mongObject).toBe('object');
          expect(typeof mongObject.result).toBe('object');
          expect(mongObject.result.ok).toBe(1);
          expect(mongObject.result.n).toBe(1);
          done();
        });
      });
  });

  // test only with one before insert hook
  describe('Insert with before hooks', function() {
    it('should insert new document to Person collection and handle before insert hook',
    function (done) {
      // add before insert hook
      _this.testCol.before('insert', function (object) {
        expect(object.firstName).toBe('Yacine');
        expect(object.lastName).toBe('KHATAl');
        expect(object.age).toBe(25);
        object.job = 'software engineer';
        return object;
      });

      _this.testCol.insert({
        firstName: 'Yacine',
        lastName: 'KHATAl',
        age: 25
      }).then(function (mongObject) {
        expect(typeof mongObject).toBe('object');
        expect(typeof mongObject.result).toBe('object');
        expect(mongObject.result.ok).toBe(1);
        expect(mongObject.result.n).toBe(1);
        done();
      });
    });

    // test with multiple before insert hooks
    it('should insert new document to Person collection and handle before insert hooks',
    function (done) {
      // add before insert hooks
      _this.testCol.before('insert', function (object) {
        expect(object.firstName).toBe('Yacine');
        expect(object.lastName).toBe('KHATAl');
        expect(object.age).toBe(25);
        object.email = 'khatal.yacine@gmail.com';
        return object;
      });

      _this.testCol.before('insert', function (object) {
        expect(object.firstName).toBe('Yacine');
        expect(object.lastName).toBe('KHATAl');
        expect(object.age).toBe(25);
        expect(object.email).toBe('khatal.yacine@gmail.com');
        object.company = 'Dial Once';
        return object;
      });

      _this.testCol.insert({
        firstName: 'Yacine',
        lastName: 'KHATAl',
        age: 25
      }).then(function (mongObject) {
        expect(typeof mongObject).toBe('object');
        expect(typeof mongObject.result).toBe('object');
        expect(mongObject.result.ok).toBe(1);
        expect(mongObject.result.n).toBe(1);
        done();
      });
    });
  });

  // test only with one after insert hook
  describe('Insert with after hooks', function() {
    it('should insert new document to Person collection and handle after insert hook',
    function (done) {
      // add after insert hook
      _this.testCol.after('insert', function (object) {
        expect(object.firstName).toBe('Yacine');
        expect(object.lastName).toBe('KHATAl');
        expect(object.age).toBe(25);
        return object;
      });

      _this.testCol.insert({
        firstName: 'Yacine',
        lastName: 'KHATAl',
        age: 25
      }).then(function (mongObject) {
        expect(typeof mongObject).toBe('object');
        expect(typeof mongObject.result).toBe('object');
        expect(mongObject.result.ok).toBe(1);
        expect(mongObject.result.n).toBe(1);
        done();
      });
    });

    // test with multiple after insert hooks
    it('should insert new document to Person collection and handle after insert hooks',
    function (done) {
      // add after insert hooks
      _this.testCol.after('insert', function (object) {
        expect(object.firstName).toBe('Yacine');
        expect(object.lastName).toBe('KHATAl');
        expect(object.age).toBe(25);
        return object;
      });

      _this.testCol.after('insert', function (object) {
        expect(object.firstName).toBe('Yacine');
        expect(object.lastName).toBe('KHATAl');
        expect(object.age).toBe(25);
        return object;
      });

      _this.testCol.insert({
        firstName: 'Yacine',
        lastName: 'KHATAl',
        age: 25
      }).then(function (mongObject) {
        expect(typeof mongObject).toBe('object');
        expect(typeof mongObject.result).toBe('object');
        expect(mongObject.result.ok).toBe(1);
        expect(mongObject.result.n).toBe(1);
        done();
      });
    });
  });

  // test with multiple before and after insert hooks
  describe('Insert with before and after hooks', function() {
    it('should insert new document to Person collection and handle before and after insert hooks',
    function (done) {
      // add before insert hooks
      _this.testCol.before('insert', function (object) {
        expect(object.firstName).toBe('Yacine');
        expect(object.lastName).toBe('KHATAl');
        expect(object.age).toBe(25);
        object.email = 'khatal.yacine@gmail.com';
        return object;
      });

      _this.testCol.before('insert', function (object) {
        expect(object.firstName).toBe('Yacine');
        expect(object.lastName).toBe('KHATAl');
        expect(object.age).toBe(25);
        expect(object.email).toBe('khatal.yacine@gmail.com');
        object.company = 'Dial Once';
        return object;
      });

      // add after insert hooks
      _this.testCol.after('insert', function (object) {
        expect(object.firstName).toBe('Yacine');
        expect(object.lastName).toBe('KHATAl');
        expect(object.age).toBe(25);
        expect(object.email).toBe('khatal.yacine@gmail.com');
        expect(object.company).toBe('Dial Once');
        return object;
      });

      _this.testCol.after('insert', function (object) {
        expect(object.firstName).toBe('Yacine');
        expect(object.lastName).toBe('KHATAl');
        expect(object.age).toBe(25);
        expect(object.email).toBe('khatal.yacine@gmail.com');
        expect(object.company).toBe('Dial Once');
        return object;
      });

      _this.testCol.insert({
        firstName: 'Yacine',
        lastName: 'KHATAl',
        age: 25
      }).then(function (mongObject) {
        expect(typeof mongObject).toBe('object');
        expect(typeof mongObject.result).toBe('object');
        expect(mongObject.result.ok).toBe(1);
        expect(mongObject.result.n).toBe(1);
        done();
      });
    });
  });
});
<|endoftext|>


<commit_before>var urlParams;

$(function() {
  resizeWindow();
  parseUrlParameters();
  authenticate();
  FastClick.attach(document.body);
  setUpFormSubmission();
  setUpTagAutoComplete();
  check_for_existing_bookmark_details();
  get_suggested_tags();
  update_user_tags();
  $('input#tags').focus();
  Ladda.bind('button[type=submit]');
});

/** Ensure window is tall enough to show all form elements. */
function resizeWindow() {
  var min_width = 600;
  var min_height = 700;
  if (window.outerHeight < min_height) {
    window.resizeTo(min_width, min_height);
  }

  if (document.addEventListener) {
    document.addEventListener('keydown', winclose, false);
  } else {
    document.attachEvent('onkeydown', winclose);
  }
}

/** Parse URL query parameters into urlParams hash. */
function parseUrlParameters() {
  (window.onpopstate = function () {
    var match,
        pl     = /\+/g,  // Regex for replacing addition symbol with a space
        search = /([^&=]+)=?([^&]*)/g,
        decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
        query  = window.location.search.substring(1);

    urlParams = {};
    while (match = search.exec(query))
       urlParams[decode(match[1])] = decode(match[2]);
  })();

  /* Set form inputs to values passed via URL query parameters. */
  $('input#url').val(urlParams['url']);
  $('input#title').val(urlParams['title']);
  $('textarea#description').val(urlParams['description']);
  $('#suggestion_row, #suggested').hide(); // We’ll show it again later if there are any suggestions
}

function authenticate() {
  if (!(urlParams['user'] && urlParams['token'])) {
    alert("You must provide both ‘user’ and ‘token’ parameters to this page to allow it to use the Pinboard API.");
    $('#submit').addClass('fail');
    $('#submit').prop('disabled', true)
    $('#spinner').addClass('hidden');
  }
}

function auth_token() {
  return urlParams['user'] + ':' + urlParams['token'];
}

function serialized_inputs() {
  var serialized_inputs = $('#url, #title, #description, #tags').serialize();
  if ($('#private').prop('checked')) {
    serialized_inputs += '&shared=no';
  }
  if ($('#toread').prop('checked')) {
    serialized_inputs += '&toread=yes';
  }
  return serialized_inputs;
}

/** Check for pre-existing bookmark for this URL. */
function check_for_existing_bookmark_details() {
  if (!urlParams['url']) { return; }
  var bookmark_details_api = "https://pinboard-bridge.herokuapp.com/posts/get?format=json&auth_token=" + auth_token() + "&url=" + urlParams['url'];

  $.get(bookmark_details_api, 'json')
    .done(function(response) {
      if (response['posts'].length < 1) { return; }
      var bookmark = response['posts'][0];

      $('input#title').val(bookmark['description']);
      $('textarea#description').val(bookmark['extended']);
      prepopulate_tags(bookmark['tags']);

      if (bookmark['shared'] == 'no') {
        $('#private').prop('checked', true);
      }
      if (bookmark['toread'] == 'yes') {
        $('#toread').prop('checked', true);
      }
      if (bookmark['time']) {
        var date = new Date(bookmark['time']);
        $('#bookmark-status').text("Previously saved on " + date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate());
      }
      $('#submit span.text').text('Update bookmark');
      $('#spinner').addClass('hidden');
    })

    .fail(function(response) {
      if (response.status == '401') {
        alert("401 Unauthorised. Please check your username and API access token.");
      }
    });
}

/** Submit the form with Ajax */
function setUpFormSubmission() {
  $('#post-to-pinboard').on('submit', function(event) {
    event.preventDefault();

    var post_bookmark_api = "https://pinboard-bridge.herokuapp.com/posts/add?format=json&auth_token=" + auth_token() + "&" + serialized_inputs();

    $.get(post_bookmark_api, 'json')
      .done(function(response) {
        if (response['result_code'] == 'done') {
          console.log("Bookmark saved correctly.");
          Ladda.stopAll();
          $('#submit').addClass('success');
          setTimeout(function() {
            window.close();
            $('#submit').removeClass('success'); // for windows that aren't popups
          }, 900);
        } else if (response['result_code'] == 'must provide title') {
          Ladda.stopAll();
          $('#submit').addClass('fail');
          setTimeout(function() {
            $('#submit').removeClass('fail'); // let user try again
          }, 1900);
          $('#title').focus();
        }
      })

      .fail(function(response) {
        Ladda.stopAll();
        $('#submit').addClass('fail');
        if (response.status == '401') {
          alert("401 Unauthorised. Please check your username and API access token.");
        }
      });
  });

  $('input, textarea').on('blur', function() {
    $('body').animate({ scrollTop: 0 }, 200);
  });
}

function prepopulate_tags(tagString) {
  var tags = tagString.split(' ');
  console.log(tags);
  var safeIndex = 10000000;
  for (var i = 0; i < tags.length; i++) {
    $('input#tags')[0].selectize.addOption({
      value: i,
      label: tags[i]
    });
    $('input#tags')[0].selectize.addItem(tags[i]);
    console.log(i);
  }
}

function setUpTagAutoComplete() {
  console.log('Setting up autocomplete.');

  $('input#tags').selectize({
    delimiter: ' ',
    create: true,
    openOnFocus: false,
    persist: false,
    maxItems: null,
    hideSelected: true,
    valueField: 'label',
    labelField: 'label',
    searchField: ['label']
  });
}

function get_suggested_tags() {
  if (!urlParams['url']) { return; }
  var suggested_tags_api = "https://pinboard-bridge.herokuapp.com/posts/suggest?format=json&url=" + urlParams['url'] + "&auth_token=" + auth_token();

  $('#spinner').removeClass('hidden');
  $.get(suggested_tags_api, function(data) {
    show_suggested_tags(data);
    $('#spinner').addClass('hidden');
  }, 'json');
}

function update_user_tags() {
  if (!localStorage.tags) {
    localStorage['tags'] = JSON.stringify([]);
    var all_tags_api = "https://pinboard-bridge.herokuapp.com/tags/get?format=json&auth_token=" + auth_token();

    $.get(all_tags_api, 'json')
      .done(function(response) {
        console.log(response);
        localStorage['tags'] = JSON.stringify(response);
        localStorage['tags-updated'] = new Date();
      })

      .fail(function(response) {
        if (response.status == '401') {
          alert("401 Unauthorised. Please check your username and API access token.");
        }
      });
  } else {
    console.log('Have tags');
    console.log(JSON.parse(localStorage['tags']));
  }
}

function prepareDatabase(ready, error) {
  return openDatabase('tags', '1.0', 'Local tag lookup cache', (50 * 1024 * 1024), function(db) {
      db.changeVersion('', '1.0', function (t) {
          t.executeSql('CREATE TABLE tagids (id, name)');
      }, error);
  });
}

function show_suggested_tags(tag_suggestions) {
  if (!tag_suggestions) { return; }
  tag_suggestions = tag_suggestions[0]['popular'].concat(tag_suggestions[1]['recommended']); // flatten JSON
  tag_suggestions = $.unique(tag_suggestions); // filter out duplicates
  tag_suggestions = removeSpuriousResults(tag_suggestions); // empty the array if they are the default/broken suggestions

  var suggested_tags = [];
  for (var i = 0; i < tag_suggestions.length; i++) {
    var suggested_tag = tag_suggestions[i];
    var escaped = pin_escape(suggested_tag);
    var cooked  = pin_cook(suggested_tag);
    var suggested_tag = '<button type="button" class="suggested_tag" onclick="add_tag(\''  +
                escaped + '\'); $(this).hide(); return false;">' + cooked + '</button>';
    suggested_tags.push(suggested_tag);
  }

  if (suggested_tags.length > 0) {
    $('#suggested').append(suggested_tags.join(" "));
    $('#suggestion_row').show();
    $('#suggested').show(800);
  } else {
    $('#suggestion_row th').addClass('none').text('No tag suggestions for this page.');
    $('#suggestion_row').show();
  }
}

/** Remove default set of tags that are suggested by the Pinboard API when there are no good suggestions. */
function removeSpuriousResults(tag_suggestions) {
  if ($.inArray('facebook', tag_suggestions) >= 0 && $.inArray('googlereader', tag_suggestions) >= 0 &&
      $.inArray('ifttt', tag_suggestions) >= 0 && $.inArray('objective-c', tag_suggestions) >= 0 &&
      $.inArray('twitter', tag_suggestions) >= 0 && $.inArray('twitterlink', tag_suggestions) >= 0 &&
      $.inArray('WSH', tag_suggestions) >= 0 && $.inArray('music', tag_suggestions) >= 0 &&
      $.inArray('04:22PM', tag_suggestions) >= 0 && $.inArray('1960s', tag_suggestions) >= 0) {
    return [];
  } else {
    return tag_suggestions;
  }
}

function pin_escape(s) {
  s = s.replace(/\\/g, "\\\\");
  s = s.replace(/'/g, "\\'"); // "
  s = s.replace(/"/g, '"'); // "
  return s;
}

function pin_cook(s) {
  s = s.replace(/</g, '<');
  s = s.replace(/>/g, '>');
  s = s.replace(/"/g, '"');  //"
  return s;
}

RegExp.escape = function(text) {
  return text.replace(/[-[\]{}()*+?.,\\\\'"^$|#\s]/g, "\\$&"); //"'
}

function add_tag(tag) {
  var field = $('#tags');
  var curr = field.val();
  var tag_regex = new RegExp( "(\\b|\\s)" + RegExp.escape(tag) + "(\\b|\\s)");
  if (curr.match(tag_regex) === null) {
    // TODO handle case when tag is at start of field
    field.val(field.val() + " " + tag);
  }
  return false;
}

function pin_sort(a,b) {
  var l = a.toLowerCase ? a.toLowerCase() : a;
  var r = b.toLowerCase ? b.toLowerCase() : b;
  if (l == r) { return 0; }
  if (l > r) { return 1; }
  return -1;
}

function winclose(e) {
  var code;
  if (e.keyCode) {
    code = e.keyCode;
  } else {
    if (e.which) {
      code = e.which;
    }
  }
  if (code == 27) {
    if (!(pin_tagcomplete && pin_tagcomplete.active())) {
      window.close();
    }
  }
}<commit_msg>Let suggested tags be added to the selectize widget.<commit_after>var urlParams;

$(function() {
  resizeWindow();
  parseUrlParameters();
  authenticate();
  FastClick.attach(document.body);
  setUpFormSubmission();
  setUpTagAutoComplete();
  check_for_existing_bookmark_details();
  get_suggested_tags();
  update_user_tags();
  $('input#tags').focus();
  Ladda.bind('button[type=submit]');
});

/** Ensure window is tall enough to show all form elements. */
function resizeWindow() {
  var min_width = 600;
  var min_height = 700;
  if (window.outerHeight < min_height) {
    window.resizeTo(min_width, min_height);
  }

  if (document.addEventListener) {
    document.addEventListener('keydown', winclose, false);
  } else {
    document.attachEvent('onkeydown', winclose);
  }
}

/** Parse URL query parameters into urlParams hash. */
function parseUrlParameters() {
  (window.onpopstate = function () {
    var match,
        pl     = /\+/g,  // Regex for replacing addition symbol with a space
        search = /([^&=]+)=?([^&]*)/g,
        decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
        query  = window.location.search.substring(1);

    urlParams = {};
    while (match = search.exec(query))
       urlParams[decode(match[1])] = decode(match[2]);
  })();

  /* Set form inputs to values passed via URL query parameters. */
  $('input#url').val(urlParams['url']);
  $('input#title').val(urlParams['title']);
  $('textarea#description').val(urlParams['description']);
  $('#suggestion_row, #suggested').hide(); // We’ll show it again later if there are any suggestions
}

function authenticate() {
  if (!(urlParams['user'] && urlParams['token'])) {
    alert("You must provide both ‘user’ and ‘token’ parameters to this page to allow it to use the Pinboard API.");
    $('#submit').addClass('fail');
    $('#submit').prop('disabled', true)
    $('#spinner').addClass('hidden');
  }
}

function auth_token() {
  return urlParams['user'] + ':' + urlParams['token'];
}

function serialized_inputs() {
  var serialized_inputs = $('#url, #title, #description, #tags').serialize();
  if ($('#private').prop('checked')) {
    serialized_inputs += '&shared=no';
  }
  if ($('#toread').prop('checked')) {
    serialized_inputs += '&toread=yes';
  }
  return serialized_inputs;
}

/** Check for pre-existing bookmark for this URL. */
function check_for_existing_bookmark_details() {
  if (!urlParams['url']) { return; }
  var bookmark_details_api = "https://pinboard-bridge.herokuapp.com/posts/get?format=json&auth_token=" + auth_token() + "&url=" + urlParams['url'];

  $.get(bookmark_details_api, 'json')
    .done(function(response) {
      if (response['posts'].length < 1) { return; }
      var bookmark = response['posts'][0];

      $('input#title').val(bookmark['description']);
      $('textarea#description').val(bookmark['extended']);
      prepopulate_tags(bookmark['tags']);

      if (bookmark['shared'] == 'no') {
        $('#private').prop('checked', true);
      }
      if (bookmark['toread'] == 'yes') {
        $('#toread').prop('checked', true);
      }
      if (bookmark['time']) {
        var date = new Date(bookmark['time']);
        $('#bookmark-status').text("Previously saved on " + date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate());
      }
      $('#submit span.text').text('Update bookmark');
      $('#spinner').addClass('hidden');
    })

    .fail(function(response) {
      if (response.status == '401') {
        alert("401 Unauthorised. Please check your username and API access token.");
      }
    });
}

/** Submit the form with Ajax */
function setUpFormSubmission() {
  $('#post-to-pinboard').on('submit', function(event) {
    event.preventDefault();

    var post_bookmark_api = "https://pinboard-bridge.herokuapp.com/posts/add?format=json&auth_token=" + auth_token() + "&" + serialized_inputs();

    $.get(post_bookmark_api, 'json')
      .done(function(response) {
        if (response['result_code'] == 'done') {
          console.log("Bookmark saved correctly.");
          Ladda.stopAll();
          $('#submit').addClass('success');
          setTimeout(function() {
            window.close();
            $('#submit').removeClass('success'); // for windows that aren't popups
          }, 900);
        } else if (response['result_code'] == 'must provide title') {
          Ladda.stopAll();
          $('#submit').addClass('fail');
          setTimeout(function() {
            $('#submit').removeClass('fail'); // let user try again
          }, 1900);
          $('#title').focus();
        }
      })

      .fail(function(response) {
        Ladda.stopAll();
        $('#submit').addClass('fail');
        if (response.status == '401') {
          alert("401 Unauthorised. Please check your username and API access token.");
        }
      });
  });

  $('input, textarea').on('blur', function() {
    $('body').animate({ scrollTop: 0 }, 200);
  });
}

function prepopulate_tags(tagString) {
  var tags = tagString.split(' ');
  for (var i = 0; i < tags.length; i++) {
    $('input#tags')[0].selectize.addOption({
      label: tags[i]
    });
    $('input#tags')[0].selectize.addItem(tags[i]);
  }
}

function setUpTagAutoComplete() {
  console.log('Setting up autocomplete.');

  $('input#tags').selectize({
    delimiter: ' ',
    create: true,
    openOnFocus: false,
    persist: false,
    maxItems: null,
    hideSelected: true,
    valueField: 'label',
    labelField: 'label',
    searchField: ['label']
  });
}

function get_suggested_tags() {
  if (!urlParams['url']) { return; }
  var suggested_tags_api = "https://pinboard-bridge.herokuapp.com/posts/suggest?format=json&url=" + urlParams['url'] + "&auth_token=" + auth_token();

  $('#spinner').removeClass('hidden');
  $.get(suggested_tags_api, function(data) {
    show_suggested_tags(data);
    $('#spinner').addClass('hidden');
  }, 'json');
}

function update_user_tags() {
  if (!localStorage.tags) {
    localStorage['tags'] = JSON.stringify([]);
    var all_tags_api = "https://pinboard-bridge.herokuapp.com/tags/get?format=json&auth_token=" + auth_token();

    $.get(all_tags_api, 'json')
      .done(function(response) {
        console.log(response);
        localStorage['tags'] = JSON.stringify(response);
        localStorage['tags-updated'] = new Date();
      })

      .fail(function(response) {
        if (response.status == '401') {
          alert("401 Unauthorised. Please check your username and API access token.");
        }
      });
  } else {
    console.log('Have tags');
    console.log(JSON.parse(localStorage['tags']));
  }
}

function show_suggested_tags(tag_suggestions) {
  if (!tag_suggestions) { return; }
  tag_suggestions = tag_suggestions[0]['popular'].concat(tag_suggestions[1]['recommended']); // flatten JSON
  tag_suggestions = $.unique(tag_suggestions); // filter out duplicates
  tag_suggestions = removeSpuriousResults(tag_suggestions); // empty the array if they are the default/broken suggestions

  var suggested_tags = [];
  for (var i = 0; i < tag_suggestions.length; i++) {
    var suggested_tag = tag_suggestions[i];
    var escaped = pin_escape(suggested_tag);
    var cooked  = pin_cook(suggested_tag);
    var suggested_tag = '<button type="button" class="suggested_tag" onclick="add_tag(\''  +
                escaped + '\'); $(this).hide(); return false;">' + cooked + '</button>';
    suggested_tags.push(suggested_tag);
  }

  if (suggested_tags.length > 0) {
    $('#suggested').append(suggested_tags.join(" "));
    $('#suggestion_row').show();
    $('#suggested').show(800);
  } else {
    $('#suggestion_row th').addClass('none').text('No tag suggestions for this page.');
    $('#suggestion_row').show();
  }
}

/** Remove default set of tags that are suggested by the Pinboard API when there are no good suggestions. */
function removeSpuriousResults(tag_suggestions) {
  if ($.inArray('facebook', tag_suggestions) >= 0 && $.inArray('googlereader', tag_suggestions) >= 0 &&
      $.inArray('ifttt', tag_suggestions) >= 0 && $.inArray('objective-c', tag_suggestions) >= 0 &&
      $.inArray('twitter', tag_suggestions) >= 0 && $.inArray('twitterlink', tag_suggestions) >= 0 &&
      $.inArray('WSH', tag_suggestions) >= 0 && $.inArray('music', tag_suggestions) >= 0 &&
      $.inArray('04:22PM', tag_suggestions) >= 0 && $.inArray('1960s', tag_suggestions) >= 0) {
    return [];
  } else {
    return tag_suggestions;
  }
}

function pin_escape(s) {
  s = s.replace(/\\/g, "\\\\");
  s = s.replace(/'/g, "\\'"); // "
  s = s.replace(/"/g, '"'); // "
  return s;
}

function pin_cook(s) {
  s = s.replace(/</g, '<');
  s = s.replace(/>/g, '>');
  s = s.replace(/"/g, '"');  //"
  return s;
}

RegExp.escape = function(text) {
  return text.replace(/[-[\]{}()*+?.,\\\\'"^$|#\s]/g, "\\$&"); //"'
}

function add_tag(tag) {
  $('input#tags')[0].selectize.addOption({
    label: tag
  });
  $('input#tags')[0].selectize.addItem(tag);
}

function pin_sort(a,b) {
  var l = a.toLowerCase ? a.toLowerCase() : a;
  var r = b.toLowerCase ? b.toLowerCase() : b;
  if (l == r) { return 0; }
  if (l > r) { return 1; }
  return -1;
}

function winclose(e) {
  var code;
  if (e.keyCode) {
    code = e.keyCode;
  } else {
    if (e.which) {
      code = e.which;
    }
  }
  if (code == 27) {
    if (!(pin_tagcomplete && pin_tagcomplete.active())) {
      window.close();
    }
  }
}<|endoftext|>


<commit_before>document.addEventListener('DOMContentLoaded', function() {
  var checkPageButton = document.getElementById('checkPage');
  checkPageButton.addEventListener('click', function() {

    chrome.tabs.getSelected(null, function(tab) {
      d = document;

      var f = d.createElement('form');
      f.action = 'http://cin.ufpe.br/~robocin/?bm';
      f.method = 'post';
      var i = d.createElement('input');
      i.type = 'hidden';
      i.name = 'url';
      i.value = tab.url;
      f.appendChild(i);
      d.body.appendChild(f);
      f.submit();
    });
  }, false);
}, false);

function updateIcon() {
  console.log("Update");

}

chrome.browserAction.onClicked.addListener(updateIcon);
updateIcon();
document.addEventListener("fill_siga", function() {
  console.log("BBBBBBBBBBB");
}<commit_msg>Erase useless code, also create onload function<commit_after>document.addEventListener('DOMContentLoaded', function() {
  var checkPageButton = document.getElementById('checkPage');
  checkPageButton.addEventListener('click', function() {

    chrome.tabs.getSelected(null, function(tab) {
      d = document;

      var f = d.createElement('form');
      f.action = 'http://cin.ufpe.br/~robocin/?bm';
      f.method = 'post';
      var i = d.createElement('input');
      i.type = 'hidden';
      i.name = 'url';
      i.value = tab.url;
      f.appendChild(i);
      d.body.appendChild(f);
      f.submit();
    });
  }, false);
}, false);

function InitialMsg() {
  console.log("It is Working!");

}

/**
 * This code start "after" html code definitions
 * Get the element checkPage (a button) and criate a listener for the
 * function of click
 */
window.onload = function() {
  InitialMsg();

  document.getElementById("checkPage").addEventListener("click", function(){
    var status = document.getElementById("checkS").checked;
    if(status == true){
       document.getElementById("checkS").checked = false;
    }
    else{
      document.getElementById("checkS").checked = true;
    }
  });

}
<|endoftext|>