<commit_before>var gulp = require('gulp');
var clean = require('gulp-clean');
var less = require('gulp-less');
var lessAutoprefix = require('less-plugin-autoprefix');
var gulpStylelint = require('gulp-stylelint');
var browserSync = require('browser-sync').create();
var variablesOutput = require('less-plugin-variables-output');
var concat = require('gulp-concat');
var fileinclude = require('gulp-file-include');
var shell = require('gulp-shell');

var autoprefix = new lessAutoprefix({ browsers: ['IE 11', 'last 2 Safari versions', 'iOS 9.0', 'last 2 Chrome versions', 'Firefox ESR'] });
var exportLessVariablesToJson = new variablesOutput({filename: 'build/skin/less-variables.json'});

//
// Lint less files using stylelint
//
gulp.task('lint', function() {
  return gulp.src('./src/**/*.less')
    .pipe(gulpStylelint({
      failAfterError: false,
      reporters: [
        {formatter: 'string', console: true}
      ]
    }));
});

//
// Build CSS
//
gulp.task('less', function() {
  return gulp.src('./src/less/*.less')
    .pipe(less({
      plugins: [autoprefix, exportLessVariablesToJson]
    }).on('error', function(err) {
      console.error(err.message);
      browserSync.notify(err.message, 5000); // Display error in the browser
      this.emit('end'); // Prevent gulp from catching the error and exiting the watch process
    }))
    .pipe(gulp.dest('./build'))
    .pipe(browserSync.stream());
});

//
// Build HTML
//
gulp.task('buildHtml', function() {
  // Build HTML
  return gulp.src(['./src/demo/**/*.html'])
    .pipe(fileinclude({
      prefix: '@@',
      basepath: '@file'
    }))
    .pipe(gulp.dest('./build'));
});

//
// Copy Files
//
gulp.task('copyFilesA', function() {
  return gulp.src(['./src/demo/styles.css', './src/demo/scripts.js'])
    .pipe(gulp.dest('./build'));
});

gulp.task('copyFilesB', function() {
  return gulp.src(['./src/demo/skin/*.css', './src/demo/skin/*.js'])
    .pipe(gulp.dest('./build/skin'));
});

gulp.task('copyFilesC', function() {
  return gulp.src(['./src/less/theme/**'])
    .pipe(gulp.dest('./build/skin/theme/'));
});

//
// Concat icon packs and copy iconManager
//
gulp.task('setupIconManager', function() {
  return gulp.src([ 'src/demo/iconManager.js', './node_modules/@ephox/oxide-icons-*/dist/js/TinymceIcons.js' ])
    .pipe(concat('iconManager.js'))
    .pipe(gulp.dest('./build'));
});

gulp.task('copyFiles', gulp.series('copyFilesA', 'copyFilesB', 'copyFilesC', 'setupIconManager'));

//
// Browsersync
//
gulp.task('serve', function() {
  browserSync.init({
    server: './build',
    ghostMode: false, // prevent scrolls and clicks between browsers
    open: false // Don't open a browser by default.
  });

  gulp.watch('./src/**/*.less', gulp.series('lint', 'copyFilesC', 'less'));
  gulp.watch('./src/demo/**/*.html', gulp.series('buildHtml', 'copyFiles'));
  gulp.watch(['./src/demo/**/*.css', './src/demo/**/*.js'], gulp.series('buildHtml', 'copyFiles'));
  gulp.watch('./build/**/*.*').on('change', browserSync.reload);
});

//
// clean builds
//
gulp.task('cleanBuild', function () {
  return gulp.src('./build', {
    read: false,
    allowEmpty: true,
  })
  .pipe(clean());
});

const packages = [
  '@ephox/oxide-icons-material',
  '@ephox/oxide-icons-jam'
];
gulp.task('getInternal',
  shell.task('npm install ' + packages.join(' ') + ' --no-save --registry http://nexus:8081/repository/npm-group/')
);

//
// clean tmp
//
gulp.task('cleanTmp', function () {
  return gulp.src('./tmp', {
    read: false,
    allowEmpty: true,
  })
  .pipe(clean());
});

//
// clean all the things
//
gulp.task('clean', gulp.series('cleanBuild', 'cleanTmp'));

//
// Build project and watch LESS file changes
//
gulp.task('build', gulp.series('clean', 'buildHtml', 'lint', 'less', 'copyFiles', 'setupIconManager'));
gulp.task('default', gulp.series('build', 'serve'));
<commit_msg>Added an option to set the background color for the skin tool demos by compiling the skin tool less files in the browser<commit_after>var gulp = require('gulp');
var clean = require('gulp-clean');
var less = require('gulp-less');
var lessAutoprefix = require('less-plugin-autoprefix');
var gulpStylelint = require('gulp-stylelint');
var browserSync = require('browser-sync').create();
var variablesOutput = require('less-plugin-variables-output');
var concat = require('gulp-concat');
var fileinclude = require('gulp-file-include');
var shell = require('gulp-shell');

var autoprefix = new lessAutoprefix({ browsers: ['IE 11', 'last 2 Safari versions', 'iOS 9.0', 'last 2 Chrome versions', 'Firefox ESR'] });
var exportLessVariablesToJson = new variablesOutput({filename: 'build/skin/less-variables.json'});

//
// Lint less files using stylelint
//
gulp.task('lint', function() {
  return gulp.src('./src/less/**/*.less')
    .pipe(gulpStylelint({
      failAfterError: false,
      reporters: [
        {formatter: 'string', console: true}
      ]
    }));
});

//
// Build CSS
//
gulp.task('less', function() {
  return gulp.src('./src/less/*.less')
    .pipe(less({
      plugins: [autoprefix, exportLessVariablesToJson]
    }).on('error', function(err) {
      console.error(err.message);
      browserSync.notify(err.message, 5000); // Display error in the browser
      this.emit('end'); // Prevent gulp from catching the error and exiting the watch process
    }))
    .pipe(gulp.dest('./build'))
    .pipe(browserSync.stream());
});

//
// Build HTML
//
gulp.task('buildHtml', function() {
  // Build HTML
  return gulp.src(['./src/demo/**/*.html'])
    .pipe(fileinclude({
      prefix: '@@',
      basepath: '@file'
    }))
    .pipe(gulp.dest('./build'));
});

//
// Copy Files
//
gulp.task('copyFilesA', function() {
  return gulp.src(['./src/demo/styles.css', './src/demo/scripts.js'])
    .pipe(gulp.dest('./build'));
});

gulp.task('copyFilesB', function() {
  return gulp.src(['./src/demo/skin/*.less', './src/demo/skin/*.css', './src/demo/skin/*.js'])
    .pipe(gulp.dest('./build/skin'));
});

gulp.task('copyFilesC', function() {
  return gulp.src(['./src/less/theme/**'])
    .pipe(gulp.dest('./build/skin/theme/'));
});

//
// Concat icon packs and copy iconManager
//
gulp.task('setupIconManager', function() {
  return gulp.src([ 'src/demo/iconManager.js', './node_modules/@ephox/oxide-icons-*/dist/js/TinymceIcons.js' ])
    .pipe(concat('iconManager.js'))
    .pipe(gulp.dest('./build'));
});

gulp.task('copyFiles', gulp.series('copyFilesA', 'copyFilesB', 'copyFilesC', 'setupIconManager'));

//
// Browsersync
//
gulp.task('serve', function() {
  browserSync.init({
    server: './build',
    ghostMode: false, // prevent scrolls and clicks between browsers
    open: false // Don't open a browser by default.
  });

  gulp.watch('./src/**/*.less', gulp.series('lint', 'copyFilesC', 'less'));
  gulp.watch('./src/demo/**/*.html', gulp.series('buildHtml', 'copyFiles'));
  gulp.watch(['./src/demo/**/*.css', './src/demo/**/*.js'], gulp.series('buildHtml', 'copyFiles'));
  gulp.watch('./build/**/*.*').on('change', browserSync.reload);
});

//
// clean builds
//
gulp.task('cleanBuild', function () {
  return gulp.src('./build', {
    read: false,
    allowEmpty: true,
  })
  .pipe(clean());
});

const packages = [
  '@ephox/oxide-icons-material',
  '@ephox/oxide-icons-jam'
];
gulp.task('getInternal',
  shell.task('npm install ' + packages.join(' ') + ' --no-save --registry http://nexus:8081/repository/npm-group/')
);

//
// clean tmp
//
gulp.task('cleanTmp', function () {
  return gulp.src('./tmp', {
    read: false,
    allowEmpty: true,
  })
  .pipe(clean());
});

//
// clean all the things
//
gulp.task('clean', gulp.series('cleanBuild', 'cleanTmp'));

//
// Build project and watch LESS file changes
//
gulp.task('build', gulp.series('clean', 'buildHtml', 'lint', 'less', 'copyFiles', 'setupIconManager'));
gulp.task('default', gulp.series('build', 'serve'));
<|endoftext|>


<commit_before>var gulp = require('gulp');
var ts = require('gulp-typescript');
var mocha = require('gulp-mocha');
var clean = require('gulp-clean');

var tsProject = ts.createProject('./configurations/typescript.json');

gulp.task('default', ['clean-test']);

gulp.task('trasnpile-source', function () {
    return gulp.src('Source/**/*')
                .pipe(tsProject())
                .js
                .pipe(gulp.dest('distribution'));
});

gulp.task('create-source-definition', ['trasnpile-source'], function () {
    return gulp.src('Source/**/*')
                .pipe(tsProject())
                .dts
                .pipe(gulp.dest('distribution'));
});

gulp.task('build', ['create-source-definition']);

gulp.task('trasnpile-test', ['create-source-definition'], function () {
    return gulp.src('Test/**/*')
                .pipe(tsProject({allowJs: true}))
                .js
                .pipe(gulp.dest('test_transpiled'));
});

gulp.task('run-test', ['trasnpile-test'], function () {
    return gulp.src(['test_transpiled/TestStarter.js'])
               .pipe(mocha());
});

gulp.task('clean-test', ['run-test'], function () {
  return gulp.src('test_transpiled', {read: false})
    .pipe(clean());
});

gulp.task('distribute-source', ['clean-test'], function () {

});<commit_msg>Modifying the gulp task organisation for better CI.<commit_after>var gulp = require('gulp');
var ts = require('gulp-typescript');
var mocha = require('gulp-mocha');
var clean = require('gulp-clean');

var tsProject = ts.createProject('./configurations/typescript.json');

// =========================================================================
//                              Build Tasks
// =========================================================================

gulp.task('trasnpile-source', function () {
    return gulp.src('Source/**/*')
                .pipe(tsProject())
                .js
                .pipe(gulp.dest('distribution'));
});

gulp.task('create-source-definition', ['trasnpile-source'], function () {
    return gulp.src('Source/**/*')
                .pipe(tsProject())
                .dts
                .pipe(gulp.dest('distribution'));
});

gulp.task('build', ['create-source-definition'], function() {
    console.log('=========================================');
    console.log('   Source code and definition builded');
    console.log('=========================================');
});

// =========================================================================
//                              Test Tasks
// =========================================================================

gulp.task('trasnpile-test', function () {
    return gulp.src('Test/**/*')
                .pipe(tsProject({allowJs: true}))
                .js
                .pipe(gulp.dest('test_transpiled'));
});

gulp.task('run-test', ['trasnpile-test'], function () {
    return gulp.src(['test_transpiled/TestStarter.js'])
               .pipe(mocha());
});

gulp.task('clean-test', ['run-test'], function () {
  return gulp.src('test_transpiled', {read: false})
    .pipe(clean());
});

gulp.task('test', ['clean-test'], function() {
    console.log('=========================================');
    console.log('            Test performed');
    console.log('=========================================');
});

<|endoftext|>


<commit_before>jQuery(document).ready(function($) {
	var options = {
		sourceAttr: 	php_vars.ar_sl_sourceAttr,
		overlay: 		(php_vars.ar_sl_overlay == '1') ? true : false,
		spinner: 		(php_vars.ar_sl_spinner == '1') ? true : false,
		nav: 			(php_vars.ar_sl_nav === '1') ? true : false,
		navText:		[php_vars.ar_sl_navtextPrev,php_vars.ar_sl_navtextNext],
		captions:		(php_vars.ar_sl_caption === '1') ? true : false,
		captionSelector:php_vars.ar_sl_captionSelector,
		captionType: 	php_vars.ar_sl_captionType,
		captionsData:	php_vars.ar_sl_captionData,
		captionPosition:php_vars.ar_sl_captionPosition,
		captionDelay:   parseInt(php_vars.ar_sl_captionDelay,10),
		captionClass:   php_vars.ar_sl_captionClass,
		close:			(php_vars.ar_sl_close === '1') ? true : false,
		closeText:		php_vars.ar_sl_closeText,
		showCounter:	(php_vars.ar_sl_showCounter === '1') ? true : false,
	 	fileExt:		(php_vars.ar_sl_fileExt == 'false') ? false : php_vars.ar_sl_fileExt,
	 	animationSpeed:	parseInt(php_vars.ar_sl_animationSpeed,10),
		animationSlide: (php_vars.ar_sl_animationSlide === '1') ? true : false,
	 	preloading:		(php_vars.ar_sl_preloading === '1') ? true : false,
	 	enableKeyboard:	(php_vars.ar_sl_enableKeyboard === '1') ? true : false,
	 	loop:			(php_vars.ar_sl_loop === '1') ? true : false,
		rel:			(php_vars.ar_sl_rel == 'false') ? false : php_vars.ar_sl_rel,
	 	docClose: 	 	(php_vars.ar_sl_docClose === '1') ? true : false,
	 	swipeTolerance: parseInt(php_vars.ar_sl_swipeTolerance,10),
	 	className:		php_vars.ar_sl_className,
	 	widthRatio: 	php_vars.ar_sl_widthRatio,
	 	heightRatio: 	php_vars.ar_sl_heightRatio,
		scaleImageToRatio: php_vars.ar_sl_scaleImageToRatio,
	 	disableRightClick:(php_vars.ar_sl_disableRightClick == '1') ? true : false,
	 	disableScroll:	(php_vars.ar_sl_disableScroll == '1') ? true : false,
		alertError:     (php_vars.ar_sl_alertError == '1') ? true : false,
		alertErrorMessage:php_vars.ar_sl_alertErrorMessage,
		additionalHtml: php_vars.ar_sl_additionalHtml,
		history:		(php_vars.ar_sl_history == '1') ? true : false,
		throttleInterval:parseInt(php_vars.ar_sl_throttleInterval,10),
		doubleTapZoom:	parseInt(php_vars.ar_sl_doubleTapZoom,10),
		maxZoom:		parseInt(php_vars.ar_sl_maxZoom,10),
		htmlClass:		php_vars.ar_sl_htmlClass
	}

	if($('a.simplelightbox ').length ) {
		var simplelightbox = $("a.simplelightbox").simpleLightbox(options);
	}
});<commit_msg>Changed plugin init<commit_after>jQuery(document).ready(function($) {
	var options = {
		sourceAttr: 	php_vars.ar_sl_sourceAttr,
		overlay: 		(php_vars.ar_sl_overlay == '1') ? true : false,
		spinner: 		(php_vars.ar_sl_spinner == '1') ? true : false,
		nav: 			(php_vars.ar_sl_nav === '1') ? true : false,
		navText:		[php_vars.ar_sl_navtextPrev,php_vars.ar_sl_navtextNext],
		captions:		(php_vars.ar_sl_caption === '1') ? true : false,
		captionSelector:php_vars.ar_sl_captionSelector,
		captionType: 	php_vars.ar_sl_captionType,
		captionsData:	php_vars.ar_sl_captionData,
		captionPosition:php_vars.ar_sl_captionPosition,
		captionDelay:   parseInt(php_vars.ar_sl_captionDelay,10),
		captionClass:   php_vars.ar_sl_captionClass,
		close:			(php_vars.ar_sl_close === '1') ? true : false,
		closeText:		php_vars.ar_sl_closeText,
		showCounter:	(php_vars.ar_sl_showCounter === '1') ? true : false,
	 	fileExt:		(php_vars.ar_sl_fileExt == 'false') ? false : php_vars.ar_sl_fileExt,
	 	animationSpeed:	parseInt(php_vars.ar_sl_animationSpeed,10),
		animationSlide: (php_vars.ar_sl_animationSlide === '1') ? true : false,
	 	preloading:		(php_vars.ar_sl_preloading === '1') ? true : false,
	 	enableKeyboard:	(php_vars.ar_sl_enableKeyboard === '1') ? true : false,
	 	loop:			(php_vars.ar_sl_loop === '1') ? true : false,
		rel:			(php_vars.ar_sl_rel == 'false') ? false : php_vars.ar_sl_rel,
	 	docClose: 	 	(php_vars.ar_sl_docClose === '1') ? true : false,
	 	swipeTolerance: parseInt(php_vars.ar_sl_swipeTolerance,10),
	 	className:		php_vars.ar_sl_className,
	 	widthRatio: 	php_vars.ar_sl_widthRatio,
	 	heightRatio: 	php_vars.ar_sl_heightRatio,
		scaleImageToRatio: php_vars.ar_sl_scaleImageToRatio,
	 	disableRightClick:(php_vars.ar_sl_disableRightClick == '1') ? true : false,
	 	disableScroll:	(php_vars.ar_sl_disableScroll == '1') ? true : false,
		alertError:     (php_vars.ar_sl_alertError == '1') ? true : false,
		alertErrorMessage:php_vars.ar_sl_alertErrorMessage,
		additionalHtml: php_vars.ar_sl_additionalHtml,
		history:		(php_vars.ar_sl_history == '1') ? true : false,
		throttleInterval:parseInt(php_vars.ar_sl_throttleInterval,10),
		doubleTapZoom:	parseInt(php_vars.ar_sl_doubleTapZoom,10),
		maxZoom:		parseInt(php_vars.ar_sl_maxZoom,10),
		htmlClass:		php_vars.ar_sl_htmlClass
	}

	if($('a.simplelightbox ').length ) {
		var simplelightbox = new SimpleLightbox('a.simplelightbox', options);
	}
});<|endoftext|>


<commit_before>var gulp = require('gulp');
var gulpCoffee = require('gulp-coffee');

gulp.task('coffee', function(){
  gulp.src('lib/*')
    .pipe(gulpCoffee());
});
<commit_msg>add task to compile Less<commit_after>var gulp = require('gulp');
var gulpCoffee = require('gulp-coffee');
var less = require('gulp-less');

gulp.task('coffee', function(){
  gulp.src('lib/*')
    .pipe(gulpCoffee());
});

gulp.task('less', function(){
  gulp.src('./styles/*.less')
    .pipe(less())
    .pipe(gulp.dest('./mock'));
});

gulp.task('default', function(){
  gulp.watch('styles/*.less', ['less']);
});
<|endoftext|>


<commit_before>var gulp = require("gulp"),
    del = require("del"),
    concat = require("gulp-concat"),
    sourcemaps = require("gulp-sourcemaps"),
    uglify = require("gulp-uglify");

var fileName = "angular-autowrap.js",
    minFileName = "angular-autowrap.min.js";

var getSourceFiles = function(){
    return gulp.src("./src/**/*.js");
};

gulp.task("clean-debug", function(cb){
   return del("./dest/debug/*", cb);
});

gulp.task("clean-release", function(cb){
   return del("./dest/release/*", cb);
});

gulp.task("clean", ["clean-debug", "clean-release"]);

gulp.task("debug", ["clean-debug"], function(){
    return getSourceFiles()
    .pipe(sourcemaps.init())
    .pipe(concat(fileName))
    .pipe(sourcemaps.write("./", {includeContent: false, sourceRoot: "../../src/"}))
    .pipe(gulp.dest("./dest/debug/"));
});

gulp.task("release", ["clean-release"], function(){
    return getSourceFiles()
    .pipe(concat(minFileName))
    .pipe(uglify())
    .pipe(gulp.dest("./dest/release/"));
});

gulp.task("all", ["debug", "release"]);

gulp.task('default', ["all"]);<commit_msg>fixed typo. dest > dist<commit_after>var gulp = require("gulp"),
    del = require("del"),
    concat = require("gulp-concat"),
    sourcemaps = require("gulp-sourcemaps"),
    uglify = require("gulp-uglify");

var fileName = "angular-autowrap.js",
    minFileName = "angular-autowrap.min.js";

var getSourceFiles = function(){
    return gulp.src("./src/**/*.js");
};

gulp.task("clean-debug", function(cb){
   return del("./dist/debug/*", cb);
});

gulp.task("clean-release", function(cb){
   return del("./dist/release/*", cb);
});

gulp.task("clean", ["clean-debug", "clean-release"]);

gulp.task("debug", ["clean-debug"], function(){
    return getSourceFiles()
    .pipe(sourcemaps.init())
    .pipe(concat(fileName))
    .pipe(sourcemaps.write("./", {includeContent: false, sourceRoot: "../../src/"}))
    .pipe(gulp.dest("./dist/debug/"));
});

gulp.task("release", ["clean-release"], function(){
    return getSourceFiles()
    .pipe(concat(minFileName))
    .pipe(uglify())
    .pipe(gulp.dest("./dist/release/"));
});

gulp.task("all", ["debug", "release"]);

gulp.task('default', ["all"]);<|endoftext|>


<commit_before>'use strict';

var Gulp = require('gulp');
var RequireDir = require('require-dir');

// Load Tasks
RequireDir('./tasks');

//  Build task definition
Gulp.task('dev-build', ['fonts', 'images', 'misc', 'styles', 'webpack', 'lint']);
Gulp.task('prod-build', ['dev-build', 'rev']);

Gulp.task('dev', ['dev-build', 'watch', 'nodemon']);
Gulp.task('build', ['prod-build']);

Gulp.task('default', ['dev']);
<commit_msg>Update gulpfile for ES2015<commit_after>'use strict';

const Gulp = require('gulp');
const RequireDir = require('require-dir');

// Load Tasks

RequireDir('./tasks');

//  Build task definition

Gulp.task('dev-build', ['fonts', 'images', 'misc', 'styles', 'webpack', 'lint']);
Gulp.task('prod-build', ['dev-build', 'rev']);

Gulp.task('dev', ['dev-build', 'watch', 'nodemon']);
Gulp.task('build', ['prod-build']);

Gulp.task('default', ['dev']);
<|endoftext|>


<commit_before>"use strict";

var babelify = require("babelify");
var browserify = require("browserify");
var browserSync = require('browser-sync').create();
var changed = require("gulp-changed");
var compass = require("gulp-compass");
var ejs = require("gulp-ejs");
var gulp = require("gulp");
var gutil = require("gulp-util");
var KarmaServer = require("karma").Server;
var notify = require("gulp-notify");
var path = require("path");
var plumber = require("gulp-plumber");
var rename = require("gulp-rename");
var source = require("vinyl-source-stream");
var watchify = require("watchify");

// Parameters
var SRC_DIR = "src";
var DEST_DIR = "build";
var DIRS = {
    fonts: {src: "fonts"},
    html: {src: "html", dest: "", srcPattern: "*.ejs"},
    js: {src: "js"},
    css: {src: "scss", dest: "css", srcPattern: "*.scss"},
    resources: {src: "../node_modules/vivliostyle/resources", dest: "resources"},
    mathjax: {src: "../node_modules/mathjax", dest: "mathjax"}
};
var JS_ENTRIES = {
    production: "main.js",
    development: "main-dev.js"
};
var VIVLIOSTYLE_JS_SRC_DIR = "node_modules/vivliostyle/src";
var HTML_FILENAMES = {
    production: "vivliostyle-viewer.html",
    development: "vivliostyle-viewer-dev.html"
};
var SERVER_START_PATH = "/vivliostyle-ui/build/%viewer-html%#x=/vivliostyle.js/samples/gon/index.html";

// Utility functions
function srcDir(type) {
    return SRC_DIR + "/" + DIRS[type].src;
}
function destDir(type) {
    var dirs = DIRS[type];
    return DEST_DIR + "/" + (typeof dirs.dest === "string" ? dirs.dest : dirs.src);
}
function srcPattern(type) {
    return SRC_DIR + "/" + DIRS[type].src + "/" + (DIRS[type].srcPattern || "**/*");
}
function serverStartPath(development) {
    var name = development ? HTML_FILENAMES.development : HTML_FILENAMES.production;
    return SERVER_START_PATH.replace("%viewer-html%", name);
}

// JS build
function getBrowserify(development, watch) {
    var b = browserify({
        cache: {},
        packageCache: {},
        entries: [srcDir("js") + "/" + (development ? JS_ENTRIES.development : JS_ENTRIES.production)],
        transform: [babelify],
        debug: development
    });
    if (watch) {
        b = watchify(b);
    }
    b.on("log", gutil.log);
    return b;
}
function bundleJs(b, name) {
    return b.bundle()
            .on("error", gutil.log.bind(gutil, "Browserify Error"))
            .pipe(source(name))
            .pipe(gulp.dest(destDir("js")));
}
var b;
var watching = false;
function bundleJsProd() {
    var name = JS_ENTRIES.production;
    return bundleJs(b, name);
}
function bundleJsDev() {
    var name = JS_ENTRIES.development;
    return bundleJs(b, name);
}
gulp.task("build:js", function() {
    b = getBrowserify(false, watching);
    bundleJsProd();
});
gulp.task("build:js-dev", function() {
    b = getBrowserify(true, watching);
    bundleJsDev();
});

// create a task simply copying files
function copyTask(type) {
    var dest = destDir(type);
    return gulp.task("build:" + type, function() {
        return gulp.src(srcPattern(type))
            .pipe(changed(dest))
            .pipe(gulp.dest(dest));
    });
}
copyTask("fonts");
copyTask("resources");
copyTask("mathjax");

// HTML build
function buildHtml(development) {
    return gulp.src(srcPattern("html"))
        .pipe(ejs({development: development}))
        .pipe(plumber({
            errorHandler: notify.onError("Error: <%= error.message %>")
        }))
        .pipe(rename(development ? HTML_FILENAMES.development : HTML_FILENAMES.production))
        .pipe(gulp.dest(destDir("html")));
}
gulp.task("build:html", function() {
    return buildHtml(false);
});
gulp.task("build:html-dev", function() {
    return buildHtml(true);
});

// CSS build
function buildCss(development) {
    return gulp.src(srcPattern("css"))
        .pipe(plumber({
            errorHandler: notify.onError("Error: <%= error.message %>")
        }))
        .pipe(compass({
            config_file: SRC_DIR + "/config.rb",
            css: path.resolve(destDir("css")),
            sass: path.resolve(srcDir("css")),
            environment: development ? "development" : "production"
        }));
}
gulp.task("build:css", function() {
    return buildCss(false);
});
gulp.task("build:css-dev", function() {
    return buildCss(true);
});

// build all
gulp.task("build", [
    "build:js",
    "build:html",
    "build:fonts",
    "build:resources",
    "build:mathjax",
    "build:css"
]);
gulp.task("build-dev", [
    "build:js-dev",
    "build:html-dev",
    "build:fonts",
    "build:resources",
    "build:css-dev"
]);

// watch
gulp.task("start-watching", function() {
    watching = true;
});
gulp.task("watch", ["start-watching", "build"], function() {
    b.on("update", bundleJsProd);
    gulp.watch(srcPattern("html"), ["build:html"]);
    gulp.watch(srcPattern("fonts"), ["build:fonts"]);
    gulp.watch(srcPattern("resources"), ["build:resources"]);
    gulp.watch(srcPattern("css"), ["build:css"]);
});
gulp.task("watch-dev", ["start-watching", "build-dev"], function() {
    b.on("update", bundleJsDev);
    gulp.watch(srcPattern("html"), ["build:html-dev"]);
    gulp.watch(srcPattern("fonts"), ["build:fonts"]);
    gulp.watch(srcPattern("resources"), ["build:resources"]);
    gulp.watch(srcPattern("css"), ["build:css-dev"]);
});

// serve
function serve(development) {
    browserSync.init({
        browser: "google chrome",
        server: {
            baseDir: "../"
        },
        startPath: "/vivliostyle.js/test/files/"
    });
    var target = [DEST_DIR + "/**/*"];
    if (development) {
        target.push(VIVLIOSTYLE_JS_SRC_DIR + "/**/*");
    }
    gulp.watch(target).on("change", browserSync.reload);
}
gulp.task("serve", ["watch"], function() {
    serve(false);
});
gulp.task("serve-dev", ["watch-dev"], function() {
    serve(true);
});

gulp.task("default", ["serve-dev"]);

// test
gulp.task("test-local", function(done) {
    var server = new KarmaServer({
        configFile: process.cwd() + "/test/conf/karma-local.conf"
    }, function(exitStatus) {
        done(exitStatus ? "Some tests failed" : undefined);
    });
    server.start();
});
gulp.task("test-sauce", function(done) {
    var server = new KarmaServer({
        configFile: process.cwd() + "/test/conf/karma-sauce.conf"
    }, function(exitStatus) {
        done(exitStatus ? "Some tests failed" : undefined);
    });
    server.start();
});
<commit_msg>allow running of dev on ubuntu<commit_after>"use strict";

var babelify = require("babelify");
var browserify = require("browserify");
var browserSync = require('browser-sync').create();
var changed = require("gulp-changed");
var compass = require("gulp-compass");
var ejs = require("gulp-ejs");
var gulp = require("gulp");
var gutil = require("gulp-util");
var KarmaServer = require("karma").Server;
var notify = require("gulp-notify");
var path = require("path");
var plumber = require("gulp-plumber");
var rename = require("gulp-rename");
var source = require("vinyl-source-stream");
var watchify = require("watchify");

// Parameters
var SRC_DIR = "src";
var DEST_DIR = "build";
var DIRS = {
    fonts: {src: "fonts"},
    html: {src: "html", dest: "", srcPattern: "*.ejs"},
    js: {src: "js"},
    css: {src: "scss", dest: "css", srcPattern: "*.scss"},
    resources: {src: "../node_modules/vivliostyle/resources", dest: "resources"},
    mathjax: {src: "../node_modules/mathjax", dest: "mathjax"}
};
var JS_ENTRIES = {
    production: "main.js",
    development: "main-dev.js"
};
var VIVLIOSTYLE_JS_SRC_DIR = "node_modules/vivliostyle/src";
var HTML_FILENAMES = {
    production: "vivliostyle-viewer.html",
    development: "vivliostyle-viewer-dev.html"
};
var SERVER_START_PATH = "/vivliostyle-ui/build/%viewer-html%#x=/vivliostyle.js/samples/gon/index.html";

// Utility functions
function srcDir(type) {
    return SRC_DIR + "/" + DIRS[type].src;
}
function destDir(type) {
    var dirs = DIRS[type];
    return DEST_DIR + "/" + (typeof dirs.dest === "string" ? dirs.dest : dirs.src);
}
function srcPattern(type) {
    return SRC_DIR + "/" + DIRS[type].src + "/" + (DIRS[type].srcPattern || "**/*");
}
function serverStartPath(development) {
    var name = development ? HTML_FILENAMES.development : HTML_FILENAMES.production;
    return SERVER_START_PATH.replace("%viewer-html%", name);
}

// JS build
function getBrowserify(development, watch) {
    var b = browserify({
        cache: {},
        packageCache: {},
        entries: [srcDir("js") + "/" + (development ? JS_ENTRIES.development : JS_ENTRIES.production)],
        transform: [babelify],
        debug: development
    });
    if (watch) {
        b = watchify(b);
    }
    b.on("log", gutil.log);
    return b;
}
function bundleJs(b, name) {
    return b.bundle()
            .on("error", gutil.log.bind(gutil, "Browserify Error"))
            .pipe(source(name))
            .pipe(gulp.dest(destDir("js")));
}
var b;
var watching = false;
function bundleJsProd() {
    var name = JS_ENTRIES.production;
    return bundleJs(b, name);
}
function bundleJsDev() {
    var name = JS_ENTRIES.development;
    return bundleJs(b, name);
}
gulp.task("build:js", function() {
    b = getBrowserify(false, watching);
    bundleJsProd();
});
gulp.task("build:js-dev", function() {
    b = getBrowserify(true, watching);
    bundleJsDev();
});

// create a task simply copying files
function copyTask(type) {
    var dest = destDir(type);
    return gulp.task("build:" + type, function() {
        return gulp.src(srcPattern(type))
            .pipe(changed(dest))
            .pipe(gulp.dest(dest));
    });
}
copyTask("fonts");
copyTask("resources");
copyTask("mathjax");

// HTML build
function buildHtml(development) {
    return gulp.src(srcPattern("html"))
        .pipe(ejs({development: development}))
        .pipe(plumber({
            errorHandler: notify.onError("Error: <%= error.message %>")
        }))
        .pipe(rename(development ? HTML_FILENAMES.development : HTML_FILENAMES.production))
        .pipe(gulp.dest(destDir("html")));
}
gulp.task("build:html", function() {
    return buildHtml(false);
});
gulp.task("build:html-dev", function() {
    return buildHtml(true);
});

// CSS build
function buildCss(development) {
    return gulp.src(srcPattern("css"))
        .pipe(plumber({
            errorHandler: notify.onError("Error: <%= error.message %>")
        }))
        .pipe(compass({
            config_file: SRC_DIR + "/config.rb",
            css: path.resolve(destDir("css")),
            sass: path.resolve(srcDir("css")),
            environment: development ? "development" : "production"
        }));
}
gulp.task("build:css", function() {
    return buildCss(false);
});
gulp.task("build:css-dev", function() {
    return buildCss(true);
});

// build all
gulp.task("build", [
    "build:js",
    "build:html",
    "build:fonts",
    "build:resources",
    "build:mathjax",
    "build:css"
]);
gulp.task("build-dev", [
    "build:js-dev",
    "build:html-dev",
    "build:fonts",
    "build:resources",
    "build:css-dev"
]);

// watch
gulp.task("start-watching", function() {
    watching = true;
});
gulp.task("watch", ["start-watching", "build"], function() {
    b.on("update", bundleJsProd);
    gulp.watch(srcPattern("html"), ["build:html"]);
    gulp.watch(srcPattern("fonts"), ["build:fonts"]);
    gulp.watch(srcPattern("resources"), ["build:resources"]);
    gulp.watch(srcPattern("css"), ["build:css"]);
});
gulp.task("watch-dev", ["start-watching", "build-dev"], function() {
    b.on("update", bundleJsDev);
    gulp.watch(srcPattern("html"), ["build:html-dev"]);
    gulp.watch(srcPattern("fonts"), ["build:fonts"]);
    gulp.watch(srcPattern("resources"), ["build:resources"]);
    gulp.watch(srcPattern("css"), ["build:css-dev"]);
});

// serve
function serve(development) {
    browserSync.init({
        browser: process.platform === "darwin" ? "google chrome": "chromium-browser",
        server: {
            baseDir: "../"
        },
        startPath: "/vivliostyle.js/test/files/"
    });
    var target = [DEST_DIR + "/**/*"];
    if (development) {
        target.push(VIVLIOSTYLE_JS_SRC_DIR + "/**/*");
    }
    gulp.watch(target).on("change", browserSync.reload);
}
gulp.task("serve", ["watch"], function() {
    serve(false);
});
gulp.task("serve-dev", ["watch-dev"], function() {
    serve(true);
});

gulp.task("default", ["serve-dev"]);

// test
gulp.task("test-local", function(done) {
    var server = new KarmaServer({
        configFile: process.cwd() + "/test/conf/karma-local.conf"
    }, function(exitStatus) {
        done(exitStatus ? "Some tests failed" : undefined);
    });
    server.start();
});
gulp.task("test-sauce", function(done) {
    var server = new KarmaServer({
        configFile: process.cwd() + "/test/conf/karma-sauce.conf"
    }, function(exitStatus) {
        done(exitStatus ? "Some tests failed" : undefined);
    });
    server.start();
});
<|endoftext|>


<commit_before>var concat = require('gulp-concat');
var gulp = require('gulp');
var changed = require('gulp-changed');
var glob = require('glob');
var path = require('path');
var browserify  = require('browserify');
var source = require('vinyl-source-stream');
var map = require('vinyl-map');
var transform = require('vinyl-transform');
var exorcist = require('exorcist');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');

var typescript = require('gulp-typescript');

gulp.task('compile', function() {
    var tsProject = typescript.createProject({
        declarationFiles: true,
        noExternalResolve: true,
        target: 'ES5',
        module: 'commonjs',
        sourceRoot: './awayjs-core/lib/'
    });

    var ambientWrap = map(function(code, filename) {
        code = code.toString();
        code = 'declare module "' + path.relative('../', filename.slice(0,-5)) + '" {\n\t'
        + code.split('declare ').join('').split('\n').join('\n\t') + "\n"
        + '}';
        return code;
    });

    var tsResult = gulp.src('./lib/**/*.ts')
        .pipe(sourcemaps.init())
        .pipe(typescript(tsProject));

    tsResult.dts
        .pipe(ambientWrap)
        .pipe(concat('awayjs-core.d.ts'))
        .pipe(gulp.dest('./build'));

    return tsResult.js
        .pipe(sourcemaps.write({sourceRoot: '../'}))
        .pipe(gulp.dest('./lib'));
});

gulp.task('watch', ['package', 'tests'], function() {
    gulp.watch('./lib/**/*.ts', ['package']);
    gulp.watch('./tests/**/*.ts', ['tests']);
});

gulp.task('package', ['compile'], function(callback){

    glob('./lib/**/*.js', {}, function (error, files) {
        var b = browserify({
            debug: true,
            paths: ['../']
        });

        files.forEach(function (file) {
            b.require(file, {expose:path.relative('../', file.slice(0,-3))});
        });

        b.bundle()
            .pipe(exorcist('./build/awayjs-core.js.map'))
            .pipe(source('awayjs-core.js'))
            .pipe(gulp.dest('./build'))
            .on('end', callback);
    });
});

gulp.task('package-min', ['package'], function(callback){
    return gulp.src('./build/awayjs-core.js')
        .pipe(sourcemaps.init({loadMaps:true}))
        .pipe(uglify({compress:false}))
        .pipe(rename(function (path) {
            path.basename += '.min';
        }))
        .pipe(sourcemaps.write('./', {sourceRoot: './'}))
        .pipe(gulp.dest('./build'));
});

gulp.task('tests', function () {

    var tsProject = typescript.createProject({
        declarationFiles: true,
        noExternalResolve: true,
        target: 'ES5',
        module: 'commonjs',
        sourceRoot: './'
    });

    var tsResult = gulp.src(['./tests/**/*.ts', './build/awayjs-core.d.ts'])
        //.pipe(changed('./tests', {extension:'.js', hasChanged: changed.compareLastModifiedTime}))
        .pipe(sourcemaps.init())
        .pipe(typescript(tsProject));

    return tsResult.js
        .pipe(sourcemaps.write({sourceRoot: './tests'}))
        .pipe(gulp.dest('./tests'));
});<commit_msg>windows compatability fix<commit_after>var concat = require('gulp-concat');
var gulp = require('gulp');
var changed = require('gulp-changed');
var glob = require('glob');
var path = require('path');
var browserify  = require('browserify');
var source = require('vinyl-source-stream');
var map = require('vinyl-map');
var transform = require('vinyl-transform');
var exorcist = require('exorcist');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');

var typescript = require('gulp-typescript');

gulp.task('compile', function() {
    var tsProject = typescript.createProject({
        declarationFiles: true,
        noExternalResolve: true,
        target: 'ES5',
        module: 'commonjs',
        sourceRoot: './awayjs-core/lib/'
    });

    var ambientWrap = map(function(code, filename) {
        code = code.toString();
        code = 'declare module "' + path.relative('../', filename.slice(0,-5)).replace(/\\/gi, '/') + '" {\n\t'
        + code.split('declare ').join('').split('\n').join('\n\t') + "\n"
        + '}';
        return code;
    });

    var tsResult = gulp.src('./lib/**/*.ts')
        .pipe(sourcemaps.init())
        .pipe(typescript(tsProject));

    tsResult.dts
        .pipe(ambientWrap)
        .pipe(concat('awayjs-core.d.ts'))
        .pipe(gulp.dest('./build'));

    return tsResult.js
        .pipe(sourcemaps.write({sourceRoot: '../'}))
        .pipe(gulp.dest('./lib'));
});

gulp.task('watch', ['package', 'tests'], function() {
    gulp.watch('./lib/**/*.ts', ['package']);
    gulp.watch('./tests/**/*.ts', ['tests']);
});

gulp.task('package', ['compile'], function(callback){

    glob('./lib/**/*.js', {}, function (error, files) {
        var b = browserify({
            debug: true,
            paths: ['../']
        });

        files.forEach(function (file) {
            b.require(file, {expose:path.relative('../', file.slice(0,-3))});
        });

        b.bundle()
            .pipe(exorcist('./build/awayjs-core.js.map'))
            .pipe(source('awayjs-core.js'))
            .pipe(gulp.dest('./build'))
            .on('end', callback);
    });
});

gulp.task('package-min', ['package'], function(callback){
    return gulp.src('./build/awayjs-core.js')
        .pipe(sourcemaps.init({loadMaps:true}))
        .pipe(uglify({compress:false}))
        .pipe(rename(function (path) {
            path.basename += '.min';
        }))
        .pipe(sourcemaps.write('./', {sourceRoot: './'}))
        .pipe(gulp.dest('./build'));
});

gulp.task('tests', function () {

    var tsProject = typescript.createProject({
        declarationFiles: true,
        noExternalResolve: true,
        target: 'ES5',
        module: 'commonjs',
        sourceRoot: './'
    });

    var tsResult = gulp.src(['./tests/**/*.ts', './build/awayjs-core.d.ts'])
        //.pipe(changed('./tests', {extension:'.js', hasChanged: changed.compareLastModifiedTime}))
        .pipe(sourcemaps.init())
        .pipe(typescript(tsProject));

    return tsResult.js
        .pipe(sourcemaps.write({sourceRoot: './tests'}))
        .pipe(gulp.dest('./tests'));
});<|endoftext|>


<commit_before>// These gulp tasks can be ran using the command: gulp.
// The gulp command will create a build folder, which you'll
// point your server to.
// The build folder will not be minified, but will contain
// things like validated HTML, compiled SASS, vendor-prefixed CSS etc...

// Autobuild on file saves with: gulp watch
// Watch tasks are used to update file changes,
// and will be ran automatically.
// use `ctrl+c` to quit the watch task.

// To build the dist folder use the command: gulp dist
// This will run minification processes and render the code
// unreadalbe.

// Include gulp
var gulp = require('gulp');

// Include Plugins
// Include Gulp
var gulp = require('gulp');

// Include plugins
var plugins = require("gulp-load-plugins")({
	pattern: ['gulp-*', 'gulp.*', 'main-bower-files'],
	replaceString: /\bgulp[\-.]/
});

// Move JS Files Into Build
gulp.task('build-js', function() {
   gulp.src('src/js/*.js')
   .pipe(gulp.dest('build/js'));
});

// Minifies JS Files
gulp.task('compress-js', function() {
  gulp.src('build/js/*.js')
    .pipe(plugins.minify({
        ext:{
            src:'.js',
            min:'.min.js'
        }
    }))
    .pipe(gulp.dest('dist'))
});

// Put CSS libs in build
gulp.task('build-vendor-css', function() {
    return gulp.src('src/vendor/**/*.css')
    .pipe(gulp.dest('build/vendor'))
})

// Put CSS libs in dist
gulp.task('dist-vendor-css', function() {
    return gulp.src('build/vendor/**/*.css')
    .pipe(gulp.dest('dist/vendor'))
})

// Put JS libs in build
gulp.task('build-vendor-js', function() {
    return gulp.src('src/vendor/**/*.js')
    .pipe(gulp.dest('build/vendor'))
})

// Put JS libs in dist
gulp.task('dist-vendor-js', function() {
    return gulp.src('build/vendor/**/*.js')
    .pipe(gulp.dest('dist/vendor'))
})

// Minify CSS
gulp.task('minify-css', function() {
   return gulp.src('build/css/*.css')
    //.pipe(strip({ignore: /url\([\w\s:\/=\-\+;,]*\)/g}))
    .pipe(plugins.cleanCss({compatibility: 'ie8'}))
    .pipe(gulp.dest('dist/css'));
});

// Minify HTML
gulp.task('minify-html', function () {
  return gulp.src('build/*.html')
    .pipe(plugins.stripComments())
    .pipe(plugins.htmlmin({collapseWhitespace: true}))
    .pipe(gulp.dest('dist'));
});

// Compress Images
gulp.task('images', function() {
    return gulp.src('src/images/**/*')
        .pipe(plugins.imagemin())
        .pipe(gulp.dest('build/images'));
});

// Add images to dist
gulp.task('dist-images', function() {
    return gulp.src('build/images/**/*')
        .pipe(plugins.imagemin())
        .pipe(gulp.dest('dist/images'));
});

// Validate HTML
gulp.task('html', function() {
  return gulp.src('src/*.html')
  .pipe(plugins.html())
  .pipe(gulp.dest('build/'));
});

// Compile Sass
gulp.task('sass', function() {
    return gulp.src('src/scss/*.scss')
        .pipe(plugins.sass())
        .pipe(plugins.autoprefixer())
        .pipe(gulp.dest('build/css/'));
});

// Move php files into build
gulp.task('build-php', function() {
    return gulp.src('src/*.php')
        .pipe(gulp.dest('build'));
});

// Move php files into dist
gulp.task('dist-php', function() {
    return gulp.src('build/*.php')
        .pipe(gulp.dest('dist'));
});

// Watch Files For Changes
gulp.task('watch', function() {
    gulp.watch(['src/**/*'], ['default']);
});

// Build Distrobution Folder
gulp.task('dist', [
        'minify-html',
        'minify-css',
        'dist-images',
        'dist-vendor-css',
        'dist-vendor-js',
        'compress-js',
        'dist-php'
    ]);

// Default Task
gulp.task('default', [
        'sass',
        'html',
        'images',
        'build-vendor-css',
        'build-vendor-js',
        'build-js',
        'build-php'
    ]);
<commit_msg>Fix js dist<commit_after>// These gulp tasks can be ran using the command: gulp.
// The gulp command will create a build folder, which you'll
// point your server to.
// The build folder will not be minified, but will contain
// things like validated HTML, compiled SASS, vendor-prefixed CSS etc...

// Autobuild on file saves with: gulp watch
// Watch tasks are used to update file changes,
// and will be ran automatically.
// use `ctrl+c` to quit the watch task.

// To build the dist folder use the command: gulp dist
// This will run minification processes and render the code
// unreadalbe.

// Include gulp
var gulp = require('gulp');

// Include Plugins
// Include Gulp
var gulp = require('gulp');

// Include plugins
var plugins = require("gulp-load-plugins")({
	pattern: ['gulp-*', 'gulp.*', 'main-bower-files'],
	replaceString: /\bgulp[\-.]/
});

// Move JS Files Into Build
gulp.task('build-js', function() {
   gulp.src('src/js/*.js')
   .pipe(gulp.dest('build/js'));
});

// Minifies JS Files
gulp.task('compress-js', function() {
  gulp.src('build/js/*.js')
    .pipe(plugins.minify({
        ext:{
            src:'.js',
            min:'.min.js'
        }
    }))
    .pipe(gulp.dest('dist/js'))
});

// Put CSS libs in build
gulp.task('build-vendor-css', function() {
    return gulp.src('src/vendor/**/*.css')
    .pipe(gulp.dest('build/vendor'))
})

// Put CSS libs in dist
gulp.task('dist-vendor-css', function() {
    return gulp.src('build/vendor/**/*.css')
    .pipe(gulp.dest('dist/vendor'))
})

// Put JS libs in build
gulp.task('build-vendor-js', function() {
    return gulp.src('src/vendor/**/*.js')
    .pipe(gulp.dest('build/vendor'))
})

// Put JS libs in dist
gulp.task('dist-vendor-js', function() {
    return gulp.src('build/vendor/**/*.js')
    .pipe(gulp.dest('dist/vendor'))
})

// Minify CSS
gulp.task('minify-css', function() {
   return gulp.src('build/css/*.css')
    //.pipe(strip({ignore: /url\([\w\s:\/=\-\+;,]*\)/g}))
    .pipe(plugins.cleanCss({compatibility: 'ie8'}))
    .pipe(gulp.dest('dist/css'));
});

// Minify HTML
gulp.task('minify-html', function () {
  return gulp.src('build/*.html')
    .pipe(plugins.stripComments())
    .pipe(plugins.htmlmin({collapseWhitespace: true}))
    .pipe(gulp.dest('dist'));
});

// Compress Images
gulp.task('images', function() {
    return gulp.src('src/images/**/*')
        .pipe(plugins.imagemin())
        .pipe(gulp.dest('build/images'));
});

// Add images to dist
gulp.task('dist-images', function() {
    return gulp.src('build/images/**/*')
        .pipe(plugins.imagemin())
        .pipe(gulp.dest('dist/images'));
});

// Validate HTML
gulp.task('html', function() {
  return gulp.src('src/*.html')
  .pipe(plugins.html())
  .pipe(gulp.dest('build/'));
});

// Compile Sass
gulp.task('sass', function() {
    return gulp.src('src/scss/*.scss')
        .pipe(plugins.sass())
        .pipe(plugins.autoprefixer())
        .pipe(gulp.dest('build/css/'));
});

// Move php files into build
gulp.task('build-php', function() {
    return gulp.src('src/*.php')
        .pipe(gulp.dest('build'));
});

// Move php files into dist
gulp.task('dist-php', function() {
    return gulp.src('build/*.php')
        .pipe(gulp.dest('dist'));
});

// Watch Files For Changes
gulp.task('watch', function() {
    gulp.watch(['src/**/*'], ['default']);
});

// Build Distrobution Folder
gulp.task('dist', [
        'minify-html',
        'minify-css',
        'dist-images',
        'dist-vendor-css',
        'dist-vendor-js',
        'compress-js',
        'dist-php'
    ]);

// Default Task
gulp.task('default', [
        'sass',
        'html',
        'images',
        'build-vendor-css',
        'build-vendor-js',
        'build-js',
        'build-php'
    ]);
<|endoftext|>


<commit_before>/**
* JavaScript project for accessing and normalizing the accelerometer and gyroscope data on mobile devices
*
* @author Doruk Eker <dorukeker@gmail.com>
* @copyright 2015 Doruk Eker <http://dorukeker.com>
* @version 2.0.0
* @license MIT License | http://opensource.org/licenses/MIT
*/

(function(root, factory) {
  if (typeof define === 'function' && define.amd) {
    define(function() {
      return (root.GyroNorm = factory());
    });
  } else if (typeof module === 'object' && module.exports) {
    module.exports = (root.GyroNorm = factory());
  } else {
    root.GyroNorm = factory();
  }
}(this, function() {
  /* Constants */
  var GAME                            = 'game';
  var WORLD                           = 'world';
  var DEVICE_ORIENTATION              = 'deviceorientation';
  var ACCELERATION                    = 'acceleration';
  var ACCELERATION_INCLUDING_GRAVITY  = 'accelerationinludinggravity';
  var ROTATION_RATE                   = 'rotationrate';

  /*-------------------------------------------------------*/
  /* PRIVATE VARIABLES */

  var _interval           = null;       // Timer to return values
  var _isCalibrating      = false;      // Flag if calibrating
  var _calibrationValue   = 0;          // Alpha offset value
  var _gravityCoefficient = 0;          // Coefficient to normalze gravity related values
  var _isRunning          = false;      // Boolean value if GyroNorm is tracking
  var _isReady            = false;      // Boolean value if GyroNorm is is initialized

  var _do                 = null;       // Object to store the device orientation values
  var _dm                 = null;       // Object to store the device motion values

  /* OPTIONS */
  var _frequency          = 50;         // Frequency for the return data in milliseconds
  var _gravityNormalized  = true;       // Flag if to normalize gravity values
  var _orientationBase    = 'game';     // Can be GyroNorm.GAME or GyroNorm.WORLD. GyroNorm.GAME returns orientation values with respect to the head direction of the device. GyroNorm.WORLD returns the orientation values with respect to the actual north direction of the world.
  var _decimalCount       = 2;          // Number of digits after the decimals point for the return values
  var _logger             = null;       // Function to callback on error. There is no default value. It can only be set by the user on gn.init()
  var _screenAdjusted     = false;      // If set to true it will return screen adjusted values. (e.g. On a horizontal orientation of a mobile device, the head would be one of the sides, instead of  the actual head of the device.)

  var _values = {
    do: {
      alpha: 0,
      beta: 0,
      gamma: 0,
      absolute: false
    },
    dm: {
      x: 0,
      y: 0,
      z: 0,
      gx: 0,
      gy: 0,
      gz: 0,
      alpha: 0,
      beta: 0,
      gamma: 0
    }
  }

  /*-------------------------------------------------------*/
  /* PUBLIC FUNCTIONS */

  /*
  *
  * Constructor function
  *
  */

  var GyroNorm = function(options) {}

  /* Constants */
  GyroNorm.prototype.GAME                             = 'game';
  GyroNorm.prototype.WORLD                            = 'world';
  GyroNorm.prototype.DEVICE_ORIENTATION               = 'deviceorientation';
  GyroNorm.prototype.ACCELERATION                     = 'acceleration';
  GyroNorm.prototype.ACCELERATION_INCLUDING_GRAVITY   = 'accelerationinludinggravity';
  GyroNorm.prototype.ROTATION_RATE                    = 'rotationrate';

  /*
  *
  * Initialize GyroNorm instance function
  *
  * @param object options - values are as follows. If set in the init function they overwrite the default option values
  * @param int options.frequency
  * @param boolean options.gravityNormalized
  * @param boolean options.orientationBase
  * @param boolean options.decimalCount
  * @param function options.logger
  * @param function options.screenAdjusted
  *
  */

  GyroNorm.prototype.init = function(options) {
    // Assign options that are passed with the constructor function
    if (options && options.frequency) _frequency = options.frequency;
    if (options && options.gravityNormalized) _gravityNormalized = options.gravityNormalized;
    if (options && options.orientationBase) _orientationBase = options.orientationBase;
    if (options && options.decimalCount) _decimalCount = options.decimalCount;
    if (options && options.logger) _logger = options.logger;
    if (options && options.screenAdjusted) _screenAdjusted = options.screenAdjusted;

    return new Promise(function(resolve, reject) {
      var isDeviceOrientationReady = false;
      var isDeviceMotionReady = false;

      new FULLTILT.getDeviceOrientation({ 'type': _orientationBase }).then(function(controller) {
        _do = controller;
        isDeviceOrientationReady = true;

        if (isDeviceOrientationReady && isDeviceMotionReady) {
          _isReady = true;
          resolve();
        }
      }).catch(function(err) {
        reject(err);
      });

      new FULLTILT.getDeviceMotion().then(function(controller) {
        isDeviceMotionReady = true;
        _dm = controller;
        // Set gravity coefficient
        _gravityCoefficient = (_dm.getScreenAdjustedAccelerationIncludingGravity().z > 0) ? 1 : -1;

        if (isDeviceOrientationReady && isDeviceMotionReady) {
          _isReady = true;
          resolve();
        }
      }).catch(function(err) {
        reject(err);
      });
    });

  }

  /*
  *
  * Stops all the tracking and listening on the window objects
  *
  */
  GyroNorm.prototype.end = function() {
    try {
      _isReady = false;
      this.stop();
      _dm.stop();
      _do.stop();
    } catch(err){
      log(err);
    }
  }

  /*
  *
  * Starts tracking the values
  *
  * @param function callback - Callback function to read the values
  *
  */
  GyroNorm.prototype.start = function(callback) {
    if (!_isReady) {
      log({ message: 'GyroNorm is not initialized yet. First call the "init()" function.', code: 1 });
      return;
    }

    _interval = setInterval(function() {
      callback(snapShot());
    }, _frequency);
    _isRunning = true;
  }

  /*
  *
  * Stops tracking the values
  *
  */
  GyroNorm.prototype.stop = function() {
    if (_interval) {
      clearInterval(_interval);
      _isRunning = false;
    }
  }

  /*
  *
  * Toggles if to normalize gravity related values
  *
  * @param boolean flag
  *
  */
  GyroNorm.prototype.normalizeGravity = function(flag) {
    _gravityNormalized = (flag) ? true : false;
  }

  /*
  *
  * Sets the current head direction as alpha = 0
  * Can only be used if device orientation is being tracked, values are not screen adjusted, value type is GyroNorm.EULER and orientation base is GyroNorm.GAME
  *
  * @return: If head direction is set successfully returns true, else false
  *
  */
  GyroNorm.prototype.setHeadDirection = function() {
    if (_screenAdjusted || _orientationBase === this.WORLD) {
      return false;
    }

    _calibrationValue = _do.getFixedFrameEuler().alpha;
    return true;
  }

  /*
  *
  * Sets the log function
  *
  */
  GyroNorm.prototype.startLogging = function(logger) {
    if (logger) {
      _logger = logger;
    }
  }

  /*
  *
  * Sets the log function to null which stops the logging
  *
  */
  GyroNorm.prototype.stopLogging = function() {
    _logger = null;
  }

  /*
  *
  * Returns if certain type of event is available on the device
  *
  * @param string _eventType - possible values are "deviceorientation" , "devicemotion" , "compassneedscalibration"
  *
  * @return true if event is available false if not
  *
  */
  GyroNorm.prototype.isAvailable = function(_eventType) {

    switch (_eventType) {
      case this.DEVICE_ORIENTATION:
        return (_do.isAvailable(_do.ALPHA) && _do.isAvailable(_do.BETA) && _do.isAvailable(_do.GAMMA));
        break;

      case this.ACCELERATION:
        return (_dm.isAvailable(_dm.ACCELERATION_X) && _dm.isAvailable(_dm.ACCELERATION_Y) && _dm.isAvailable(_dm.ACCELERATION_Z));
        break;

      case this.ACCELERATION_INCLUDING_GRAVITY:
        return (_dm.isAvailable(_dm.ACCELERATION_INCLUDING_GRAVITY_X) && _dm.isAvailable(_dm.ACCELERATION_INCLUDING_GRAVITY_Y) && _dm.isAvailable(_dm.ACCELERATION_INCLUDING_GRAVITY_Z));
        break;

      case this.ROTATION_RATE:
        return (_dm.isAvailable(_dm.ROTATION_RATE_ALPHA) && _dm.isAvailable(_dm.ROTATION_RATE_BETA) && _dm.isAvailable(_dm.ROTATION_RATE_GAMMA));
        break;

      default:
        return {
          deviceOrientationAvailable: (_do.isAvailable(_do.ALPHA) && _do.isAvailable(_do.BETA) && _do.isAvailable(_do.GAMMA)),
          accelerationAvailable: (_dm.isAvailable(_dm.ACCELERATION_X) && _dm.isAvailable(_dm.ACCELERATION_Y) && _dm.isAvailable(_dm.ACCELERATION_Z)),
          accelerationIncludingGravityAvailable: (_dm.isAvailable(_dm.ACCELERATION_INCLUDING_GRAVITY_X) && _dm.isAvailable(_dm.ACCELERATION_INCLUDING_GRAVITY_Y) && _dm.isAvailable(_dm.ACCELERATION_INCLUDING_GRAVITY_Z)),
          rotationRateAvailable: (_dm.isAvailable(_dm.ROTATION_RATE_ALPHA) && _dm.isAvailable(_dm.ROTATION_RATE_BETA) && _dm.isAvailable(_dm.ROTATION_RATE_GAMMA))
        }
        break;
    }
  }

  /*
  *
  * Returns boolean value if the GyroNorm is running
  *
  */
  GyroNorm.prototype.isRunning = function() {
    return _isRunning;
  }

  /*-------------------------------------------------------*/
  /* PRIVATE FUNCTIONS */

  /*
  *
  * Utility function to round with digits after the decimal point
  *
  * @param float number - the original number to round
  *
  */
  function rnd(number) {
    return Math.round(number * Math.pow(10, _decimalCount)) / Math.pow(10, _decimalCount);
  }

  /*
  *
  * Starts calibration
  *
  */
  function calibrate() {
    _isCalibrating = true;
    _calibrationValues = new Array();
  }

  /*
  *
  * Takes a snapshot of the current deviceo orientaion and device motion values
  *
  */
  function snapShot() {
    var doSnapShot = {};

    if (_screenAdjusted) {
      doSnapShot = _do.getScreenAdjustedEuler();
    } else {
      doSnapShot = _do.getFixedFrameEuler();
    }

    var accSnapShot = _dm.getScreenAdjustedAcceleration();
    var accGraSnapShot = _dm.getScreenAdjustedAccelerationIncludingGravity();
    var rotRateSnapShot = _dm.getScreenAdjustedRotationRate();

    var alphaToSend = 0;

    if (_orientationBase === GAME) {
      alphaToSend = doSnapShot.alpha - _calibrationValue;
      alphaToSend = (alphaToSend < 0) ? (360 - Math.abs(alphaToSend)) : alphaToSend;
    } else {
      alphaToSend = doSnapShot.alpha;
    }

    var snapShot = {
      do: {
        alpha: rnd(alphaToSend),
        beta: rnd(doSnapShot.beta),
        gamma: rnd(doSnapShot.gamma),
        absolute: _do.isAbsolute()
      },
      dm: {
        x: rnd(accSnapShot.x),
        y: rnd(accSnapShot.y),
        z: rnd(accSnapShot.z),
        gx: rnd(accGraSnapShot.x),
        gy: rnd(accGraSnapShot.y),
        gz: rnd(accGraSnapShot.z),
        alpha: rnd(rotRateSnapShot.alpha),
        beta: rnd(rotRateSnapShot.beta),
        gamma: rnd(rotRateSnapShot.gamma)
      }
    };

    // Normalize gravity
    if (_gravityNormalized) {
      snapShot.dm.gx *= _gravityCoefficient;
      snapShot.dm.gy *= _gravityCoefficient;
      snapShot.dm.gz *= _gravityCoefficient;
    }

    return snapShot;
  }

  /*
  *
  * Starts listening to orientation event on the window object
  *
  */
  function log(err) {
    if (_logger) {
      if (typeof(err) == 'string') {
        err = { message: err, code: 0 }
      }
      _logger(err);
    }
  }

  return GyroNorm;
}));
<commit_msg>Re-used existing constants. Assign constants to GyroNorm constructor function instead of prototype.<commit_after>/**
* JavaScript project for accessing and normalizing the accelerometer and gyroscope data on mobile devices
*
* @author Doruk Eker <dorukeker@gmail.com>
* @copyright 2015 Doruk Eker <http://dorukeker.com>
* @version 2.0.0
* @license MIT License | http://opensource.org/licenses/MIT
*/

(function(root, factory) {
  if (typeof define === 'function' && define.amd) {
    define(function() {
      return (root.GyroNorm = factory());
    });
  } else if (typeof module === 'object' && module.exports) {
    module.exports = (root.GyroNorm = factory());
  } else {
    root.GyroNorm = factory();
  }
}(this, function() {
  /* Constants */
  var GAME                            = 'game';
  var WORLD                           = 'world';
  var DEVICE_ORIENTATION              = 'deviceorientation';
  var ACCELERATION                    = 'acceleration';
  var ACCELERATION_INCLUDING_GRAVITY  = 'accelerationinludinggravity';
  var ROTATION_RATE                   = 'rotationrate';

  /*-------------------------------------------------------*/
  /* PRIVATE VARIABLES */

  var _interval           = null;       // Timer to return values
  var _isCalibrating      = false;      // Flag if calibrating
  var _calibrationValue   = 0;          // Alpha offset value
  var _gravityCoefficient = 0;          // Coefficient to normalze gravity related values
  var _isRunning          = false;      // Boolean value if GyroNorm is tracking
  var _isReady            = false;      // Boolean value if GyroNorm is is initialized

  var _do                 = null;       // Object to store the device orientation values
  var _dm                 = null;       // Object to store the device motion values

  /* OPTIONS */
  var _frequency          = 50;         // Frequency for the return data in milliseconds
  var _gravityNormalized  = true;       // Flag if to normalize gravity values
  var _orientationBase    = 'game';     // Can be GyroNorm.GAME or GyroNorm.WORLD. GyroNorm.GAME returns orientation values with respect to the head direction of the device. GyroNorm.WORLD returns the orientation values with respect to the actual north direction of the world.
  var _decimalCount       = 2;          // Number of digits after the decimals point for the return values
  var _logger             = null;       // Function to callback on error. There is no default value. It can only be set by the user on gn.init()
  var _screenAdjusted     = false;      // If set to true it will return screen adjusted values. (e.g. On a horizontal orientation of a mobile device, the head would be one of the sides, instead of  the actual head of the device.)

  var _values = {
    do: {
      alpha: 0,
      beta: 0,
      gamma: 0,
      absolute: false
    },
    dm: {
      x: 0,
      y: 0,
      z: 0,
      gx: 0,
      gy: 0,
      gz: 0,
      alpha: 0,
      beta: 0,
      gamma: 0
    }
  }

  /*-------------------------------------------------------*/
  /* PUBLIC FUNCTIONS */

  /*
  *
  * Constructor function
  *
  */

  var GyroNorm = function(options) {}

  /* Constants */
  GyroNorm.GAME                             = GAME;
  GyroNorm.WORLD                            = WORLD;
  GyroNorm.DEVICE_ORIENTATION               = DEVICE_ORIENTATION;
  GyroNorm.ACCELERATION                     = ACCELERATION;
  GyroNorm.ACCELERATION_INCLUDING_GRAVITY   = ACCELARATION_INCLUDING_GRAVITY;
  GyroNorm.ROTATION_RATE                    = ROTATION_RATE;

  /*
  *
  * Initialize GyroNorm instance function
  *
  * @param object options - values are as follows. If set in the init function they overwrite the default option values
  * @param int options.frequency
  * @param boolean options.gravityNormalized
  * @param boolean options.orientationBase
  * @param boolean options.decimalCount
  * @param function options.logger
  * @param function options.screenAdjusted
  *
  */

  GyroNorm.prototype.init = function(options) {
    // Assign options that are passed with the constructor function
    if (options && options.frequency) _frequency = options.frequency;
    if (options && options.gravityNormalized) _gravityNormalized = options.gravityNormalized;
    if (options && options.orientationBase) _orientationBase = options.orientationBase;
    if (options && options.decimalCount) _decimalCount = options.decimalCount;
    if (options && options.logger) _logger = options.logger;
    if (options && options.screenAdjusted) _screenAdjusted = options.screenAdjusted;

    return new Promise(function(resolve, reject) {
      var isDeviceOrientationReady = false;
      var isDeviceMotionReady = false;

      new FULLTILT.getDeviceOrientation({ 'type': _orientationBase }).then(function(controller) {
        _do = controller;
        isDeviceOrientationReady = true;

        if (isDeviceOrientationReady && isDeviceMotionReady) {
          _isReady = true;
          resolve();
        }
      }).catch(function(err) {
        reject(err);
      });

      new FULLTILT.getDeviceMotion().then(function(controller) {
        isDeviceMotionReady = true;
        _dm = controller;
        // Set gravity coefficient
        _gravityCoefficient = (_dm.getScreenAdjustedAccelerationIncludingGravity().z > 0) ? 1 : -1;

        if (isDeviceOrientationReady && isDeviceMotionReady) {
          _isReady = true;
          resolve();
        }
      }).catch(function(err) {
        reject(err);
      });
    });

  }

  /*
  *
  * Stops all the tracking and listening on the window objects
  *
  */
  GyroNorm.prototype.end = function() {
    try {
      _isReady = false;
      this.stop();
      _dm.stop();
      _do.stop();
    } catch(err){
      log(err);
    }
  }

  /*
  *
  * Starts tracking the values
  *
  * @param function callback - Callback function to read the values
  *
  */
  GyroNorm.prototype.start = function(callback) {
    if (!_isReady) {
      log({ message: 'GyroNorm is not initialized yet. First call the "init()" function.', code: 1 });
      return;
    }

    _interval = setInterval(function() {
      callback(snapShot());
    }, _frequency);
    _isRunning = true;
  }

  /*
  *
  * Stops tracking the values
  *
  */
  GyroNorm.prototype.stop = function() {
    if (_interval) {
      clearInterval(_interval);
      _isRunning = false;
    }
  }

  /*
  *
  * Toggles if to normalize gravity related values
  *
  * @param boolean flag
  *
  */
  GyroNorm.prototype.normalizeGravity = function(flag) {
    _gravityNormalized = (flag) ? true : false;
  }

  /*
  *
  * Sets the current head direction as alpha = 0
  * Can only be used if device orientation is being tracked, values are not screen adjusted, value type is GyroNorm.EULER and orientation base is GyroNorm.GAME
  *
  * @return: If head direction is set successfully returns true, else false
  *
  */
  GyroNorm.prototype.setHeadDirection = function() {
    if (_screenAdjusted || _orientationBase === WORLD) {
      return false;
    }

    _calibrationValue = _do.getFixedFrameEuler().alpha;
    return true;
  }

  /*
  *
  * Sets the log function
  *
  */
  GyroNorm.prototype.startLogging = function(logger) {
    if (logger) {
      _logger = logger;
    }
  }

  /*
  *
  * Sets the log function to null which stops the logging
  *
  */
  GyroNorm.prototype.stopLogging = function() {
    _logger = null;
  }

  /*
  *
  * Returns if certain type of event is available on the device
  *
  * @param string _eventType - possible values are "deviceorientation" , "devicemotion" , "compassneedscalibration"
  *
  * @return true if event is available false if not
  *
  */
  GyroNorm.prototype.isAvailable = function(_eventType) {

    switch (_eventType) {
      case DEVICE_ORIENTATION:
        return (_do.isAvailable(_do.ALPHA) && _do.isAvailable(_do.BETA) && _do.isAvailable(_do.GAMMA));
        break;

      case ACCELERATION:
        return (_dm.isAvailable(_dm.ACCELERATION_X) && _dm.isAvailable(_dm.ACCELERATION_Y) && _dm.isAvailable(_dm.ACCELERATION_Z));
        break;

      case ACCELERATION_INCLUDING_GRAVITY:
        return (_dm.isAvailable(_dm.ACCELERATION_INCLUDING_GRAVITY_X) && _dm.isAvailable(_dm.ACCELERATION_INCLUDING_GRAVITY_Y) && _dm.isAvailable(_dm.ACCELERATION_INCLUDING_GRAVITY_Z));
        break;

      case ROTATION_RATE:
        return (_dm.isAvailable(_dm.ROTATION_RATE_ALPHA) && _dm.isAvailable(_dm.ROTATION_RATE_BETA) && _dm.isAvailable(_dm.ROTATION_RATE_GAMMA));
        break;

      default:
        return {
          deviceOrientationAvailable: (_do.isAvailable(_do.ALPHA) && _do.isAvailable(_do.BETA) && _do.isAvailable(_do.GAMMA)),
          accelerationAvailable: (_dm.isAvailable(_dm.ACCELERATION_X) && _dm.isAvailable(_dm.ACCELERATION_Y) && _dm.isAvailable(_dm.ACCELERATION_Z)),
          accelerationIncludingGravityAvailable: (_dm.isAvailable(_dm.ACCELERATION_INCLUDING_GRAVITY_X) && _dm.isAvailable(_dm.ACCELERATION_INCLUDING_GRAVITY_Y) && _dm.isAvailable(_dm.ACCELERATION_INCLUDING_GRAVITY_Z)),
          rotationRateAvailable: (_dm.isAvailable(_dm.ROTATION_RATE_ALPHA) && _dm.isAvailable(_dm.ROTATION_RATE_BETA) && _dm.isAvailable(_dm.ROTATION_RATE_GAMMA))
        }
        break;
    }
  }

  /*
  *
  * Returns boolean value if the GyroNorm is running
  *
  */
  GyroNorm.prototype.isRunning = function() {
    return _isRunning;
  }

  /*-------------------------------------------------------*/
  /* PRIVATE FUNCTIONS */

  /*
  *
  * Utility function to round with digits after the decimal point
  *
  * @param float number - the original number to round
  *
  */
  function rnd(number) {
    return Math.round(number * Math.pow(10, _decimalCount)) / Math.pow(10, _decimalCount);
  }

  /*
  *
  * Starts calibration
  *
  */
  function calibrate() {
    _isCalibrating = true;
    _calibrationValues = new Array();
  }

  /*
  *
  * Takes a snapshot of the current deviceo orientaion and device motion values
  *
  */
  function snapShot() {
    var doSnapShot = {};

    if (_screenAdjusted) {
      doSnapShot = _do.getScreenAdjustedEuler();
    } else {
      doSnapShot = _do.getFixedFrameEuler();
    }

    var accSnapShot = _dm.getScreenAdjustedAcceleration();
    var accGraSnapShot = _dm.getScreenAdjustedAccelerationIncludingGravity();
    var rotRateSnapShot = _dm.getScreenAdjustedRotationRate();

    var alphaToSend = 0;

    if (_orientationBase === GAME) {
      alphaToSend = doSnapShot.alpha - _calibrationValue;
      alphaToSend = (alphaToSend < 0) ? (360 - Math.abs(alphaToSend)) : alphaToSend;
    } else {
      alphaToSend = doSnapShot.alpha;
    }

    var snapShot = {
      do: {
        alpha: rnd(alphaToSend),
        beta: rnd(doSnapShot.beta),
        gamma: rnd(doSnapShot.gamma),
        absolute: _do.isAbsolute()
      },
      dm: {
        x: rnd(accSnapShot.x),
        y: rnd(accSnapShot.y),
        z: rnd(accSnapShot.z),
        gx: rnd(accGraSnapShot.x),
        gy: rnd(accGraSnapShot.y),
        gz: rnd(accGraSnapShot.z),
        alpha: rnd(rotRateSnapShot.alpha),
        beta: rnd(rotRateSnapShot.beta),
        gamma: rnd(rotRateSnapShot.gamma)
      }
    };

    // Normalize gravity
    if (_gravityNormalized) {
      snapShot.dm.gx *= _gravityCoefficient;
      snapShot.dm.gy *= _gravityCoefficient;
      snapShot.dm.gz *= _gravityCoefficient;
    }

    return snapShot;
  }

  /*
  *
  * Starts listening to orientation event on the window object
  *
  */
  function log(err) {
    if (_logger) {
      if (typeof(err) == 'string') {
        err = { message: err, code: 0 }
      }
      _logger(err);
    }
  }

  return GyroNorm;
}));
<|endoftext|>


<commit_before>import { hot } from 'react-hot-loader'
import { Meteor } from 'meteor/meteor'
import React, { Component, Fragment } from 'react'
import { Router, Route, Redirect } from 'react-router-dom'
import history from '../utils/history'
import qs from 'query-string'

// Includes
import MainMenu from './includes/MainMenu'

// Pages
import Home from './pages/Home'
import About from './pages/About'
import Authentication from './pages/Authentication'
import Map_ from './pages/Map'
import NewEventLoadable from './pages/NewEvent/loadable'
import CongratsModal from './pages/NewEvent/CongratsModal'
import Page from './pages/Page'

// Components
import ScrollToTop from './components/ScrollToTop'

class App extends Component {
  componentDidMount () {
    setTimeout(() => {
      document.querySelector('#root').classList.toggle('show')
    }, 100) // add a fading effect on the inital loading
  }

  render () {
    return (
      <Router history={history}>
        <Fragment>
          <MainMenu />

          <ScrollToTop>
            <Route exact path='/' component={Home} />
            <Route exact path='/about' component={About} />
            <Route path='/map' component={Map_} />
            <Route path='*' render={this.renderNewEvent} />
            <Route exact path='/thank-you' component={CongratsModal} />
            <Route exact path='/page/:id' component={Page} />
            <Authentication />
          </ScrollToTop>
        </Fragment>
      </Router>
    )
  }

  renderNewEvent = ({ location, history }) => {
    const { new: new_, edit } = qs.parse(location.search)
    const isOpen = Boolean(new_ === '1' || (edit === '1' && window.__editData))

    if (isOpen && !Meteor.userId()) {
      sessionStorage.setItem('redirect', '/?new=1')
      return <Redirect to='/sign-in' />
    }

    return <NewEventLoadable isOpen={isOpen} location={location} history={history} />
  }
}

export default hot(module)(App)
<commit_msg>fixed the blank page on "/home" by redirecting to "/" route<commit_after>import { hot } from 'react-hot-loader'
import { Meteor } from 'meteor/meteor'
import React, { Component, Fragment } from 'react'
import { Router, Route, Redirect } from 'react-router-dom'
import history from '../utils/history'
import qs from 'query-string'

// Includes
import MainMenu from './includes/MainMenu'

// Pages
import Home from './pages/Home'
import About from './pages/About'
import Authentication from './pages/Authentication'
import Map_ from './pages/Map'
import NewEventLoadable from './pages/NewEvent/loadable'
import CongratsModal from './pages/NewEvent/CongratsModal'
import Page from './pages/Page'

// Components
import ScrollToTop from './components/ScrollToTop'

class App extends Component {
  componentDidMount () {
    setTimeout(() => {
      document.querySelector('#root').classList.toggle('show')
    }, 100) // add a fading effect on the inital loading
  }

  render () {
    return (
      <Router history={history}>
        <Fragment>
          <MainMenu />

          <ScrollToTop>
            <Route exact path='/(home)?' component={Home} />
            <Route exact path='/about' component={About} />
            <Route path='/map' component={Map_} />
            <Route path='*' render={this.renderNewEvent} />
            <Route exact path='/thank-you' component={CongratsModal} />
            <Route exact path='/page/:id' component={Page} />
            <Authentication />
          </ScrollToTop>
        </Fragment>
      </Router>
    )
  }

  renderNewEvent = ({ location, history }) => {
    const { new: new_, edit } = qs.parse(location.search)
    const isOpen = Boolean(new_ === '1' || (edit === '1' && window.__editData))

    if (isOpen && !Meteor.userId()) {
      sessionStorage.setItem('redirect', '/?new=1')
      return <Redirect to='/sign-in' />
    }

    return <NewEventLoadable isOpen={isOpen} location={location} history={history} />
  }
}

export default hot(module)(App)
<|endoftext|>


<commit_before>!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):a("object"==typeof exports?require("jquery"):jQuery)}(function(a){function b(b,d,e){var d={content:{message:"object"==typeof d?d.message:d,title:d.title?d.title:"",icon:d.icon?d.icon:"",url:d.url?d.url:"#",target:d.target?d.target:"-"}};e=a.extend(!0,{},d,e),this.settings=a.extend(!0,{},c,e),this._defaults=c,"-"==this.settings.content.target&&(this.settings.content.target=this.settings.url_target),this.animations={start:"webkitAnimationStart oanimationstart MSAnimationStart animationstart",end:"webkitAnimationEnd oanimationend MSAnimationEnd animationend"},"number"==typeof this.settings.offset&&(this.settings.offset={x:this.settings.offset,y:this.settings.offset}),this.init()}var c={element:"body",position:null,type:"info",allow_dismiss:!0,newest_on_top:!1,showProgressbar:!1,placement:{from:"top",align:"right"},offset:20,spacing:10,z_index:1031,delay:5e3,timer:1e3,url_target:"_blank",mouse_over:null,animate:{enter:"animated fadeInDown",exit:"animated fadeOutUp"},onShow:null,onShown:null,onClose:null,onClosed:null,icon_type:"class",template:'
<button type="button" aria-hidden="true" class="close" data-notify="dismiss">×</button> {1} {2}

'};String.format=function(){for(var a=arguments[0],b=1;b<arguments.length;b++)a=a.replace(RegExp("\\{"+(b-1)+"\\}","gm"),arguments[b]);return a},a.extend(b.prototype,{init:function(){var a=this;this.buildNotify(),this.settings.content.icon&&this.setIcon(),"#"!=this.settings.content.url&&this.styleURL(),this.styleDismiss(),this.placement(),this.bind(),this.notify={$ele:this.$ele,update:function(b,c){var d={};"string"==typeof b?d[b]=c:d=b;for(var b in d)switch(b){case"type":this.$ele.removeClass("alert-"+a.settings.type),this.$ele.find('[data-notify="progressbar"] > .progress-bar').removeClass("progress-bar-"+a.settings.type),a.settings.type=d[b],this.$ele.addClass("alert-"+d[b]).find('[data-notify="progressbar"] > .progress-bar').addClass("progress-bar-"+d[b]);break;case"icon":var e=this.$ele.find('[data-notify="icon"]');"class"==a.settings.icon_type.toLowerCase()?e.removeClass(a.settings.content.icon).addClass(d[b]):(e.is("img")||e.find("img"),e.attr("src",d[b]));break;case"progress":var f=a.settings.delay-a.settings.delay*(d[b]/100);this.$ele.data("notify-delay",f),this.$ele.find('[data-notify="progressbar"] > div').attr("aria-valuenow",d[b]).css("width",d[b]+"%");break;case"url":this.$ele.find('[data-notify="url"]').attr("href",d[b]);break;case"target":this.$ele.find('[data-notify="url"]').attr("target",d[b]);break;default:this.$ele.find('[data-notify="'+b+'"]').html(d[b])}var g=this.$ele.outerHeight()+parseInt(a.settings.spacing)+parseInt(a.settings.offset.y);a.reposition(g)},close:function(){a.close()}}},buildNotify:function(){var b=this.settings.content;this.$ele=a(String.format(this.settings.template,this.settings.type,b.title,b.message,b.url,b.target)),this.$ele.attr("data-notify-position",this.settings.placement.from+"-"+this.settings.placement.align),this.settings.allow_dismiss||this.$ele.find('[data-notify="dismiss"]').css("display","none"),(this.settings.delay<=0&&!this.settings.showProgressbar||!this.settings.showProgressbar)&&this.$ele.find('[data-notify="progressbar"]').remove()},setIcon:function(){"class"==this.settings.icon_type.toLowerCase()?this.$ele.find('[data-notify="icon"]').addClass(this.settings.content.icon):this.$ele.find('[data-notify="icon"]').is("img")?this.$ele.find('[data-notify="icon"]').attr("src",this.settings.content.icon):this.$ele.find('[data-notify="icon"]').append('')},styleDismiss:function(){this.$ele.find('[data-notify="dismiss"]').css({position:"absolute",right:"10px",top:"5px",zIndex:this.settings.z_index+2})},styleURL:function(){this.$ele.find('[data-notify="url"]').css({backgroundImage:"url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)",height:"100%",left:"0px",position:"absolute",top:"0px",width:"100%",zIndex:this.settings.z_index+1})},placement:function(){var b=this,c=this.settings.offset.y,d={display:"inline-block",margin:"0px auto",position:this.settings.position?this.settings.position:"body"===this.settings.element?"fixed":"absolute",transition:"all .5s ease-in-out",zIndex:this.settings.z_index},e=!1,f=this.settings;switch(a('[data-notify-position="'+this.settings.placement.from+"-"+this.settings.placement.align+'"]:not([data-closing="true"])').each(function(){return c=Math.max(c,parseInt(a(this).css(f.placement.from))+parseInt(a(this).outerHeight())+parseInt(f.spacing))}),1==this.settings.newest_on_top&&(c=this.settings.offset.y),d[this.settings.placement.from]=c+"px",this.settings.placement.align){case"left":case"right":d[this.settings.placement.align]=this.settings.offset.x+"px";break;case"center":d.left=0,d.right=0}this.$ele.css(d).addClass(this.settings.animate.enter),a.each(Array("webkit","moz","o","ms",""),function(a,c){b.$ele[0].style[c+"AnimationIterationCount"]=1}),a(this.settings.element).append(this.$ele),1==this.settings.newest_on_top&&(c=parseInt(c)+parseInt(this.settings.spacing)+this.$ele.outerHeight(),this.reposition(c)),a.isFunction(b.settings.onShow)&&b.settings.onShow.call(this.$ele),this.$ele.one(this.animations.start,function(a){e=!0}).one(this.animations.end,function(c){a.isFunction(b.settings.onShown)&&b.settings.onShown.call(this)}),setTimeout(function(){e||a.isFunction(b.settings.onShown)&&b.settings.onShown.call(this)},600)},bind:function(){var b=this;if(this.$ele.find('[data-notify="dismiss"]').on("click",function(){b.close()}),this.$ele.mouseover(function(b){a(this).data("data-hover","true")}).mouseout(function(b){a(this).data("data-hover","false")}),this.$ele.data("data-hover","false"),this.settings.delay>0){b.$ele.data("notify-delay",b.settings.delay);var c=setInterval(function(){var a=parseInt(b.$ele.data("notify-delay"))-b.settings.timer;if("false"===b.$ele.data("data-hover")&&"pause"==b.settings.mouse_over||"pause"!=b.settings.mouse_over){var d=(b.settings.delay-a)/b.settings.delay*100;b.$ele.data("notify-delay",a),b.$ele.find('[data-notify="progressbar"] > div').attr("aria-valuenow",d).css("width",d+"%")}a<=-b.settings.timer&&(clearInterval(c),b.close())},b.settings.timer)}},close:function(){var b=this,c=parseInt(this.$ele.css(this.settings.placement.from)),d=!1;this.$ele.data("closing","true").addClass(this.settings.animate.exit),b.reposition(c),a.isFunction(b.settings.onClose)&&b.settings.onClose.call(this.$ele),this.$ele.one(this.animations.start,function(a){d=!0}).one(this.animations.end,function(c){a(this).remove(),a.isFunction(b.settings.onClosed)&&b.settings.onClosed.call(this)}),setTimeout(function(){d||(b.$ele.remove(),b.settings.onClosed&&b.settings.onClosed(b.$ele))},600)},reposition:function(b){var c=this,d='[data-notify-position="'+this.settings.placement.from+"-"+this.settings.placement.align+'"]:not([data-closing="true"])',e=this.$ele.nextAll(d);1==this.settings.newest_on_top&&(e=this.$ele.prevAll(d)),e.each(function(){a(this).css(c.settings.placement.from,b),b=parseInt(b)+parseInt(c.settings.spacing)+a(this).outerHeight()})}}),a.notify=function(a,c){var d=new b(this,a,c);return d.notify},a.notifyDefaults=function(b){return c=a.extend(!0,{},c,b)},a.notifyClose=function(b){"undefined"==typeof b||"all"==b?a("[data-notify]").find('[data-notify="dismiss"]').trigger("click"):a('[data-notify-position="'+b+'"]').find('[data-notify="dismiss"]').trigger("click")}});<commit_msg>Updating minified version<commit_after>!function(t){"function"==typeof define&&define.amd?define(["jquery"],t):t("object"==typeof exports?require("jquery"):jQuery)}(function(t){function s(s,i,n){var a={content:{message:"object"==typeof i?i.message:i,title:i.title?i.title:"",icon:i.icon?i.icon:"",url:i.url?i.url:"#",target:i.target?i.target:"-"}};n=t.extend(!0,{},a,n),this.settings=t.extend(!0,{},e,n),this._defaults=e,"-"==this.settings.content.target&&(this.settings.content.target=this.settings.url_target),this.animations={start:"webkitAnimationStart oanimationstart MSAnimationStart animationstart",end:"webkitAnimationEnd oanimationend MSAnimationEnd animationend"},"number"==typeof this.settings.offset&&(this.settings.offset={x:this.settings.offset,y:this.settings.offset}),this.init()}var e={element:"body",position:null,type:"info",allow_dismiss:!0,newest_on_top:!1,showProgressbar:!1,placement:{from:"top",align:"right"},offset:20,spacing:10,z_index:1031,delay:5e3,timer:1e3,url_target:"_blank",mouse_over:null,animate:{enter:"animated fadeInDown",exit:"animated fadeOutUp"},onShow:null,onShown:null,onClose:null,onClosed:null,icon_type:"class",template:'
<button type="button" aria-hidden="true" class="close" data-notify="dismiss">×</button> {1} {2}

'};String.format=function(){for(var t=arguments[0],s=1;s<arguments.length;s++)t=t.replace(RegExp("\\{"+(s-1)+"\\}","gm"),arguments[s]);return t},t.extend(s.prototype,{init:function(){var t=this;this.buildNotify(),this.settings.content.icon&&this.setIcon(),"#"!=this.settings.content.url&&this.styleURL(),this.styleDismiss(),this.placement(),this.bind(),this.notify={$ele:this.$ele,update:function(s,e){var i={};"string"==typeof s?i[s]=e:i=s;for(var n in i)switch(n){case"type":this.$ele.removeClass("alert-"+t.settings.type),this.$ele.find('[data-notify="progressbar"] > .progress-bar').removeClass("progress-bar-"+t.settings.type),t.settings.type=i[n],this.$ele.addClass("alert-"+i[n]).find('[data-notify="progressbar"] > .progress-bar').addClass("progress-bar-"+i[n]);break;case"icon":var a=this.$ele.find('[data-notify="icon"]');"class"==t.settings.icon_type.toLowerCase()?a.removeClass(t.settings.content.icon).addClass(i[n]):(a.is("img")||a.find("img"),a.attr("src",i[n]));break;case"progress":var o=t.settings.delay-t.settings.delay*(i[n]/100);this.$ele.data("notify-delay",o),this.$ele.find('[data-notify="progressbar"] > div').attr("aria-valuenow",i[n]).css("width",i[n]+"%");break;case"url":this.$ele.find('[data-notify="url"]').attr("href",i[n]);break;case"target":this.$ele.find('[data-notify="url"]').attr("target",i[n]);break;default:this.$ele.find('[data-notify="'+n+'"]').html(i[n])}var r=this.$ele.outerHeight()+parseInt(t.settings.spacing)+parseInt(t.settings.offset.y);t.reposition(r)},close:function(){t.close()}}},buildNotify:function(){var s=this.settings.content;this.$ele=t(String.format(this.settings.template,this.settings.type,s.title,s.message,s.url,s.target)),this.$ele.attr("data-notify-position",this.settings.placement.from+"-"+this.settings.placement.align),this.settings.allow_dismiss||this.$ele.find('[data-notify="dismiss"]').css("display","none"),(this.settings.delay>0||this.settings.showProgressbar)&&this.settings.showProgressbar||this.$ele.find('[data-notify="progressbar"]').remove()},setIcon:function(){"class"==this.settings.icon_type.toLowerCase()?this.$ele.find('[data-notify="icon"]').addClass(this.settings.content.icon):this.$ele.find('[data-notify="icon"]').is("img")?this.$ele.find('[data-notify="icon"]').attr("src",this.settings.content.icon):this.$ele.find('[data-notify="icon"]').append('')},styleDismiss:function(){this.$ele.find('[data-notify="dismiss"]').css({position:"absolute",right:"10px",top:"5px",zIndex:this.settings.z_index+2})},styleURL:function(){this.$ele.find('[data-notify="url"]').css({backgroundImage:"url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)",height:"100%",left:0,position:"absolute",top:0,width:"100%",zIndex:this.settings.z_index+1})},placement:function(){var s=this,e=this.settings.offset.y,i={display:"inline-block",margin:"0px auto",position:this.settings.position?this.settings.position:"body"===this.settings.element?"fixed":"absolute",transition:"all .5s ease-in-out",zIndex:this.settings.z_index},n=!1,a=this.settings;switch(t('[data-notify-position="'+this.settings.placement.from+"-"+this.settings.placement.align+'"]:not([data-closing="true"])').each(function(){e=Math.max(e,parseInt(t(this).css(a.placement.from))+parseInt(t(this).outerHeight())+parseInt(a.spacing))}),this.settings.newest_on_top===!0&&(e=this.settings.offset.y),i[this.settings.placement.from]=e+"px",this.settings.placement.align){case"left":case"right":i[this.settings.placement.align]=this.settings.offset.x+"px";break;case"center":i.left=0,i.right=0}this.$ele.css(i).addClass(this.settings.animate.enter),t.each(["webkit-","moz-","o-","ms-",""],function(t,e){s.$ele[0].style[e+"AnimationIterationCount"]=1}),t(this.settings.element).append(this.$ele),this.settings.newest_on_top===!0&&(e=parseInt(e)+parseInt(this.settings.spacing)+this.$ele.outerHeight(),this.reposition(e)),t.isFunction(s.settings.onShow)&&s.settings.onShow.call(this.$ele),this.$ele.one(this.animations.start,function(){n=!0}).one(this.animations.end,function(){t.isFunction(s.settings.onShown)&&s.settings.onShown.call(this)}),setTimeout(function(){n||t.isFunction(s.settings.onShown)&&s.settings.onShown.call(this)},600)},bind:function(){var s=this;if(this.$ele.find('[data-notify="dismiss"]').on("click",function(){s.close()}),this.$ele.mouseover(function(){t(this).data("data-hover","true")}).mouseout(function(){t(this).data("data-hover","false")}),this.$ele.data("data-hover","false"),this.settings.delay>0){s.$ele.data("notify-delay",s.settings.delay);var e=setInterval(function(){var t=parseInt(s.$ele.data("notify-delay"))-s.settings.timer;if("false"===s.$ele.data("data-hover")&&"pause"==s.settings.mouse_over||"pause"!=s.settings.mouse_over){var i=(s.settings.delay-t)/s.settings.delay*100;s.$ele.data("notify-delay",t),s.$ele.find('[data-notify="progressbar"] > div').attr("aria-valuenow",i).css("width",i+"%")}t>-s.settings.timer||(clearInterval(e),s.close())},s.settings.timer)}},close:function(){var s=this,e=parseInt(this.$ele.css(this.settings.placement.from)),i=!1;this.$ele.data("closing","true").addClass(this.settings.animate.exit),s.reposition(e),t.isFunction(s.settings.onClose)&&s.settings.onClose.call(this.$ele),this.$ele.one(this.animations.start,function(){i=!0}).one(this.animations.end,function(){t(this).remove(),t.isFunction(s.settings.onClosed)&&s.settings.onClosed.call(this)}),setTimeout(function(){i||(s.$ele.remove(),s.settings.onClosed&&s.settings.onClosed(s.$ele))},600)},reposition:function(s){var e=this,i='[data-notify-position="'+this.settings.placement.from+"-"+this.settings.placement.align+'"]:not([data-closing="true"])',n=this.$ele.nextAll(i);this.settings.newest_on_top===!0&&(n=this.$ele.prevAll(i)),n.each(function(){t(this).css(e.settings.placement.from,s),s=parseInt(s)+parseInt(e.settings.spacing)+t(this).outerHeight()})}}),t.notify=function(t,e){var i=new s(this,t,e);return i.notify},t.notifyDefaults=function(s){return e=t.extend(!0,{},e,s)},t.notifyClose=function(s){void 0===s||"all"==s?t("[data-notify]").find('[data-notify="dismiss"]').trigger("click"):t('[data-notify-position="'+s+'"]').find('[data-notify="dismiss"]').trigger("click")}});<|endoftext|>