<commit_before>//  AJAX: FETCH Assets 3d
function wpunity_fetchSceneAssetsAjax(isAdmin, gameProjectSlug, urlforAssetEdit){

    jQuery.ajax({
        url :  isAdmin == "back" ? 'admin-ajax.php' : my_ajax_object_fbrowse.ajax_url,
        type : 'POST',
        data : {
            'action': 'wpunity_fetch_game_assets_action',
            'gameProjectSlug': gameProjectSlug
        },

        success : function(responseRecords) {

            responseRecords = responseRecords.items;

            file_Browsing_By_DB(responseRecords, gameProjectSlug, urlforAssetEdit);
        },
        error : function(xhr, ajaxOptions, thrownError){
            console.log("ERROR 51:" + thrownError);
        }
    });
}

/**
 * Start the browser
 * @param responseData
 */
function file_Browsing_By_DB(responseData, gameProjectSlug, urlforAssetEdit) {

    var filemanager = jQuery('#fileBrowserToolbar'),
        //breadcrumbs = jQuery('.breadcrumbs'),
        fileList = filemanager.find('.data'),
        closeButton = jQuery('.bt_close_file_toolbar');

    render(responseData, gameProjectSlug, urlforAssetEdit );

    // Hiding and showing the search box
    filemanager.find('.search').click(function() {
        var search = jQuery(this);
        search.find('span').hide();
        search.find('input[type=search]').show().focus();
    });

    // Listening for keyboard input on the search field.
    // We are using the "input" event which detects cut and paste
    // in addition to keyboard input.

    filemanager.find('input').on('input', function(e){

        var value = this.value.trim();

        if(value.length) {
            filemanager.addClass('searching');

            // Filter the responseData according to value.trim()
            filteredResponseData = selectByTitleComparizon(responseData, value.trim());
            render(filteredResponseData, gameProjectSlug, urlforAssetEdit);
        } else {
            filemanager.removeClass('searching');
            render(responseData, gameProjectSlug, urlforAssetEdit);
        }

    }).on('keyup', function(e){ // Clicking 'ESC' button triggers focusout and cancels the search
        var search = jQuery(this);
        if(e.keyCode === 27)
            search.trigger('focusout');
    }).focusout(function(e){  // Cancel the search
        var search = jQuery(this);
        if(!search.val().trim().length) {
            //window.location.hash = encodeURIComponent(currentPath);
            search.hide();
            search.parent().find('span').show();
        }
    });

    fileList.on({
        click: function(e) {
            //alert("Drag n drop zip files onto 3D space");
            e.preventDefault();
        },

        dragstart: function(e) {

            var dragData = {
                "title": e.target.attributes.getNamedItem("data-assetslug").value + "_" + Math.floor(Date.now() / 1000),
                "assetid": e.target.attributes.getNamedItem("data-assetid").value,
                "obj": e.target.attributes.getNamedItem("data-objPath").value,
                "objID": e.target.attributes.getNamedItem("data-objID").value,
                "mtl": e.target.attributes.getNamedItem("data-mtlPath").value,
                "mtlID": e.target.attributes.getNamedItem("data-mtlID").value,
                "diffImages": e.target.attributes.getNamedItem("data-diffImages").value,
                "diffImageIDs": e.target.attributes.getNamedItem("data-diffImageIDs").value,
                "categoryID": e.target.attributes.getNamedItem("data-categoryID").value,
                "categoryName": e.target.attributes.getNamedItem("data-categoryName").value,
                "image1id":e.target.attributes.getNamedItem("data-image1id").value,
                "doorName_source":e.target.attributes.getNamedItem("data-doorName_source").value,
                "doorName_target":e.target.attributes.getNamedItem("data-doorName_target").value,
                "sceneName_target":e.target.attributes.getNamedItem("data-sceneName_target").value
            };

            var jsonDataDrag = JSON.stringify(dragData);

            e.originalEvent.dataTransfer.setData("text/plain", jsonDataDrag);

        },
        drag: function(e) {
            e.preventDefault();
        },
        dragend: function(e) {
            e.preventDefault();
        }
    });

    // Render the HTML for the file manager
    // Here we make the list
    function render(enlistData, gameProjectSlug, urlforAssetEdit) {

        var i, f, name;

        // Empty the old result and make the new one
        fileList.empty().hide();

        if (!enlistData) {
            filemanager.find('.nothingfound').show();
        } else  {
            filemanager.find('.nothingfound').hide();

            for (i = 0; i < enlistData.length; i++) {

                f = enlistData[i];

                var fileSize = bytesToSize(f.size);

                name = escapeHTML(f.name);

                if(!f.objPath)
                    return;

                var fileType = f.objPath.split('.').pop();

                /*var icon = '.'+f.categoryName+'';*/
                var img;
                var imgFileExtension;

                if (fileType.toUpperCase() === 'JPG' || fileType.toUpperCase()==='PNG') {
                    imgFileExtension = '';
                }
                // Check if icon of obj exists  file.obj.png or file.obj.jpg
                else if (fileType.toUpperCase() === 'OBJ') {
                    imgFileExtension = '.jpg';
                }

                if (!f.screenImagePath) {
                    f.screenImagePath = f.mtlPath.substr(0, f.mtlPath.indexOf('uploads')) + 'plugins/WordpressUnity3DEditor/images/ic_no_sshot.png';
                }

                img = '
'+ fileSize +'';

                var file = jQuery('
' +
                    '<a class="mdc-list-item" style="align-items:baseline; left:0; padding:6px 0 6px 6px; height: 100%; width:100%" href="'+ f.objPath +
                    '" title="'+ f.name +
                    '" data-assetslug="'+ f.assetSlug +
                    '" data-assetid="'+ f.assetid +
                    '" data-objPath="'+ f.objPath +
                    '" data-objID="'+ f.objID +
                    '" data-mtlPath="'+ f.mtlPath +
                    '" data-mtlID="'+ f.mtlID +
                    '" data-diffImages="'+ f.diffImages +
                    '" data-diffImageIDs="'+ f.diffImageIDs +
                    '" data-categoryID="'+ f.categoryID +
                    '" data-categoryName="'+ f.categoryName +
                    '" data-image1id="'+ f.image1id +
                    '" data-doorName_source="'+ f.doorName_source +
                    '" data-doorName_target="'+ f.doorName_target +
                    '" data-sceneName_target="'+ f.sceneName_target +
                    '" >' + img +
                    ''+ name +
                    ''+ f.categoryName +'' +
                    '' +
                    'Edit'+
                    'Delete'+
                    '' +
                    '
\n' +
                    '

\n' +
                    '

\n' +
                    '

\n' +
                    '
' +
                    '
' );

            // <?php echo esc_url( get_permalink($newAssetPage[0]->ID) . $parameter_pass . $project_id . $parameter_assetpass . $asset_checked_id ); ?>

                file.appendTo(fileList);
            }

            mdc.autoInit(document, () => {});
        }

        // Remove animation
        if(filemanager.hasClass('searching'))
            fileList.removeClass('animated');

        // Show the generated elements
        fileList.animate({'display':'inline-block'});

        // Perform click to open (bug appeared from migrating jquery-1.11 to 3.1.1
        closeButton.click();
    }

    // This function escapes special html characters in names
    function escapeHTML(text) {
        return text.replace(/\&/g,'&').replace(/\</g,'<').replace(/\>/g,'>');
    }

    // Convert file sizes from bytes to human readable units
    function bytesToSize(bytes) {
        var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
        if (bytes == 0) return '0 Bytes';
        var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
        return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
    }

    function selectByTitleComparizon(input_data, needle){
        var output_data = [];

        input_data.forEach(function(d){
            if (d.assetName.indexOf(needle) !== -1)
                    output_data.push(d);
        });
        return output_data;
    }

}<commit_msg>- Fix asset viewer on 3D editor<commit_after>//  AJAX: FETCH Assets 3d
function wpunity_fetchSceneAssetsAjax(isAdmin, gameProjectSlug, urlforAssetEdit){

    jQuery.ajax({
        url :  isAdmin == "back" ? 'admin-ajax.php' : my_ajax_object_fbrowse.ajax_url,
        type : 'POST',
        data : {
            'action': 'wpunity_fetch_game_assets_action',
            'gameProjectSlug': gameProjectSlug
        },

        success : function(responseRecords) {

            responseRecords = responseRecords.items;

            file_Browsing_By_DB(responseRecords, gameProjectSlug, urlforAssetEdit);
        },
        error : function(xhr, ajaxOptions, thrownError){
            console.log("ERROR 51:" + thrownError);
        }
    });
}

/**
 * Start the browser
 * @param responseData
 */
function file_Browsing_By_DB(responseData, gameProjectSlug, urlforAssetEdit) {

    var filemanager = jQuery('#fileBrowserToolbar'),
        //breadcrumbs = jQuery('.breadcrumbs'),
        fileList = filemanager.find('.data'),
        closeButton = jQuery('.bt_close_file_toolbar');

    render(responseData, gameProjectSlug, urlforAssetEdit );

    // Hiding and showing the search box
    filemanager.find('.search').click(function() {
        var search = jQuery(this);
        search.find('span').hide();
        search.find('input[type=search]').show().focus();
    });

    // Listening for keyboard input on the search field.
    // We are using the "input" event which detects cut and paste
    // in addition to keyboard input.

    filemanager.find('input').on('input', function(e){

        var value = this.value.trim();

        if(value.length) {
            filemanager.addClass('searching');

            // Filter the responseData according to value.trim()
            filteredResponseData = selectByTitleComparizon(responseData, value.trim());
            render(filteredResponseData, gameProjectSlug, urlforAssetEdit);
        } else {
            filemanager.removeClass('searching');
            render(responseData, gameProjectSlug, urlforAssetEdit);
        }

    }).on('keyup', function(e){ // Clicking 'ESC' button triggers focusout and cancels the search
        var search = jQuery(this);
        if(e.keyCode === 27)
            search.trigger('focusout');
    }).focusout(function(e){  // Cancel the search
        var search = jQuery(this);
        if(!search.val().trim().length) {
            //window.location.hash = encodeURIComponent(currentPath);
            search.hide();
            search.parent().find('span').show();
        }
    });

    fileList.on({
        click: function(e) {
            //alert("Drag n drop zip files onto 3D space");
            e.preventDefault();
        },

        dragstart: function(e) {

            var dragData = {
                "title": e.target.attributes.getNamedItem("data-assetslug").value + "_" + Math.floor(Date.now() / 1000),
                "assetid": e.target.attributes.getNamedItem("data-assetid").value,
                "obj": e.target.attributes.getNamedItem("data-objPath").value,
                "objID": e.target.attributes.getNamedItem("data-objID").value,
                "mtl": e.target.attributes.getNamedItem("data-mtlPath").value,
                "mtlID": e.target.attributes.getNamedItem("data-mtlID").value,
                "diffImages": e.target.attributes.getNamedItem("data-diffImages").value,
                "diffImageIDs": e.target.attributes.getNamedItem("data-diffImageIDs").value,
                "categoryID": e.target.attributes.getNamedItem("data-categoryID").value,
                "categoryName": e.target.attributes.getNamedItem("data-categoryName").value,
                "image1id":e.target.attributes.getNamedItem("data-image1id").value,
                "doorName_source":e.target.attributes.getNamedItem("data-doorName_source").value,
                "doorName_target":e.target.attributes.getNamedItem("data-doorName_target").value,
                "sceneName_target":e.target.attributes.getNamedItem("data-sceneName_target").value
            };

            var jsonDataDrag = JSON.stringify(dragData);

            e.originalEvent.dataTransfer.setData("text/plain", jsonDataDrag);

        },
        drag: function(e) {
            e.preventDefault();
        },
        dragend: function(e) {
            e.preventDefault();
        }
    });

    // Render the HTML for the file manager
    // Here we make the list
    function render(enlistData, gameProjectSlug, urlforAssetEdit) {

        var i, f, name;

        // Empty the old result and make the new one
        fileList.empty().hide();

        if (!enlistData) {
            filemanager.find('.nothingfound').show();
        } else  {
            filemanager.find('.nothingfound').hide();

            console.log(enlistData);

            for (i = 0; i < enlistData.length; i++) {

                f = enlistData[i];

                var fileSize = bytesToSize(f.size);

                name = escapeHTML(f.name);

                if(f.categoryName=="Molecule")
                    continue;

                if(!f.objPath)
                     continue;

                var fileType = f.objPath.split('.').pop();

                /*var icon = '.'+f.categoryName+'';*/
                var img;
                var imgFileExtension;

                if (fileType.toUpperCase() === 'JPG' || fileType.toUpperCase()==='PNG') {
                    imgFileExtension = '';
                }

                // Check if icon of obj exists  file.obj.png or file.obj.jpg
                else if (fileType.toUpperCase() === 'OBJ') {
                    imgFileExtension = '.jpg';
                }

                if (!f.screenImagePath) {
                    f.screenImagePath = f.mtlPath.substr(0, f.mtlPath.indexOf('uploads')) + 'plugins/WordpressUnity3DEditor/images/ic_no_sshot.png';
                }

                img = '
'+ fileSize +'';

                var file = jQuery('
' +
                    '<a class="mdc-list-item" style="align-items:baseline; left:0; padding:6px 0 6px 6px; height: 100%; width:100%" href="'+ f.objPath +
                    '" title="'+ f.name +
                    '" data-assetslug="'+ f.assetSlug +
                    '" data-assetid="'+ f.assetid +
                    '" data-objPath="'+ f.objPath +
                    '" data-objID="'+ f.objID +
                    '" data-mtlPath="'+ f.mtlPath +
                    '" data-mtlID="'+ f.mtlID +
                    '" data-diffImages="'+ f.diffImages +
                    '" data-diffImageIDs="'+ f.diffImageIDs +
                    '" data-categoryID="'+ f.categoryID +
                    '" data-categoryName="'+ f.categoryName +
                    '" data-image1id="'+ f.image1id +
                    '" data-doorName_source="'+ f.doorName_source +
                    '" data-doorName_target="'+ f.doorName_target +
                    '" data-sceneName_target="'+ f.sceneName_target +
                    '" >' + img +
                    ''+ name +
                    ''+ f.categoryName +'' +
                    '' +
                    'Edit'+
                    'Delete'+
                    '' +
                    '
\n' +
                    '

\n' +
                    '

\n' +
                    '

\n' +
                    '
' +
                    '
' );

            // <?php echo esc_url( get_permalink($newAssetPage[0]->ID) . $parameter_pass . $project_id . $parameter_assetpass . $asset_checked_id ); ?>

                file.appendTo(fileList);
            }

            mdc.autoInit(document, () => {});
        }

        // Remove animation
        if(filemanager.hasClass('searching'))
            fileList.removeClass('animated');

        // Show the generated elements
        fileList.animate({'display':'inline-block'});

        // Perform click to open (bug appeared from migrating jquery-1.11 to 3.1.1
        closeButton.click();
    }

    // This function escapes special html characters in names
    function escapeHTML(text) {
        return text.replace(/\&/g,'&').replace(/\</g,'<').replace(/\>/g,'>');
    }

    // Convert file sizes from bytes to human readable units
    function bytesToSize(bytes) {
        var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
        if (bytes == 0) return '0 Bytes';
        var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
        return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
    }

    function selectByTitleComparizon(input_data, needle){
        var output_data = [];

        input_data.forEach(function(d){
            if (d.assetName.indexOf(needle) !== -1)
                    output_data.push(d);
        });
        return output_data;
    }

}<|endoftext|>


<commit_before>'use strict';
var file = require('file');
var path = require('path');
var generators = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var mkdirp = require('mkdirp');
var camelcase = require('lodash.camelcase');
var kebabcase = require('lodash.kebabcase');
var trim = require('lodash.trim');
var Promise = require('bluebird');
var exec = Promise.promisify(require('child_process').exec);
var gitConfig = require('git-config');

module.exports = generators.Base.extend({
  initializing: function() {
    this.pkg = require('../package.json');
  },

  prompting: function() {
    var done = this.async();

    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the ' + chalk.red('Babel Library Boilerplate') + ' generator!'
    ));

    Promise.all([exec('npm whoami').catch(function(e) {
      console.error('Error getting npm user name: run `npm login`');
      console.error(e);
    })])
    .then(function(result) {
      result = result ? result : {};
      this.username = trim(result[0]);
      this._showPrompts(done);
    }.bind(this));
  },

  _showPrompts: function(done) {
    var config = gitConfig.sync();
    config.user = config.user ? config.user : {};
    var prompts = [{
      type: 'input',
      name: 'user',
      message: 'What is the Github username/organization for this project?',
      default: this.username,
      store: true
    }, {
      type: 'input',
      name: 'repo',
      message: 'What is the repository/project name?',
      default: kebabcase(this.appname)
    }, {
      type: 'input',
      name: 'description',
      message: 'What is a short description for this project?'
    }, {
      type: 'input',
      name: 'author',
      message: 'Who is the author of this project?',
      default: config.user.name + ' <' + config.user.email + '>',
      store: true
    }, {
      type: 'input',
      name: 'variable',
      message: 'If there is one, what is the name of this project\'s main variable?',
      default: camelcase(this.appname)
    }];

    this.prompt(prompts, function (props) {
      this.user = props.user;
      this.repo = props.repo;
      this.description = props.description;
      this.author = props.author;
      this.variable = props.variable;
      done();
    }.bind(this));
  },

  writing: {
    app: function() {
      var src = this.sourceRoot();
      var self = this;
      file.walkSync(src, function(dirPath, dirs, files) {
        var relativeDir = path.relative(src, dirPath);
        files.forEach(function(filename) {
          var target;
          // Only copy the files that we don't want to rename. We do that after this loop.
          // The files we don't want to rename are both "index.js", and one of them is in
          // "test/unit," and the other is in "src"
          var ignoreDir = relativeDir === 'test/unit' || relativeDir === 'src';
          var shouldCopy = !ignoreDir && !/index.js$/.test(filename);
          if (shouldCopy) {
            target = path.join(relativeDir, filename);
            self.template(target, target);
          }
        });
      });
      this.template('src/index.js', 'src/' + this.repo + '.js');
      this.template('test/unit/index.js', 'test/unit/' + this.repo + '.js');
    }
  },

  install: function() {
    this.installDependencies({
      bower: false,
      npm: true,
      skipInstall: this.options['skip-install']
    });
  }
});
<commit_msg>Use a Promise API for Yeoman, rather than this.async<commit_after>'use strict';
var file = require('file');
var path = require('path');
var generators = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var mkdirp = require('mkdirp');
var camelcase = require('lodash.camelcase');
var kebabcase = require('lodash.kebabcase');
var trim = require('lodash.trim');
var Promise = require('bluebird');
var exec = Promise.promisify(require('child_process').exec);
var gitConfig = require('git-config');

module.exports = generators.Base.extend({
  initializing: function() {
    this.pkg = require('../package.json');
  },

  prompting: function() {
    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the ' + chalk.red('Babel Library Boilerplate') + ' generator!'
    ));

    return Promise.all([exec('npm whoami').catch(function(e) {
      console.error('Error getting npm user name: run `npm login`');
      console.error(e);
    })])
    .then(function(result) {
      result = result ? result : {};
      this.username = trim(result[0]);
      return this._showPrompts();
    }.bind(this));
  },

  _showPrompts: function() {
    var config = gitConfig.sync();
    config.user = config.user ? config.user : {};
    var prompts = [{
      type: 'input',
      name: 'user',
      message: 'What is the Github username/organization for this project?',
      default: this.username,
      store: true
    }, {
      type: 'input',
      name: 'repo',
      message: 'What is the repository/project name?',
      default: kebabcase(this.appname)
    }, {
      type: 'input',
      name: 'description',
      message: 'What is a short description for this project?'
    }, {
      type: 'input',
      name: 'author',
      message: 'Who is the author of this project?',
      default: config.user.name + ' <' + config.user.email + '>',
      store: true
    }, {
      type: 'input',
      name: 'variable',
      message: 'If there is one, what is the name of this project\'s main variable?',
      default: camelcase(this.appname)
    }];

    var self = this;
    return new Promise(function(resolve, reject) {
      self.prompt(prompts, function(props) {
        self.user = props.user;
        self.repo = props.repo;
        self.description = props.description;
        self.author = props.author;
        self.variable = props.variable;
        resolve();
      });
    });
  },

  writing: {
    app: function() {
      var src = this.sourceRoot();
      var self = this;
      file.walkSync(src, function(dirPath, dirs, files) {
        var relativeDir = path.relative(src, dirPath);
        files.forEach(function(filename) {
          var target;
          // Only copy the files that we don't want to rename. We do that after this loop.
          // The files we don't want to rename are both "index.js", and one of them is in
          // "test/unit," and the other is in "src"
          var ignoreDir = relativeDir === 'test/unit' || relativeDir === 'src';
          var shouldCopy = !ignoreDir && !/index.js$/.test(filename);
          if (shouldCopy) {
            target = path.join(relativeDir, filename);
            self.template(target, target);
          }
        });
      });
      this.template('src/index.js', 'src/' + this.repo + '.js');
      this.template('test/unit/index.js', 'test/unit/' + this.repo + '.js');
    }
  },

  install: function() {
    this.installDependencies({
      bower: false,
      npm: true,
      skipInstall: this.options['skip-install']
    });
  }
});
<|endoftext|>


<commit_before>'use strict';

var yeoman = require('yeoman-generator');
var yosay = require('yosay');
var cordova = new (require('./cordovaAdapter.js'))('cordova');
var _ = require('underscore');
var OptionBuilder = require('./optionBuilder.js');
var promptConfig = require('./promptConfig.js');
var ProjectFiles = require('./projectFiles.js');

var GraybulletCordovaGenerator = yeoman.generators.Base.extend({
  constructor: function () {
    yeoman.Base.apply(this, arguments);

    // Delegate options from generator-webapp.
    this.optionBuilder = new OptionBuilder(this, this.env.create('webapp'));
    this.optionBuilder.copyDelegatedDefines();
  },

  initializing: function () {
    this.pkg = require('../package.json');

    this.projectOptions = {};
  },

  prompting: {
    /**
     * Prompting project information.
     */
    promptingProject: function () {
      var done = this.async();

      this.log(yosay('Welcome to the Apache Cordova generator!'));

      var prompts = [
        {
          name: 'name',
          message: 'What is the name of Apache Cordova App?',
          'default': 'HelloCordova'
        }, {
          name: 'id',
          message: 'What is the ID of Apache Cordova App?',
          'default': 'io.cordova.hellocordova'
        }
      ];

      this.prompt(prompts, function (props) {
        this.projectOptions.name = props.appName;
        this.projectOptions.id = props.id;

        done();
      }.bind(this));
    },

    /**
     * Create Apache Cordova project to 'cordova' directory.
     */
    createCordovaProject: function () {
      var done = this.async();

      cordova.create(this.projectOptions.id, this.projectOptions.name, done);
    },

    /**
     * Prompting adding platforms.
     */
    promptingAddPlatforms: function () {
      var done = this.async();

      var prompt = function (platforms) {
        var prompts = [
          _.extend(promptConfig.getPlatforms(platforms), {
            name: 'platforms',
            message: 'What app of the platform to be created?'
          })
        ];

        this.prompt(prompts, function (props) {
          this.projectOptions.platforms = props.platforms;

          done();
        }.bind(this));
      }.bind(this);

      cordova.getAvailablePlatforms(prompt);
    },

    /**
     * Add Cordova Platforms to Apache Cordova Project.
     */
    addPlatforms: function () {
      if (this.projectOptions.platforms.length > 0) {
        var done = this.async();

        cordova.addPlatform(this.projectOptions.platforms, done);
      }
    },

    /**
     * Prompting adding plugins.
     */
    promptingAddPlugins: function () {
      var done = this.async();

      var prompt = function (plugins) {
        var prompts = [
          _.extend(promptConfig.getPlugins(plugins), {
            name: 'plugins',
            message: 'Are you sure you want to add any plugins?'
          })
        ];

        this.prompt(prompts, function (props) {
          this.projectOptions.plugins = props.plugins;

          done();
        }.bind(this));
      }.bind(this);

      cordova.searchPlugin('org.apache.cordova', prompt);
    },

    /**
     * Add plugins.
     */
    addPlugins: function () {
      var done = this.async();

      cordova.addPlugin(this.projectOptions.plugins, done);
    },

    /**
     * Run generator-webapp.
     */
    createWebappProject: function () {
      // Delegate options to generator-webapp.
      var options = this.optionBuilder.getDelegatedValues();

      var createReplaceFiles = function (generator) {
        var files = new ProjectFiles(generator);

        return function () {
          files.loadPackageJson()
            .appendToDevDependencies('cordova', '4.0.0')
            .appendToDevDependencies('grunt-cordova-ng', '^0.1.3')
            .commit();

          files.loadGruntfileJs()
            .changeDistDirectory('cordova/www')
            .appendLoadNpmTasks('grunt-cordova-ng')
            .appendCordovaRoot('./cordova')
            .appendConnectRoot('./fake')
            .renameTask('build', 'buildweb')
            .appendTask('cordova-build', ['cordova:build'])
            .appendTask('cordova-emulate', ['cordova:emulate'])
            .appendTask('cordova-run', ['cordova:run'])
            .appendTask('cordova-compile', ['cordova:compile'])
            .appendTask('cordova-prepare', ['cordova:prepare'])
            .appendTask('build', ['buildweb', 'cordova-build'])
            .appendTask('emulate', ['buildweb', 'cordova-emulate'])
            .appendTask('run', ['buildweb', 'cordova-run'])
            .appendTask('compile', ['buildweb', 'cordova-compile'])
            .appendTask('prepare', ['buildweb', 'cordova-prepare'])
            .commit();

          files.loadIndexHtml()
            .appendScript('cordova.js')
            .setMetas(cordova.getMetasFromIndexHtml()) // Copy meta informations.
            .commit();

          files.loadMainJs()
            .appendToLast('$(document).on(\'deviceready\', function () {\n' +
                          '  console.log(\'deviceready\');\n' +
                          '});')
            .commit();
        };
      };

      var subGenerator = this.composeWith('webapp', {options: options});
      subGenerator.on('end', createReplaceFiles(subGenerator));
    }
  },

  writing: function () {
    this.src.copy('_gitignore-cordova-external', 'cordova/.gitignore');
    this.src.copy('cordova.js', 'fake/cordova.js');
    this.dest.write('cordova/www/.gitkeep', '');
  }
});

module.exports = GraybulletCordovaGenerator;
<commit_msg>Fix bug unknown app name.<commit_after>'use strict';

var yeoman = require('yeoman-generator');
var yosay = require('yosay');
var cordova = new (require('./cordovaAdapter.js'))('cordova');
var _ = require('underscore');
var OptionBuilder = require('./optionBuilder.js');
var promptConfig = require('./promptConfig.js');
var ProjectFiles = require('./projectFiles.js');

var GraybulletCordovaGenerator = yeoman.generators.Base.extend({
  constructor: function () {
    yeoman.Base.apply(this, arguments);

    // Delegate options from generator-webapp.
    this.optionBuilder = new OptionBuilder(this, this.env.create('webapp'));
    this.optionBuilder.copyDelegatedDefines();
  },

  initializing: function () {
    this.pkg = require('../package.json');

    this.projectOptions = {};
  },

  prompting: {
    /**
     * Prompting project information.
     */
    promptingProject: function () {
      var done = this.async();

      this.log(yosay('Welcome to the Apache Cordova generator!'));

      var prompts = [
        {
          name: 'name',
          message: 'What is the name of Apache Cordova App?',
          'default': 'HelloCordova'
        }, {
          name: 'id',
          message: 'What is the ID of Apache Cordova App?',
          'default': 'io.cordova.hellocordova'
        }
      ];

      this.prompt(prompts, function (props) {
        this.projectOptions.name = props.name;
        this.projectOptions.id = props.id;

        done();
      }.bind(this));
    },

    /**
     * Create Apache Cordova project to 'cordova' directory.
     */
    createCordovaProject: function () {
      var done = this.async();

      cordova.create(this.projectOptions.id, this.projectOptions.name, done);
    },

    /**
     * Prompting adding platforms.
     */
    promptingAddPlatforms: function () {
      var done = this.async();

      var prompt = function (platforms) {
        var prompts = [
          _.extend(promptConfig.getPlatforms(platforms), {
            name: 'platforms',
            message: 'What app of the platform to be created?'
          })
        ];

        this.prompt(prompts, function (props) {
          this.projectOptions.platforms = props.platforms;

          done();
        }.bind(this));
      }.bind(this);

      cordova.getAvailablePlatforms(prompt);
    },

    /**
     * Add Cordova Platforms to Apache Cordova Project.
     */
    addPlatforms: function () {
      if (this.projectOptions.platforms.length > 0) {
        var done = this.async();

        cordova.addPlatform(this.projectOptions.platforms, done);
      }
    },

    /**
     * Prompting adding plugins.
     */
    promptingAddPlugins: function () {
      var done = this.async();

      var prompt = function (plugins) {
        var prompts = [
          _.extend(promptConfig.getPlugins(plugins), {
            name: 'plugins',
            message: 'Are you sure you want to add any plugins?'
          })
        ];

        this.prompt(prompts, function (props) {
          this.projectOptions.plugins = props.plugins;

          done();
        }.bind(this));
      }.bind(this);

      cordova.searchPlugin('org.apache.cordova', prompt);
    },

    /**
     * Add plugins.
     */
    addPlugins: function () {
      var done = this.async();

      cordova.addPlugin(this.projectOptions.plugins, done);
    },

    /**
     * Run generator-webapp.
     */
    createWebappProject: function () {
      // Delegate options to generator-webapp.
      var options = this.optionBuilder.getDelegatedValues();

      var createReplaceFiles = function (generator) {
        var files = new ProjectFiles(generator);

        return function () {
          files.loadPackageJson()
            .appendToDevDependencies('cordova', '4.0.0')
            .appendToDevDependencies('grunt-cordova-ng', '^0.1.3')
            .commit();

          files.loadGruntfileJs()
            .changeDistDirectory('cordova/www')
            .appendLoadNpmTasks('grunt-cordova-ng')
            .appendCordovaRoot('./cordova')
            .appendConnectRoot('./fake')
            .renameTask('build', 'buildweb')
            .appendTask('cordova-build', ['cordova:build'])
            .appendTask('cordova-emulate', ['cordova:emulate'])
            .appendTask('cordova-run', ['cordova:run'])
            .appendTask('cordova-compile', ['cordova:compile'])
            .appendTask('cordova-prepare', ['cordova:prepare'])
            .appendTask('build', ['buildweb', 'cordova-build'])
            .appendTask('emulate', ['buildweb', 'cordova-emulate'])
            .appendTask('run', ['buildweb', 'cordova-run'])
            .appendTask('compile', ['buildweb', 'cordova-compile'])
            .appendTask('prepare', ['buildweb', 'cordova-prepare'])
            .commit();

          files.loadIndexHtml()
            .appendScript('cordova.js')
            .setMetas(cordova.getMetasFromIndexHtml()) // Copy meta informations.
            .commit();

          files.loadMainJs()
            .appendToLast('$(document).on(\'deviceready\', function () {\n' +
                          '  console.log(\'deviceready\');\n' +
                          '});')
            .commit();
        };
      };

      var subGenerator = this.composeWith('webapp', {options: options});
      subGenerator.on('end', createReplaceFiles(subGenerator));
    }
  },

  writing: function () {
    this.src.copy('_gitignore-cordova-external', 'cordova/.gitignore');
    this.src.copy('cordova.js', 'fake/cordova.js');
    this.dest.write('cordova/www/.gitkeep', '');
  }
});

module.exports = GraybulletCordovaGenerator;
<|endoftext|>


<commit_before>module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    cssmin: {
      minify: {
        expand: true,
        cwd: 'css/',
        src: ['*.css', '!*.min.css'],
        dest: 'css/',
        ext: '.min.css'
      },
      combine: {
        files: {
          'css/smashApp.min.css': ['css/smash.min.css','css/fonts.min.css']
        }
      }
    },
    jshint:{
      all: ['js/models/**/*.js','js/static/**/*.js','js/views/**/*.js','js/req.js']
    }
  });

  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-cssmin');

  grunt.registerTask('default', ['cssmin', 'jshint']);
  // grunt.registerTask('jscopy', 'copy');
  // grunt.registerTask('release', ['clean:build', 'cssmin', 'copy', 'clean:release', 'jshint']);

}
<commit_msg>Cleaned up Gruntfile<commit_after>module.exports = function(grunt) {
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    cssmin: {
      minify: {
        expand: true,
        cwd: 'css/',
        src: ['*.css', '!*.min.css'],
        dest: 'css/',
        ext: '.min.css'
      },
      combine: {
        files: {
          'css/smashApp.min.css': ['css/smash.min.css','css/fonts.min.css']
        }
      }
    },
    jshint:{
      all: ['js/models/**/*.js','js/static/**/*.js','js/views/**/*.js','js/req.js']
    }
  });

  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-cssmin');

  grunt.registerTask('default', ['cssmin', 'jshint']);

}
<|endoftext|>


<commit_before>'use strict';
var fs = require('fs');
var path = require('path');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');
var chalk = require('chalk');
var wiredep = require('wiredep');

module.exports = yeoman.generators.Base.extend({
  constructor: function () {
    yeoman.generators.Base.apply(this, arguments);

    this.option('test-framework', {
      desc: 'Test framework to be invoked',
      type: String,
      defaults: 'mocha'
    });

    this.option('skip-welcome-message', {
      desc: 'Skips the welcome message',
      type: Boolean
    });

    this.option('skip-install', {
      desc: 'Skips the installation of dependencies',
      type: Boolean
    });

    this.option('skip-install-message', {
      desc: 'Skips the message after the installation of dependencies',
      type: Boolean
    });
  },

  initializing: function () {
    this.pkg = require('../package.json');
  },

  prompting: function () {
    var done = this.async();

    if (!this.options['skip-welcome-message']) {
      this.log(yosay('\'Allo \'allo! Out of the box I include HTML5 Boilerplate, jQuery, and a gulpfile.js to build your app.'));
    }

    var prompts = [{
      type: 'checkbox',
      name: 'features',
      message: 'What more would you like?',
      choices: [{
        name: 'Sass',
        value: 'includeSass',
        checked: true
      }, {
        name: 'Bootstrap',
        value: 'includeBootstrap',
        checked: true
      }, {
        name: 'Modernizr',
        value: 'includeModernizr',
        checked: true
      }]
    }];

    this.prompt(prompts, function (answers) {
      var features = answers.features;

      var hasFeature = function (feat) {
        return features.indexOf(feat) !== -1;
      };

      // manually deal with the response, get back and store the results.
      // we change a bit this way of doing to automatically do this in the self.prompt() method.
      this.includeSass = hasFeature('includeSass');
      this.includeBootstrap = hasFeature('includeBootstrap');
      this.includeModernizr = hasFeature('includeModernizr');

      done();
    }.bind(this));
  },

  writing: {
    gulpfile: function() {
      this.template('gulpfile.js');
    },

    packageJSON: function() {
      this.template('_package.json', 'package.json');
    },

    git: function() {
      this.copy('gitignore', '.gitignore');
      this.copy('gitattributes', '.gitattributes');
    },

    bower: function() {
      var bower = {
        name: this._.slugify(this.appname),
        private: true,
        dependencies: {}
      };

      if (this.includeBootstrap) {
        var bs = 'bootstrap' + (this.includeSass ? '-sass-official' : '');
        bower.dependencies[bs] = '~3.2.0';
      } else {
        bower.dependencies.jquery = '~2.1.1';
      }

      if (this.includeModernizr) {
        bower.dependencies.modernizr = '~2.8.1';
      }

      this.copy('bowerrc', '.bowerrc');
      this.write('bower.json', JSON.stringify(bower, null, 2));
    },

    jshint: function () {
      this.copy('jshintrc', '.jshintrc');
    },

    editorConfig: function () {
      this.copy('editorconfig', '.editorconfig');
    },

    h5bp: function () {
      this.copy('favicon.ico', 'app/favicon.ico');
      this.copy('robots.txt', 'app/robots.txt');
    },

    mainStylesheet: function () {
      var css = 'main';

      if (this.includeSass) {
        css += '.scss';
      } else {
        css += '.css';
      }

      this.copy(css, 'app/styles/' + css);
    },

    writeIndex: function () {
      this.indexFile = this.src.read('index.html');
      this.indexFile = this.engine(this.indexFile, this);

      // wire Bootstrap plugins
      if (this.includeBootstrap) {
        var bs = '../bower_components/';

        if (this.includeSass) {
          bs += 'bootstrap-sass-official/assets/javascripts/bootstrap/';
        } else {
          bs += 'bootstrap/js/';
        }

        this.indexFile = this.appendScripts(this.indexFile, 'scripts/plugins.js', [
          bs + 'affix.js',
          bs + 'alert.js',
          bs + 'dropdown.js',
          bs + 'tooltip.js',
          bs + 'modal.js',
          bs + 'transition.js',
          bs + 'button.js',
          bs + 'popover.js',
          bs + 'carousel.js',
          bs + 'scrollspy.js',
          bs + 'collapse.js',
          bs + 'tab.js'
        ]);
      }

      this.indexFile = this.appendFiles({
        html: this.indexFile,
        fileType: 'js',
        optimizedPath: 'scripts/main.js',
        sourceFileList: ['scripts/main.js']
      });

      this.write('app/index.html', this.indexFile);
    },

    app: function () {
      this.mkdir('app');
      this.mkdir('app/scripts');
      this.mkdir('app/styles');
      this.mkdir('app/images');
      this.mkdir('app/fonts');
      this.copy('main.js', 'app/scripts/main.js');
    }
  },

  install: function () {
    var howToInstall =
      '\nAfter running ' +
      chalk.yellow.bold('npm install & bower install') +
      ', inject your' +
      '\nfront end dependencies by running ' +
      chalk.yellow.bold('gulp wiredep') +
      '.';

    if (this.options['skip-install']) {
      this.log(howToInstall);
      return;
    }

    this.installDependencies({
      skipMessage: this.options['skip-install-message'],
      skipInstall: this.options['skip-install']
    });

    this.on('end', function () {
      var bowerJson = this.dest.readJSON('bower.json');

      // wire Bower packages to .html
      wiredep({
        bowerJson: bowerJson,
        directory: 'bower_components',
        exclude: ['bootstrap-sass', 'bootstrap.js'],
        src: 'app/index.html'
      });

      if (this.includeSass) {
        // wire Bower packages to .scss
        wiredep({
          bowerJson: bowerJson,
          directory: 'bower_components',
          src: 'app/styles/*.scss'
        });
      }

      // ideally we should use composeWith, but we're invoking it here
      // because generator-mocha is changing the working directory
      // https://github.com/yeoman/generator-mocha/issues/28
      this.invoke(this.options['test-framework'], {
        options: {
          'skip-message': this.options['skip-install-message'],
          'skip-install': this.options['skip-install']
        }
      });
    }.bind(this));
  }
});
<commit_msg>Bump Bootstrap version to 3.3.1<commit_after>'use strict';
var fs = require('fs');
var path = require('path');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');
var chalk = require('chalk');
var wiredep = require('wiredep');

module.exports = yeoman.generators.Base.extend({
  constructor: function () {
    yeoman.generators.Base.apply(this, arguments);

    this.option('test-framework', {
      desc: 'Test framework to be invoked',
      type: String,
      defaults: 'mocha'
    });

    this.option('skip-welcome-message', {
      desc: 'Skips the welcome message',
      type: Boolean
    });

    this.option('skip-install', {
      desc: 'Skips the installation of dependencies',
      type: Boolean
    });

    this.option('skip-install-message', {
      desc: 'Skips the message after the installation of dependencies',
      type: Boolean
    });
  },

  initializing: function () {
    this.pkg = require('../package.json');
  },

  prompting: function () {
    var done = this.async();

    if (!this.options['skip-welcome-message']) {
      this.log(yosay('\'Allo \'allo! Out of the box I include HTML5 Boilerplate, jQuery, and a gulpfile.js to build your app.'));
    }

    var prompts = [{
      type: 'checkbox',
      name: 'features',
      message: 'What more would you like?',
      choices: [{
        name: 'Sass',
        value: 'includeSass',
        checked: true
      }, {
        name: 'Bootstrap',
        value: 'includeBootstrap',
        checked: true
      }, {
        name: 'Modernizr',
        value: 'includeModernizr',
        checked: true
      }]
    }];

    this.prompt(prompts, function (answers) {
      var features = answers.features;

      var hasFeature = function (feat) {
        return features.indexOf(feat) !== -1;
      };

      // manually deal with the response, get back and store the results.
      // we change a bit this way of doing to automatically do this in the self.prompt() method.
      this.includeSass = hasFeature('includeSass');
      this.includeBootstrap = hasFeature('includeBootstrap');
      this.includeModernizr = hasFeature('includeModernizr');

      done();
    }.bind(this));
  },

  writing: {
    gulpfile: function() {
      this.template('gulpfile.js');
    },

    packageJSON: function() {
      this.template('_package.json', 'package.json');
    },

    git: function() {
      this.copy('gitignore', '.gitignore');
      this.copy('gitattributes', '.gitattributes');
    },

    bower: function() {
      var bower = {
        name: this._.slugify(this.appname),
        private: true,
        dependencies: {}
      };

      if (this.includeBootstrap) {
        var bs = 'bootstrap' + (this.includeSass ? '-sass-official' : '');
        bower.dependencies[bs] = '~3.3.1';
      } else {
        bower.dependencies.jquery = '~2.1.1';
      }

      if (this.includeModernizr) {
        bower.dependencies.modernizr = '~2.8.1';
      }

      this.copy('bowerrc', '.bowerrc');
      this.write('bower.json', JSON.stringify(bower, null, 2));
    },

    jshint: function () {
      this.copy('jshintrc', '.jshintrc');
    },

    editorConfig: function () {
      this.copy('editorconfig', '.editorconfig');
    },

    h5bp: function () {
      this.copy('favicon.ico', 'app/favicon.ico');
      this.copy('robots.txt', 'app/robots.txt');
    },

    mainStylesheet: function () {
      var css = 'main';

      if (this.includeSass) {
        css += '.scss';
      } else {
        css += '.css';
      }

      this.copy(css, 'app/styles/' + css);
    },

    writeIndex: function () {
      this.indexFile = this.src.read('index.html');
      this.indexFile = this.engine(this.indexFile, this);

      // wire Bootstrap plugins
      if (this.includeBootstrap) {
        var bs = '../bower_components/';

        if (this.includeSass) {
          bs += 'bootstrap-sass-official/assets/javascripts/bootstrap/';
        } else {
          bs += 'bootstrap/js/';
        }

        this.indexFile = this.appendScripts(this.indexFile, 'scripts/plugins.js', [
          bs + 'affix.js',
          bs + 'alert.js',
          bs + 'dropdown.js',
          bs + 'tooltip.js',
          bs + 'modal.js',
          bs + 'transition.js',
          bs + 'button.js',
          bs + 'popover.js',
          bs + 'carousel.js',
          bs + 'scrollspy.js',
          bs + 'collapse.js',
          bs + 'tab.js'
        ]);
      }

      this.indexFile = this.appendFiles({
        html: this.indexFile,
        fileType: 'js',
        optimizedPath: 'scripts/main.js',
        sourceFileList: ['scripts/main.js']
      });

      this.write('app/index.html', this.indexFile);
    },

    app: function () {
      this.mkdir('app');
      this.mkdir('app/scripts');
      this.mkdir('app/styles');
      this.mkdir('app/images');
      this.mkdir('app/fonts');
      this.copy('main.js', 'app/scripts/main.js');
    }
  },

  install: function () {
    var howToInstall =
      '\nAfter running ' +
      chalk.yellow.bold('npm install & bower install') +
      ', inject your' +
      '\nfront end dependencies by running ' +
      chalk.yellow.bold('gulp wiredep') +
      '.';

    if (this.options['skip-install']) {
      this.log(howToInstall);
      return;
    }

    this.installDependencies({
      skipMessage: this.options['skip-install-message'],
      skipInstall: this.options['skip-install']
    });

    this.on('end', function () {
      var bowerJson = this.dest.readJSON('bower.json');

      // wire Bower packages to .html
      wiredep({
        bowerJson: bowerJson,
        directory: 'bower_components',
        exclude: ['bootstrap-sass', 'bootstrap.js'],
        src: 'app/index.html'
      });

      if (this.includeSass) {
        // wire Bower packages to .scss
        wiredep({
          bowerJson: bowerJson,
          directory: 'bower_components',
          src: 'app/styles/*.scss'
        });
      }

      // ideally we should use composeWith, but we're invoking it here
      // because generator-mocha is changing the working directory
      // https://github.com/yeoman/generator-mocha/issues/28
      this.invoke(this.options['test-framework'], {
        options: {
          'skip-message': this.options['skip-install-message'],
          'skip-install': this.options['skip-install']
        }
      });
    }.bind(this));
  }
});
<|endoftext|>


<commit_before>'use strict';

import React, { Component } from 'react';
import {
	AppRegistry,
	NavigatorIOS,
	BackAndroid,
	StatusBar,
	AppState,
	View
} from 'react-native';
import TimerMixin from 'react-timer-mixin';

// SETUP / UTIL / NAV
var AppSettings = 			require('./AppSettings'),
	general = 				require('./util/general'),
	logger = 				require('./util/logger'),

// VIEWS
	Home = 					require('./views/Home'),
	ShuttleStop = 			require('./views/ShuttleStop'),
	SurfReport = 			require('./views/weather/SurfReport'),
	DiningList = 			require('./views/dining/DiningList'),
	DiningDetail = 			require('./views/dining/DiningDetail'),
	DiningNutrition = 		require('./views/dining/DiningNutrition'),
	NewsDetail = 			require('./views/news/NewsDetail'),
	EventDetail = 			require('./views/events/EventDetail'),
	WebWrapper = 			require('./views/WebWrapper');

import GeoLocationContainer from './containers/geoLocationContainer';

import WelcomeWeekView from './views/welcomeWeek/WelcomeWeekView';
import EventListView from './views/events/EventListView';
import NewsListView from './views/news/NewsListView';
import DiningListView from './views/dining/DiningListView';
import FeedbackView from './views/FeedbackView';

// NAV
import NavigationBarWithRouteMapper from './views/NavigationBarWithRouteMapper';

// REDUX
import { Provider } from 'react-redux';
import configureStore from './store/configureStore';

/**
 * Timeout that allows for pause and resume
**/
function Timer(callback, delay) {
	var timerId, start, remaining = delay;

	this.pause = function() {
		clearTimeout(timerId);
		remaining -= new Date() - start;
	};

	this.resume = function() {
		start = new Date();
		clearTimeout(timerId);
		timerId = setTimeout(callback, remaining);
	};

	this.do = function() {
		clearTimeout(timerId);
		callback();
	}

	this.getID = function() {
		return timerId;
	};

	this.resume();
}
var timers = {};

var nowucsandiego = React.createClass({

	mixins: [TimerMixin],
	store: configureStore(),

	getInitialState() {
		return {
			inHome: true,
		};
	},

	componentWillMount() {
		AppState.addEventListener('change', this.handleAppStateChange);
	},

	componentDidMount() {
		if (general.platformAndroid() || AppSettings.NAVIGATOR_ENABLED) {
			// Listen to route focus changes
			// Should be a better way to do this...
			this.refs.navRef.refs.navRef.navigationContext.addListener('willfocus', (event) => {

				const route = event.data.route;

				// Make sure renders/card refreshes are only happening when in home route
				if (route.id === "Home") {
					this.setState({inHome: true});
					this._resumeTimeout();
				} else {
					this.setState({inHome: false});
					this._pauseTimeout();
				}
			});

			// Listen to back button on Android
			BackAndroid.addEventListener('hardwareBackPress', () => {
				//console.log(util.inspect(this.refs.navRef.refs.navRef.getCurrentRoutes()));
				//var route = this.refs.navRef.refs.navRef.getCurrentRoutes()[0];

				if(this.state.inHome) {
					BackAndroid.exitApp();
					return false;

				} else {
					this.refs.navRef.refs.navRef.pop();
					return true;
				}
			});
		}
		else {
			// Pause/resume timeouts
			this.refs.navRef.navigationContext.addListener('didfocus', (event) => {
				const route = event.data.route;

				// Make sure renders/card refreshes are only happening when in home route
				if (route.id === undefined) { //undefined is foxusing "Home"... weird I know
					this.setState({inHome: true});
					this._resumeTimeout();
				} else {
					this.setState({inHome: false});
					this._pauseTimeout();
				}
			});

			// Make all back buttons use text "Back"
			this.refs.navRef.navigationContext.addListener('willfocus', (event) => {
				const route = event.data.route;
				route.backButtonTitle = "Back";
			});
		}
	},

	componentWillUnmount() {
		AppState.removeEventListener('change', this.handleAppStateChange);
		this._pauseTimeout();
	},

	newTimeout: function(key, callback, delay) {
		timers[key] = (new Timer(callback, delay));
	},

	_pauseTimeout: function() {
		for (var key in timers) {
			timers[key].pause();
		}
	},

	_resumeTimeout: function() {
		for (var key in timers) {
			timers[key].resume();
		}
	},

	doTimeout: function() {
		for (var key in timers) {
			timers[key].do();
		}
	},

	render: function() {

		if (general.platformIOS()) {
			StatusBar.setBarStyle('light-content');
		}

		if (general.platformAndroid() || AppSettings.NAVIGATOR_ENABLED) {
			return (
				<Provider store={this.store}>
					<View style={{ flex: 1 }}>
						<GeoLocationContainer />
						<NavigationBarWithRouteMapper
							ref="navRef"
							route={{ id: 'Home', name: 'Home', title: 'now@ucsandiego' }}
							renderScene={this.renderScene}
						/>
					</View>
				</Provider>
			);
		} else {
			return (
				<Provider store={this.store}>
					<View style={{ flex: 1 }}>
						<GeoLocationContainer />
						<NavigatorIOS
							initialRoute={{
								component: Home,
								title: AppSettings.APP_NAME,
								passProps: {
									isSimulator: this.props.isSimulator,
									new_timeout: this.newTimeout,
									do_timeout: this.doTimeout
								},
								backButtonTitle: 'Back'
							}}
							style={{ flex: 1 }}
							tintColor='#FFFFFF'
							barTintColor='#006C92'
							titleTextColor='#FFFFFF'
							navigationBarHidden={false}
							translucent={true}
							ref="navRef"
						/>
					</View>
				</Provider>
			);
		}
	},

	renderScene: function(route, navigator, index, navState) {

		switch (route.id) {
			case 'Home': 				return (<Home route={route} navigator={navigator} new_timeout={this.newTimeout} do_timeout={this.doTimeout}/>);
			case 'ShuttleStop': 		return (<ShuttleStop route={route} navigator={navigator} />);
			case 'SurfReport': 			return (<SurfReport route={route} navigator={navigator} />);
			case 'DiningListView': 		return (<DiningListView route={route} navigator={navigator} />);
			case 'DiningDetail': 		return (<DiningDetail route={route} navigator={navigator} />);
			case 'DiningNutrition': 	return (<DiningNutrition route={route} navigator={navigator} />);
			case 'NewsDetail': 			return (<NewsDetail route={route} navigator={navigator} />);
			case 'EventDetail': 		return (<EventDetail route={route} navigator={navigator} />);
			case 'WebWrapper': 			return (<WebWrapper route={route} navigator={navigator} />);
			case 'WelcomeWeekView': 	return (<WelcomeWeekView route={route} navigator={navigator} />);
			case 'EventListView': 		return (<EventListView route={route} navigator={navigator} />);
			case 'NewsListView': 		return (<NewsListView route={route} navigator={navigator} />);
			case 'FeedbackView': 		return (<FeedbackView route={route} navigator={navigator} />);
			default: 					return (<Home route={route} navigator={navigator} new_timeout={this.newTimeout} do_timeout={this.doTimeout}/>);
		}
	},

	handleAppStateChange(currentAppState) {
		if (currentAppState === 'active') {
			if(this.state.inHome) {
				this._resumeTimeout();
			}
		}
		else if(currentAppState === 'background') {
			this._pauseTimeout();
		}
	},
});

module.exports = nowucsandiego;
<commit_msg>Not sure why you have all this timer code<commit_after>'use strict';

import React, { Component } from 'react';
import {
	AppRegistry,
	NavigatorIOS,
	BackAndroid,
	StatusBar,
	AppState,
	View
} from 'react-native';

// SETUP / UTIL / NAV
var AppSettings = 			require('./AppSettings'),
	general = 				require('./util/general'),
	logger = 				require('./util/logger'),

// VIEWS
	Home = 					require('./views/Home'),
	ShuttleStop = 			require('./views/ShuttleStop'),
	SurfReport = 			require('./views/weather/SurfReport'),
	DiningList = 			require('./views/dining/DiningList'),
	DiningDetail = 			require('./views/dining/DiningDetail'),
	DiningNutrition = 		require('./views/dining/DiningNutrition'),
	NewsDetail = 			require('./views/news/NewsDetail'),
	EventDetail = 			require('./views/events/EventDetail'),
	WebWrapper = 			require('./views/WebWrapper');

import GeoLocationContainer from './containers/geoLocationContainer';

import WelcomeWeekView from './views/welcomeWeek/WelcomeWeekView';
import EventListView from './views/events/EventListView';
import NewsListView from './views/news/NewsListView';
import DiningListView from './views/dining/DiningListView';
import FeedbackView from './views/FeedbackView';

// NAV
import NavigationBarWithRouteMapper from './views/NavigationBarWithRouteMapper';

// REDUX
import { Provider } from 'react-redux';
import configureStore from './store/configureStore';

var nowucsandiego = React.createClass({

	store: configureStore(),

	getInitialState() {
		return {
			inHome: true,
		};
	},

	componentWillMount() {
		AppState.addEventListener('change', this.handleAppStateChange);
	},

	componentDidMount() {
		if (general.platformAndroid() || AppSettings.NAVIGATOR_ENABLED) {
			// Listen to route focus changes
			// Should be a better way to do this...
			this.refs.navRef.refs.navRef.navigationContext.addListener('willfocus', (event) => {

				const route = event.data.route;

				// Make sure renders/card refreshes are only happening when in home route
				if (route.id === "Home") {
					this.setState({inHome: true});
					this._resumeTimeout();
				} else {
					this.setState({inHome: false});
					this._pauseTimeout();
				}
			});

			// Listen to back button on Android
			BackAndroid.addEventListener('hardwareBackPress', () => {
				//console.log(util.inspect(this.refs.navRef.refs.navRef.getCurrentRoutes()));
				//var route = this.refs.navRef.refs.navRef.getCurrentRoutes()[0];

				if(this.state.inHome) {
					BackAndroid.exitApp();
					return false;

				} else {
					this.refs.navRef.refs.navRef.pop();
					return true;
				}
			});
		}
		else {
			// Pause/resume timeouts
			this.refs.navRef.navigationContext.addListener('didfocus', (event) => {
				const route = event.data.route;

				// Make sure renders/card refreshes are only happening when in home route
				if (route.id === undefined) { //undefined is foxusing "Home"... weird I know
					this.setState({inHome: true});
				} else {
					this.setState({inHome: false});
				}
			});

			// Make all back buttons use text "Back"
			this.refs.navRef.navigationContext.addListener('willfocus', (event) => {
				const route = event.data.route;
				route.backButtonTitle = "Back";
			});
		}
	},

	componentWillUnmount() {
		AppState.removeEventListener('change', this.handleAppStateChange);
	},

	render: function() {

		if (general.platformIOS()) {
			StatusBar.setBarStyle('light-content');
		}

		if (general.platformAndroid() || AppSettings.NAVIGATOR_ENABLED) {
			return (
				<Provider store={this.store}>
					<View style={{ flex: 1 }}>
						<GeoLocationContainer />
						<NavigationBarWithRouteMapper
							ref="navRef"
							route={{ id: 'Home', name: 'Home', title: 'now@ucsandiego' }}
							renderScene={this.renderScene}
						/>
					</View>
				</Provider>
			);
		} else {
			return (
				<Provider store={this.store}>
					<View style={{ flex: 1 }}>
						<GeoLocationContainer />
						<NavigatorIOS
							initialRoute={{
								component: Home,
								title: AppSettings.APP_NAME,
								passProps: {
									isSimulator: this.props.isSimulator
								},
								backButtonTitle: 'Back'
							}}
							style={{ flex: 1 }}
							tintColor='#FFFFFF'
							barTintColor='#006C92'
							titleTextColor='#FFFFFF'
							navigationBarHidden={false}
							translucent={true}
							ref="navRef"
						/>
					</View>
				</Provider>
			);
		}
	},

	renderScene: function(route, navigator, index, navState) {

		switch (route.id) {
			case 'Home': 				return (<Home route={route} navigator={navigator}/>);
			case 'ShuttleStop': 		return (<ShuttleStop route={route} navigator={navigator} />);
			case 'SurfReport': 			return (<SurfReport route={route} navigator={navigator} />);
			case 'DiningListView': 		return (<DiningListView route={route} navigator={navigator} />);
			case 'DiningDetail': 		return (<DiningDetail route={route} navigator={navigator} />);
			case 'DiningNutrition': 	return (<DiningNutrition route={route} navigator={navigator} />);
			case 'NewsDetail': 			return (<NewsDetail route={route} navigator={navigator} />);
			case 'EventDetail': 		return (<EventDetail route={route} navigator={navigator} />);
			case 'WebWrapper': 			return (<WebWrapper route={route} navigator={navigator} />);
			case 'WelcomeWeekView': 	return (<WelcomeWeekView route={route} navigator={navigator} />);
			case 'EventListView': 		return (<EventListView route={route} navigator={navigator} />);
			case 'NewsListView': 		return (<NewsListView route={route} navigator={navigator} />);
			case 'FeedbackView': 		return (<FeedbackView route={route} navigator={navigator} />);
			default: 					return (<Home route={route} navigator={navigator} />);
		}
	}
});

module.exports = nowucsandiego;
<|endoftext|>


<commit_before>#! /usr/bin/env node
/* eslint-disable no-console */
const args = require('args-parser')(process.argv);
const { default: Screenshot } = require('../');

const isUrl = url => /[^\w]/g.test(url);
const urls = Object.keys(args).filter(key => isUrl(key));
const {
  width = 1366,
  height,
  type = 'png',
  quality = 100,
  dpr: deviceScaleFactor = 2,
  emulate: emulateConfig,
  waitUntil = 'networkidle',
  disableJS = false,
  sleep,
} = args;

async function takeAllScreenshot(screenshot) {
  let url = urls.shift();
  try {
    if (typeof url === 'string') {
      if (url.indexOf('://') === -1) { url = `http://${url}`; }
      const path = `${url}.${type}`.replace(/http[^/]+\/\//, '').replace(/\//g, '-');
      await screenshot.init({
        waitFor: sleep,
        disableJS,
        waitUntil,
        emulateConfig,
        screenshotConfig: Object.assign(
          { type, path },
          type === 'jpeg' ? { quality } : null, // only jpeg have quality
          height ? null : { fullPage: true }, // when height is not specified, using fullPage
        ),
      });

      console.log(`🤖  start take screenshot with ${url}`.data);
      await screenshot.takeScreenshot(url);
      console.log(`🎉  save ${url} with ${path.info}`.data);
    }
  } catch (err) {
    console.error(`😿  cannot take screenshot with ${url}`.error);
    console.error(err);
  }
  if (urls.length > 0) await takeAllScreenshot(screenshot);
}

(async () => {
  const screenshot = new Screenshot({
    waitUntil: 'networkidle',
    waitForFunction: () => {
      window.imageList = window.imageList || Array.from(document.getElementsByTagName('img'));

      return window.imageList.length <= window.imageList.reduce((loaded, imageElm) => (
        imageElm.complete ? loaded + 1 : loaded
      ), 0);
    },
    viewportConfig: { width, height: height || 768, deviceScaleFactor },
  });
  await takeAllScreenshot(screenshot);
  process.exit();
})();
<commit_msg>CLI support named streenshot<commit_after>#! /usr/bin/env node
/* eslint-disable no-console */
const args = require('args-parser')(process.argv);
const { default: Screenshot } = require('../');

const isUrl = url => /[^\w]/g.test(url);
const urls = Object.keys(args).filter(key => isUrl(key));
const {
  width = 1366,
  height,
  type = 'png',
  quality = 100,
  dpr: deviceScaleFactor = 2,
  emulate: emulateConfig,
  waitUntil = 'networkidle',
  disableJS = false,
  sleep,
  named,
} = args;

function fileName(url) {
  let name = `${url}.${type}`.replace(/http[^/]+\/\//, '').replace(/\//g, '_');

  if (!fileName.count) fileName.count = 0;
  if (named && named !== true) name = `${named}${fileName.count > 0 ? `_${fileName.count}` : ''}.${type}`;

  fileName.count += 1;
  return name;
}

async function takeAllScreenshot(screenshot) {
  let url = urls.shift();
  try {
    if (typeof url === 'string') {
      if (url.indexOf('://') === -1) { url = `http://${url}`; }
      const path = fileName(url);
      await screenshot.init({
        waitFor: sleep,
        disableJS,
        waitUntil,
        emulateConfig,
        screenshotConfig: Object.assign(
          { type, path },
          type === 'jpeg' ? { quality } : null, // only jpeg have quality
          height ? null : { fullPage: true }, // when height is not specified, using fullPage
        ),
      });

      console.log(`🤖  start take screenshot with ${url}`.data);
      await screenshot.takeScreenshot(url);
      console.log(`🎉  save ${url} with ${path.info}`.data);
    }
  } catch (err) {
    console.error(`😿  cannot take screenshot with ${url}`.error);
    console.error(err);
  }
  if (urls.length > 0) await takeAllScreenshot(screenshot);
}

(async () => {
  const screenshot = new Screenshot({
    waitUntil: 'networkidle',
    waitForFunction: () => {
      window.imageList = window.imageList || Array.from(document.getElementsByTagName('img'));

      return window.imageList.length <= window.imageList.reduce((loaded, imageElm) => (
        imageElm.complete ? loaded + 1 : loaded
      ), 0);
    },
    viewportConfig: { width, height: height || 768, deviceScaleFactor },
  });
  await takeAllScreenshot(screenshot);
  process.exit();
})();
<|endoftext|>


<commit_before>'use strict';

var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var merge = function (obj, sources) {
    if (!(sources instanceof Array)) {
        sources = [sources];
    }

    sources.forEach(function (source) {
        var key;
        var deeperKey;
        for (key in source) {
            if (source.hasOwnProperty(key)) {
                for (deeperKey in source[key]) {
                    if (source[key].hasOwnProperty(deeperKey)) {
                        obj[key][deeperKey] = source[key][deeperKey];
                    }
                }
            }
        }
    });
}

var WdjAppGenerator = module.exports = function WdjAppGenerator (args, options, config) {
    this.projectName = args[0];

    yeoman.generators.Base.apply(this, arguments);

    this.on('end', function () {
        this.installDependencies({
            skipInstall: options['skip-install'],
            skipMessage: options['skip-install-message']
        });
    });

    this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(WdjAppGenerator, yeoman.generators.Base);

WdjAppGenerator.prototype.askFor = function askFor() {
    var cb = this.async();

    if (!this.options['skip-welcome-message']) {
        console.log(this.yeoman);
    }

    var prompts = [{
        type : 'list',
        name : 'projectType',
        message : 'Which kind of project are u scaffolding? ',
        choices : [{
            name : 'Browser-based project. ',
            value : 'browser'
        }, {
            name : 'Node.js project. ',
            value : 'node'
        }, {
            name : 'Sails project. ',
            value : 'sails'
        }]
    }];

    var promptsSubType = [{
        type : 'list',
        name : 'projectSubType',
        message : 'It\'s a ...',
        choices : [{
            name : 'Typical browser-based project. ',
            value : 'typical'
        }, {
            name : 'Chrome extension project. ',
            value : 'crx'
        }, {
            name : 'Polymer project. ',
            value : 'polymer'
        }]
    }];

    this.prompt(prompts, function (props) {
        this.projectType = props.projectType;

        if (props.projectType === 'browser') {
            this.prompt(promptsSubType, function (props) {
                this.projectSubType = props.projectSubType;
                cb();
            }.bind(this));
        } else {
            cb();
        }
    }.bind(this));
};

WdjAppGenerator.prototype.app = function app() {
    var packageJson = this.src.readJSON('_package.json');
    var bowerJson = this.src.readJSON('_bower.json');

    switch (this.projectType) {
    case 'browser':
        var packageJsonBrowserBase = this.src.readJSON('browser/_package.json');

        this.mkdir('app');

        // Make bower components dir
        this.mkdir('app/components');

        // Make images dir
        this.mkdir('app/images');

        // Make JavaScript dir
        this.mkdir('app/javascripts');

        // Make compass dir
        this.mkdir('app/compass');
        this.mkdir('app/compass/sass');
        this.mkdir('app/compass/images');

        // Make test dir
        this.mkdir('test/specs');

        // Copy public resources
        this.copy('bowerrc', '.bowerrc');

        this.copy('browser/_main.scss', 'app/compass/sass/main.scss');
        this.copy('browser/_main.js', 'app/javascripts/main.js');
        this.copy('browser/_karma.conf.js', 'test/karma.conf.js');
        this.copy('browser/_test-main.js', 'test/test-main.js');
        this.copy('browser/_Gruntfile.js', 'Gruntfile.js');
        this.directory('browser/grunt', 'grunt');

        switch (this.projectSubType) {
        case 'typical':
            // Genertate `package.json`
            var packageJsonBrowserTypical = this.src.readJSON('browser/typical/_package.json');
            merge(packageJson, [packageJsonBrowserBase, packageJsonBrowserTypical]);

            this.copy('browser/typical/_index.html', 'app/index.html');
            this.directory('browser/typical/grunt', 'grunt');
            break;
        case 'crx':
            // Genertate `package.json`
            var packageJsonCrx = this.src.readJSON('browser/crx/_package.json');
            merge(packageJson, [packageJsonBrowserBase, packageJsonCrx]);

            this.copy('browser/crx/_background.html', 'app/background.html');
            this.copy('browser/crx/_manifest.json', 'app/manifest.json');
            this.mkdir('app/dev');
            this.copy('browser/crx/_reload.js', 'app/dev/reload.js');

            this.directory('browser/crx/grunt', 'grunt');
            break;
        case 'polymer':
            // Genertate `package.json`
            var packageJsonPolymer = this.src.readJSON('browser/polymer/_package.json');
            merge(packageJson, [packageJsonBrowserBase, packageJsonPolymer]);

            // Generate `bower.json`
            var bowerJsonPolymer = this.src.readJSON('browser/polymer/_bower.json');
            merge(bowerJson, [bowerJsonPolymer]);

            this.copy('browser/polymer/_index.html', 'app/index.html');
            this.mkdir('app/elements');
            this.copy('browser/polymer/elements/_elements.html', 'app/elements/elements.html');

            this.directory('browser/typical/grunt', 'grunt');
            this.directory('browser/polymer/grunt', 'grunt');
            break;
        }
        break;
    case 'node':
        // Genertate `package.json`
        var packageJsonNode = this.src.readJSON('_package_node.json');
        merge(packageJson, packageJsonNode);

        this.copy('_package_node.json', 'package.json');
        this.copy('_Gruntfile_node.js', 'Gruntfile.js');
        break;
    case 'sails':
        this.copy('_bower.json', 'bower.json');
        this.directory('sails', './');
        break;
    }

    this.dest.write('bower.json', JSON.stringify(bowerJson, null, 4));
    this.dest.write('package.json', JSON.stringify(packageJson, null, 4));
};

WdjAppGenerator.prototype.projectfiles = function projectfiles() {
    this.copy('_README.md', 'README.md');
    this.copy('gitignore', '.gitignore');
    this.copy('_travis.yml', '.travis.yml');
    this.copy('editorconfig', '.editorconfig');
    this.copy('jshintrc', '.jshintrc');
};
<commit_msg>fix: Improve robust<commit_after>'use strict';

var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var merge = function (obj, sources) {
    if (!(sources instanceof Array)) {
        sources = [sources];
    }

    sources.forEach(function (source) {
        var key;
        var deeperKey;
        for (key in source) {
            if (source.hasOwnProperty(key)) {
                for (deeperKey in source[key]) {
                    if (source[key].hasOwnProperty(deeperKey)) {
                        obj[key] = obj[key] || {};
                        obj[key][deeperKey] = source[key][deeperKey];
                    }
                }
            }
        }
    });
}

var WdjAppGenerator = module.exports = function WdjAppGenerator (args, options, config) {
    this.projectName = args[0];

    yeoman.generators.Base.apply(this, arguments);

    this.on('end', function () {
        this.installDependencies({
            skipInstall: options['skip-install'],
            skipMessage: options['skip-install-message']
        });
    });

    this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(WdjAppGenerator, yeoman.generators.Base);

WdjAppGenerator.prototype.askFor = function askFor() {
    var cb = this.async();

    if (!this.options['skip-welcome-message']) {
        console.log(this.yeoman);
    }

    var prompts = [{
        type : 'list',
        name : 'projectType',
        message : 'Which kind of project are u scaffolding? ',
        choices : [{
            name : 'Browser-based project. ',
            value : 'browser'
        }, {
            name : 'Node.js project. ',
            value : 'node'
        }, {
            name : 'Sails project. ',
            value : 'sails'
        }]
    }];

    var promptsSubType = [{
        type : 'list',
        name : 'projectSubType',
        message : 'It\'s a ...',
        choices : [{
            name : 'Typical browser-based project. ',
            value : 'typical'
        }, {
            name : 'Chrome extension project. ',
            value : 'crx'
        }, {
            name : 'Polymer project. ',
            value : 'polymer'
        }]
    }];

    this.prompt(prompts, function (props) {
        this.projectType = props.projectType;

        if (props.projectType === 'browser') {
            this.prompt(promptsSubType, function (props) {
                this.projectSubType = props.projectSubType;
                cb();
            }.bind(this));
        } else {
            cb();
        }
    }.bind(this));
};

WdjAppGenerator.prototype.app = function app() {
    var packageJson = this.src.readJSON('_package.json');
    var bowerJson = this.src.readJSON('_bower.json');

    switch (this.projectType) {
    case 'browser':
        var packageJsonBrowserBase = this.src.readJSON('browser/_package.json');

        this.mkdir('app');

        // Make bower components dir
        this.mkdir('app/components');

        // Make images dir
        this.mkdir('app/images');

        // Make JavaScript dir
        this.mkdir('app/javascripts');

        // Make compass dir
        this.mkdir('app/compass');
        this.mkdir('app/compass/sass');
        this.mkdir('app/compass/images');

        // Make test dir
        this.mkdir('test/specs');

        // Copy public resources
        this.copy('bowerrc', '.bowerrc');

        this.copy('browser/_main.scss', 'app/compass/sass/main.scss');
        this.copy('browser/_main.js', 'app/javascripts/main.js');
        this.copy('browser/_karma.conf.js', 'test/karma.conf.js');
        this.copy('browser/_test-main.js', 'test/test-main.js');
        this.copy('browser/_Gruntfile.js', 'Gruntfile.js');
        this.directory('browser/grunt', 'grunt');

        switch (this.projectSubType) {
        case 'typical':
            // Genertate `package.json`
            var packageJsonBrowserTypical = this.src.readJSON('browser/typical/_package.json');
            merge(packageJson, [packageJsonBrowserBase, packageJsonBrowserTypical]);

            this.copy('browser/typical/_index.html', 'app/index.html');
            this.directory('browser/typical/grunt', 'grunt');
            break;
        case 'crx':
            // Genertate `package.json`
            var packageJsonCrx = this.src.readJSON('browser/crx/_package.json');
            merge(packageJson, [packageJsonBrowserBase, packageJsonCrx]);

            this.copy('browser/crx/_background.html', 'app/background.html');
            this.copy('browser/crx/_manifest.json', 'app/manifest.json');
            this.mkdir('app/dev');
            this.copy('browser/crx/_reload.js', 'app/dev/reload.js');

            this.directory('browser/crx/grunt', 'grunt');
            break;
        case 'polymer':
            // Genertate `package.json`
            var packageJsonPolymer = this.src.readJSON('browser/polymer/_package.json');
            merge(packageJson, [packageJsonBrowserBase, packageJsonPolymer]);

            // Generate `bower.json`
            var bowerJsonPolymer = this.src.readJSON('browser/polymer/_bower.json');
            merge(bowerJson, [bowerJsonPolymer]);

            this.copy('browser/polymer/_index.html', 'app/index.html');
            this.mkdir('app/elements');
            this.copy('browser/polymer/elements/_elements.html', 'app/elements/elements.html');

            this.directory('browser/typical/grunt', 'grunt');
            this.directory('browser/polymer/grunt', 'grunt');
            break;
        }
        break;
    case 'node':
        // Genertate `package.json`
        var packageJsonNode = this.src.readJSON('_package_node.json');
        merge(packageJson, packageJsonNode);

        this.copy('_package_node.json', 'package.json');
        this.copy('_Gruntfile_node.js', 'Gruntfile.js');
        break;
    case 'sails':
        this.copy('_bower.json', 'bower.json');
        this.directory('sails', './');
        break;
    }

    this.dest.write('bower.json', JSON.stringify(bowerJson, null, 4));
    this.dest.write('package.json', JSON.stringify(packageJson, null, 4));
};

WdjAppGenerator.prototype.projectfiles = function projectfiles() {
    this.copy('_README.md', 'README.md');
    this.copy('gitignore', '.gitignore');
    this.copy('_travis.yml', '.travis.yml');
    this.copy('editorconfig', '.editorconfig');
    this.copy('jshintrc', '.jshintrc');
};
<|endoftext|>


<commit_before>/*
 * editor.js
 */

(function (editor, store, runner) {

    var EMPTY_SCRIPT,
        currentScript = 0,
        lastEditorTouchTS = 0,
        _editor,
        $editor,
        $hidden,
        $select,
        $playBtn,
        $saveBtn,
        $trashBtn,
        $githubBtn,
        $star,
        toWhite = Zanimo.transitionf("color", "#F0F1F3", 100),
        toGreen = Zanimo.transitionf("color", "green", 100),
        isMobile = /WebKit.*Mobile.*|Android/.test(navigator.userAgent),
        codeMirror = CodeMirror || {};

    if (isMobile) {
        var cm = { el : null };
        codeMirror = {};
        codeMirror.fromTextArea = function (el, options) {
            cm.el = el; return cm;
        };
        cm.getValue = function () { return cm.el.value; };
        cm.setValue = function (code) { cm.el.value = code; };
    }

    editor.init = function () {
        $hidden = $("#hidden-a");
        $editor = $("article.editor");
        $select = $("select", $editor);
        $playBtn = $("button.icon-play", $editor);
        $saveBtn = $("button.icon-save", $editor);
        $trashBtn = $("button.icon-trash", $editor);
        $githubBtn = $("button.icon-github-alt", $editor);
        $star = $(".chip span");

        _editor = codeMirror.fromTextArea($("textarea", $editor), {
            lineNumbers: true,
            matchBrackets: true,
            indentUnit: 4,
            extraKeys: { "Enter" : "newlineAndIndentContinueComment" }
        });

        EMPTY_SCRIPT = $("#empty-script-help").innerHTML;

        currentScript = store.head();
        editor.populateSelect(currentScript, store);
        editor.loadExample(currentScript, store);

        if(isTouchable) $editor.addEventListener("touchstart", editor.onTouchStart);
        $playBtn.addEventListener(isTouchable ? "touchstart" : "click", editor.onPlay);
        $saveBtn.addEventListener(isTouchable ? "touchstart" : "click", editor.onSave);
        $trashBtn.addEventListener(isTouchable ? "touchstart" : "click", editor.onTrash);
        $githubBtn.addEventListener(isTouchable ? "touchstart" : "click", editor.onGithub);
        $select.addEventListener("change", editor.onSelect);
        window.document.addEventListener("keydown", editor.onKeydown);
    };

    editor.onKeydown = function (evt) {
        if((evt.metaKey || evt.ctrlKey) && evt.keyCode === 83) {
            evt.preventDefault();
            editor.onSave();
        }
        if((evt.metaKey || evt.ctrlKey) && evt.keyCode === 69) {
            evt.preventDefault();
            editor.onPlay();
        }
    }

    editor.onTouchStart = function (evt) {
        var t = (new Date()).getTime();
        if((t-lastEditorTouchTS) < 400) $hidden.focus();
        lastEditorTouchTS = t;
    };

    editor.onPlay = function (evt) {
        try {
            $hidden.focus();
            runner.run(_editor.getValue());
        } catch(err) {
            alert(err);
        }
    };

    editor.onSave = function (evt) {
        $hidden.focus();
        if(!store.save($select.value, _editor.getValue())) {
            alert("Can't overwrite example script!");
        } else {
            Zanimo($star)
                .then(toGreen)
                .then(toWhite)
                .then(toGreen)
                .then(toWhite)
                .then(toGreen)
                .then(toWhite);
        }
    };

    editor.onTrash = function (evt) {
        $hidden.focus();
        if (store.isDefaultExample($select.value)) {
            alert("Can't delete example script!");
            return;
        }
        if(confirm("Delete " + $select.value + " ?")) {
            store.trash($select.value);
            var head = store.head();
            if(currentScript === $select.value) currentScript = head;
            editor.populateSelect(head, store);
            editor.loadExample(head, store);
        }
    };

    editor.onGithub = function (evt) {
        $hidden.focus();
        if(confirm("Visit on Github?")) location = "http://github.com/peutetre/Zanimo";
    };

    editor.onSelect = function (evt) {
        $hidden.focus();

        if(evt.target.value === "New") {
            var name = window.prompt("Script name:", "my-test"),
                trimedName = "";
            if (name && name.length > 0 && name.trim() !== "New") {
                trimedName = name.trim();
                if (store.save(trimedName, EMPTY_SCRIPT)) {
                    _editor.setValue(EMPTY_SCRIPT);
                    editor.populateSelect(trimedName, store);
                    $select.value = trimedName;
                    currentScript = trimedName;
                }
                else {
                    $select.value = currentScript;
                    alert("Can't overwrite example script!");
                    setTimeout(function () {
                        $select.value = currentScript;
                    },10);
                }
            }
            else if (name == null) {
                $select.value = currentScript;
            }
            else {
                $select.value = currentScript;
                alert("Script name is invalid!");
                setTimeout(function () {
                    $select.value = currentScript;
                },10);
            }
        } else {
            editor.loadExample(evt.target.value, store);
            currentScript = evt.target.value;
        }
    };

    editor.populateSelect = function (name) {
        var items = store.getList(),
            exampleScripts = items.filter(function (ex) {
                return store.isDefaultExample(ex);
            }),
            userScripts = items.filter(function (ex) {
                return !store.isDefaultExample(ex);
            }),
            createOption = function (val, container) {
                var op = DOM("option");
                op.innerHTML = val;
                op.value = val;
                container.appendChild(op);
                return op;
            },
            optgroupCommands = DOM("optgroup"),
            optgroupExamples = DOM("optgroup"),
            optgroupUser = DOM("optgroup");

        $select.innerHTML = "";
        optgroupCommands.label = "Commands";
        optgroupExamples.label = "Examples";
        optgroupUser.label = "Scripts";
        $select.appendChild(optgroupCommands);
        createOption("New", $select);
        $select.appendChild(optgroupExamples);
        exampleScripts.forEach(function (ex) {
            var op = createOption(ex, $select);
            if (ex == name) op.selected = "selected";
        });
        $select.appendChild(optgroupUser);
        userScripts.forEach(function (script) {
            var op = createOption(script, $select);
            if (script == name) op.selected = "selected";
        });
    };

    editor.loadExample = function (name) { _editor.setValue(store.get(name)); };

}(window.Editor = {}, window.Store, window.Runner));
<commit_msg>[editor] open github on new tab<commit_after>/*
 * editor.js
 */

(function (editor, store, runner) {

    var EMPTY_SCRIPT,
        currentScript = 0,
        lastEditorTouchTS = 0,
        _editor,
        $editor,
        $hidden,
        $select,
        $playBtn,
        $saveBtn,
        $trashBtn,
        $githubBtn,
        $star,
        toWhite = Zanimo.transitionf("color", "#F0F1F3", 100),
        toGreen = Zanimo.transitionf("color", "green", 100),
        isMobile = /WebKit.*Mobile.*|Android/.test(navigator.userAgent),
        codeMirror = CodeMirror || {};

    if (isMobile) {
        var cm = { el : null };
        codeMirror = {};
        codeMirror.fromTextArea = function (el, options) {
            cm.el = el; return cm;
        };
        cm.getValue = function () { return cm.el.value; };
        cm.setValue = function (code) { cm.el.value = code; };
    }

    editor.init = function () {
        $hidden = $("#hidden-a");
        $editor = $("article.editor");
        $select = $("select", $editor);
        $playBtn = $("button.icon-play", $editor);
        $saveBtn = $("button.icon-save", $editor);
        $trashBtn = $("button.icon-trash", $editor);
        $githubBtn = $("button.icon-github-alt", $editor);
        $star = $(".chip span");

        _editor = codeMirror.fromTextArea($("textarea", $editor), {
            lineNumbers: true,
            matchBrackets: true,
            indentUnit: 4,
            extraKeys: { "Enter" : "newlineAndIndentContinueComment" }
        });

        EMPTY_SCRIPT = $("#empty-script-help").innerHTML;

        currentScript = store.head();
        editor.populateSelect(currentScript, store);
        editor.loadExample(currentScript, store);

        if(isTouchable) $editor.addEventListener("touchstart", editor.onTouchStart);
        $playBtn.addEventListener(isTouchable ? "touchstart" : "click", editor.onPlay);
        $saveBtn.addEventListener(isTouchable ? "touchstart" : "click", editor.onSave);
        $trashBtn.addEventListener(isTouchable ? "touchstart" : "click", editor.onTrash);
        $githubBtn.addEventListener(isTouchable ? "touchstart" : "click", editor.onGithub);
        $select.addEventListener("change", editor.onSelect);
        window.document.addEventListener("keydown", editor.onKeydown);
    };

    editor.onKeydown = function (evt) {
        if((evt.metaKey || evt.ctrlKey) && evt.keyCode === 83) {
            evt.preventDefault();
            editor.onSave();
        }
        if((evt.metaKey || evt.ctrlKey) && evt.keyCode === 69) {
            evt.preventDefault();
            editor.onPlay();
        }
    }

    editor.onTouchStart = function (evt) {
        var t = (new Date()).getTime();
        if((t-lastEditorTouchTS) < 400) $hidden.focus();
        lastEditorTouchTS = t;
    };

    editor.onPlay = function (evt) {
        try {
            $hidden.focus();
            runner.run(_editor.getValue());
        } catch(err) {
            alert(err);
        }
    };

    editor.onSave = function (evt) {
        $hidden.focus();
        if(!store.save($select.value, _editor.getValue())) {
            alert("Can't overwrite example script!");
        } else {
            Zanimo($star)
                .then(toGreen)
                .then(toWhite)
                .then(toGreen)
                .then(toWhite)
                .then(toGreen)
                .then(toWhite);
        }
    };

    editor.onTrash = function (evt) {
        $hidden.focus();
        if (store.isDefaultExample($select.value)) {
            alert("Can't delete example script!");
            return;
        }
        if(confirm("Delete " + $select.value + " ?")) {
            store.trash($select.value);
            var head = store.head();
            if(currentScript === $select.value) currentScript = head;
            editor.populateSelect(head, store);
            editor.loadExample(head, store);
        }
    };

    editor.onGithub = function (evt) {
        $hidden.focus();
        if(confirm("Visit on Github?")) window.open("http://github.com/peutetre/Zanimo");
    };

    editor.onSelect = function (evt) {
        $hidden.focus();

        if(evt.target.value === "New") {
            var name = window.prompt("Script name:", "my-test"),
                trimedName = "";
            if (name && name.length > 0 && name.trim() !== "New") {
                trimedName = name.trim();
                if (store.save(trimedName, EMPTY_SCRIPT)) {
                    _editor.setValue(EMPTY_SCRIPT);
                    editor.populateSelect(trimedName, store);
                    $select.value = trimedName;
                    currentScript = trimedName;
                }
                else {
                    $select.value = currentScript;
                    alert("Can't overwrite example script!");
                    setTimeout(function () {
                        $select.value = currentScript;
                    },10);
                }
            }
            else if (name == null) {
                $select.value = currentScript;
            }
            else {
                $select.value = currentScript;
                alert("Script name is invalid!");
                setTimeout(function () {
                    $select.value = currentScript;
                },10);
            }
        } else {
            editor.loadExample(evt.target.value, store);
            currentScript = evt.target.value;
        }
    };

    editor.populateSelect = function (name) {
        var items = store.getList(),
            exampleScripts = items.filter(function (ex) {
                return store.isDefaultExample(ex);
            }),
            userScripts = items.filter(function (ex) {
                return !store.isDefaultExample(ex);
            }),
            createOption = function (val, container) {
                var op = DOM("option");
                op.innerHTML = val;
                op.value = val;
                container.appendChild(op);
                return op;
            },
            optgroupCommands = DOM("optgroup"),
            optgroupExamples = DOM("optgroup"),
            optgroupUser = DOM("optgroup");

        $select.innerHTML = "";
        optgroupCommands.label = "Commands";
        optgroupExamples.label = "Examples";
        optgroupUser.label = "Scripts";
        $select.appendChild(optgroupCommands);
        createOption("New", $select);
        $select.appendChild(optgroupExamples);
        exampleScripts.forEach(function (ex) {
            var op = createOption(ex, $select);
            if (ex == name) op.selected = "selected";
        });
        $select.appendChild(optgroupUser);
        userScripts.forEach(function (script) {
            var op = createOption(script, $select);
            if (script == name) op.selected = "selected";
        });
    };

    editor.loadExample = function (name) { _editor.setValue(store.get(name)); };

}(window.Editor = {}, window.Store, window.Runner));
<|endoftext|>


<commit_before>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var MagentoGenerator = module.exports = function MagentoGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(MagentoGenerator, yeoman.generators.Base);

MagentoGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // have Yeoman greet the user.
  console.log(this.yeoman);

  var prompts = [{
    name: 'magentoVersion',
    message: 'What version do you want to use? (e.g. 1.7.0.2)',
    default: '1.7.0.2'
  }, {
    type: 'confirm',
    name: 'includeUnitTest',
    message: 'Do you want to include EcomDevs PHPUnit module?',
    default: true
  }];

  this.prompt(prompts, function (props) {
    this.magentoVersion = props.magentoVersion;
    this.includeUnitTest = props.includeUnitTest;

    cb();
  }.bind(this));
};

MagentoGenerator.prototype.app = function app() {
  var cb = this.async(),
    self = this;

  this.tarball('http://www.magentocommerce.com/downloads/assets/' + self.magentoVersion + '/magento-' + self.magentoVersion + '.tar.gz', './', cb);
};

MagentoGenerator.prototype.phpunit = function phpunit() {
  var cb = this.async(),
    self = this;

  if (self.includeUnitTest) {
    try {
      var version = exec('git ls-remote --tags git://github.com/EcomDev/EcomDev_PHPUnit.git | tail -n 1', function(err, stdout, stderr) {
        if (err) {
          cb()
        } else {
          var pattern = /\d\.\d[\.\d]*/ig,
            match = pattern.exec(stdout);

          if (match !== null && typeof match[0] !== 'undefined') {
            self.ecomdevPHPUnitVersion = match[0];
          }
        }

        cb()
      });
    } catch(e) {
      cb()
    }

    if (typeof self.ecomdevPHPUnitVersion !== "undefined") {
      this.tarball('https://github.com/EcomDev/EcomDev_PHPUnit  /tarball/' + self.ecomdevPHPUnitVersion, './', cb);
    }
  }
}
<commit_msg>Default PHPUnit module install to false<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var MagentoGenerator = module.exports = function MagentoGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(MagentoGenerator, yeoman.generators.Base);

MagentoGenerator.prototype.askFor = function askFor() {
  var cb = this.async();

  // have Yeoman greet the user.
  console.log(this.yeoman);

  var prompts = [{
    name: 'magentoVersion',
    message: 'What version do you want to use? (e.g. 1.7.0.2)',
    default: '1.7.0.2'
  }, {
    type: 'confirm',
    name: 'includeUnitTest',
    message: 'Do you want to include EcomDevs PHPUnit module?',
    default: false
  }];

  this.prompt(prompts, function (props) {
    this.magentoVersion = props.magentoVersion;
    this.includeUnitTest = props.includeUnitTest;

    cb();
  }.bind(this));
};

MagentoGenerator.prototype.app = function app() {
  var cb = this.async(),
    self = this;

  this.tarball('http://www.magentocommerce.com/downloads/assets/' + self.magentoVersion + '/magento-' + self.magentoVersion + '.tar.gz', './', cb);
};

MagentoGenerator.prototype.phpunit = function phpunit() {
  var cb = this.async(),
    self = this;

  if (self.includeUnitTest) {
    try {
      var version = exec('git ls-remote --tags git://github.com/EcomDev/EcomDev_PHPUnit.git | tail -n 1', function(err, stdout, stderr) {
        if (err) {
          cb()
        } else {
          var pattern = /\d\.\d[\.\d]*/ig,
            match = pattern.exec(stdout);

          if (match !== null && typeof match[0] !== 'undefined') {
            self.ecomdevPHPUnitVersion = match[0];
          }
        }

        cb()
      });
    } catch(e) {
      cb()
    }

    if (typeof self.ecomdevPHPUnitVersion !== "undefined") {
      this.tarball('https://github.com/EcomDev/EcomDev_PHPUnit  /tarball/' + self.ecomdevPHPUnitVersion, './', cb);
    }
  }
}
<|endoftext|>