<commit_before>/**
 * Created by Awesome on 1/30/2016.
 */

    // use strict
'use strict';

// require dependencies
var fs         = require ('fs');
var os         = require ('os');
var glob       = require ('glob');
var path       = require ('path');
var through    = require ('through2');
var browserify = require ('browserify');
var babelify   = require ('babelify');
var source     = require ('vinyl-source-stream');

// require gulp dependencies
var riot       = require ('gulp-riot');
var sass       = require ('gulp-sass');
var chmod      = require ('gulp-chmod');
var watch      = require ('gulp-watch');
var concat     = require ('gulp-concat');
var header     = require ('gulp-header');
var rename     = require ('gulp-rename');
var uglify     = require ('gulp-uglify');
var nodemon    = require ('gulp-nodemon');
var streamify  = require ('gulp-streamify');
var sourcemaps = require ('gulp-sourcemaps');

// import local dependencies
var config     = require ('./config');
var configPipe = require ('./bin/util/gulp.config.pipe');

/**
 * build gulp builder class
 */
class gulpBuilder {
    /**
     * construct gulp builder class
     */
    constructor () {
        // wait time
        this.wait = (config.gulpDelay ? parseInt (config.gulpDelay) : 500);

        // bind variables
        this.gulp = require ('gulp');

        // bind methods
        this._tasks = {
            'sass'   : [
                './bin/bundles/*/resources/scss/**/*.scss',
                './app/bundles/*/resources/scss/**/*.scss'
            ],
            'daemon' : [
                './bin/bundles/*/daemon/**/*Daemon.js',
                './app/bundles/*/daemon/**/*Daemon.js'
            ],
            'config' : [
                './bin/bundles/*/controller/**/*Controller.js',
                './app/bundles/*/controller/**/*Controller.js'
            ],
            'view'   : [
                './bin/bundles/*/view/**/*.hbs',
                './app/bundles/*/view/**/*.hbs'
            ],
            'tag'    : [
                './bin/bundles/*/view/tag/**/*.tag',
                './app/bundles/*/view/tag/**/*.tag'
            ],
            'js'     : [
                './bin/bundles/*/resources/js/**/*.js',
                './app/bundles/*/resources/js/**/*.js'
            ],
            'image'  : [
                './bin/bundles/*/resources/image/**/*',
                './app/bundles/*/resources/image/**/*'
            ]
        };

        // set keys array
        var that     = this;
        var keys     = Object.keys (this._tasks);
        var watchers = [];

        // bind and add gulp task methods
        for (var i = 0; i < keys.length; i++) {
            // set task
            let task = keys[i];
            // bind method
            this[task] = this[task].bind (this);
            // setup task
            this.gulp.task (task, this[task]);
            // setup watch task
            this.gulp.task (task + ':watch', () => {
                watch (that._tasks[task], () => {
                    that.gulp.start (task);
                });
            });
            // add watch task to array
            watchers.push (task + ':watch');
        }

        // add install task
        this.gulp.task ('install', keys);
        // add watch task
        this.gulp.task ('watch', watchers);
        // add dev server task
        this.gulp.task ('dev', () => {
            setTimeout(() => {
                // run nodemon task
                nodemon ({
                    'script' : './app.js',
                    'ext'    : 'js json',
                    'ignore' : [
                        'tags.min.js'
                    ],
                    'delay'  : this.wait,
                    'watch'  : [
                        'cache/'
                    ],
                    'env'    : {
                        'NODE_ENV' : 'development'
                    }
                });

                // loop for watch
                for (var i = 0; i < keys.length; i++) {
                    // set task
                    let task = keys[i];
                    // setup watch task
                    watch (that._tasks[task], () => {
                       that.gulp.start (task);
                    });
                }
            }, that.wait * 2);
        });
        // add default task
        this.gulp.task ('default', [
            'install',
            'dev'
        ]);
    }

    /**
     * sass task
     */
    sass () {
        // set variables
        var that = this;
        var all  = '';

        // grab gulp source for sass
        // do within setTimeout to remove empty files
        setTimeout (() => {
            // create local variables array for sass files
            var sassFiles = [
                './bin/bundles/*/resources/scss/variables.scss',
                './app/bundles/*/resources/scss/variables.scss'
            ];

            // loop config sass files
            if (config.sass && config.sass.length) {
                for (var i = 0; i < config.sass.length; i ++) {
                    sassFiles.push(config.sass[i]);
                }
            }

            // push local bootstrap files
            sassFiles.push('./bin/bundles/*/resources/scss/bootstrap.scss');
            sassFiles.push('./app/bundles/*/resources/scss/bootstrap.scss');

            // run gulp
            this.gulp.src (sassFiles)
                .pipe (through.obj (function (chunk, enc, cb) {
                    // run through callback
                    var type = chunk.path.split('.');
                        type = type[type.length - 1];
                    if (type == 'css') {
                        var prepend = fs.readFileSync(chunk.path, 'utf8');
                        this.push ({
                            'all' : prepend + os.EOL
                        });
                    } else {
                        this.push ({
                            'all' : '@import ".' + chunk.path.replace (__dirname, '').split (path.delimiter).join ('/') + '";' + os.EOL
                        });
                    }

                    // run callback
                    cb (null, chunk);
                }))
                .on ('data', (data) => {
                    if (data.all) {
                        all += data.all;
                    }
                })
                .on ('end', function () {
                // write temp sass file
                fs.writeFile ('./tmp.scss', all, (err) => {
                    if (err) {
                        console.log (err);
                        return;
                    }

                    // pipe temp sass file for sass function
                    that.gulp.src ('./tmp.scss')
                        .pipe (sourcemaps.init ())
                        .pipe (sass ({
                            outputStyle : 'compressed'
                        }))
                        .pipe (rename ('app.min.css'))
                        .pipe (sourcemaps.write ('./www/assets/css'))
                        .pipe (that.gulp.dest ('./www/assets/css'))
                        .on ('end', () => {
                            fs.unlinkSync ('./tmp.scss');
                        });
                });
            });
        }, this.wait);
    }

    /**
     * daemon task
     */
    daemon () {
        // grab daemon controllers
        var daemons = [];
        for (var i = 0; i < this._tasks.daemon.length; i++) {
            daemons = daemons.concat (glob.sync (this._tasks.daemon[i]));
        }

        // loop daemons
        for (var key in daemons) {
            daemons[key] = daemons[key].replace ('./', '/');
        }

        // write daemons cache file
        this._write ('daemons', daemons);
    }

    /**
     * route task
     */
    config () {
        // set variables
        var that = this;
        var all  = {};

        // get all routes
        // do within setTimeout to remove empty files
        setTimeout (() => {
            this.gulp.src (this._tasks.config)
                .pipe (through.obj (function (chunk, enc, cb) {
                    var pip = this;
                    configPipe.pipe (chunk).then (result => {
                        pip.push ({
                            'result' : result
                        });
                        cb (null, chunk);
                    });
                }))
                .on ('data', (data) => {
                    // merge config object
                    that._merge (all, data.result);
                })
                .on ('end', function () {
                    // write config file
                    that._write ('config', all);
                });
        }, this.wait);
    }

    /**
     * view task
     */
    view () {
        // move views into single folder
        // do within setTimeout to remove empty files
        // @todo bundle priority
        setTimeout (() => {
            this.gulp.src (
                this._tasks.view
            )
                .pipe (rename ((filePath) => {
                    var amended = filePath.dirname.split (path.sep);
                    amended.shift ();
                    amended.shift ();
                    filePath.dirname = amended.join (path.sep);
                }))
                .pipe (chmod (755))
                .pipe (this.gulp.dest ('cache/view'));
        }, this.wait);
    }

    /**
     * tag task
     */
    tag () {
        // set that
        var that = this;

        // move tags into javascript compiled file (riotjs)
        // do within setTimeout to remove empty files
        setTimeout (() => {
            this.gulp.src (
                this._tasks.tag
            )
                .pipe (rename (function (filePath) {
                    var amended = filePath.dirname.split (path.sep);
                    amended.shift ();
                    amended.shift ();
                    amended.shift ();
                    filePath.dirname = amended.join (path.sep);
                }))
                .pipe (riot ({
                    compact : true
                }))
                .pipe (concat ('tags.min.js'))
                .pipe (header ('var riot = require(\'riot\');'))
                .pipe (this.gulp.dest ('./cache/tag'))
                .on ('end', () => {
                    that.gulp.start ('js');
                });
        }, this.wait);
    }

    /**
     * javascript task
     */
    js () {
        // create javascript array
        var js = [];
        js     = js.concat (glob.sync ('./bin/bundles/*/resources/js/bootstrap.js'));
        js     = js.concat (glob.sync ('./app/bundles/*/resources/js/bootstrap.js'));

        // build vendor prepend
        var vendor = '';
        if (config.js && config.js.length) {
            for (var i = 0; i < config.js.length; i++) {
                vendor += fs.readFileSync (config.js[i], 'utf8') + os.EOL;
            }
        }

        // browserfiy javascript
        // do within setTimeout to remove empty files
        setTimeout (() => {
            browserify ({
                entries : js
            })
                .transform (babelify)
                .bundle ()
                .pipe (source ('app.min.js'))
                .pipe (streamify (uglify ()))
                .pipe (streamify (header (vendor)))
                .pipe (this.gulp.dest ('./www/assets/js'));
        }, this.wait);
    }

    /**
     * image task
     */
    image () {
        // move images into single folder
        // do within setTimeout to remove empty files
        // @todo bundle priority
        setTimeout (() => {
            this.gulp.src (
                this._tasks.image
            )
                .pipe (rename ((filePath) => {
                    var amended = filePath.dirname.split (path.sep);
                    amended.shift ();
                    amended.shift ();
                    amended.shift ();
                    filePath.dirname = amended.join (path.sep);
                }))
                .pipe (chmod (755))
                .pipe (this.gulp.dest ('www/image'));
        }, this.wait);
    }

    /**
     * writes config file
     *
     * @param name
     * @param obj
     */
    _write (name, obj) {
        fs.writeFile ('./cache/' + name + '.json', JSON.stringify (obj), function (err) {
            if (err) {
                return console.log (err);
            }
        });
    }

    /**
     * merges two objects
     *
     * @param obj1
     * @param obj2
     * @returns {*}
     * @private
     */
    _merge (obj1, obj2) {
        for (var p in obj2) {
            try {
                // Property in destination object set; update its value.
                if (obj2[p].constructor == Object) {
                    obj1[p] = this._merge (obj1[p], obj2[p]);
                } else {
                    obj1[p] = obj2[p];
                }
            } catch (e) {
                // Property in destination object not set; create it and set its value.
                obj1[p] = obj2[p];
            }
        }

        return obj1;
    }
}

/**
 * export gulp builder class
 *
 * @type {gulpBuilder}
 */
module.exports = new gulpBuilder ();
<commit_msg>refactor gulpfile for actually compiling files<commit_after>/**
 * Created by Awesome on 1/30/2016.
 */

    // use strict
'use strict';

// require dependencies
var fs         = require ('fs');
var os         = require ('os');
var glob       = require ('glob');
var path       = require ('path');
var through    = require ('through2');
var browserify = require ('browserify');
var babelify   = require ('babelify');
var source     = require ('vinyl-source-stream');

// require gulp dependencies
var riot       = require ('gulp-riot');
var sass       = require ('gulp-sass');
var chmod      = require ('gulp-chmod');
var watch      = require ('gulp-watch');
var concat     = require ('gulp-concat');
var header     = require ('gulp-header');
var rename     = require ('gulp-rename');
var uglify     = require ('gulp-uglify');
var nodemon    = require ('gulp-nodemon');
var streamify  = require ('gulp-streamify');
var sourcemaps = require ('gulp-sourcemaps');

// import local dependencies
var config     = require ('./config');
var configPipe = require ('./bin/util/gulp.config.pipe');

/**
 * build gulp builder class
 */
class gulpBuilder {
    /**
     * construct gulp builder class
     */
    constructor () {
        // wait time
        this.wait = (config.gulpDelay ? parseInt (config.gulpDelay) : 500);

        // bind variables
        this.gulp = require ('gulp');

        // bind methods
        this._tasks = {
            'tmp'    : {
                'files' : [
                    './bin/bundles/*/resources/scss/**/*.scss',
                    './app/bundles/*/resources/scss/**/*.scss'
                ],
                'skip' : true
            },
            'sass'   : {
                'files' : [
                    './bin/bundles/*/resources/scss/**/*.scss',
                    './app/bundles/*/resources/scss/**/*.scss'
                ],
                'dependencies' : [
                    'tmp'
                ]
            },
            'daemon' : {
                'files' : [
                    './bin/bundles/*/daemon/**/*Daemon.js',
                    './app/bundles/*/daemon/**/*Daemon.js'
                ],
            },
            'config' : {
                'files' : [
                    './bin/bundles/*/controller/**/*Controller.js',
                    './app/bundles/*/controller/**/*Controller.js'
                ],
            },
            'view'   : {
                'files' : [
                    './bin/bundles/*/view/**/*.hbs',
                    './app/bundles/*/view/**/*.hbs'
                ],
            },
            'tag'    : {
                'files' : [
                    './bin/bundles/*/view/tag/**/*.tag',
                    './app/bundles/*/view/tag/**/*.tag'
                ],
                'skip' : true
            },
            'js'     : {
                'files' : [
                    './bin/bundles/*/resources/js/**/*.js',
                    './app/bundles/*/resources/js/**/*.js'
                ],
                'dependencies' : [
                    'tag'
                ]
            },
            'image'  : {
                'files' : [
                    './bin/bundles/*/resources/image/**/*',
                    './app/bundles/*/resources/image/**/*'
                ]
            }
        };

        // set keys array
        var that     = this;
        var keys     = Object.keys (this._tasks);
        var install  = [];
        var watchers = [];

        // bind and add gulp task methods
        for (var i = 0; i < keys.length; i++) {
            // set task
            let task = keys[i];
            // bind method
            this[task] = this[task].bind (this);
            // setup task
            if (this._tasks[task].dependencies) {
                this.gulp.task (task, this._tasks[task].dependencies, this[task]);
            } else {
                this.gulp.task (task, this[task]);
            }
            // check for skip
            if (this._tasks[task].skip) {
                continue;
            }
            // setup watch task
            this.gulp.task (task + ':watch', () => {
                watch (that._tasks[task].files, () => {
                    that.gulp.start (task);
                });
            });
            // push to install
            install.push (task);
            // add watch task to array
            watchers.push (task + ':watch');
        }

        // add install task
        this.gulp.task ('install', install);
        // add watch task
        this.gulp.task ('watch', watchers);
        // add dev server task
        this.gulp.task ('dev', () => {
            setTimeout(() => {
                // run nodemon task
                nodemon ({
                    'script' : './app.js',
                    'ext'    : 'js json',
                    'ignore' : [
                        'tags.min.js'
                    ],
                    'delay'  : this.wait,
                    'watch'  : [
                        'cache/'
                    ],
                    'env'    : {
                        'NODE_ENV' : 'development'
                    }
                });
            }, that.wait * 2);
        });
        // add default task
        this.gulp.task ('default', [
            'install',
            'watch',
            'dev'
        ]);
    }

    /**
     * creates temporary sass file
     *
     * @return {gulp}
     */
    tmp () {
        // set variables
        var that = this;
        var all  = '';

        // set running
        if (this._sassRunning) {
            return;
        }
        this._sassRunning = true;

        // grab gulp source for sass
        // create local variables array for sass files
        var sassFiles = [
            './bin/bundles/*/resources/scss/variables.scss',
            './app/bundles/*/resources/scss/variables.scss'
        ];

        // loop config sass files
        if (config.sass && config.sass.length) {
            for (var i = 0; i < config.sass.length; i ++) {
                sassFiles.push(config.sass[i]);
            }
        }

        // push local bootstrap files
        sassFiles.push('./bin/bundles/*/resources/scss/bootstrap.scss');
        sassFiles.push('./app/bundles/*/resources/scss/bootstrap.scss');

        // run gulp
        return this.gulp.src (sassFiles)
            .pipe (through.obj (function (chunk, enc, cb) {
                // run through callback
                var type = chunk.path.split('.');
                    type = type[type.length - 1];
                if (type == 'css') {
                    var prepend = fs.readFileSync(chunk.path, 'utf8');
                    this.push ({
                        'all' : prepend + os.EOL
                    });
                } else {
                    this.push ({
                        'all' : '@import ".' + chunk.path.replace (__dirname, '').split (path.delimiter).join ('/') + '";' + os.EOL
                    });
                }

                // run callback
                cb (null, chunk);
            }))
            .on ('data', (data) => {
                if (data.all) {
                    all += data.all;
                }
            })
            .on ('end', function () {
                // write temp sass file
                fs.writeFileSync ('./tmp.scss', all);
            });
    }

    /**
     * sass task
     */
    sass () {
        // set that
        var that = this;

        // check running
        if (this._sassRunning) {
            return;
        }
        this._sassRunning = true;

        // run gulp task
        return this.gulp.src ('./tmp.scss')
            .pipe (sourcemaps.init ())
            .pipe (sass ({
                outputStyle : 'compressed'
            }))
            .pipe (rename ('app.min.css'))
            .pipe (sourcemaps.write ('./www/assets/css'))
            .pipe (that.gulp.dest ('./www/assets/css'))
            .on ('end', () => {
                // unlink temp sass file
                fs.unlinkSync ('./tmp.scss');

                // reset running
                that._sassRunning = false;
            });
    }

    /**
     * daemon task
     */
    daemon () {
        // grab daemon controllers
        var daemons = [];
        for (var i = 0; i < this._tasks.daemon.files.length; i++) {
            daemons = daemons.concat (glob.sync (this._tasks.daemon.files[i]));
        }

        // loop daemons
        for (var key in daemons) {
            daemons[key] = daemons[key].replace ('./', '/');
        }

        // write daemons cache file
        this._write ('daemons', daemons);
    }

    /**
     * route task
     */
    config () {
        // set variables
        var that = this;
        var all  = {};

        // set running
        if (this._configRunning) {
            return;
        }
        this._configRunning = true;

        // get all routes
        // do within setTimeout to remove empty files
        return this.gulp.src (this._tasks.config.files)
            .pipe (through.obj (function (chunk, enc, cb) {
                var pip = this;
                configPipe.pipe (chunk).then (result => {
                    pip.push ({
                        'result' : result
                    });
                    cb (null, chunk);
                });
            }))
            .on ('data', (data) => {
                // merge config object
                that._merge (all, data.result);
            })
            .on ('end', function () {
                // write config file
                that._write ('config', all);

                // reset running tag
                that._configRunning = false;
            });
    }

    /**
     * view task
     */
    view () {
        // set that
        var that = this;

        // ensure running only once
        if (this._viewRunning) {
            return;
        }
        this._viewRunning = true;

        // move views into single folder
        // do within setTimeout to remove empty files
        // @todo bundle priority
        return this.gulp.src (this._tasks.view.files)
            .pipe (rename ((filePath) => {
                var amended = filePath.dirname.split (path.sep);
                amended.shift ();
                amended.shift ();
                filePath.dirname = amended.join (path.sep);
            }))
            .pipe (chmod (755))
            .pipe (this.gulp.dest ('cache/view'))
            .on('end', () => {
                // reset view running
                that._viewRunning = false;
            });
    }

    /**
     * tag task
     */
    tag () {
        // set that
        var that = this;

        // ensure running only once
        if (this._tagRunning || this._jsRunning) {
            return;
        }
        this._tagRunning = true;

        // move tags into javascript compiled file (riotjs)
        return this.gulp.src (this._tasks.tag.files)
            .pipe (rename (function (filePath) {
                var amended = filePath.dirname.split (path.sep);
                amended.shift ();
                amended.shift ();
                amended.shift ();
                filePath.dirname = amended.join (path.sep);
            }))
            .pipe (riot ({
                compact : true
            }))
            .pipe (concat ('tags.min.js'))
            .pipe (header ('var riot = require(\'riot\');'))
            .pipe (this.gulp.dest ('./cache/tag'))
            .on ('end', () => {
                // start js task
                that.gulp.start ('js');

                // reset running flag
                that._tagRunning = false;
            });
    }

    /**
     * javascript task
     */
    js () {
        // set that
        var that = this;

        // ensure running only once
        if (this._jsRunning) {
            return;
        }
        this._jsRunning = true;

        // create javascript array
        var js = [];
        js     = js.concat (glob.sync ('./bin/bundles/*/resources/js/bootstrap.js'));
        js     = js.concat (glob.sync ('./app/bundles/*/resources/js/bootstrap.js'));

        // build vendor prepend
        var vendor = '';
        if (config.js && config.js.length) {
            for (var i = 0; i < config.js.length; i++) {
                vendor += fs.readFileSync (config.js[i], 'utf8') + os.EOL;
            }
        }

        // browserfiy javascript
        // do within setTimeout to remove empty files
        return browserify ({
            entries : js
        })
            .transform (babelify)
            .bundle ()
            .pipe (source ('app.min.js'))
            .pipe (streamify (uglify ()))
            .pipe (streamify (header (vendor)))
            .pipe (this.gulp.dest ('./www/assets/js'))
            .on ('end', () => {
                // reset running flag
                that._jsRunning = false;
            });
    }

    /**
     * image task
     */
    image () {
        // move images into single folder
        // do within setTimeout to remove empty files
        // @todo bundle priority
        setTimeout (() => {
            this.gulp.src (this._tasks.image.files)
                .pipe (rename ((filePath) => {
                    var amended = filePath.dirname.split (path.sep);
                    amended.shift ();
                    amended.shift ();
                    amended.shift ();
                    filePath.dirname = amended.join (path.sep);
                }))
                .pipe (chmod (755))
                .pipe (this.gulp.dest ('www/image'));
        }, this.wait);
    }

    /**
     * writes config file
     *
     * @param name
     * @param obj
     */
    _write (name, obj) {
        fs.writeFile ('./cache/' + name + '.json', JSON.stringify (obj), function (err) {
            if (err) {
                return console.log (err);
            }
        });
    }

    /**
     * merges two objects
     *
     * @param obj1
     * @param obj2
     * @returns {*}
     * @private
     */
    _merge (obj1, obj2) {
        for (var p in obj2) {
            try {
                // Property in destination object set; update its value.
                if (obj2[p].constructor == Object) {
                    obj1[p] = this._merge (obj1[p], obj2[p]);
                } else {
                    obj1[p] = obj2[p];
                }
            } catch (e) {
                // Property in destination object not set; create it and set its value.
                obj1[p] = obj2[p];
            }
        }

        return obj1;
    }
}

/**
 * export gulp builder class
 *
 * @type {gulpBuilder}
 */
module.exports = new gulpBuilder ();
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var to5 = require('gulp-6to5');
var watch = require('gulp-watch');
var deploy = require('gulp-gh-pages');
var jshint = require('gulp-jshint');

var options = {
    cacheDir: './tmp'
};

gulp.task('deploy', ['js:lint', 'js:compile'], function () {
    return gulp.src(['./**/*', '!./node_modules/**'])
        .pipe(deploy(options));
});

gulp.task('js:compile', function() {
    return gulp.src('src/**/*.js')
        .pipe(to5())
        .pipe(gulp.dest('dist'));
});

gulp.task('js:lint', function() {
    return gulp.src('./src/**/*.js')
        .pipe(jshint({ esnext: true }))
        .pipe(jshint.reporter('default'));
});

gulp.task('default', function () {
    watch('./src/**/*.js', function () {
        gulp.start('js:lint');
        gulp.start('js:compile');
    });
});
<commit_msg>Add tmp directory to deploy exclude list<commit_after>'use strict';

var gulp = require('gulp');
var to5 = require('gulp-6to5');
var watch = require('gulp-watch');
var deploy = require('gulp-gh-pages');
var jshint = require('gulp-jshint');

var options = {
    cacheDir: './tmp'
};

gulp.task('deploy', ['js:lint', 'js:compile'], function () {
    return gulp.src(['./**/*', '!./node_modules/**', '!./tmp/**'])
        .pipe(deploy(options));
});

gulp.task('js:compile', function() {
    return gulp.src('src/**/*.js')
        .pipe(to5())
        .pipe(gulp.dest('dist'));
});

gulp.task('js:lint', function() {
    return gulp.src('./src/**/*.js')
        .pipe(jshint({ esnext: true }))
        .pipe(jshint.reporter('default'));
});

gulp.task('default', function () {
    watch('./src/**/*.js', function () {
        gulp.start('js:lint');
        gulp.start('js:compile');
    });
});
<|endoftext|>


<commit_before>if(typeof(L) !== 'undefined') {
/**
 * full canvas layer implementation for Leaflet
 */

L.CanvasLayer = L.Class.extend({

  includes: [L.Mixin.Events, L.Mixin.TileLoader],

  options: {
      minZoom: 0,
      maxZoom: 28,
      tileSize: 256,
      subdomains: 'abc',
      errorTileUrl: '',
      attribution: '',
      zoomOffset: 0,
      opacity: 1,
      unloadInvisibleTiles: L.Browser.mobile,
      updateWhenIdle: L.Browser.mobile,
      tileLoader: false // installs tile loading events
  },

  initialize: function (options) {
    var self = this;
    options = options || {};
    //this.project = this._project.bind(this);
    this.render = this.render.bind(this);
    L.Util.setOptions(this, options);
    this._canvas = this._createCanvas();
    this._ctx = this._canvas.getContext('2d');
    var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
                                window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) {
                                    return window.setTimeout(callback, 1000 / 60);
                                };
    this.requestAnimationFrame = requestAnimationFrame;
  },

  _createCanvas: function() {
    var canvas;
    canvas = document.createElement('canvas');
    canvas.style.position = 'absolute';
    canvas.style.top = 0;
    canvas.style.left = 0;
    canvas.style.pointerEvents = "none";
    canvas.style.zIndex = this.options.zIndex || 0;
    var className = 'leaflet-tile-container leaflet-zoom-animated';
    canvas.setAttribute('class', className);
    return canvas;
  },

  onAdd: function (map) {
    this._map = map;
    var tilePane = this._map._panes.tilePane;

    var _container = L.DomUtil.create('div', 'leaflet-layer');

    _container.appendChild(this._canvas);
    tilePane.appendChild(_container);

    this._container = _container;

    map.dragging._draggable.on('predrag', function() {
      var d = map.dragging._draggable;
      L.DomUtil.setPosition(this._canvas, { x: -d._newPos.x, y: -d._newPos.y });
    }, this);

    map.on({ 'viewreset': this._reset }, this);
    map.on('move', this.render, this);
    map.on('resize', this._reset, this);
    map.on({
        'zoomanim': this._animateZoom,
        'zoomend': this._endZoomAnim
    }, this);

    if(this.options.tileLoader) {
      this._initTileLoader();
    }

    this._reset();
  },

  _animateZoom: function (e) {
      if (!this._animating) {
          this._animating = true;
      }

      var back = this._createCanvas();
      back.width = this._canvas.width;
      back.height = this._canvas.height;
      // paint current canvas in back canvas with trasnformation
      var pos = this._canvas._leaflet_pos || { x: 0, y: 0 };
      //back.getContext('2d').drawImage(this._canvas, -pos.x, -pos.y);
      back.getContext('2d').drawImage(this._canvas, 0, 0);
      // hide
      this._container.appendChild(back);
      this._canvas.style.visibility = 'hidden';

      var bg = back,
          transform = L.DomUtil.TRANSFORM,
          initialTransform = e.delta ? L.DomUtil.getTranslateString(e.delta) : bg.style[transform],
          scaleStr = L.DomUtil.getScaleString(e.scale, e.origin);

      //scaleStr = ' scale(' + e.scale + ') ';
      bg.style[transform] = scaleStr;
        bg.style[transform] = e.backwards ?
                scaleStr + ' ' + initialTransform :
                initialTransform + ' ' + scaleStr;
  },

  _endZoomAnim: function () {
      this._animating = false;
      //this._canvas.style.visibility = 'block';
  },

  getCanvas: function() {
    return this._canvas;
  },

  getAttribution: function() {
    return this.options.attribution;
  },

  draw: function() {
    return this._reset();
  },

  onRemove: function (map) {
    this._container.parentNode.removeChild(this._container);
    map.off({
      'viewreset': this._reset,
      'move': this._render,
      'resize': this._reset
      //'zoomanim': this._animateZoom,
      //'zoomend': this._endZoomAnim
    }, this);
  },

  addTo: function (map) {
    map.addLayer(this);
    return this;
  },

  setOpacity: function (opacity) {
    this.options.opacity = opacity;
    this._updateOpacity();
    return this;
  },

  setZIndex: function(zIndex) {
    this._canvas.style.zIndex = zIndex;
  },

  bringToFront: function () {
    return this;
  },

  bringToBack: function () {
    return this;
  },

  _reset: function () {
    var size = this._map.getSize();
    this._canvas.width = size.x;
    this._canvas.height = size.y;
    this.onResize();
    this._render();
  },

  /*
  _project: function(x) {
    var point = this._map.latLngToLayerPoint(new L.LatLng(x[1], x[0]));
    return [point.x, point.y];
  },
  */

  _updateOpacity: function () { },

  _render: function() {
    this.requestAnimationFrame.call(window, this.render);
  },

  // use direct: true if you are inside an animation frame call
  redraw: function(direct) {
    if (direct) {
      this.render();
    } else {
      this._render();
    }
  },

  onResize: function() {
  },

  render: function() {
    throw new Error('render function should be implemented');
  }

});

} //L defined
<commit_msg>animation zoom wip<commit_after>if(typeof(L) !== 'undefined') {
/**
 * full canvas layer implementation for Leaflet
 */

L.CanvasLayer = L.Class.extend({

  includes: [L.Mixin.Events, L.Mixin.TileLoader],

  options: {
      minZoom: 0,
      maxZoom: 28,
      tileSize: 256,
      subdomains: 'abc',
      errorTileUrl: '',
      attribution: '',
      zoomOffset: 0,
      opacity: 1,
      unloadInvisibleTiles: L.Browser.mobile,
      updateWhenIdle: L.Browser.mobile,
      tileLoader: false // installs tile loading events
  },

  initialize: function (options) {
    var self = this;
    options = options || {};
    //this.project = this._project.bind(this);
    this.render = this.render.bind(this);
    L.Util.setOptions(this, options);
    this._canvas = this._createCanvas();
    // backCanvas for zoom animation
    this._backCanvas = this._createCanvas();
    this._ctx = this._canvas.getContext('2d');
    var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
                                window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) {
                                    return window.setTimeout(callback, 1000 / 60);
                                };
    this.requestAnimationFrame = requestAnimationFrame;
  },

  _createCanvas: function() {
    var canvas;
    canvas = document.createElement('canvas');
    canvas.style.position = 'absolute';
    canvas.style.top = 0;
    canvas.style.left = 0;
    canvas.style.pointerEvents = "none";
    canvas.style.zIndex = this.options.zIndex || 0;
    var className = 'leaflet-tile-container leaflet-zoom-animated';
    canvas.setAttribute('class', className);
    return canvas;
  },

  onAdd: function (map) {
    this._map = map;

    // add container with the canvas to the tile pane
    // the container is moved in the oposite direction of the
    // map pane to keep the canvas always in (0, 0)
    var tilePane = this._map._panes.tilePane;
    var _container = L.DomUtil.create('div', 'leaflet-layer');
    _container.appendChild(this._canvas);
    _container.appendChild(this._backCanvas);
    this._backCanvas.style.display = 'none';
    tilePane.appendChild(_container);

    this._container = _container;

    // hack: listen to predrag event launched by dragging to
    // set container in position (0, 0) in screen coordinates
    map.dragging._draggable.on('predrag', function() {
      var d = map.dragging._draggable;
      L.DomUtil.setPosition(this._canvas, { x: -d._newPos.x, y: -d._newPos.y });
    }, this);

    map.on({ 'viewreset': this._reset }, this);
    map.on('move', this.render, this);
    map.on('resize', this._reset, this);
    map.on({
        'zoomanim': this._animateZoom,
        'zoomend': this._endZoomAnim
    }, this);

    if(this.options.tileLoader) {
      this._initTileLoader();
    }

    this._reset();
  },

  _animateZoom: function (e) {
      if (!this._animating) {
          this._animating = true;
      }
      var back = this._backCanvas;

      back.width = this._canvas.width;
      back.height = this._canvas.height;

      // paint current canvas in back canvas with trasnformation
      var pos = this._canvas._leaflet_pos || { x: 0, y: 0 };
      back.getContext('2d').drawImage(this._canvas, 0, 0);

      // hide original
      this._canvas.style.display = 'none';
      back.style.display = 'block';

      var bg = back,
          transform = L.DomUtil.TRANSFORM,
          initialTransform = e.delta ? L.DomUtil.getTranslateString(e.delta) : bg.style[transform],
          scaleStr = L.DomUtil.getScaleString(e.scale, e.origin);

      //scaleStr = ' scale(' + e.scale + ') ';
      bg.style[transform] = scaleStr;
        /*bg.style[transform] = e.backwards ?
                scaleStr + ' ' + initialTransform :
                initialTransform + ' ' + scaleStr;
                */
  },

  _endZoomAnim: function () {
      this._animating = false;
      //this._canvas.style.visibility = 'block';
  },

  getCanvas: function() {
    return this._canvas;
  },

  getAttribution: function() {
    return this.options.attribution;
  },

  draw: function() {
    return this._reset();
  },

  onRemove: function (map) {
    this._container.parentNode.removeChild(this._container);
    map.off({
      'viewreset': this._reset,
      'move': this._render,
      'resize': this._reset,
      'zoomanim': this._animateZoom,
      'zoomend': this._endZoomAnim
    }, this);
  },

  addTo: function (map) {
    map.addLayer(this);
    return this;
  },

  setOpacity: function (opacity) {
    this.options.opacity = opacity;
    this._updateOpacity();
    return this;
  },

  setZIndex: function(zIndex) {
    this._canvas.style.zIndex = zIndex;
  },

  bringToFront: function () {
    return this;
  },

  bringToBack: function () {
    return this;
  },

  _reset: function () {
    var size = this._map.getSize();
    this._canvas.width = size.x;
    this._canvas.height = size.y;
    this.onResize();
    this._render();
  },

  /*
  _project: function(x) {
    var point = this._map.latLngToLayerPoint(new L.LatLng(x[1], x[0]));
    return [point.x, point.y];
  },
  */

  _updateOpacity: function () { },

  _render: function() {
    this.requestAnimationFrame.call(window, this.render);
  },

  // use direct: true if you are inside an animation frame call
  redraw: function(direct) {
    if (direct) {
      this.render();
    } else {
      this._render();
    }
  },

  onResize: function() {
  },

  render: function() {
    throw new Error('render function should be implemented');
  }

});

} //L defined
<|endoftext|>


<commit_before>/**
 * Name: MessageBar
 * Description: A Message Bar Component displayed at the top of screen
 * https://github.com/KBLNY/react-native-message-bar
 */
'use strict';

import React, {Component} from 'react'
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  Animated,
  Dimensions,
  Image,
} from 'react-native';

let windowWidth = Dimensions.get('window').width
let windowHeight = Dimensions.get('window').height

class MessageBar extends Component {

  constructor(props) {
    super(props)

    this.animatedValue = new Animated.Value(0);
    this.notifyAlertHiddenCallback = null;
    this.alertShown = false;
    this.timeoutHide = null;

    this.state = this.getStateByProps(props);
  }

  componentWillReceiveProps(nextProps) {
    this.setNewState(nextProps);
  }

  setNewState(state) {
    // Set the new state, this is triggered when the props of this MessageBar changed
    this.setState(this.getStateByProps(state));

    // Apply the colors of the alert depending on its alertType
    this._applyAlertStylesheet(state.alertType);

    // Override the opposition style position regarding the state position in order to have the alert sticks that position
    this._changeOffsetByPosition(state.position);
  }

  getStateByProps(props) {
    return {
      // Default values, will be overridden
      backgroundColor: '#007bff', // default value : blue
      strokeColor: '#006acd', // default value : blue
      animationTypeTransform: 'SlideFromTop', // default value

      /* Cusomisation of the alert: Title, Message, Icon URL, Alert alertType (error, success, warning, info), Duration for Alert keep shown */
      title: props.title,
      message: props.message,
      avatar: props.avatar,
      alertType: props.alertType || 'info',
      duration: props.duration || 3000,

      /* Hide setters */
      shouldHideAfterDelay: (props.shouldHideAfterDelay == undefined) ? true : props.shouldHideAfterDelay,
      shouldHideOnTap: (props.shouldHideOnTap == undefined) ? true : props.shouldHideOnTap,

      /* Callbacks method on Alert Tapped, on Alert Show, on Alert Hide */
      onTapped: props.onTapped,
      onShow: props.onShow,
      onHide: props.onHide,

      /* Stylesheets */
      stylesheetInfo: props.stylesheetInfo || { backgroundColor: '#007bff', strokeColor: '#006acd' }, // Default are blue colors
      stylesheetSuccess: props.stylesheetSuccess || { backgroundColor: 'darkgreen', strokeColor: '#b40000' }, // Default are Green colors
      stylesheetWarning: props.stylesheetWarning || { backgroundColor: '#ff9c00', strokeColor: '#f29400' }, // Default are orange colors
      stylesheetError: props.stylesheetError || { backgroundColor: '#ff3232', strokeColor: '#FF0000' }, // Default are red colors
      stylesheetExtra: props.stylesheetExtra || { backgroundColor: '#007bff', strokeColor: '#006acd' }, // Default are blue colors, same as info

      /* Duration of the animation */
      durationToShow: props.durationToShow || 350,
      durationToHide: props.durationToHide || 350,

      /* Offset of the View, useful if you have a navigation bar or if you want the alert be shown below another component instead of the top of the screen */
      viewTopOffset: props.viewTopOffset || 0,
      viewBottomOffset: props.viewBottomOffset || 0,
      viewLeftOffset: props.viewLeftOffset || 0,
      viewRightOffset: props.viewRightOffset || 0,

      /* Inset of the view, useful if you want to apply a padding at your alert content */
      viewTopInset: props.viewTopInset || 0,
      viewBottomInset: props.viewBottomInset || 0,
      viewLeftInset: props.viewLeftInset || 0,
      viewRightInset: props.viewRightInset || 0,

      /* Number of Lines for Title and Message */
      titleNumberOfLines: (props.titleNumberOfLines == undefined) ? 1 : props.titleNumberOfLines,
      messageNumberOfLines: (props.messageNumberOfLines == undefined) ? 2 : props.messageNumberOfLines,

      /* Style for the text elements and the avatar */
      titleStyle: props.titleStyle || { color: 'white', fontSize: 18, fontWeight: 'bold' },
      messageStyle: props.messageStyle || { color: 'white', fontSize: 16 },
      avatarStyle: props.avatarStyle || { height: 40, width: 40, borderRadius: 20 },

      /* Position of the alert and Animation Type the alert is shown */
      position: props.position || 'top',
      animationType: props.animationType,
    };
  }

  /*
  * Show the alert
  */
  showMessageBarAlert() {
    // If an alert is already shonw or doesn't have a title or a message, do nothing
    if (this.alertShown || (this.state.title == null && this.state.message == null)) {
      return;
    }

    // Set the data of the alert in the state
    this.alertShown = true;

    // Display the alert by animating it from the top of the screen
    // Auto-Hide it after a delay set in the state
    Animated.timing(this.animatedValue, {
      toValue: 1,
      duration: this.state.durationToShow
    }).start(this._showMessageBarAlertComplete());
  }

  /*
  * Hide the alert after a delay, typically used for auto-hidding
  */
  _showMessageBarAlertComplete() {
    // Execute onShow callback if any
    this._onShow();

    // If the duration is null, do not hide the
    if (this.state.shouldHideAfterDelay) {
      this.timeoutHide = setTimeout(() => {
        this.hideMessageBarAlert();
      }, this.state.duration);
    }
  }

  /*
  * Return true if the MessageBar is currently displayed, otherwise false
  */
  isMessageBarShown() {
    return this.alertShown;
  }

  /*
  * Hide the alert, typically used when user tap the alert
  */
  hideMessageBarAlert() {
    // Hide the alert after a delay set in the state only if the alert is still visible
    if (!this.alertShown) {
      return;
    }

    clearTimeout(this.timeoutHide);

    // Animate the alert to hide it to the top of the screen
    Animated.timing(this.animatedValue, {
      toValue: 0,
      duration: this.state.durationToHide
    }).start(this._hideMessageBarAlertComplete());
  }

  _hideMessageBarAlertComplete() {
    // The alert is not shown anymore
    this.alertShown = false;

    this._notifyAlertHidden();

    // Execute onHide callback if any
    this._onHide();
  }

  /*
  * Callback executed to tell the observer the alert is hidden
  */
  _notifyAlertHidden() {
    if (this.notifyAlertHiddenCallback) {
      this.notifyAlertHiddenCallback();
    }
  }

  /*
  * Callback executed when the user tap the alert
  */
  _alertTapped() {
    // Hide the alert
    if (this.state.shouldHideOnTap) {
      this.hideMessageBarAlert();
    }

    // Execute the callback passed in parameter
    if (this.state.onTapped) {
      this.state.onTapped();
    }
  }

  /*
  * Callback executed when alert is shown
  */
  _onShow() {
    if (this.state.onShow) {
      this.state.onShow();
    }
  }

  /*
  * Callback executed when alert is hidden
  */
  _onHide() {
    if (this.state.onHide) {
      this.state.onHide();
    }
  }

  /*
  * Change the background color and the line stroke color depending on the alertType
  * If the alertType is not recognized, the 'info' one (blue colors) is selected for you
  */
  _applyAlertStylesheet(alertType) {
    // Set the Background color and the line stroke color of the alert depending on its alertType
    // Set to blue-info if no alertType or if the alertType is not recognized

    let backgroundColor;
    let strokeColor;

    switch (alertType) {
      case 'success':
        backgroundColor = this.state.stylesheetSuccess.backgroundColor;
        strokeColor = this.state.stylesheetSuccess.strokeColor;
        break;
      case 'error':
        backgroundColor = this.state.stylesheetError.backgroundColor;
        strokeColor = this.state.stylesheetError.strokeColor;
        break;
      case 'warning':
        backgroundColor = this.state.stylesheetWarning.backgroundColor;
        strokeColor = this.state.stylesheetWarning.strokeColor;
        break;
      case 'info':
        backgroundColor = this.state.stylesheetInfo.backgroundColor;
        strokeColor = this.state.stylesheetInfo.strokeColor;
        break;
      default:
        backgroundColor = this.state.stylesheetExtra.backgroundColor;
        strokeColor = this.state.stylesheetExtra.strokeColor;
        break;
    }

    this.setState({
      backgroundColor: backgroundColor,
      strokeColor: strokeColor
    });
  }

  /*
  * Change view<Position>Offset property depending on the state position
  */
  _changeOffsetByPosition(position) {
    switch (position) {
      case 'top':
        this.setState({
          viewBottomOffset: null
        });
        break;
      case 'bottom':
        this.setState({
          viewTopOffset: null
        });
        break;
      default:
        this.setState({
          viewBottomOffset: null
        });
        break;
    }
  }

  /*
  * Set the animation transformation depending on the chosen animationType, or depending on the state's position if animationType is not overridden
  */
  _apllyAnimationTypeTransformation() {
    let position = this.state.position;
    let animationType = this.state.animationType;

    if (animationType === undefined) {
      if (position === 'bottom') {
        animationType = 'SlideFromBottom';
      } else {
        // Top by default
        animationType = 'SlideFromTop';
      }
    }

    switch (animationType) {
      case 'SlideFromTop':
         var animationY = this.animatedValue.interpolate({
          inputRange: [0, 1],
          outputRange: [-windowHeight, 0]
        });
        this.animationTypeTransform = [{ translateY: animationY }];
        break;
      case 'SlideFromBottom':
         var animationY = this.animatedValue.interpolate({
          inputRange: [0, 1],
          outputRange: [windowHeight, 0]
        });
        this.animationTypeTransform = [{ translateY: animationY }];
        break;
      case 'SlideFromLeft':
         var animationX = this.animatedValue.interpolate({
          inputRange: [0, 1],
          outputRange: [-windowWidth, 0]
        });
        this.animationTypeTransform = [{ translateX: animationX }];
        break;
      case 'SlideFromRight':
         var animationX = this.animatedValue.interpolate({
          inputRange: [0, 1],
          outputRange: [windowWidth, 0]
        });
        this.animationTypeTransform = [{ translateX: animationX }];
        break;
      default:
         var animationY = this.animatedValue.interpolate({
          inputRange: [0, 1],
          outputRange: [-windowHeight, 0]
        });
        this.animationTypeTransform = [{ translateY: animationY }];
        break;
    }
  }

  /*
  * Alert Rendering Methods
  */

  render() {
    // Set the animation transformation depending on the chosen animationType, or depending on the state's position if animationType is not overridden
    this._apllyAnimationTypeTransformation();

    return (
      <Animated.View style={{ transform: this.animationTypeTransform, backgroundColor: this.state.backgroundColor, borderColor: this.state.strokeColor, borderBottomWidth: 1, position: 'absolute', top: this.state.viewTopOffset, bottom: this.state.viewBottomOffset, left: this.state.viewLeftOffset, right: this.state.viewRightOffset, paddingTop: this.state.viewTopInset, paddingBottom: this.state.viewBottomInset, paddingLeft: this.state.viewLeftInset, paddingRight: this.state.viewRightInset }}>
        <TouchableOpacity onPress={()=>{this._alertTapped()}} style={{ flex: 1 }}>
          <View style={{ flex: 1, flexDirection: 'row', alignItems: 'flex-end', padding: 10 }} >
            { this.renderImage() }
            <View style={{ flex: 1, flexDirection: 'column', alignSelf: 'stretch', justifyContent: 'center', marginLeft: 10 }} >
              { this.renderTitle() }
              { this.renderMessage() }
            </View>
          </View>
        </TouchableOpacity>
      </Animated.View>
    );
  }

  renderImage() {
    if (this.state.avatar != null) {
      var imageSource;
      let uri = this.state.avatar;
      if (!!(typeof uri === 'string' && uri.match(/^https?:/))) {
        // this is a network file
        imageSource = { uri: this.state.avatar }
      } else {
        // this is a local file : require('<path/to/my/local/image.extension>')
        imageSource = this.state.avatar
      }

      return (
        <Image source={imageSource} style={this.state.avatarStyle} />
      );
    }
  }

  renderTitle() {
    if (this.state.title != null) {
      return (
        <Text numberOfLines={this.state.titleNumberOfLines} style={this.state.titleStyle}>
          { this.state.title }
        </Text>
      );
    }
  }

  renderMessage() {
    if (this.state.message != null) {
      return (
        <Text numberOfLines={this.state.messageNumberOfLines} style={this.state.messageStyle}>
          { this.state.message }
        </Text>
      );
    }
  }

}

module.exports = MessageBar;
<commit_msg>Fix typo aplly to apply in function name.<commit_after>/**
 * Name: MessageBar
 * Description: A Message Bar Component displayed at the top of screen
 * https://github.com/KBLNY/react-native-message-bar
 */
'use strict';

import React, {Component} from 'react'
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  Animated,
  Dimensions,
  Image,
} from 'react-native';

let windowWidth = Dimensions.get('window').width
let windowHeight = Dimensions.get('window').height

class MessageBar extends Component {

  constructor(props) {
    super(props)

    this.animatedValue = new Animated.Value(0);
    this.notifyAlertHiddenCallback = null;
    this.alertShown = false;
    this.timeoutHide = null;

    this.state = this.getStateByProps(props);
  }

  componentWillReceiveProps(nextProps) {
    this.setNewState(nextProps);
  }

  setNewState(state) {
    // Set the new state, this is triggered when the props of this MessageBar changed
    this.setState(this.getStateByProps(state));

    // Apply the colors of the alert depending on its alertType
    this._applyAlertStylesheet(state.alertType);

    // Override the opposition style position regarding the state position in order to have the alert sticks that position
    this._changeOffsetByPosition(state.position);
  }

  getStateByProps(props) {
    return {
      // Default values, will be overridden
      backgroundColor: '#007bff', // default value : blue
      strokeColor: '#006acd', // default value : blue
      animationTypeTransform: 'SlideFromTop', // default value

      /* Cusomisation of the alert: Title, Message, Icon URL, Alert alertType (error, success, warning, info), Duration for Alert keep shown */
      title: props.title,
      message: props.message,
      avatar: props.avatar,
      alertType: props.alertType || 'info',
      duration: props.duration || 3000,

      /* Hide setters */
      shouldHideAfterDelay: (props.shouldHideAfterDelay == undefined) ? true : props.shouldHideAfterDelay,
      shouldHideOnTap: (props.shouldHideOnTap == undefined) ? true : props.shouldHideOnTap,

      /* Callbacks method on Alert Tapped, on Alert Show, on Alert Hide */
      onTapped: props.onTapped,
      onShow: props.onShow,
      onHide: props.onHide,

      /* Stylesheets */
      stylesheetInfo: props.stylesheetInfo || { backgroundColor: '#007bff', strokeColor: '#006acd' }, // Default are blue colors
      stylesheetSuccess: props.stylesheetSuccess || { backgroundColor: 'darkgreen', strokeColor: '#b40000' }, // Default are Green colors
      stylesheetWarning: props.stylesheetWarning || { backgroundColor: '#ff9c00', strokeColor: '#f29400' }, // Default are orange colors
      stylesheetError: props.stylesheetError || { backgroundColor: '#ff3232', strokeColor: '#FF0000' }, // Default are red colors
      stylesheetExtra: props.stylesheetExtra || { backgroundColor: '#007bff', strokeColor: '#006acd' }, // Default are blue colors, same as info

      /* Duration of the animation */
      durationToShow: props.durationToShow || 350,
      durationToHide: props.durationToHide || 350,

      /* Offset of the View, useful if you have a navigation bar or if you want the alert be shown below another component instead of the top of the screen */
      viewTopOffset: props.viewTopOffset || 0,
      viewBottomOffset: props.viewBottomOffset || 0,
      viewLeftOffset: props.viewLeftOffset || 0,
      viewRightOffset: props.viewRightOffset || 0,

      /* Inset of the view, useful if you want to apply a padding at your alert content */
      viewTopInset: props.viewTopInset || 0,
      viewBottomInset: props.viewBottomInset || 0,
      viewLeftInset: props.viewLeftInset || 0,
      viewRightInset: props.viewRightInset || 0,

      /* Number of Lines for Title and Message */
      titleNumberOfLines: (props.titleNumberOfLines == undefined) ? 1 : props.titleNumberOfLines,
      messageNumberOfLines: (props.messageNumberOfLines == undefined) ? 2 : props.messageNumberOfLines,

      /* Style for the text elements and the avatar */
      titleStyle: props.titleStyle || { color: 'white', fontSize: 18, fontWeight: 'bold' },
      messageStyle: props.messageStyle || { color: 'white', fontSize: 16 },
      avatarStyle: props.avatarStyle || { height: 40, width: 40, borderRadius: 20 },

      /* Position of the alert and Animation Type the alert is shown */
      position: props.position || 'top',
      animationType: props.animationType,
    };
  }

  /*
  * Show the alert
  */
  showMessageBarAlert() {
    // If an alert is already shonw or doesn't have a title or a message, do nothing
    if (this.alertShown || (this.state.title == null && this.state.message == null)) {
      return;
    }

    // Set the data of the alert in the state
    this.alertShown = true;

    // Display the alert by animating it from the top of the screen
    // Auto-Hide it after a delay set in the state
    Animated.timing(this.animatedValue, {
      toValue: 1,
      duration: this.state.durationToShow
    }).start(this._showMessageBarAlertComplete());
  }

  /*
  * Hide the alert after a delay, typically used for auto-hidding
  */
  _showMessageBarAlertComplete() {
    // Execute onShow callback if any
    this._onShow();

    // If the duration is null, do not hide the
    if (this.state.shouldHideAfterDelay) {
      this.timeoutHide = setTimeout(() => {
        this.hideMessageBarAlert();
      }, this.state.duration);
    }
  }

  /*
  * Return true if the MessageBar is currently displayed, otherwise false
  */
  isMessageBarShown() {
    return this.alertShown;
  }

  /*
  * Hide the alert, typically used when user tap the alert
  */
  hideMessageBarAlert() {
    // Hide the alert after a delay set in the state only if the alert is still visible
    if (!this.alertShown) {
      return;
    }

    clearTimeout(this.timeoutHide);

    // Animate the alert to hide it to the top of the screen
    Animated.timing(this.animatedValue, {
      toValue: 0,
      duration: this.state.durationToHide
    }).start(this._hideMessageBarAlertComplete());
  }

  _hideMessageBarAlertComplete() {
    // The alert is not shown anymore
    this.alertShown = false;

    this._notifyAlertHidden();

    // Execute onHide callback if any
    this._onHide();
  }

  /*
  * Callback executed to tell the observer the alert is hidden
  */
  _notifyAlertHidden() {
    if (this.notifyAlertHiddenCallback) {
      this.notifyAlertHiddenCallback();
    }
  }

  /*
  * Callback executed when the user tap the alert
  */
  _alertTapped() {
    // Hide the alert
    if (this.state.shouldHideOnTap) {
      this.hideMessageBarAlert();
    }

    // Execute the callback passed in parameter
    if (this.state.onTapped) {
      this.state.onTapped();
    }
  }

  /*
  * Callback executed when alert is shown
  */
  _onShow() {
    if (this.state.onShow) {
      this.state.onShow();
    }
  }

  /*
  * Callback executed when alert is hidden
  */
  _onHide() {
    if (this.state.onHide) {
      this.state.onHide();
    }
  }

  /*
  * Change the background color and the line stroke color depending on the alertType
  * If the alertType is not recognized, the 'info' one (blue colors) is selected for you
  */
  _applyAlertStylesheet(alertType) {
    // Set the Background color and the line stroke color of the alert depending on its alertType
    // Set to blue-info if no alertType or if the alertType is not recognized

    let backgroundColor;
    let strokeColor;

    switch (alertType) {
      case 'success':
        backgroundColor = this.state.stylesheetSuccess.backgroundColor;
        strokeColor = this.state.stylesheetSuccess.strokeColor;
        break;
      case 'error':
        backgroundColor = this.state.stylesheetError.backgroundColor;
        strokeColor = this.state.stylesheetError.strokeColor;
        break;
      case 'warning':
        backgroundColor = this.state.stylesheetWarning.backgroundColor;
        strokeColor = this.state.stylesheetWarning.strokeColor;
        break;
      case 'info':
        backgroundColor = this.state.stylesheetInfo.backgroundColor;
        strokeColor = this.state.stylesheetInfo.strokeColor;
        break;
      default:
        backgroundColor = this.state.stylesheetExtra.backgroundColor;
        strokeColor = this.state.stylesheetExtra.strokeColor;
        break;
    }

    this.setState({
      backgroundColor: backgroundColor,
      strokeColor: strokeColor
    });
  }

  /*
  * Change view<Position>Offset property depending on the state position
  */
  _changeOffsetByPosition(position) {
    switch (position) {
      case 'top':
        this.setState({
          viewBottomOffset: null
        });
        break;
      case 'bottom':
        this.setState({
          viewTopOffset: null
        });
        break;
      default:
        this.setState({
          viewBottomOffset: null
        });
        break;
    }
  }

  /*
  * Set the animation transformation depending on the chosen animationType, or depending on the state's position if animationType is not overridden
  */
  _applyAnimationTypeTransformation() {
    let position = this.state.position;
    let animationType = this.state.animationType;

    if (animationType === undefined) {
      if (position === 'bottom') {
        animationType = 'SlideFromBottom';
      } else {
        // Top by default
        animationType = 'SlideFromTop';
      }
    }

    switch (animationType) {
      case 'SlideFromTop':
         var animationY = this.animatedValue.interpolate({
          inputRange: [0, 1],
          outputRange: [-windowHeight, 0]
        });
        this.animationTypeTransform = [{ translateY: animationY }];
        break;
      case 'SlideFromBottom':
         var animationY = this.animatedValue.interpolate({
          inputRange: [0, 1],
          outputRange: [windowHeight, 0]
        });
        this.animationTypeTransform = [{ translateY: animationY }];
        break;
      case 'SlideFromLeft':
         var animationX = this.animatedValue.interpolate({
          inputRange: [0, 1],
          outputRange: [-windowWidth, 0]
        });
        this.animationTypeTransform = [{ translateX: animationX }];
        break;
      case 'SlideFromRight':
         var animationX = this.animatedValue.interpolate({
          inputRange: [0, 1],
          outputRange: [windowWidth, 0]
        });
        this.animationTypeTransform = [{ translateX: animationX }];
        break;
      default:
         var animationY = this.animatedValue.interpolate({
          inputRange: [0, 1],
          outputRange: [-windowHeight, 0]
        });
        this.animationTypeTransform = [{ translateY: animationY }];
        break;
    }
  }

  /*
  * Alert Rendering Methods
  */

  render() {
    // Set the animation transformation depending on the chosen animationType, or depending on the state's position if animationType is not overridden
    this._applyAnimationTypeTransformation();

    return (
      <Animated.View style={{ transform: this.animationTypeTransform, backgroundColor: this.state.backgroundColor, borderColor: this.state.strokeColor, borderBottomWidth: 1, position: 'absolute', top: this.state.viewTopOffset, bottom: this.state.viewBottomOffset, left: this.state.viewLeftOffset, right: this.state.viewRightOffset, paddingTop: this.state.viewTopInset, paddingBottom: this.state.viewBottomInset, paddingLeft: this.state.viewLeftInset, paddingRight: this.state.viewRightInset }}>
        <TouchableOpacity onPress={()=>{this._alertTapped()}} style={{ flex: 1 }}>
          <View style={{ flex: 1, flexDirection: 'row', alignItems: 'flex-end', padding: 10 }} >
            { this.renderImage() }
            <View style={{ flex: 1, flexDirection: 'column', alignSelf: 'stretch', justifyContent: 'center', marginLeft: 10 }} >
              { this.renderTitle() }
              { this.renderMessage() }
            </View>
          </View>
        </TouchableOpacity>
      </Animated.View>
    );
  }

  renderImage() {
    if (this.state.avatar != null) {
      var imageSource;
      let uri = this.state.avatar;
      if (!!(typeof uri === 'string' && uri.match(/^https?:/))) {
        // this is a network file
        imageSource = { uri: this.state.avatar }
      } else {
        // this is a local file : require('<path/to/my/local/image.extension>')
        imageSource = this.state.avatar
      }

      return (
        <Image source={imageSource} style={this.state.avatarStyle} />
      );
    }
  }

  renderTitle() {
    if (this.state.title != null) {
      return (
        <Text numberOfLines={this.state.titleNumberOfLines} style={this.state.titleStyle}>
          { this.state.title }
        </Text>
      );
    }
  }

  renderMessage() {
    if (this.state.message != null) {
      return (
        <Text numberOfLines={this.state.messageNumberOfLines} style={this.state.messageStyle}>
          { this.state.message }
        </Text>
      );
    }
  }

}

module.exports = MessageBar;
<|endoftext|>


<commit_before>var gulp = require('gulp');
var babelify = require('babelify');
var browserify = require('browserify');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var source = require('vinyl-source-stream');
var livereload = require('gulp-livereload');
var audiosprite = require('audiosprite');
var glob = require('glob');
var shell = require('gulp-shell');
var fs = require('fs');
var rename = require('gulp-rename');
var connect = require('gulp-connect');

gulp.task('modules', function() {
  browserify({
    entries: './main.js',
    debug: true
  }).transform(babelify)
    .bundle()
    .pipe(source('main.js'))
    .pipe(rename('duckhunt.js'))
    .pipe(gulp.dest('./dist'))
    .pipe(connect.reload());
});

gulp.task('jshint', function() {
  return gulp.src([
    'src/modules/**',
    'duckhunt.js'
  ]).pipe(jshint())
    .pipe(jshint.reporter('default'))
    .pipe(jshint.reporter('fail'))
});

gulp.task('jscs', function() {
  return gulp.src([
    'src/modules/*.js',
    'duckhunt.js'
  ]).pipe(jscs())
});

gulp.task('watch', function() {
  gulp.watch(['./src/modules/*.js', './src/data/*.json', 'main.js', 'libs/*.js'], ['jshint', 'jscs', 'modules']);
  gulp.watch(['./src/assets/images/**/*.png'], ['images']);
  gulp.watch(['./src/assets/sounds/**/*.mp3'], ['audio']);
});

gulp.task('serve', function() {
  connect.server({
    root: 'dist',
    livereload: true
  });
});

gulp.task('audio', function() {
  var files = glob.sync('./src/assets/sounds/*.mp3');
  var outputPath = './dist/audio';
  var opts = {
    output: outputPath,
    path: './',
    format: 'howler',
    'export': 'ogg,mp3',
    loop: ['quacking', 'sniff']
  };

  return audiosprite(files, opts, function(err, obj) {
    if (err) {
      console.error(err);
    }

    return fs.writeFile('./dist/audio' + '.json', JSON.stringify(obj, null, 2));
  });
});

gulp.task('images', function(){
  // There is a texturepacker template for spritesmith but it doesn't work
  // well with complex directory structures, so instead we use the shell
  // checking TexturePacker --version first ensures it bails if TexturePacker
  // isn't installed
  return gulp.src('', {read:false})
    .pipe(shell([
      'TexturePacker --version || echo ERROR: TexturePacker not found, install TexturePacker',
      'TexturePacker --disable-rotation --data dist/sprites.json --format json --sheet dist/sprites.png src/assets/images'
    ]))
    .pipe(connect.reload());
});

gulp.task('deploy', function() {
  return gulp.src('', {read:false})
    .pipe(shell([
    'terraform plan',
    'terraform apply',
    'aws s3 sync dist/ s3://duckhuntjs.com --include \'*\' --acl \'public-read\''
  ]));
});

gulp.task('js', ['jshint', 'jscs', 'modules']);
gulp.task('dev', ['default', 'watch', 'serve']);
gulp.task('default', ['images', 'audio', 'js']);
<commit_msg>Use aws profiles<commit_after>var gulp = require('gulp');
var babelify = require('babelify');
var browserify = require('browserify');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var source = require('vinyl-source-stream');
var livereload = require('gulp-livereload');
var audiosprite = require('audiosprite');
var glob = require('glob');
var shell = require('gulp-shell');
var fs = require('fs');
var rename = require('gulp-rename');
var connect = require('gulp-connect');

gulp.task('modules', function() {
  browserify({
    entries: './main.js',
    debug: true
  }).transform(babelify)
    .bundle()
    .pipe(source('main.js'))
    .pipe(rename('duckhunt.js'))
    .pipe(gulp.dest('./dist'))
    .pipe(connect.reload());
});

gulp.task('jshint', function() {
  return gulp.src([
    'src/modules/**',
    'duckhunt.js'
  ]).pipe(jshint())
    .pipe(jshint.reporter('default'))
    .pipe(jshint.reporter('fail'))
});

gulp.task('jscs', function() {
  return gulp.src([
    'src/modules/*.js',
    'duckhunt.js'
  ]).pipe(jscs())
});

gulp.task('watch', function() {
  gulp.watch(['./src/modules/*.js', './src/data/*.json', 'main.js', 'libs/*.js'], ['jshint', 'jscs', 'modules']);
  gulp.watch(['./src/assets/images/**/*.png'], ['images']);
  gulp.watch(['./src/assets/sounds/**/*.mp3'], ['audio']);
});

gulp.task('serve', function() {
  connect.server({
    root: 'dist',
    livereload: true
  });
});

gulp.task('audio', function() {
  var files = glob.sync('./src/assets/sounds/*.mp3');
  var outputPath = './dist/audio';
  var opts = {
    output: outputPath,
    path: './',
    format: 'howler',
    'export': 'ogg,mp3',
    loop: ['quacking', 'sniff']
  };

  return audiosprite(files, opts, function(err, obj) {
    if (err) {
      console.error(err);
    }

    return fs.writeFile('./dist/audio' + '.json', JSON.stringify(obj, null, 2));
  });
});

gulp.task('images', function(){
  // There is a texturepacker template for spritesmith but it doesn't work
  // well with complex directory structures, so instead we use the shell
  // checking TexturePacker --version first ensures it bails if TexturePacker
  // isn't installed
  return gulp.src('', {read:false})
    .pipe(shell([
      'TexturePacker --version || echo ERROR: TexturePacker not found, install TexturePacker',
      'TexturePacker --disable-rotation --data dist/sprites.json --format json --sheet dist/sprites.png src/assets/images'
    ]))
    .pipe(connect.reload());
});

gulp.task('deploy', function() {
  return gulp.src('', {read:false})
    .pipe(shell([
    'AWS_PROFILE=duckhunt terraform plan',
    'AWS_PROFILE=duckhunt terraform apply',
    'aws --profile duckhunt s3 sync dist/ s3://duckhuntjs.com --include \'*\' --acl \'public-read\''
  ]));
});

gulp.task('js', ['jshint', 'jscs', 'modules']);
gulp.task('dev', ['default', 'watch', 'serve']);
gulp.task('default', ['images', 'audio', 'js']);
<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

const fs = require('fs');
const path = require('path');
const del = require('del');
const gulp = require('gulp');
const mocha = require('gulp-mocha');
const tslint = require('gulp-tslint');
const vsce = require('vsce');
const debugUtil = require('./out/src/coreclr-debug/util');
const debugInstall = require('./out/src/coreclr-debug/install');
const packages = require('./out/src/packages');
const logger = require('./out/src/logger');
const platform = require('./out/src/platform');
const util = require('./out/src/common');
const child_process = require('child_process');
const optionsSchemaGenerator = require('./out/src/tools/GenerateOptionsSchema');
const packageDependencyUpdater = require('./out/src/tools/UpdatePackageDependencies');

const Logger = logger.Logger;
const PackageManager = packages.PackageManager;
const LinuxDistribution = platform.LinuxDistribution;
const PlatformInformation = platform.PlatformInformation;

function cleanSync(deleteVsix) {
    del.sync('install.*');
    del.sync('.omnisharp-*');
    del.sync('.debugger');

    if (deleteVsix) {
        del.sync('*.vsix');
    }
}

gulp.task('clean', () => {
    cleanSync(true);
});

gulp.task('generateOptionsSchema', () => {
    optionsSchemaGenerator.GenerateOptionsSchema();
});

gulp.task('updatePackageDependencies', () => {
    packageDependencyUpdater.updatePackageDependencies();
});

// Install Tasks
function install(platformInfo, packageJSON) {
    const packageManager = new PackageManager(platformInfo, packageJSON);
    const logger = new Logger(message => process.stdout.write(message));
    const debuggerUtil = new debugUtil.CoreClrDebugUtil(path.resolve('.'), logger);
    const debugInstaller = new debugInstall.DebugInstaller(debuggerUtil);

    return packageManager.DownloadPackages(logger)
        .then(() => {
            return packageManager.InstallPackages(logger);
        })
        .then(() => {
            return util.touchInstallFile(util.InstallFileType.Lock)
        })
        .then(() => {
            return debugInstaller.finishInstall();
        });
}

gulp.task('install', ['clean'], () => {
    util.setExtensionPath(__dirname);

    return PlatformInformation.GetCurrent()
        .then(platformInfo => {
            return install(platformInfo, getPackageJSON());
        });
});

/// Packaging (VSIX) Tasks
function doPackageSync(packageName) {

    var vsceArgs = [];
    vsceArgs.push(path.join(__dirname, 'node_modules', 'vsce', 'out', 'vsce'))
    vsceArgs.push('package'); // package command

    if (packageName !== undefined) {
        vsceArgs.push('-o');
        vsceArgs.push(packageName);
    }

    var proc = child_process.spawnSync('node', vsceArgs);
    if (proc.error) {
        console.error(proc.error.toString());
    }
}

function doOfflinePackage(platformInfo, packageName, packageJSON) {
    if (process.platform === 'win32') {
        throw new Error('Do not build offline packages on windows. Runtime executables will not be marked executable in *nix packages.');
    }

    cleanSync(false);
    return install(platformInfo, packageJSON)
        .then(() => {
            doPackageSync(packageName + '-' + platformInfo.runtimeId + '.vsix');
        });
}

function getPackageJSON() {
    return JSON.parse(fs.readFileSync('package.json'));
}

gulp.task('package:clean', () => {
    del.sync('*.vsix');
});

gulp.task('package:online', ['clean'], () => {
    doPackageSync();
});

gulp.task('package:offline', ['clean'], () => {
    util.setExtensionPath(__dirname);

    var packageJSON = getPackageJSON();
    var name = packageJSON.name;
    var version = packageJSON.version;
    var packageName = name + '.' + version;

    var packages = [];
    packages.push(new PlatformInformation('win32', 'x86_64'));
    packages.push(new PlatformInformation('darwin', 'x86_64'));
    packages.push(new PlatformInformation('linux', 'x86_64', new LinuxDistribution('centos', '7')));
    packages.push(new PlatformInformation('linux', 'x86_64', new LinuxDistribution('debian', '8')));
    packages.push(new PlatformInformation('linux', 'x86_64', new LinuxDistribution('fedora', '23')));
    packages.push(new PlatformInformation('linux', 'x86_64', new LinuxDistribution('opensuse', '13.2')));
    packages.push(new PlatformInformation('linux', 'x86_64', new LinuxDistribution('rhel', '7.2')));
    packages.push(new PlatformInformation('linux', 'x86_64', new LinuxDistribution('ubuntu', '14.04')));
    packages.push(new PlatformInformation('linux', 'x86_64', new LinuxDistribution('ubuntu', '16.04')));

    var promise = Promise.resolve();

    packages.forEach(platformInfo => {
        promise = promise
            .then(() => {
                return doOfflinePackage(platformInfo, packageName, packageJSON);
            });
    });

    return promise;
});

/// Misc Tasks
const allTypeScript = [
    'src/**/*.ts',
    '!**/*.d.ts',
    '!**/typings**'
];

const lintReporter = (output, file, options) => {
    //emits: src/helloWorld.c:5:3: warning: implicit declaration of function ‘prinft’
    var relativeBase = file.base.substring(file.cwd.length + 1).replace('\\', '/');
    output.forEach(e => {
        var message = relativeBase + e.name + ':' + (e.startPosition.line + 1) + ':' + (e.startPosition.character + 1) + ': ' + e.failure;
        console.log('[tslint] ' + message);
    });
};

gulp.task('tslint', () => {
    gulp.src(allTypeScript)
        .pipe(tslint({
            program: require('tslint').Linter.createProgram("./tsconfig.json"),
            configuration: "./tslint.json"
        }))
        .pipe(tslint.report(lintReporter, {
            summarizeFailureOutput: false,
            emitError: false
        }))
});
<commit_msg>Removed runtime ids (#1931)<commit_after>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

const fs = require('fs');
const path = require('path');
const del = require('del');
const gulp = require('gulp');
const mocha = require('gulp-mocha');
const tslint = require('gulp-tslint');
const vsce = require('vsce');
const debugUtil = require('./out/src/coreclr-debug/util');
const debugInstall = require('./out/src/coreclr-debug/install');
const packages = require('./out/src/packages');
const logger = require('./out/src/logger');
const platform = require('./out/src/platform');
const util = require('./out/src/common');
const child_process = require('child_process');
const optionsSchemaGenerator = require('./out/src/tools/GenerateOptionsSchema');
const packageDependencyUpdater = require('./out/src/tools/UpdatePackageDependencies');

const Logger = logger.Logger;
const PackageManager = packages.PackageManager;
const LinuxDistribution = platform.LinuxDistribution;
const PlatformInformation = platform.PlatformInformation;

function cleanSync(deleteVsix) {
    del.sync('install.*');
    del.sync('.omnisharp*');
    del.sync('.debugger');

    if (deleteVsix) {
        del.sync('*.vsix');
    }
}

gulp.task('clean', () => {
    cleanSync(true);
});

gulp.task('generateOptionsSchema', () => {
    optionsSchemaGenerator.GenerateOptionsSchema();
});

gulp.task('updatePackageDependencies', () => {
    packageDependencyUpdater.updatePackageDependencies();
});

// Install Tasks
function install(platformInfo, packageJSON) {
    const packageManager = new PackageManager(platformInfo, packageJSON);
    const logger = new Logger(message => process.stdout.write(message));
    const debuggerUtil = new debugUtil.CoreClrDebugUtil(path.resolve('.'), logger);
    const debugInstaller = new debugInstall.DebugInstaller(debuggerUtil);

    return packageManager.DownloadPackages(logger)
        .then(() => {
            return packageManager.InstallPackages(logger);
        })
        .then(() => {
            return util.touchInstallFile(util.InstallFileType.Lock)
        })
        .then(() => {
            return debugInstaller.finishInstall();
        });
}

gulp.task('install', ['clean'], () => {
    util.setExtensionPath(__dirname);

    return PlatformInformation.GetCurrent()
        .then(platformInfo => {
            return install(platformInfo, getPackageJSON());
        });
});

/// Packaging (VSIX) Tasks
function doPackageSync(packageName) {

    var vsceArgs = [];
    vsceArgs.push(path.join(__dirname, 'node_modules', 'vsce', 'out', 'vsce'))
    vsceArgs.push('package'); // package command

    if (packageName !== undefined) {
        vsceArgs.push('-o');
        vsceArgs.push(packageName);
    }

    var proc = child_process.spawnSync('node', vsceArgs);
    if (proc.error) {
        console.error(proc.error.toString());
    }
}

function doOfflinePackage(platformInfo, packageName, packageJSON) {
    if (process.platform === 'win32') {
        throw new Error('Do not build offline packages on windows. Runtime executables will not be marked executable in *nix packages.');
    }

    cleanSync(false);
    return install(platformInfo, packageJSON)
        .then(() => {
            doPackageSync(packageName + '-' + platformInfo.platform + '-' + platformInfo.architecture + '.vsix');
        });
}

function getPackageJSON() {
    return JSON.parse(fs.readFileSync('package.json'));
}

gulp.task('package:clean', () => {
    del.sync('*.vsix');
});

gulp.task('package:online', ['clean'], () => {
    doPackageSync();
});

gulp.task('package:offline', ['clean'], () => {
    util.setExtensionPath(__dirname);

    var packageJSON = getPackageJSON();
    var name = packageJSON.name;
    var version = packageJSON.version;
    var packageName = name + '.' + version;

    var packages = [];
    packages.push(new PlatformInformation('win32', 'x86_64'));
    packages.push(new PlatformInformation('darwin', 'x86_64'));
    packages.push(new PlatformInformation('linux', 'x86_64'));

    var promise = Promise.resolve();

    packages.forEach(platformInfo => {
        promise = promise
            .then(() => {
                return doOfflinePackage(platformInfo, packageName, packageJSON);
            });
    });

    return promise;
});

/// Misc Tasks
const allTypeScript = [
    'src/**/*.ts',
    '!**/*.d.ts',
    '!**/typings**'
];

const lintReporter = (output, file, options) => {
    //emits: src/helloWorld.c:5:3: warning: implicit declaration of function ‘prinft’
    var relativeBase = file.base.substring(file.cwd.length + 1).replace('\\', '/');
    output.forEach(e => {
        var message = relativeBase + e.name + ':' + (e.startPosition.line + 1) + ':' + (e.startPosition.character + 1) + ': ' + e.failure;
        console.log('[tslint] ' + message);
    });
};

gulp.task('tslint', () => {
    gulp.src(allTypeScript)
        .pipe(tslint({
            program: require('tslint').Linter.createProgram("./tsconfig.json"),
            configuration: "./tslint.json"
        }))
        .pipe(tslint.report(lintReporter, {
            summarizeFailureOutput: false,
            emitError: false
        }))
});
<|endoftext|>


<commit_before>/**
 * jKif - 2015
 * truth_tree_base.js
 * @file Base TruthTree Constructor which all TruthTrees call up to on initialization
 * @author Clark Feusier - cfeusier@gmail.com
 * @copyright Copyright (C) Clark Feusier - All Rights Reserved
 */

/**
 *
 * @params {Array} kwBase
 * @constructor
 */
function TruthTreeBase(kwBase) {
  this.kwBase = kwBase || [];
}

TruthTreeBase.prototype = {
  constructor: TruthTreeBase,
  isConsistent: function() {}
};

/**
 *
 * @type {TruthTreeBase}
 */
module.exports = TruthTreeBase;
<commit_msg>Update truth tree base to have open and close stack properties<commit_after>/**
 * jKif - 2015
 * truth_tree_base.js
 * @file Base TruthTree Constructor which all TruthTrees call up to on initialization
 * @author Clark Feusier - cfeusier@gmail.com
 * @copyright Copyright (C) Clark Feusier - All Rights Reserved
 */

/**
 *
 * @params {Array} kwBase
 * @constructor
 */
function TruthTreeBase(kwBase) {
  this.openStacks = {};
  this.closedStacks = {};
}

TruthTreeBase.prototype = {
  constructor: TruthTreeBase,
  isConsistent: function() {}
};

/**
 *
 * @type {TruthTreeBase}
 */
module.exports = TruthTreeBase;
<|endoftext|>


<commit_before>var
gulp = require('gulp'),
fs = require('fs'),
path = require('path'),
uglify = require('gulp-uglify'),
concat = require('gulp-concat'),
slash = require('gulp-slash'),
del = require('del'),
less = require('gulp-less'),
paths =
{
	less: './less/build.less',
	js:
	{
		player:
		[
			'./browser/vendor/gl-matrix.js',
			'./browser/scripts/util.js',
			'./browser/scripts/renderer.js',
			'./browser/scripts/plugin-manager-bundled.js',
			'./browser/scripts/plugin-group.js',
			'./browser/scripts/preset-manager.js',
			'./browser/scripts/connection.js',
			'./browser/scripts/graph.js',
			'./browser/scripts/node.js',
			'./browser/scripts/registers.js',
			'./browser/scripts/core.js',
			'./browser/plugins/*.plugin.js',
			'./browser/scripts/player.js',
			'./browser/scripts/player-run.js'
		]
	}
};

gulp.task('clean:js:plugins', function(cb)
{
	del('./browser/plugins/all.plugins.js', cb);
});

gulp.task('clean:js:player', function(cb)
{
	del('./browser/scripts/player.min.js', cb);
});

gulp.task('clean:less', function(cb)
{
	del('./browser/style/less.css', cb);
});

gulp.task('clean:js', ['clean:js:plugins', 'clean:js:player']);

gulp.task('clean', ['clean:js']);

gulp.task('js:plugins', ['clean:js:plugins'], function()
{
	gulp.src('browser/plugins/*.js')
	.pipe(slash())
	.pipe(uglify())
	.pipe(concat('all.plugins.js'))
	.pipe(gulp.dest('./browser/plugins/'))
});

gulp.task('js:player', ['clean:js:player'], function()
{
	gulp.src(paths.js.player)
	.pipe(slash())
	.pipe(uglify())
	.pipe(concat('player.min.js'))
	.pipe(gulp.dest(path.join(__dirname, 'browser', 'scripts')))
});

gulp.task('js', ['js:plugins', 'js:player']);

gulp.task('less', ['clean:less'], function()
{
	gulp.src(paths.less)
	.pipe(slash())
    .pipe(less({
		paths: [ path.join(__dirname, 'less') ]
    }))
	.pipe(concat('less.css'))
    .pipe(gulp.dest(path.join(__dirname, 'browser', 'style')));
});

gulp.task('watch', ['default'], function() {
	gulp.watch('less/**/*', ['less']);
	gulp.watch(paths.js.player, ['js:player']);
});

gulp.task('default', ['less', 'js']);

<commit_msg>gulpfile: build plugins<commit_after>var
gulp = require('gulp'),
fs = require('fs'),
path = require('path'),
uglify = require('gulp-uglify'),
concat = require('gulp-concat'),
slash = require('gulp-slash'),
del = require('del'),
less = require('gulp-less'),
paths =
{
	less: './less/build.less',
	js:
	{
		plugins: './browser/plugins/*.plugin.js',
		player:
		[
			'./browser/vendor/gl-matrix.js',
			'./browser/scripts/util.js',
			'./browser/scripts/renderer.js',
			'./browser/scripts/plugin-manager-bundled.js',
			'./browser/scripts/plugin-group.js',
			'./browser/scripts/preset-manager.js',
			'./browser/scripts/connection.js',
			'./browser/scripts/graph.js',
			'./browser/scripts/node.js',
			'./browser/scripts/registers.js',
			'./browser/scripts/core.js',
			'./browser/plugins/*.plugin.js',
			'./browser/scripts/player.js',
			'./browser/scripts/player-run.js'
		]
	}
};

gulp.task('clean:js:plugins', function(cb)
{
	del('./browser/plugins/all.plugins.js', cb);
});

gulp.task('clean:js:player', function(cb)
{
	del('./browser/scripts/player.min.js', cb);
});

gulp.task('clean:less', function(cb)
{
	del('./browser/style/less.css', cb);
});

gulp.task('clean:js', ['clean:js:plugins', 'clean:js:player']);

gulp.task('clean', ['clean:js']);

gulp.task('js:plugins', ['clean:js:plugins'], function()
{
	gulp.src('browser/plugins/*.js')
	.pipe(slash())
	.pipe(uglify())
	.pipe(concat('all.plugins.js'))
	.pipe(gulp.dest('./browser/plugins/'))
});

gulp.task('js:player', ['clean:js:player'], function()
{
	gulp.src(paths.js.player)
	.pipe(slash())
	.pipe(uglify())
	.pipe(concat('player.min.js'))
	.pipe(gulp.dest(path.join(__dirname, 'browser', 'scripts')))
});

gulp.task('js', ['js:plugins', 'js:player']);

gulp.task('less', ['clean:less'], function()
{
	gulp.src(paths.less)
	.pipe(slash())
    .pipe(less({
		paths: [ path.join(__dirname, 'less') ]
    }))
	.pipe(concat('less.css'))
    .pipe(gulp.dest(path.join(__dirname, 'browser', 'style')));
});

gulp.task('watch', ['default'], function() {
	gulp.watch('less/**/*', ['less']);
	gulp.watch(paths.js.plugins, ['js:plugins']);
	gulp.watch(paths.js.player, ['js:player']);
});

gulp.task('default', ['less', 'js']);

<|endoftext|>


<commit_before>/* eslint-disable strict, global-strict */
'use strict';

var gulp = require('gulp');

var $ = require('gulp-load-plugins')();
var browserSync = require('browser-sync');
var del = require('del');

// Paths
var appPath = 'app';
var distPath = 'dist';

var paths = {
    app: {
        public: appPath + '/public/**/*',
        templates: appPath + '/**/*.{html,htm}',
        scripts: appPath + '/public/scripts/**/*.js',
        styles: appPath + '/public/styles/**/*.css',
        images: appPath + '/public/img/**/*',
        fonts: appPath + '/public/fonts/*.{eot,svg,ttf,woff}',
        icons: appPath + '/public/icons/*',
        audio: appPath + '/public/audio/*'
    },
    dist: {
        fonts: distPath + '/fonts',
        icons: distPath + '/icons',
        audio: distPath + '/audio',
        imgages: distPath + '/img'
    }
};

// Options

var options = {
    autoprefixer: {
        browsers: [
            '> 2%',
            'last 2 versions',
            'Firefox ESR',
            'ie >= 9'
        ],
        cascade: false
    },
    htmlmin: {
        removeComments: true,
        collapseWhitespace: true
    },
    imagemin: {
        progressive: true,
        svgoPlugins: [
            {removeViewBox: false}
        ],
        use: []
    }
};

// linters

gulp.task('lint', function() {
    return gulp.src('app/**/*.js')
        .pipe($.eslint())
        .pipe($.eslint.format());
});

// clean

gulp.task('clean', function() {
    del([
        distPath + '/*'
    ]);
});

// compile

gulp.task('compile', function() {
    var assets = $.useref.assets();

    return gulp.src(paths.app.html)
        .pipe(assets)
        .pipe($.if('*.js', $.uglify()))
        .pipe($.if('*.css', $.autoprefixer(options.autoprefixer)))
        .pipe($.if('*.css', $.csso()))
        .pipe($.rev())
        .pipe(assets.restore())
        .pipe($.useref())
        .pipe($.revReplace())
        .pipe($.if('*.html', $.htmlmin(options.htmlmin)))
        .pipe(gulp.dest(distPath));
});

gulp.task('img', function() {
    return gulp.src(paths.app.img)
            // .pipe($.imagemin(options.imagemin))
            .pipe(gulp.dest(paths.dist.img));
});

gulp.task('fonts', function() {
    return gulp.src(paths.app.fonts)
        // .pipe($.flatten())
        .pipe(gulp.dest(paths.dist.fonts));
});

gulp.task('icons', function() {
    return gulp.src(paths.app.icons)
        .pipe(gulp.dest(paths.dist.icons));
});

// Browser sync

gulp.task('browser-sync', function() {
    return browserSync({
        server: {
            baseDir: distPath,
            index: 'index.html'
        },
        browser: 'chrome'
    });
});

gulp.task('browser-sync-dev', function() {
    return browserSync({
        server: {
            baseDir: appPath,
            index: 'index.js'
        },
        browser: 'chrome'
    });
});

// run server
gulp.task('server:start', function() {
    $.developServer.listen({path: 'app/index.js'});
});

// restart server
gulp.task('server:restart', function() {
    $.developServer.restart();
});

// Main gulp tasks

// builds all files and runs from dist directory
gulp.task('default', ['lintjs', 'compile', 'img', 'fonts', 'icons', 'audio', 'browser-sync']);

// skips building phase and runs from dist directory
gulp.task('run', ['browser-sync']);

// runs from app directory
gulp.task('dev', function() {
    $.developServer.listen({
        path: 'app/index.js',
        env: {
            NODE_ENV: 'development'
        }
    });

    browserSync.init({
        proxy: 'localhost:8000',
        port: 8080,
        https: false,
        ghostMode: {
            clicks: true,
            forms: true,
            scroll: true
        },
        notify: false, // The small pop-over notifications in the browser are not always needed/wanted.
        open: false // Decide which URL to open automatically when Browsersync starts. Defaults to "local" if none set. Can be true, local, external, ui, ui-external, tunnel or false
    });

    // watch for changes

    // gulp.watch(paths.app.scripts, ['lint', browserSync.reload]);
    gulp.watch(paths.app.public, browserSync.reload);
    // gulp.watch('app/*.js', browserSync.reload);

});
<commit_msg>gulpfile.js: 'gulp dev' task now restarts node server and reloads browser when files change<commit_after>/* eslint-disable strict, global-strict */
'use strict';

var gulp = require('gulp');

var $ = require('gulp-load-plugins')();
var browserSync = require('browser-sync');
var del = require('del');

// Paths
var appPath = 'app';
var distPath = 'dist';

var paths = {
    app: {
        public: appPath + '/public/**/*',
        templates: appPath + '/**/*.{html,htm}',
        scripts: appPath + '/public/scripts/**/*.js',
        styles: appPath + '/public/styles/**/*.css',
        images: appPath + '/public/img/**/*',
        fonts: appPath + '/public/fonts/*.{eot,svg,ttf,woff}',
        icons: appPath + '/public/icons/*',
        audio: appPath + '/public/audio/*'
    },
    dist: {
        fonts: distPath + '/fonts',
        icons: distPath + '/icons',
        audio: distPath + '/audio',
        imgages: distPath + '/img'
    }
};

// Options

var options = {
    autoprefixer: {
        browsers: [
            '> 2%',
            'last 2 versions',
            'Firefox ESR',
            'ie >= 9'
        ],
        cascade: false
    },
    htmlmin: {
        removeComments: true,
        collapseWhitespace: true
    },
    imagemin: {
        progressive: true,
        svgoPlugins: [
            {removeViewBox: false}
        ],
        use: []
    }
};

// linters

gulp.task('lint', function() {
    return gulp.src('app/**/*.js')
        .pipe($.eslint())
        .pipe($.eslint.format());
});

// clean

gulp.task('clean', function() {
    del([
        distPath + '/*'
    ]);
});

// compile

gulp.task('compile', function() {
    var assets = $.useref.assets();

    return gulp.src(paths.app.html)
        .pipe(assets)
        .pipe($.if('*.js', $.uglify()))
        .pipe($.if('*.css', $.autoprefixer(options.autoprefixer)))
        .pipe($.if('*.css', $.csso()))
        .pipe($.rev())
        .pipe(assets.restore())
        .pipe($.useref())
        .pipe($.revReplace())
        .pipe($.if('*.html', $.htmlmin(options.htmlmin)))
        .pipe(gulp.dest(distPath));
});

gulp.task('img', function() {
    return gulp.src(paths.app.img)
            // .pipe($.imagemin(options.imagemin))
            .pipe(gulp.dest(paths.dist.img));
});

gulp.task('fonts', function() {
    return gulp.src(paths.app.fonts)
        // .pipe($.flatten())
        .pipe(gulp.dest(paths.dist.fonts));
});

gulp.task('icons', function() {
    return gulp.src(paths.app.icons)
        .pipe(gulp.dest(paths.dist.icons));
});

// Browser sync

gulp.task('browser-sync', function() {
    return browserSync({
        server: {
            baseDir: distPath,
            index: 'index.html'
        },
        browser: 'chrome'
    });
});

gulp.task('browser-sync-dev', function() {
    return browserSync({
        server: {
            baseDir: appPath,
            index: 'index.js'
        },
        browser: 'chrome'
    });
});

// run server
gulp.task('server:start', function() {
    $.developServer.listen({path: 'app/index.js'});
});

// restart server
gulp.task('server:restart', function() {
    $.developServer.restart();
});

// Main gulp tasks

// builds all files and runs from dist directory
gulp.task('default', ['lintjs', 'compile', 'img', 'fonts', 'icons', 'audio', 'browser-sync']);

// skips building phase and runs from dist directory
gulp.task('run', ['browser-sync']);

// runs from app directory
gulp.task('dev', function() {
    $.developServer.listen({
        path: 'app/index.js',
        env: {
            NODE_ENV: 'development'
        }
    });

    browserSync.init({
        proxy: 'localhost:8000',
        port: 8080,
        https: false,
        ghostMode: {
            clicks: true,
            forms: true,
            scroll: true
        },
        notify: false, // The small pop-over notifications in the browser are not always needed/wanted.
        open: false // Decide which URL to open automatically when Browsersync starts. Defaults to "local" if none set. Can be true, local, external, ui, ui-external, tunnel or false
    });

    // watch for changes

    gulp.watch('app/**/*.{js,html,less}', function() {
        $.developServer.restart();
        browserSync.reload();
    });

});
<|endoftext|>