<commit_before>/* jshint strict: false */

var gulp    = require('gulp'),
    map     = require('map-stream'),
    plugins = require('gulp-load-plugins')(),
    server  = require('tiny-lr')(),
    config  = require('./config.json');

// Prepare CSS
// ===========

// Compile SASS and add prefixes
var fnSass = function (path) {
    return gulp.src(path)
        .pipe(plugins.plumber())
        .pipe(plugins.filesize())    // .pipe(plugins.size({ showFiles: true }))
        .pipe(plugins.concat('main.scss'))
        .pipe(plugins.rubySass({ style: 'expanded' }))
        .pipe(plugins.autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
        .pipe(plugins.filesize())    // .pipe(plugins.size({ showFiles: true }))
        .pipe(gulp.dest(config.build + '/assets'));
};
gulp.task('styles:sass', function () {
    var files = [config.app + '/sass/main.scss', config.app + '/common/**/*.scss', config.app + '/app/**/*.scss'];
    return fnSass(files);
});

// Minify CSS
gulp.task('styles', ['styles:sass'], function () {
    return gulp.src(config.build + '/assets/*.css')
        .pipe(plugins.bytediff.start())
        .pipe(plugins.minifyCss({ keepSpecialComments: 0 }))
        .pipe(plugins.rename({ suffix: '.min' }))
        .pipe(plugins.bytediff.stop())
        .pipe(gulp.dest(config.dist + '/assets'));
});

// Prepare vendor files
// ====================

// Copy vendor JS files to /build/
gulp.task('vendor:js', function () {
    if (!config.vendor_files.js.length) {
        return;
    }
    return gulp.src(config.vendor_files.js, { base: '.' })
        .pipe(gulp.dest(config.build));
});

// Copy vendor assets to /build/
gulp.task('vendor:assets', function () {
    if (!config.vendor_files.assets.length) {
        return;
    }
    return gulp.src(config.vendor_files.assets)
        .pipe(gulp.dest(config.build + '/assets'));
});

// Prepare JavaScript
// ==================

// Cache AngularJS templates
var fnCacheTpls = function (path) {
    return gulp.src(path)
        .pipe(plugins.minifyHtml({
            empty: true,
            spare: true,
            quotes: true
        }))
        .pipe(plugins.angularTemplatecache({
            module: 'ngDevstack.templates',
            standalone: true
        }))
        .pipe(plugins.concat('templates.js'))
        .pipe(gulp.dest(config.build + '/app'));
};
gulp.task('scripts:cacheTpls', function () {
    return fnCacheTpls(config.paths.templates);
});

// Check JavaScript code quality with JSHint
var fnLint = function (path, exitOnError) {
    return gulp.src(path, { base: config.app })
        .pipe(plugins.plumber())
        .pipe(plugins.jshint())
        .pipe(plugins.jshint.reporter('jshint-stylish'))
        .pipe(map(function (file, cb) {
            if (!file.jshint.success && exitOnError) {
                process.exit(1);
            }
            cb(null, file);
        }))
        .pipe(gulp.dest(config.build));
};
gulp.task('scripts:lint', function () {
    return fnLint(config.paths.scripts, true);
});

// Concat and minify JavaScript
gulp.task('scripts', ['scripts:lint', 'scripts:cacheTpls', 'vendor:js'], function () {
    var arr = (config.vendor_files.js).concat(config.paths.scripts, config.build + '/app/templates.js');
    return gulp.src(arr)
        .pipe(plugins.concat('main.js'))
        .pipe(plugins.bytediff.start())
        .pipe(plugins.ngmin())
        .pipe(plugins.removelogs())
        .pipe(plugins.uglify())
        .pipe(plugins.rename({ suffix: '.min' }))
        .pipe(plugins.bytediff.stop())
        .pipe(gulp.dest(config.dist + '/assets'));
});

// Prepare assets
// ==============

// Copy assets
var fnImg = function (path) {
    return gulp.src(path, { base: config.app })
        .pipe(gulp.dest(config.build));
};
gulp.task('assets:img', function () {
    return fnImg(config.paths.assets);
});

// Compress images
gulp.task('assets', ['assets:img', 'vendor:assets'], function () {
    var arr = (config.vendor_files.assets).concat(config.paths.assets);
    return gulp.src(arr)
        .pipe(plugins.plumber())
        // .pipe(plugins.bytediff.start())
        .pipe(plugins.newer(config.dist + '/assets'))
        // .pipe(plugins.imagemin({ optimizationLevel: 5, progressive: true }))
        // .pipe(plugins.bytediff.stop())
        .pipe(gulp.dest(config.dist + '/assets'));
});

// Prepare HTML
// ============

// Inject CSS & JS to index.html source
var fnInject = function (path) {
    var inject = {
        css : (config.vendor_files.css).concat(config.build + '/assets/*.css'),
        js  : (config.vendor_files.js).concat(config.build + '/+(app|common)/**/*.js')
    };

    return gulp.src(inject.css.concat(inject.js), { read: false })
        .pipe(plugins.inject(path, {
            addRootSlash: false,
            ignorePath: ['/', config.build + '/']
        }))
        .pipe(gulp.dest(config.build));
};
gulp.task('html:inject', ['styles:sass', 'scripts:lint', 'scripts:cacheTpls'], function () {
    return fnInject(config.paths.html);
});

// Replace non-optimized HTML blocks
gulp.task('html:replace', ['html:inject'], function () {
    return gulp.src(config.build + '/index.html')
        .pipe(plugins.htmlReplace({
            css: 'assets/main.min.css',
            js: 'assets/main.min.js'
        }))
        .pipe(gulp.dest(config.dist));
});

// Compile and minify HTML
gulp.task('html', ['html:replace'], function () {
    return gulp.src(config.dist + '/index.html')
        .pipe(plugins.plumber())
        .pipe(plugins.minifyHtml({ quotes: true }))
        .pipe(gulp.dest(config.dist));
});

// Karma
// ============
var testFiles = [
    config.build + '/vendor/**/*.js',
    config.build + '/+(app|common)/**/*.js',
    config.mocks,
    config.paths.tests
];

gulp.task('test:run', ['vendor:assets'] , function() {
  // Be sure to return the stream
  return gulp.src(testFiles)
    .pipe(plugins.karma({
      configFile: 'karma.conf.js',
      action: 'run'
    }))
    .on('error', function(err) {
      process.exit(1);
    });
});

gulp.task('test:watch', ['vendor:assets'], function() {
  gulp.src(testFiles)
    .pipe(plugins.karma({
      configFile: 'karma.conf.js',
      action: 'watch'
    }));
});

// Set up Watch
// ============

// Add files to Watch
gulp.task('watch', ['styles:sass', 'scripts:lint', 'scripts:cacheTpls', 'assets:img', 'vendor:js', 'vendor:assets', 'test:watch', 'html:inject'], function () {
    require('./server.js')(server);

    // watch for JS changes
    gulp.watch(config.paths.scripts, function (event) {
        if (event.path.lastIndexOf('.js') === event.path.length - 3) {
            if (event.type === 'deleted') {
                var buildPath = event.path.replace(config.app, config.build);
                return gulp.src(buildPath, { read: false })
                    .pipe(plugins.rimraf());
            } else {
                return fnLint(event.path).pipe(plugins.livereload(server));
            }
        }
    });

    // remove deleted JS files from index.html
    gulp.watch(config.build + '/+(app|common)/**/*.js', function (event) {
        if (event.type !== 'changed') {
            return fnInject(config.paths.html).pipe(plugins.livereload(server));
        }
    });

    // watch AngularJS templates to cache
    gulp.watch(config.app + '/+(app|common)/**', function (event) {
        if (event.path.lastIndexOf('.tpl.html') === event.path.length - 9) {
            return fnCacheTpls(config.paths.templates).pipe(plugins.livereload(server));
        }
    });

    // watch for SASS changes
    gulp.watch(config.paths.sass, function (event) {
        if (event.path.lastIndexOf('.scss') === event.path.length - 5) {
            var files = [
                config.app + '/sass/main.scss',
                config.app + '/+(app|common)/**/*.scss'
            ];
            return fnSass(files).pipe(plugins.livereload(server));
        }
    });

    gulp.watch(config.paths.assets, function (event) {
        if (event.type === 'deleted') {
            var buildPath = event.path.replace(config.app, config.build);
            return gulp.src(buildPath, { read: false })
                .pipe(plugins.rimraf());
        } else {
            return fnImg(event.path).pipe(plugins.livereload(server));
        }
    });

    gulp.watch(config.paths.html, function (event) {
        return fnInject(event.path).pipe(plugins.livereload(server));
    });
});

// Clean up development & production directories
// =============================================

gulp.task('clean', function () {
    return gulp.src([config.build, config.dist], { read: false })
        .pipe(plugins.rimraf());
});

// Main gulp tasks
// ===============

gulp.task('build', ['clean'], function () {
    gulp.start('styles:sass', 'scripts:lint', 'scripts:cacheTpls', 'vendor:js', 'vendor:assets', 'test:run', 'assets:img', 'html:inject');
});

gulp.task('compile', ['build'], function () {
    gulp.start('styles', 'scripts', 'assets', 'html');
});

gulp.task('default', function () {
    gulp.start('compile');
});
<commit_msg>fix(build): fixed running Karma after updating to latest version<commit_after>/* jshint strict: false */

var gulp    = require('gulp'),
    map     = require('map-stream'),
    plugins = require('gulp-load-plugins')(),
    server  = require('tiny-lr')(),
    config  = require('./config.json');

// Prepare CSS
// ===========

// Compile SASS and add prefixes
var fnSass = function (path) {
    return gulp.src(path)
        .pipe(plugins.plumber())
        .pipe(plugins.filesize())    // .pipe(plugins.size({ showFiles: true }))
        .pipe(plugins.concat('main.scss'))
        .pipe(plugins.rubySass({ style: 'expanded' }))
        .pipe(plugins.autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
        .pipe(plugins.filesize())    // .pipe(plugins.size({ showFiles: true }))
        .pipe(gulp.dest(config.build + '/assets'));
};
gulp.task('styles:sass', function () {
    var files = [config.app + '/sass/main.scss', config.app + '/common/**/*.scss', config.app + '/app/**/*.scss'];
    return fnSass(files);
});

// Minify CSS
gulp.task('styles', ['styles:sass'], function () {
    return gulp.src(config.build + '/assets/*.css')
        .pipe(plugins.bytediff.start())
        .pipe(plugins.minifyCss({ keepSpecialComments: 0 }))
        .pipe(plugins.rename({ suffix: '.min' }))
        .pipe(plugins.bytediff.stop())
        .pipe(gulp.dest(config.dist + '/assets'));
});

// Prepare vendor files
// ====================

// Copy vendor JS files to /build/
gulp.task('vendor:js', function () {
    if (!config.vendor_files.js.length) {
        return;
    }
    return gulp.src(config.vendor_files.js, { base: '.' })
        .pipe(gulp.dest(config.build));
});

// Copy vendor assets to /build/
gulp.task('vendor:assets', function () {
    if (!config.vendor_files.assets.length) {
        return;
    }
    return gulp.src(config.vendor_files.assets)
        .pipe(gulp.dest(config.build + '/assets'));
});

// Prepare JavaScript
// ==================

// Cache AngularJS templates
var fnCacheTpls = function (path) {
    return gulp.src(path)
        .pipe(plugins.minifyHtml({
            empty: true,
            spare: true,
            quotes: true
        }))
        .pipe(plugins.angularTemplatecache({
            module: 'ngDevstack.templates',
            standalone: true
        }))
        .pipe(plugins.concat('templates.js'))
        .pipe(gulp.dest(config.build + '/app'));
};
gulp.task('scripts:cacheTpls', function () {
    return fnCacheTpls(config.paths.templates);
});

// Check JavaScript code quality with JSHint
var fnLint = function (path, exitOnError) {
    return gulp.src(path, { base: config.app })
        .pipe(plugins.plumber())
        .pipe(plugins.jshint())
        .pipe(plugins.jshint.reporter('jshint-stylish'))
        .pipe(map(function (file, cb) {
            if (!file.jshint.success && exitOnError) {
                process.exit(1);
            }
            cb(null, file);
        }))
        .pipe(gulp.dest(config.build));
};
gulp.task('scripts:lint', function () {
    return fnLint(config.paths.scripts, true);
});

// Concat and minify JavaScript
gulp.task('scripts', ['scripts:lint', 'scripts:cacheTpls', 'vendor:js'], function () {
    var arr = (config.vendor_files.js).concat(config.paths.scripts, config.build + '/app/templates.js');
    return gulp.src(arr)
        .pipe(plugins.concat('main.js'))
        .pipe(plugins.bytediff.start())
        .pipe(plugins.ngmin())
        .pipe(plugins.removelogs())
        .pipe(plugins.uglify())
        .pipe(plugins.rename({ suffix: '.min' }))
        .pipe(plugins.bytediff.stop())
        .pipe(gulp.dest(config.dist + '/assets'));
});

// Prepare assets
// ==============

// Copy assets
var fnImg = function (path) {
    return gulp.src(path, { base: config.app })
        .pipe(gulp.dest(config.build));
};
gulp.task('assets:img', function () {
    return fnImg(config.paths.assets);
});

// Compress images
gulp.task('assets', ['assets:img', 'vendor:assets'], function () {
    var arr = (config.vendor_files.assets).concat(config.paths.assets);
    return gulp.src(arr)
        .pipe(plugins.plumber())
        // .pipe(plugins.bytediff.start())
        .pipe(plugins.newer(config.dist + '/assets'))
        // .pipe(plugins.imagemin({ optimizationLevel: 5, progressive: true }))
        // .pipe(plugins.bytediff.stop())
        .pipe(gulp.dest(config.dist + '/assets'));
});

// Prepare HTML
// ============

// Inject CSS & JS to index.html source
var fnInject = function (path) {
    var inject = {
        css : (config.vendor_files.css).concat(config.build + '/assets/*.css'),
        js  : (config.vendor_files.js).concat(config.build + '/+(app|common)/**/*.js')
    };

    return gulp.src(inject.css.concat(inject.js), { read: false })
        .pipe(plugins.inject(path, {
            addRootSlash: false,
            ignorePath: ['/', config.build + '/']
        }))
        .pipe(gulp.dest(config.build));
};
gulp.task('html:inject', ['styles:sass', 'scripts:lint', 'scripts:cacheTpls'], function () {
    return fnInject(config.paths.html);
});

// Replace non-optimized HTML blocks
gulp.task('html:replace', ['html:inject'], function () {
    return gulp.src(config.build + '/index.html')
        .pipe(plugins.htmlReplace({
            css: 'assets/main.min.css',
            js: 'assets/main.min.js'
        }))
        .pipe(gulp.dest(config.dist));
});

// Compile and minify HTML
gulp.task('html', ['html:replace'], function () {
    return gulp.src(config.dist + '/index.html')
        .pipe(plugins.plumber())
        .pipe(plugins.minifyHtml({ quotes: true }))
        .pipe(gulp.dest(config.dist));
});

// Karma
// ============
var testFiles = [
    config.build + '/vendor/**/*.js',
    config.build + '/+(app|common)/**/*.js',
    config.mocks,
    config.paths.tests
];

gulp.task('test:run', ['scripts:lint', 'scripts:cacheTpls', 'vendor:assets'] , function() {
  // Be sure to return the stream
  return gulp.src(testFiles)
    .pipe(plugins.karma({
      configFile: 'karma.conf.js',
      action: 'run'
    }))
    .on('error', function(err) {
      process.exit(1);
    });
});

gulp.task('test:watch', ['vendor:assets'], function() {
  gulp.src(testFiles)
    .pipe(plugins.karma({
      configFile: 'karma.conf.js',
      action: 'watch'
    }));
});

// Set up Watch
// ============

// Add files to Watch
gulp.task('watch', ['styles:sass', 'scripts:lint', 'scripts:cacheTpls', 'assets:img', 'vendor:js', 'vendor:assets', 'test:watch', 'html:inject'], function () {
    require('./server.js')(server);

    // watch for JS changes
    gulp.watch(config.paths.scripts, function (event) {
        if (event.path.lastIndexOf('.js') === event.path.length - 3) {
            if (event.type === 'deleted') {
                var buildPath = event.path.replace(config.app, config.build);
                return gulp.src(buildPath, { read: false })
                    .pipe(plugins.rimraf());
            } else {
                return fnLint(event.path).pipe(plugins.livereload(server));
            }
        }
    });

    // remove deleted JS files from index.html
    gulp.watch(config.build + '/+(app|common)/**/*.js', function (event) {
        if (event.type !== 'changed') {
            return fnInject(config.paths.html).pipe(plugins.livereload(server));
        }
    });

    // watch AngularJS templates to cache
    gulp.watch(config.app + '/+(app|common)/**', function (event) {
        if (event.path.lastIndexOf('.tpl.html') === event.path.length - 9) {
            return fnCacheTpls(config.paths.templates).pipe(plugins.livereload(server));
        }
    });

    // watch for SASS changes
    gulp.watch(config.paths.sass, function (event) {
        if (event.path.lastIndexOf('.scss') === event.path.length - 5) {
            var files = [
                config.app + '/sass/main.scss',
                config.app + '/+(app|common)/**/*.scss'
            ];
            return fnSass(files).pipe(plugins.livereload(server));
        }
    });

    gulp.watch(config.paths.assets, function (event) {
        if (event.type === 'deleted') {
            var buildPath = event.path.replace(config.app, config.build);
            return gulp.src(buildPath, { read: false })
                .pipe(plugins.rimraf());
        } else {
            return fnImg(event.path).pipe(plugins.livereload(server));
        }
    });

    gulp.watch(config.paths.html, function (event) {
        return fnInject(event.path).pipe(plugins.livereload(server));
    });
});

// Clean up development & production directories
// =============================================

gulp.task('clean', function () {
    return gulp.src([config.build, config.dist], { read: false })
        .pipe(plugins.rimraf());
});

// Main gulp tasks
// ===============

gulp.task('build', ['clean'], function () {
    gulp.start('styles:sass', 'scripts:lint', 'scripts:cacheTpls', 'vendor:js', 'vendor:assets', 'test:run', 'assets:img', 'html:inject');
});

gulp.task('compile', ['build'], function () {
    gulp.start('styles', 'scripts', 'assets', 'html');
});

gulp.task('default', function () {
    gulp.start('compile');
});
<|endoftext|>


<commit_before>/*

UI-Util module
Author: Flavio De Stefano
Company: Caffeina SRL

*/

exports.ListView = {

	createFromCollection: function(C, opt) {
		var sec = [];
		var array = [];

		if (opt.groupBy) {
			if (C instanceof Backbone.Collection) {
				array = C.groupBy(opt.groupBy);
			} else {
				array = _.groupBy(C, opt.groupBy);
			}
		} else {
			if (C instanceof Backbone.Collection) {
				array = C.toJSON();
			} else {
				array = C;
			}
		}

		_.each(array, function(els, key){
			var dataset = [];
			_.each(els, function(el){
				dataset.push(opt.datasetCb(el));
			});

			var s = Ti.UI.createListSection({ items: dataset });

			if (opt.headerViewCb) {
				s.headerView = opt.headerViewCb(key);
			} else {
				s.headerTitle = key;
			}

			sec.push(s);
		});

		return sec;
	}

};<commit_msg>UiUtil fixes<commit_after>/*

UI-Util module
Author: Flavio De Stefano
Company: Caffeina SRL

*/

var config = _.extend({}, Alloy.CFG.uiutil);

exports.ListView = {

	createFromCollection: function(C, opt) {
		var array = [];
		var dataset = [];

		if (opt.groupBy) {

			if (C instanceof Backbone.Collection) {
				array = C.groupBy(opt.groupBy);
			} else {
				array = _.groupBy(C, opt.groupBy);
			}

			var sec = [];
			_.each(array, function(els, key){
				_.each(els, function(el){
					dataset.push(opt.datasetCb(el));
				});

				var s = Ti.UI.createListSection({ items: dataset });

				if (opt.headerViewCb) {
					s.headerView = opt.headerViewCb(key);
				} else {
					s.headerTitle = key;
				}

				sec.push(s);
			});

			return sec;

		} else {

			if (C instanceof Backbone.Collection) {
				array = C.toJSON();
			} else {
				array = C;
			}

			_.each(array, function(el){
				dataset.push(opt.datasetCb(el));
			});

			return [ Ti.UI.createListSection({ items: dataset }) ];

		}

	}

};<|endoftext|>


<commit_before>const deployDir = 'dist';

const copyTheseFilesToDist = [
  './src/*.png'
];

const dontVulcanizeTheseFiles = [
  './src/sw/sw.js'
];

var babel = require('gulp-babel');
var browserSync = require('browser-sync');
var clean = require('gulp-clean');
var concat = require('gulp-concat');
var crisper = require('gulp-crisper');
var debug = require('gulp-debug');
var filter = require('gulp-filter');
var ghPages = require('gulp-gh-pages');
var gulp = require('gulp');
var inject = require('gulp-inject');
var injectVersion = require('gulp-inject-version');
var jshint = require('gulp-jshint');
var minifyCss = require('gulp-clean-css');
var minifyHtml = require('gulp-minify-html');
var uglify = require('gulp-uglify');
var vulcanize = require('gulp-vulcanize');

gulp.task('default', ['vulcanize', 'copy-files']);

gulp.task('copy-files', ['clean'], function() {
    gulp.src(['sw/sw.js'])
        .pipe(gulp.dest('./dist/'));
  return gulp.src([...dontVulcanizeTheseFiles, ...copyTheseFilesToDist], {base: './src'})
    .pipe(debug('copied files'))
    .pipe(gulp.dest('./dist/'));
});

gulp.task('vulcanize', ['clean'], function() {

  var jsFilter = filter(['**/*.js'], {restore: true});
  var htmlFilter = filter(['**/*.html'], {restore: true});

  gulp.src('./src/index.html').pipe(vulcanize({
    excludes: dontVulcanizeTheseFiles,
    stripComments: true,
    inlineCss: true,
    inlineScripts: true
  }))
    .pipe(crisper())

    .pipe(htmlFilter)
    .pipe(minifyHtml())
    .pipe(htmlFilter.restore)

    .pipe(jsFilter)
    .pipe(babel({
      presets: ["es2015"],
      compact: true
    }))
    .pipe(jsFilter.restore)

    .pipe(injectVersion())
    .pipe(gulp.dest(deployDir));
});

gulp.task('build', ['build-html', 'build-sw']);

gulp.task('clean', function () {
  return gulp.src(deployDir)
      .pipe(clean());
});

gulp.task('lint', function () {
  return gulp.src(['gulpfile.js, ./src/**.js'])
      .pipe(jshint({
        eqeqeq: true,
        esversion: 6,
        eqnull: true
      }))
      .pipe(jshint.reporter('jshint-stylish'))
      .pipe(jshint.reporter('fail'));
});

gulp.task('gh-deploy', ['build'], () => {
  return gulp.src(deployDir + '/**/*')
    .pipe(ghPages({
      remote: "origin",
      branch: "gh-pages"
    }));
});

gulp.task('serve', function () {
  browserSync({
    server: {
      baseDir: './src/'
    },
    notify: false
  });
  gulp.watch(['./src/*'], browserSync.reload);
});
<commit_msg>remove buid tasks<commit_after>const deployDir = 'dist';

const copyTheseFilesToDist = [
  './src/*.png'
];

const dontVulcanizeTheseFiles = [
  './src/sw/sw.js'
];

var babel = require('gulp-babel');
var browserSync = require('browser-sync');
var clean = require('gulp-clean');
var concat = require('gulp-concat');
var crisper = require('gulp-crisper');
var debug = require('gulp-debug');
var filter = require('gulp-filter');
var ghPages = require('gulp-gh-pages');
var gulp = require('gulp');
var inject = require('gulp-inject');
var injectVersion = require('gulp-inject-version');
var jshint = require('gulp-jshint');
var minifyCss = require('gulp-clean-css');
var minifyHtml = require('gulp-minify-html');
var uglify = require('gulp-uglify');
var vulcanize = require('gulp-vulcanize');

gulp.task('default', ['vulcanize', 'copy-files']);

gulp.task('copy-files', ['clean'], function() {
    gulp.src(['sw/sw.js'])
        .pipe(gulp.dest('./dist/'));
  return gulp.src([...dontVulcanizeTheseFiles, ...copyTheseFilesToDist], {base: './src'})
    .pipe(debug('copied files'))
    .pipe(gulp.dest('./dist/'));
});

gulp.task('vulcanize', ['clean'], function() {

  var jsFilter = filter(['**/*.js'], {restore: true});
  var htmlFilter = filter(['**/*.html'], {restore: true});

  gulp.src('./src/index.html').pipe(vulcanize({
    excludes: dontVulcanizeTheseFiles,
    stripComments: true,
    inlineCss: true,
    inlineScripts: true
  }))
    .pipe(crisper())

    .pipe(htmlFilter)
    .pipe(minifyHtml())
    .pipe(htmlFilter.restore)

    .pipe(jsFilter)
    .pipe(babel({
      presets: ["es2015"],
      compact: true
    }))
    .pipe(jsFilter.restore)

    .pipe(injectVersion())
    .pipe(gulp.dest(deployDir));
});

gulp.task('clean', function () {
  return gulp.src(deployDir)
      .pipe(clean());
});

gulp.task('lint', function () {
  return gulp.src(['gulpfile.js, ./src/**.js'])
      .pipe(jshint({
        eqeqeq: true,
        esversion: 6,
        eqnull: true
      }))
      .pipe(jshint.reporter('jshint-stylish'))
      .pipe(jshint.reporter('fail'));
});

gulp.task('gh-deploy', ['vulcanize'], () => {
  return gulp.src(deployDir + '/**/*')
    .pipe(ghPages({
      remote: "origin",
      branch: "gh-pages"
    }));
});

gulp.task('serve', function () {
  browserSync({
    server: {
      baseDir: './src/'
    },
    notify: false
  });
  gulp.watch(['./src/*'], browserSync.reload);
});
<|endoftext|>


<commit_before>(function() {
  'use strict';

  var gulp = require('gulp');
  var bumper = require('gulp-bump');
  var git = require('gulp-git');
  var shell = require('gulp-shell');
  var rename = require('gulp-rename');
  var fs = require('fs');
  var sequence = require('gulp-sequence');
  var path = require('path');
  var eslint = require('gulp-eslint');
  var excludeGitignore = require('gulp-exclude-gitignore');
  var mocha = require('gulp-mocha');
  var istanbul = require('gulp-istanbul');
  var nsp = require('gulp-nsp');
  var plumber = require('gulp-plumber');

  gulp.task('static', function () {
    return gulp.src('**/*.js')
      .pipe(excludeGitignore())
      .pipe(eslint())
      .pipe(eslint.format())
      .pipe(eslint.failAfterError());
  });

  gulp.task('nsp', function (cb) {
    nsp({package: path.resolve('package.json')}, cb);
  });

  gulp.task('pre-test', function () {
    return gulp.src('generators/**/*.js')
      .pipe(istanbul({
        includeUntested: true
      }))
      .pipe(istanbul.hookRequire());
  });

  gulp.task('test', ['pre-test'], function (cb) {
    var mochaErr;

    gulp.src('test/**/*.js')
      .pipe(plumber())
      .pipe(mocha({reporter: 'spec'}))
      .on('error', function (err) {
        mochaErr = err;
      })
      .pipe(istanbul.writeReports())
      .on('end', function () {
        cb(mochaErr);
      });
  });

  gulp.task('bump-patch', bump('patch'));
  gulp.task('bump-minor', bump('minor'));
  gulp.task('bump-major', bump('major'));

  gulp.task('git-commit', function() {
    var v = 'update to version ' + version();
    gulp.src(['./generators/**/*','./README.md', './package.json', './gulpfile.js', './.travis.yml', './travis/**/*'])
      .pipe(git.add())
      .pipe(git.commit(v));
  });

  gulp.task('git-push', function(cb) {
    var v = 'v' + version();
    git.push('origin', 'master', function(err) {
      if (err) return cb(err);
      git.tag(v, v, function(err) {
        if (err) return cb(err);
        git.push('origin', 'master', {
          args: '--tags'
        }, cb);
      });
    });
  });

  gulp.task('npm', shell.task([
    'npm publish'
  ]));

  function bump(level) {
    return function() {
      return gulp.src(['./package.json'])
        .pipe(bumper({
          type: level
        }))
        .pipe(gulp.dest('./'));
    };
  }

  function version() {
    return JSON.parse(fs.readFileSync('package.json', 'utf8')).version;
  }

  gulp.task('prepublish', ['nsp']);
  gulp.task('default', ['static', 'test']);
  gulp.task('deploy-patch', sequence('test', 'bump-patch', 'git-commit', 'git-push', 'npm'));
  gulp.task('deploy-minor', sequence('test', 'bump-minor', 'git-commit', 'git-push', 'npm'));
  gulp.task('deploy-major', sequence('test', 'bump-major', 'git-commit', 'git-push', 'npm'));

})();
<commit_msg>fix testing via gulp<commit_after>(function() {
  'use strict';

  var gulp = require('gulp');
  var bumper = require('gulp-bump');
  var git = require('gulp-git');
  var shell = require('gulp-shell');
  var rename = require('gulp-rename');
  var fs = require('fs');
  var sequence = require('gulp-sequence');
  var path = require('path');
  var eslint = require('gulp-eslint');
  var excludeGitignore = require('gulp-exclude-gitignore');
  var mocha = require('gulp-mocha');
  var istanbul = require('gulp-istanbul');
  var nsp = require('gulp-nsp');
  var plumber = require('gulp-plumber');

  gulp.task('static', function () {
    return gulp.src('**/*.js')
      .pipe(excludeGitignore())
      .pipe(eslint())
      .pipe(eslint.format())
      .pipe(eslint.failAfterError());
  });

  gulp.task('nsp', function (cb) {
    nsp({package: path.resolve('package.json')}, cb);
  });

  gulp.task('pre-test', function () {
    return gulp.src(['generators/app/index.js'])
      .pipe(istanbul({
        includeUntested: true
      }))
      .pipe(istanbul.hookRequire());
  });

  gulp.task('test', ['pre-test'], function (cb) {
    var mochaErr;

    gulp.src('test/**/*.js')
      .pipe(plumber())
      .pipe(mocha({reporter: 'spec'}))
      .on('error', function (err) {
        mochaErr = err;
      })
      .pipe(istanbul.writeReports())
      .on('end', function () {
        cb(mochaErr);
      });
  });

  gulp.task('bump-patch', bump('patch'));
  gulp.task('bump-minor', bump('minor'));
  gulp.task('bump-major', bump('major'));

  gulp.task('git-commit', function() {
    var v = 'update to version ' + version();
    gulp.src(['./generators/**/*','./README.md', './package.json', './gulpfile.js', './.travis.yml', './travis/**/*'])
      .pipe(git.add())
      .pipe(git.commit(v));
  });

  gulp.task('git-push', function(cb) {
    var v = 'v' + version();
    git.push('origin', 'master', function(err) {
      if (err) return cb(err);
      git.tag(v, v, function(err) {
        if (err) return cb(err);
        git.push('origin', 'master', {
          args: '--tags'
        }, cb);
      });
    });
  });

  gulp.task('npm', shell.task([
    'npm publish'
  ]));

  function bump(level) {
    return function() {
      return gulp.src(['./package.json'])
        .pipe(bumper({
          type: level
        }))
        .pipe(gulp.dest('./'));
    };
  }

  function version() {
    return JSON.parse(fs.readFileSync('package.json', 'utf8')).version;
  }

  gulp.task('prepublish', ['nsp']);
  gulp.task('default', ['static', 'test']);
  gulp.task('deploy-patch', sequence('test', 'bump-patch', 'git-commit', 'git-push', 'npm'));
  gulp.task('deploy-minor', sequence('test', 'bump-minor', 'git-commit', 'git-push', 'npm'));
  gulp.task('deploy-major', sequence('test', 'bump-major', 'git-commit', 'git-push', 'npm'));

})();
<|endoftext|>


<commit_before>+function() {
    'use strict';

    // A lot of javascript developers will hate me for
    // extending the standard objects but I honestly
    // don't care.

    // Alias the objects
    var string = String,
        array = Array,
        object = Object,
        number = Number;

	function extend(obj, name, func) {
		object.defineProperty(obj.prototype, name, {
			enumerable: false,
			value: func
		});
	}

    // Extending existing stuff
    /**
     * @function regex escape
     * @module Misc
     * @param {string} str - String to be escaped
     * Escapes a string so that it can safely be used in a regex.
     * Taken from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript/3561711#3561711
     */
    RegExp.escape = function(str) {
        return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    };

    // String methods

    /**
     * Trims the start and end of a string
     * @function trim
     * @module String
     * @param {string} [str= ] - A set of trimable characters
     * @example "#!#!Hey!#!#!".trim('#!') == "Hey"
     */
    extend(string, 'trim', function(str) {
        str = RegExp.escape(str || ' ');
	    return this.replace(new RegExp('^[' + str + ']+|[' + str + ']+$', 'g'), '');
    });

    /**
     * Trims the start of a string
     * @function ltrim
     * @module String
     * @param {string} [str= ] - A set of trimable characters
     * @example "#!#!Hey!#!#!".ltrim('#!') == "Hey!#!#!"
     */
    extend(string, 'ltrim', function(str) {
        str = RegExp.escape(str || ' ');
	    return this.replace(new RegExp('^[' + str + ']+'), '');
    });

    /**
     * Trims the end of a string
     * @function rtrim
     * @module String
     * @param {string} [str= ] - A set of trimable characters
     * @example "#!#!Hey!#!#!".rtrim('#!') == "#!#!Hey"
     */
    extend(string, 'rtrim', function(str) {
        str = RegExp.escape(str || ' ');
	    return this.replace(new RegExp('[' + str + ']+$'), '');
    });

    /**
     * @function capitalize
     * @module String
     * Makes the first character uppercase
     * @example "hello world!".capitalize() === "Hello world!"
     */
    extend(string, 'capitalize', function() {
        return this.charAt(0).toUpperCase() + this.slice(1);
    });

    /**
     * @function reverse
     * @module String
     * Reverses the string
     * @example "Hello World!".reverse() === "!dlroW olleH";
     */
    extend(string, 'reverse', function() {
        return this.split("").reverse().join("");
    });

    /**
     * @function contains
     * @module String
     * @param {string} what - What to search for
     * Test if the string contains a substring
     * @example "Quick brown fox".contains("brown") === true
     */
    extend(string, 'contains', function(what) {
        return this.indexOf(what) !== -1;
    });

    /**
     * @function endsWith
     * @module String
     * @param {string} what - What to search for
     * Tests if a string ends with the provided string
     * @example "Hello World".endsWith("World") === true
     */
    extend(string, 'endsWith', function(what) {
        return this.indexOf(what, this.length - what.length) !== -1;
    });

    // Taken from stackoverflow.com's javascript minus the regex
    /**
     * @function format
     * @module String
     * Tests if a string ends with the provided string
     * @example "Hello {1} {0}!".format("Doe", "John")
     * @example "Hello {first} {last}!".format({first: "John", last: "Doe"})
     */
    extend(string, 'format', function() {
        var str = this.toString();
        if (!arguments.length) {
            return str;
        }

        var args = typeof arguments[0],
            args = (("string" == args || "number" == args) ? arguments : arguments[0]);

        for (var arg in args) {
            str = str.replace("{" + arg + "}", args[arg]);
        }

        return str;
    });

    // Array methods
    /**
     * @function contains
     * @module Array
     * @param {string} item - The item to search for
     * Tests if the array contains the item
     * @example ["Blue", "Red", "Green"].contains("Red")
     */
    extend(array, 'contains', function(item) {
        return this.indexOf(item) !== -1;
    });

    /**
     * @function first
     * @module Array
     * @param {integer} [amount=1] - How many items to return
     * Fetches the first n items
     * @example ["Blue", "Red", "Green"].first(2) === ["Blue", "Red"]
     * @example ["Blue", "Red", "Green"].first() === "Blue"
     * @example ["Blue", "Red", "Green"].first(1) === ["Blue"]
     */
    extend(array, 'first', function(amount) {
        var ret = this.slice(0, Math.max(0, amount == null ? 1 : amount));
        return amount === undefined ? ret[0] : ret;
    });

    /**
     * @alias first
     * @module Array
     */
	extend(array, 'take', Array.prototype.first)

    // Object methods

    // Number methods
    /**
     * @function isNaN
     * @module Number
     * Test if you're dealing with number
     * @example (+"asd").isNaN() === true
     */
    extend(number, 'isNaN', function() {
        return +this !== +this;
    });
}()
<commit_msg>Fix indenting<commit_after>+function() {
    'use strict';

    // A lot of javascript developers will hate me for
    // extending the standard objects but I honestly
    // don't care.

    // Alias the objects
    var string = String,
        array = Array,
        object = Object,
        number = Number;

    function extend(obj, name, func) {
        object.defineProperty(obj.prototype, name, {
            enumerable: false,
            value: func
        });
    }

    // Extending existing stuff
    /**
     * @function regex escape
     * @module Misc
     * @param {string} str - String to be escaped
     * Escapes a string so that it can safely be used in a regex.
     * Taken from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript/3561711#3561711
     */
    RegExp.escape = function(str) {
        return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    };

    // String methods

    /**
     * Trims the start and end of a string
     * @function trim
     * @module String
     * @param {string} [str= ] - A set of trimable characters
     * @example "#!#!Hey!#!#!".trim('#!') == "Hey"
     */
    extend(string, 'trim', function(str) {
        str = RegExp.escape(str || ' ');
	    return this.replace(new RegExp('^[' + str + ']+|[' + str + ']+$', 'g'), '');
    });

    /**
     * Trims the start of a string
     * @function ltrim
     * @module String
     * @param {string} [str= ] - A set of trimable characters
     * @example "#!#!Hey!#!#!".ltrim('#!') == "Hey!#!#!"
     */
    extend(string, 'ltrim', function(str) {
        str = RegExp.escape(str || ' ');
	    return this.replace(new RegExp('^[' + str + ']+'), '');
    });

    /**
     * Trims the end of a string
     * @function rtrim
     * @module String
     * @param {string} [str= ] - A set of trimable characters
     * @example "#!#!Hey!#!#!".rtrim('#!') == "#!#!Hey"
     */
    extend(string, 'rtrim', function(str) {
        str = RegExp.escape(str || ' ');
	    return this.replace(new RegExp('[' + str + ']+$'), '');
    });

    /**
     * @function capitalize
     * @module String
     * Makes the first character uppercase
     * @example "hello world!".capitalize() === "Hello world!"
     */
    extend(string, 'capitalize', function() {
        return this.charAt(0).toUpperCase() + this.slice(1);
    });

    /**
     * @function reverse
     * @module String
     * Reverses the string
     * @example "Hello World!".reverse() === "!dlroW olleH";
     */
    extend(string, 'reverse', function() {
        return this.split("").reverse().join("");
    });

    /**
     * @function contains
     * @module String
     * @param {string} what - What to search for
     * Test if the string contains a substring
     * @example "Quick brown fox".contains("brown") === true
     */
    extend(string, 'contains', function(what) {
        return this.indexOf(what) !== -1;
    });

    /**
     * @function endsWith
     * @module String
     * @param {string} what - What to search for
     * Tests if a string ends with the provided string
     * @example "Hello World".endsWith("World") === true
     */
    extend(string, 'endsWith', function(what) {
        return this.indexOf(what, this.length - what.length) !== -1;
    });

    // Taken from stackoverflow.com's javascript minus the regex
    /**
     * @function format
     * @module String
     * Tests if a string ends with the provided string
     * @example "Hello {1} {0}!".format("Doe", "John")
     * @example "Hello {first} {last}!".format({first: "John", last: "Doe"})
     */
    extend(string, 'format', function() {
        var str = this.toString();
        if (!arguments.length) {
            return str;
        }

        var args = typeof arguments[0],
            args = (("string" == args || "number" == args) ? arguments : arguments[0]);

        for (var arg in args) {
            str = str.replace("{" + arg + "}", args[arg]);
        }

        return str;
    });

    // Array methods
    /**
     * @function contains
     * @module Array
     * @param {string} item - The item to search for
     * Tests if the array contains the item
     * @example ["Blue", "Red", "Green"].contains("Red")
     */
    extend(array, 'contains', function(item) {
        return this.indexOf(item) !== -1;
    });

    /**
     * @function first
     * @module Array
     * @param {integer} [amount=1] - How many items to return
     * Fetches the first n items
     * @example ["Blue", "Red", "Green"].first(2) === ["Blue", "Red"]
     * @example ["Blue", "Red", "Green"].first() === "Blue"
     * @example ["Blue", "Red", "Green"].first(1) === ["Blue"]
     */
    extend(array, 'first', function(amount) {
        var ret = this.slice(0, Math.max(0, amount == null ? 1 : amount));
        return amount === undefined ? ret[0] : ret;
    });

    /**
     * @alias first
     * @module Array
     */
	extend(array, 'take', Array.prototype.first)

    // Object methods

    // Number methods
    /**
     * @function isNaN
     * @module Number
     * Test if you're dealing with number
     * @example (+"asd").isNaN() === true
     */
    extend(number, 'isNaN', function() {
        return +this !== +this;
    });
}()
<|endoftext|>


<commit_before>var autoprefix = require('gulp-autoprefixer');
var browserify = require('browserify');
var concat = require('gulp-concat');
var del = require('del');
var gulp = require('gulp');
var less = require('gulp-less');
var reactify = require('reactify');
var size = require('gulp-size');
var source = require('vinyl-source-stream');
var sourcemaps = require('gulp-sourcemaps');
var webserver = require('gulp-webserver');

gulp.task('clean', function(cb) {
  del(['build'], cb);
});

gulp.task('css', [], function() {
  return gulp.src('./style/*.less')
    .pipe(sourcemaps.init())
    .pipe(less())
    .on('error', swallowError)
    .pipe(autoprefix())
    .pipe(concat('app.css'))
    .pipe(size())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('build'));
});

gulp.task('js', [], function() {
  browserify({
    debug: true,
    insertGlobals: true,
    entries: ['./App.js']
  })
  .transform(function(file) { return reactify(file, {es6: true}); })
  .bundle()
  .on('error', swallowError)
  .pipe(source('app.js'))
  .pipe(gulp.dest('build'));
});

gulp.task('watch', ['build'], function () {
  gulp.watch('./*.js', ['js']);
  gulp.watch('./style/*.less', ['css']);
});

gulp.task('webserver', function() {
  gulp.src('.')
    .pipe(webserver({
      fallback: 'index.html'
    }));
});

gulp.task('build', ['css', 'js']);

gulp.task('default', ['watch', 'webserver']);

function swallowError(error) {
  console.log(error.toString());
  this.emit('end');
}
<commit_msg>Fix sourcemap support<commit_after>var autoprefix = require('gulp-autoprefixer');
var browserify = require('browserify');
var concat = require('gulp-concat');
var del = require('del');
var gulp = require('gulp');
var less = require('gulp-less');
var reactify = require('reactify');
var size = require('gulp-size');
var source = require('vinyl-source-stream');
var sourcemaps = require('gulp-sourcemaps');
var webserver = require('gulp-webserver');

gulp.task('clean', function(cb) {
  del(['build'], cb);
});

gulp.task('css', [], function() {
  return gulp.src('./style/*.less')
    .pipe(sourcemaps.init())
    .pipe(less())
    .on('error', swallowError)
    .pipe(autoprefix())
    .pipe(concat('app.css'))
    .pipe(size())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('build'));
});

gulp.task('js', [], function() {
  browserify({
    debug: true,
    insertGlobals: true,
    entries: ['./App.js']
  })
  .transform(function(file) { return reactify(file, {es6: true}); })
  .bundle({debug: true})
  .on('error', swallowError)
  .pipe(source('app.js'))
  .pipe(gulp.dest('build'));
});

gulp.task('watch', ['build'], function () {
  gulp.watch('./*.js', ['js']);
  gulp.watch('./style/*.less', ['css']);
});

gulp.task('webserver', function() {
  gulp.src('.')
    .pipe(webserver({
      fallback: 'index.html'
    }));
});

gulp.task('build', ['css', 'js']);

gulp.task('default', ['watch', 'webserver']);

function swallowError(error) {
  console.log(error.toString());
  this.emit('end');
}
<|endoftext|>


<commit_before>var gulp        = require('gulp');
var browserSync = require('browser-sync').create();
var sass        = require('gulp-sass');
var cleanCSS = require('gulp-clean-css');
var uglify = require('gulp-uglify');
var rename = require("gulp-rename");

// Static Server + watching scss/js/html files
gulp.task('dev', function() {
    browserSync.init({
        server: {
            baseDir: "./"
        }
    });
    gulp.watch("scss/*.scss", ['sass']);
    gulp.watch("js/*.js", ['js']);
    gulp.watch("index.html").on('change', browserSync.reload);
});

// Compile sass into CSS and copy CSS to dist
gulp.task('sass', function() {
    return gulp.src("scss/*.scss")
        .pipe(sass())
        .pipe(gulp.dest("dist/css"))
        .pipe(browserSync.stream());
});

// Minify compiled CSS
gulp.task('minify-css', ['sass'], function() {
    return gulp.src('dist/css/*.css')
        .pipe(cleanCSS({ compatibility: 'ie8' }))
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest('dist/css'))
        .pipe(browserSync.stream());
});

// Copy JS to dist
gulp.task('js', function() {
    return gulp.src(['js/*.js'])
        .pipe(gulp.dest('dist/js'))
        .pipe(browserSync.stream());
})

// Minify JS
gulp.task('minify-js', ['js'], function() {
    return gulp.src('js/*.js')
        .pipe(uglify())
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest('dist/js'))
        .pipe(browserSync.stream());
});

// Run all
gulp.task('all', ['sass', 'minify-css', 'js', 'minify-js']);

// Run dev as default
gulp.task('default', ['all']);<commit_msg>Updated gulpfile.js<commit_after>var gulp        = require('gulp');
var browserSync = require('browser-sync').create();
var sass        = require('gulp-sass');
var cleanCSS = require('gulp-clean-css');
var uglify = require('gulp-uglify');
var rename = require("gulp-rename");

var onError = function(error) {
    console.log(error.toString());
    this.emit('end');
};

// Static Server + watching scss/js/html files
gulp.task('dev', function() {
    browserSync.init({
        server: {
            baseDir: "./"
        }
    });
    gulp.watch("sass/**/*.scss", ['sass']);
    gulp.watch("js/**/*.js", ['js']);
    gulp.watch("index.html").on('change', browserSync.reload);
});

// Compile sass into CSS and copy CSS to dist
gulp.task('sass', function() {
    return gulp.src("sass/*.scss")
        .pipe(sass())
        .on('error', onError)
        .pipe(gulp.dest("dist/css"))
        .pipe(browserSync.stream());
});

// Minify compiled CSS
gulp.task('minify-css', ['sass'], function() {
    return gulp.src('dist/css/*.css')
        .pipe(cleanCSS({ compatibility: 'ie8' }))
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest('dist/css'))
        .pipe(browserSync.stream());
});

// Copy JS to dist
gulp.task('js', function() {
    return gulp.src(['js/*.js'])
        .pipe(gulp.dest('dist/js'))
        .pipe(browserSync.stream());
})

// Minify JS
gulp.task('minify-js', ['js'], function() {
    return gulp.src('js/*.js')
        .pipe(uglify())
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest('dist/js'))
        .pipe(browserSync.stream());
});

// Run all
gulp.task('all', ['sass', 'minify-css', 'js', 'minify-js']);

// Run dev as default
gulp.task('default', ['all']);<|endoftext|>


<commit_before>// Gulpfile developed from:
// https://github.com/zellwk/gulp-starter-csstricks
// https://github.com/roots/sage
// http://justinmccandless.com/post/a-tutorial-for-getting-started-with-gulp

// See README for more help and info

var gulp = require('gulp');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');
var gulpIf = require('gulp-if');
var cssnano = require('gulp-cssnano');
var imagemin = require('gulp-imagemin');
var cache = require('gulp-cache');
var runSequence = require('run-sequence');

// Development Tasks
// -----------------

gulp.task('sass', function() {
  return gulp.src('scss/**/*.scss') // Gets all files ending with .scss in main.css.source/styles and children dirs
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError)) // Passes it through gulp-sass and deal with errors
    .pipe(sourcemaps.write('../maps'))
    .pipe(gulp.dest('css/')); // Outputs it in the css folder
})

gulp.task('sass:production', function() {
  return gulp.src('scss/**/*.scss') // Gets all files ending with .scss in main.css.source/styles and children dirs
    .pipe(sass({ outputStyle: 'compressed' })) // Passes it through a gulp-sass
    .pipe(gulpIf('*.css', cssnano())) // Minify css
    .pipe(gulp.dest('dist/')); // Outputs it in the css folder
})

// Watchers
gulp.task('watch', function() {
  gulp.watch('scss/**/*.scss', ['sass']);
})

// Optimization Tasks
// ------------------

// Optimizing Images
gulp.task('images', function() {
  return gulp.src('../../images/**/*.+(png|jpg|jpeg|gif|svg)')
    // Caching images that ran through imagemin
    .pipe(cache(imagemin({
      interlaced: true,
    })))
    .pipe(gulp.dest('../../images'))
});

// Build Sequences
// ---------------

gulp.task('clear', function (done) {
  return cache.clearAll(done);
})

gulp.task('default', function(callback) {
  runSequence(['sass', 'watch'],
    callback
  )
})

gulp.task('sass:only', function(callback) {
  runSequence(['sass', 'watch'],
    callback
  )
})

gulp.task('build', function(callback) {
  runSequence(
    ['sass', 'images'],
    callback
  )
})

gulp.task('build:production', function(callback) {
  runSequence(
    ['sass:production'],
    callback
  )
})
<commit_msg>Clean up gulp<commit_after>// Gulpfile developed from:
// https://github.com/zellwk/gulp-starter-csstricks
// https://github.com/roots/sage
// http://justinmccandless.com/post/a-tutorial-for-getting-started-with-gulp

// See README for more help and info

var gulp = require('gulp');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');
var gulpIf = require('gulp-if');
var cssnano = require('gulp-cssnano');
var imagemin = require('gulp-imagemin');
var cache = require('gulp-cache');
var runSequence = require('run-sequence');

// Development Tasks
// -----------------

gulp.task('sass', function() {
  return gulp.src('scss/**/*.scss') // Gets all files ending with .scss in main.css.source/styles and children dirs
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError)) // Passes it through gulp-sass and deal with errors
    .pipe(sourcemaps.write('../maps'))
    .pipe(gulp.dest('css/')); // Outputs it in the css folder
})

gulp.task('sass:production', function() {
  return gulp.src('scss/**/*.scss') // Gets all files ending with .scss in main.css.source/styles and children dirs
    .pipe(sass({ outputStyle: 'compressed' })) // Passes it through a gulp-sass
    .pipe(gulpIf('*.css', cssnano())) // Minify css
    .pipe(gulp.dest('dist/')); // Outputs it in the css folder
})

// Watchers
gulp.task('watch', function() {
  gulp.watch('scss/**/*.scss', ['sass']);
})

// Build Sequences
// ---------------

gulp.task('clear', function (done) {
  return cache.clearAll(done);
})

gulp.task('default', function(callback) {
  runSequence(['sass', 'watch'],
    callback
  )
})

gulp.task('build:production', function(callback) {
  runSequence(
    ['sass:production'],
    callback
  )
})
<|endoftext|>


<commit_before>const gulp = require('gulp');
const sass = require('node-sass');
const inlineTemplates = require('gulp-inline-ng2-template');
const exec = require('child_process').exec;

/**
 * Inline templates configuration.
 * @see  https://github.com/ludohenin/gulp-inline-ng2-template
 */
const INLINE_TEMPLATES = {
  SRC: './src/**/*.ts',
  DIST: './tmp/src-inlined',
  CONFIG: {
    base: '/src',
    target: 'es6',
    useRelativePaths: true,
    styleProcessor: compileSass
  }
};

/**
 * Inline external HTML and SCSS templates into Angular component files.
 * @see: https://github.com/ludohenin/gulp-inline-ng2-template
 */
gulp.task('inline-templates', () => {
  return gulp.src(INLINE_TEMPLATES.SRC)
    .pipe(inlineTemplates(INLINE_TEMPLATES.CONFIG))
    .pipe(gulp.dest(INLINE_TEMPLATES.DIST));
});

/**
 * Build ESM by running npm task.
 * This is a temporary solution until ngc is supported --watch mode.
 * @see: https://github.com/angular/angular/issues/12867
 */
gulp.task('build:esm', ['inline-templates'], (callback) => {
  exec('npm run ngcompile', function (error, stdout, stderr) {
    console.log(stdout, stderr);
    callback(error)
  });
});

/**
 * Implements ESM build watch mode.
 * This is a temporary solution until ngc is supported --watch mode.
 * @see: https://github.com/angular/angular/issues/12867
 */
gulp.task('build:esm:watch', ['build:esm'], () => {
  gulp.watch('src/**/*', ['build:esm']);
});

/**
 * Compile SASS to CSS.
 * @see https://github.com/ludohenin/gulp-inline-ng2-template
 * @see https://github.com/sass/node-sass
 */
function compileSass(path, ext, file, callback) {
  let compiledCss = sass.renderSync({
    file: path,
    outputStyle: 'compressed',
  });
  callback(null, compiledCss.css);
}
<commit_msg>add copy demos to docs command<commit_after>const gulp = require('gulp');
const sass = require('node-sass');
const inlineTemplates = require('gulp-inline-ng2-template');
const exec = require('child_process').exec;

/**
 * Inline templates configuration.
 * @see  https://github.com/ludohenin/gulp-inline-ng2-template
 */
const INLINE_TEMPLATES = {
  SRC: './src/**/*.ts',
  DIST: './tmp/src-inlined',
  CONFIG: {
    base: '/src',
    target: 'es6',
    useRelativePaths: true,
    styleProcessor: compileSass
  }
};

/**
 * Inline external HTML and SCSS templates into Angular component files.
 * @see: https://github.com/ludohenin/gulp-inline-ng2-template
 */
gulp.task('inline-templates', () => {
  return gulp.src(INLINE_TEMPLATES.SRC)
    .pipe(inlineTemplates(INLINE_TEMPLATES.CONFIG))
    .pipe(gulp.dest(INLINE_TEMPLATES.DIST));
});

/**
 * Build ESM by running npm task.
 * This is a temporary solution until ngc is supported --watch mode.
 * @see: https://github.com/angular/angular/issues/12867
 */
gulp.task('build:esm', ['inline-templates'], (callback) => {
  exec('npm run ngcompile', function (error, stdout, stderr) {
    console.log(stdout, stderr);
    callback(error)
  });
});

/**
 * Implements ESM build watch mode.
 * This is a temporary solution until ngc is supported --watch mode.
 * @see: https://github.com/angular/angular/issues/12867
 */
gulp.task('build:esm:watch', ['build:esm'], () => {
  gulp.watch('src/**/*', ['build:esm']);
});

/**
 * Copy demo builds to docs folder for gh-pages
 */
gulp.task('copy:demo', () => {
  return gulp.src('demo/esm/dist/aot/**/*')
    .pipe(gulp.dest('docs/demo'));
});

/**
 * Compile SASS to CSS.
 * @see https://github.com/ludohenin/gulp-inline-ng2-template
 * @see https://github.com/sass/node-sass
 */
function compileSass(path, ext, file, callback) {
  let compiledCss = sass.renderSync({
    file: path,
    outputStyle: 'compressed',
  });
  callback(null, compiledCss.css);
}
<|endoftext|>


<commit_before>// ## Globals
var argv         = require('minimist')(process.argv.slice(2));
var autoprefixer = require('gulp-autoprefixer');
var browserSync  = require('browser-sync').create();
var changed      = require('gulp-changed');
var concat       = require('gulp-concat');
var flatten      = require('gulp-flatten');
var gulp         = require('gulp');
var gulpif       = require('gulp-if');
var imagemin     = require('gulp-imagemin');
var jshint       = require('gulp-jshint');
var lazypipe     = require('lazypipe');
var less         = require('gulp-less');
var merge        = require('merge-stream');
var cssNano      = require('gulp-cssnano');
var plumber      = require('gulp-plumber');
var rev          = require('gulp-rev');
var runSequence  = require('run-sequence');
var sass         = require('gulp-sass');
var sourcemaps   = require('gulp-sourcemaps');
var uglify       = require('gulp-uglify');

// See https://github.com/austinpray/asset-builder
var manifest = require('asset-builder')('./assets/manifest.json');

// `path` - Paths to base asset directories. With trailing slashes.
// - `path.source` - Path to the source files. Default: `assets/`
// - `path.dist` - Path to the build directory. Default: `dist/`
var path = manifest.paths;

// `config` - Store arbitrary configuration values here.
var config = manifest.config || {};

// `globs` - These ultimately end up in their respective `gulp.src`.
// - `globs.js` - Array of asset-builder JS dependency objects. Example:
//   ```
//   {type: 'js', name: 'main.js', globs: []}
//   ```
// - `globs.css` - Array of asset-builder CSS dependency objects. Example:
//   ```
//   {type: 'css', name: 'main.css', globs: []}
//   ```
// - `globs.fonts` - Array of font path globs.
// - `globs.images` - Array of image path globs.
// - `globs.bower` - Array of all the main Bower files.
var globs = manifest.globs;

// `project` - paths to first-party assets.
// - `project.js` - Array of first-party JS assets.
// - `project.css` - Array of first-party CSS assets.
var project = manifest.getProjectGlobs();

// CLI options
var enabled = {
  // Enable static asset revisioning when `--production`
  rev: argv.production,
  // Disable source maps when `--production`
  maps: !argv.production,
  //maps: false,
  // Fail styles task on error when `--production`
  failStyleTask: argv.production,
  // Fail due to JSHint warnings only when `--production`
  failJSHint: argv.production,
  // Strip debug statments from javascript when `--production`
  stripJSDebug: argv.production
};

// Path to the compiled assets manifest in the dist directory
var revManifest = path.dist + 'assets.json';

// ## Reusable Pipelines
// See https://github.com/OverZealous/lazypipe

// ### CSS processing pipeline
// Example
// ```
// gulp.src(cssFiles)
//   .pipe(cssTasks('main.css')
//   .pipe(gulp.dest(path.dist + 'styles'))
// ```
var cssTasks = function(filename) {
  return lazypipe()
    .pipe(function() {
      return gulpif(!enabled.failStyleTask, plumber());
    })
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.init());
    })
    .pipe(function() {
      return gulpif('*.less', less());
    })
    .pipe(function() {
      return gulpif('*.scss', sass({
        outputStyle: 'nested', // libsass doesn't support expanded yet
        precision: 10,
        includePaths: ['.'],
        errLogToConsole: !enabled.failStyleTask
      }));
    })
    .pipe(concat, filename)
    .pipe(autoprefixer, {
      browsers: [
        'last 2 versions',
        'android 4',
        'opera 12'
      ]
    })
    .pipe(cssNano, {
      safe: true
    })
    .pipe(function() {
      return gulpif(enabled.rev, rev());
    })
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.write('.', {
        sourceRoot: 'assets/styles/'
      }));
    })();
};

// ### JS processing pipeline
// Example
// ```
// gulp.src(jsFiles)
//   .pipe(jsTasks('main.js')
//   .pipe(gulp.dest(path.dist + 'scripts'))
// ```
var jsTasks = function(filename) {
  return lazypipe()
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.init());
    })
    .pipe(concat, filename)
    .pipe(uglify, {
      compress: {
        'drop_debugger': enabled.stripJSDebug
      }
    })
    .pipe(function() {
      return gulpif(enabled.rev, rev());
    })
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.write('.', {
        sourceRoot: 'assets/scripts/'
      }));
    })();
};

// ### Write to rev manifest
// If there are any revved files then write them to the rev manifest.
// See https://github.com/sindresorhus/gulp-rev
var writeToManifest = function(directory) {
  return lazypipe()
    .pipe(gulp.dest, path.dist + directory)
    .pipe(browserSync.stream, {match: '**/*.{js,css}'})
    .pipe(rev.manifest, revManifest, {
      base: path.dist,
      merge: true
    })
    .pipe(gulp.dest, path.dist)();
};

// ## Gulp tasks
// Run `gulp -T` for a task summary

// ### Styles
// `gulp styles` - Compiles, combines, and optimizes Bower CSS and project CSS.
// By default this task will only log a warning if a precompiler error is
// raised. If the `--production` flag is set: this task will fail outright.
gulp.task('styles', ['wiredep'], function() {
  var merged = merge();
  manifest.forEachDependency('css', function(dep) {
    var cssTasksInstance = cssTasks(dep.name);
    if (!enabled.failStyleTask) {
      cssTasksInstance.on('error', function(err) {
        console.error(err.message);
        this.emit('end');
      });
    }
    merged.add(gulp.src(dep.globs, {base: 'styles'})
      .pipe(cssTasksInstance));
  });
  return merged
    .pipe(writeToManifest('styles'));
});

// ### Scripts
// `gulp scripts` - Runs JSHint then compiles, combines, and optimizes Bower JS
// and project JS.
gulp.task('scripts', ['jshint'], function() {
  var merged = merge();
  manifest.forEachDependency('js', function(dep) {
    merged.add(
      gulp.src(dep.globs, {base: 'scripts'})
        .pipe(jsTasks(dep.name))
    );
  });
  return merged
    .pipe(writeToManifest('scripts'));
});

// ### Fonts
// `gulp fonts` - Grabs all the fonts and outputs them in a flattened directory
// structure. See: https://github.com/armed/gulp-flatten
gulp.task('fonts', function() {
  return gulp.src(globs.fonts)
    .pipe(flatten())
    .pipe(gulp.dest(path.dist + 'fonts'))
    .pipe(browserSync.stream());
});

// ### Images
// `gulp images` - Run lossless compression on all the images.
gulp.task('images', function() {
  return gulp.src(globs.images)
    .pipe(imagemin({
      progressive: true,
      interlaced: true,
      svgoPlugins: [{removeUnknownsAndDefaults: false}, {cleanupIDs: false}]
    }))
    .pipe(gulp.dest(path.dist + 'images'))
    .pipe(browserSync.stream());
});

// ### JSHint
// `gulp jshint` - Lints configuration JSON and project JS.
gulp.task('jshint', function() {
  return gulp.src([
    'bower.json', 'gulpfile.js'
  ].concat(project.js))
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'))
    .pipe(gulpif(enabled.failJSHint, jshint.reporter('fail')));
});

// ### Clean
// `gulp clean` - Deletes the build folder entirely.
gulp.task('clean', require('del').bind(null, [path.dist]));

// ### Watch
// `gulp watch` - Use BrowserSync to proxy your dev server and synchronize code
// changes across devices. Specify the hostname of your dev server at
// `manifest.config.devUrl`. When a modification is made to an asset, run the
// build step for that asset and inject the changes into the page.
// See: http://www.browsersync.io
gulp.task('watch', function() {
  browserSync.init({
    files: ['{lib,templates}/**/*.php', '*.php'],
    proxy: config.devUrl,
    open: "external",
    snippetOptions: {
      whitelist: ['/wp-admin/admin-ajax.php'],
      blacklist: ['/wp-admin/**']
    }
  });
  gulp.watch([path.source + 'styles/**/*'], ['styles']);
  gulp.watch([path.source + 'scripts/**/*'], ['jshint', 'scripts']);
  gulp.watch([path.source + 'fonts/**/*'], ['fonts']);
  gulp.watch([path.source + 'images/**/*'], ['images']);
  gulp.watch(['bower.json', 'assets/manifest.json'], ['build']);
});

// ### Build
// `gulp build` - Run all the build tasks but don't clean up beforehand.
// Generally you should be running `gulp` instead of `gulp build`.
gulp.task('build', function(callback) {
  runSequence('styles',
              'scripts',
              ['fonts', 'images'],
              callback);
});

// ### Wiredep
// `gulp wiredep` - Automatically inject Less and Sass Bower dependencies. See
// https://github.com/taptapship/wiredep
gulp.task('wiredep', function() {
  var wiredep = require('wiredep').stream;
  return gulp.src(project.css)
    .pipe(wiredep())
    .pipe(changed(path.source + 'styles', {
      hasChanged: changed.compareSha1Digest
    }))
    .pipe(gulp.dest(path.source + 'styles'));
});

// ### Gulp
// `gulp` - Run a complete build. To compile for production run `gulp --production`.
gulp.task('default', ['clean'], function() {
  gulp.start('build');
});
<commit_msg>Finally source map is working, sourceRoot must be /<commit_after>// ## Globals
var argv         = require('minimist')(process.argv.slice(2));
var autoprefixer = require('gulp-autoprefixer');
var browserSync  = require('browser-sync').create();
var changed      = require('gulp-changed');
var concat       = require('gulp-concat');
var flatten      = require('gulp-flatten');
var gulp         = require('gulp');
var gulpif       = require('gulp-if');
var imagemin     = require('gulp-imagemin');
var jshint       = require('gulp-jshint');
var lazypipe     = require('lazypipe');
var less         = require('gulp-less');
var merge        = require('merge-stream');
var cssNano      = require('gulp-cssnano');
var plumber      = require('gulp-plumber');
var rev          = require('gulp-rev');
var runSequence  = require('run-sequence');
var sass         = require('gulp-sass');
var sourcemaps   = require('gulp-sourcemaps');
var uglify       = require('gulp-uglify');

// See https://github.com/austinpray/asset-builder
var manifest = require('asset-builder')('./assets/manifest.json');

// `path` - Paths to base asset directories. With trailing slashes.
// - `path.source` - Path to the source files. Default: `assets/`
// - `path.dist` - Path to the build directory. Default: `dist/`
var path = manifest.paths;

// `config` - Store arbitrary configuration values here.
var config = manifest.config || {};

// `globs` - These ultimately end up in their respective `gulp.src`.
// - `globs.js` - Array of asset-builder JS dependency objects. Example:
//   ```
//   {type: 'js', name: 'main.js', globs: []}
//   ```
// - `globs.css` - Array of asset-builder CSS dependency objects. Example:
//   ```
//   {type: 'css', name: 'main.css', globs: []}
//   ```
// - `globs.fonts` - Array of font path globs.
// - `globs.images` - Array of image path globs.
// - `globs.bower` - Array of all the main Bower files.
var globs = manifest.globs;

// `project` - paths to first-party assets.
// - `project.js` - Array of first-party JS assets.
// - `project.css` - Array of first-party CSS assets.
var project = manifest.getProjectGlobs();

// CLI options
var enabled = {
  // Enable static asset revisioning when `--production`
  rev: argv.production,
  // Disable source maps when `--production`
  maps: !argv.production,
  //maps: false,
  // Fail styles task on error when `--production`
  failStyleTask: argv.production,
  // Fail due to JSHint warnings only when `--production`
  failJSHint: argv.production,
  // Strip debug statments from javascript when `--production`
  stripJSDebug: argv.production
};

// Path to the compiled assets manifest in the dist directory
var revManifest = path.dist + 'assets.json';

// ## Reusable Pipelines
// See https://github.com/OverZealous/lazypipe

// ### CSS processing pipeline
// Example
// ```
// gulp.src(cssFiles)
//   .pipe(cssTasks('main.css')
//   .pipe(gulp.dest(path.dist + 'styles'))
// ```
var cssTasks = function(filename) {
  return lazypipe()
    .pipe(function() {
      return gulpif(!enabled.failStyleTask, plumber());
    })
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.init());
    })
    // .pipe(function() {
    //   return gulpif('*.less', less());
    // })
    .pipe(function() {
      return gulpif('*.scss', sass({
        outputStyle: 'nested', // libsass doesn't support expanded yet
        precision: 10,
        includePaths: ['.'],
        errLogToConsole: !enabled.failStyleTask
      }));
    })
    .pipe(concat, filename)
    .pipe(autoprefixer, {
      browsers: [
        'last 2 versions',
        'android 4',
        'opera 12'
      ]
    })
    .pipe(cssNano, {
      safe: true
    })
    .pipe(function() {
      return gulpif(enabled.rev, rev());
    })
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.write('.', {
        sourceRoot: '/'
      }));
    })();
};

// ### JS processing pipeline
// Example
// ```
// gulp.src(jsFiles)
//   .pipe(jsTasks('main.js')
//   .pipe(gulp.dest(path.dist + 'scripts'))
// ```
var jsTasks = function(filename) {
  return lazypipe()
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.init());
    })
    .pipe(concat, filename)
    .pipe(uglify, {
      compress: {
        'drop_debugger': enabled.stripJSDebug
      }
    })
    .pipe(function() {
      return gulpif(enabled.rev, rev());
    })
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.write('.', {
        sourceRoot: '/'
      }));
    })();
};

// ### Write to rev manifest
// If there are any revved files then write them to the rev manifest.
// See https://github.com/sindresorhus/gulp-rev
var writeToManifest = function(directory) {
  return lazypipe()
    .pipe(gulp.dest, path.dist + directory)
    .pipe(browserSync.stream, {match: '**/*.{js,css}'})
    .pipe(rev.manifest, revManifest, {
      base: path.dist,
      merge: true
    })
    .pipe(gulp.dest, path.dist)();
};

// ## Gulp tasks
// Run `gulp -T` for a task summary

// ### Styles
// `gulp styles` - Compiles, combines, and optimizes Bower CSS and project CSS.
// By default this task will only log a warning if a precompiler error is
// raised. If the `--production` flag is set: this task will fail outright.
gulp.task('styles', ['wiredep'], function() {
  var merged = merge();
  manifest.forEachDependency('css', function(dep) {
    var cssTasksInstance = cssTasks(dep.name);
    if (!enabled.failStyleTask) {
      cssTasksInstance.on('error', function(err) {
        console.error(err.message);
        this.emit('end');
      });
    }
    merged.add(gulp.src(dep.globs, {base: 'styles'})
      .pipe(cssTasksInstance));
  });
  return merged
    .pipe(writeToManifest('styles'));
});

// ### Scripts
// `gulp scripts` - Runs JSHint then compiles, combines, and optimizes Bower JS
// and project JS.
gulp.task('scripts', ['jshint'], function() {
  var merged = merge();
  manifest.forEachDependency('js', function(dep) {
    merged.add(
      gulp.src(dep.globs, {base: 'scripts'})
        .pipe(jsTasks(dep.name))
    );
  });
  return merged
    .pipe(writeToManifest('scripts'));
});

// ### Fonts
// `gulp fonts` - Grabs all the fonts and outputs them in a flattened directory
// structure. See: https://github.com/armed/gulp-flatten
gulp.task('fonts', function() {
  return gulp.src(globs.fonts)
    .pipe(flatten())
    .pipe(gulp.dest(path.dist + 'fonts'))
    .pipe(browserSync.stream());
});

// ### Images
// `gulp images` - Run lossless compression on all the images.
gulp.task('images', function() {
  return gulp.src(globs.images)
    .pipe(imagemin({
      progressive: true,
      interlaced: true,
      svgoPlugins: [{removeUnknownsAndDefaults: false}, {cleanupIDs: false}]
    }))
    .pipe(gulp.dest(path.dist + 'images'))
    .pipe(browserSync.stream());
});

// ### JSHint
// `gulp jshint` - Lints configuration JSON and project JS.
gulp.task('jshint', function() {
  return gulp.src([
    'bower.json', 'gulpfile.js'
  ].concat(project.js))
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'))
    .pipe(gulpif(enabled.failJSHint, jshint.reporter('fail')));
});

// ### Clean
// `gulp clean` - Deletes the build folder entirely.
gulp.task('clean', require('del').bind(null, [path.dist]));

// ### Watch
// `gulp watch` - Use BrowserSync to proxy your dev server and synchronize code
// changes across devices. Specify the hostname of your dev server at
// `manifest.config.devUrl`. When a modification is made to an asset, run the
// build step for that asset and inject the changes into the page.
// See: http://www.browsersync.io
gulp.task('watch', function() {
  browserSync.init({
    files: ['{lib,templates}/**/*.php', '*.php'],
    proxy: config.devUrl,
    snippetOptions: {
      whitelist: ['/wp-admin/admin-ajax.php'],
      blacklist: ['/wp-admin/**']
    }
  });
  gulp.watch([path.source + 'styles/**/*'], ['styles']);
  gulp.watch([path.source + 'scripts/**/*'], ['jshint', 'scripts']);
  gulp.watch([path.source + 'fonts/**/*'], ['fonts']);
  gulp.watch([path.source + 'images/**/*'], ['images']);
  gulp.watch(['bower.json', 'assets/manifest.json'], ['build']);
});

// ### Build
// `gulp build` - Run all the build tasks but don't clean up beforehand.
// Generally you should be running `gulp` instead of `gulp build`.
gulp.task('build', function(callback) {
  runSequence('styles',
              'scripts',
              ['fonts', 'images'],
              callback);
});

// ### Wiredep
// `gulp wiredep` - Automatically inject Less and Sass Bower dependencies. See
// https://github.com/taptapship/wiredep
gulp.task('wiredep', function() {
  var wiredep = require('wiredep').stream;
  return gulp.src(project.css)
    .pipe(wiredep())
    .pipe(changed(path.source + 'styles', {
      hasChanged: changed.compareSha1Digest
    }))
    .pipe(gulp.dest(path.source + 'styles'));
});

// ### Gulp
// `gulp` - Run a complete build. To compile for production run `gulp --production`.
gulp.task('default', ['clean'], function() {
  gulp.start('build');
});
<|endoftext|>


<commit_before>/*
 *
 * MyFrameController
 *
 * @author [Your Name]
 *
 * Copyright (c) 2014 [Your Company]
 *
 * [Website]
 *
 * [License information]
 *
 */

(function(){

	var jQuerySap = jQuery.sap;

	jQuerySap.declare("tld__domain.product__app.modules.AppFrameExample");

	jQuerySap.require("pks.ui5strap.viewer.AppFrame");

	jQuerySap.require("ui5strap.Bar");
	jQuerySap.require("ui5strap.NavBar");
	jQuerySap.require("ui5strap.Nav");
	jQuerySap.require("ui5strap.ListNavItem");
	jQuerySap.require("ui5strap.Link");
	jQuerySap.require("ui5strap.ButtonGroup");
	jQuerySap.require("ui5strap.Button");
	jQuerySap.require("ui5strap.Icon");

	jQuerySap.require("jquery.sap.history");

	//FrameControllers must extend the AppFrame class
	pks.ui5strap.viewer.AppFrame.extend("tld__domain.product__app.modules.AppFrameExample");

	var FrameController = tld__domain.product__app.modules.AppFrameExample,
		FrameControllerProto = FrameController.prototype,
		configuration = sap.ui.getCore().getConfiguration();

	FrameControllerProto.showInitialContent = function(callback){
		this.app.log.debug('[APP_FRAME_EXAMPLE] Show initial content...');
		var _this = this;
		var complete = function(){
			_this.initialized = true;
			callback && callback();
		};

		try{
			/*
			 * We want to show the intro only for the first time
			 */
			if(!this.app.getLocalStorageItem("skipIntro")){
				//Now we set the skipIntro flag in local storage to true.
				//Next time, we won't see the Intro
				this.app.setLocalStorageItem("skipIntro", true);

				this.gotoPage({
					"viewName" : "tld__domain.product__app.views.Intro",
					"transition" : "transition-none"
				}, complete);
			}
			else{
				this.gotoPage({
					"viewName" : "tld__domain.product__app.views.Page1",
					"transition" : "transition-none"
				}, complete);
			}
		}
		catch(e){
			//If localStorage is not supported, always show the Intro (IE9)
			this.gotoPage({
				"viewName" : "tld__domain.product__app.views.Intro",
				"transition" : "transition-none"
			}, complete);
		}

	};

	/*
	* Create the nav container control used by this frame.
	*/
	FrameControllerProto._createControl = function(){
		var _this = this,
			navContainer = pks.ui5strap.viewer.AppFrame.prototype._createControl.call(this);

		//Get the frame options
		var frameOptions = this.options;

		//Navbar
		var navbar = new ui5strap.NavBar({
			inverse : true,
			fluid : true,
			position : ui5strap.NavBarPosition.StaticTop
		});

		this.navbar = navbar;

		//Sidenav toggle
		var toggle = new ui5strap.Button( {
				align : ui5strap.Alignment.NavBarLeft
			}
		);
		toggle.addStyleClass("btn-toggle-sidenav");
		toggle.addContent(new ui5strap.Icon( { icon : 'columns', size : ui5strap.IconSize.Large } ));

		toggle.attachEvent('tap', {}, function(){
			_this.getRootControl().toggleOption('sidenav');
		});

		navbar.addContentLeft(toggle);

		//Brand
		var brand = new ui5strap.Link();
		brand.bindProperty('text', {path : 'i18n>MENU_BRAND'});

		brand.attachEvent('tap', {}, function(){
			_this.showInitialContent();
		});

		navbar.setBrand(brand);

		//Main menu
		var navNavbar = new ui5strap.Nav(),
			menu = this.app.config.getMenuData(frameOptions.navbarMenu);

		if(menu){
			//If a navbarMenu is specified in frameOptions, create the nav menu from it
			for (var i = 0; i < menu.items.length; i++){
				var menuPage = menu.items[i],
					navItem = new ui5strap.ListItem(),
					navItemLink = new ui5strap.Link();

				navItemLink.bindProperty('text', {path : menuPage.label});

				navItem.addContent(navItemLink);

				navItem.data(menuPage);
				navNavbar.addItem(navItem);
			}

		}

		navNavbar.attachEvent('tap', {}, function(oEvent){
			var listItem = oEvent.getParameter('listItem');
			if(listItem){
				_this.gotoPage(listItem.data());

				navbar.setCollapsed(true);
			}
		});
		navNavbar.setAlign(ui5strap.Alignment.NavBarLeft);

		navbar.addCollapse(navNavbar);
		this.navNavbar = navNavbar;

		//Language select buttons
		var navButtons = new ui5strap.ButtonGroup({align : ui5strap.Alignment.NavBarRight}),
			buttonDe = new ui5strap.Button({'text' : "DE" }),
			buttonEn = new ui5strap.Button({'text' : "EN" });

		navButtons.addButton(buttonEn);
		navButtons.addButton(buttonDe);
		navbar.addCollapse(navButtons);

		navButtons.attachEvent('tap', {}, function(oEvent){
			var srcButton = oEvent.getParameter('button');
			navButtons.setSelectedControl(srcButton);

			if(buttonEn === srcButton){
				configuration.setLanguage('en-us');
			}
			else if(buttonDe === srcButton){
				configuration.setLanguage('de-de');
			}
		});

		if(jQuery.sap.startsWithIgnoreCase(configuration.getLanguage(), 'de')){
			buttonDe.setSelected(true);
		}
		else{
			buttonEn.setSelected(true);
		}

		//Nav menu toggle
		var toggleRight = new ui5strap.Button( {
				align : ui5strap.Alignment.NavBarRight
			}
		);
		toggle.addStyleClass("btn-toggle-navbar");
		toggleRight.addContent(new ui5strap.Icon( { icon : 'bars', size : ui5strap.IconSize.Large } ));

		toggleRight.attachEvent('tap', {}, function(){
			navbar.toggle();
		});

		navbar.addContentRight(toggleRight);

		//Sidebar / Sidenav
		var sidebar = new ui5strap.Bar({ "fullHeight" : true, "inverse" : true }),
			navSidebar = new ui5strap.Nav({ type : ui5strap.NavType.PillsStacked, align : ui5strap.Alignment.Sidebar });

		navSidebar.addStyleClass("sidebar-nav")

		this.sidebar = sidebar;

		navSidebar.attachEvent('tap', {}, function(oEvent){
			var listItem = oEvent.getParameter('listItem');
			if(listItem){
				_this.gotoPage(listItem.data());
			}
		});

		sidebar.addContent(navSidebar);
		this.navSidebar = navSidebar;

		return navContainer;
	};

	/*
	* Init navigation history
	*/
	FrameControllerProto._initHistory = function(){
		var _this = this;

		if(!this.app.config.data.app.history){
			return false;
		}

		jQuery.sap.history({
			routes : [
				{
					path : "content",
					handler : function (params, navType) {
						if(_this.initialized){
							params.writeHistory = false;
							_this.gotoPage(params);
						}
						else{
							params.writeHistory = true;
							params.transition = 'transition-none';
						}
					}
				}
			],
			defaultHandler : function (navType) {

				if(_this.initialized){
					_this.showInitialContent();
				}

			}
		});
	};

	/*
	* Navigate to a page
	*
	* @Public
	* @Override
	*/
	FrameControllerProto.gotoPage = function (viewDef, callback) {
		var _this = this,
			frameOptions = this.options;

		//If "sidebarMenu" is set, and no "viewName" specified, goto first page of sidebarMenu.
		if(viewDef.sidebarMenu && !viewDef.viewName){
			//if the viewDef contains no viewName but a sidebarMenu only, show the first entry of the submenu

			var submenu = this.app.config.getMenuData(viewDef.sidebarMenu);
			if("items" in submenu && submenu.items.length > 0){
				this.gotoPage(submenu.items[0], callback);
			}
			else{
				throw new Error('Invalid sidebar menu: ' + viewDef.sidebarMenu);
			}

			return;
		}

		//Get final view configuration
		var viewConfig = this.getViewConfig(viewDef),
			target = viewConfig.target;

		if(this.isBusy(target)){
			this.app.log.debug('[APP_FRAME_EXAMPLE] Target is busy: "' + target + '"');

			return false;
		}

		this.app.log.debug('[APP_FRAME_EXAMPLE] Navigate Target "' + target + '" to View "' + viewConfig.viewName + '"');

		var navbarEnabled = frameOptions.navbar;
		if("navbar" in viewConfig){
			navbarEnabled = viewConfig.navbar;
		}

		var sidebarEnabled = frameOptions.sidebar;
		if("sidebar" in viewConfig){
			sidebarEnabled = viewConfig.sidebar;
		}

		var sidenavEnabled = frameOptions.sidenav;
		if("sidenav" in viewConfig){
			sidenavEnabled = viewConfig.sidenav;
		}

		var sidebar2Nav = frameOptions.sidebar2Nav;
		if("sidebar2Nav" in viewConfig){
			sidebar2Nav = viewConfig.sidebar2Nav;
		}

		var sidebarSmall = frameOptions.sidebarSmall;
		if("sidebarSmall" in viewConfig){
			sidebarSmall = viewConfig.sidebarSmall;
		}

		var sidenavToggle = frameOptions.sidenavToggle;
		if("sidenavToggle" in viewConfig){
			sidenavToggle = viewConfig.sidenavToggle;
		}

		this.getRootControl().setOptionsEnabled({
			'navbar' :  navbarEnabled,
			'sidebar' : sidebarEnabled,
			'sidenav' : sidenavEnabled,

			'sidebar-2nav' : sidebar2Nav,
			'sidebar-small' : sidebarSmall,
			'sidenav-toggle' : sidenavToggle
		});

		if("sidebarMenu" in viewConfig){
			this.setSidebarMenu(viewConfig.sidebarMenu);
		}
		else if("sidebarMenu" in frameOptions){
			this.setSidebarMenu(frameOptions.sidebarMenu);
		}

		this.getRootControl().toPage(this.sidebar, 'sidebar', "transition-none");
		this.getRootControl().toPage(this.navbar, 'navbar', "transition-none");

		var currentPage = this.getCurrentPage(target);
		if(
			_this.getRootControl().getDomRef()
			&& viewConfig.id
			&& currentPage
			&& viewConfig.id === currentPage.getId()
		){
			this.updatePage(currentPage, viewConfig.parameters);

			this.app.log.debug('[APP_FRAME_EXAMPLE] Page is current: "' + viewConfig.id + '"');

			return false;
		}

		if(viewConfig.documentTitle){
			var titlePath = viewConfig.documentTitle.split('>');
			if(titlePath.length === 2){
				document.title = this.app.getLocaleString(titlePath[1], titlePath[0]);
			}
		}

		this.updateMenu(viewConfig.viewName);

		if(viewConfig.showLoader){
			this.app.setLoaderVisible(true, function(){
				_this.toPage(viewConfig, callback);
			})
		}
		else{
			this.toPage(viewConfig, callback);
		}

		//Write history entry for back/forward navigation in browser / using javascript.
		if (viewConfig.writeHistory && this.app.config.data.app.history) {
			jQuery.sap.history.addHistory(target, viewDef, viewConfig.bookmarkable, viewConfig.virtual);
		}

		return true;
	};

	/*
	*
	* Update menu and highlight items that match to current view
	*
	* @Public
	*/
	FrameControllerProto.updateMenu = function(viewName){
		this.app.log.debug('[APP_FRAME_EXAMPLE] updateMenu "' + viewName + '"');

		var navSidebar = this.navSidebar;

		if(this.sidebarMenu){
			var sidebarMenu = this.app.config.getMenuData(this.sidebarMenu);

			if(null !== sidebarMenu && 'items' in sidebarMenu){
				var sidebarMenuIndex = -1,
					sidebarItems = sidebarMenu.items;

				for(var i=0; i<sidebarItems.length; i++){
					if(viewName === this.app.config.resolvePackage(sidebarItems[i].viewName, "views")){
						sidebarMenuIndex = i;
						break;
					}
				}

				if(sidebarMenuIndex !== -1){
					navSidebar.setSelectedIndex(sidebarMenuIndex);
				}
				else{
					navSidebar.setSelectedControl(null);
				}
			}
			else{
				throw new Error('Invalid sidebar menu: ' + this.sidebarMenu);
			}
		}

		var frameOptions = this.options;
		if(frameOptions.navbarMenu){
			var menu = this.app.config.getMenuData(frameOptions.navbarMenu);

			if(null !== menu && 'items' in menu){
				var menuIndex = -1,
					menuItems = menu.items;

				for(var i=0; i<menuItems.length; i++){
					if(viewName === menuItems[i].viewName || (this.sidebarMenu && this.sidebarMenu === menuItems[i].sidebarMenu)){
						menuIndex = i;
						break;
					}
				}

				if(menuIndex !== -1){
					this.navNavbar.setSelectedIndex(menuIndex);
				}
				else{
					this.navNavbar.setSelectedControl(null);
				}
			}

		}
	};

	/*
	* Sets the sidebar menu
	* @param menuName Name of menu defined in configuration
	*/
	FrameControllerProto.setSidebarMenu = function(menuName){
		var navSidebar = this.navSidebar,
			_this = this;

		if(menuName === this.sidebarMenu){
			return;
		}

		navSidebar.removeAllItems();

		this.sidebarMenu = menuName;

		if(!menuName){
			return;
		}

		var sidebarMenu = this.app.config.getMenuData(menuName);

		if(null !== sidebarMenu && "items" in sidebarMenu){

			var items = sidebarMenu.items;
			for(var i = 0; i < items.length; i++){
				var menuItemData = items[i],
					navItem = new ui5strap.ListNavItem();

				navItem.bindProperty('text', menuItemData.label);
				navItem.data(menuItemData);

				if(menuItemData.icon){
					navItem.addContent(new ui5strap.Icon({ 'icon' : menuItemData.icon, 'fixedWidth' : true }));
				}

				navSidebar.addItem(navItem);
			}

		}
		else{

			throw new Error('Invalid sidebar menu: ' + menuName);

		}
	};

}());<commit_msg>myapp refac<commit_after>sap.ui.define([
               "ui5strap/library",
               'pks/ui5strap/viewer/AppFrame',
               "ui5strap/Bar",
               "ui5strap/NavBar",
               "ui5strap/Nav",
               "ui5strap/ListNavItem",
               "ui5strap/Link",
               "ui5strap/ButtonGroup",
               "ui5strap/Button",
               "ui5strap/Icon"
               ], function(ui5strapBs3Lib, AppFrame, Bar, NavBar, Nav, ListNavItem, Link, ButtonGroup, Button, Icon){

	var jQuerySap = jQuery.sap;

	jQuerySap.require("jquery.sap.history");

	//FrameControllers must extend the AppFrame class
	var FrameController = AppFrame.extend("tld__domain.product__app.modules.AppFrameExample"),
		FrameControllerProto = FrameController.prototype,
		configuration = sap.ui.getCore().getConfiguration();

	FrameControllerProto.showInitialContent = function(callback){
		this.app.log.debug('[APP_FRAME_EXAMPLE] Show initial content...');
		var _this = this;
		var complete = function(){
			_this.initialized = true;
			callback && callback();
		};

		try{
			/*
			 * We want to show the intro only for the first time
			 */
			if(!this.app.getLocalStorageItem("skipIntro")){
				//Now we set the skipIntro flag in local storage to true.
				//Next time, we won't see the Intro
				this.app.setLocalStorageItem("skipIntro", true);

				this.gotoPage({
					"viewName" : "tld__domain.product__app.views.Intro",
					"transition" : "transition-none"
				}, complete);
			}
			else{
				this.gotoPage({
					"viewName" : "tld__domain.product__app.views.Page1",
					"transition" : "transition-none"
				}, complete);
			}
		}
		catch(e){
			//If localStorage is not supported, always show the Intro (IE9)
			this.gotoPage({
				"viewName" : "tld__domain.product__app.views.Intro",
				"transition" : "transition-none"
			}, complete);
		}

	};

	/*
	* Create the nav container control used by this frame.
	*/
	FrameControllerProto._createControl = function(){
		var _this = this,
			navContainer = AppFrame.prototype._createControl.call(this);

		//Get the frame options
		var frameOptions = this.options;

		//Navbar
		var navbar = new NavBar({
			inverse : true,
			fluid : true,
			position : ui5strapBs3Lib.NavBarPosition.StaticTop
		});

		this.navbar = navbar;

		//Sidenav toggle
		var toggle = new Button( {
				align : ui5strapBs3Lib.Alignment.NavBarLeft
			}
		);
		toggle.addStyleClass("btn-toggle-sidenav");
		toggle.addContent(new Icon( { icon : 'columns', size : ui5strapBs3Lib.IconSize.Large } ));

		toggle.attachEvent('tap', {}, function(){
			_this.getRootControl().toggleOption('sidenav');
		});

		navbar.addContentLeft(toggle);

		//Brand
		var brand = new Link();
		brand.bindProperty('text', {path : 'i18n>MENU_BRAND'});

		brand.attachEvent('tap', {}, function(){
			_this.showInitialContent();
		});

		navbar.setBrand(brand);

		//Main menu
		var navNavbar = new Nav(),
			menu = this.app.config.getMenuData(frameOptions.navbarMenu);

		if(menu){
			//If a navbarMenu is specified in frameOptions, create the nav menu from it
			for (var i = 0; i < menu.items.length; i++){
				var menuPage = menu.items[i],
					navItem = new ListItem(),
					navItemLink = new Link();

				navItemLink.bindProperty('text', {path : menuPage.label});

				navItem.addContent(navItemLink);

				navItem.data(menuPage);
				navNavbar.addItem(navItem);
			}

		}

		navNavbar.attachEvent('tap', {}, function(oEvent){
			var listItem = oEvent.getParameter('listItem');
			if(listItem){
				_this.gotoPage(listItem.data());

				navbar.setCollapsed(true);
			}
		});
		navNavbar.setAlign(ui5strapBs3Lib.Alignment.NavBarLeft);

		navbar.addCollapse(navNavbar);
		this.navNavbar = navNavbar;

		//Language select buttons
		var navButtons = new ButtonGroup({align : ui5strapBs3Lib.Alignment.NavBarRight}),
			buttonDe = new Button({'text' : "DE" }),
			buttonEn = new Button({'text' : "EN" });

		navButtons.addButton(buttonEn);
		navButtons.addButton(buttonDe);
		navbar.addCollapse(navButtons);

		navButtons.attachEvent('tap', {}, function(oEvent){
			var srcButton = oEvent.getParameter('button');
			navButtons.setSelectedControl(srcButton);

			if(buttonEn === srcButton){
				configuration.setLanguage('en-us');
			}
			else if(buttonDe === srcButton){
				configuration.setLanguage('de-de');
			}
		});

		if(jQuery.sap.startsWithIgnoreCase(configuration.getLanguage(), 'de')){
			buttonDe.setSelected(true);
		}
		else{
			buttonEn.setSelected(true);
		}

		//Nav menu toggle
		var toggleRight = new Button( {
				align : ui5strapBs3Lib.Alignment.NavBarRight
			}
		);
		toggle.addStyleClass("btn-toggle-navbar");
		toggleRight.addContent(new Icon( { icon : 'bars', size : ui5strapBs3Lib.IconSize.Large } ));

		toggleRight.attachEvent('tap', {}, function(){
			navbar.toggle();
		});

		navbar.addContentRight(toggleRight);

		//Sidebar / Sidenav
		var sidebar = new Bar({ "fullHeight" : true, "inverse" : true }),
			navSidebar = new Nav({ type : ui5strapBs3Lib.NavType.PillsStacked, align : ui5strapBs3Lib.Alignment.Sidebar });

		navSidebar.addStyleClass("sidebar-nav")

		this.sidebar = sidebar;

		navSidebar.attachEvent('tap', {}, function(oEvent){
			var listItem = oEvent.getParameter('listItem');
			if(listItem){
				_this.gotoPage(listItem.data());
			}
		});

		sidebar.addContent(navSidebar);
		this.navSidebar = navSidebar;

		return navContainer;
	};

	/*
	* Init navigation history
	*/
	FrameControllerProto._initHistory = function(){
		var _this = this;

		if(!this.app.config.data.app.history){
			return false;
		}

		jQuery.sap.history({
			routes : [
				{
					path : "content",
					handler : function (params, navType) {
						if(_this.initialized){
							params.writeHistory = false;
							_this.gotoPage(params);
						}
						else{
							params.writeHistory = true;
							params.transition = 'transition-none';
						}
					}
				}
			],
			defaultHandler : function (navType) {

				if(_this.initialized){
					_this.showInitialContent();
				}

			}
		});
	};

	/*
	* Navigate to a page
	*
	* @Public
	* @Override
	*/
	FrameControllerProto.gotoPage = function (viewDef, callback) {
		var _this = this,
			frameOptions = this.options;

		//If "sidebarMenu" is set, and no "viewName" specified, goto first page of sidebarMenu.
		if(viewDef.sidebarMenu && !viewDef.viewName){
			//if the viewDef contains no viewName but a sidebarMenu only, show the first entry of the submenu

			var submenu = this.app.config.getMenuData(viewDef.sidebarMenu);
			if("items" in submenu && submenu.items.length > 0){
				this.gotoPage(submenu.items[0], callback);
			}
			else{
				throw new Error('Invalid sidebar menu: ' + viewDef.sidebarMenu);
			}

			return;
		}

		//Get final view configuration
		var viewConfig = this.getViewConfig(viewDef),
			target = viewConfig.target;

		if(this.isBusy(target)){
			this.app.log.debug('[APP_FRAME_EXAMPLE] Target is busy: "' + target + '"');

			return false;
		}

		this.app.log.debug('[APP_FRAME_EXAMPLE] Navigate Target "' + target + '" to View "' + viewConfig.viewName + '"');

		var navbarEnabled = frameOptions.navbar;
		if("navbar" in viewConfig){
			navbarEnabled = viewConfig.navbar;
		}

		var sidebarEnabled = frameOptions.sidebar;
		if("sidebar" in viewConfig){
			sidebarEnabled = viewConfig.sidebar;
		}

		var sidenavEnabled = frameOptions.sidenav;
		if("sidenav" in viewConfig){
			sidenavEnabled = viewConfig.sidenav;
		}

		var sidebar2Nav = frameOptions.sidebar2Nav;
		if("sidebar2Nav" in viewConfig){
			sidebar2Nav = viewConfig.sidebar2Nav;
		}

		var sidebarSmall = frameOptions.sidebarSmall;
		if("sidebarSmall" in viewConfig){
			sidebarSmall = viewConfig.sidebarSmall;
		}

		var sidenavToggle = frameOptions.sidenavToggle;
		if("sidenavToggle" in viewConfig){
			sidenavToggle = viewConfig.sidenavToggle;
		}

		this.getRootControl().setOptionsEnabled({
			'navbar' :  navbarEnabled,
			'sidebar' : sidebarEnabled,
			'sidenav' : sidenavEnabled,

			'sidebar-2nav' : sidebar2Nav,
			'sidebar-small' : sidebarSmall,
			'sidenav-toggle' : sidenavToggle
		});

		if("sidebarMenu" in viewConfig){
			this.setSidebarMenu(viewConfig.sidebarMenu);
		}
		else if("sidebarMenu" in frameOptions){
			this.setSidebarMenu(frameOptions.sidebarMenu);
		}

		this.getRootControl().toPage(this.sidebar, 'sidebar', "transition-none");
		this.getRootControl().toPage(this.navbar, 'navbar', "transition-none");

		var currentPage = this.getCurrentPage(target);
		if(
			_this.getRootControl().getDomRef()
			&& viewConfig.id
			&& currentPage
			&& viewConfig.id === currentPage.getId()
		){
			this.updatePage(currentPage, viewConfig.parameters);

			this.app.log.debug('[APP_FRAME_EXAMPLE] Page is current: "' + viewConfig.id + '"');

			return false;
		}

		if(viewConfig.documentTitle){
			var titlePath = viewConfig.documentTitle.split('>');
			if(titlePath.length === 2){
				document.title = this.app.getLocaleString(titlePath[1], titlePath[0]);
			}
		}

		this.updateMenu(viewConfig.viewName);

		if(viewConfig.showLoader){
			this.app.setLoaderVisible(true, function(){
				_this.toPage(viewConfig, callback);
			})
		}
		else{
			this.toPage(viewConfig, callback);
		}

		//Write history entry for back/forward navigation in browser / using javascript.
		if (viewConfig.writeHistory && this.app.config.data.app.history) {
			jQuery.sap.history.addHistory(target, viewDef, viewConfig.bookmarkable, viewConfig.virtual);
		}

		return true;
	};

	/*
	*
	* Update menu and highlight items that match to current view
	*
	* @Public
	*/
	FrameControllerProto.updateMenu = function(viewName){
		this.app.log.debug('[APP_FRAME_EXAMPLE] updateMenu "' + viewName + '"');

		var navSidebar = this.navSidebar;

		if(this.sidebarMenu){
			var sidebarMenu = this.app.config.getMenuData(this.sidebarMenu);

			if(null !== sidebarMenu && 'items' in sidebarMenu){
				var sidebarMenuIndex = -1,
					sidebarItems = sidebarMenu.items;

				for(var i=0; i<sidebarItems.length; i++){
					if(viewName === this.app.config.resolvePackage(sidebarItems[i].viewName, "views")){
						sidebarMenuIndex = i;
						break;
					}
				}

				if(sidebarMenuIndex !== -1){
					navSidebar.setSelectedIndex(sidebarMenuIndex);
				}
				else{
					navSidebar.setSelectedControl(null);
				}
			}
			else{
				throw new Error('Invalid sidebar menu: ' + this.sidebarMenu);
			}
		}

		var frameOptions = this.options;
		if(frameOptions.navbarMenu){
			var menu = this.app.config.getMenuData(frameOptions.navbarMenu);

			if(null !== menu && 'items' in menu){
				var menuIndex = -1,
					menuItems = menu.items;

				for(var i=0; i<menuItems.length; i++){
					if(viewName === menuItems[i].viewName || (this.sidebarMenu && this.sidebarMenu === menuItems[i].sidebarMenu)){
						menuIndex = i;
						break;
					}
				}

				if(menuIndex !== -1){
					this.navNavbar.setSelectedIndex(menuIndex);
				}
				else{
					this.navNavbar.setSelectedControl(null);
				}
			}

		}
	};

	/*
	* Sets the sidebar menu
	* @param menuName Name of menu defined in configuration
	*/
	FrameControllerProto.setSidebarMenu = function(menuName){
		var navSidebar = this.navSidebar,
			_this = this;

		if(menuName === this.sidebarMenu){
			return;
		}

		navSidebar.removeAllItems();

		this.sidebarMenu = menuName;

		if(!menuName){
			return;
		}

		var sidebarMenu = this.app.config.getMenuData(menuName);

		if(null !== sidebarMenu && "items" in sidebarMenu){

			var items = sidebarMenu.items;
			for(var i = 0; i < items.length; i++){
				var menuItemData = items[i],
					navItem = new ListNavItem();

				navItem.bindProperty('text', menuItemData.label);
				navItem.data(menuItemData);

				if(menuItemData.icon){
					navItem.addContent(new Icon({ 'icon' : menuItemData.icon, 'fixedWidth' : true }));
				}

				navSidebar.addItem(navItem);
			}

		}
		else{

			throw new Error('Invalid sidebar menu: ' + menuName);

		}
	};

	return FrameController;
});<|endoftext|>