<commit_before>/*
 * grunt-sass-bootstrapper
 * https://github.com/mkatanski/grunt-sassdepress
 *
 * Copyright (c) 2014 Nexway Lab.
 * Licensed under the MIT license.
 *
 * @author Michal Katanski <mkatanski@nexway.com>
 */

'use strict';

var nodePath = require('path');

module.exports = function(grunt) {

    var DIList = [];
    var options = null;

    /*
     * Returns sass or scss file path without its extension
     * and without first occurence of underscore character ('_')
     * in filename.
     *
     * @path string path to be cleaned
     */
    function cleanFilePath(path) {
        var elements = path.split("/");

        if (elements[elements.length - 1].indexOf('_') == 0) {
            elements[elements.length - 1] = elements[elements.length - 1].replace('_', '');
        }
        elements[elements.length - 1] = elements[elements.length - 1].replace('.sass', '');
        elements[elements.length - 1] = elements[elements.length - 1].replace('.scss', '');

        return elements.join("/");
    }

    /*
     * Seeks given file for import keywords and DI keywords
     * if DI keyword is found it push it to the global array
     * import values are returned as an array.
     *
     * @importKeyword string sass import keyword
     * @requiresKeyword string dependency injection keyword
     * @file string file to be seek
     */
    function getKeywordsValues(importKeyword, requiresKeyword, file) {
        var values = [];
        var lines = grunt.file.read(file).split("\n");

        // Search for keywords
        for (var i = lines.length - 1; i >= 0; i--) {
            var line = lines[i];

            if (line.indexOf(importKeyword) > -1) {
                // importKeyword found. Push its value to the values array
                values.push(line.match(/"(.*?)"/)[1]);
            }

            if (line.indexOf(requiresKeyword) > -1) {
                // requiresKeyword found !!
                // push it to global array. This way it will not be
                // required to parse the same file twice to look for
                // DI keywords.

                // Create new dependency object
                var DIObject = {
                    requires: line.match(/"(.*?)"/)[1],
                    fileName: file
                };

                // check if DI object exists. If not add new one
                if (searchObjectInDI(DIObject) == -1) {
                    DIList.push(DIObject);
                }
            }
        }

        return values;
    }

    /*
     * Get root folder name from path. If path
     * is only a filename it will return '*root*' string
     * as a result.
     *
     * @path string path to get its root folder
     */
    function getRootFolder(path) {
        var parts = path.split("/");
        if (parts.length > 1) {
            return parts[0];
        }
        return '*root*';
    }

    /*
     * Removes array of string items which contains
     * given string
     *
     * @fileList array an array to be cleaned
     * @cleanPath string path to find. must be cleaned first
     */
    function removeArrayItemByPath(fileList, cleanPath) {
        var i = -1;
        var seek = true;

        while (seek) {
            i++;

            if (cleanFilePath(fileList[i]).indexOf(cleanPath) != -1) {
               fileList.splice(i, 1);
            }

            if (i >= fileList.length - 1) {
                seek = false;
            }
        }

        return fileList;
    }

    /*
     * Method which parse all files from an array.
     * It cleans list from files which are already
     * being imported and stores DI list into global array (DIList).
     *
     * @fileList array list of files to be parsed
     */
    function parseFiles(fileList) {
        var pass = true;

        while (pass) {
            pass = false;

            for (var index = 0; index < fileList.length; index++) {
                // get import values from file as an array and add DI values to the DIList array.
                var kValues = getKeywordsValues(options.importKeyword, options.requireKeyword, fileList[index]);
                var curLength = fileList.length;

                for (var i = kValues.length - 1; i >= 0; i--) {
                    fileList = removeArrayItemByPath(fileList, kValues[i]);
                    // Check if size of an array has changed
                    if (curLength > fileList.length) {
                        pass = true;
                    }
                }
            }
        }

        return fileList;
    }

    /*
     * Returns array of all dependencies for a given file.
     * If there is no DI for given file, returns empty array.
     *
     * @fileName string file name for which DIs must be returned
     */
    function getDIByFilename(fileName) {
        var returnArray = [];
        var length = DIList.length;

        for (var i = 0; i < length; i++) {
            if (DIList[i]['fileName'] == fileName) {
                returnArray.push(DIList[i]['requires']);
            }
        }

        return returnArray;
    }

    /*
     * Search for specific DI Object in DI List.
     * Method returns index position when DI object
     * exists in array or '-1' when its not found.
     *
     * @DIObject object DI object to find
     */
    function searchObjectInDI(DIObject) {
        for (var i = DIList.length - 1; i >= 0; i--) {
            if (DIList[i].requires == DIObject.requires &&
                DIList[i].fileName == DIObject.fileName)
                return i;
        }

        return -1;
    }

    /*
     * Search for path in list. Path should be clean.
     * Use cleanFilePath method to clean path.
     *
     * @cleanPath string clean path
     * @list array list of files
     */
    function searchInList(cleanPath, list) {
        for (var i = list.length - 1; i >= 0; i--) {
            if (cleanFilePath(list[i]).indexOf(cleanPath) > -1) {
                return i;
            }
        }
        return -1;
    }

    /*
     * Get item in array by its index and move it before
     * another item.
     *
     * @fileList array list of files
     * @indexToReplace int index of item to be moved
     * @indexToInsert int index where item should be placed
     */
    function replaceInArray(fileList, indexToReplace, indexToInsert) {
        var removedArr = fileList.splice(indexToReplace, 1);
        fileList.splice(indexToInsert, 0, removedArr[0]);

        return fileList;
    }

    /*
     * Reorders files in a given list by their dependencies.
     * Dependencies are taken from DIList which has to be
     * generated first.
     *
     * @fileList array list of files to be reordered
     */
    function orderByDependency(fileList) {
        var doPass = true;

        // repeat sorting operation untill
        // there is no replacing procedure during
        // one pass (bubble sorting).
        while (doPass) {
            doPass = false;

            // Iterate through every file in the list and check its
            // dependency (requirements)
            for (var i = fileList.length - 1; i >= 0; i--) {
                // Get all dependencies for current file
                var DIs = getDIByFilename(fileList[i]);

                if (DIs.length > 0) {
                    // for each file that is required by current file
                    for (var DIIndex = 0; DIIndex < DIs.length; DIIndex++) {
                        var requires = DIs[DIIndex];
                        // Index of file that is required by current file
                        var reqFileindex = searchInList(requires, fileList);

                        if (reqFileindex < i) {
                            // Remove file from current index and insert
                            // it before file that requires this file.
                            fileList = replaceInArray(fileList, reqFileindex, i);
                            // Replacing procedure occured so do one more pass.
                            doPass = true;
                        }
                    }
                }
            }
        }

        // Return reordered file list
        return fileList;
    }

    grunt.registerMultiTask('sass_bootstrapper', 'Resolves dependency for SASS files and creates bootstrap file', function() {
        // Merge task-specific and/or target-specific options with these defaults.
        options = this.options({
            filterRootPaths: ['app/styles/', 'bower_components/'],
            bootstrapFile: 'app/styles/bootstrap.sass',
            importKeyword: '@import',
            requireKeyword: '#requires'
        });

        // Iterate over all specified file groups.
        this.files.forEach(function(f) {

            if (grunt.file.exists(options.bootstrapFile)) {
                grunt.file.delete(options.bootstrapFile);
                grunt.log.writeln('File "' + options.bootstrapFile + '" deleted.');
            }

            var fileList = [];

            // Concat specified files.
            f.src.filter(function(filepath) {
                // Warn on and remove invalid source files (if nonull was set).
                if (!grunt.file.exists(filepath)) {
                    grunt.log.warn('Source file "' + filepath + '" not found.');
                    return false;
                } else {
                    return true;
                }
            }).map(function(filepath) {
                // Read file source.
                fileList.unshift(filepath);
                return true;
            });

            // Parse imports and DIs and order file by their dependency
            fileList = orderByDependency(parseFiles(fileList));

            var bootstrapContent = '// This file has been generated by grunt-sass-bootstrapper. \n// A SASS/SCSS Dependency resolver module.\n';
            var folderGroup = '';

            for (var i = fileList.length - 1; i >= 0; i--) {
                var filePath = fileList[i];

                // remove root paths
                for (var rpIndex = 0; rpIndex < options.filterRootPaths.length; rpIndex++) {
                    var normalizedPath = nodePath.normalize(options.filterRootPaths[rpIndex]);
                    if(normalizedPath.substr(-1) != '/') {
                        normalizedPath += '/';
                    }
                    filePath = filePath.replace(normalizedPath, '');
                }
                // clean path
                filePath = cleanFilePath(filePath);

                var curRoot = getRootFolder(filePath);

                if (folderGroup != curRoot) {
                    bootstrapContent += '\n' + '// ' + curRoot + '\n';
                    folderGroup = curRoot;
                }

                bootstrapContent += options.importKeyword + ' "' + filePath + '"\n';
            };

            // Write the destination file.
            grunt.file.write(options.bootstrapFile, bootstrapContent);

            // Print a success message.
            grunt.log.writeln('File "' + options.bootstrapFile + '" created.');
        });
    });

};<commit_msg>Quick changes<commit_after>/*
 * grunt-sass-bootstrapper
 * https://github.com/NexwayGroup/grunt-sass-bootstrapper
 *
 * Copyright (c) 2014 Nexway Lab.
 * Licensed under the MIT license.
 *
 * @author Michał Katański <mkatanski@nexway.com>
 */

'use strict';

var nodePath = require('path');

module.exports = function(grunt) {

    var DIList  = [];
    var options = null;

    /*
     * Returns sass or scss file path without its extension
     * and without first occurence of underscore character ('_')
     * in filename.
     *
     * @path string path to be cleaned
     */
    function cleanFilePath(path) {
        var elements = path.split("/");

        if (elements[elements.length - 1].indexOf('_') == 0) {
            elements[elements.length - 1] = elements[elements.length - 1].replace('_', '');
        }
        elements[elements.length - 1] = elements[elements.length - 1].replace('.sass', '');
        elements[elements.length - 1] = elements[elements.length - 1].replace('.scss', '');

        return elements.join("/");
    }

    /*
     * Seeks given file for import keywords and DI keywords
     * if DI keyword is found it push it to the global array
     * import values are returned as an array.
     *
     * @importKeyword string sass import keyword
     * @requiresKeyword string dependency injection keyword
     * @file string file to be seek
     */
    function getKeywordsValues(importKeyword, requiresKeyword, file) {
        var values = [];
        var lines = grunt.file.read(file).split("\n");

        // Search for keywords
        for (var i = lines.length - 1; i >= 0; i--) {
            var line = lines[i];

            if (line.indexOf(importKeyword) > -1) {
                // importKeyword found. Push its value to the values array
                values.push(line.match(/"(.*?)"/)[1]);
            }

            if (line.indexOf(requiresKeyword) > -1) {
                // requiresKeyword found !!
                // push it to global array. This way it will not be
                // required to parse the same file twice to look for
                // DI keywords.

                // Create new dependency object
                var DIObject = {
                    requires: line.match(/"(.*?)"/)[1],
                    fileName: file
                };

                // check if DI object exists. If not add new one
                if (searchObjectInDI(DIObject) == -1) {
                    DIList.push(DIObject);
                }
            }
        }

        return values;
    }

    /*
     * Get root folder name from path. If path
     * is only a filename it will return '*root*' string
     * as a result.
     *
     * @path string path to get its root folder
     */
    function getRootFolder(path) {
        var parts = path.split("/");
        if (parts.length > 1) {
            return parts[0];
        }
        return '*root*';
    }

    /*
     * Removes array of string items which contains
     * given string
     *
     * @fileList array an array to be cleaned
     * @cleanPath string path to find. must be cleaned first
     */
    function removeArrayItemByPath(fileList, cleanPath) {
        var i = -1;
        var seek = true;

        while (seek) {
            i++;

            if (cleanFilePath(fileList[i]).indexOf(cleanPath) != -1) {
               fileList.splice(i, 1);
            }

            if (i >= fileList.length - 1) {
                seek = false;
            }
        }

        return fileList;
    }

    /*
     * Method which parse all files from an array.
     * It cleans list from files which are already
     * being imported and stores DI list into global array (DIList).
     *
     * @fileList array list of files to be parsed
     */
    function parseFiles(fileList) {
        var pass = true;

        while (pass) {
            pass = false;

            for (var index = 0; index < fileList.length; index++) {
                // get import values from file as an array and add DI values to the DIList array.
                var kValues = getKeywordsValues(options.importKeyword, options.requireKeyword, fileList[index]);
                var curLength = fileList.length;

                for (var i = kValues.length - 1; i >= 0; i--) {
                    fileList = removeArrayItemByPath(fileList, kValues[i]);
                    // Check if size of an array has changed
                    if (curLength > fileList.length) {
                        pass = true;
                    }
                }
            }
        }

        return fileList;
    }

    /*
     * Returns array of all dependencies for a given file.
     * If there is no DI for given file, returns empty array.
     *
     * @fileName string file name for which DIs must be returned
     */
    function getDIByFilename(fileName) {
        var returnArray = [];
        var length = DIList.length;

        for (var i = 0; i < length; i++) {
            if (DIList[i]['fileName'] == fileName) {
                returnArray.push(DIList[i]['requires']);
            }
        }

        return returnArray;
    }

    /*
     * Search for specific DI Object in DI List.
     * Method returns index position when DI object
     * exists in array or '-1' when its not found.
     *
     * @DIObject object DI object to find
     */
    function searchObjectInDI(DIObject) {
        for (var i = DIList.length - 1; i >= 0; i--) {
            if (DIList[i].requires == DIObject.requires &&
                DIList[i].fileName == DIObject.fileName)
                return i;
        }

        return -1;
    }

    /*
     * Search for path in list. Path should be clean.
     * Use cleanFilePath method to clean path.
     *
     * @cleanPath string clean path
     * @list array list of files
     */
    function searchInList(cleanPath, list) {
        for (var i = list.length - 1; i >= 0; i--) {
            if (cleanFilePath(list[i]).indexOf(cleanPath) > -1) {
                return i;
            }
        }
        return -1;
    }

    /*
     * Get item in array by its index and move it before
     * another item.
     *
     * @fileList array list of files
     * @indexToReplace int index of item to be moved
     * @indexToInsert int index where item should be placed
     */
    function replaceInArray(fileList, indexToReplace, indexToInsert) {
        var removedArr = fileList.splice(indexToReplace, 1);
        fileList.splice(indexToInsert, 0, removedArr[0]);

        return fileList;
    }

    /*
     * Reorders files in a given list by their dependencies.
     * Dependencies are taken from DIList which has to be
     * generated first.
     *
     * @fileList array list of files to be reordered
     */
    function orderByDependency(fileList) {
        var doPass = true;

        // repeat sorting operation untill
        // there is no replacing procedure during
        // one pass (bubble sorting).
        while (doPass) {
            doPass = false;

            // Iterate through every file in the list and check its
            // dependency (requirements)
            for (var i = fileList.length - 1; i >= 0; i--) {
                // Get all dependencies for current file
                var DIs = getDIByFilename(fileList[i]);

                if (DIs.length > 0) {
                    // for each file that is required by current file
                    for (var DIIndex = 0; DIIndex < DIs.length; DIIndex++) {
                        var requires = DIs[DIIndex];
                        // Index of file that is required by current file
                        var reqFileindex = searchInList(requires, fileList);

                        if (reqFileindex < i) {
                            // Remove file from current index and insert
                            // it before file that requires this file.
                            fileList = replaceInArray(fileList, reqFileindex, i);
                            // Replacing procedure occured so do one more pass.
                            doPass = true;
                        }
                    }
                }
            }
        }

        // Return reordered file list
        return fileList;
    }

    grunt.registerMultiTask('sass_bootstrapper', 'Resolves dependency for SASS files and creates bootstrap file', function() {
        // Merge task-specific and/or target-specific options with these defaults.
        options = this.options({
            filterRootPaths: ['app/styles/', 'bower_components/'],
            bootstrapFile: 'app/styles/bootstrap.sass',
            importKeyword: '@import',
            requireKeyword: '#requires'
        });

        // Iterate over all specified file groups.
        this.files.forEach(function(f) {

            if (grunt.file.exists(options.bootstrapFile)) {
                grunt.file.delete(options.bootstrapFile);
                grunt.log.writeln('File "' + options.bootstrapFile + '" deleted.');
            }

            var fileList = [];

            // Concat specified files.
            f.src.filter(function(filepath) {
                // Warn on and remove invalid source files (if nonull was set).
                if (!grunt.file.exists(filepath)) {
                    grunt.log.warn('Source file "' + filepath + '" not found.');
                    return false;
                } else {
                    return true;
                }
            }).map(function(filepath) {
                // Read file source.
                fileList.unshift(filepath);
                return true;
            });

            // Parse imports and DIs and order file by their dependency
            fileList = orderByDependency(parseFiles(fileList));

            var bootstrapContent = '// This file has been generated by grunt-sass-bootstrapper. \n// A SASS/SCSS Dependency resolver module.\n';
            var folderGroup = '';

            for (var i = fileList.length - 1; i >= 0; i--) {
                var filePath = fileList[i];

                // remove root paths
                for (var rpIndex = 0; rpIndex < options.filterRootPaths.length; rpIndex++) {
                    var normalizedPath = nodePath.normalize(options.filterRootPaths[rpIndex]);
                    if(normalizedPath.substr(-1) != '/') {
                        normalizedPath += '/';
                    }
                    filePath = filePath.replace(normalizedPath, '');
                }
                // clean path
                filePath = cleanFilePath(filePath);

                var curRoot = getRootFolder(filePath);

                if (folderGroup != curRoot) {
                    bootstrapContent += '\n' + '// ' + curRoot + '\n';
                    folderGroup = curRoot;
                }

                bootstrapContent += options.importKeyword + ' "' + filePath + '"\n';
            };

            // Write the destination file.
            grunt.file.write(options.bootstrapFile, bootstrapContent);

            // Print a success message.
            grunt.log.writeln('File "' + options.bootstrapFile + '" created.');
        });
    });

};
<|endoftext|>


<commit_before>// WARNING:
// The following global constants must be set before instantiation:
//             DEEZER_APP_ID and DEEZER_CHANNEL_URL

window.showMessage = window.showMessage || function(msg) {
  console.warn("[showMessage]", msg);
};

window.$ = window.$ || function(){return window.$};
$.getScript = $.getScript || function(js,cb){loader.includeJS(js,cb);};
$.append = $.append || function(html){document.write(html);};

DeezerPlayer = (function(){

  // CONSTANTS
  var SDK_URL = 'https://cdns-files.deezer.com/js/min/dz.js',
      SDK_LOADED = false,
      IS_LOGGED = false,
      URL_REG = /(?:https?:)?\/\/(?:www\.)deezer\.com\/track\/(\d+)/i,
      EVENT_MAP = {
        player_play: 'onPlaying',
        player_paused: 'onPaused',
        player_position: 'onTrackInfo'
      };

  //============================================================================
  function Player(eventHandlers) {

    var self = this;

    this.label = 'Deezer';
    this.eventHandlers = eventHandlers || {};
    this.currentTrack = {position: 0, duration: 0};

    loadSDK(function() {
      init(function() {
        //console.log('DeezerPlayer ready');
        //DZ.getLoginStatus = function(cb) {cb && cb({userID: null})}
        DZ.getLoginStatus(function(response) {
          DZ.player.setRepeat(0);
          IS_LOGGED = response.userID;
          self.isReady = true;
          hookHandlers(self);
        });
      });
    });

  }

  //============================================================================
  Player.prototype.getEid = function(url, cb) {
    cb(URL_REG.test(url) ? RegExp.$1 : null, this);
  }

  //============================================================================
  Player.prototype.play = function(id) {
    var self = this;
    if (IS_LOGGED) {
      DZ.player.playTracks([id], 0);
    } else {
      DZ.api('/track/' + id, function(data) {
        showMessage(
          'This is a 30 secs preview. ' +
          '' +
          'Connect to Deezer to listen to the full track.'
        );
        self.sound = createSound(self, data.preview)
      });
    }
  }

  //============================================================================
  Player.prototype.pause = function() {
    if (this.sound) {
      this.sound.pause();
    } else {
      DZ.player.pause();
    }
  }

  //============================================================================
  Player.prototype.stop = function() {
    if (this.sound) {
      this.sound.stop();
      this.sound.destruct();
      this.sound = null;
    } else {
      DZ.player.pause();
    }
  }

  //============================================================================
  Player.prototype.resume = function() {
    if (this.sound) {
      this.sound.resume();
    } else {
      DZ.player.play();
    }
  }

  //============================================================================
  // pos: seconds
  Player.prototype.setTrackPosition = function(pos) {
    if (this.sound)
      this.sound.setPosition(Math.round(pos * 1000));
    else
      DZ.player.seek(Math.round(100 * pos / this.currentTrack.duration));
  }

  //============================================================================
  // vol: float between 0 and 1
  Player.prototype.setVolume = function(vol) {
    if (this.sound)
      this.sound.setVolume(Math.round(vol * 100));
    else
      DZ.player.setVolume(Math.round(vol * 100));
  }

  //============================================================================
  function loadSDK(cb) {
    if (!SDK_LOADED) {
      //$('body').append('

');
      var dz = document.createElement('div'); dz.id = 'dz-root';
      document.getElementsByTagName("body")[0].appendChild(dz);
      $.getScript(SDK_URL, function() {
        SDK_LOADED = true;
        cb();
      });
    } else {
      cb();
    }
  }

  //============================================================================
  function init(onload) {
    DZ.init({
      appId: DEEZER_APP_ID,
      channelUrl: DEEZER_CHANNEL_URL,
      player: {
        onload: onload
      }
    });
  }

  //============================================================================
  function hookHandlers(self) {

    function createHandler(e) {
      if (e === 'player_position') {
        return function(eventObject) {
          var onTrackInfoHandler = self.eventHandlers.onTrackInfo,
              onEndedHandler = self.eventHandlers.onEnded,
              position = eventObject[0],
              duration = eventObject[1];
          if (onTrackInfoHandler) {
            self.currentTrack = {position: position, duration: duration};
            onTrackInfoHandler(self.currentTrack);
          }
          if ((duration - position <= 1.5) && onEndedHandler)
            onEndedHandler(self);
        };
      }
      return function() {
        var handler = self.eventHandlers[EVENT_MAP[e]];
        handler && handler(self);
      };
    }

    for (var e in EVENT_MAP)
      DZ.Event.suscribe(e, createHandler(e));
    self.eventHandlers.onApiLoaded && self.eventHandlers.onApiLoaded(self);
    self.eventHandlers.onApiReady && self.eventHandlers.onApiReady(self);
  }

  //============================================================================
  function createSound(self, url) {
    return soundManager.createSound({
      id: 'deezerSound' + Date.now(),
      url: url,
      autoLoad: true,
      autoPlay: true,
      whileplaying: function() {
        self.currentTrack = {
          position: self.sound.position / 1000,
          duration: self.sound.duration / 1000
        };
        if (self.eventHandlers.onTrackInfo)
          self.eventHandlers.onTrackInfo(self.currentTrack);
      },
      onplay: function() {
        if (self.eventHandlers.onPlaying)
          self.eventHandlers.onPlaying(self);
      },
      onresume: function() {
        if (self.eventHandlers.onPlaying)
          self.eventHandlers.onPlaying(self);
      },
      onfinish: function() {
        if (self.eventHandlers.onEnded)
          self.eventHandlers.onEnded();
      }
    });
  }

  //============================================================================
  Player.login = function() {
    DZ.login(function(response) {
      if (response.userID) {
        IS_LOGGED = true;
        showMessage('Login successful. Your Deezer tracks will be full length from now on!');
      } else {
        showMessage('Deezer login unsuccesful.', true);
      }
    }, {perms: 'email'});
  }

  //============================================================================
  return Player;

})();
<commit_msg>added isLogged() in Deezer player<commit_after>// WARNING:
// The following global constants must be set before instantiation:
//             DEEZER_APP_ID and DEEZER_CHANNEL_URL

window.showMessage = window.showMessage || function(msg) {
  console.warn("[showMessage]", msg);
};

window.$ = window.$ || function(){return window.$};
$.getScript = $.getScript || function(js,cb){loader.includeJS(js,cb);};
$.append = $.append || function(html){document.write(html);};

DeezerPlayer = (function(){

  // CONSTANTS
  var SDK_URL = 'https://cdns-files.deezer.com/js/min/dz.js',
      SDK_LOADED = false,
      IS_LOGGED = false,
      URL_REG = /(?:https?:)?\/\/(?:www\.)deezer\.com\/track\/(\d+)/i,
      EVENT_MAP = {
        player_play: 'onPlaying',
        player_paused: 'onPaused',
        player_position: 'onTrackInfo'
      };

  //============================================================================
  function Player(eventHandlers) {

    var self = this;

    this.label = 'Deezer';
    this.eventHandlers = eventHandlers || {};
    this.currentTrack = {position: 0, duration: 0};

    loadSDK(function() {
      init(function() {
        //console.log('DeezerPlayer ready');
        //DZ.getLoginStatus = function(cb) {cb && cb({userID: null})}
        DZ.getLoginStatus(function(response) {
          DZ.player.setRepeat(0);
          IS_LOGGED = response.userID;
          self.isReady = true;
          hookHandlers(self);
        });
      });
    });

  }

  //============================================================================
  Player.prototype.isLogged = function() {
    return IS_LOGGED;
  }

  //============================================================================
  Player.prototype.getEid = function(url, cb) {
    cb(URL_REG.test(url) ? RegExp.$1 : null, this);
  }

  //============================================================================
  Player.prototype.play = function(id) {
    var self = this;
    if (IS_LOGGED) {
      DZ.player.playTracks([id], 0);
    } else {
      DZ.api('/track/' + id, function(data) {
        showMessage(
          'This is a 30 secs preview. ' +
          '' +
          'Connect to Deezer to listen to the full track.'
        );
        self.sound = createSound(self, data.preview)
      });
    }
  }

  //============================================================================
  Player.prototype.pause = function() {
    if (this.sound) {
      this.sound.pause();
    } else {
      DZ.player.pause();
    }
  }

  //============================================================================
  Player.prototype.stop = function() {
    if (this.sound) {
      this.sound.stop();
      this.sound.destruct();
      this.sound = null;
    } else {
      DZ.player.pause();
    }
  }

  //============================================================================
  Player.prototype.resume = function() {
    if (this.sound) {
      this.sound.resume();
    } else {
      DZ.player.play();
    }
  }

  //============================================================================
  // pos: seconds
  Player.prototype.setTrackPosition = function(pos) {
    if (this.sound)
      this.sound.setPosition(Math.round(pos * 1000));
    else
      DZ.player.seek(Math.round(100 * pos / this.currentTrack.duration));
  }

  //============================================================================
  // vol: float between 0 and 1
  Player.prototype.setVolume = function(vol) {
    if (this.sound)
      this.sound.setVolume(Math.round(vol * 100));
    else
      DZ.player.setVolume(Math.round(vol * 100));
  }

  //============================================================================
  function loadSDK(cb) {
    if (!SDK_LOADED) {
      //$('body').append('

');
      var dz = document.createElement('div'); dz.id = 'dz-root';
      document.getElementsByTagName("body")[0].appendChild(dz);
      $.getScript(SDK_URL, function() {
        SDK_LOADED = true;
        cb();
      });
    } else {
      cb();
    }
  }

  //============================================================================
  function init(onload) {
    DZ.init({
      appId: DEEZER_APP_ID,
      channelUrl: DEEZER_CHANNEL_URL,
      player: {
        onload: onload
      }
    });
  }

  //============================================================================
  function hookHandlers(self) {

    function createHandler(e) {
      if (e === 'player_position') {
        return function(eventObject) {
          var onTrackInfoHandler = self.eventHandlers.onTrackInfo,
              onEndedHandler = self.eventHandlers.onEnded,
              position = eventObject[0],
              duration = eventObject[1];
          if (onTrackInfoHandler) {
            self.currentTrack = {position: position, duration: duration};
            onTrackInfoHandler(self.currentTrack);
          }
          if ((duration - position <= 1.5) && onEndedHandler)
            onEndedHandler(self);
        };
      }
      return function() {
        var handler = self.eventHandlers[EVENT_MAP[e]];
        handler && handler(self);
      };
    }

    for (var e in EVENT_MAP)
      DZ.Event.suscribe(e, createHandler(e));
    self.eventHandlers.onApiLoaded && self.eventHandlers.onApiLoaded(self);
    self.eventHandlers.onApiReady && self.eventHandlers.onApiReady(self);
  }

  //============================================================================
  function createSound(self, url) {
    return soundManager.createSound({
      id: 'deezerSound' + Date.now(),
      url: url,
      autoLoad: true,
      autoPlay: true,
      whileplaying: function() {
        self.currentTrack = {
          position: self.sound.position / 1000,
          duration: self.sound.duration / 1000
        };
        if (self.eventHandlers.onTrackInfo)
          self.eventHandlers.onTrackInfo(self.currentTrack);
      },
      onplay: function() {
        if (self.eventHandlers.onPlaying)
          self.eventHandlers.onPlaying(self);
      },
      onresume: function() {
        if (self.eventHandlers.onPlaying)
          self.eventHandlers.onPlaying(self);
      },
      onfinish: function() {
        if (self.eventHandlers.onEnded)
          self.eventHandlers.onEnded();
      }
    });
  }

  //============================================================================
  Player.login = function() {
    DZ.login(function(response) {
      if (response.userID) {
        IS_LOGGED = true;
        showMessage('Login successful. Your Deezer tracks will be full length from now on!');
      } else {
        showMessage('Deezer login unsuccesful.', true);
      }
    }, {perms: 'email'});
  }

  //============================================================================
  return Player;

})();
<|endoftext|>


<commit_before>/*
 * grunt-splitthreejsmodel
 * https://github.com/Tomasz/grunt-splitthreejsmodel
 *
 * Copyright (c) 2014 Tomasz Dysinski
 * Licensed under the MIT license.
 */
'use strict';

// Nodejs libs.
var path = require('path'),
  fs = require('fs'),
  tar = require('tar'),
  _ = require('lodash'),
  derive = require('filepathderivatives'),
  THREE = require('../lib/three.min.nodejs'),
  splitModelUtil = require('../utils/splitModel'),
  ensureDirectoryExists = require('../utils/ensureDirectoryExists');

//task shared scope
var writing = 0;
var wrote = 0;
var done;
var options;
var _grunt;

var _geometryCaches = {};

function isDoneWritingAllFiles() {
  return writing === wrote;
}

//individual file scope
function SplitModel(srcPath, callback){
  var inputPath = derive.replaceExtension(srcPath, 'json');
  _grunt.verbose.writeln('splitting', srcPath, inputPath);
  var _this = this;
  this.outputPath = path.normalize(path.dirname(srcPath) + '/' + path.basename(srcPath, path.extname(srcPath)) + '/..');
  this.loadExistingGeometryCache(this.outputPath, function(cache) {
    _this.cache = cache;
    _grunt.verbose.writeln('outputting to', _this.outputPath);
    ensureDirectoryExists(_this.outputPath, function() {
      fs.readFile(inputPath, 'utf8', function (err, dataString) {
        _grunt.log.oklns('Loading', inputPath);
        if (err) {
          _grunt.fail.warn(err);
          callback();
          return;
        }

        _grunt.log.oklns('Loaded', ~~(dataString.length * 0.001) * 0.001, 'megabytes');
        var baseName = path.basename(inputPath, path.extname(inputPath));

        _grunt.log.oklns('Splitting...');
        //var loader = new THREE.SceneLoader();
        var data = JSON.parse(dataString);
        var objectsToWrite = splitModelUtil(data, path.normalize(baseName + '/'), _this.cache, _grunt);
        for(var objectName in objectsToWrite) {
          //write the json files
          _this.writeObjectFile(objectName, objectsToWrite[objectName], callback);
        }
      });
    });
  });
}

SplitModel.prototype = {
  writeStringToFile: function(data, pathDst, callback) {
    var _this = this;
    fs.open(pathDst, 'wx', function(err, fd){
      if(fd) {
        fs.write(fd, data, 0, 'utf8', function(err, written, buffer) {
          fs.close(fd);
          _grunt.log.oklns('wrote', derive.difference(_this.outputPath, pathDst));
          wrote++;
          if(isDoneWritingAllFiles()) {
            callback();
          }
        });
      }
    });
  },

  writeStringToFileEvenIfExists: function(data, pathDst, callback) {
    var _this = this;
    fs.exists(pathDst, function(exists){
      if(exists) {
        fs.unlink(pathDst, function() {
          _this.writeStringToFile(data, pathDst, callback);
        });
      } else {
        _this.writeStringToFile(data, pathDst, callback);
      }
    });
  },

  writeObjectFile: function(objectName, objectData, callback) {
    var cloneString = JSON.stringify(objectData);
    var objectPath = path.normalize(this.outputPath + '/' + objectName + '.json');
    _grunt.log.oklns("writing", objectName);
    writing++;
    var _this = this;
    ensureDirectoryExists(path.dirname(objectPath), function() {
      _this.writeStringToFileEvenIfExists(cloneString, objectPath, callback);
    });
  },

  loadExistingGeometryCache: function(outputPath, callback) {
    _grunt.log.oklns('LOADING PRE-EXISTING GEOMETRY');

    var geometryCache = _geometryCaches[outputPath];
    var geometryToLoad = 0;
    function checkIfAllGeometryCached() {
      if(geometryToLoad === 0) {
        callback(geometryCache);
      }
    }
    if(!geometryCache) {
      _grunt.log.oklns("CREATING GEOMETRY CACHE FOR", outputPath);
      geometryCache = _geometryCaches[outputPath] = {};
      var geometryPath = path.normalize(outputPath + '/geometry');
      ensureDirectoryExists(geometryPath, function() {
        fs.readdir(geometryPath, function(err, files) {
          if(err) { throw err; }
          function handleGeometryData(filePath, err, dataString) {
            if(err) { throw err; }
            var fileKey = path.normalize(path.dirname(filePath) + '/' + path.basename(filePath, path.extname(filePath)));
            geometryCache[fileKey] = JSON.parse(dataString);
            _grunt.log.oklns('PRECACHED', fileKey);
            geometryToLoad--;
            checkIfAllGeometryCached();
          }
          if(files.length > 0) {
            for (var i = files.length - 1; i >= 0; i--) {
              geometryToLoad++;
              fs.readFile(path.resolve(geometryPath + '/' + files[i]), handleGeometryData.bind(null, files[i]));
            }
          } else {
            callback(geometryCache);
          }
        });
      });
    } else {
      _grunt.log.oklns("REUSING GEOMETRY CACHE FOR", outputPath);
      callback(geometryCache);
    }
  }
};

module.exports = function(grunt) {

  _grunt = grunt;

  grunt.registerMultiTask('splitthreejsmodel', 'A grunt plugin to split threejs json model files into geometry files and a hierarchy of object json files. For use in conjunction with [grunt-convertautodesktothree](https://github.com/bunnybones1/grunt-convertautodesktothreejs).', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    options = this.options({
    });
    done = this.async();

    function splitNextModel() {
      if(options.models.length > 0) {
        grunt.log.oklns('PROCESS MODEL', options.models[0]);
        new SplitModel(options.models.splice(0, 1), splitNextModel);
      } else {
        done();
      }
    }
    splitNextModel();
  });
};
<commit_msg>only precache json files<commit_after>/*
 * grunt-splitthreejsmodel
 * https://github.com/Tomasz/grunt-splitthreejsmodel
 *
 * Copyright (c) 2014 Tomasz Dysinski
 * Licensed under the MIT license.
 */
'use strict';

// Nodejs libs.
var path = require('path'),
  fs = require('fs'),
  tar = require('tar'),
  _ = require('lodash'),
  derive = require('filepathderivatives'),
  THREE = require('../lib/three.min.nodejs'),
  splitModelUtil = require('../utils/splitModel'),
  ensureDirectoryExists = require('../utils/ensureDirectoryExists');

//task shared scope
var writing = 0;
var wrote = 0;
var done;
var options;
var _grunt;

var _geometryCaches = {};

function isDoneWritingAllFiles() {
  return writing === wrote;
}

//individual file scope
function SplitModel(srcPath, callback){
  var inputPath = derive.replaceExtension(srcPath, 'json');
  _grunt.verbose.writeln('splitting', srcPath, inputPath);
  var _this = this;
  this.outputPath = path.normalize(path.dirname(srcPath) + '/' + path.basename(srcPath, path.extname(srcPath)) + '/..');
  this.loadExistingGeometryCache(this.outputPath, function(cache) {
    _this.cache = cache;
    _grunt.verbose.writeln('outputting to', _this.outputPath);
    ensureDirectoryExists(_this.outputPath, function() {
      fs.readFile(inputPath, 'utf8', function (err, dataString) {
        _grunt.log.oklns('Loading', inputPath);
        if (err) {
          _grunt.fail.warn(err);
          callback();
          return;
        }

        _grunt.log.oklns('Loaded', ~~(dataString.length * 0.001) * 0.001, 'megabytes');
        var baseName = path.basename(inputPath, path.extname(inputPath));

        _grunt.log.oklns('Splitting...');
        //var loader = new THREE.SceneLoader();
        var data = JSON.parse(dataString);
        var objectsToWrite = splitModelUtil(data, path.normalize(baseName + '/'), _this.cache, _grunt);
        for(var objectName in objectsToWrite) {
          //write the json files
          _this.writeObjectFile(objectName, objectsToWrite[objectName], callback);
        }
      });
    });
  });
}

SplitModel.prototype = {
  writeStringToFile: function(data, pathDst, callback) {
    var _this = this;
    fs.open(pathDst, 'wx', function(err, fd){
      if(fd) {
        fs.write(fd, data, 0, 'utf8', function(err, written, buffer) {
          fs.close(fd);
          _grunt.log.oklns('wrote', derive.difference(_this.outputPath, pathDst));
          wrote++;
          if(isDoneWritingAllFiles()) {
            callback();
          }
        });
      }
    });
  },

  writeStringToFileEvenIfExists: function(data, pathDst, callback) {
    var _this = this;
    fs.exists(pathDst, function(exists){
      if(exists) {
        fs.unlink(pathDst, function() {
          _this.writeStringToFile(data, pathDst, callback);
        });
      } else {
        _this.writeStringToFile(data, pathDst, callback);
      }
    });
  },

  writeObjectFile: function(objectName, objectData, callback) {
    var cloneString = JSON.stringify(objectData);
    var objectPath = path.normalize(this.outputPath + '/' + objectName + '.json');
    _grunt.log.oklns("writing", objectName);
    writing++;
    var _this = this;
    ensureDirectoryExists(path.dirname(objectPath), function() {
      _this.writeStringToFileEvenIfExists(cloneString, objectPath, callback);
    });
  },

  loadExistingGeometryCache: function(outputPath, callback) {
    _grunt.log.oklns('LOADING PRE-EXISTING GEOMETRY');

    var geometryCache = _geometryCaches[outputPath];
    var geometryToLoad = 0;
    function checkIfAllGeometryCached() {
      if(geometryToLoad === 0) {
        callback(geometryCache);
      }
    }
    if(!geometryCache) {
      _grunt.log.oklns("CREATING GEOMETRY CACHE FOR", outputPath);
      geometryCache = _geometryCaches[outputPath] = {};
      var geometryPath = path.normalize(outputPath + '/geometry');
      ensureDirectoryExists(geometryPath, function() {
        fs.readdir(geometryPath, function(err, files) {
          if(err) { throw err; }
          function handleGeometryData(filePath, err, dataString) {
            if(err) { throw err; }
            var fileKey = path.normalize(path.dirname(filePath) + '/' + path.basename(filePath, path.extname(filePath)));
            geometryCache[fileKey] = JSON.parse(dataString);
            _grunt.log.oklns('PRECACHED', fileKey);
            geometryToLoad--;
            checkIfAllGeometryCached();
          }
          if(files.length > 0) {
            for (var i = files.length - 1; i >= 0; i--) {
              if(files[i].lastIndexOf('.json') == files[i].length - 5) {
                geometryToLoad++;
                fs.readFile(path.resolve(geometryPath + '/' + files[i]), handleGeometryData.bind(null, files[i]));
              }
            }
          } else {
            callback(geometryCache);
          }
        });
      });
    } else {
      _grunt.log.oklns("REUSING GEOMETRY CACHE FOR", outputPath);
      callback(geometryCache);
    }
  }
};

module.exports = function(grunt) {

  _grunt = grunt;

  grunt.registerMultiTask('splitthreejsmodel', 'A grunt plugin to split threejs json model files into geometry files and a hierarchy of object json files. For use in conjunction with [grunt-convertautodesktothree](https://github.com/bunnybones1/grunt-convertautodesktothreejs).', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    options = this.options({
    });
    done = this.async();

    function splitNextModel() {
      if(options.models.length > 0) {
        grunt.log.oklns('PROCESS MODEL', options.models[0]);
        new SplitModel(options.models.splice(0, 1), splitNextModel);
      } else {
        done();
      }
    }
    splitNextModel();
  });
};
<|endoftext|>


<commit_before>'use strict';

const chalk = require('chalk');
const Insight = require('insight');
const Generator = require('@ngx-rocket/core');
const asciiLogo = require('@ngx-rocket/ascii-logo');

const prompts = require('./prompts');
const options = require('./options');
const pkg = require('../../package.json');

class NgxGenerator extends Generator {
  initializing() {
    this.version = pkg.version;
    this.insight = new Insight({trackingCode: 'UA-93069862-1', pkg});
    this.props = {};

    this.argument('appName', {
      description: 'Name of the app to generate',
      type: String,
      required: false
    });

    this.insight.optOut = !this.options.analytics || process.env.DISABLE_NGX_ANALYTICS;

    if (this.options.raw) {
      this.prop.ui = 'raw';
    }

    if (this.options['location-strategy']) {
      this.props.location = this.options['location-strategy'];
    }

    // Updating
    let fromVersion = null;

    if (this.options.update) {
      this.props = this.config.get('props') || {};
      fromVersion = this.config.get('version');
    }

    if (fromVersion) {
      if (fromVersion >= this.version) {
        this.log(chalk.green('\nNothing to update, it\'s all good!\n'));
        process.exit(0);
      }

      this.updating = true;
      this.log(`\nUpdating ${chalk.green(this.props.appName)} project (${chalk.yellow(fromVersion)} -> ${chalk.yellow(this.version)})\n`);
      this.log(`${chalk.yellow('Make sure you don\'t have uncommitted changes before overwriting files!')}`);
      this.insight.track('update', fromVersion, 'to', this.version);
    } else if (!this.options['skip-welcome']) {
      this.log(asciiLogo(pkg.version));
    }

    // Composition
    const addonsOption = this.options.addons;
    this.addons = addonsOption ? addonsOption.split(' ') : [];
    this.addons.forEach(addon => this.composeWith(addon, this.options));

    this.insight.track('version', this.version);
    this.insight.track('node', process.version);
    this.insight.track('platform', process.platform);
    this.insight.track('addons', addonsOption);
  }

  prompting() {
    return super.prompting()
      .then(() => {
        this.props.mobile = this.props.mobile || [];
        this.shareProps(this.props);
      });
  }

  configuring() {
    this.insight.track(
      'generator',
      this.props.target,
      this.props.target.includes('web') && this.props.pwa ? 'pwa' : '',
      this.props.target.includes('cordova') ? this.props.mobile : '',
      this.props.ui,
      this.props.auth ? 'auth' : 'no-auth'
    );
    this.insight.track('package-manager', this.packageManager);

    if (this.props.target.includes('cordova') && this.packageManager === 'yarn') {
      this.log(chalk.yellow('\nWarning: Using Yarn with Cordova is NOT recommended!'));
      this.log(chalk.yellow('Cordova still uses NPM to fetch packages, causing issues with Yarn.\n'));
    }
  }

  install() {
    const skipInstall = this.options['skip-install'];

    if (!skipInstall) {
      this.log(`\nRunning ${chalk.yellow(`${this.packageManager} install`)}, please wait...`);

      if (this.packageManager === 'yarn') {
        this.yarnInstall();
      } else {
        this.npmInstall(null, {loglevel: 'error'});
      }
    }
  }

  end() {
    if (this.updating) {
      this.log(`\nUpdated ${chalk.green(this.props.appName)} to ${chalk.yellow(this.version)} successfully!`);
      return;
    }

    this.log('\nAll done! Get started with these tasks:');
    this.log(`- $ ${chalk.green(`${this.packageManager} start`)}: start dev server with live reload on http://localhost:4200`);

    if (this.props.target.includes('web')) {
      this.log(`- $ ${chalk.green(`${this.packageManager} run build`)}: build web app for production`);
    }

    if (this.props.target.includes('cordova')) {
      this.log(`- $ ${chalk.green(`${this.packageManager} run cordova:prepare`)}: prepare for building mobile app`);
      this.log(`- $ ${chalk.green(`${this.packageManager} run cordova:run`)}: run app on device or simulator`);
      this.log(`- $ ${chalk.green(`${this.packageManager} run cordova:build`)}: build mobile app for production`);
    }

    this.log(`- $ ${chalk.green(`${this.packageManager} test`)}: run unit tests in watch mode for TDD`);
    this.log(`- $ ${chalk.green(`${this.packageManager} run test:ci`)}: lint code and run units tests with coverage`);
    this.log(`- $ ${chalk.green(`${this.packageManager} run e2e`)}: launch e2e tests`);
    this.log(`- $ ${chalk.green(`${this.packageManager} run docs`)}: show docs and coding guides`);
  }
}

module.exports = Generator.make({
  baseDir: __dirname,
  generator: NgxGenerator,
  options,
  prompts,
  prefixRules: Object.assign(Generator.defaultPrefixRules, {
    'material-simple': props => props.ui === 'material' && props.layout === 'simple',
    'material-side-menu': props => props.ui === 'material' && props.layout === 'side-menu',
    raw: props => props.ui === 'raw'
  })
});
<commit_msg>* [bug] the raw ui option can not work<commit_after>'use strict';

const chalk = require('chalk');
const Insight = require('insight');
const Generator = require('@ngx-rocket/core');
const asciiLogo = require('@ngx-rocket/ascii-logo');

const prompts = require('./prompts');
const options = require('./options');
const pkg = require('../../package.json');

class NgxGenerator extends Generator {
  initializing() {
    this.version = pkg.version;
    this.insight = new Insight({trackingCode: 'UA-93069862-1', pkg});
    this.props = {};

    this.argument('appName', {
      description: 'Name of the app to generate',
      type: String,
      required: false
    });

    this.insight.optOut = !this.options.analytics || process.env.DISABLE_NGX_ANALYTICS;

    if (this.options.raw) {
      this.props.ui = 'raw';
    }

    if (this.options['location-strategy']) {
      this.props.location = this.options['location-strategy'];
    }

    // Updating
    let fromVersion = null;

    if (this.options.update) {
      this.props = this.config.get('props') || {};
      fromVersion = this.config.get('version');
    }

    if (fromVersion) {
      if (fromVersion >= this.version) {
        this.log(chalk.green('\nNothing to update, it\'s all good!\n'));
        process.exit(0);
      }

      this.updating = true;
      this.log(`\nUpdating ${chalk.green(this.props.appName)} project (${chalk.yellow(fromVersion)} -> ${chalk.yellow(this.version)})\n`);
      this.log(`${chalk.yellow('Make sure you don\'t have uncommitted changes before overwriting files!')}`);
      this.insight.track('update', fromVersion, 'to', this.version);
    } else if (!this.options['skip-welcome']) {
      this.log(asciiLogo(pkg.version));
    }

    // Composition
    const addonsOption = this.options.addons;
    this.addons = addonsOption ? addonsOption.split(' ') : [];
    this.addons.forEach(addon => this.composeWith(addon, this.options));

    this.insight.track('version', this.version);
    this.insight.track('node', process.version);
    this.insight.track('platform', process.platform);
    this.insight.track('addons', addonsOption);
  }

  prompting() {
    return super.prompting()
      .then(() => {
        this.props.mobile = this.props.mobile || [];
        this.shareProps(this.props);
      });
  }

  configuring() {
    this.insight.track(
      'generator',
      this.props.target,
      this.props.target.includes('web') && this.props.pwa ? 'pwa' : '',
      this.props.target.includes('cordova') ? this.props.mobile : '',
      this.props.ui,
      this.props.auth ? 'auth' : 'no-auth'
    );
    this.insight.track('package-manager', this.packageManager);

    if (this.props.target.includes('cordova') && this.packageManager === 'yarn') {
      this.log(chalk.yellow('\nWarning: Using Yarn with Cordova is NOT recommended!'));
      this.log(chalk.yellow('Cordova still uses NPM to fetch packages, causing issues with Yarn.\n'));
    }
  }

  install() {
    const skipInstall = this.options['skip-install'];

    if (!skipInstall) {
      this.log(`\nRunning ${chalk.yellow(`${this.packageManager} install`)}, please wait...`);

      if (this.packageManager === 'yarn') {
        this.yarnInstall();
      } else {
        this.npmInstall(null, {loglevel: 'error'});
      }
    }
  }

  end() {
    if (this.updating) {
      this.log(`\nUpdated ${chalk.green(this.props.appName)} to ${chalk.yellow(this.version)} successfully!`);
      return;
    }

    this.log('\nAll done! Get started with these tasks:');
    this.log(`- $ ${chalk.green(`${this.packageManager} start`)}: start dev server with live reload on http://localhost:4200`);

    if (this.props.target.includes('web')) {
      this.log(`- $ ${chalk.green(`${this.packageManager} run build`)}: build web app for production`);
    }

    if (this.props.target.includes('cordova')) {
      this.log(`- $ ${chalk.green(`${this.packageManager} run cordova:prepare`)}: prepare for building mobile app`);
      this.log(`- $ ${chalk.green(`${this.packageManager} run cordova:run`)}: run app on device or simulator`);
      this.log(`- $ ${chalk.green(`${this.packageManager} run cordova:build`)}: build mobile app for production`);
    }

    this.log(`- $ ${chalk.green(`${this.packageManager} test`)}: run unit tests in watch mode for TDD`);
    this.log(`- $ ${chalk.green(`${this.packageManager} run test:ci`)}: lint code and run units tests with coverage`);
    this.log(`- $ ${chalk.green(`${this.packageManager} run e2e`)}: launch e2e tests`);
    this.log(`- $ ${chalk.green(`${this.packageManager} run docs`)}: show docs and coding guides`);
  }
}

module.exports = Generator.make({
  baseDir: __dirname,
  generator: NgxGenerator,
  options,
  prompts,
  prefixRules: Object.assign(Generator.defaultPrefixRules, {
    'material-simple': props => props.ui === 'material' && props.layout === 'simple',
    'material-side-menu': props => props.ui === 'material' && props.layout === 'side-menu',
    raw: props => props.ui === 'raw'
  })
});
<|endoftext|>


<commit_before><commit_msg>US2859 remove a wrong paste in a js file<commit_after><|endoftext|>


<commit_before>var yeoman = require('yeoman-generator'),
    Promise = require('promise');

module.exports = yeoman.generators.Base.extend({
    constructor: function () {
        yeoman.generators.Base.apply(this, arguments);
    },
    prompting: {
        promptName: function () {
            var done = this.async();
            this.prompt({
                type: 'input',
                name: 'name',
                message: 'Your project name',
                default: this.appname // Default to current folder name
            }, function (answers) {
                this.log(answers.name);
                done();
            }.bind(this));
        },
        promptModules: function () {
            var done = this.async();

            var prompts = [
                {
                    type: 'checkbox',
                    name: 'modules',
                    message: 'Which modules would you like to include?',
                    choices: [
                        {
                            value: 'exjsModule',
                            name: 'exjs',
                            checked: true
                        },
                        {
                            value: 'controlsModule',
                            name: 'Fayde.Controls',
                            checked: true
                        }
                    ]
                }
            ];

            this.prompt(prompts, function (props) {
                this.exjsModule = props.modules.exjsModule;
                this.controlsModule = props.modules.controlsModule;
                done();
            }.bind(this));
        }
    },
    configuring: {
        bowerSetup: function () {
            this.copy('_bowerrc', '.bowerrc');
            this.copy('_bower.json', 'bower.json');
        },
        gruntSetup: function () {
            this.copy('_package.json', 'package.json');
            this.copy('_Gruntfile.js', 'Gruntfile.js');
        }
    },
    writing: {
        appFiles: function () {
            var context = {
                exjs_lib: '',
                controls_lib: ''
            };
            if (this.exjsModule)
                context.exjs_lib = genScriptInclude('lib/exjs/dist/ex.min.js');
            if (this.controlsModule)
                context.controls_lib = genLibShim('Fayde.Controls', 'lib/Fayde.Controls/Fayde.Controls', 'Fayde.Controls');

            this.template('app/_default.html', 'app/default.html', context);
            this.copy('app/default.fap', 'app/default.fap');
            this.copy('app/ViewModels/MainViewModel.ts', 'app/ViewModels/MainViewModel.ts');
        }
    },
    install: {
        typescript: function () {
            var done = this.async();
            this.npmInstall(['typescript'], { 'saveDev': true }, done);
        },
        bower: function () {
            var _this = this;

            var done = this.async();
            var promise = new Promise(function (fulfill, reject) {
                _this.bowerInstall([], fulfill);
            });
            promise
                .then(function () {
                    if (_this.controlsModule)
                        return new Promise(function (fulfill, reject) {
                            _this.bowerInstall(['fayde.controls'], {saveDev: true}, fulfill);
                        });
                })
                .then(function () {
                    if (_this.exjsModule)
                        return new Promise(function (fulfill, reject) {
                            _this.bowerInstall(['exjs'], {saveDev: true}, fulfill);
                        });
                })
                .then(done);
        },
        grunt: function () {
            this.npmInstall();
        }
    }
});

function genScriptInclude(src) {
    return '<script src="' + src + '"></script>\
    ';
}
function genLibShim(libName, libPath, exports) {
    return '\
    <script data-lib="' + libName + '">\
        require.shim["' + libPath + '"] = {\
            exports: "' + exports + '"\
        };\
    </script>';
}<commit_msg>Simplified bower install.<commit_after>var yeoman = require('yeoman-generator'),
    Promise = require('promise');

module.exports = yeoman.generators.Base.extend({
    constructor: function () {
        yeoman.generators.Base.apply(this, arguments);
    },
    prompting: {
        promptName: function () {
            var done = this.async();
            this.prompt({
                type: 'input',
                name: 'name',
                message: 'Your project name',
                default: this.appname // Default to current folder name
            }, function (answers) {
                this.log(answers.name);
                done();
            }.bind(this));
        },
        promptModules: function () {
            var done = this.async();

            var prompts = [
                {
                    type: 'checkbox',
                    name: 'modules',
                    message: 'Which modules would you like to include?',
                    choices: [
                        {
                            value: 'exjsModule',
                            name: 'exjs',
                            checked: true
                        },
                        {
                            value: 'controlsModule',
                            name: 'Fayde.Controls',
                            checked: true
                        }
                    ]
                }
            ];

            this.prompt(prompts, function (props) {
                this.exjsModule = props.modules.exjsModule;
                this.controlsModule = props.modules.controlsModule;
                done();
            }.bind(this));
        }
    },
    configuring: {
        bowerSetup: function () {
            this.copy('_bowerrc', '.bowerrc');
            this.copy('_bower.json', 'bower.json');
        },
        gruntSetup: function () {
            this.copy('_package.json', 'package.json');
            this.copy('_Gruntfile.js', 'Gruntfile.js');
        }
    },
    writing: {
        appFiles: function () {
            var context = {
                exjs_lib: '',
                controls_lib: ''
            };
            if (this.exjsModule)
                context.exjs_lib = genScriptInclude('lib/exjs/dist/ex.min.js');
            if (this.controlsModule)
                context.controls_lib = genLibShim('Fayde.Controls', 'lib/Fayde.Controls/Fayde.Controls', 'Fayde.Controls');

            this.template('app/_default.html', 'app/default.html', context);
            this.copy('app/default.fap', 'app/default.fap');
            this.copy('app/ViewModels/MainViewModel.ts', 'app/ViewModels/MainViewModel.ts');
        }
    },
    install: {
        typescript: function () {
            var done = this.async();
            this.npmInstall(['typescript'], { 'saveDev': true }, done);
        },
        bower: function () {
            var done = this.async();
            var deps = [];
            if (this.controlsModule)
                deps.push('fayde.controls');
            if (this.exjsModule)
                deps.push('exjs');
            this.bowerInstall(deps, { save: true }, done);
        },
        grunt: function () {
            this.npmInstall();
        }
    }
});

function genScriptInclude(src) {
    return '<script src="' + src + '"></script>\
    ';
}
function genLibShim(libName, libPath, exports) {
    return '\
    <script data-lib="' + libName + '">\
        require.shim["' + libPath + '"] = {\
            exports: "' + exports + '"\
        };\
    </script>';
}<|endoftext|>


<commit_before>'use strict';

//
//  Yeoman bat app generator.
//

var generators      = require( 'yeoman-generator' )
,   yosay           = require( 'yosay' )
,   youtil          = require( './../../lib/youtil.js' )
,   mkdirp          = require( 'mkdirp' )
,   _               = require( 'lodash' )
;

var clean           = require( 'underscore.string/clean' );

//  Use different delimiters when our template itself is meant to be a template or template-like.
//
var tpl_tpl_settings =
        {
            evaluate:       /#%([\s\S]+?)%#/g
        ,   escape:         /#-([\s\S]+?)-#/g

        //  Not (yet) used:
        //
        ,   interpolate:    null
        }
;

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

            this.argument(
                'packageName'
            ,   {
                    type:           String
                ,   required:       false
                ,   desc:           'The package name of the webapp to create.'
                ,   defaults:       this.appname
                }
            );
        }

    ,   initializing: function ()
        {
            //  Load the BAT generator's 'package.json'.
            //
            this.pkg = require( './../../package.json' );

            //  Container for template expansion data.
            //
            this.templateData = {};
        }

    ,   prompting:
        {
            askSomeQuestions: function ()
            {
                /* jshint laxbreak: true */

                var done = this.async();

                //  Have Yeoman greet the user.
                //
                this.log( yosay(
                    'Welcome to the BAT generator! (Backbone Application Template)\n'
                +   'Powered by marviq'
                ));

                //  Ask the user for the webapp details.
                //
                var prompts = [
                    {
                        name:       'packageName'
                    ,   message:    'What is the package name of this webapp?'
                    ,   default:    this.packageName
                    ,   validate:   youtil.isNpmName
                    }
                ,   {
                        name:       'packageDescription'
                    ,   message:    'What is the purpose (description) of this webapp?'
                    ,   validate:   youtil.isNonBlank
                    ,   filter:     youtil.sentencify
                    }
                ,   {
                        name:       'authorName'
                    ,   message:    'What is your name?'
                    ,   default:    this.user.git.name()
                    ,   validate:   youtil.isNonBlank
                    ,   filter:     clean
                    }
                ,   {
                        name:       'authorEmail'
                    ,   message:    'What is your email address?'
                    ,   default:    this.user.git.email()
                    ,   validate:   youtil.isNonBlank
                    ,   filter:     _.trim
                    }
                ,   {
                        name:       'authorUrl'
                    ,   message:    'If any, by what URL would you like to be known?'
                    ,   default:    ''
                    ,   filter:     _.trim
                    }
                ,   {
                        name:       'multiLanguage'
                    ,   type:       'confirm'
                    ,   message:    'Do you need multi language support?'
                    ,   default:    false
                    }
                ,   {
                        name:       'ie8'
                    ,   type:       'confirm'
                    ,   message:    'Do you need IE8 and lower support? (affects the jQuery version and shims HTML5 and media query support)'
                    ,   default:    false
                    }
                ,   {
                        name:       'demo'
                    ,   type:       'confirm'
                    ,   message:    'Do you want the demo app?'
                    ,   default:    true
                    }
                ];

                this.prompt(
                    prompts
                ,   function ( answers )
                    {
                        _.extend( this.templateData, answers );

                        done();

                    }.bind( this )
                );
            }
        }

    ,   configuring: function ()
        {
            var data    = this.templateData;

            data.i18n   = data.multiLanguage || data.demo;

            //
            //  Save a '.yo-rc.json' config file.
            //  At the very least this marks your project root for sub-generators.
            //
            //  Note that answers to prompts that have `store: true` defined aren't stored here, but in '~/.yo-rc-global.json'.
            //

            this.config.set(
                {
                    'generator-version':    this.pkg.version
                }
            );
        }

    ,   writing:
        {
            setupDirectoryStructure: function ()
            {
                var data    = this.templateData
                ,   layout  =
                    [
                        //  App source:

                        'src'

                        //  Backbone:

                    ,   'src/collections'
                    ,   'src/models'
                    ,   'src/views'

                        //  Style and Compass:

                    ,   'src/sass'

                    ,   'src/style'
                    ,   'src/style/images/'
                    ,   'src/style/images/sprites/'

                        //  Testing:

                    ,   'test'

                        //  Third-party, external libraries:

                    ,   'vendor'
                    ]
                ;

                //  Location for 'i' + 'nternationalisatio'.length + 'n' definitions:
                //
                //  https://github.com/marviq/madlib-locale#readme
                //

                if ( data.i18n )
                {
                    layout.push( 'src/i18n' );
                }

                for ( var i=0, l=layout.length; i < l ; i++ )
                {
                    mkdirp.sync( this.destinationPath( layout[ i ] ));
                }
            }

        ,   setupProjectFiles: function()
            {
                var data = this.templateData;

                // Setup the config files for git, editor etc.
                //
                this.copy( '@.editorconfig',    '.editorconfig' );
                this.copy( '@.gitattributes',   '.gitattributes' );
                this.copy( '@.gitignore',       '.gitignore' );
                this.copy( '@coffeelint.json',  'coffeelint.json' );
                this.copy( '@.jshintrc',        '.jshintrc' );

                // write package.json and readme file
                //
                this.template( '@package.json',     'package.json', data );
                this.template( '@AUTHORS',          'AUTHORS', data );
                this.template( '@README.md',        'README.md', data );
                this.copy( '@LICENSE',              'LICENSE' );

                // Setup build, watch files etc
                //
                this.template( '@Gruntfile.coffee', 'Gruntfile.coffee', data, tpl_tpl_settings );

                // Setup the sass files
                //
                this.copy( 'src/sass/app.sass',             'src/sass/app.sass' );
                this.copy( 'src/sass/_settings.sass',       'src/sass/_settings.sass' );
                this.copy( 'src/sass/_views.sass',          'src/sass/_views.sass' );
                this.copy( 'src/style/images/sprites/check-green.png',      'src/style/images/sprites/check-green.png' );

                // If we want the demo copy the demo files
                //
                if ( data.demo )
                {
                    this.copy( 'demo/router.coffee',                'src/router.coffee' );
                    this.template( 'demo/index.template.html',      'src/index.template.html', data, tpl_tpl_settings );

                    this.copy( 'demo/views/buildscript.hbs',        'src/views/buildscript.hbs' );
                    this.copy( 'demo/views/buildscript.coffee',     'src/views/buildscript.coffee' );

                    this.copy( 'demo/views/documentation.hbs',      'src/views/documentation.hbs' );
                    this.copy( 'demo/views/documentation.coffee',   'src/views/documentation.coffee' );

                    this.copy( 'demo/views/i18n.hbs',               'src/views/i18n.hbs' );
                    this.copy( 'demo/views/i18n.coffee',            'src/views/i18n.coffee' );

                    this.copy( 'demo/views/index.hbs',              'src/views/index.hbs' );
                    this.copy( 'demo/views/index.coffee',           'src/views/index.coffee' );
                    this.copy( 'demo/sass/views/_index.sass',       'src/sass/views/_index.sass' );

                    this.copy( 'demo/views/navigation.hbs',         'src/views/navigation.hbs' );
                    this.copy( 'demo/views/navigation.coffee',      'src/views/navigation.coffee' );

                    this.copy( 'demo/style/images/marviq-logo-web.png', 'src/style/images/marviq-logo-web.png' );
                    this.copy( 'demo/style/images/documentation.jpg', 'src/style/images/documenting.jpg' );

                    // Copy the i18n files
                    //
                    this.copy( 'demo/i18n/nl_NL.json',              'src/i18n/nl_NL.json' );
                    this.copy( 'demo/i18n/en_GB.json',              'src/i18n/en_GB.json' );

                    // Copy the app main entry point
                    //
                    this.template( 'demo/app.coffee',               'src/app.coffee', data );

                    // Copy the test example files
                    //
                    this.copy( 'demo/models/example.coffee', 'src/models/example.coffee' );
                    this.copy( 'demo/test/example.coffee',  'test/example.coffee' );
                }
                else
                {
                    if ( data.i18n )
                    {
                        // Copy the i18n files
                        //
                        this.copy( 'src/i18n/nl_NL.json',  'src/i18n/nl_NL.json' );
                        this.copy( 'src/i18n/en_GB.json',  'src/i18n/en_GB.json' );
                    }

                    this.template( 'src/index.template.html',       'src/index.template.html', data, tpl_tpl_settings );
                    this.template( 'src/router.coffee',             'src/router.coffee', data );

                    this.copy( 'src/views/index.coffee',            'src/views/index.coffee' );
                    this.copy( 'src/views/index.hbs',               'src/views/index.hbs' );
                    this.copy( 'src/sass/views/_index.sass',        'src/sass/views/_index.sass' );

                    // Copy the app main entry point
                    //
                    this.template( 'src/app.coffee',                'src/app.coffee', data );
                }
            }
        }

    ,   install: function ()
        {
            var data = this.templateData
            ,   deps =
                    [
                        'backbone'
                    ,   ( 'jquery' + ( data.ie8 ? '@<2' : '' ))
                    ,   'madlib-console'
                    ,   'madlib-hostmapping'
                    ,   'madlib-settings'
                    ,   'q'
                    ,   'underscore'
                    ]
            ,   devDeps =
                    [
                        'browserify'
                    ,   'browserify-shim'
                    ,   'chai'
                    ,   'coffeeify'
                    ,   'grunt'
                    ,   'grunt-browserify'
                    ,   'grunt-coffee-jshint'
                    ,   'grunt-coffeelint'
                    ,   'grunt-contrib-clean'
                    ,   'grunt-contrib-compass'
                    ,   'grunt-contrib-compress'
                    ,   'grunt-contrib-copy'
                    ,   'grunt-contrib-uglify'
                    ,   'grunt-contrib-watch'
                    ,   'grunt-contrib-yuidoc'
                    ,   'grunt-mocha-test'
                    ,   'grunt-template'
                    ,   'handlebars'
                    ,   'hbsfy'
                    ]
            ;

            if ( data.i18n )
            {
                deps.push( 'madlib-locale' );
            }

            this.npmInstall( deps,      { save:     true } );
            this.npmInstall( devDeps,   { saveDev:  true } );

            //  Merely cause the "I'm all done. Running 'npm install' for you to ..." message to be outputted.
            //  Because of the `.npmInstal()`s above, setting 'skipInstall' to `true` here would do nothing to prevent those.
            //
            this.installDependencies(
                {
                    bower:          false
                ,   npm:            true
                ,   skipInstall:    false
                ,   skipMessage:    false
                }
            );
        }
    }
);
<commit_msg>feat(app generator): default demo app install to false<commit_after>'use strict';

//
//  Yeoman bat app generator.
//

var generators      = require( 'yeoman-generator' )
,   yosay           = require( 'yosay' )
,   youtil          = require( './../../lib/youtil.js' )
,   mkdirp          = require( 'mkdirp' )
,   _               = require( 'lodash' )
;

var clean           = require( 'underscore.string/clean' );

//  Use different delimiters when our template itself is meant to be a template or template-like.
//
var tpl_tpl_settings =
        {
            evaluate:       /#%([\s\S]+?)%#/g
        ,   escape:         /#-([\s\S]+?)-#/g

        //  Not (yet) used:
        //
        ,   interpolate:    null
        }
;

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

            this.argument(
                'packageName'
            ,   {
                    type:           String
                ,   required:       false
                ,   desc:           'The package name of the webapp to create.'
                ,   defaults:       this.appname
                }
            );
        }

    ,   initializing: function ()
        {
            //  Load the BAT generator's 'package.json'.
            //
            this.pkg = require( './../../package.json' );

            //  Container for template expansion data.
            //
            this.templateData = {};
        }

    ,   prompting:
        {
            askSomeQuestions: function ()
            {
                /* jshint laxbreak: true */

                var done = this.async();

                //  Have Yeoman greet the user.
                //
                this.log( yosay(
                    'Welcome to the BAT generator! (Backbone Application Template)\n'
                +   'Powered by marviq'
                ));

                //  Ask the user for the webapp details.
                //
                var prompts = [
                    {
                        name:       'packageName'
                    ,   message:    'What is the package name of this webapp?'
                    ,   default:    this.packageName
                    ,   validate:   youtil.isNpmName
                    }
                ,   {
                        name:       'packageDescription'
                    ,   message:    'What is the purpose (description) of this webapp?'
                    ,   validate:   youtil.isNonBlank
                    ,   filter:     youtil.sentencify
                    }
                ,   {
                        name:       'authorName'
                    ,   message:    'What is your name?'
                    ,   default:    this.user.git.name()
                    ,   validate:   youtil.isNonBlank
                    ,   filter:     clean
                    }
                ,   {
                        name:       'authorEmail'
                    ,   message:    'What is your email address?'
                    ,   default:    this.user.git.email()
                    ,   validate:   youtil.isNonBlank
                    ,   filter:     _.trim
                    }
                ,   {
                        name:       'authorUrl'
                    ,   message:    'If any, by what URL would you like to be known?'
                    ,   default:    ''
                    ,   filter:     _.trim
                    }
                ,   {
                        name:       'multiLanguage'
                    ,   type:       'confirm'
                    ,   message:    'Do you need multi language support?'
                    ,   default:    false
                    }
                ,   {
                        name:       'ie8'
                    ,   type:       'confirm'
                    ,   message:    'Do you need IE8 and lower support? (affects the jQuery version and shims HTML5 and media query support)'
                    ,   default:    false
                    }
                ,   {
                        name:       'demo'
                    ,   type:       'confirm'
                    ,   message:    'Do you want the demo app?'
                    ,   default:    false
                    }
                ];

                this.prompt(
                    prompts
                ,   function ( answers )
                    {
                        _.extend( this.templateData, answers );

                        done();

                    }.bind( this )
                );
            }
        }

    ,   configuring: function ()
        {
            var data    = this.templateData;

            data.i18n   = data.multiLanguage || data.demo;

            //
            //  Save a '.yo-rc.json' config file.
            //  At the very least this marks your project root for sub-generators.
            //
            //  Note that answers to prompts that have `store: true` defined aren't stored here, but in '~/.yo-rc-global.json'.
            //

            this.config.set(
                {
                    'generator-version':    this.pkg.version
                }
            );
        }

    ,   writing:
        {
            setupDirectoryStructure: function ()
            {
                var data    = this.templateData
                ,   layout  =
                    [
                        //  App source:

                        'src'

                        //  Backbone:

                    ,   'src/collections'
                    ,   'src/models'
                    ,   'src/views'

                        //  Style and Compass:

                    ,   'src/sass'

                    ,   'src/style'
                    ,   'src/style/images/'
                    ,   'src/style/images/sprites/'

                        //  Testing:

                    ,   'test'

                        //  Third-party, external libraries:

                    ,   'vendor'
                    ]
                ;

                //  Location for 'i' + 'nternationalisatio'.length + 'n' definitions:
                //
                //  https://github.com/marviq/madlib-locale#readme
                //

                if ( data.i18n )
                {
                    layout.push( 'src/i18n' );
                }

                for ( var i=0, l=layout.length; i < l ; i++ )
                {
                    mkdirp.sync( this.destinationPath( layout[ i ] ));
                }
            }

        ,   setupProjectFiles: function()
            {
                var data = this.templateData;

                // Setup the config files for git, editor etc.
                //
                this.copy( '@.editorconfig',    '.editorconfig' );
                this.copy( '@.gitattributes',   '.gitattributes' );
                this.copy( '@.gitignore',       '.gitignore' );
                this.copy( '@coffeelint.json',  'coffeelint.json' );
                this.copy( '@.jshintrc',        '.jshintrc' );

                // write package.json and readme file
                //
                this.template( '@package.json',     'package.json', data );
                this.template( '@AUTHORS',          'AUTHORS', data );
                this.template( '@README.md',        'README.md', data );
                this.copy( '@LICENSE',              'LICENSE' );

                // Setup build, watch files etc
                //
                this.template( '@Gruntfile.coffee', 'Gruntfile.coffee', data, tpl_tpl_settings );

                // Setup the sass files
                //
                this.copy( 'src/sass/app.sass',             'src/sass/app.sass' );
                this.copy( 'src/sass/_settings.sass',       'src/sass/_settings.sass' );
                this.copy( 'src/sass/_views.sass',          'src/sass/_views.sass' );
                this.copy( 'src/style/images/sprites/check-green.png',      'src/style/images/sprites/check-green.png' );

                // If we want the demo copy the demo files
                //
                if ( data.demo )
                {
                    this.copy( 'demo/router.coffee',                'src/router.coffee' );
                    this.template( 'demo/index.template.html',      'src/index.template.html', data, tpl_tpl_settings );

                    this.copy( 'demo/views/buildscript.hbs',        'src/views/buildscript.hbs' );
                    this.copy( 'demo/views/buildscript.coffee',     'src/views/buildscript.coffee' );

                    this.copy( 'demo/views/documentation.hbs',      'src/views/documentation.hbs' );
                    this.copy( 'demo/views/documentation.coffee',   'src/views/documentation.coffee' );

                    this.copy( 'demo/views/i18n.hbs',               'src/views/i18n.hbs' );
                    this.copy( 'demo/views/i18n.coffee',            'src/views/i18n.coffee' );

                    this.copy( 'demo/views/index.hbs',              'src/views/index.hbs' );
                    this.copy( 'demo/views/index.coffee',           'src/views/index.coffee' );
                    this.copy( 'demo/sass/views/_index.sass',       'src/sass/views/_index.sass' );

                    this.copy( 'demo/views/navigation.hbs',         'src/views/navigation.hbs' );
                    this.copy( 'demo/views/navigation.coffee',      'src/views/navigation.coffee' );

                    this.copy( 'demo/style/images/marviq-logo-web.png', 'src/style/images/marviq-logo-web.png' );
                    this.copy( 'demo/style/images/documentation.jpg', 'src/style/images/documenting.jpg' );

                    // Copy the i18n files
                    //
                    this.copy( 'demo/i18n/nl_NL.json',              'src/i18n/nl_NL.json' );
                    this.copy( 'demo/i18n/en_GB.json',              'src/i18n/en_GB.json' );

                    // Copy the app main entry point
                    //
                    this.template( 'demo/app.coffee',               'src/app.coffee', data );

                    // Copy the test example files
                    //
                    this.copy( 'demo/models/example.coffee', 'src/models/example.coffee' );
                    this.copy( 'demo/test/example.coffee',  'test/example.coffee' );
                }
                else
                {
                    if ( data.i18n )
                    {
                        // Copy the i18n files
                        //
                        this.copy( 'src/i18n/nl_NL.json',  'src/i18n/nl_NL.json' );
                        this.copy( 'src/i18n/en_GB.json',  'src/i18n/en_GB.json' );
                    }

                    this.template( 'src/index.template.html',       'src/index.template.html', data, tpl_tpl_settings );
                    this.template( 'src/router.coffee',             'src/router.coffee', data );

                    this.copy( 'src/views/index.coffee',            'src/views/index.coffee' );
                    this.copy( 'src/views/index.hbs',               'src/views/index.hbs' );
                    this.copy( 'src/sass/views/_index.sass',        'src/sass/views/_index.sass' );

                    // Copy the app main entry point
                    //
                    this.template( 'src/app.coffee',                'src/app.coffee', data );
                }
            }
        }

    ,   install: function ()
        {
            var data = this.templateData
            ,   deps =
                    [
                        'backbone'
                    ,   ( 'jquery' + ( data.ie8 ? '@<2' : '' ))
                    ,   'madlib-console'
                    ,   'madlib-hostmapping'
                    ,   'madlib-settings'
                    ,   'q'
                    ,   'underscore'
                    ]
            ,   devDeps =
                    [
                        'browserify'
                    ,   'browserify-shim'
                    ,   'chai'
                    ,   'coffeeify'
                    ,   'grunt'
                    ,   'grunt-browserify'
                    ,   'grunt-coffee-jshint'
                    ,   'grunt-coffeelint'
                    ,   'grunt-contrib-clean'
                    ,   'grunt-contrib-compass'
                    ,   'grunt-contrib-compress'
                    ,   'grunt-contrib-copy'
                    ,   'grunt-contrib-uglify'
                    ,   'grunt-contrib-watch'
                    ,   'grunt-contrib-yuidoc'
                    ,   'grunt-mocha-test'
                    ,   'grunt-template'
                    ,   'handlebars'
                    ,   'hbsfy'
                    ]
            ;

            if ( data.i18n )
            {
                deps.push( 'madlib-locale' );
            }

            this.npmInstall( deps,      { save:     true } );
            this.npmInstall( devDeps,   { saveDev:  true } );

            //  Merely cause the "I'm all done. Running 'npm install' for you to ..." message to be outputted.
            //  Because of the `.npmInstal()`s above, setting 'skipInstall' to `true` here would do nothing to prevent those.
            //
            this.installDependencies(
                {
                    bower:          false
                ,   npm:            true
                ,   skipInstall:    false
                ,   skipMessage:    false
                }
            );
        }
    }
);
<|endoftext|>


<commit_before><commit_msg>Hide admin panel on event creation<commit_after><|endoftext|>