<commit_before>var gulp = require('gulp');
var fs = require('fs');
var concat = require('gulp-concat');
var ts = require('gulp-typescript');
var merge = require('merge-stream');
var gutil = require('gulp-util');
var gunzip = require('gulp-gunzip');
var request = require('request');
var untar = require('gulp-untar');
var source = require('vinyl-source-stream');
var filter = require('gulp-filter');
var ngHtml2Js = require("gulp-ng-html2js");
var minifyHtml = require("gulp-minify-html");
var uglify = require("gulp-uglify");
var gulpif = require("gulp-if");
var sprity = require('sprity');
var sass = require('gulp-sass');
var spritySass = require('sprity-sass');
var rimraf = require('rimraf');
var download = require('gulp-download');
var rename = require('gulp-rename');
var cleanCss = require('gulp-clean-css');

// CONFIG
// ==============================
var outDir = "./dist";
var tsConfig = JSON.parse(fs.readFileSync('tsconfig.json'));
var tsFiles = tsConfig.files;
var tsConfigGulp = {
    "module": tsConfig.compilerOptions.module,
    "removeComments": tsConfig.compilerOptions.removeComments,
    "noEmitOnError": tsConfig.compilerOptions.noEmitOnError,
    "declaration": tsConfig.compilerOptions.declaration,
    "sourceMap": tsConfig.compilerOptions.sourceMap,
    "preserveConstEnums": tsConfig.compilerOptions.preserveConstEnums,
    "target": tsConfig.compilerOptions.target,
    "noImplicitAny": tsConfig.compilerOptions.noImplicitAny,
    "allowUnreachableCode": tsConfig.compilerOptions.allowUnreachableCode,
    "allowUnusedLabels": tsConfig.compilerOptions.allowUnusedLabels,
    "out":"main.js"
};
var thirdPartyFiles = [
    './third-party/jquery/dist/jquery.js',
    './third-party/angular/angular.js',
    './third-party/angular-ui-router/release/angular-ui-router.js',
    './third-party/angular-sanitize/angular-sanitize.js',
    './third-party/angular-animate/angular-animate.js',
    './third-party/modepress-client/dist/plugin.js',
    './third-party/angular-loading-bar/build/loading-bar.js',
    './third-party/angular-loading-bar/build/loading-bar.css'
];

/**
 * Checks to see that all TS files listed exist
 */
gulp.task('check-files', function(){

    // Make sure the files exist
    for (var i = 0, l = tsFiles.length; i < l; i++ )
        if(!fs.existsSync(tsFiles[i]))
        {
            console.log("File does not exist:" + tsFiles[i] );
            process.exit();
        }
});

gulp.task('sass', ['sprites'], function() {

    // Compile all sass files into temp/css
    return gulp.src('./src/style.scss', { base: "./src" })
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest(outDir + '/css'))
})

gulp.task('sass-release', ['sprites'], function() {

    // Compile all sass files into temp/css
    return gulp.src('./src/style.scss', { base: "./src" })
        .pipe(sass().on('error', sass.logError))
        .pipe(cleanCss())
        .pipe(gulp.dest(outDir + '/css'))
})

/**
 * Generate dist/media/sprites/sprite.png and /src/temp/sprite.scss
 */
gulp.task('sprites', function () {
  return sprity.src({
    src: './src/media/sprites/**/*.{png,jpg}',
    style: './sprites.scss',
    cssPath: '/media/sprites',
    name: 'sprites',
    orientation : 'binary-tree',
    prefix: 'sprite',
    processor: 'sass',
    'style-type': 'scss',
    margin:0
  })
  .pipe(gulpif('*.png', gulp.dest( outDir + '/media/sprites'), gulp.dest(  "src/temp-css"  )))
});

/**
 * Builds each of the ts files into JS files in the output folder
 */
gulp.task('ts-code', ['check-files'], function() {

    return gulp.src(tsFiles, { base: "." })
        .pipe(ts( tsConfigGulp ))
        .pipe(gulp.dest(outDir));
});

/**
 * Builds each of the ts files into JS files in the output folder. Also performs an uglify on the code to make it compact.
 */
gulp.task('ts-code-release', ['check-files'], function() {

    return gulp.src(tsFiles, { base: "." })
        .pipe(ts( tsConfigGulp ))
        .pipe(uglify())
        .pipe(gulp.dest(outDir));
});

/**
 * Copies the html source to its output directory
 */
gulp.task('copy-index', function() {

    return gulp.src(["src/index.jade",
            "src/sitemap.xml",
            "src/favicon.ico",
            "src/media/images/**/*.*",
            "src/media/fonts/**/*.*"
            ], { base: "src" })
        .pipe(gulp.dest(outDir));

});

/**
 * Copies the html source to its output directory
 */
gulp.task('copy-index-release', function() {

    return Promise.all([

        gulp.src( "src/index-prod.jade", { base: "src" })
            .pipe(rename("index.jade"))
            .pipe(gulp.dest(outDir)),

        gulp.src([
            "src/sitemap.xml",
            "src/favicon.ico",
            "src/media/images/**/*.*",
            "src/media/fonts/**/*.*"
            ], { base: "src" })
        .pipe(gulp.dest(outDir))
    ]);
});

/**
 * Deletes a folder and all its children recursively
 * @param {string} path The folder path to remove
 */
function deleteFolderRecursive(path) {
    if( fs.existsSync(path) ) {
        fs.readdirSync(path).forEach(function(file,index){
            var curPath = path + "/" + file;
            if(fs.lstatSync(curPath).isDirectory()) { // recurse
                deleteFolderRecursive(curPath);
            }
            else
                fs.unlinkSync(curPath);
        });
        fs.rmdirSync(path);
    }
};

/**
 * Downloads a tarbal from a given url and unzips it into a specified folder
 * @param {string} url The URL of the tarball to download
 * @param {string} folder The folder we are moving the contents to
 */
function downloadTarball(url, folder){
    return new Promise(function(resolve, reject){
        gutil.log('Downloading file "'+ url +'" into folder "' + folder + '"');
        return request(url)
        .pipe(source('hello.tar.gz'))
        .on('end', function(){
            gutil.log('Unzipping... "'+ url +'"');
        })
        .pipe(gunzip())
        .pipe(untar())
        .pipe(gulp.dest(folder))
        .on('end', function() {
            var folders = fs.readdirSync(folder);
            gulp.src( folder + '/' + folders[0] + "/**/*.*" )
                .pipe(gulp.dest(folder))
                .on('end', function() {
                    deleteFolderRecursive(folder + '/' + folders[0]);
                    gutil.log(gutil.colors.green('Finished download of "'+ url +'"'));
                    resolve(true);
                });
        })
    });
}

/**
 * Downloads each of the third party archives and unzips them into the third-party folder respectively
 */
gulp.task('install-third-parties', function () {

    deleteFolderRecursive("./third-party");

    return Promise.all([
        downloadTarball("https://github.com/angular/bower-angular/tarball/v1.5.3-build.4695+sha.7489d56", './third-party/angular'),
        downloadTarball("https://github.com/angular/bower-angular-animate/tarball/v1.5.3-build.4691+sha.e34ef23", './third-party/angular-animate'),
        downloadTarball("https://github.com/angular/bower-angular-sanitize/tarball/v1.5.3-build.4691+sha.e34ef23", './third-party/angular-sanitize'),
        downloadTarball("https://github.com/angular-ui/ui-router/tarball/0.2.18", './third-party/angular-ui-router'),
        downloadTarball("https://github.com/jquery/jquery/tarball/2.2.2", './third-party/jquery'),
        downloadTarball("https://github.com/chieffancypants/angular-loading-bar/tarball/0.9.0", './third-party/angular-loading-bar'),
        downloadTarball("https://github.com/MKHenson/modepress-client-angular/tarball/master", './third-party/modepress-client'),
    ]);
});

/**
 * This function downloads a definition file from github and writes it to a destination
 * @param {string} url The url of the file to download
 * @param {string} dest The destination folder to move the file to
 */
function getDefinition(url, dest, name) {
    return new Promise(function(resolve, reject) {
        download(url)
            .pipe(rename(name))
            .pipe(gulp.dest(dest))
            .on('error', function(err) {
                throw(err)
            })
            .on('end', function() {
                resolve(true);
            })
    });
}

/**
 * Downloads the definition files used in the development of the application and moves them into the definitions folder
 */
gulp.task('install-definitions', function () {
     return Promise.all([
            getDefinition("https://raw.githubusercontent.com/MKHenson/users/dev/src/definitions/custom/definitions.d.ts", "src/definitions/required/", "users.d.ts"),
            getDefinition("https://raw.githubusercontent.com/MKHenson/modepress/dev/server/src/definitions/custom/modepress-api.d.ts", "src/definitions/required/", "modepress-api.d.ts"),
            getDefinition("https://raw.githubusercontent.com/MKHenson/modepress-client-angular/master/src/definitions/generated/plugin.d.ts", "src/definitions/required/", "modepress-client.d.ts")
         ]);
});

/**
 * Copies the required third party files to the index file
 */
gulp.task('deploy-third-party', function() {

    return gulp.src( thirdPartyFiles, { base: "third-party" } )
        .pipe(gulp.dest(outDir + "/third-party"));
});

/**
 * Copies the required third party files to the index file. Also concatenates the files into 1, compressed, JS file
 */
gulp.task('deploy-third-party-release', function() {

    const jsFilter = filter('**/*.js', {restore: true});
    const cssFilter = filter('**/*.css', {restore: true});

    return gulp.src( thirdPartyFiles, { base: "third-party" } )
        .pipe(jsFilter)
        .pipe(concat("third-party.min.js"))
        .pipe(uglify())
        .pipe(jsFilter.restore)
        .pipe(cssFilter)
        .pipe(cleanCss())
        .pipe(concat("third-party.min.css"))
        .pipe(cssFilter.restore)
        .pipe(gulp.dest(outDir + "/third-party"));
});

/**
 * Builds the definition
 */
gulp.task('html-to-ng', function() {
    return gulp.src("./src/**/*.html")
        .pipe(minifyHtml({
            empty: true,
            spare: true,
            quotes: true
        }))
        .pipe(ngHtml2Js({
            moduleName: "html-templates",
            prefix: ""
        }))
        .pipe(concat("partials.min.js"))
        .pipe(uglify())
        .pipe(gulp.dest(outDir + "/templates"));
});

gulp.task('install', [ 'install-definitions', 'install-third-parties']);
gulp.task('build-all', [ 'deploy-third-party', 'html-to-ng', 'copy-index', 'sass', 'ts-code']);
gulp.task('build-all-release', [ 'deploy-third-party-release', 'html-to-ng', 'copy-index-release', 'sass-release', 'ts-code-release']);<commit_msg>Updated gulp file to use rimraf instead of custom function<commit_after>var gulp = require('gulp');
var fs = require('fs');
var concat = require('gulp-concat');
var ts = require('gulp-typescript');
var merge = require('merge-stream');
var gutil = require('gulp-util');
var gunzip = require('gulp-gunzip');
var request = require('request');
var untar = require('gulp-untar');
var source = require('vinyl-source-stream');
var filter = require('gulp-filter');
var ngHtml2Js = require("gulp-ng-html2js");
var minifyHtml = require("gulp-minify-html");
var uglify = require("gulp-uglify");
var gulpif = require("gulp-if");
var sprity = require('sprity');
var sass = require('gulp-sass');
var spritySass = require('sprity-sass');
var rimraf = require('rimraf');
var download = require('gulp-download');
var rename = require('gulp-rename');
var cleanCss = require('gulp-clean-css');

// CONFIG
// ==============================
var outDir = "./dist";
var tsConfig = JSON.parse(fs.readFileSync('tsconfig.json'));
var tsFiles = tsConfig.files;
var tsConfigGulp = {
    "module": tsConfig.compilerOptions.module,
    "removeComments": tsConfig.compilerOptions.removeComments,
    "noEmitOnError": tsConfig.compilerOptions.noEmitOnError,
    "declaration": tsConfig.compilerOptions.declaration,
    "sourceMap": tsConfig.compilerOptions.sourceMap,
    "preserveConstEnums": tsConfig.compilerOptions.preserveConstEnums,
    "target": tsConfig.compilerOptions.target,
    "noImplicitAny": tsConfig.compilerOptions.noImplicitAny,
    "allowUnreachableCode": tsConfig.compilerOptions.allowUnreachableCode,
    "allowUnusedLabels": tsConfig.compilerOptions.allowUnusedLabels,
    "out":"main.js"
};
var thirdPartyFiles = [
    './third-party/jquery/dist/jquery.js',
    './third-party/angular/angular.js',
    './third-party/angular-ui-router/release/angular-ui-router.js',
    './third-party/angular-sanitize/angular-sanitize.js',
    './third-party/angular-animate/angular-animate.js',
    './third-party/modepress-client/dist/plugin.js',
    './third-party/angular-loading-bar/build/loading-bar.js',
    './third-party/angular-loading-bar/build/loading-bar.css'
];

/**
 * Checks to see that all TS files listed exist
 */
gulp.task('check-files', function(){

    // Make sure the files exist
    for (var i = 0, l = tsFiles.length; i < l; i++ )
        if(!fs.existsSync(tsFiles[i]))
        {
            console.log("File does not exist:" + tsFiles[i] );
            process.exit();
        }
});

gulp.task('sass', ['sprites'], function() {

    // Compile all sass files into temp/css
    return gulp.src('./src/style.scss', { base: "./src" })
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest(outDir + '/css'))
})

gulp.task('sass-release', ['sprites'], function() {

    // Compile all sass files into temp/css
    return gulp.src('./src/style.scss', { base: "./src" })
        .pipe(sass().on('error', sass.logError))
        .pipe(cleanCss())
        .pipe(gulp.dest(outDir + '/css'))
})

/**
 * Generate dist/media/sprites/sprite.png and /src/temp/sprite.scss
 */
gulp.task('sprites', function () {
  return sprity.src({
    src: './src/media/sprites/**/*.{png,jpg}',
    style: './sprites.scss',
    cssPath: '/media/sprites',
    name: 'sprites',
    orientation : 'binary-tree',
    prefix: 'sprite',
    processor: 'sass',
    'style-type': 'scss',
    margin:0
  })
  .pipe(gulpif('*.png', gulp.dest( outDir + '/media/sprites'), gulp.dest(  "src/temp-css"  )))
});

/**
 * Builds each of the ts files into JS files in the output folder
 */
gulp.task('ts-code', ['check-files'], function() {

    return gulp.src(tsFiles, { base: "." })
        .pipe(ts( tsConfigGulp ))
        .pipe(gulp.dest(outDir));
});

/**
 * Builds each of the ts files into JS files in the output folder. Also performs an uglify on the code to make it compact.
 */
gulp.task('ts-code-release', ['check-files'], function() {

    return gulp.src(tsFiles, { base: "." })
        .pipe(ts( tsConfigGulp ))
        .pipe(uglify())
        .pipe(gulp.dest(outDir));
});

/**
 * Copies the html source to its output directory
 */
gulp.task('copy-index', function() {

    return gulp.src(["src/index.jade",
            "src/sitemap.xml",
            "src/favicon.ico",
            "src/media/images/**/*.*",
            "src/media/fonts/**/*.*"
            ], { base: "src" })
        .pipe(gulp.dest(outDir));

});

/**
 * Copies the html source to its output directory
 */
gulp.task('copy-index-release', function() {

    return Promise.all([

        gulp.src( "src/index-prod.jade", { base: "src" })
            .pipe(rename("index.jade"))
            .pipe(gulp.dest(outDir)),

        gulp.src([
            "src/sitemap.xml",
            "src/favicon.ico",
            "src/media/images/**/*.*",
            "src/media/fonts/**/*.*"
            ], { base: "src" })
        .pipe(gulp.dest(outDir))
    ]);
});

/**
 * Downloads a tarbal from a given url and unzips it into a specified folder
 * @param {string} url The URL of the tarball to download
 * @param {string} folder The folder we are moving the contents to
 */
function downloadTarball(url, folder){
    return new Promise(function(resolve, reject){
        gutil.log('Downloading file "'+ url +'" into folder "' + folder + '"');
        return request(url)
        .pipe(source('hello.tar.gz'))
        .on('end', function(){
            gutil.log('Unzipping... "'+ url +'"');
        })
        .pipe(gunzip())
        .pipe(untar())
        .pipe(gulp.dest(folder))
        .on('end', function() {
            var folders = fs.readdirSync(folder);
            gulp.src( folder + '/' + folders[0] + "/**/*.*" )
                .pipe(gulp.dest(folder))
                .on('end', function() {
                    rimraf.sync(folder + '/' + folders[0]);
                    gutil.log(gutil.colors.green('Finished download of "'+ url +'"'));
                    resolve(true);
                });
        })
    });
}

/**
 * Downloads each of the third party archives and unzips them into the third-party folder respectively
 */
gulp.task('install-third-parties', function () {

    rimraf.sync("./third-party");

    return Promise.all([
        downloadTarball("https://github.com/angular/bower-angular/tarball/v1.5.3-build.4695+sha.7489d56", './third-party/angular'),
        downloadTarball("https://github.com/angular/bower-angular-animate/tarball/v1.5.3-build.4691+sha.e34ef23", './third-party/angular-animate'),
        downloadTarball("https://github.com/angular/bower-angular-sanitize/tarball/v1.5.3-build.4691+sha.e34ef23", './third-party/angular-sanitize'),
        downloadTarball("https://github.com/angular-ui/ui-router/tarball/0.2.18", './third-party/angular-ui-router'),
        downloadTarball("https://github.com/jquery/jquery/tarball/2.2.2", './third-party/jquery'),
        downloadTarball("https://github.com/chieffancypants/angular-loading-bar/tarball/0.9.0", './third-party/angular-loading-bar'),
        downloadTarball("https://github.com/MKHenson/modepress-client-angular/tarball/master", './third-party/modepress-client'),
    ]);
});

/**
 * This function downloads a definition file from github and writes it to a destination
 * @param {string} url The url of the file to download
 * @param {string} dest The destination folder to move the file to
 */
function getDefinition(url, dest, name) {
    return new Promise(function(resolve, reject) {
        download(url)
            .pipe(rename(name))
            .pipe(gulp.dest(dest))
            .on('error', function(err) {
                throw(err)
            })
            .on('end', function() {
                resolve(true);
            })
    });
}

/**
 * Downloads the definition files used in the development of the application and moves them into the definitions folder
 */
gulp.task('install-definitions', function () {
     return Promise.all([
            getDefinition("https://raw.githubusercontent.com/MKHenson/users/dev/src/definitions/custom/definitions.d.ts", "src/definitions/required/", "users.d.ts"),
            getDefinition("https://raw.githubusercontent.com/MKHenson/modepress/dev/server/src/definitions/custom/modepress-api.d.ts", "src/definitions/required/", "modepress-api.d.ts"),
            getDefinition("https://raw.githubusercontent.com/MKHenson/modepress-client-angular/master/src/definitions/generated/plugin.d.ts", "src/definitions/required/", "modepress-client.d.ts")
         ]);
});

/**
 * Copies the required third party files to the index file
 */
gulp.task('deploy-third-party', function() {

    return gulp.src( thirdPartyFiles, { base: "third-party" } )
        .pipe(gulp.dest(outDir + "/third-party"));
});

/**
 * Copies the required third party files to the index file. Also concatenates the files into 1, compressed, JS file
 */
gulp.task('deploy-third-party-release', function() {

    const jsFilter = filter('**/*.js', {restore: true});
    const cssFilter = filter('**/*.css', {restore: true});

    return gulp.src( thirdPartyFiles, { base: "third-party" } )
        .pipe(jsFilter)
        .pipe(concat("third-party.min.js"))
        .pipe(uglify())
        .pipe(jsFilter.restore)
        .pipe(cssFilter)
        .pipe(cleanCss())
        .pipe(concat("third-party.min.css"))
        .pipe(cssFilter.restore)
        .pipe(gulp.dest(outDir + "/third-party"));
});

/**
 * Builds the definition
 */
gulp.task('html-to-ng', function() {
    return gulp.src("./src/**/*.html")
        .pipe(minifyHtml({
            empty: true,
            spare: true,
            quotes: true
        }))
        .pipe(ngHtml2Js({
            moduleName: "html-templates",
            prefix: ""
        }))
        .pipe(concat("partials.min.js"))
        .pipe(uglify())
        .pipe(gulp.dest(outDir + "/templates"));
});

gulp.task('install', [ 'install-definitions', 'install-third-parties']);
gulp.task('build-all', [ 'deploy-third-party', 'html-to-ng', 'copy-index', 'sass', 'ts-code']);
gulp.task('build-all-release', [ 'deploy-third-party-release', 'html-to-ng', 'copy-index-release', 'sass-release', 'ts-code-release']);<|endoftext|>


<commit_before>var gulp = require('gulp');
var csso = require('gulp-csso');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
var plumber = require('gulp-plumber');
var cp = require('child_process');
var imagemin = require('gulp-imagemin');
var browserSync = require('browser-sync');
var del = require('del');

var jekyllCommand = (/^win/.test(process.platform)) ? 'jekyll.bat' : 'jekyll';

/*
 * Build the Jekyll Site
 * runs a child process in node that runs the jekyll commands
 */
gulp.task('jekyll-build', function (done) {
	return cp.spawn(jekyllCommand, ['build'], {stdio: 'inherit'})
		.on('close', done);
});

/*
 * Rebuild Jekyll & reload browserSync
 */
gulp.task('jekyll-rebuild', ['jekyll-build'], function () {
	browserSync.reload();
});

/*
 * Build the jekyll site and launch browser-sync
 */
gulp.task('browser-sync', ['jekyll-build'], function() {
	browserSync({
		server: {
			baseDir: '_site'
		}
	});
});

/*
* Compile and minify sass
*/
gulp.task('sass', function() {
  gulp.src('src/styles/**/*.scss')
    .pipe(plumber())
    .pipe(sass())
    .pipe(csso())
    .pipe(gulp.dest('assets/css'));
});

/*
 * Minify images
 */
gulp.task('imagemin', function() {
	return gulp.src('src/img/**/*.{jpg,png,gif}')
		.pipe(plumber())
		.pipe(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true }))
		.pipe(gulp.dest('assets/img/'));
});

/**
 * Compile and minify js
 */
gulp.task('js', function(){
	return gulp.src('src/js/**/*.js')
		.pipe(plumber())
		.pipe(concat('main.js'))
		.pipe(uglify())
		.pipe(gulp.dest('assets/js/'))
});

gulp.task('watch', function() {
  gulp.watch('src/styles/**/*.scss', ['sass']);
  gulp.watch('src/js/**/*.js', ['js-watch']);
  gulp.watch('src/img/**/*.{jpg,png,gif}', ['imagemin']);
  gulp.watch(['*html', '_includes/*html', '_layouts/*.html'], ['jekyll-rebuild']);
  gulp.watch(['_data/*.yml'], ['jekyll-rebuild']);
});

gulp.task('reload', ['js', 'jekyll-rebuild']);

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

gulp.task('default', ['build', 'browser-sync', 'watch']);

gulp.task('clean', function () {
    return del([
        'src/**/*',
        'gulpfile.js',
        'package.json'
    ]);
});

gulp.task('deploy', ['build', 'clean']);
<commit_msg>delete travis yml so build does not trigger on master<commit_after>var gulp = require('gulp');
var csso = require('gulp-csso');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
var plumber = require('gulp-plumber');
var cp = require('child_process');
var imagemin = require('gulp-imagemin');
var browserSync = require('browser-sync');
var del = require('del');

var jekyllCommand = (/^win/.test(process.platform)) ? 'jekyll.bat' : 'jekyll';

/*
 * Build the Jekyll Site
 * runs a child process in node that runs the jekyll commands
 */
gulp.task('jekyll-build', function (done) {
	return cp.spawn(jekyllCommand, ['build'], {stdio: 'inherit'})
		.on('close', done);
});

/*
 * Rebuild Jekyll & reload browserSync
 */
gulp.task('jekyll-rebuild', ['jekyll-build'], function () {
	browserSync.reload();
});

/*
 * Build the jekyll site and launch browser-sync
 */
gulp.task('browser-sync', ['jekyll-build'], function() {
	browserSync({
		server: {
			baseDir: '_site'
		}
	});
});

/*
* Compile and minify sass
*/
gulp.task('sass', function() {
  gulp.src('src/styles/**/*.scss')
    .pipe(plumber())
    .pipe(sass())
    .pipe(csso())
    .pipe(gulp.dest('assets/css'));
});

/*
 * Minify images
 */
gulp.task('imagemin', function() {
	return gulp.src('src/img/**/*.{jpg,png,gif}')
		.pipe(plumber())
		.pipe(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true }))
		.pipe(gulp.dest('assets/img/'));
});

/**
 * Compile and minify js
 */
gulp.task('js', function(){
	return gulp.src('src/js/**/*.js')
		.pipe(plumber())
		.pipe(concat('main.js'))
		.pipe(uglify())
		.pipe(gulp.dest('assets/js/'))
});

gulp.task('watch', function() {
  gulp.watch('src/styles/**/*.scss', ['sass']);
  gulp.watch('src/js/**/*.js', ['js-watch']);
  gulp.watch('src/img/**/*.{jpg,png,gif}', ['imagemin']);
  gulp.watch(['*html', '_includes/*html', '_layouts/*.html'], ['jekyll-rebuild']);
  gulp.watch(['_data/*.yml'], ['jekyll-rebuild']);
});

gulp.task('reload', ['js', 'jekyll-rebuild']);

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

gulp.task('default', ['build', 'browser-sync', 'watch']);

gulp.task('clean', function () {
    return del([
        'src/**/*',
        'gulpfile.js',
        '.DS_Store',
        '.travis.yml',
        'package.json'
    ]);
});

gulp.task('deploy', ['build', 'clean']);
<|endoftext|>


<commit_before>// Define project paths.
// Note: all of these are relative to the project root.
var projectPaths = {
    scssSources: 'scss',
    wwwRoot: 'www'
};

// Import required dependencies.
var gulp = require('gulp'),
    browserSync = require('browser-sync'),
    browserSyncReload = browserSync.reload,
    sass = require('gulp-sass'),
    filter = require('gulp-filter');

var browserSyncConfig = {
    server: {
        baseDir: './' + projectPaths.wwwRoot
    },
    files: [
        projectPaths.wwwRoot + '/css/*.css',
        projectPaths.wwwRoot + '/*.html'
    ]
};

gulp.task('sass', function() {
   return gulp.src(projectPaths.scssSources + '/*.scss')
        .pipe(sass())
        .pipe(gulp.dest(projectPaths.wwwRoot + '/css'))
        .pipe(filter('**/*.css'))
        .pipe(browserSyncReload({stream: true}));
});

gulp.task('browser-sync', function() {
    browserSync(browserSyncConfig);
});

gulp.task('copy-vendor-js', function() {
    gulp.src([
        './bower_components/jquery/dist/jquery.js',
        './bower_components/parse-js-sdk/lib/parse.js'
    ]).pipe(gulp.dest('./www/js'));
});

gulp.task('default', ['sass', 'browser-sync'], function() {
    gulp.watch(projectPaths.scssSources + '/*.scss', ['sass']);
});

<commit_msg>Updates gulp tasks definition to split out the watch task from the default task.<commit_after>// Define project paths.
// Note: all of these are relative to the project root.
var projectPaths = {
    scssSources: 'scss',
    wwwRoot: 'www'
};

// Import required dependencies.
var gulp = require('gulp'),
    browserSync = require('browser-sync'),
    browserSyncReload = browserSync.reload,
    sass = require('gulp-sass'),
    filter = require('gulp-filter');

var browserSyncConfig = {
    server: {
        baseDir: './' + projectPaths.wwwRoot
    },
    files: [
        projectPaths.wwwRoot + '/css/*.css',
        projectPaths.wwwRoot + '/*.html'
    ]
};

gulp.task('sass', function() {
   return gulp.src(projectPaths.scssSources + '/*.scss')
        .pipe(sass())
        .pipe(gulp.dest(projectPaths.wwwRoot + '/css'))
        .pipe(filter('**/*.css'))
        .pipe(browserSyncReload({stream: true}));
});

gulp.task('browser-sync', function() {
    browserSync(browserSyncConfig);
});

gulp.task('copy-vendor-js', function() {
    gulp.src([
        './bower_components/jquery/dist/jquery.js',
        './bower_components/parse-js-sdk/lib/parse.js'
    ]).pipe(gulp.dest('./www/js'));
});

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

gulp.task('default', ['sass', 'browser-sync', 'watch']);

<|endoftext|>


<commit_before>//Basic build process. Nothing too fancy

var gulp = require('gulp');
var concat = require('gulp-concat');
var prettify = require('gulp-jsbeautifier');
var minify = require('gulp-minify');
var jsfuck = require('gulp-jsfuck');

gulp.task('default', function() {
  return gulp.src(['./src/constants/start.js','./src/*.js','./src/constants/end.js'])
    .pipe(concat('anything.js'))
    .pipe(prettify())
    .pipe(minify({
        ext:{
            src: '.js',
            min: '.min.js'
        }
    }))
    .pipe(gulp.dest('./dist/'));
});

gulp.task('fuck', function() {
    return gulp.src(['./src/constants/start.js','./src/*.js','./src/constants/end.js'])
    .pipe(concat('anything.fucked.js'))
    .pipe(jsfuck())
    .pipe(gulp.dest('./dist/'));
})
<commit_msg>require gulp-jsfuck only when really must<commit_after>//Basic build process. Nothing too fancy

var gulp = require('gulp');
var concat = require('gulp-concat');
var prettify = require('gulp-jsbeautifier');
var minify = require('gulp-minify');

gulp.task('default', function() {
  return gulp.src(['./src/constants/start.js','./src/*.js','./src/constants/end.js'])
    .pipe(concat('anything.js'))
    .pipe(prettify())
    .pipe(minify({
        ext:{
            src: '.js',
            min: '.min.js'
        }
    }))
    .pipe(gulp.dest('./dist/'));
});

gulp.task('fuck', function() {
    var jsfuck = require('gulp-jsfuck');
    return gulp.src(['./src/constants/start.js','./src/*.js','./src/constants/end.js'])
    .pipe(concat('anything.fucked.js'))
    .pipe(jsfuck())
    .pipe(gulp.dest('./dist/'));
})
<|endoftext|>


<commit_before>'use strict';

const pkg = require('./package');
const gulp = require('gulp');
const jshint = require('gulp-jshint');
const stylish = require('jshint-stylish');

gulp.task('jshint', function() {
	return gulp
		.src(['./src/*.js', './sample/*.js'])
		.pipe(jshint(pkg.jshintConfig))
		.pipe(jshint.reporter(stylish));
});

<commit_msg>add gulp browser command<commit_after>'use strict';

const pkg = require('./package');
const gulp = require('gulp');
const jshint = require('gulp-jshint');
const stylish = require('jshint-stylish');
const browserify = require('browserify');
const source = require('vinyl-source-stream');
const del = require('del');
const uglify = require('gulp-uglify');
const pump = require('pump');
const babelify = require('babelify');
const rename = require('gulp-rename');

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

gulp.task('jshint', function() {
	return gulp
		.src(['./src/*.js', './sample/*.js'])
		.pipe(jshint(pkg.jshintConfig))
		.pipe(jshint.reporter(stylish));
});

gulp.task('browser:uncompressed', function() {
	return browserify({debug: true})
		.require('./src/index.js', {expose: 'counterjs'})
		.transform(babelify)
		.bundle()
		.pipe(source('counterjs.js'))
		.pipe(gulp.dest('dist'));
});

gulp.task('browser:compressed', ['browser:uncompressed'], function(cb) {
	pump([
		gulp.src('./dist/counterjs.js'),
		uglify(),
		rename('counterjs.min.js'),
		gulp.dest('./dist'),
	], cb);
});

gulp.task('browser', ['browser:compressed']);

<|endoftext|>


<commit_before>(function($){

  //Utils functions
  function setActivities(){
    var activities = activityList.find(".notification li");
    activities.removeClass("chidden");
    if(!activityList.hasClass("fullList")){
      for(var i = 7; i<activities.length; i++){
        $(activities.get(i)).addClass("chidden");
      }
      $("#activity-list-full-btn").addClass("chidden");
      $("#activity-list-expand-btn a").text("Tout afficher");
    } else {
      $("#activity-list-full-btn").removeClass("chidden");
      $("#activity-list-expand-btn a").text("Cacher");
    }
  }

  String.prototype.hashCode = function() {
    var hash = 0, i, chr;
    if (this.length === 0) return hash;
    for (i = 0; i < this.length; i++) {
      chr   = this.charCodeAt(i);
      hash  = ((hash << 5) - hash) + chr;
      hash |= 0; // Convert to 32bit integer
    }
    return hash;
  };

  function getActivityHash(activity){
    var title = activity.find(".resume strong a").text();
    var author = activity.find(".auteur").text();
    var date = activity.find(".date").text();
    return (title+author+date).hashCode().toString().replace(/-/g,"k");
  }

  //Events and iterators functions

  function onEachActivity(){
    var $this = $(this);
    var hash = getActivityHash($this);
    $this.attr("id","activity-"+hash);
    $this.attr("data-hash",hash);
    $this.prepend('')
  }

  function initOnEachActivityBroadcast(el){
      var $this = $(broadcastsActivity.get(el));
      var $title = $this.find(".titre");
      var title = $title.text();
      $title.text("Annonce");
      $this.find(".vignette_deco2").prepend("
"+title+"
");
      $this.find(".vignette_deco2 .auteur").text("Annonce d'administration")
  }

  function onClickActivity(e){
    if($(e.target).is("a") || $(e.target).is("a *"))
      return;
    var link = $(this).find("strong a").attr('href');
    if(link)
     window.location = link;
  }

  function onClickExpandActivity(e){
    e.preventDefault();
    activityList.toggleClass("fullList");
    setActivities();
  }

  //INIT

  $(".layout__slot:nth-child(1)").attr("id","calendar-list");
  $(".layout__slot:nth-child(2)").attr("id","app-list");
  $(".layout__slot:nth-child(3)").attr("id","activity-list");
  $(".layout__slot:nth-child(4)").attr("id","tweets-list");
  $(".layout__slot:nth-child(5)").attr("id","campus-post-list");
  $(".layout__slot:nth-child(6)").attr("id","school-post-list");

  var appList = $("#app-list")
  appList.prependTo(appList.parent())
  appList.removeClass();

  var tweetsList = $("#tweets-list")
  tweetsList.appendTo(tweetsList.parent())
  tweetsList.removeClass();

  var activityList = $("#activity-list");
  var broadcastsActivity = activityList.find(".notification li .vignette_deco .icon-chat").parent().parent();
  broadcastsActivity.each(initOnEachActivityBroadcast);

  var activities = activityList.find(".notification li");
  activities.on("click",onClickActivity)
  activities.each(onEachActivity)

  var oldActivityBox = activityList.find(".card__lien");
  oldActivityBox.attr("id","activity-list-full-btn");
  activityList.find(".carte-activite").append("
Tout afficher
");

  $("#activity-list-expand-btn").on("click",onClickExpandActivity)

  setActivities();

})(jQuery);
<commit_msg>Update page-manipulation.js<commit_after>(function($){

  //Utils functions
  function setActivities(){
    var activities = activityList.find(".notification li");
    activities.removeClass("chidden");
    if(!activityList.hasClass("fullList")){
      for(var i = 7; i<activities.length; i++){
        $(activities.get(i)).addClass("chidden");
      }
      $("#activity-list-full-btn").addClass("chidden");
      $("#activity-list-expand-btn a").text("Tout afficher");
    } else {
      $("#activity-list-full-btn").removeClass("chidden");
      $("#activity-list-expand-btn a").text("Cacher");
    }
  }

  String.prototype.hashCode = function() {
    var hash = 0, i, chr;
    if (this.length === 0) return hash;
    for (i = 0; i < this.length; i++) {
      chr   = this.charCodeAt(i);
      hash  = ((hash << 5) - hash) + chr;
      hash |= 0; // Convert to 32bit integer
    }
    return hash;
  };

  function getActivityHash(activity){
    var title = activity.find(".resume strong a").text();
    var author = activity.find(".auteur").text();
    var date = activity.find(".date").text();
    return (title+author+date).hashCode().toString().replace(/-/g,"k");
  }

  //Events and iterators functions

  function onEachActivity(){
    var $this = $(this);
    var hash = getActivityHash($this);
    $this.attr("id","activity-"+hash);
    $this.attr("data-hash",hash);
    $this.prepend('')
  }

  function initOnEachActivityBroadcast(el){
      var $this = $(broadcastsActivity.get(el));
      var $title = $this.find(".titre");
      var title = $title.text();
      $title.text("Annonce");
      $this.find(".vignette_deco2").prepend("
"+title+"
");
      $this.find(".vignette_deco2 .auteur").text("Annonce d'administration")
  }

  function onClickActivity(e){
    if($(e.target).is("a") || $(e.target).is("a *"))
      return;
    var link = $(this).find("strong a").attr('href');
    if(link)
     window.location = link;
  }

  function onClickPinActivity(e){
    e.preventDefault();
    var activity = $(this).parent();
    if(activity.hasClass("pinned")){
      activity.removeClass("pinned");
    } else {
      activity.addClass("pinned");
      activity.prependTo(activity.parent());
    }
  }

  function onClickExpandActivity(e){
    e.preventDefault();
    activityList.toggleClass("fullList");
    setActivities();
  }

  //INIT

  $(".layout__slot:nth-child(1)").attr("id","calendar-list");
  $(".layout__slot:nth-child(2)").attr("id","app-list");
  $(".layout__slot:nth-child(3)").attr("id","activity-list");
  $(".layout__slot:nth-child(4)").attr("id","tweets-list");
  $(".layout__slot:nth-child(5)").attr("id","campus-post-list");
  $(".layout__slot:nth-child(6)").attr("id","school-post-list");

  var appList = $("#app-list")
  appList.prependTo(appList.parent())
  appList.removeClass();

  var tweetsList = $("#tweets-list")
  tweetsList.appendTo(tweetsList.parent())
  tweetsList.removeClass();

  var activityList = $("#activity-list");
  var broadcastsActivity = activityList.find(".notification li .vignette_deco .icon-chat").parent().parent();
  broadcastsActivity.each(initOnEachActivityBroadcast);

  var activities = activityList.find(".notification li");
  activities.on("click",onClickActivity)
  activities.find(".activity-pin").on("click",onClickPinActivity)
  activities.each(onEachActivity)

  var oldActivityBox = activityList.find(".card__lien");
  oldActivityBox.attr("id","activity-list-full-btn");
  activityList.find(".carte-activite").append("
Tout afficher
");

  $("#activity-list-expand-btn").on("click",onClickExpandActivity)

  setActivities();

})(jQuery);
<|endoftext|>


<commit_before>var gulp = require('gulp');
var concat = require('gulp-concat');					//- 多个文件合并为一个
var tinypng = require('gulp-tinypng');					//- png图片压缩
var webp = require('gulp-webp');					//- 转webp图片
var autoprefixer = require('gulp-autoprefixer');			//- 补充浏览器前缀
var cleanCSS = require('gulp-clean-css');				//- 压缩CSS为一行
var px3rem = require('gulp-px3rem');					//- px转rem
var uncss = require('gulp-uncss');					//- 删除没用到的css
var img64 = require('gulp-imgbase64');					//- img转base64
var css64 = require('gulp-base64');					//- css文件转base64
var sass = require('gulp-sass');					//- scss文件编译
var fontSpider = require('gulp-font-spider');				//- 删除没用到的字体
var replace = require('gulp-replace');					//- 文本替换
var processhtml = require('gulp-processhtml');				//- html更改模板
var htmlmin = require('gulp-htmlmin');					//- html压缩
var browserSync = require('browser-sync');				//- 浏览器同步测试工具
var del = require('del');						//- 管理文件

var y_Sz="src";								//- 生产环境路径
var y_Dz="dist";							//- 上线环境路径

gulp.task('allcss',function(){						//- 创建一个名为 concat 的 task
	var date=new Date().getTime();					//- 创建版本时间
	gulp.src(['./'+y_Sz+'/css/**/*.css'])				//- 需要处理的css文件，放到一个字符串数组里
	.pipe(replace(/_VERSION_/gi,date))				//- 文件指纹
	.pipe(autoprefixer({
	browsers: [
	'last 2 version',						//- 主流浏览器的最新两个版本
	'ios 7',							//- IOS7版本
	'android 2.3',							//- android 2.3版本
	'Firefox >= 20',						//- 火狐浏览器的版本大于或等于20
	'last 2 Explorer versions'],					//- IE的最新两个版本
	cascade: true,							//- 是否美化属性值 默认：true 像这样：-webkit-transform: rotate(45deg); transform: rotate(45deg);
	remove:true							//- 是否去掉不必要的前缀 默认：true
	}))
	.pipe(css64({
     extensions: ['gif','png','jpg','webp'],
     maxImageSize: 10*1024, // bytes
     debug: true
     }))
	.pipe(uncss({
	html: ['./'+y_Sz+'/**/*.html'],					//- 检查的页面
	ignore: ['abc','.abc','#abc']					//- 忽略的标签 class or id or 分号隔开
	}))
	.pipe(px3rem({remUnit: 100}))					//- px/100转rem值，如果有不想转换的类在值后面加/*no*/
	.pipe(cleanCSS({compatibility: 'ie8', keepBreaks:false, keepSpecialComments: '*'}))	//- 压缩处理成一行,兼容ie
	.pipe(concat('index.css'))					//- 合并后的文件名
	.pipe(gulp.dest('./'+y_Dz+'/css'));				//- 输出文件本地
});

gulp.task('vhtml',function(){					//- 修改html的dom
	var date = new Date().getTime();
	gulp.src('./'+y_Sz+'/**/*.html')
	.pipe(replace(/_VERSION_/gi, date))
	.pipe(processhtml())
	.pipe(gulp.dest('./'+y_Dz+'/'));
});

gulp.task('imgmin',function(){
	return gulp.src('./'+y_Sz+'/img/**/*.{png,jpg,gif,ico}')
	.pipe(tinypng('i4PmfZF5yvFHbhn_S6vI1D6WcY5OM07o'))		//- 去官网注册一下,填写TinyPN API KEY 免费版一个月有500张压缩
	.pipe(gulp.dest('./'+y_Dz+'/img'));				//- 输出路径
});

gulp.task('img64',['imgmin'],function() {
	gulp.src('./'+y_Dz+'/**/*.html')
    .pipe(img64({limit: '10kb'}))
    .on("error", function(error) {
            console.error(error.toString());
            this.emit("end");
    })
    .pipe(gulp.dest('./'+y_Dz+'/'));
});

gulp.task('fontSpider',function(){
	return gulp.src(['./'+y_Sz+'/**/*.html'])			//- 删除多余的字体和图标，添加return返回最终的数据流
	.pipe(fontSpider());
});

gulp.task('copy',['fontSpider'],function(){				//- 先把fs命令执行完后，再去执行cp命令，fs需要添加return
	gulp.src(['./'+y_Sz+'/font/**'],{				//- 被复制的文件夹下的所有文件
	base: './'+y_Sz+'/font'})					//- 被复制的目标路径
	.pipe(gulp.dest('./'+y_Dz+'/font'))				//- 输出路径
	gulp.src(['./'+y_Sz+'/icon/**'],{
	base: './'+y_Sz+'/icon'})
	.pipe(gulp.dest('./'+y_Dz+'/icon'));
});

/*-------------sass,webp,htmlmin,bs这些命令需要时手动添加执行-----------------*/

gulp.task('sass', function () {
	return gulp.src('./'+y_Sz+'/sass/**/*.scss')
	.pipe(sass().on('error', sass.logError))
	.pipe(gulp.dest('./'+y_Sz+'/sass/css/'));
});

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

gulp.task('webp',['webp_img'],function(){
	del(['./'+y_Dz+'/img/**/*.{png,jpg,gif,ico}', '!./'+y_Dz+'/img/**/*.{webp}']).then(paths => {
	console.log('Deleted files and folders:\n', paths.join('\n'));
	});
});

gulp.task('webp_img',['webp_css'],function(){
	return gulp.src('./'+y_Dz+'/img/**/*.{png,jpg,gif,ico}')
	.pipe(webp())
	.pipe(gulp.dest('./'+y_Dz+'/img/'))
});

gulp.task('webp_css',['webp_html'],function(){
	return gulp.src(['./'+y_Dz+'/css/**/*.css'])
	.pipe(replace(/.(jpg|png|gif)/gi,'.webp'))
	.pipe(gulp.dest('./'+y_Dz+'/css'));
});

gulp.task('webp_html',function(){
	return gulp.src('./'+y_Dz+'/**/*.html')
	.pipe(replace(/.(jpg|png|gif)/gi,'.webp'))
	.pipe(processhtml())
	.pipe(gulp.dest('./'+y_Dz+'/'));
});

gulp.task('htmlmin',function(){
	var options = {
	removeComments: true,						//- 清除HTML注释
	collapseWhitespace: true,					//- 压缩HTML
	minifyJS: true,							//- 压缩页面JS
	minifyCSS: true							//- 压缩页面CSS
	};
	gulp.src('./'+y_Dz+'/**/*.html')				//- 压缩页面路径
	.pipe(htmlmin(options))
	.pipe(gulp.dest('./'+y_Dz+'/'));				//- 输出路径
});

gulp.task('bs',function(){
	browserSync({
	files: "**",							//- 监控所有文件
	server: {baseDir: './'+y_Sz+'/'}				//- 目标文件夹路径
	});
});

//执行插件函数
gulp.task('default',['allcss','vhtml','img64','copy']);<commit_msg>base64<commit_after>var gulp = require('gulp');
var concat = require('gulp-concat');					//- 多个文件合并为一个
var tinypng = require('gulp-tinypng');					//- png图片压缩
var webp = require('gulp-webp');					//- 转webp图片
var autoprefixer = require('gulp-autoprefixer');			//- 补充浏览器前缀
var cleanCSS = require('gulp-clean-css');				//- 压缩CSS为一行
var px3rem = require('gulp-px3rem');					//- px转rem
var uncss = require('gulp-uncss');					//- 删除没用到的css
var img64 = require('gulp-imgbase64');					//- img转base64
var css64 = require('gulp-base64');					//- css文件转base64
var sass = require('gulp-sass');					//- scss文件编译
var fontSpider = require('gulp-font-spider');				//- 删除没用到的字体
var replace = require('gulp-replace');					//- 文本替换
var processhtml = require('gulp-processhtml');				//- html更改模板
var htmlmin = require('gulp-htmlmin');					//- html压缩
var browserSync = require('browser-sync');				//- 浏览器同步测试工具
var del = require('del');						//- 管理文件

var y_Sz="src";								//- 生产环境路径
var y_Dz="dist";							//- 上线环境路径

gulp.task('allcss',function(){						//- 创建一个名为 concat 的 task
	var date=new Date().getTime();					//- 创建版本时间
	gulp.src(['./'+y_Sz+'/css/**/*.css'])				//- 需要处理的css文件，放到一个字符串数组里
	.pipe(replace(/_VERSION_/gi,date))				//- 文件指纹
	.pipe(autoprefixer({
	browsers: [
	'last 2 version',						//- 主流浏览器的最新两个版本
	'ios 7',							//- IOS7版本
	'android 2.3',							//- android 2.3版本
	'Firefox >= 20',						//- 火狐浏览器的版本大于或等于20
	'last 2 Explorer versions'],					//- IE的最新两个版本
	cascade: true,							//- 是否美化属性值 默认：true 像这样：-webkit-transform: rotate(45deg); transform: rotate(45deg);
	remove:true							//- 是否去掉不必要的前缀 默认：true
	}))
	.pipe(css64({
	extensions: ['gif','png','jpg','webp'],
	maxImageSize: 10*1024, // bytes
	debug: true
	}))
	.pipe(uncss({
	html: ['./'+y_Sz+'/**/*.html'],					//- 检查的页面
	ignore: ['abc','.abc','#abc']					//- 忽略的标签 class or id or 分号隔开
	}))
	.pipe(px3rem({remUnit: 100}))					//- px/100转rem值，如果有不想转换的类在值后面加/*no*/
	.pipe(cleanCSS({compatibility: 'ie8', keepBreaks:false, keepSpecialComments: '*'}))	//- 压缩处理成一行,兼容ie
	.pipe(concat('index.css'))					//- 合并后的文件名
	.pipe(gulp.dest('./'+y_Dz+'/css'));				//- 输出文件本地
});

gulp.task('vhtml',function(){					//- 修改html的dom
	var date = new Date().getTime();
	gulp.src('./'+y_Sz+'/**/*.html')
	.pipe(replace(/_VERSION_/gi, date))
	.pipe(processhtml())
	.pipe(gulp.dest('./'+y_Dz+'/'));
});

gulp.task('imgmin',function(){
	gulp.src('./'+y_Sz+'/img/**/*.{png,jpg,gif,ico}')
	.pipe(tinypng('i4PmfZF5yvFHbhn_S6vI1D6WcY5OM07o'))		//- 去官网注册一下,填写TinyPN API KEY 免费版一个月有500张压缩
	.pipe(gulp.dest('./'+y_Dz+'/img'));				//- 输出路径
});

gulp.task('fontSpider',function(){
	return gulp.src(['./'+y_Sz+'/**/*.html'])			//- 删除多余的字体和图标，添加return返回最终的数据流
	.pipe(fontSpider());
});

gulp.task('copy',['fontSpider'],function(){				//- 先把fs命令执行完后，再去执行cp命令，fs需要添加return
	gulp.src(['./'+y_Sz+'/font/**'],{				//- 被复制的文件夹下的所有文件
	base: './'+y_Sz+'/font'})					//- 被复制的目标路径
	.pipe(gulp.dest('./'+y_Dz+'/font'))				//- 输出路径
	gulp.src(['./'+y_Sz+'/icon/**'],{
	base: './'+y_Sz+'/icon'})
	.pipe(gulp.dest('./'+y_Dz+'/icon'));
});

/*-------------sass,webp,htmlmin,bs这些命令需要时手动添加执行-----------------*/

gulp.task('sass', function () {
	return gulp.src('./'+y_Sz+'/sass/**/*.scss')
	.pipe(sass().on('error', sass.logError))
	.pipe(gulp.dest('./'+y_Sz+'/sass/css/'));
});

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

gulp.task('webp',['webp_img'],function(){
	del(['./'+y_Dz+'/img/**/*.{png,jpg,gif,ico}', '!./'+y_Dz+'/img/**/*.{webp}']).then(paths => {
	console.log('Deleted files and folders:\n', paths.join('\n'));
	});
});

gulp.task('webp_img',['webp_css'],function(){
	return gulp.src('./'+y_Dz+'/img/**/*.{png,jpg,gif,ico}')
	.pipe(webp())
	.pipe(gulp.dest('./'+y_Dz+'/img/'))
});

gulp.task('webp_css',['webp_html'],function(){
	return gulp.src(['./'+y_Dz+'/css/**/*.css'])
	.pipe(replace(/.(jpg|png|gif)/gi,'.webp'))
	.pipe(gulp.dest('./'+y_Dz+'/css'));
});

gulp.task('webp_html',function(){
	return gulp.src('./'+y_Dz+'/**/*.html')
	.pipe(replace(/.(jpg|png|gif)/gi,'.webp'))
	.pipe(processhtml())
	.pipe(gulp.dest('./'+y_Dz+'/'));
});

gulp.task('css64',function(){
	return gulp.src(['./'+y_Dz+'/css/**/*.css'])
	.pipe(css64({
	extensions: ['gif','png','jpg','webp'],
	maxImageSize: 10*1024, // bytes
	debug: true
	}))
	.pipe(concat('index.css'))
	.pipe(gulp.dest('./'+y_Dz+'/css'));
});

gulp.task('base64',['css64'],function() {
	gulp.src('./'+y_Dz+'/**/*.html')
   	.pipe(img64({limit: '10kb'}))
   	.on("error", function(error) {
         console.error(error.toString());
         this.emit("end");
  	 })
   	 .pipe(gulp.dest('./'+y_Dz+'/'));
});

gulp.task('htmlmin',function(){
	var options = {
	removeComments: true,						//- 清除HTML注释
	collapseWhitespace: true,					//- 压缩HTML
	minifyJS: true,							//- 压缩页面JS
	minifyCSS: true							//- 压缩页面CSS
	};
	gulp.src('./'+y_Dz+'/**/*.html')				//- 压缩页面路径
	.pipe(htmlmin(options))
	.pipe(gulp.dest('./'+y_Dz+'/'));				//- 输出路径
});

gulp.task('bs',function(){
	browserSync({
	files: "**",							//- 监控所有文件
	server: {baseDir: './'+y_Sz+'/'}				//- 目标文件夹路径
	});
});

//执行插件函数
gulp.task('default',['allcss','imgmin','vhtml','copy']);<|endoftext|>


<commit_before>// Third party
import template from 'lodash-es/template';

// Components
import { query } from '../../utils';
import { layoutEn, layoutZh } from '../../components/layout';

// Assets
import jsData from '../../assets/datas/js-bar-chart.json';

// About
import about from './about.html';
import tplOptsEn from './langs/en.json';
import tplOptsZh from './langs/zh.json';

const commom = () => {
  new Chart(query('#js-bar-chart'), {
    type: 'bar',
    data: jsData
  });

  new Chart(query('#skill-radar-chart'), {
    type: 'radar',
    data: {
      "labels": ["HTML", "CSS", "JS", "Angular", "Express", "Ionic", "Pug", "Stylus", "TypeScript"],
      "datasets": [
        {
          "label": "Skills",
          "backgroundColor": "rgba(179, 181, 198, .2)",
          "borderColor": "rgba(179, 181, 198, 1)",
          "pointBackgroundColor": "rgba(179, 181, 198, 1)",
          "pointBorderColor": "rgba(255, 255, 255, 1)",
          "pointHoverBackgroundColor": "rgba(255, 255, 255, 1)",
          "pointHoverBorderColor": "rgba(179, 181, 198, 1)",
          "data": [90, 50, 75, 80, 50, 33, 85, 75, 80]
        }
      ]
    }
  });
  componentHandler.upgradeAllRegistered();
};

export const loadAbout = () => {
  query('#app').innerHTML = layoutEn;
  query('#page').innerHTML = template(about)(tplOptsEn);
  query('#zh').onclick = () => { page.redirect('/zh/about'); };
  commom();
};

export const loadAboutZh = () => {
  query('#app').innerHTML = layoutZh;
  query('#page').innerHTML = template(about)(tplOptsZh);
  query('#en').onclick = () => { page.redirect('/en/about'); };
  commom();
};
<commit_msg>200th Commit<commit_after>// Third party
import template from 'lodash-es/template';

// Components
import { query } from '../../utils';
import { layoutEn, layoutZh } from '../../components/layout';

// Assets
import jsData from '../../assets/datas/js-bar-chart.json';

// About
import about from './about.html';
import tplOptsEn from './langs/en.json';
import tplOptsZh from './langs/zh.json';

const commom = () => {
  new Chart(query('#js-bar-chart'), {
    type: 'bar',
    data: jsData,
    options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } }
  });

  new Chart(query('#skill-radar-chart'), {
    type: 'radar',
    data: {
      "labels": ["HTML", "CSS", "JS", "Angular", "Express", "Ionic", "Pug", "Stylus", "TypeScript"],
      "datasets": [
        {
          "label": "Skills",
          "backgroundColor": "rgba(179, 181, 198, .2)",
          "borderColor": "rgba(179, 181, 198, 1)",
          "pointBackgroundColor": "rgba(179, 181, 198, 1)",
          "pointBorderColor": "rgba(255, 255, 255, 1)",
          "pointHoverBackgroundColor": "rgba(255, 255, 255, 1)",
          "pointHoverBorderColor": "rgba(179, 181, 198, 1)",
          "data": [90, 50, 75, 80, 50, 33, 85, 75, 80]
        }
      ]
    }
  });
  componentHandler.upgradeAllRegistered();
};

export const loadAbout = () => {
  query('#app').innerHTML = layoutEn;
  query('#page').innerHTML = template(about)(tplOptsEn);
  query('#zh').onclick = () => { page.redirect('/zh/about'); };
  commom();
};

export const loadAboutZh = () => {
  query('#app').innerHTML = layoutZh;
  query('#page').innerHTML = template(about)(tplOptsZh);
  query('#en').onclick = () => { page.redirect('/en/about'); };
  commom();
};
<|endoftext|>


<commit_before>// GULP DEPENDENCIES
// ----------------------------------------------------------------------------
var gulp         = require('gulp');
var sass         = require('gulp-ruby-sass');
var autoprefixer = require('gulp-autoprefixer');
var minifycss    = require('gulp-minify-css');
var jshint       = require('gulp-jshint');
var concat       = require('gulp-concat');
var uglify       = require('gulp-uglify');
var imageMin     = require('gulp-imagemin');
var notify       = require('gulp-notify');
var rename       = require('gulp-rename');
var cache        = require('gulp-cache');
var del          = require('del');

// GULP TASKS.
// ----------------------------------------------------------------------------
gulp.task('styles', function() {
    return sass('./resources/assets/scss/*.scss', { style: 'expanded' })
        .pipe(autoprefixer('last 2 version'))
        .pipe(gulp.dest('./public/css'))
        .pipe(rename({suffix: '.min'}))
        .pipe(minifycss())
        .pipe(gulp.dest('./public/css'))
        .pipe(notify({ message: 'Styles task complete' }));
});

// Clean the assets directories.
gulp.task('clean', function() {
    return del(['./public/styles']);
});

// Gulp default task.
// You can simply run it with `gulp`
gulp.task('default', ['clean'], function() {
    gulp.start('styles');
});

gulp.task('watch', function() {
    // Watch .scss files.
    gulp.watch('./resources/assets/scss/*.scss', ['styles']);
});

<commit_msg>add scss-lint function<commit_after>// GULP DEPENDENCIES
// ----------------------------------------------------------------------------
var gulp         = require('gulp');
var sass         = require('gulp-ruby-sass');
var autoprefixer = require('gulp-autoprefixer');
var minifycss    = require('gulp-minify-css');
var jshint       = require('gulp-jshint');
var concat       = require('gulp-concat');
var uglify       = require('gulp-uglify');
var imageMin     = require('gulp-imagemin');
var notify       = require('gulp-notify');
var rename       = require('gulp-rename');
var cache        = require('gulp-cache');
var del          = require('del');
var scsslint     = require('gulp-scss-lint');

// GULP TASKS.
// ----------------------------------------------------------------------------
gulp.task('styles', function() {
    return sass('./resources/assets/scss/*.scss', { style: 'expanded' })
        .pipe(autoprefixer('last 2 version'))
        .pipe(gulp.dest('./public/css'))
        .pipe(rename({suffix: '.min'}))
        .pipe(minifycss())
        .pipe(gulp.dest('./public/css'))
        .pipe(notify({ message: 'Styles task complete' }));
});

// Lint the scss resources,
// This function is depended on.
// the scss_lint gem.
// You can install it with the following command:
//
// gem install scss_lint
gulp.task('scss-lint', function() {
    return gulp.src('./resources/assets/scss/*.scss')
        .pipe(scsslint());
});

// Clean the assets directories.
gulp.task('clean', function() {
    return del(['./public/styles']);
});

// Gulp default task.
// You can simply run it with `gulp`
gulp.task('default', ['clean'], function() {
    gulp.start('styles');
});

gulp.task('watch', function() {
    // Watch .scss files.
    gulp.watch('./resources/assets/scss/*.scss', ['styles']);
});

<|endoftext|>


<commit_before>var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var browserify = require('browserify');
var watchify = require('watchify');
var babel = require('babelify');
var jade = require('gulp-jade');
var connect = require('gulp-connect');
var uglify = require('gulp-uglify');
var envify = require('envify/custom');
var file = require('gulp-file');

var buildDir = 'build';
var devBuildDir = 'dev_build';

function handleError(err) {
  console.error(err); // eslint-disable-line no-console
  this.emit('end');
}

function templates(outDir) {
  return function() {
    return gulp.src('public/*.jade')
      .pipe(jade())
      .pipe(gulp.dest(outDir));
  };
}

function styles(outDir) {
  return function() {
    return gulp.src('public/*.css')
      .pipe(gulp.dest(outDir))
      .pipe(connect.reload());
  };
}

function vendor(outDir) {
  return function() {
    return gulp.src('public/vendor/**')
      .pipe(gulp.dest(outDir + '/vendor'));
  };
}

function icons(outDir) {
  return function() {
    return gulp.src('public/icons/**')
      .pipe(gulp.dest(outDir + '/icons'));
  };
}

gulp.task('templates', templates(devBuildDir));
gulp.task('styles', styles(devBuildDir));
gulp.task('vendor', vendor(devBuildDir));
gulp.task('icons', icons(devBuildDir));

function compile(opts) {
  var bundler = watchify(
    browserify('./public/main.js', { debug: true })
      .transform(babel)
      .transform(envify({
        NODE_ENV: 'development'
      }), {global: true})
  );

  function rebundle() {
    return bundler.bundle()
      .on('error', handleError)
      .pipe(source('main.js'))
      .pipe(buffer())
      .pipe(sourcemaps.init({ loadMaps: true }))
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest(devBuildDir))
      .pipe(connect.reload());
  }

  if (opts.watch) {
    bundler.on('update', function() {
      console.log('-> bundling...'); // eslint-disable-line no-console
      return rebundle();
    });
  }

  return rebundle();
}

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

gulp.task('watch', function() {
  gulp.watch('public/*.css', ['styles']);
  return compile({watch: true});
});

gulp.task('build', function() {
  templates(buildDir)();
  vendor(buildDir)();
  icons(buildDir)();
  file('CNAME', 'circuits.im', { src: true })
    .pipe(gulp.dest(buildDir));
  return browserify('./public/main.js')
    .transform(envify({
      NODE_ENV: 'production'
    }), {global: true})
    .transform(babel.configure({
      optional: [
        'optimisation.react.constantElements',
        'optimisation.react.inlineElements'
      ]
    }))
    .bundle().on('error', handleError)
    .pipe(source('main.js'))
    .pipe(buffer())
    .pipe(uglify())
    .pipe(gulp.dest(buildDir));
});

gulp.task('default', ['templates', 'vendor', 'styles', 'icons', 'connect', 'watch']);
<commit_msg>Fix build to include css<commit_after>var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var browserify = require('browserify');
var watchify = require('watchify');
var babel = require('babelify');
var jade = require('gulp-jade');
var connect = require('gulp-connect');
var uglify = require('gulp-uglify');
var envify = require('envify/custom');
var file = require('gulp-file');

var buildDir = 'build';
var devBuildDir = 'dev_build';

function handleError(err) {
  console.error(err); // eslint-disable-line no-console
  this.emit('end');
}

function templates(outDir) {
  return function() {
    return gulp.src('public/*.jade')
      .pipe(jade())
      .pipe(gulp.dest(outDir));
  };
}

function styles(outDir) {
  return function() {
    return gulp.src('public/*.css')
      .pipe(gulp.dest(outDir))
      .pipe(connect.reload());
  };
}

function vendor(outDir) {
  return function() {
    return gulp.src('public/vendor/**')
      .pipe(gulp.dest(outDir + '/vendor'));
  };
}

function icons(outDir) {
  return function() {
    return gulp.src('public/icons/**')
      .pipe(gulp.dest(outDir + '/icons'));
  };
}

gulp.task('templates', templates(devBuildDir));
gulp.task('styles', styles(devBuildDir));
gulp.task('vendor', vendor(devBuildDir));
gulp.task('icons', icons(devBuildDir));

function compile(opts) {
  var bundler = watchify(
    browserify('./public/main.js', { debug: true })
      .transform(babel)
      .transform(envify({
        NODE_ENV: 'development'
      }), {global: true})
  );

  function rebundle() {
    return bundler.bundle()
      .on('error', handleError)
      .pipe(source('main.js'))
      .pipe(buffer())
      .pipe(sourcemaps.init({ loadMaps: true }))
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest(devBuildDir))
      .pipe(connect.reload());
  }

  if (opts.watch) {
    bundler.on('update', function() {
      console.log('-> bundling...'); // eslint-disable-line no-console
      return rebundle();
    });
  }

  return rebundle();
}

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

gulp.task('watch', function() {
  gulp.watch('public/*.css', ['styles']);
  return compile({watch: true});
});

gulp.task('build', function() {
  templates(buildDir)();
  styles(buildDir)();
  vendor(buildDir)();
  icons(buildDir)();
  file('CNAME', 'circuits.im', { src: true })
    .pipe(gulp.dest(buildDir));
  return browserify('./public/main.js')
    .transform(envify({
      NODE_ENV: 'production'
    }), {global: true})
    .transform(babel.configure({
      optional: [
        'optimisation.react.constantElements',
        'optimisation.react.inlineElements'
      ]
    }))
    .bundle().on('error', handleError)
    .pipe(source('main.js'))
    .pipe(buffer())
    .pipe(uglify())
    .pipe(gulp.dest(buildDir));
});

gulp.task('default', ['templates', 'vendor', 'styles', 'icons', 'connect', 'watch']);
<|endoftext|>


<commit_before>import React, { Component, Fragment } from 'react'
import Helmet from 'react-helmet'
import { api } from 'data.json'
import {
  ThemeProvider,
  Box,
  Button,
  Card,
  Container,
  Flex,
  Heading,
  LargeButton,
  Link as DSLink,
  Text,
  cx
} from '@hackclub/design-system'
import ApplyNav from 'components/apply/ApplyNav'
import LeaderInviteForm from 'components/apply/LeaderInviteForm'
import Login from 'components/apply/Login'
import SubmitButton from 'components/apply/SubmitButton'
import LoadingAnimation from 'components/LoadingAnimation'
import fetch from 'unfetch'
import Link from 'gatsby-link'

LargeButton.link = LargeButton.withComponent(Link)

const A = DSLink.extend`
  :hover {
    text-decoration: underline;
  }
`

const timeSince = time => {
  const seconds = Math.floor((new Date() - new Date(time)) / 1000)
  const intervals = [
    [Math.floor(seconds / (60 * 60 * 24 * 7)), 'weeks'],
    [Math.floor(seconds / (60 * 60 * 24)), 'days'],
    [Math.floor(seconds / (60 * 60)), 'hours'],
    [Math.floor(seconds / 60), 'minutes']
  ]
  for (var i = 0; i < intervals.length; i++) {
    let interval = intervals[i]
    if (interval[0] > 1) {
      return interval.join(' ')
    }
  }
  return 'less than a minute'
}

const Neg = () => <Text.span color="error" bold children="NOT" />

const ApplicationCard = props => {
  const {
    id,
    leader_profiles,
    updated_at,
    created_at,
    submitted_at
  } = props.app
  const { authToken, callback, app } = props

  const leaderProfile = leader_profiles.find(
    profile => profile.user.id == props.userId
  )
  const coLeaderProfiles = leader_profiles.filter(
    profile => profile.user.id != props.userId
  )

  return (
    <Container maxWidth={36} my={3} p={3}>
      <Card boxShadowSize="md" p={[3, 4]} color="black" bg="snow">
        <Heading.h3>How to get into Hack Club</Heading.h3>
        <Text>
          When reviewing applications, we look for a strong leadership team that
          has obtained a teacher sponsor to host their club and the support of
          their school administration. Teams should have 2 to 3 co-leads -- we
          rarely accept solo leaders.
        </Text>

        <Text>Invite your co-leads:</Text>
        <LeaderInviteForm id={id} authToken={authToken} callback={callback} />
        <Text>After you submit your application:</Text>

We’ll get back to you with our decision in 3 days

            If you’re accepted, we’ll schedule a call to train you to lead your
            club

            We’ll give you access to our curriculum, a template for your
            meetings, and our online community of club leaders

            Once you start holding meetings, we’ll check in with you each week
            to make sure everything is going well

          Contact us at team@hackclub.com{' '}
          if you have any questions while applying.

            This application was{' '}
            {submitted_at !== null
              ? 'submitted'
              : updated_at === created_at ? 'created' : 'updated'}{' '}
            {timeSince(updated_at)} ago

            You have {leaderProfile.completed_at ? null : <Neg />} finished your
            leader profile

          {coLeaderProfiles.map((profile, index) => (

              {profile.user.email}
              {profile.completed_at ? null : (

                  has <Neg />{' '}

              )}
              finished their leader profile

          ))}

        <Text color="slate" f={1}>

            * We also accept applications from clubs that have already held
            meetings.

        </Text>
      </Card>
      <Flex
        align="center"
        justify="center"
        flexDirection={['column', 'row']}
        mt={4}
        mx={[null, -2]}
      >
        <LargeButton.link
          w={1}
          m={2}
          inverted
          to={`/apply/club?id=${id}`}
          children="Edit Application"
        />
        <LargeButton.link
          w={1}
          m={2}
          inverted
          to={`/apply/leader?id=${leaderProfile.id}`}
          children="Edit Leader Profile"
        />
      </Flex>
      <Flex mt={2} mb={4}>
        <SubmitButton authToken={authToken} application={app} />
      </Flex>
    </Container>
  )
}

export default class extends Component {
  constructor(props) {
    super(props)

    this.state = {
      status: 'loading',
      app: undefined,
      authToken: undefined,
      userId: undefined
    }

    this.populateApplications = this.populateApplications.bind(this)
  }

  populateApplications(
    authToken = this.state.authToken,
    userId = this.state.userId
  ) {
    fetch(`${api}/v1/users/${userId}/new_club_applications`, {
      headers: { Authorization: `Bearer ${authToken}` }
    })
      .then(res => {
        if (res.ok) {
          return res.json()
        } else {
          throw res
        }
      })
      .then(json => {
        if (json.length === 0) {
          return fetch(`${api}/v1/users/${userId}/new_club_applications`, {
            method: 'POST',
            headers: { Authorization: `Bearer ${authToken}` }
          }).then(res => {
            if (res.ok) {
              return res.json()
            } else {
              throw res
            }
          })
        }
        return json.sort((a, b) => {
          return new Date(b.created_at) - new Date(a.created_at)
        })[0]
      })
      .then(app => {
        this.setState({
          status: 'finished',
          app: app
        })
      })
      .catch(e => {
        console.error(e)
        if (e.status === 401) {
          this.setState({ status: 'needsToAuth' })
        }
      })
  }

  componentDidMount() {
    const authToken = window.localStorage.getItem('authToken')
    const userId = window.localStorage.getItem('userId')
    this.setState({ authToken, userId })
    const needsToAuth = authToken === null || userId === null

    if (needsToAuth) {
      this.setState({ status: 'needsToAuth' })
    } else {
      this.populateApplications(authToken, userId)
    }
  }

  content() {
    const { app, status, authToken, userId } = this.state

    switch (status) {
      case 'needsToAuth':
        return <Login />
      case 'loading':
        return <LoadingAnimation />
      case 'finished':
        return (
          <Fragment>
            <ApplyNav breadcrumb={0} />
            <Heading.h1
              bg="primary"
              color="white"
              f={[5, 6]}
              mt={-1}
              py={4}
              px={3}
              align="center"
            >
              Apply to Hack Club
            </Heading.h1>
            <ApplicationCard
              app={app}
              userId={userId}
              authToken={authToken}
              callback={this.populateApplications}
            />
          </Fragment>
        )
      default:
        return <Text>Something terrible has happened.</Text>
    }
  }

  render() {
    return (
      <ThemeProvider>
        <Helmet title="Apply – Hack Club" />
        {this.content()}
      </ThemeProvider>
    )
  }
}
<commit_msg>Replace dashes with emdash<commit_after>import React, { Component, Fragment } from 'react'
import Helmet from 'react-helmet'
import { api } from 'data.json'
import {
  ThemeProvider,
  Box,
  Button,
  Card,
  Container,
  Flex,
  Heading,
  LargeButton,
  Link as DSLink,
  Text,
  cx
} from '@hackclub/design-system'
import ApplyNav from 'components/apply/ApplyNav'
import LeaderInviteForm from 'components/apply/LeaderInviteForm'
import Login from 'components/apply/Login'
import SubmitButton from 'components/apply/SubmitButton'
import LoadingAnimation from 'components/LoadingAnimation'
import fetch from 'unfetch'
import Link from 'gatsby-link'

LargeButton.link = LargeButton.withComponent(Link)

const A = DSLink.extend`
  :hover {
    text-decoration: underline;
  }
`

const timeSince = time => {
  const seconds = Math.floor((new Date() - new Date(time)) / 1000)
  const intervals = [
    [Math.floor(seconds / (60 * 60 * 24 * 7)), 'weeks'],
    [Math.floor(seconds / (60 * 60 * 24)), 'days'],
    [Math.floor(seconds / (60 * 60)), 'hours'],
    [Math.floor(seconds / 60), 'minutes']
  ]
  for (var i = 0; i < intervals.length; i++) {
    let interval = intervals[i]
    if (interval[0] > 1) {
      return interval.join(' ')
    }
  }
  return 'less than a minute'
}

const Neg = () => <Text.span color="error" bold children="NOT" />

const ApplicationCard = props => {
  const {
    id,
    leader_profiles,
    updated_at,
    created_at,
    submitted_at
  } = props.app
  const { authToken, callback, app } = props

  const leaderProfile = leader_profiles.find(
    profile => profile.user.id == props.userId
  )
  const coLeaderProfiles = leader_profiles.filter(
    profile => profile.user.id != props.userId
  )

  return (
    <Container maxWidth={36} my={3} p={3}>
      <Card boxShadowSize="md" p={[3, 4]} color="black" bg="snow">
        <Heading.h3>How to get into Hack Club</Heading.h3>
        <Text>
          When reviewing applications, we look for a strong leadership team that
          has obtained a teacher sponsor to host their club and the support of
          their school administration. Teams should have 2 to 3 co-leads — we
          rarely accept solo leaders.
        </Text>

        <Text>Invite your co-leads:</Text>
        <LeaderInviteForm id={id} authToken={authToken} callback={callback} />
        <Text>After you submit your application:</Text>

We’ll get back to you with our decision in 3 days

            If you’re accepted, we’ll schedule a call to train you to lead your
            club

            We’ll give you access to our curriculum, a template for your
            meetings, and our online community of club leaders

            Once you start holding meetings, we’ll check in with you each week
            to make sure everything is going well

          Contact us at team@hackclub.com{' '}
          if you have any questions while applying.

            This application was{' '}
            {submitted_at !== null
              ? 'submitted'
              : updated_at === created_at ? 'created' : 'updated'}{' '}
            {timeSince(updated_at)} ago

            You have {leaderProfile.completed_at ? null : <Neg />} finished your
            leader profile

          {coLeaderProfiles.map((profile, index) => (

              {profile.user.email}
              {profile.completed_at ? null : (

                  has <Neg />{' '}

              )}
              finished their leader profile

          ))}

        <Text color="slate" f={1}>

            * We also accept applications from clubs that have already held
            meetings.

        </Text>
      </Card>
      <Flex
        align="center"
        justify="center"
        flexDirection={['column', 'row']}
        mt={4}
        mx={[null, -2]}
      >
        <LargeButton.link
          w={1}
          m={2}
          inverted
          to={`/apply/club?id=${id}`}
          children="Edit Application"
        />
        <LargeButton.link
          w={1}
          m={2}
          inverted
          to={`/apply/leader?id=${leaderProfile.id}`}
          children="Edit Leader Profile"
        />
      </Flex>
      <Flex mt={2} mb={4}>
        <SubmitButton authToken={authToken} application={app} />
      </Flex>
    </Container>
  )
}

export default class extends Component {
  constructor(props) {
    super(props)

    this.state = {
      status: 'loading',
      app: undefined,
      authToken: undefined,
      userId: undefined
    }

    this.populateApplications = this.populateApplications.bind(this)
  }

  populateApplications(
    authToken = this.state.authToken,
    userId = this.state.userId
  ) {
    fetch(`${api}/v1/users/${userId}/new_club_applications`, {
      headers: { Authorization: `Bearer ${authToken}` }
    })
      .then(res => {
        if (res.ok) {
          return res.json()
        } else {
          throw res
        }
      })
      .then(json => {
        if (json.length === 0) {
          return fetch(`${api}/v1/users/${userId}/new_club_applications`, {
            method: 'POST',
            headers: { Authorization: `Bearer ${authToken}` }
          }).then(res => {
            if (res.ok) {
              return res.json()
            } else {
              throw res
            }
          })
        }
        return json.sort((a, b) => {
          return new Date(b.created_at) - new Date(a.created_at)
        })[0]
      })
      .then(app => {
        this.setState({
          status: 'finished',
          app: app
        })
      })
      .catch(e => {
        console.error(e)
        if (e.status === 401) {
          this.setState({ status: 'needsToAuth' })
        }
      })
  }

  componentDidMount() {
    const authToken = window.localStorage.getItem('authToken')
    const userId = window.localStorage.getItem('userId')
    this.setState({ authToken, userId })
    const needsToAuth = authToken === null || userId === null

    if (needsToAuth) {
      this.setState({ status: 'needsToAuth' })
    } else {
      this.populateApplications(authToken, userId)
    }
  }

  content() {
    const { app, status, authToken, userId } = this.state

    switch (status) {
      case 'needsToAuth':
        return <Login />
      case 'loading':
        return <LoadingAnimation />
      case 'finished':
        return (
          <Fragment>
            <ApplyNav breadcrumb={0} />
            <Heading.h1
              bg="primary"
              color="white"
              f={[5, 6]}
              mt={-1}
              py={4}
              px={3}
              align="center"
            >
              Apply to Hack Club
            </Heading.h1>
            <ApplicationCard
              app={app}
              userId={userId}
              authToken={authToken}
              callback={this.populateApplications}
            />
          </Fragment>
        )
      default:
        return <Text>Something terrible has happened.</Text>
    }
  }

  render() {
    return (
      <ThemeProvider>
        <Helmet title="Apply – Hack Club" />
        {this.content()}
      </ThemeProvider>
    )
  }
}
<|endoftext|>


<commit_before>var gulp = require('gulp');
var concat = require('gulp-concat');					//- 多个文件合并为一个
var replace = require('gulp-replace');					//- 文本替换
var autoprefixer = require('gulp-autoprefixer');			//- 补充浏览器前缀
var cleanCSS = require('gulp-clean-css');				//- 压缩CSS为一行
var px3rem = require('gulp-px3rem');					//- px转rem
var uncss = require('gulp-uncss');					//- 删除没用到的css
var sass = require('gulp-sass');					//- scss文件编译
var css64 = require('gulp-base64');					//- css文件转base64
var img64 = require('gulp-imgbase64');					//- img转base64
var tinypng = require('gulp-tinypng');					//- png图片压缩
var webp = require('gulp-webp');					//- 转webp图片
var fontSpider = require('gulp-font-spider');				//- 删除没用到的字体
var processhtml = require('gulp-processhtml');				//- html更改模板
var htmlmin = require('gulp-htmlmin');					//- html压缩
var browserSync = require('browser-sync');				//- 浏览器同步测试工具
var del = require('del');						//- 管理文件
var path = require("path");

var y_Sz="src";								//- 源码环境路径
var y_Dz="dist";							//- 上线环境路径

gulp.task('sass', function () {
	return gulp.src('./'+y_Sz+'/sass/**/*.scss')
	.pipe(sass().on('error', sass.logError))
	.pipe(gulp.dest('./'+y_Sz+'/css/'));
});

gulp.task('cssDeal',['sass'],function(){
	var date=new Date().getTime();					//- 创建版本时间
	gulp.src(['./'+y_Sz+'/css/**/*.css'])				//- 需要处理的css文件，放到一个字符串数组里
	.pipe(replace(/_VERSION_/gi,date))				//- 文件指纹
	.pipe(uncss({
	html: ['./'+y_Sz+'/**/*.html'],					//- 检查的页面
	ignore: ['abc','.abc','#abc']					//- 忽略的标签 class or id or 分号隔开
	}))
	.pipe(px3rem({remUnit: 100}))					//- px/100转rem值，如果有不想转换的类在值后面加/*no*/
	.pipe(cleanCSS({						//- 压缩处理成一行,兼容ie
		compatibility: 'ie8',
		keepBreaks:false,
		keepSpecialComments: '*'
	}))
	.pipe(concat('index.css'))					//- 合并后的文件名
	.pipe(gulp.dest('./'+y_Dz+'/css'));				//- 输出文件本地
});

gulp.task('htmlDeal',function(){					//- 修改html的dom
	var date = new Date().getTime();
	gulp.src('./'+y_Sz+'/**/*.html')
	.pipe(replace(/_VERSION_/gi, date))
	.pipe(processhtml())
	.pipe(gulp.dest('./'+y_Dz+'/'));
});

gulp.task('imgDeal',function(){
	gulp.src('./'+y_Sz+'/img/**/*.{png,jpg,gif,ico}')
	.pipe(tinypng('i4PmfZF5yvFHbhn_S6vI1D6WcY5OM07o'))		//- 去官网注册一下,填写TinyPN API KEY 免费版一个月有500张压缩
	.pipe(gulp.dest('./'+y_Dz+'/img'));				//- 输出路径
});

/*-------------(htmlmin,font,cssper,webp,base64,bsWatch)需要时手动添加执行或修改-----------------*/

gulp.task('htmlmin',function(){
	var options = {
	removeComments: true,						//- 清除HTML注释
	collapseWhitespace: true,					//- 压缩HTML
	minifyJS: true,							//- 压缩页面JS
	minifyCSS: true							//- 压缩页面CSS
	};
	gulp.src('./'+y_Dz+'/**/*.html')				//- 压缩页面路径
	.pipe(htmlmin(options))
	.pipe(gulp.dest('./'+y_Dz+'/'));				//- 输出路径
});

gulp.task('fontSpider',function(){
	return gulp.src(path.resolve(process.cwd(), y_Sz) + '/*.html')			//- 删除多余的字体和图标，添加return返回最终的数据流
	.pipe(fontSpider());
});

gulp.task('font',['fontSpider'],function(){				//- 先把fs命令执行完后，再去执行cp命令，fs需要添加return
	gulp.src(['./'+y_Sz+'/font/**'],{				//- 被复制的文件夹下的所有文件
	base: './'+y_Sz+'/font'})					//- 被复制的目标路径
	.pipe(gulp.dest('./'+y_Dz+'/font'))				//- 输出路径
	gulp.src(['./'+y_Sz+'/icon/**'],{
	base: './'+y_Sz+'/icon'})
	.pipe(gulp.dest('./'+y_Dz+'/icon'));
});

gulp.task('cssper',function(){
	gulp.src(['./'+y_Dz+'/css/**/*.css'])
	.pipe(autoprefixer({
	browsers: [
	'last 2 version',						//- 主流浏览器的最新两个版本
	'ios 7',							//- IOS7版本
	'android 2.3',							//- android 2.3版本
	'Firefox >= 20',						//- 火狐浏览器的版本大于或等于20
	'last 2 Explorer versions'],					//- IE的最新两个版本 'last 2 Explorer versions'
	cascade: true,							//- 是否美化属性值 默认：true 像这样：-webkit-transform: rotate(45deg); transform: rotate(45deg);
	remove:true							//- 是否去掉不必要的前缀 默认：true
	}))
	.pipe(concat('index.css'))					//- 合并后的文件名
	.pipe(gulp.dest('./'+y_Dz+'/css'));				//- 输出文件本地
});

gulp.task('base64',['css64'],function() {				//- 插件不支持wepb转换，需要手动修改node_modules/gulp-imgbase64/index.js，把jpeg替换为webp,把大写CONERT-HTML-IMG-BASE64改成小写conert-html-img-base64，为了兼容htmlmin
	gulp.src('./'+y_Dz+'/**/*.html')
   	.pipe(img64({limit: '8kb'}))
   	.pipe(gulp.dest('./'+y_Dz+'/'));
});

gulp.task('css64',['webp'],function(){
	return gulp.src(['./'+y_Dz+'/css/**/*.css'])
	.pipe(css64({
	extensions: ['gif','png','jpg','webp'],
	maxImageSize: 8*1024 // bytes
	}))
	.pipe(concat('index.css'))
	.pipe(gulp.dest('./'+y_Dz+'/css'));
});

gulp.task('webp',['webp_css'],function(){
	return del(['./'+y_Dz+'/img/**/*.{png,jpg}', '!./'+y_Dz+'/img/**/*.{webp}'])
});

gulp.task('webp_css',['webp_html'],function(){
	return gulp.src(['./'+y_Dz+'/css/**/*.css'])
	.pipe(replace(/.(jpg|png|gif)/gi,'.webp'))
	.pipe(gulp.dest('./'+y_Dz+'/css'));
});

gulp.task('webp_html',['webp_img'],function(){
	return gulp.src('./'+y_Dz+'/**/*.html')
	.pipe(replace(/.(jpg|png|gif)/gi,'.webp'))
	.pipe(processhtml())
	.pipe(gulp.dest('./'+y_Dz+'/'));
});

gulp.task('webp_img',function(){
	return gulp.src('./'+y_Dz+'/img/**/*.{png,jpg}')
	.pipe(webp())
	.pipe(gulp.dest('./'+y_Dz+'/img/'))
});

gulp.task('bs',function(){
	browserSync({
	files: "**",							//- 监控所有文件
	server: {baseDir: './'+y_Dz+'/'}				//- 目标文件夹路径
	});
});

//default
gulp.task('default',['cssDeal','imgDeal','htmlDeal']);

//min
gulp.task('min',['htmlmin','font','cssper','webp','base64']);<commit_msg>gulpfile<commit_after>var gulp = require('gulp');
var concat = require('gulp-concat');					//- 多个文件合并为一个
var replace = require('gulp-replace');					//- 文本替换
var autoprefixer = require('gulp-autoprefixer');			//- 补充浏览器前缀
var cleanCSS = require('gulp-clean-css');				//- 压缩CSS为一行
var px3rem = require('gulp-px3rem');					//- px转rem
var uncss = require('gulp-uncss');					//- 删除没用到的css
var sass = require('gulp-sass');					//- scss文件编译
var css64 = require('gulp-base64');					//- css文件转base64
var img64 = require('gulp-imgbase64');					//- img转base64
var tinypng = require('gulp-tinypng');					//- png图片压缩
var webp = require('gulp-webp');					//- 转webp图片
var fontSpider = require('gulp-font-spider');				//- 删除没用到的字体
var processhtml = require('gulp-processhtml');				//- html更改模板
var htmlmin = require('gulp-htmlmin');					//- html压缩
var browserSync = require('browser-sync');				//- 浏览器同步测试工具
var del = require('del');						//- 管理文件
var path = require("path");

var y_Sz="src";								//- 源码环境路径
var y_Dz="dist";							//- 上线环境路径

gulp.task('sass', function () {
	return gulp.src('./'+y_Sz+'/sass/**/*.scss')
	.pipe(sass().on('error', sass.logError))
	.pipe(gulp.dest('./'+y_Sz+'/css/'));
});

gulp.task('cssDeal',['sass'],function(){
	var date=new Date().getTime();					//- 创建版本时间
	gulp.src(['./'+y_Sz+'/css/**/*.css'])				//- 需要处理的css文件，放到一个字符串数组里
	.pipe(replace(/_VERSION_/gi,date))				//- 文件指纹
	.pipe(uncss({
	html: ['./'+y_Sz+'/**/*.html'],					//- 检查的页面
	ignore: ['abc','.abc','#abc']					//- 忽略的标签 class or id or 分号隔开
	}))
	.pipe(px3rem({remUnit: 100}))					//- px/100转rem值，如果有不想转换的类在值后面加/*no*/
	.pipe(cleanCSS({						//- 压缩处理成一行,兼容ie
		compatibility: 'ie8',
		keepBreaks:false,
		keepSpecialComments: '*'
	}))
	.pipe(concat('index.css'))					//- 合并后的文件名
	.pipe(gulp.dest('./'+y_Dz+'/css'));				//- 输出文件本地
});

gulp.task('htmlDeal',function(){					//- 修改html的dom
	var date = new Date().getTime();
	gulp.src('./'+y_Sz+'/**/*.html')
	.pipe(replace(/_VERSION_/gi, date))
	.pipe(processhtml())
	.pipe(gulp.dest('./'+y_Dz+'/'));
});

gulp.task('imgDeal',function(){
	gulp.src('./'+y_Sz+'/img/**/*.{png,jpg,gif,ico}')
	.pipe(tinypng('i4PmfZF5yvFHbhn_S6vI1D6WcY5OM07o'))		//- 去官网注册一下,填写TinyPN API KEY 免费版一个月有500张压缩
	.pipe(gulp.dest('./'+y_Dz+'/img'));				//- 输出路径
});

/*-------------(htmlmin,font,cssper,webp,base64,bs)需要时手动添加执行或修改-----------------*/

gulp.task('htmlmin',function(){
	var options = {
	removeComments: true,						//- 清除HTML注释
	collapseWhitespace: true,					//- 压缩HTML
	minifyJS: true,							//- 压缩页面JS
	minifyCSS: true							//- 压缩页面CSS
	};
	gulp.src('./'+y_Dz+'/**/*.html')				//- 压缩页面路径
	.pipe(htmlmin(options))
	.pipe(gulp.dest('./'+y_Dz+'/'));				//- 输出路径
});

gulp.task('fontSpider',function(){
	return gulp.src(path.resolve(process.cwd(), y_Sz) + '/*.html')	//- 删除多余的字体和图标，添加return返回最终的数据流
	.pipe(fontSpider());
});

gulp.task('font',['fontSpider'],function(){				//- 先把fs命令执行完后，再去执行cp命令，fs需要添加return
	gulp.src(['./'+y_Sz+'/font/**'],{				//- 被复制的文件夹下的所有文件
	base: './'+y_Sz+'/font'})					//- 被复制的目标路径
	.pipe(gulp.dest('./'+y_Dz+'/font'))				//- 输出路径
	gulp.src(['./'+y_Sz+'/icon/**'],{
	base: './'+y_Sz+'/icon'})
	.pipe(gulp.dest('./'+y_Dz+'/icon'));
});

gulp.task('cssper',function(){
	gulp.src(['./'+y_Dz+'/css/**/*.css'])
	.pipe(autoprefixer({
	browsers: [
	'last 2 version',						//- 主流浏览器的最新两个版本
	'ios 7',							//- IOS7版本
	'android 2.3',							//- android 2.3版本
	'Firefox >= 20',						//- 火狐浏览器的版本大于或等于20
	'last 2 Explorer versions'],					//- IE的最新两个版本 'last 2 Explorer versions'
	cascade: true,							//- 是否美化属性值 默认：true 像这样：-webkit-transform: rotate(45deg); transform: rotate(45deg);
	remove:true							//- 是否去掉不必要的前缀 默认：true
	}))
	.pipe(concat('index.css'))					//- 合并后的文件名
	.pipe(gulp.dest('./'+y_Dz+'/css'));				//- 输出文件本地
});

gulp.task('base64',['css64'],function() {				//- 插件不支持wepb转换，需要手动修改node_modules/gulp-imgbase64/index.js，把jpeg替换为webp,把大写CONERT-HTML-IMG-BASE64改成小写conert-html-img-base64，为了兼容htmlmin
	gulp.src('./'+y_Dz+'/**/*.html')
   	.pipe(img64({limit: '8kb'}))
   	.pipe(gulp.dest('./'+y_Dz+'/'));
});

gulp.task('css64',['webp'],function(){
	return gulp.src(['./'+y_Dz+'/css/**/*.css'])
	.pipe(css64({
	extensions: ['jpg','png','gif','webp'],
	maxImageSize: 8*1024 // bytes
	}))
	.pipe(concat('index.css'))
	.pipe(gulp.dest('./'+y_Dz+'/css'));
});

gulp.task('webp',['webp_css'],function(){
	return del(['./'+y_Dz+'/img/**/*.{jpg,png,gif}', '!./'+y_Dz+'/img/**/*.{webp}'])
});

gulp.task('webp_css',['webp_html'],function(){
	return gulp.src(['./'+y_Dz+'/css/**/*.css'])
	.pipe(replace(/.(jpg|png|gif)/gi,'.webp'))
	.pipe(gulp.dest('./'+y_Dz+'/css'));
});

gulp.task('webp_html',['webp_img'],function(){
	return gulp.src('./'+y_Dz+'/**/*.html')
	.pipe(replace(/.(jpg|png|gif)/gi,'.webp'))
	.pipe(processhtml())
	.pipe(gulp.dest('./'+y_Dz+'/'));
});

gulp.task('webp_img',function(){
	return gulp.src('./'+y_Dz+'/img/**/*.{jpg,png,gif}')
	.pipe(webp())
	.pipe(gulp.dest('./'+y_Dz+'/img/'))
});

gulp.task('bs',function(){
	browserSync({
	files: "**",							//- 监控所有文件
	server: {baseDir: './'+y_Dz+'/'}				//- 目标文件夹路径
	});
});

//default
gulp.task('default',['cssDeal','imgDeal','htmlDeal']);

//min
gulp.task('min',['htmlmin','font','cssper','webp','base64']);<|endoftext|>


<commit_before>var browserSync = require('browser-sync'),
    compass = require('gulp-compass'),
    concat = require('gulp-concat'),
    csso = require('gulp-csso'),
    del = require('del'),
    gulp = require('gulp'),
    gutil = require('gulp-util'),
    imagemin = require('gulp-imagemin'),
    plumber = require('gulp-plumber'),
    reload = browserSync.reload,
    runSequence = require('run-sequence'),
    size = require('gulp-size'),
    uglify = require('gulp-uglify'),
    watch = require('gulp-watch');

var src = 'src',
    dist = 'dist',
    dirs = {
        js: src + '/assets/js',
        css: src + '/assets/css',
        img: src + '/assets/img',
        sass: src + '/assets/sass',
        vend: src + '/assets/vendor'
    },
    build = {
        js: dist + '/assets/js',
        css: dist + '/assets/css',
        img: dist + '/assets/img',
        sass: dist + '/assets/sass',
        vend: dist + '/assets/vendor'
    };

// 'full' or 'assets'
var distMode = 'assets',
    minCss = false,
    minJs = false;

// browser-sync task for starting the server.
gulp.task('browser-sync', function() {
    browserSync({
        server: {
            baseDir: src
        },
        port: 9000
    });
});

// Reload all Browsers
gulp.task('browser-reload', function() {
    browserSync.reload();
});

gulp.task('build', function(cb) {
    runSequence(
        'cleanByDistMode', ['compass', 'concat'],
        'copyByDistMode', ['clean:sprite', 'uglify'],
        'imagemin',
        'clean:release',
        'copy:vendors',
        cb
    );
});

gulp.task('clean:release', function(cb) {
    return del([
        build.sass,
        build.js + '/**/*',
        '!' + build.js + '/scripts.js',
        build.vend
    ], {
        force: true
    }, cb);
});

gulp.task('clean:sprite', function(cb) {
    return del([
        build.img + '/sprite/hd',
        build.img + '/sprite/standard'
    ], {
        force: true
    }, cb);
});

gulp.task('cleanByDistMode', function(cb) {
    switch (distMode) {
        case 'assets':
            return del(dist + '/assets', {
                force: true
            }, cb);
            break;
        default:
            return del(dist, {
                force: true
            }, cb);
    }
});

gulp.task('compass', function() {
    var config = {
        css: dirs.css,
        sass: dirs.sass,
        image: dirs.img,
        javascript: dirs.js
    };

    if (minCss) {
        return gulp.src([
                dirs.sass + '/main.scss',
                //dirs.sass + '/main-ie.scss',
            ])
            .pipe(plumber({
                errorHandler: function(error) {
                    console.log(error.message);
                    this.emit('end');
                }
            }))
            .pipe(compass(config))
            .on('error', gutil.log)
            .pipe(csso())
            .pipe(gulp.dest(dirs.css))
            .pipe(reload({
                stream: true
            }));
    } else {
        return gulp.src([
                dirs.sass + '/main.scss',
                //dirs.sass + '/main-ie.scss',
            ])
            .pipe(plumber({
                errorHandler: function(error) {
                    console.log(error.message);
                    this.emit('end');
                }
            }))
            .pipe(compass(config))
            .on('error', gutil.log)
            .pipe(gulp.dest(dirs.css))
            .pipe(reload({
                stream: true
            }));
    }
});

gulp.task('concat', function() {
    return gulp.src([
            // Plugins
            dirs.js + '/plugins.js',
            // Vendors
            dirs.vend + '/bootstrap-sass-official/assets/javascripts/bootstrap.js',
            // Main
            dirs.js + '/main.js',
            // Modules
            dirs.js + '/modules/**/*.js'
        ])
        .pipe(plumber())
        .pipe(concat('scripts.js'))
        .pipe(gulp.dest(dirs.js))
        .pipe(reload({
            stream: true
        }));
});

gulp.task('copyByDistMode', function() {
    switch (distMode) {
        case 'assets':
            return gulp.src([
                    src + '/assets/**/*'
                ])
                .pipe(gulp.dest(dist + '/assets'));
            break;
        default:
            return gulp.src([
                    src + '/**/*'
                ])
                .pipe(gulp.dest(dist));
    }
});

gulp.task('copy:vendors', function() {
    return gulp.src([
            dirs.vend + '/**/*jquery.min.js',
            dirs.vend + '/**/*jquery.mask.min.js',
            dirs.vend + '/**/*retina.min.js'
        ])
        .pipe(gulp.dest(build.vend));
});

gulp.task('default', ['browser-sync'], function() {
    gulp.watch(dirs.sass + '/**/*.scss', ['compass']);
    gulp.watch([
        dirs.js + '/plugins.js',
        dirs.js + '/main.js',
        dirs.js + '/modules/**/*.js'
    ], ['concat']);
    gulp.watch(src + '/**/*.html', ['browser-reload']);
});

gulp.task('imagemin', function() {
    return gulp.src(build.img + '/**/*.{svg,png,jpg,jpeg,gif}')
        .pipe(imagemin({
            progressive: true,
            interlaced: true
        }))
        .pipe(gulp.dest(build.img))
        .pipe(size({
            title: 'imagemin',
            showFiles: true
        }));
});

gulp.task('uglify', function(cb) {
    if (minJs) {
        return gulp.src(dirs.js + '/scripts.js')
            .pipe(uglify().on('error', gutil.log))
            .pipe(gulp.dest(build.js));
    } else {
        return gulp.src(dirs.js + '/scripts.js')
            .pipe(gulp.dest(build.js));
    }
});
<commit_msg>Task styles com libsass<commit_after>var browserSync = require('browser-sync'),
    compass = require('gulp-compass'),
    concat = require('gulp-concat'),
    csso = require('gulp-csso'),
    del = require('del'),
    gulp = require('gulp'),
    gutil = require('gulp-util'),
    imagemin = require('gulp-imagemin'),
    plumber = require('gulp-plumber'),
    reload = browserSync.reload,
    runSequence = require('run-sequence'),
    size = require('gulp-size'),
    uglify = require('gulp-uglify'),
    watch = require('gulp-watch');

var src = 'src',
    dist = 'dist',
    dirs = {
        js: src + '/assets/js',
        css: src + '/assets/css',
        img: src + '/assets/img',
        sass: src + '/assets/sass',
        vend: src + '/assets/vendor'
    },
    build = {
        js: dist + '/assets/js',
        css: dist + '/assets/css',
        img: dist + '/assets/img',
        sass: dist + '/assets/sass',
        vend: dist + '/assets/vendor'
    };

// 'full' or 'assets'
var distMode = 'assets',
    minCss = false,
    minJs = false;

// browser-sync task for starting the server.
gulp.task('browser-sync', function() {
    browserSync({
        server: {
            baseDir: src
        },
        port: 9000
    });
});

// Reload all Browsers
gulp.task('browser-reload', function() {
    browserSync.reload();
});

gulp.task('build', function(cb) {
    runSequence(
        'cleanByDistMode', ['styles', 'concat'],
        'copyByDistMode', ['clean:sprite', 'uglify'],
        'imagemin',
        'clean:release',
        'copy:vendors',
        cb
    );
});

gulp.task('clean:release', function(cb) {
    return del([
        build.sass,
        build.js + '/**/*',
        '!' + build.js + '/scripts.js',
        build.vend
    ], {
        force: true
    }, cb);
});

gulp.task('clean:sprite', function(cb) {
    return del([
        build.img + '/sprite/hd',
        build.img + '/sprite/standard'
    ], {
        force: true
    }, cb);
});

gulp.task('cleanByDistMode', function(cb) {
    switch (distMode) {
        case 'assets':
            return del(dist + '/assets', {
                force: true
            }, cb);
            break;
        default:
            return del(dist, {
                force: true
            }, cb);
    }
});

gulp.task('styles', function() {
    return gulp.src(dirs.sass + '/main.scss')
        .pipe($.sourcemaps.init())
        .pipe($.sass({
            outputStyle: 'nested', // libsass doesn't support expanded yet
            precision: 10,
            includePaths: ['.'],
            onError: console.error.bind(console, 'Sass error:')
        }))
        .pipe($.postcss([
            require('autoprefixer-core')({
                browsers: ['last 1 version']
            })
        ]))
        .pipe($.sourcemaps.write())
        .pipe(csso())
        .pipe(gulp.dest(dirs.css))
        .pipe(reload({
            stream: true
        }));
});

gulp.task('compass', function() {
    var config = {
        css: dirs.css,
        sass: dirs.sass,
        image: dirs.img,
        javascript: dirs.js
    };

    if (minCss) {
        return gulp.src([
                dirs.sass + '/main.scss',
                //dirs.sass + '/main-ie.scss',
            ])
            .pipe(plumber({
                errorHandler: function(error) {
                    console.log(error.message);
                    this.emit('end');
                }
            }))
            .pipe(compass(config))
            .on('error', gutil.log)
            .pipe(csso())
            .pipe(gulp.dest(dirs.css))
            .pipe(reload({
                stream: true
            }));
    } else {
        return gulp.src([
                dirs.sass + '/main.scss',
                //dirs.sass + '/main-ie.scss',
            ])
            .pipe(plumber({
                errorHandler: function(error) {
                    console.log(error.message);
                    this.emit('end');
                }
            }))
            .pipe(compass(config))
            .on('error', gutil.log)
            .pipe(gulp.dest(dirs.css))
            .pipe(reload({
                stream: true
            }));
    }
});

gulp.task('concat', function() {
    return gulp.src([
            // Plugins
            dirs.js + '/plugins.js',
            // Vendors
            dirs.vend + '/bootstrap-sass-official/assets/javascripts/bootstrap.js',
            // Main
            dirs.js + '/main.js',
            // Modules
            dirs.js + '/modules/**/*.js'
        ])
        .pipe(plumber())
        .pipe(concat('scripts.js'))
        .pipe(gulp.dest(dirs.js))
        .pipe(reload({
            stream: true
        }));
});

gulp.task('copyByDistMode', function() {
    switch (distMode) {
        case 'assets':
            return gulp.src([
                    src + '/assets/**/*'
                ])
                .pipe(gulp.dest(dist + '/assets'));
            break;
        default:
            return gulp.src([
                    src + '/**/*'
                ])
                .pipe(gulp.dest(dist));
    }
});

gulp.task('copy:vendors', function() {
    return gulp.src([
            dirs.vend + '/**/*jquery.min.js',
            dirs.vend + '/**/*jquery.mask.min.js',
            dirs.vend + '/**/*retina.min.js'
        ])
        .pipe(gulp.dest(build.vend));
});

gulp.task('default', ['browser-sync'], function() {
    gulp.watch(dirs.sass + '/**/*.scss', ['styles']);
    gulp.watch([
        dirs.js + '/plugins.js',
        dirs.js + '/main.js',
        dirs.js + '/modules/**/*.js'
    ], ['concat']);
    gulp.watch(src + '/**/*.html', ['browser-reload']);
});

gulp.task('imagemin', function() {
    return gulp.src(build.img + '/**/*.{svg,png,jpg,jpeg,gif}')
        .pipe(imagemin({
            progressive: true,
            interlaced: true
        }))
        .pipe(gulp.dest(build.img))
        .pipe(size({
            title: 'imagemin',
            showFiles: true
        }));
});

gulp.task('uglify', function(cb) {
    if (minJs) {
        return gulp.src(dirs.js + '/scripts.js')
            .pipe(uglify().on('error', gutil.log))
            .pipe(gulp.dest(build.js));
    } else {
        return gulp.src(dirs.js + '/scripts.js')
            .pipe(gulp.dest(build.js));
    }
});
<|endoftext|>


<commit_before>import { Collection } from 'backbone';
import Page from './Page';

export default Collection.extend({
  model: Page,

  initialize(models, config = {}) {
    this.config = config;
    this.on('reset', this.onReset);
    this.on('remove', this.onRemove);
  },

  onReset(m, opts = {}) {
    const prev = opts.previousModels || [];
    prev.map(p => this.onRemove(p));
  },

  onRemove(removed) {
    removed && removed.onRemove();
  },

  add(m, o = {}) {
    const { config } = this;
    return Collection.prototype.add.call(this, m, { ...o, config });
  }
});
<commit_msg>Add Pages class<commit_after>import { Collection } from 'backbone';
import Page from './Page';

export default class Pages extends Collection {
  initialize(models, config = {}) {
    this.config = config;
    this.on('reset', this.onReset);
    this.on('remove', this.onRemove);
  }

  onReset(m, opts = {}) {
    const prev = opts.previousModels || [];
    prev.map(p => this.onRemove(p));
  }

  onRemove(removed) {
    removed && removed.onRemove();
  }

  add(m, o = {}) {
    const { config } = this;
    return Collection.prototype.add.call(this, m, { ...o, config });
  }
}

Pages.prototype.model = Page;
<|endoftext|>