<commit_before>var _ = require('underscore'),
    Cheerio = require('cheerio');

var $make = Cheerio.prototype.make;

Cheerio.prototype.make = function(dom, context) {
  var ret = $make.call(this, dom, context);

  ret.__defineGetter__('innerHTML', function() {
    return this.html();
  });
  ret.__defineSetter__('innerHTML', function(html) {
    this.html(html || '');
  });

  return ret;
};

Cheerio.prototype.bind = Cheerio.prototype.unbind =
Cheerio.prototype.on = Cheerio.prototype.off =
Cheerio.prototype.delegate = function() {
  return this;
};

Cheerio.prototype.get = Cheerio.prototype.eq;
Cheerio.prototype.forEach = function(callback, scope) {
  var elements = this;
  elements.each(function(index) {
    callback.call(scope || elements, this, index);
  });
};

Cheerio.prototype.getAttribute = function(name) {
  return this.attr(name);
};

Cheerio.prototype.val = function(value) {
  // TODO : Special case for non-text inputs
  return this.attr('value', value);
};

Cheerio.prototype.css = function(name, value) {
  /*jshint eqnull: true */
  var styles = {};
  (this.attr('style') || '').split(/\s*;\s*/g).forEach(function(style) {
    var components = style.split(':');
    if (!components[0]) {
      return;
    }

    styles[components[0]] = (components[1] || '').replace(/;\s*$/, '');
  });

  if (value != null) {
    styles[name] = value;

    this.attr('style', _.map(styles, function(value, key) { return value ? (key + ':' + value + ';') : ''; }).join(''));
  } else {
    return styles[name];
  }
};
Cheerio.prototype.toggle = function(toggle) {
  if (toggle === undefined) {
    toggle = this.css('display') !== 'none';
  }

  this[toggle ? 'show' : 'hide']();
  return this;
};
Cheerio.prototype.show = function() {
  this.css('display', '');
  return this;
};
Cheerio.prototype.hide = function() {
  this.css('display', 'none');
  return this;
};
Cheerio.prototype.toggleClass = function(className, toggle) {
  if (toggle === undefined) {
    toggle = !this.hasClass(className);
  }
  if (toggle) {
    this.addClass(className);
  } else {
    this.removeClass(className);
  }
  return this;
};

Cheerio.prototype.focus = function() {
  this.attr('autofocus', 'autofocus');
};

Cheerio.prototype.ready = function(callback) {
  callback();
};
<commit_msg>Implement $.prop NOP stub<commit_after>var _ = require('underscore'),
    Cheerio = require('cheerio');

var $make = Cheerio.prototype.make;

Cheerio.prototype.make = function(dom, context) {
  var ret = $make.call(this, dom, context);

  ret.__defineGetter__('innerHTML', function() {
    return this.html();
  });
  ret.__defineSetter__('innerHTML', function(html) {
    this.html(html || '');
  });

  return ret;
};

Cheerio.prototype.bind = Cheerio.prototype.unbind =
Cheerio.prototype.on = Cheerio.prototype.off =
Cheerio.prototype.delegate = function() {
  return this;
};

Cheerio.prototype.prop = function() {
  return this;
};

Cheerio.prototype.get = Cheerio.prototype.eq;
Cheerio.prototype.forEach = function(callback, scope) {
  var elements = this;
  elements.each(function(index) {
    callback.call(scope || elements, this, index);
  });
};

Cheerio.prototype.getAttribute = function(name) {
  return this.attr(name);
};

Cheerio.prototype.val = function(value) {
  // TODO : Special case for non-text inputs
  return this.attr('value', value);
};

Cheerio.prototype.css = function(name, value) {
  /*jshint eqnull: true */
  var styles = {};
  (this.attr('style') || '').split(/\s*;\s*/g).forEach(function(style) {
    var components = style.split(':');
    if (!components[0]) {
      return;
    }

    styles[components[0]] = (components[1] || '').replace(/;\s*$/, '');
  });

  if (value != null) {
    styles[name] = value;

    this.attr('style', _.map(styles, function(value, key) { return value ? (key + ':' + value + ';') : ''; }).join(''));
  } else {
    return styles[name];
  }
};
Cheerio.prototype.toggle = function(toggle) {
  if (toggle === undefined) {
    toggle = this.css('display') !== 'none';
  }

  this[toggle ? 'show' : 'hide']();
  return this;
};
Cheerio.prototype.show = function() {
  this.css('display', '');
  return this;
};
Cheerio.prototype.hide = function() {
  this.css('display', 'none');
  return this;
};
Cheerio.prototype.toggleClass = function(className, toggle) {
  if (toggle === undefined) {
    toggle = !this.hasClass(className);
  }
  if (toggle) {
    this.addClass(className);
  } else {
    this.removeClass(className);
  }
  return this;
};

Cheerio.prototype.focus = function() {
  this.attr('autofocus', 'autofocus');
};

Cheerio.prototype.ready = function(callback) {
  callback();
};
<|endoftext|>


<commit_before>var buildDir = 'build';

var path = require('path');
var UglifyJS = require("uglify-js");
var fs = require('fs');
var cli = require('commander');
var wrench = require('wrench');
var glob = require('glob-whatev')

cli
    .version('0.1.0')
    .option('--pretty', 'Skip uglification and just concatenate the files for debugging.')

cli
    .command('build')
    .description('concatenate (and uglify unless using --pretty) files and place them in the build directory')
    .action(build)

cli
    .command('clean')
    .description('erase the build directory and its contents')
    .action(clean)

function build() {
    clean();
    console.log('building all...');
    gluJS();
    gluJSTest();
    gluJSExt3();
    gluJSExt4();
    copyToBuild('MIT.LICENSE');
    copyToBuild('readme.txt');
    copyExamples();
}

function clean() {
    if (path.existsSync(buildDir)) {
        wrench.rmdirSyncRecursive('build');
        console.log('deleted old build.');
    } else {
        console.log('no old build to clean.');
    }
}

function copyExamples() {
    console.log('copying examples');
    copyDirs('examples', buildDir + '/examples', function(kind, dir, filename, contents){
        if (filename.match(/^\./)) return false;
        if (kind==='f' && (filename==='index.html' || filename==='runner.html')) {
            return contents.replace(/\.\.\/\.\.\/build\/glu/g,'../../glu');
        }
    });
    wrench.mkdirSyncRecursive(buildDir + '/lib/extjs-4.x');
}

function gluJS() {
    console.log('building Core');
    var files = new FileList()
        .include('src/glu.js')
        .include('src/conventions.js')
        .include('src/viewmodel.js')
        .include('src/list.js')
        .include('src/*.js');
    concat('build/glu.js', files);
}

function gluJSTest() {
    console.log('building test library');
    var files = new FileList()
        .include('src/test/*.js');
    concat('build/glu-test.js', files);
}

function gluJSExt3() {
    console.log('building Ext JS 3.x adapter');
    var files = new FileList()
        .include('src/providers/sencha/setup.js')
        .include('src/providers/sencha/*.js')
        .include('src/providers/sencha/adapters_extjs/basic.js')
        .include('src/providers/sencha/adapters_extjs/*.js')
        .include('src/providers/sencha/adapters_extjs3/*.js')
    concat('build/glu-extjs-3.js', files);
}

function gluJSExt4() {
    console.log('building Ext JS 4.x adapter');
    var files = new FileList()
        .include('src/providers/sencha/setup.js')
        .include('src/providers/sencha/*.js')
        .include('src/providers/sencha/adapters_extjs/basic.js')
        .include('src/providers/sencha/adapters_extjs/*.js')
        .include('src/providers/sencha/adapters_extjs4/*.js')
    concat('build/glu-extjs-4.js', files);
}

//MINI-BUILD LIBRARY
var license = "// Copyright (c) 2012 CoNarrative - http://www.conarrative.com/\n" +
    "// License: MIT (http://www.opensource.org/licenses/mit-license.php)\n" +
    "// GluJS version 1.1.0\n";
function concat(combined, files) {
    //make parent directory of combined output file
    var lastSlashIdx = combined.lastIndexOf('/');
    if (lastSlashIdx == -1) {
        lastSlashIdx = combined.lastIndexOf('\\');
    }
    if (lastSlashIdx > 0) {
        wrench.mkdirSyncRecursive(combined.substring(0, lastSlashIdx));
    }
    if (files.toArray) {
        files = files.toArray();
    }
    var out = files.map(function (filePath) {
        var src = fs.readFileSync(filePath, 'utf8');
        return cli.isPretty ?
            '//BEGIN ' + filePath + "\n" + src + '//END' + filePath + "\n" :
            src;
    });
    var final = cli.pretty ?
        license + '\n' + out.join('\n') :
        license + uglify(out.join(' '));
    fs.writeFileSync(combined, final, 'utf8');
}

function uglify(code) {
    ast = UglifyJS.parse(code);
    ast.figure_out_scope();
    compressor = UglifyJS.Compressor({unused:false, warnings:false});
    ast = ast.transform(compressor);
    return ast.print_to_string();
}

FileList = function () {
    this.files = {};
};
FileList.prototype.include = function (pattern) {
    var thisBatch = glob.glob(pattern);
    for (var i = 0; i < thisBatch.length; i++) {
        this.files[thisBatch[i]] = true;
    }
    return this;
}
FileList.prototype.toArray = function () {
    var files = [];
    for (var filename in this.files) {
        files.push(filename);
    }
    return files;
}

copyDirs = function(sourceDir, newDir, filter) {
    filter = filter || function(){};
    var checkDir = fs.statSync(sourceDir);
    try {
        fs.mkdirSync(newDir, checkDir.mode);
    } catch (e) {
        if (e.code !== 'EEXIST') throw e;
    }
    var files = fs.readdirSync(sourceDir);
    for(var i = 0; i < files.length; i++) {
        var filename = files[i];
        var destPath = newDir + '/' + filename;
        var currFile = fs.lstatSync(sourceDir + '/' + filename);
        if(currFile.isDirectory()) {
            //directory
            if (filter('d', sourceDir, filename)!==false) {
                copyDirs(sourceDir + '/' + filename, destPath, filter);
            }
        } else if(currFile.isSymbolicLink()) {
            //sym link
            var symlink = fs.readlinkSync(sourceDir + '/' + filename);
            if (filter('s', sourceDir, filename)!=false) {
                fs.symlinkSync(symlink, destPath);
            }
        } else {
            //file
            var contents = fs.readFileSync(sourceDir + '/' + filename, 'utf8');
            var filtered = filter('f', sourceDir, filename, contents);
            if (filtered!=false) {
                if (typeof(filtered)==='string') {
                    contents = filtered;
                }
                fs.writeFileSync(destPath, contents);
            }
        }
    }
};

function copyToBuild(oldFileName){
    oldFile = fs.createReadStream(oldFileName);
    newFile = fs.createWriteStream(buildDir + '/' + oldFileName);
    require('util').pump(oldFile, newFile);
}

//EXECUTE
cli.parse(process.argv);

<commit_msg>Fixed node existsSync and library licence version<commit_after>var buildDir = 'build';

var path = require('path');
var UglifyJS = require("uglify-js");
var fs = require('fs');
var cli = require('commander');
var wrench = require('wrench');
var glob = require('glob-whatev')

cli
    .version('0.1.0')
    .option('--pretty', 'Skip uglification and just concatenate the files for debugging.')

cli
    .command('build')
    .description('concatenate (and uglify unless using --pretty) files and place them in the build directory')
    .action(build)

cli
    .command('clean')
    .description('erase the build directory and its contents')
    .action(clean)

function build() {
    clean();
    console.log('building all...');
    gluJS();
    gluJSTest();
    gluJSExt3();
    gluJSExt4();
    copyToBuild('MIT.LICENSE');
    copyToBuild('readme.txt');
    copyExamples();
}

function clean() {
    if (fs.existsSync(buildDir)) {
        wrench.rmdirSyncRecursive('build');
        console.log('deleted old build.');
    } else {
        console.log('no old build to clean.');
    }
}

function copyExamples() {
    console.log('copying examples');
    copyDirs('examples', buildDir + '/examples', function(kind, dir, filename, contents){
        if (filename.match(/^\./)) return false;
        if (kind==='f' && (filename==='index.html' || filename==='runner.html')) {
            return contents.replace(/\.\.\/\.\.\/build\/glu/g,'../../glu');
        }
    });
    wrench.mkdirSyncRecursive(buildDir + '/lib/extjs-4.x');
}

function gluJS() {
    console.log('building Core');
    var files = new FileList()
        .include('src/glu.js')
        .include('src/conventions.js')
        .include('src/viewmodel.js')
        .include('src/list.js')
        .include('src/*.js');
    concat('build/glu.js', files);
}

function gluJSTest() {
    console.log('building test library');
    var files = new FileList()
        .include('src/test/*.js');
    concat('build/glu-test.js', files);
}

function gluJSExt3() {
    console.log('building Ext JS 3.x adapter');
    var files = new FileList()
        .include('src/providers/sencha/setup.js')
        .include('src/providers/sencha/*.js')
        .include('src/providers/sencha/adapters_extjs/basic.js')
        .include('src/providers/sencha/adapters_extjs/*.js')
        .include('src/providers/sencha/adapters_extjs3/*.js')
    concat('build/glu-extjs-3.js', files);
}

function gluJSExt4() {
    console.log('building Ext JS 4.x adapter');
    var files = new FileList()
        .include('src/providers/sencha/setup.js')
        .include('src/providers/sencha/*.js')
        .include('src/providers/sencha/adapters_extjs/basic.js')
        .include('src/providers/sencha/adapters_extjs/*.js')
        .include('src/providers/sencha/adapters_extjs4/*.js')
    concat('build/glu-extjs-4.js', files);
}

//MINI-BUILD LIBRARY
var license = "// Copyright (c) 2012 CoNarrative - http://www.conarrative.com/\n" +
    "// License: MIT (http://www.opensource.org/licenses/mit-license.php)\n" +
    "// GluJS version 1.1.0 (maybe it is actually 1.2.0?)\n" +
    "// Build by Murray Hopkins from Ryan Smith fork\n";
function concat(combined, files) {
    //make parent directory of combined output file
    var lastSlashIdx = combined.lastIndexOf('/');
    if (lastSlashIdx == -1) {
        lastSlashIdx = combined.lastIndexOf('\\');
    }
    if (lastSlashIdx > 0) {
        wrench.mkdirSyncRecursive(combined.substring(0, lastSlashIdx));
    }
    if (files.toArray) {
        files = files.toArray();
    }
    var out = files.map(function (filePath) {
        var src = fs.readFileSync(filePath, 'utf8');
        return cli.isPretty ?
            '//BEGIN ' + filePath + "\n" + src + '//END' + filePath + "\n" :
            src;
    });
    var final = cli.pretty ?
        license + '\n' + out.join('\n') :
        license + uglify(out.join(' '));
    fs.writeFileSync(combined, final, 'utf8');
}

function uglify(code) {
    ast = UglifyJS.parse(code);
    ast.figure_out_scope();
    compressor = UglifyJS.Compressor({unused:false, warnings:false});
    ast = ast.transform(compressor);
    return ast.print_to_string();
}

FileList = function () {
    this.files = {};
};
FileList.prototype.include = function (pattern) {
    var thisBatch = glob.glob(pattern);
    for (var i = 0; i < thisBatch.length; i++) {
        this.files[thisBatch[i]] = true;
    }
    return this;
}
FileList.prototype.toArray = function () {
    var files = [];
    for (var filename in this.files) {
        files.push(filename);
    }
    return files;
}

copyDirs = function(sourceDir, newDir, filter) {
    filter = filter || function(){};
    var checkDir = fs.statSync(sourceDir);
    try {
        fs.mkdirSync(newDir, checkDir.mode);
    } catch (e) {
        if (e.code !== 'EEXIST') throw e;
    }
    var files = fs.readdirSync(sourceDir);
    for(var i = 0; i < files.length; i++) {
        var filename = files[i];
        var destPath = newDir + '/' + filename;
        var currFile = fs.lstatSync(sourceDir + '/' + filename);
        if(currFile.isDirectory()) {
            //directory
            if (filter('d', sourceDir, filename)!==false) {
                copyDirs(sourceDir + '/' + filename, destPath, filter);
            }
        } else if(currFile.isSymbolicLink()) {
            //sym link
            var symlink = fs.readlinkSync(sourceDir + '/' + filename);
            if (filter('s', sourceDir, filename)!=false) {
                fs.symlinkSync(symlink, destPath);
            }
        } else {
            //file
            var contents = fs.readFileSync(sourceDir + '/' + filename, 'utf8');
            var filtered = filter('f', sourceDir, filename, contents);
            if (filtered!=false) {
                if (typeof(filtered)==='string') {
                    contents = filtered;
                }
                fs.writeFileSync(destPath, contents);
            }
        }
    }
};

function copyToBuild(oldFileName){
    oldFile = fs.createReadStream(oldFileName);
    newFile = fs.createWriteStream(buildDir + '/' + oldFileName);
    require('util').pump(oldFile, newFile);
}

//EXECUTE
cli.parse(process.argv);

<|endoftext|>


<commit_before>;$(function() {

  if (!$.Jcrop) {
    console.error('Uncaught ReferenceError: Jcrop is not defined')
    return
  }

  var vueCrop = {}
  var options = {}
  var events = [
    'create',
    'start',
    'move',
    'end',
    'focus',
    'blur',
    'remove'
  ]

  vueCrop.install = function(Vue) {

    Vue.directive('crop', {

      acceptStatement: true,

      bind: function() {
        var event = this.arg

        if ($.inArray(event, events) == -1) {
          console.warn('Invalid v-crop event: ' + event)
          return
        }

        if (this.vm.jcrop) return

        var $wrapper = $(this.el).wrap('<div/>').parent()

        $wrapper.width(this.el.width).height(this.el.height)

        this.vm.jcrop = $.Jcrop.attach($wrapper, options)
      },

      update: function(callback) {
        this.vm.jcrop.container.on('crop' + this.arg, callback)
      },

      unbind: function() {
        this.vm.jcrop.container.off('crop' + this.arg)

        if (this._watcher.id != 1) return

        this.vm.jcrop.destroy()
        this.vm.jcrop = null
      }
    })
  }

  vueCrop.setOptions = function(opts) {
    options = opts
  }

  if (window.Vue) {
    window.VueCrop = vueCrop
    Vue.use(vueCrop)
  }

}());
<commit_msg>Attach jcrop object to the element (fix #4)<commit_after>;$(function() {

  if (!$.Jcrop) {
    console.error('Uncaught ReferenceError: Jcrop is not defined')
    return
  }

  var vueCrop = {}
  var options = {}
  var events = [
    'create',
    'start',
    'move',
    'end',
    'focus',
    'blur',
    'remove'
  ]

  vueCrop.install = function(Vue) {

    Vue.directive('crop', {

      acceptStatement: true,

      bind: function() {
        var event = this.arg

        if ($.inArray(event, events) == -1) {
          console.warn('Invalid v-crop event: ' + event)
          return
        }

        if (this.el.jcrop) return

        var $wrapper = $(this.el).wrap('<div/>').parent()

        $wrapper.width(this.el.width).height(this.el.height)

        this.el.jcrop = $.Jcrop.attach($wrapper, options)
      },

      update: function(callback) {
        this.el.jcrop.container.on('crop' + this.arg, callback)
      },

      unbind: function() {
        this.el.jcrop.container.off('crop' + this.arg)

        if (this._watcher.id != 1) return

        this.el.jcrop.destroy()
        this.el.jcrop = null
      }
    })
  }

  vueCrop.setOptions = function(opts) {
    options = opts
  }

  if (window.Vue) {
    window.VueCrop = vueCrop
    Vue.use(vueCrop)
  }

}());
<|endoftext|>


<commit_before>import { UPDATE_PATH } from 'redux-simple-router'

import {
  LOGIN_REQUEST,
  LOGIN_SUCCESS,
  LOGIN_FAILURE,

  LOGOUT_REQUEST,
  LOGOUT_SUCCESS,

  CHECK_AUTH_REQUEST,
  CHECK_AUTH_SUCCESS,
  CHECK_AUTH_FAILURE
} from '../actionTypes'

const initialState = {}

export function _auth(state = initialState, action) {
  switch (action.type) {

    case LOGIN_REQUEST:
      return {
        ...state,
        loggingIn: true
      }
    case LOGIN_SUCCESS:
      return {
        ...state,
        loggingIn: false,
        isLoggedIn: action.result.isLoggedIn,
        ssid: action.result.ssid,
        error: false,
        message: null
      }
    case LOGIN_FAILURE:
      return {
        ...state,
        loggingIn: false,
        isLoggedIn: false,
        ssid: null,
        error: true,
        message: action.error.message
      }

    case LOGOUT_REQUEST:
      return {
        ...state
      }
    case LOGOUT_SUCCESS:
      return {
        ...state,
        error: false,
        isLoggedIn: false,
        ssid: null
      }

    case CHECK_AUTH_REQUEST:
      return {
        ...state
      }
    case CHECK_AUTH_SUCCESS:
      return {
        ...state,
        isLoggedIn: true,
        ssid: action.result.ssid,
        message: null
      }
    case CHECK_AUTH_FAILURE:
      return {
        ...state,
        isLoggedIn: false,
        ssid: null,
        message: null
      }

    default:
      return state
  }
}
<commit_msg>cleanup<commit_after>import {
  LOGIN_REQUEST,
  LOGIN_SUCCESS,
  LOGIN_FAILURE,

  LOGOUT_REQUEST,
  LOGOUT_SUCCESS,

  CHECK_AUTH_REQUEST,
  CHECK_AUTH_SUCCESS,
  CHECK_AUTH_FAILURE
} from '../actionTypes'

const initialState = {}

export function _auth(state = initialState, action) {
  switch (action.type) {

    case LOGIN_REQUEST:
      return {
        ...state,
        loggingIn: true
      }
    case LOGIN_SUCCESS:
      return {
        ...state,
        loggingIn: false,
        isLoggedIn: action.result.isLoggedIn,
        ssid: action.result.ssid,
        error: false,
        message: null
      }
    case LOGIN_FAILURE:
      return {
        ...state,
        loggingIn: false,
        isLoggedIn: false,
        ssid: null,
        error: true,
        message: action.error.message
      }

    case LOGOUT_REQUEST:
      return {
        ...state
      }
    case LOGOUT_SUCCESS:
      return {
        ...state,
        error: false,
        isLoggedIn: false,
        ssid: null
      }

    case CHECK_AUTH_REQUEST:
      return {
        ...state
      }
    case CHECK_AUTH_SUCCESS:
      return {
        ...state,
        isLoggedIn: true,
        ssid: action.result.ssid,
        message: null
      }
    case CHECK_AUTH_FAILURE:
      return {
        ...state,
        isLoggedIn: false,
        ssid: null,
        message: null
      }

    default:
      return state
  }
}
<|endoftext|>


<commit_before>const pcServices = require('./pcServices');
const metadataMapperJson = require('./metadataMapperJson');
const metadataMapperXML = require('./metadataMapperXML');
const metadataMapperPC2 = require('./metadataMapperPC2');

//Get pathway name, description, and datasource
//Requires a valid pathway uri
function getPathwayLevelMetadata(uri) {

  let title, dataSource, comments, organism;
  let getValue = data => data.traverseEntry[0].value;
  let get = path => pcServices.traversePC2(uri, path).then(getValue);

  return Promise.all([
    get('Named/displayName').then(value => title = value),
    get('Entity/dataSource/displayName').then(value => dataSource = value),
    get('Entity/comment').then(value => dataSource = value),
    get('Entity/organism/displayName').then(value => organism = value)
  ]).then(data => ({ comments, dataSource, title, organism }));
};

//Get metadata enhanced cytoscape JSON
//Requires a valid pathway uri
function getMetadataJson(uri, parseType) {
  let sbgn, biopax;
  let downloadType = (parseType === 'pc2' ? 'jsonld' : parseType);

  //Get SBGN and Biopax Files
  return Promise.all([
    pcServices.getPC2(uri, 'sbgn').then(file => sbgn = file),
    pcServices.getPC2(uri, downloadType).then(file => biopax = file)
  ]).then(files => {
    //Map metadata
    if (parseType === 'jsonld') { return metadataMapperJson(biopax, sbgn); }
    else if (parseType === 'biopax') { return metadataMapperXML(biopax, sbgn); }
    else if (parseType === 'pc2') { return metadataMapperPC2(biopax, sbgn); }
  })
}

//Return enhanced cytoscape json
//Requires a valid pathway uri
function getCytoscapeJson(uri, parseType = 'jsonld') {
  let pathwayMetadata;

  //Start Generation
  return getPathwayLevelMetadata(uri).then(function (data) {
    pathwayMetadata = data;
    return getMetadataJson(uri, parseType).then(function (data) {
      data.pathwayMetadata = pathwayMetadata;
      data.parseType = parseType;
      return data;
    })
  }).catch(function (e) {
    console.log(e);
    return { error: e };
  })
}

module.exports = {
  getCytoscapeJson,
  getPathwayLevelMetadata
};
<commit_msg>Undefined Comments Fix<commit_after>const pcServices = require('./pcServices');
const metadataMapperJson = require('./metadataMapperJson');
const metadataMapperXML = require('./metadataMapperXML');
const metadataMapperPC2 = require('./metadataMapperPC2');

//Get pathway name, description, and datasource
//Requires a valid pathway uri
function getPathwayLevelMetadata(uri) {

  let title, dataSource, comments, organism;
  let getValue = data => data.traverseEntry[0].value;
  let get = path => pcServices.traversePC2(uri, path).then(getValue);

  return Promise.all([
    get('Named/displayName').then(value => title = value),
    get('Entity/dataSource/displayName').then(value => dataSource = value),
    get('Entity/comment').then(value => comments = value),
    get('Entity/organism/displayName').then(value => organism = value)
  ]).then(data => ({ comments, dataSource, title, organism }));
};

//Get metadata enhanced cytoscape JSON
//Requires a valid pathway uri
function getMetadataJson(uri, parseType) {
  let sbgn, biopax;
  let downloadType = (parseType === 'pc2' ? 'jsonld' : parseType);

  //Get SBGN and Biopax Files
  return Promise.all([
    pcServices.getPC2(uri, 'sbgn').then(file => sbgn = file),
    pcServices.getPC2(uri, downloadType).then(file => biopax = file)
  ]).then(files => {
    //Map metadata
    if (parseType === 'jsonld') { return metadataMapperJson(biopax, sbgn); }
    else if (parseType === 'biopax') { return metadataMapperXML(biopax, sbgn); }
    else if (parseType === 'pc2') { return metadataMapperPC2(biopax, sbgn); }
  })
}

//Return enhanced cytoscape json
//Requires a valid pathway uri
function getCytoscapeJson(uri, parseType = 'jsonld') {
  let pathwayMetadata;

  //Start Generation
  return getPathwayLevelMetadata(uri).then(function (data) {
    pathwayMetadata = data;
    return getMetadataJson(uri, parseType).then(function (data) {
      data.pathwayMetadata = pathwayMetadata;
      data.parseType = parseType;
      return data;
    })
  }).catch(function (e) {
    console.log(e);
    return { error: e };
  })
}

module.exports = {
  getCytoscapeJson,
  getPathwayLevelMetadata
};
<|endoftext|>


<commit_before>// Credit goes to https://github.com/kurisubrooks/midori

const { Command } = require('discord.js-commando');
const moment = require('moment');
const request = require('request-promise');
const winston = require('winston');

const config = require('../../settings');
const version = require('../../package').version;

module.exports = class WeatherCommand extends Command {
	constructor(client) {
		super(client, {
			name: 'weather-alt',
			aliases: ['w-alt'],
			group: 'weather',
			memberName: 'weather-alt',
			description: 'Get the weather.',
			format: '<location>',
			guildOnly: true,

			args: [
				{
					key: 'location',
					prompt: 'What location would you like to have information on?\n',
					type: 'string'
				}
			]
		});
	}

	async run(msg, args) {
		const location = args.location;

		if (!config.GoogleAPIKey) return msg.reply('my Commander has not set the Google API Key. Go yell at him.');
		if (!config.WeatherAPIKey) return msg.reply('my Commander has not set the Weather API Key. Go yell at him.');

		let locationURI = encodeURIComponent(location.replace(/ /g, '+'));

		return request({
			uri: `https://maps.googleapis.com/maps/api/geocode/json?address=${locationURI}&key=${config.GoogleAPIKey}`,
			headers: { 'User-Agent': `Hamakaze ${version} (https://github.com/iCrawl/Hamakaze/)` },
			json: true
		}).then(response => {
			if (response.status !== 'OK') return this.handleNotOK(msg, response.body.status);
			if (response.results.length === 0) return msg.reply('I couldn\'t find a place with the location you provded me');

			return request({
				uri: `https://api.darksky.net/forecast/${config.WeatherAPIKey}/${response.results[0].geometry.location.lat},${response.results[0].geometry.location.lng}?exclude=minutely,hourly,flags&units=auto`,
				headers: { 'User-Agent': `Hamakaze ${version} (https://github.com/iCrawl/Hamakaze/)` },
				json: true
			}).then(res => {
				let datetime = moment().utcOffset(res.timezone).format('D MMMM, h:mma');
				let condition = res.currently.summary;
				let icon = res.currently.icon;
				let chanceofrain = Math.round((res.currently.precipProbability * 100) / 5) * 5;
				let temperature = Math.round(res.currently.temperature * 10) / 10;
				let temperatureMin = Math.round(res.daily.data[0].temperatureMin * 10) / 10;
				let temperatureMax = Math.round(res.daily.data[0].temperatureMax * 10) / 10;
				let feelslike = Math.round(res.currently.apparentTemperature * 10) / 10;
				let humidity = Math.round(res.currently.humidity * 100);
				let windspeed = res.currently.windSpeed;

				let embed = {
					color: 3447003,
					fields: [
						{
							name: 'Los Angeles',
							value: `${this.getBase(icon)}`,
							inline: true
						},
						{
							name: 'Condition',
							value: `${condition}`,
							inline: true
						},
						{
							name: 'Temperature',
							value: `${temperature}°`,
							inline: true
						},
						{
							name: 'High / Low',
							value: `${temperatureMax}°\n${temperatureMin}°`,
							inline: true
						},
						{
							name: 'Feels like',
							value: `${feelslike}°`,
							inline: true
						},
						{
							name: 'Humidity',
							value: `${humidity}%`,
							inline: true
						},
						{
							name: 'Chance of rain',
							value: `${chanceofrain}%`,
							inline: true
						},
						{
							name: 'Windspeed',
							value: `${windspeed.toFixed(2)} ${this.getUnit(response.results[0].address_components)} `,
							inline: true
						}
					],
					footer: {
						icon_url: msg.client.user.avatarURL, // eslint-disable-line camelcase
						text: `${datetime}`
					}
				};

				return msg.channel.sendMessage('', { embed })
					.catch(error => { winston.error(error); });
			}).catch(error => {
				return winston.error(error);
			});
		}).catch(error => {
			winston.error(error);
			return msg.say(`Error: Status code ${error.status || error.response} from Google.`);
		});
	}

	handleNotOK(msg, status) {
		if (status === 'ZERO_RESULTS') {
			return { plain: `${msg.author}, your request returned no results.` };
		} else if (status === 'REQUEST_DENIED') {
			return { plain: `Error: Geocode API Request was denied.` };
		} else if (status === 'INVALID_REQUEST') {
			return { plain: `Error: Invalid Request,` };
		} else if (status === 'OVER_QUERY_LIMIT') {
			return { plain: `${msg.author}, Query Limit Exceeded. Try again tomorrow.` };
		} else {
			return { plain: `Error: Unknown.` };
		}
	}

	getBase(icon) {
		if (icon === 'clear-night' || icon === 'partly-cloudly-night') return `☁`;
		if (icon === 'rain') return `🌧`;
		if (icon === 'snow' || icon === 'sleet' || icon === 'fog' || icon === 'wind') return `🌫`;
		if (icon === 'cloudy') return `☁`;
		return `☀`;
	}

	getUnit(units) {
		let unit = units.find(un => un.types.includes('country'));

		if (unit === undefined) return 'm/s';
		if (unit.short_name === 'US' || unit.short_name === 'GB') return 'mph';
		if (unit.short_name === 'CA') return 'kph';
		return 'm/s';
	}
};
<commit_msg>Get Temp Units<commit_after>// Credit goes to https://github.com/kurisubrooks/midori

const { Command } = require('discord.js-commando');
const moment = require('moment');
const request = require('request-promise');
const winston = require('winston');

const config = require('../../settings');
const version = require('../../package').version;

module.exports = class WeatherCommand extends Command {
	constructor(client) {
		super(client, {
			name: 'weather-alt',
			aliases: ['w-alt'],
			group: 'weather',
			memberName: 'weather-alt',
			description: 'Get the weather.',
			format: '<location>',
			guildOnly: true,

			args: [
				{
					key: 'location',
					prompt: 'What location would you like to have information on?\n',
					type: 'string'
				}
			]
		});
	}

	async run(msg, args) {
		const location = args.location;

		if (!config.GoogleAPIKey) return msg.reply('my Commander has not set the Google API Key. Go yell at him.');
		if (!config.WeatherAPIKey) return msg.reply('my Commander has not set the Weather API Key. Go yell at him.');

		let locationURI = encodeURIComponent(location.replace(/ /g, '+'));

		return request({
			uri: `https://maps.googleapis.com/maps/api/geocode/json?address=${locationURI}&key=${config.GoogleAPIKey}`,
			headers: { 'User-Agent': `Hamakaze ${version} (https://github.com/iCrawl/Hamakaze/)` },
			json: true
		}).then(response => {
			if (response.status !== 'OK') return this.handleNotOK(msg, response.body.status);
			if (response.results.length === 0) return msg.reply('I couldn\'t find a place with the location you provded me');

			return request({
				uri: `https://api.darksky.net/forecast/${config.WeatherAPIKey}/${response.results[0].geometry.location.lat},${response.results[0].geometry.location.lng}?exclude=minutely,hourly,flags&units=auto`,
				headers: { 'User-Agent': `Hamakaze ${version} (https://github.com/iCrawl/Hamakaze/)` },
				json: true
			}).then(res => {
				let datetime = moment().utcOffset(res.timezone).format('D MMMM, h:mma');
				let condition = res.currently.summary;
				let icon = res.currently.icon;
				let chanceofrain = Math.round((res.currently.precipProbability * 100) / 5) * 5;
				let temperature = Math.round(res.currently.temperature * 10) / 10;
				let temperatureMin = Math.round(res.daily.data[0].temperatureMin * 10) / 10;
				let temperatureMax = Math.round(res.daily.data[0].temperatureMax * 10) / 10;
				let feelslike = Math.round(res.currently.apparentTemperature * 10) / 10;
				let humidity = Math.round(res.currently.humidity * 100);
				let windspeed = res.currently.windSpeed;

				let embed = {
					color: 3447003,
					fields: [
						{
							name: 'Los Angeles',
							value: `${this.getBase(icon)}`,
							inline: true
						},
						{
							name: 'Condition',
							value: `${condition}`,
							inline: true
						},
						{
							name: 'Temperature',
							value: `${temperature}° ${this.getTempUnit(response.results[0].address_components)}`,
							inline: true
						},
						{
							name: 'High / Low',
							value: `${temperatureMax}° ${this.getTempUnit(response.results[0].address_components)}\n${temperatureMin}° ${this.getTempUnit(response.results[0].address_components)}`,
							inline: true
						},
						{
							name: 'Feels like',
							value: `${feelslike}°`,
							inline: true
						},
						{
							name: 'Humidity',
							value: `${humidity}%`,
							inline: true
						},
						{
							name: 'Chance of rain',
							value: `${chanceofrain}%`,
							inline: true
						},
						{
							name: 'Windspeed',
							value: `${windspeed.toFixed(2)} ${this.getWindspeedUnit(response.results[0].address_components)} `,
							inline: true
						}
					],
					footer: {
						icon_url: msg.client.user.avatarURL, // eslint-disable-line camelcase
						text: `${datetime}`
					}
				};

				return msg.channel.sendMessage('', { embed })
					.catch(error => { winston.error(error); });
			}).catch(error => {
				return winston.error(error);
			});
		}).catch(error => {
			winston.error(error);
			return msg.say(`Error: Status code ${error.status || error.response} from Google.`);
		});
	}

	handleNotOK(msg, status) {
		if (status === 'ZERO_RESULTS') {
			return { plain: `${msg.author}, your request returned no results.` };
		} else if (status === 'REQUEST_DENIED') {
			return { plain: `Error: Geocode API Request was denied.` };
		} else if (status === 'INVALID_REQUEST') {
			return { plain: `Error: Invalid Request,` };
		} else if (status === 'OVER_QUERY_LIMIT') {
			return { plain: `${msg.author}, Query Limit Exceeded. Try again tomorrow.` };
		} else {
			return { plain: `Error: Unknown.` };
		}
	}

	getBase(icon) {
		if (icon === 'clear-night' || icon === 'partly-cloudly-night') return `☁`;
		if (icon === 'rain') return `🌧`;
		if (icon === 'snow' || icon === 'sleet' || icon === 'fog' || icon === 'wind') return `🌫`;
		if (icon === 'cloudy') return `☁`;
		return `☀`;
	}

	getWindspeedUnit(units) {
		let unit = units.find(un => un.types.includes('country'));

		if (unit === undefined) return 'm/s';
		if (unit.short_name === 'US' || unit.short_name === 'GB') return 'mph';
		if (unit.short_name === 'CA') return 'kph';
		return 'm/s';
	}

	getTempUnit(units) {
		let unit = units.find(un => un.types.includes('country'));

		if (unit === undefined) return 'C';
		if (unit.short_name === 'US') return 'F';
		return 'C';
	}
};
<|endoftext|>


<commit_before>/**
 * Created by Dean Panayotov Local on 29.1.2015 г..
 */

var CherryBlossom = function(){

    this.RADIUS = 3;
    this.FADE_OUT_SPEED = 1;
    this.GROUND_Y = 1570;
    this.BASE_Y_SPEED = 1;
    this.VAR_Y_SPEED = 1;
    this.MAX_X_SPEED = 3;
    this.H = 335;
    this.MAX_S = 60;
    this.L = 100;

    this.dead = false;
    this.onGround = false;

    if((Math.random() > 0.5)){
        this.x = Math.random() * WIDTH;
        this.y = 0;
    }else{
        this.x = 900;
        this.y = Math.random() * HEIGHT;
    }
    this.xspeed = Math.random() * this.MAX_X_SPEED * -1;
    this.yspeed = this.BASE_Y_SPEED + this.VAR_Y_SPEED * Math.random();
    this.s = Math.floor(Math.random()*this.MAX_S);
    this.alpha = 1.0;
    this.color = "hsla("+this.H+","+this.s+"%,"+this.L+"%,+"+this.alpha+")";
    this.update = function(){
        if(!this.dead) {
            if (this.onGround) {
                this.alpha -= this.FADE_OUT_SPEED;
                if (this.alpha <= 0) {
                    this.alpha = 0;
                    this.dead = true;
                }
            } else {
                this.x += this.xspeed;
                this.y += this.yspeed;
                if(this.x < 0){
                    this.dead = true;
                } else if (this.y >= this.GROUND_Y) {
                    this.onGround = true;
                }
            }
        }
    }

    this.render = function(ctx){
        if(this.onGround){
            this.color = "hsla("+this.H+","+this.s+"%,"+this.L+"%,+"+this.alpha+")";
        }
        ctx.fillStyle = this.color;
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.RADIUS, 0, 2 * Math.PI, false);
        ctx.fill();
    }
}

var BlossomManager = function(){
    var self = this;
    this.MAX_LEAVES = 100;
    this.FIRE_RATE = 100;
    this.MAX_LEAVES_SPAWN = 5;

    this.leaves = [];
    this.spawn = function(){
        if(self.leaves.length < self.MAX_LEAVES){
            var count = Math.floor(Math.random() * self.MAX_LEAVES_SPAWN);
            for(var i=0; i<count;i++){
                self.leaves.push(new CherryBlossom());
            }
        }
        setInterval(this.spawn, this.FIRE_RATE);
    }
    this.start = function(){
        this.spawn();
    }

    this.update = function(){
        for(var i=0;i<this.leaves.length;i++){
            this.leaves[i].update();
            if(this.leaves[i].dead){
                this.leaves.splice(i, 1);
            }
        }
    }
    this.render = function(ctx){
        for(var i=0;i<this.leaves.length;i++){
            this.leaves[i].render(ctx);
        }
    }
}<commit_msg>Fixed leave coloring and fadeout.<commit_after>/**
 * Created by Dean Panayotov Local on 29.1.2015 г..
 */

var CherryBlossom = function(){

    this.RADIUS = 3;
    this.FADE_OUT_SPEED = 0.01;
    this.GROUND_Y = 1570;
    this.BASE_Y_SPEED = 1;
    this.VAR_Y_SPEED = 1;
    this.MAX_X_SPEED = 3;
    this.H = 335;
    this.S = 100;
    this.MIN_L = 60;

    this.dead = false;
    this.onGround = false;

    if((Math.random() > 0.5)){
        this.x = Math.random() * WIDTH;
        this.y = 0;
    }else{
        this.x = 900;
        this.y = Math.random() * HEIGHT;
    }
    this.xspeed = Math.random() * this.MAX_X_SPEED * -1;
    this.yspeed = this.BASE_Y_SPEED + this.VAR_Y_SPEED * Math.random();
    this.l = this.MIN_L + Math.floor(Math.random()*this.MIN_L);
    this.alpha = 1.0;
    this.color = "hsl("+this.H+","+this.S+"%,"+this.l+"%)";
	console.log(this.color);
    this.update = function(){
        if(!this.dead) {
            if (this.onGround) {
                this.alpha -= this.FADE_OUT_SPEED;
                if (this.alpha <= 0) {
                    this.alpha = 0;
                    this.dead = true;
                }
            } else {
                this.x += this.xspeed;
                this.y += this.yspeed;
                if(this.x < 0){
                    this.dead = true;
                } else if (this.y >= this.GROUND_Y) {
                    this.onGround = true;
                }
            }
        }
    }

    this.render = function(ctx){
        if(this.onGround){
            this.color = "hsla("+this.H+","+this.s+"%,"+this.L+"%,+"+this.alpha+")";
        }
        ctx.fillStyle = this.color;
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.RADIUS, 0, 2 * Math.PI, false);
        ctx.fill();
    }
}

var BlossomManager = function(){
    var self = this;
    this.MAX_LEAVES = 100;
    this.FIRE_RATE = 100;
    this.MAX_LEAVES_SPAWN = 5;

    this.leaves = [];
    this.spawn = function(){
        if(self.leaves.length < self.MAX_LEAVES){
            var count = Math.floor(Math.random() * self.MAX_LEAVES_SPAWN);
            for(var i=0; i<count;i++){
                self.leaves.push(new CherryBlossom());
            }
        }
        setInterval(this.spawn, this.FIRE_RATE);
    }
    this.start = function(){
        this.spawn();
    }

    this.update = function(){
        for(var i=0;i<this.leaves.length;i++){
            this.leaves[i].update();
            if(this.leaves[i].dead){
                this.leaves.splice(i, 1);
            }
        }
    }
    this.render = function(ctx){
        for(var i=0;i<this.leaves.length;i++){
            this.leaves[i].render(ctx);
        }
    }
}<|endoftext|>


<commit_before>import React from 'react';
import I18n from 'i18n-js';
import PropTypes from 'prop-types';
import Events from '../../../utils/helpers/events';
import DateHelper from '../../../utils/helpers/date';
import DateValidator from '../../../utils/validations/date';
import tagComponent from '../../../utils/helpers/tags';
import DatePicker from './date-picker.component';
import StyledDateInput from './date.style';
import Textbox from '../textbox';
import withUniqueName from '../../../utils/helpers/with-unique-name';

const defaultDateFormat = 'DD/MM/YYYY';

class BaseDateInput extends React.Component {
  isBlurBlocked = false;

  isOpening = false;

  inputHasFocus = this.props.autoFocus || false;

  isControlled = this.props.value !== undefined;

  adjustedValue = DateHelper.isValidDate(this.props.value) ? this.props.value : DateHelper.todayFormatted();

  initialVisibleValue = this.isControlled ? this.adjustedValue : this.props.defaultValue;

  state = {
    isDatePickerOpen: false,
    /** Date object to pass to the DatePicker */
    selectedDate: DateHelper.stringToDate(this.initialVisibleValue),
    /** Displayed value, format dependent on a region */
    visibleValue: formatDateToCurrentLocale(this.initialVisibleValue)
  };

  componentDidMount() {
    if (this.props.autoFocus) {
      this.isAutoFocused = true;
      this.input.focus();
    }
  }

  componentDidUpdate(prevProps) {
    if (this.isControlled && !this.inputHasFocus && this.hasValueChanged(prevProps)) {
      this.updateVisibleValue(this.props.value);
      this.updateSelectedDate(this.props.value);
    } else if (this.isBlurBlocked && this.hasValueChanged(prevProps)) {
      this.isBlurBlocked = false;
      this.handleBlur();
    }
  }

  hasValueChanged = (prevProps) => {
    return this.props.value && prevProps.value !== this.props.value;
  };

  assignInput = (input) => {
    this.input = input.current;
  };

  handleBlur = () => {
    this.inputHasFocus = false;
    const { disabled, readOnly } = this.props;

    if (disabled || readOnly || this.isBlurBlocked) return;

    this.reformatVisibleDate();

    if (this.props.onBlur) {
      const dateWithSlashes = DateHelper.sanitizeDateInput(this.state.visibleValue);
      const event = this.buildCustomTarget({ target: this.input }, DateHelper.formatValue(dateWithSlashes));
      this.props.onBlur(event);
    }
  }

  handleFocus = (ev) => {
    this.inputHasFocus = true;
    const { disabled, readOnly } = this.props;

    if (disabled || readOnly) return;

    if (this.isAutoFocused) {
      this.isAutoFocused = false;
    } else {
      this.openDatePicker();
    }

    if (this.props.onFocus) {
      this.props.onFocus(ev);
    }
  };

  handleTabKeyDown = (ev) => {
    if (Events.isTabKey(ev)) {
      this.isOpening = false;
      this.closeDatePicker();
    }
  };

  openDatePicker = () => {
    this.isBlurBlocked = true;
    document.addEventListener('click', this.closeDatePicker);
    this.updateSelectedDate(this.props.value || this.state.visibleValue);
    this.setState({ isDatePickerOpen: true });
  };

  reformatVisibleDate = () => {
    const { visibleValue } = this.state;
    if (DateHelper.isValidDate(visibleValue)) {
      this.setState({ visibleValue: formatDateToCurrentLocale(visibleValue) });
    }
  }

  closeDatePicker = () => {
    if (this.isOpening) {
      this.isOpening = false;
      return;
    }
    document.removeEventListener('click', this.closeDatePicker);
    this.setState({ isDatePickerOpen: false });
  };

  handleDateSelect = (selectedDate) => {
    const stringDateIso = DateHelper.formatDateString(selectedDate);
    this.isBlurBlocked = true;
    this.closeDatePicker();
    this.updateVisibleValue(stringDateIso, true);
  };

  updateVisibleValue = (date, pickerUsed) => {
    const visibleValue = formatDateToCurrentLocale(date);

    this.setState({ selectedDate: date, visibleValue },
      () => {
        if (pickerUsed) {
          const event = { target: this.input };
          event.target.value = this.state.selectedDate;
          this.emitOnChangeCallback(event, date);
        }
      });
  };

  handleVisibleInputChange = (ev) => {
    const { disabled, readOnly } = this.props;
    const dateWithSlashes = DateHelper.sanitizeDateInput(ev.target.value);
    const isValidDate = DateHelper.isValidDate(dateWithSlashes);
    let isoDateString;

    if (disabled || readOnly) return;

    this.isBlurBlocked = false;

    if (isValidDate) {
      isoDateString = DateHelper.formatValue(dateWithSlashes);
      this.updateSelectedDate(isoDateString);
      this.emitOnChangeCallback(ev, isoDateString);
    }

    this.setState({ visibleValue: ev.target.value.displayText || ev.target.value });
  };

  updateSelectedDate = (newValue) => {
    let newDate = DateHelper.stringToDate(DateHelper.formatValue(newValue));
    const isNewDateInvalid = !newDate.getDate();

    if (isNewDateInvalid) {
      newDate = DateHelper.stringToDate(DateHelper.todayFormatted());
    }

    this.setState({ selectedDate: newDate });
  };

  emitOnChangeCallback = (ev, isoFormattedValue) => {
    if (this.props.onChange) {
      const event = this.buildCustomTarget(ev, isoFormattedValue);
      this.props.onChange(event);
    }
  };

  buildCustomTarget = (ev, isoFormattedValue) => {
    const { id, name, value } = ev.target;

    ev.target = {
      ...(name && { name }),
      ...(id && { id }),
      value:
        {
          displayText: formatDateToCurrentLocale(value),
          optionValue: isoFormattedValue
        }
    };
    return ev;
  }

  renderDatePicker = (dateRangeProps) => {
    if (!this.state.isDatePickerOpen) return null;

    return (
      <DatePicker
        inputElement={ this.input && this.input.parentElement }
        selectedDate={ this.state.selectedDate }
        handleDateSelect={ this.handleDateSelect }
        { ...dateRangeProps }
      />
    );
  }

  markCurrentDatepicker = () => {
    this.isOpening = true;
  }

  render() {
    const { minDate, maxDate, ...inputProps } = this.props;
    let events = {};
    delete inputProps.autoFocus;
    delete inputProps.defaultValue;
    delete inputProps.value;

    inputProps.validations = concatAllValidations(inputProps);

    events = {
      onBlur: this.handleBlur,
      onChange: this.handleVisibleInputChange,
      onFocus: this.handleFocus,
      onKeyDown: this.handleTabKeyDown
    };

    return (
      <StyledDateInput
        onClick={ this.markCurrentDatepicker }
        role='presentation'
        size={ inputProps.size }
        { ...tagComponent('date', this.props) }
      >
        <Textbox
          { ...inputProps }
          inputIcon='calendar'
          value={ this.state.visibleValue }
          inputRef={ this.assignInput }
          { ...events }
        />
        {this.renderDatePicker({ minDate, maxDate }) }
      </StyledDateInput>
    );
  }
}

function concatAllValidations(props) {
  if (!props.validations) props.validations = [];
  if (typeof props.validations === 'function') props.validations = [props.validations];

  return [...props.validations, ...props.internalValidations];
}

function formatDateToCurrentLocale(value) {
  const visibleFormat = I18n.t('date.formats.javascript', { defaultValue: defaultDateFormat }).toUpperCase();

  return DateHelper.formatValue(value || DateHelper.todayFormatted(), visibleFormat);
}

const DateInput = withUniqueName(BaseDateInput);

BaseDateInput.propTypes = {
  ...Textbox.propTypes,
  /** Automatically focus on component mount */
  autoFocus: PropTypes.bool,
  /** Used to provide additional validations on composed components */
  internalValidations: PropTypes.array,
  /** Minimum possible date YYYY-MM-DD */
  minDate: PropTypes.string,
  /** Maximum possible date YYYY-MM-DD */
  maxDate: PropTypes.string,
  /** Specify a callback triggered on blur */
  onBlur: PropTypes.func,
  /** Specify a callback triggered on change */
  onChange: PropTypes.func,
  /** Specify a callback triggered on focus */
  onFocus: PropTypes.func,
  /** Name of the input */
  name: PropTypes.string,
  /** The current date YYYY-MM-DD */
  value: PropTypes.string,
  /** Triggers textbox validation when it's boolean value changes */
  forceUpdateTriggerToggle: PropTypes.bool
};

BaseDateInput.defaultProps = {
  internalValidations: [new DateValidator()]
};

export { defaultDateFormat, BaseDateInput };
export default DateInput;
<commit_msg>refactor: renames to buildCustomEvent<commit_after>import React from 'react';
import I18n from 'i18n-js';
import PropTypes from 'prop-types';
import Events from '../../../utils/helpers/events';
import DateHelper from '../../../utils/helpers/date';
import DateValidator from '../../../utils/validations/date';
import tagComponent from '../../../utils/helpers/tags';
import DatePicker from './date-picker.component';
import StyledDateInput from './date.style';
import Textbox from '../textbox';
import withUniqueName from '../../../utils/helpers/with-unique-name';

const defaultDateFormat = 'DD/MM/YYYY';

class BaseDateInput extends React.Component {
  isBlurBlocked = false;

  isOpening = false;

  inputHasFocus = this.props.autoFocus || false;

  isControlled = this.props.value !== undefined;

  adjustedValue = DateHelper.isValidDate(this.props.value) ? this.props.value : DateHelper.todayFormatted();

  initialVisibleValue = this.isControlled ? this.adjustedValue : this.props.defaultValue;

  state = {
    isDatePickerOpen: false,
    /** Date object to pass to the DatePicker */
    selectedDate: DateHelper.stringToDate(this.initialVisibleValue),
    /** Displayed value, format dependent on a region */
    visibleValue: formatDateToCurrentLocale(this.initialVisibleValue)
  };

  componentDidMount() {
    if (this.props.autoFocus) {
      this.isAutoFocused = true;
      this.input.focus();
    }
  }

  componentDidUpdate(prevProps) {
    if (this.isControlled && !this.inputHasFocus && this.hasValueChanged(prevProps)) {
      this.updateVisibleValue(this.props.value);
      this.updateSelectedDate(this.props.value);
    } else if (this.isBlurBlocked && this.hasValueChanged(prevProps)) {
      this.isBlurBlocked = false;
      this.handleBlur();
    }
  }

  hasValueChanged = (prevProps) => {
    return this.props.value && prevProps.value !== this.props.value;
  };

  assignInput = (input) => {
    this.input = input.current;
  };

  handleBlur = () => {
    this.inputHasFocus = false;
    const { disabled, readOnly } = this.props;

    if (disabled || readOnly || this.isBlurBlocked) return;

    this.reformatVisibleDate();

    if (this.props.onBlur) {
      const dateWithSlashes = DateHelper.sanitizeDateInput(this.state.visibleValue);
      const event = this.buildCustomEvent({ target: this.input }, DateHelper.formatValue(dateWithSlashes));
      this.props.onBlur(event);
    }
  }

  handleFocus = (ev) => {
    this.inputHasFocus = true;
    const { disabled, readOnly } = this.props;

    if (disabled || readOnly) return;

    if (this.isAutoFocused) {
      this.isAutoFocused = false;
    } else {
      this.openDatePicker();
    }

    if (this.props.onFocus) {
      this.props.onFocus(ev);
    }
  };

  handleTabKeyDown = (ev) => {
    if (Events.isTabKey(ev)) {
      this.isOpening = false;
      this.closeDatePicker();
    }
  };

  openDatePicker = () => {
    this.isBlurBlocked = true;
    document.addEventListener('click', this.closeDatePicker);
    this.updateSelectedDate(this.props.value || this.state.visibleValue);
    this.setState({ isDatePickerOpen: true });
  };

  reformatVisibleDate = () => {
    const { visibleValue } = this.state;
    if (DateHelper.isValidDate(visibleValue)) {
      this.setState({ visibleValue: formatDateToCurrentLocale(visibleValue) });
    }
  }

  closeDatePicker = () => {
    if (this.isOpening) {
      this.isOpening = false;
      return;
    }
    document.removeEventListener('click', this.closeDatePicker);
    this.setState({ isDatePickerOpen: false });
  };

  handleDateSelect = (selectedDate) => {
    const stringDateIso = DateHelper.formatDateString(selectedDate);
    this.isBlurBlocked = true;
    this.closeDatePicker();
    this.updateVisibleValue(stringDateIso, true);
  };

  updateVisibleValue = (date, pickerUsed) => {
    const visibleValue = formatDateToCurrentLocale(date);

    this.setState({ selectedDate: date, visibleValue },
      () => {
        if (pickerUsed) {
          const event = { target: this.input };
          event.target.value = this.state.selectedDate;
          this.emitOnChangeCallback(event, date);
        }
      });
  };

  handleVisibleInputChange = (ev) => {
    const { disabled, readOnly } = this.props;
    const dateWithSlashes = DateHelper.sanitizeDateInput(ev.target.value);
    const isValidDate = DateHelper.isValidDate(dateWithSlashes);
    let isoDateString;

    if (disabled || readOnly) return;

    this.isBlurBlocked = false;

    if (isValidDate) {
      isoDateString = DateHelper.formatValue(dateWithSlashes);
      this.updateSelectedDate(isoDateString);
      this.emitOnChangeCallback(ev, isoDateString);
    }

    this.setState({ visibleValue: ev.target.value.displayText || ev.target.value });
  };

  updateSelectedDate = (newValue) => {
    let newDate = DateHelper.stringToDate(DateHelper.formatValue(newValue));
    const isNewDateInvalid = !newDate.getDate();

    if (isNewDateInvalid) {
      newDate = DateHelper.stringToDate(DateHelper.todayFormatted());
    }

    this.setState({ selectedDate: newDate });
  };

  emitOnChangeCallback = (ev, isoFormattedValue) => {
    if (this.props.onChange) {
      const event = this.buildCustomEvent(ev, isoFormattedValue);
      this.props.onChange(event);
    }
  };

  buildCustomEvent = (ev, isoFormattedValue) => {
    const { id, name, value } = ev.target;

    ev.target = {
      ...(name && { name }),
      ...(id && { id }),
      value:
        {
          displayText: formatDateToCurrentLocale(value),
          optionValue: isoFormattedValue
        }
    };
    return ev;
  }

  renderDatePicker = (dateRangeProps) => {
    if (!this.state.isDatePickerOpen) return null;

    return (
      <DatePicker
        inputElement={ this.input && this.input.parentElement }
        selectedDate={ this.state.selectedDate }
        handleDateSelect={ this.handleDateSelect }
        { ...dateRangeProps }
      />
    );
  }

  markCurrentDatepicker = () => {
    this.isOpening = true;
  }

  render() {
    const { minDate, maxDate, ...inputProps } = this.props;
    let events = {};
    delete inputProps.autoFocus;
    delete inputProps.defaultValue;
    delete inputProps.value;

    inputProps.validations = concatAllValidations(inputProps);

    events = {
      onBlur: this.handleBlur,
      onChange: this.handleVisibleInputChange,
      onFocus: this.handleFocus,
      onKeyDown: this.handleTabKeyDown
    };

    return (
      <StyledDateInput
        onClick={ this.markCurrentDatepicker }
        role='presentation'
        size={ inputProps.size }
        { ...tagComponent('date', this.props) }
      >
        <Textbox
          { ...inputProps }
          inputIcon='calendar'
          value={ this.state.visibleValue }
          inputRef={ this.assignInput }
          { ...events }
        />
        {this.renderDatePicker({ minDate, maxDate }) }
      </StyledDateInput>
    );
  }
}

function concatAllValidations(props) {
  if (!props.validations) props.validations = [];
  if (typeof props.validations === 'function') props.validations = [props.validations];

  return [...props.validations, ...props.internalValidations];
}

function formatDateToCurrentLocale(value) {
  const visibleFormat = I18n.t('date.formats.javascript', { defaultValue: defaultDateFormat }).toUpperCase();

  return DateHelper.formatValue(value || DateHelper.todayFormatted(), visibleFormat);
}

const DateInput = withUniqueName(BaseDateInput);

BaseDateInput.propTypes = {
  ...Textbox.propTypes,
  /** Automatically focus on component mount */
  autoFocus: PropTypes.bool,
  /** Used to provide additional validations on composed components */
  internalValidations: PropTypes.array,
  /** Minimum possible date YYYY-MM-DD */
  minDate: PropTypes.string,
  /** Maximum possible date YYYY-MM-DD */
  maxDate: PropTypes.string,
  /** Specify a callback triggered on blur */
  onBlur: PropTypes.func,
  /** Specify a callback triggered on change */
  onChange: PropTypes.func,
  /** Specify a callback triggered on focus */
  onFocus: PropTypes.func,
  /** Name of the input */
  name: PropTypes.string,
  /** The current date YYYY-MM-DD */
  value: PropTypes.string,
  /** Triggers textbox validation when it's boolean value changes */
  forceUpdateTriggerToggle: PropTypes.bool
};

BaseDateInput.defaultProps = {
  internalValidations: [new DateValidator()]
};

export { defaultDateFormat, BaseDateInput };
export default DateInput;
<|endoftext|>


<commit_before>//META{"name":"ResizeX"}*//
var resizexDragging;
var resizexHandle;
var resizexImage;
var resizexWidth;
var resizexX;
var resizexY;
var resizexAspectRatio;

var ResizeX = function() {};

// unused
ResizeX.prototype.load = function() {};
ResizeX.prototype.unload = function() {};
ResizeX.prototype.onMessage = function() {};
// unused

ResizeX.prototype.start = function() {
    BdApi.injectCSS("resizex-style", '@font-face{font-family:Batch;src:url(https://cdn.rawgit.com/AdamWhitcroft/batch/a3640352/Webfont/batch-icons-webfont.ttf)}.resizex-icon::before{content:"\\F0A5";transform:scaleX(-1);display:inline-block;margin-top:8px;draggable:false!important}.resizex-handle{box-sizing:border-box;display:flex;-webkit-box-orient:horizontal;-webkit-box-direction:reverse;flex-direction:row-reverse;-webkit-box-pack:justify;justify-content:space-between;-webkit-box-align:center;align-items:center;cursor:nwse-resize;draggable:false!important;font-family:Batch;min-width:none!important}iframe.image{min-width:400px;max-width:none!important}');
    $(document)
        .on("mousemove.resizex", function(e) {
            if (resizexHandle) {
                $(resizexHandle).siblings().width(resizexWidth + (e.pageX - resizexX + e.pageY - resizexY) / 2);
                $(resizexHandle).siblings().height($(resizexHandle).siblings().width() * resizexAspectRatio);
            }
            if (resizexImage) {
                resizexDragging = true;
                $(resizexImage).width(resizexWidth + (e.pageX - resizexX + e.pageY - resizexY) / 2);
            }
        })
        .on("mouseup.resizex", function() {
            resizexHandle = null;
            resizexImage = null;
            BdApi.clearCSS("resizex-dragging");
        });
};

ResizeX.prototype.stop = function() {
    BdApi.clearCSS("resizex-style");
    $(document).add("*").off(".resizex");
};

ResizeX.prototype.observer = function(e) {
    if (e.addedNodes.length && e.addedNodes[0].classList && e.addedNodes[0].classList.contains("embed-thumbnail-video")) {
        $("

")
            .insertAfter($(e.addedNodes[0]).find("iframe"))
            .on("mousedown.resizex", function(e) {
                resizexWidth = $(this).siblings().width();
                resizexX = e.pageX;
                resizexY = e.pageY;
                resizexHandle = this;
                resizexAspectRatio = $(this).siblings().height() / $(this).siblings().width();
                BdApi.injectCSS("resizex-dragging", "iframe{pointer-events:none;}*{-webkit-user-select:none!important;cursor:nwse-resize!important;}");
            });
    }
    if (e.addedNodes.length && $(e.addedNodes[0]).attr("src") && $(e.addedNodes[0]).attr("src").indexOf("discordapp") != -1 && ($(e.addedNodes[0]).parent().attr('class')?$(e.addedNodes[0]).parent().attr('class').indexOf("embed-thumbnail-video") == -1:true)) {
        $(e.addedNodes[0])
            .one("mousedown.resizex", function() {
                resizexWidth = $(this).width();
                $(this)
                    .attr("src", $(this).attr("src").split("?")[0])
                    .attr("height", "")
                    .attr("width", "")
                    .attr("draggable", "false")
                    .width(resizexWidth)
                    .css("min-width", resizexWidth)
                    .css("max-width", "none")
                    .parent().attr("draggable", "false");
            })
            .on("mousedown.resizex", function(e) {
                resizexImage = this;
                resizexWidth = $(this).width();
                resizexX = e.pageX;
                resizexY = e.pageY;
                resizexDragging = false;
            })
            .parent()
            .on("click.resizex", function() {
                if (resizexDragging)
                    return false;
            });
    }
};

ResizeX.prototype.getSettingsPanel = function() {
    return "";
};

ResizeX.prototype.getName = function() {
    return "ResizeX";
};

ResizeX.prototype.getDescription = function() {
    return "Lets you resize videos and images";
};

ResizeX.prototype.getVersion = function() {
    return "0.1.2";
};

ResizeX.prototype.getAuthor = function() {
    return "Anxeal";
};
<commit_msg>Delete ResizeX.plugin.js<commit_after><|endoftext|>


<commit_before>import React, { Component } from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import AppBar from 'material-ui/AppBar';
import Drawer from 'material-ui/Drawer';
import MenuItem from 'material-ui/MenuItem';
import FlatButton from 'material-ui/FlatButton';

import MnSnackbar from "./MnSnackbar";

import './App.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showMenu: false
    };
  }

  render() {
    return (
      <MuiThemeProvider>

          <AppBar
            title="> notes"
            onLeftIconButtonTouchTap={this.showMenu.bind(this)}
            iconElementRight={<FlatButton label="Sync" />}
            onRightIconButtonTouchTap={this.syncAll.bind(this)}
          />
          <Drawer open={this.state.showMenu}>
            <MenuItem onTouchTap={this.goToDatabases.bind(this)}>Databases</MenuItem>
            <MenuItem onTouchTap={this.goToNotes.bind(this)}>Notes</MenuItem>
          </Drawer>
          {this.props.children}
          <MnSnackbar/>

      </MuiThemeProvider>
    );
  }

  goToDatabases() {
    this.context.router.push("dbs");
    this.setState({
      showMenu: false
    });
  }

  goToNotes() {
    this.context.router.push("notesList");
    this.setState({
      showMenu: false
    });
  }

  showMenu() {
    this.setState({
      showMenu: true
    });
  }

  syncAll() {
    this.context.repo.getAllDbs().then((dbs) => {
      return Promise.all(dbs.map((db) => {
        return this.context.repo.syncDb(db).then(() => {
          this.context.pubsub.publish("info.db.sync." + db._id, db);
        }).catch((err) => {
          this.context.pubsub.publish("error.db.sync." + db._id, err);
        });
      }));
    });
  }
}

App.contextTypes = {
  router: React.PropTypes.object,
  pubsub: React.PropTypes.object,
  repo: React.PropTypes.object
};

export default App;
<commit_msg>added check for empty sync address to sync all function<commit_after>import React, { Component } from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import AppBar from 'material-ui/AppBar';
import Drawer from 'material-ui/Drawer';
import MenuItem from 'material-ui/MenuItem';
import FlatButton from 'material-ui/FlatButton';

import MnSnackbar from "./MnSnackbar";

import './App.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showMenu: false
    };
  }

  render() {
    return (
      <MuiThemeProvider>

          <AppBar
            title="> notes"
            onLeftIconButtonTouchTap={this.showMenu.bind(this)}
            iconElementRight={<FlatButton label="Sync" />}
            onRightIconButtonTouchTap={this.syncAll.bind(this)}
          />
          <Drawer open={this.state.showMenu}>
            <MenuItem onTouchTap={this.goToDatabases.bind(this)}>Databases</MenuItem>
            <MenuItem onTouchTap={this.goToNotes.bind(this)}>Notes</MenuItem>
          </Drawer>
          {this.props.children}
          <MnSnackbar/>

      </MuiThemeProvider>
    );
  }

  goToDatabases() {
    this.context.router.push("dbs");
    this.setState({
      showMenu: false
    });
  }

  goToNotes() {
    this.context.router.push("notesList");
    this.setState({
      showMenu: false
    });
  }

  showMenu() {
    this.setState({
      showMenu: true
    });
  }

  syncAll() {
    this.context.repo.getAllDbs().then((dbs) => {
      return Promise.all(dbs.filer((db) => {
        return db.syncAddr && db.syncAddr !== "";
      }).map((db) => {
        return this.context.repo.syncDb(db).then(() => {
          this.context.pubsub.publish("info.db.sync." + db._id, db);
        }).catch((err) => {
          this.context.pubsub.publish("error.db.sync." + db._id, err);
        });
      }));
    });
  }
}

App.contextTypes = {
  router: React.PropTypes.object,
  pubsub: React.PropTypes.object,
  repo: React.PropTypes.object
};

export default App;
<|endoftext|>


<commit_before>'use strict';
/*
 * Feeds Controller
 *
 */
function FeedsCtrl($scope, $rootScope, $feedDataPaths, $feedsService, $location, $filter, ngTableParams, $interval, $timeout, $route) {

  // initialize page header variables
  $rootScope.setPageHeader("Feeds", $rootScope.getBreadCrumbs(), "feeds", null);

  $feedDataPaths.getResponse({ path: "/db/feeds",
                               scope: $rootScope,
                               key: "feeds",
                               errorMessage: "Could not retrieve Feeds."});
}

/*
 * Get the Feed Queue
 *
 */
function FeedsCtrl_getFeedQueue($scope, $rootScope, $feedsService, servicePath, $filter, ngTableParams){

  // get Feed Queue
  $feedsService.getFeedQueue(servicePath)
    .success(function (data) {

      // set the feeds data into the Angular model
      $scope.feedQueue = data.feedQueue;

    }).error(function (data) {

      $rootScope.pageHeader.error += "Could not retrieve List of Queued Feeds. ";

      // so the loading spinner goes away and we are left with an empty table
      $scope.feedQueue = {};
    });
}
<commit_msg>[CS] We don't have the feed queue anymore<commit_after>'use strict';
/*
 * Feeds Controller
 *
 */
function FeedsCtrl($scope, $rootScope, $feedDataPaths, $feedsService, $location, $filter, ngTableParams, $interval, $timeout, $route) {

  // initialize page header variables
  $rootScope.setPageHeader("Feeds", $rootScope.getBreadCrumbs(), "feeds", null);

  $feedDataPaths.getResponse({ path: "/db/feeds",
                               scope: $rootScope,
                               key: "feeds",
                               errorMessage: "Could not retrieve Feeds."});
}
<|endoftext|>


<commit_before>'use strict';

describe("angular-inview", function() {

	var $rootScope, $compile, $q;

	beforeEach(function () {
		module('angular-inview');

		inject(function (_$rootScope_, _$compile_, _$q_) {
			$rootScope = _$rootScope_;
			$compile = _$compile_;
			$q = _$q_;
		});
	});

	describe("in-view directive", function() {

		it("should trigger in-view expression with `$inview` local", function(done) {
			makeTestForHtml(
				'

'
			)
			.then(function (test) {
				expect(test.spy.calls.count()).toBe(1);
				expect(test.spy).toHaveBeenCalledWith(true);
			})
			.then(done);
		});

		it("should not trigger in-view expression if out of viewport", function(done) {
			makeTestForHtml(
				'

'
			)
			.then(function (test) {
				expect(test.spy.calls.count()).toBe(0);
			})
			.then(done);
		});

		it("should change inview status when scrolling out of view", function(done) {
			makeTestForHtml(
				'

' +
				'

'
			)
			.then(lazyScrollTo(100))
			.then(function (test) {
				expect(test.spy.calls.count()).toBe(2);
				expect(test.spy).toHaveBeenCalledWith(true);
				expect(test.spy).toHaveBeenCalledWith(false);
			})
			.then(done);
		});

		describe("informations object", function() {

			it("should return an info object with relative informations", function(done) {
				makeTestForHtml(
					'

'
				)
				.then(function (test) {
					expect(test.spy.calls.count()).toBe(1);
					var info = test.spy.calls.mostRecent().args[0];
					expect(info.inView).toEqual(true);
					expect(info.parts).toEqual({
						top: true,
						left: true,
						bottom: true,
						right: true
					});
				})
				.then(done);
			});

		});

	});

	// A test object has the properties:
	//
	//  - `element`: An angular element inserted in the test page
	//  - `scope`: a new isolated scope that can be referenced in the element
	//  - `spy`: a conveninence jasmine spy attached to the scope as `spy`
	function makeTestForHtml(html) {
		var test = {};
		// Prepare test elements
		window.document.body.style.height = '100%';
		window.document.body.parentElement.style.height = '100%';
		test.element = angular.element(html);
		angular.element(window.document.body).empty().append(test.element);
		// Prepare test scope
		test.scope = $rootScope.$new(true);
		test.spy = test.scope.spy = jasmine.createSpy('spy');
		// Compile the element
		$compile(test.element)(test.scope);
		test.scope.$digest();
		return scrollTo(window, [0, 0]).then(function () {
			return test;
		});
	}

	// Scrolls the element to the given x, y position and waits a bit before
	// resolving the returned promise.
	function scrollTo(element, position) {
		if (!angular.isDefined(position)) {
			position = element;
			element = window;
		}
		if (!angular.isArray(position)) {
			position = [0, position];
		}
		// Prepare promise resolution
		var deferred = $q.defer(), timeout;
		var scrollOnceHandler = function () {
			var check = (element === window) ?
				[element.scrollX, element.scrollY] :
				[element.scrollLeft, element.scrollTop];
			if (check[0] != position[0] || check[1] != position[1]) {
				return;
			}
			if (timeout) {
				clearTimeout(timeout);
				timeout = null;
			}
			angular.element(element).off('scroll', scrollOnceHandler);
			deferred.resolve();
			$rootScope.$digest();
		};
		angular.element(element).on('scroll', scrollOnceHandler);
		// Actual scrolling
		if (element === window) {
			element.scrollTo.apply(element, position);
		}
		else {
			element.scrollLeft += position[0];
			element.scrollTop += position[1];
		}
		// Backup resolver
		timeout = setTimeout(function () {
			angular.element(element).off('scroll', scrollOnceHandler);
			var check = (element === window) ?
				[element.scrollX, element.scrollY] :
				[element.scrollLeft, element.scrollTop];
			if (check[0] != position[0] || check[1] != position[1]) {
				deferred.reject();
			}
			else {
				deferred.resolve();
			}
			$rootScope.$digest();
		}, 100);
		return deferred.promise;
	}

	function lazyScrollTo () {
		var args = arguments;
		return function (x) {
			return scrollTo.apply(null, args).then(function () {
				return x;
			});
		}
	}

});
<commit_msg>Add test for inviewInfo changes<commit_after>'use strict';

describe("angular-inview", function() {

	var $rootScope, $compile, $q;

	beforeEach(function () {
		module('angular-inview');

		inject(function (_$rootScope_, _$compile_, _$q_) {
			$rootScope = _$rootScope_;
			$compile = _$compile_;
			$q = _$q_;
		});
	});

	describe("in-view directive", function() {

		it("should trigger in-view expression with `$inview` local", function(done) {
			makeTestForHtml(
				'

'
			)
			.then(function (test) {
				expect(test.spy.calls.count()).toBe(1);
				expect(test.spy).toHaveBeenCalledWith(true);
			})
			.then(done);
		});

		it("should not trigger in-view expression if out of viewport", function(done) {
			makeTestForHtml(
				'

'
			)
			.then(function (test) {
				expect(test.spy.calls.count()).toBe(0);
			})
			.then(done);
		});

		it("should change inview status when scrolling out of view", function(done) {
			makeTestForHtml(
				'

' +
				'

'
			)
			.then(lazyScrollTo(100))
			.then(function (test) {
				expect(test.spy.calls.count()).toBe(2);
				expect(test.spy).toHaveBeenCalledWith(true);
				expect(test.spy).toHaveBeenCalledWith(false);
			})
			.then(done);
		});

		describe("informations object", function() {

			it("should return an info object with relative informations", function(done) {
				makeTestForHtml(
					'

'
				)
				.then(function (test) {
					expect(test.spy.calls.count()).toBe(1);
					var info = test.spy.calls.mostRecent().args[0];
					expect(info.inView).toEqual(true);
					expect(info.parts).toEqual({
						top: true,
						left: true,
						bottom: true,
						right: true
					});
				})
				.then(done);
			});

			it("should return proper `parts` informations", function(done) {
				makeTestForHtml(
					'

' +
					'

'
				)
				.then(function (test) {
					expect(test.spy.calls.count()).toBe(1);
					var info = test.spy.calls.argsFor(0)[0];
					expect(info.parts).toEqual({
						top: false,
						left: false,
						bottom: true,
						right: true
					});
					return test;
				})
				.then(lazyScrollTo([400, 400]))
				.then(function (test) {
					var info = test.spy.calls.argsFor(1)[0];
					expect(test.spy.calls.count()).toBe(2);
					expect(info.parts).toEqual(undefined);
				})
				.then(done);
			});

		});

	});

	// A test object has the properties:
	//
	//  - `element`: An angular element inserted in the test page
	//  - `scope`: a new isolated scope that can be referenced in the element
	//  - `spy`: a conveninence jasmine spy attached to the scope as `spy`
	function makeTestForHtml(html) {
		var test = {};
		// Prepare test elements
		window.document.body.style.height = '100%';
		window.document.body.parentElement.style.height = '100%';
		test.element = angular.element(html);
		angular.element(window.document.body).empty().append(test.element);
		// Prepare test scope
		test.scope = $rootScope.$new(true);
		test.spy = test.scope.spy = jasmine.createSpy('spy');
		// Compile the element
		$compile(test.element)(test.scope);
		test.scope.$digest();
		return scrollTo(window, [0, 0]).then(function () {
			return test;
		});
	}

	// Scrolls the element to the given x, y position and waits a bit before
	// resolving the returned promise.
	function scrollTo(element, position) {
		if (!angular.isDefined(position)) {
			position = element;
			element = window;
		}
		if (!angular.isArray(position)) {
			position = [0, position];
		}
		// Prepare promise resolution
		var deferred = $q.defer(), timeout;
		var scrollOnceHandler = function () {
			var check = (element === window) ?
				[element.scrollX, element.scrollY] :
				[element.scrollLeft, element.scrollTop];
			if (check[0] != position[0] || check[1] != position[1]) {
				return;
			}
			if (timeout) {
				clearTimeout(timeout);
				timeout = null;
			}
			angular.element(element).off('scroll', scrollOnceHandler);
			deferred.resolve();
			$rootScope.$digest();
		};
		angular.element(element).on('scroll', scrollOnceHandler);
		// Actual scrolling
		if (element === window) {
			element.scrollTo.apply(element, position);
		}
		else {
			element.scrollLeft += position[0];
			element.scrollTop += position[1];
		}
		// Backup resolver
		timeout = setTimeout(function () {
			angular.element(element).off('scroll', scrollOnceHandler);
			var check = (element === window) ?
				[element.scrollX, element.scrollY] :
				[element.scrollLeft, element.scrollTop];
			if (check[0] != position[0] || check[1] != position[1]) {
				deferred.reject();
			}
			else {
				deferred.resolve();
			}
			$rootScope.$digest();
		}, 100);
		return deferred.promise;
	}

	function lazyScrollTo () {
		var args = arguments;
		return function (x) {
			return scrollTo.apply(null, args).then(function () {
				return x;
			});
		}
	}

});
<|endoftext|>