<commit_before>// generated on 2015-01-26 using generator-4dev 0.1.0

var gulp = require('gulp');
var uglify = require('gulp-uglify');
var notify = require('gulp-notify');
var concat = require('gulp-concat');
var glob = require('glob');
var del = require('del');
var $ = require('gulp-load-plugins')();
var pagespeed = require('psi');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var gm = require('gulp-gm');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var watchify = require('watchify');
var browserify = require('browserify');
var uncss = require('gulp-uncss');

var site = 'http://www.andreaslorer.de';

// bundler
var bundler = watchify(browserify('./site/assets/js/Ajax.js', watchify.args));
// add any other browserify options or transforms here
// bundler.transform(brfs);

gulp.task('bundle', bundle); // so you can run `gulp js` to build the file
bundler.on('update', bundle); // on any dep update, runs the bundler

function bundle() {
  return bundler.bundle()
    // log errors if they happen
    .on('error', gutil.log.bind(gutil, 'Browserify Error'))
    .pipe(source('bundle.js'))
    // optional, remove if you dont want sourcemaps
      .pipe(buffer())
      .pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file
      .pipe(sourcemaps.write('./')) // writes .map file

    //
    .pipe(gulp.dest('./dist/assets/js/'));
}

// uncss
var gulp = require('gulp');
var uncss = require('gulp-uncss');

gulp.task('uncss', function() {
  return gulp.src('site/assets/**/*.css')
    .pipe(concat('main.css'))
    .pipe(uncss({
        html: ['site/index.html'],
        ignore: [
          ".fade",
          ".fade.in",
          ".collapse",
          ".collapse.in",
          ".collapsing",
          ".alert-danger",
          /\.open/
       ]
    }))
    .pipe($.csso())
    .pipe(gulp.dest('./out'));
});

// css styles
gulp.task('styles', function () {
  return gulp.src('site/assets/css/*.scss')
    .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(gulp.dest('dist/assets/css/'));
});

// Lint JavaScript
gulp.task('jshint', function () {
  return gulp.src('site/assets/js/scripts.js')
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.jshint.reporter('fail'))
    .pipe(reload({stream: true}));
});

// html
gulp.task('html', ['styles'], function () {
  var assets = $.useref.assets({searchPath: ['site/assets/**/*/', '.']});

  return gulp.src('site/index.html')
    .pipe(assets)
    .pipe($.if('*.js', $.uglify()))
    .pipe($.if('*.css', $.csso()))
    .pipe(assets.restore())
    .pipe($.useref())
    .pipe($.if('*.html', $.minifyHtml({conditionals: true, loose: true})))
    .pipe(gulp.dest('dist'));
});

// minify javascript
gulp.task('js', function () {
    gulp.src('site/assets/js/**/*.js')
      .pipe(concat('all.min.js'))
        .pipe(uglify())
        .pipe(gulp.dest('dist/assets/js/'))
        .pipe(notify({ message: 'Finished minifying JavaScript'}));
});

gulp.task('fonts', function () {
  return gulp.src(require('main-bower-files')().concat('site/assets/fonts/**/*'))
    .pipe($.filter('**/*.{eot,svg,ttf,woff}'))
    .pipe($.flatten())
    .pipe(gulp.dest('.tmp/fonts'))
    .pipe(gulp.dest('dist/fonts'));
});

// copy all files from /site/
gulp.task('copy', function () {
  return gulp.src([
    'site/**/*',
    '!site/assets/**/*.jpg',
    '!site/assets/js/*.js',
    '!site/assets/css/*.scss',
    '!site/index.html'
    ],{
     dot:true
    }).pipe(gulp.dest('dist'))
      .pipe($.size({title: 'copy'}));
});

// Watch Files For Changes & Reload
gulp.task('serve', function () {
  browserSync({
    proxy: "multicolumn.local/site/"
  });

  // watch for changes
  gulp.watch([
    'site/*.html',
    'site/assets/css/**/*.css',
    'site/assets/js/**/*.js',
    'site/php/*.php'
  ]).on('change', reload);

  gulp.watch('site/assets/css/**/*.scss', ['styles']);
  gulp.watch(['site/assets/images/**/*'], ['images']);
});

// resize images
 gulp.task('resize', function () {
  gulp.src('site/assets/images/**/*.jpg')

  .pipe(gm(function (gmfile) {
    return gmfile.resize(300, 198);
  }, {
    imageMagick: true
  }))

  .pipe(gulp.dest('dist/assets/'));
});

// Optimize Images
gulp.task('images', function () {
  return gulp.src('site/assets/**/*')
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true,
      optimizationLevel: 5
    })))
    .pipe(gulp.dest('dist/assets/'))
    .pipe(reload({stream: true, once: true}))
    .pipe($.size({title: 'images'}));
});

// watch task
gulp.task('watch', function () {
    gulp.watch('site/assets/js/**/*.js', ['js']);
});

// Clean Output Directory
gulp.task('clean', del.bind(null, ['dist']));

gulp.task('cleanApp', del.bind(null, ['app']));

// Build Production Files, the Default Task
gulp.task('default', ['clean'], function (cb) {
  runSequence('images', ['html', 'js', 'styles', 'copy'], 'cleanApp', cb);
});

gulp.task('mobile', function () {
    return pagespeed(site, {
        // key: key
        nokey: 'true',
        strategy: 'mobile',
    }, function (err, data) {
        console.log(data.score);
        console.log(data.pageStats);
    });
});

gulp.task('desktop', function () {
    return pagespeed(site, {
        // key: key
        nokey: 'true',
        strategy: 'desktop',
    }, function (err, data) {
        console.log(data.score);
        console.log(data.pageStats);
    });
});<commit_msg>fix: just all.js gets copyed to dist folder<commit_after>// generated on 2015-01-26 using generator-4dev 0.1.0

var gulp = require('gulp');
var uglify = require('gulp-uglify');
var notify = require('gulp-notify');
var concat = require('gulp-concat');
var glob = require('glob');
var del = require('del');
var $ = require('gulp-load-plugins')();
var pagespeed = require('psi');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var gm = require('gulp-gm');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var watchify = require('watchify');
var browserify = require('browserify');
var uncss = require('gulp-uncss');

var site = 'http://www.andreaslorer.de';

// bundler
var bundler = watchify(browserify('./site/assets/js/Ajax.js', watchify.args));
// add any other browserify options or transforms here
// bundler.transform(brfs);

gulp.task('bundle', bundle); // so you can run `gulp js` to build the file
bundler.on('update', bundle); // on any dep update, runs the bundler

function bundle() {
  return bundler.bundle()
    // log errors if they happen
    .on('error', gutil.log.bind(gutil, 'Browserify Error'))
    .pipe(source('bundle.js'))
    // optional, remove if you dont want sourcemaps
      .pipe(buffer())
      .pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file
      .pipe(sourcemaps.write('./')) // writes .map file

    //
    .pipe(gulp.dest('./dist/assets/js/'));
}

// uncss
var gulp = require('gulp');
var uncss = require('gulp-uncss');

gulp.task('uncss', function() {
  return gulp.src('site/assets/**/*.css')
    .pipe(concat('main.css'))
    .pipe(uncss({
        html: ['site/index.html'],
        ignore: [
          ".fade",
          ".fade.in",
          ".collapse",
          ".collapse.in",
          ".collapsing",
          ".alert-danger",
          /\.open/
       ]
    }))
    .pipe($.csso())
    .pipe(gulp.dest('./out'));
});

// css styles
gulp.task('styles', function () {
  return gulp.src('site/assets/css/*.scss')
    .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(gulp.dest('dist/assets/css/'));
});

// Lint JavaScript
gulp.task('jshint', function () {
  return gulp.src('site/assets/js/scripts.js')
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.jshint.reporter('fail'))
    .pipe(reload({stream: true}));
});

// html
gulp.task('html', ['styles'], function () {
  // var assets = $.useref.assets({searchPath: ['site/assets/**/*/', '.']});

  return gulp.src('site/index.html')
/*    .pipe(assets)
    .pipe($.if('*.js', $.uglify()))
    .pipe($.if('*.css', $.csso()))
    .pipe(assets.restore())
    .pipe($.useref())*/
    .pipe($.if('*.html', $.minifyHtml({conditionals: true, loose: true})))
    .pipe(gulp.dest('dist'));
});

// minify javascript
gulp.task('js', function () {
    gulp.src('site/assets/js/*.js')
      .pipe(concat('all.min.js'))
      .pipe(uglify())
      .pipe(gulp.dest('dist/assets/js/'))
      .pipe(notify({ message: 'Finished minifying JavaScript'}));
});

gulp.task('fonts', function () {
  return gulp.src(require('main-bower-files')().concat('site/assets/fonts/**/*'))
    .pipe($.filter('**/*.{eot,svg,ttf,woff}'))
    .pipe($.flatten())
    .pipe(gulp.dest('.tmp/fonts'))
    .pipe(gulp.dest('dist/fonts'));
});

// copy all files from /site/
gulp.task('copy', function () {
  return gulp.src([
    'site/**/*',
    '!site/assets/**/*.jpg',
    '!site/assets/js/*.js',
    '!site/assets/css/*.scss',
    '!site/index.html'
    ],{
     dot:true
    }).pipe(gulp.dest('dist'))
      .pipe($.size({title: 'copy'}));
});

// Watch Files For Changes & Reload
gulp.task('serve', function () {
  browserSync({
    proxy: "multicolumn.local/site/"
  });

  // watch for changes
  gulp.watch([
    'site/*.html',
    'site/assets/css/**/*.css',
    'site/assets/js/**/*.js',
    'site/php/*.php'
  ]).on('change', reload);

  gulp.watch('site/assets/css/**/*.scss', ['styles']);
  gulp.watch(['site/assets/images/**/*'], ['images']);
});

// resize images
 gulp.task('resize', function () {
  gulp.src('site/assets/images/**/*.jpg')

  .pipe(gm(function (gmfile) {
    return gmfile.resize(300, 198);
  }, {
    imageMagick: true
  }))

  .pipe(gulp.dest('dist/assets/'));
});

// Optimize Images
gulp.task('images', function () {
  return gulp.src('site/assets/**/*.+(jpg|png)')
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true,
      optimizationLevel: 5
    })))
    .pipe(gulp.dest('dist/assets/'))
    .pipe(reload({stream: true, once: true}))
    .pipe($.size({title: 'images'}));
});

// watch task
gulp.task('watch', function () {
    gulp.watch('site/assets/js/**/*.js', ['js']);
});

// Clean Output Directory
gulp.task('clean', del.bind(null, ['dist']));

gulp.task('cleanApp', del.bind(null, ['app']));

// Build Production Files, the Default Task
gulp.task('default', ['clean'], function (cb) {
  runSequence('images', ['html', 'js', 'styles', 'copy'], 'cleanApp', cb);
});

gulp.task('mobile', function () {
    return pagespeed(site, {
        // key: key
        nokey: 'true',
        strategy: 'mobile',
    }, function (err, data) {
        console.log(data.score);
        console.log(data.pageStats);
    });
});

gulp.task('desktop', function () {
    return pagespeed(site, {
        // key: key
        nokey: 'true',
        strategy: 'desktop',
    }, function (err, data) {
        console.log(data.score);
        console.log(data.pageStats);
    });
});<|endoftext|>


<commit_before>const gulp = require('gulp')
const $ = require('gulp-load-plugins')()
const autoprefixer = require('autoprefixer')
const atImport = require('postcss-import')
const browserSync = require('browser-sync').create()
const del = require('del')
const exec = require('child_process').exec
const path = require('path')

// Deletes folders containing compiled output.
gulp.task('clean', () => {
	return del(['.tmp', 'dist'])
})

// Builds all content
gulp.task('hugo', function (callback) {
	return exec('hugo', function (err, stdout, stderr) {
		console.log(stdout)
		console.log(stderr)
		callback(err)
	})
})

// Sass, sourcemaps, postcss-import and autoprefixer
gulp.task('styles', function () {
	return gulp.src(['app/styles/*.scss'])
		.pipe($.sourcemaps.init())
		.pipe($.sass.sync({
			precision: 10,
			includePaths: [
				'.',
				path.join(__dirname, '../node_modules')
			]
		}).on('error', $.sass.logError))
		.pipe($.postcss([
			atImport(),
			autoprefixer()
		]))
		.pipe($.sourcemaps.write())
		.pipe(gulp.dest('.tmp/styles'))
		.pipe(browserSync.stream())
})

// Scripts
gulp.task('scripts', function () {
	return gulp.src('app/scripts/**/*.js')
		.pipe($.sourcemaps.init())
		.pipe($.sourcemaps.write('.'))
		.pipe(gulp.dest('.tmp/scripts/'))
		.pipe(browserSync.stream({once: true}))
})

// Development server
gulp.task('serve', gulp.series('styles', 'scripts', 'hugo', function () {
	// watch for changes
	// gulp.watch([
	// 	// 'app/*.html',
	// 	'app/scripts/**/*.js',
	// 	'app/images/**/*',
	// 	'.tmp/fonts/**/*'
	// ]).on('change', browserSync.reload)

	// watch for changes and run tasks
	gulp.watch(['content/**/*.md', 'app/templates/**/*.html']).on('change',  gulp.series('hugo'))
	gulp.watch('app/styles/**/*', gulp.series('styles'))
	gulp.watch('app/scripts/**/*.js', gulp.series('scripts'))

	browserSync.init({
		notify: false,
		// 'dist' and 'static' are needed because hugo builds all content here
		server: {baseDir: ['.tmp', 'app', 'static', 'dist']}
	})
}))

/**
 * Starts a server from the `dist` folder, which is
 * useful for testing `gulp build`.
 */
gulp.task('serve:dist', () => {
	browserSync.init({
		notify: false,
		server: {
			baseDir: ['dist']
		}
	})
})

// Copies all assets after they are built
gulp.task('copy-from-tmp', function () {
	return gulp.src('.tmp/**/*')
		.pipe(gulp.dest('dist/'))
		.pipe($.size({title: 'build', gzip: true}))
})

gulp.task('minify-templates', () => {
	return gulp.src('dist/**/*.html', {base: 'dist'})
		.pipe($.htmlmin({collapseWhitespace: true}))
		.pipe(gulp.dest('dist'))
})

gulp.task('minify-styles', () => {
	return gulp.src('dist/styles/*.css', {base: 'dist'})
		// Don't remove vendor-prefixes.
		.pipe($.cssnano({autoprefixer: false}))
		.pipe(gulp.dest('dist'))
})

// First cleans, then starts the building sequence
gulp.task('build', gulp.series(
	'clean',
	gulp.parallel('hugo', 'styles', 'scripts'),
	'copy-from-tmp',
	gulp.parallel('minify-styles', 'minify-templates')
))

<commit_msg>Get rid of gulp:scripts task<commit_after>const gulp = require('gulp')
const $ = require('gulp-load-plugins')()
const autoprefixer = require('autoprefixer')
const atImport = require('postcss-import')
const browserSync = require('browser-sync').create()
const del = require('del')
const exec = require('child_process').exec
const path = require('path')

// Deletes folders containing compiled output.
gulp.task('clean', () => {
	return del(['.tmp', 'dist'])
})

// Builds all content
gulp.task('hugo', function (callback) {
	return exec('hugo', function (err, stdout, stderr) {
		console.log(stdout)
		console.log(stderr)
		callback(err)
	})
})

// Sass, sourcemaps, postcss-import and autoprefixer
gulp.task('styles', function () {
	return gulp.src(['app/styles/*.scss'])
		.pipe($.sourcemaps.init())
		.pipe($.sass.sync({
			precision: 10,
			includePaths: [
				'.',
				path.join(__dirname, '../node_modules')
			]
		}).on('error', $.sass.logError))
		.pipe($.postcss([
			atImport(),
			autoprefixer()
		]))
		.pipe($.sourcemaps.write())
		.pipe(gulp.dest('.tmp/styles'))
		.pipe(browserSync.stream())
})

// Development server
gulp.task('serve', gulp.series('styles', 'hugo', function () {
	// watch for changes and run tasks
	gulp.watch(['content/**/*.md', 'app/templates/**/*.html']).on('change',  gulp.series('hugo'))
	gulp.watch('app/styles/**/*', gulp.series('styles'))

	browserSync.init({
		notify: false,
		// 'dist' and 'static' are needed because hugo builds all content here
		server: {baseDir: ['.tmp', 'app', 'static', 'dist']}
	})
}))

/**
 * Starts a server from the `dist` folder, which is
 * useful for testing `gulp build`.
 */
gulp.task('serve:dist', () => {
	browserSync.init({
		notify: false,
		server: {
			baseDir: ['dist']
		}
	})
})

// Copies all assets after they are built
gulp.task('copy-from-tmp', function () {
	return gulp.src('.tmp/**/*')
		.pipe(gulp.dest('dist/'))
		.pipe($.size({title: 'build', gzip: true}))
})

gulp.task('minify-templates', () => {
	return gulp.src('dist/**/*.html', {base: 'dist'})
		.pipe($.htmlmin({collapseWhitespace: true}))
		.pipe(gulp.dest('dist'))
})

gulp.task('minify-styles', () => {
	return gulp.src('dist/styles/*.css', {base: 'dist'})
		// Don't remove vendor-prefixes.
		.pipe($.cssnano({autoprefixer: false}))
		.pipe(gulp.dest('dist'))
})

// First cleans, then starts the building sequence
gulp.task('build', gulp.series(
	'clean',
	gulp.parallel('hugo', 'styles'),
	'copy-from-tmp',
	gulp.parallel('minify-styles', 'minify-templates')
))

<|endoftext|>


<commit_before>import { format } from 'url'
import React from 'react'
import PropTypes from 'prop-types'
import { translate } from 'react-i18next'
import { withRouter } from 'next/router'

import Link from './link'

class Facet extends React.Component {
  static propTypes = {
    facet: PropTypes.shape({
      name: PropTypes.oneOf([
        'availability',
        'dgvPublication',
        'distributionFormat',
        'keyword',
        'metadataType',
        'opendata',
        'organization',
        'representationType',
        'type',
        'catalog'
      ]).isRequired,
      value: PropTypes.string.isRequired
    }).isRequired,

    defaultQuery: PropTypes.object,

    count: PropTypes.number,
    detailed: PropTypes.bool,
    removable: PropTypes.bool,

    router: PropTypes.shape({
      query: PropTypes.object.isRequired
    }).isRequired,

    i18n: PropTypes.shape({
      exists: PropTypes.func.isRequired
    }).isRequired,

    t: PropTypes.func.isRequired
  }

  static defaultProps = {
    detailed: false,
    removable: false
  }

  getAddQuery = facet => {
    const { router, defaultQuery } = this.props

    let query = {
      ...defaultQuery
    }

    if (router.pathname === '/search') {
      query = {
        ...query,
        ...router.query
      }

      delete query.p

      const match = query[facet.name]
      if (Array.isArray(match)) {
        query[facet.name] = [
          ...match,
          facet.value
        ]
      } else if (match) {
        query[facet.name] = [match, facet.value]
      } else {
        query[facet.name] = facet.value
      }
    } else {
      query[facet.name] = facet.value
    }

    return query
  }

  getRemoveQuery = facet => {
    const { router } = this.props

    const query = {
      ...router.query
    }

    delete query.p

    const match = query[facet.name]
    if (Array.isArray(match)) {
      query[facet.name] = match.filter(v => v !== facet.value)
    } else {
      delete query[facet.name]
    }

    return query
  }

  getLink = () => {
    const { removable, facet } = this.props

    const query = removable ? this.getRemoveQuery(facet) : this.getAddQuery(facet)

    return format({
      pathname: '/search',
      query
    })
  }

  render() {
    const { facet, count, detailed, removable, t, i18n } = this.props

    const title = t(`facets.types.${facet.name}`)
    const value = i18n.exists(`facets.values.${facet.value}`) ? t(`facets.values.${facet.value}`) : facet.value

    return (

        <Link href={this.getLink()}>
          <a className={`facet ${removable && 'removable'}`}>
            {detailed &&
{title}
}

{value}

        </Link>
        {count &&
× {count}
}

    )
  }
}

export default translate()(withRouter(Facet))
<commit_msg>Fix facets on IE11<commit_after>import { format } from 'url'
import React from 'react'
import PropTypes from 'prop-types'
import { translate } from 'react-i18next'
import { withRouter } from 'next/router'

import Link from './link'

class Facet extends React.Component {
  static propTypes = {
    facet: PropTypes.shape({
      name: PropTypes.oneOf([
        'availability',
        'dgvPublication',
        'distributionFormat',
        'keyword',
        'metadataType',
        'opendata',
        'organization',
        'representationType',
        'type',
        'catalog'
      ]).isRequired,
      value: PropTypes.string.isRequired
    }).isRequired,

    defaultQuery: PropTypes.object,

    count: PropTypes.number,
    detailed: PropTypes.bool,
    removable: PropTypes.bool,

    router: PropTypes.shape({
      query: PropTypes.object.isRequired
    }).isRequired,

    i18n: PropTypes.shape({
      exists: PropTypes.func.isRequired
    }).isRequired,

    t: PropTypes.func.isRequired
  }

  static defaultProps = {
    detailed: false,
    removable: false
  }

  getAddQuery = facet => {
    const { router, defaultQuery } = this.props

    let query = {
      ...defaultQuery
    }

    if (router.pathname === '/search') {
      query = {
        ...query,
        ...router.query
      }

      delete query.p

      const match = query[facet.name]
      if (Array.isArray(match)) {
        query[facet.name] = [
          ...match,
          facet.value
        ]
      } else if (match) {
        query[facet.name] = [match, facet.value]
      } else {
        query[facet.name] = facet.value
      }
    } else {
      query[facet.name] = facet.value
    }

    return query
  }

  getRemoveQuery = facet => {
    const { router } = this.props

    const query = {
      ...router.query
    }

    delete query.p

    const match = query[facet.name]
    if (Array.isArray(match)) {
      query[facet.name] = match.filter(v => v !== facet.value)
    } else {
      delete query[facet.name]
    }

    return query
  }

  getLink = () => {
    const { removable, facet } = this.props

    const query = removable ? this.getRemoveQuery(facet) : this.getAddQuery(facet)

    return format({
      pathname: '/search',
      query
    })
  }

  render() {
    const { facet, count, detailed, removable, t, i18n } = this.props

    const title = t(`facets.types.${facet.name}`)
    const value = i18n.exists(`facets.values.${facet.value}`) ? t(`facets.values.${facet.value}`) : facet.value

    return (

        <Link href={this.getLink()}>
          <a className={`facet ${removable && 'removable'}`}>
            {detailed &&
{title}
}

{value}

        </Link>
        {count &&
× {count}
}

    )
  }
}

export default translate()(withRouter(Facet))
<|endoftext|>


<commit_before>var gulp = require('gulp');
var gutil = require('gulp-util');
var bower = require('bower');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css');
var rename = require('gulp-rename');
var sh = require('shelljs');
var nodeCLI = require("shelljs-nodecli");
var webpack = require('gulp-webpack');
var config = require('./webpack.config.js');
var karma = require('karma').server;
var del = require('del');
var argv = require('yargs')
  .option('env', { alias: 'e', describe: 'debug or release' })
  .option('target', { alias: 't', describe: 'ios or android' }).argv;

var paths = {
  sass: ['./scss/**/*.scss'],
  typescript: ['./src/**/*.ts']
};

gulp.task('clean', function () {
  del(['www/js/*.js', 'www/css/*.css', 'plugins', 'platforms', 'node_modules'])
});

gulp.task('default', ['sass', 'webpack']);

gulp.task('webpack', function () {
  gulp.src(paths.typescript)
    .pipe(webpack(config))
    .pipe(gulp.dest('./'));
});

gulp.task('karma', function (done) {
  karma.start({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, function () {
    done();
  });
});

gulp.task('sass', function (done) {
  gulp.src('./scss/ionic.app.scss')
    .pipe(sass())
    .on('error', sass.logError)
    .pipe(gulp.dest('./www/css/'))
    .pipe(minifyCss({
      keepSpecialComments: 0
    }))
    .pipe(rename({ extname: '.min.css' }))
    .pipe(gulp.dest('./www/css/'))
    .on('end', done);
});

gulp.task('watch', function () {
  gulp.watch(paths.sass, ['sass']);
  gulp.watch(paths.typescript, ['webpack', 'karma']);
});

gulp.task('build', function () {
  var target = argv.target || "ios";
  var env = argv.env || "debug";
  nodeCLI.exec("ionic", "build", target);
});
gulp.task('run', function () {
  var target = argv.target || "ios";
  var env = argv.env || "debug";
  nodeCLI.exec("ionic", "run", target, " -l -c -s");
});

gulp.task('install', ['git-check'], function () {
  return bower.commands.install()
    .on('log', function (data) {
      gutil.log('bower', gutil.colors.cyan(data.id), data.message);
    });
});

gulp.task('git-check', function (done) {
  if (!sh.which('git')) {
    console.log(
      '  ' + gutil.colors.red('Git is not installed.'),
      '\n  Git, the version control system, is required to download Ionic.',
      '\n  Download git here:', gutil.colors.cyan('http://git-scm.com/downloads') + '.',
      '\n  Once git is installed, run \'' + gutil.colors.cyan('gulp install') + '\' again.'
    );
    process.exit(1);
  }
  done();
});
<commit_msg>Remove gulp run<commit_after>var gulp = require('gulp');
var gutil = require('gulp-util');
var bower = require('bower');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css');
var rename = require('gulp-rename');
var sh = require('shelljs');
var nodeCLI = require("shelljs-nodecli");
var webpack = require('gulp-webpack');
var config = require('./webpack.config.js');
var karma = require('karma').server;
var del = require('del');
var argv = require('yargs')
  .option('env', { alias: 'e', describe: 'debug or release' })
  .option('target', { alias: 't', describe: 'ios or android' }).argv;

var paths = {
  sass: ['./scss/**/*.scss'],
  typescript: ['./src/**/*.ts']
};

gulp.task('clean', function () {
  del(['www/js/*.js', 'www/css/*.css', 'plugins', 'platforms', 'node_modules'])
});

gulp.task('default', ['sass', 'webpack']);

gulp.task('webpack', function () {
  gulp.src(paths.typescript)
    .pipe(webpack(require('./webpack.config.js')))
    .pipe(gulp.dest('./'));
});

gulp.task('karma', function (done) {
  karma.start({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, function () {
    done();
  });
});

gulp.task('sass', function (done) {
  gulp.src('./scss/ionic.app.scss')
    .pipe(sass())
    .on('error', sass.logError)
    .pipe(gulp.dest('./www/css/'))
    .pipe(minifyCss({
      keepSpecialComments: 0
    }))
    .pipe(rename({ extname: '.min.css' }))
    .pipe(gulp.dest('./www/css/'))
    .on('end', done);
});

gulp.task('watch', function () {
  gulp.watch(paths.sass, ['sass']);
  gulp.watch(paths.typescript, ['webpack', 'karma']);
});

gulp.task('build', function () {
  var target = argv.target || "ios";
  var env = argv.env || "debug";
  nodeCLI.exec("ionic", "build", target);
});
gulp.task('install', ['git-check'], function () {
  return bower.commands.install()
    .on('log', function (data) {
      gutil.log('bower', gutil.colors.cyan(data.id), data.message);
    });
});

gulp.task('git-check', function (done) {
  if (!sh.which('git')) {
    console.log(
      '  ' + gutil.colors.red('Git is not installed.'),
      '\n  Git, the version control system, is required to download Ionic.',
      '\n  Download git here:', gutil.colors.cyan('http://git-scm.com/downloads') + '.',
      '\n  Once git is installed, run \'' + gutil.colors.cyan('gulp install') + '\' again.'
    );
    process.exit(1);
  }
  done();
});
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import {
  View,
  TouchableOpacity,
  LayoutAnimation,
  Platform,
  UIManager,
  StatusBar,
  StyleSheet,
  Image
} from 'react-native'
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'
import { getColor } from '../components/config'
import Background from '../components/background'
import InitialView from '../components/login_screen/initial_view'
import SignInForm from '../components/login_screen/signIn_form'
import SignUpForm from '../components/login_screen/signUp_form'
import ForgotPassForm from '../components/login_screen/forgotPassword_form'
import { firebaseApp } from '../firebase'
import { observer, inject } from 'mobx-react/native'
import { Actions } from 'react-native-mobx'

@inject("appStore") @observer
export default class LoginScreen extends Component {
  constructor(props) {
    super(props)
    this.state = {
      initialScreen: false,
      signIn: false,
      signUp: false,
      forgotPass: false
    }
    if (Platform.OS === 'android') {
      UIManager.setLayoutAnimationEnabledExperimental(true)
    }
    _unsubscribe = firebaseApp.auth().onAuthStateChanged((user) => {
      if (user) {
        console.log(" --- User Signed In ---> " + user.displayName)
        this.props.appStore.user = user
        this.props.appStore.username = user.displayName
        firebaseApp.database().ref('users').child(user.uid).once('value')
        .then((snapshot) => {
          this.props.appStore.post_count = parseInt(snapshot.val().post_count)
        })
        Actions.home({ type: 'replace' })
      }
      else {
        console.log(" --- User is Signed Off --- ")
        this.setState({ initialScreen: true })
      }
      _unsubscribe()
    })
  }

  componentWillUnmount() {
  }

  componentWillMount() {
  }

  componentDidMount() {
  }

  componentDidUpdate() {
    LayoutAnimation.configureNext(LayoutAnimation.Presets.spring)
  }

  render() {
    const initialView = this.state.initialScreen ?
      <InitialView
      onSignIn={this._onSignIn}
      onSignUp={this._onSignUp}
      animDelay={0}/>
    : null

    const signIn = this.state.signIn ?
      <SignInForm
      onBackFromSignIn={this._onBackFromSignIn}
      onForgotPass = {this._onForgotPass} />
    : null

    const signUp = this.state.signUp ?
      <SignUpForm
      onBackFromSignUp={this._onBackFromSignUp} />
    : null

    const fogotPass = this.state.forgotPass ?
      <ForgotPassForm
      onBackFromForgotPass={this._onBackFromForgotPass} />
    : null

    return (
      <View style={styles.container}>
      <Background imgSrouce={require('../assets/images/bk.png')}/>
      <KeyboardAwareScrollView contentContainerStyle={styles.scrollContainer} >
        <StatusBar
          backgroundColor={getColor('googleBlue700')}
          barStyle='light-content'
          animated={true}
        />
        <View style={styles.logoContainer}>
          <TouchableOpacity onPress={this._onLogoClicked}>
            <Image source={require('../assets/images/jsapp.png')} style={styles.logoImage}/>
          </TouchableOpacity>
        </View>
        { initialView }
        { signIn }
        { signUp }
        { fogotPass }
      </KeyboardAwareScrollView>
      </View>
    )
  }

  _onLogoClicked = () => {
    this.setState({
      initialScreen: true,
      signIn: false,
      signUp: false,
      forgotPass: false
    })
  }

  _onSignIn = () => {
    this.setState({
      initialScreen: false,
      signIn: true
    })
  }

  _onBackFromSignIn = () => {
    this.setState({
      initialScreen: true,
      signIn: false
    })
  }

  _onSignUp = () => {
    this.setState({
      initialScreen: false,
      signUp: true
    })
  }

  _onBackFromSignUp = () => {
    this.setState({
      initialScreen: true,
      signUp: false
    })
  }

  _onForgotPass = () => {
    this.setState({
      initialScreen: false,
      signIn: false,
      signUp: false,
      forgotPass: true
    })
  }

  _onBackFromForgotPass = () => {
    this.setState({
      initialScreen: true,
      forgotPass: false
    })
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
  },
  scrollContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  logoContainer: {
  },
  logoImage : {
    height: 220,
    width: 220,
  },
})
<commit_msg>styling<commit_after>import React, { Component } from 'react'
import {
  View,
  TouchableOpacity,
  LayoutAnimation,
  Platform,
  UIManager,
  StatusBar,
  StyleSheet,
  Image
} from 'react-native'
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'
import { getColor } from '../components/config'
import Background from '../components/background'
import InitialView from '../components/login_screen/initial_view'
import SignInForm from '../components/login_screen/signIn_form'
import SignUpForm from '../components/login_screen/signUp_form'
import ForgotPassForm from '../components/login_screen/forgotPassword_form'
import { firebaseApp } from '../firebase'
import { observer, inject } from 'mobx-react/native'
import { Actions } from 'react-native-mobx'

@inject("appStore") @observer
export default class LoginScreen extends Component {
  constructor(props) {
    super(props)
    this.state = {
      initialScreen: false,
      signIn: false,
      signUp: false,
      forgotPass: false
    }
    if (Platform.OS === 'android') {
      UIManager.setLayoutAnimationEnabledExperimental(true)
    }
    _unsubscribe = firebaseApp.auth().onAuthStateChanged((user) => {
      if (user) {
        console.log(" --- User Signed In ---> " + user.displayName)
        this.props.appStore.user = user
        this.props.appStore.username = user.displayName
        firebaseApp.database().ref('users').child(user.uid).once('value')
        .then((snapshot) => {
          this.props.appStore.post_count = parseInt(snapshot.val().post_count)
        })
        Actions.home({ type: 'replace' })
      }
      else {
        console.log(" --- User is Signed Off --- ")
        this.setState({ initialScreen: true })
      }
      _unsubscribe()
    })
  }

  componentWillUnmount() {
  }

  componentWillMount() {
  }

  componentDidMount() {
  }

  componentDidUpdate() {
    LayoutAnimation.configureNext(LayoutAnimation.Presets.spring)
  }

  render() {
    const initialView = this.state.initialScreen ?
      <InitialView
      onSignIn={this._onSignIn}
      onSignUp={this._onSignUp}
      animDelay={0}/>
    : null

    const signIn = this.state.signIn ?
      <SignInForm
      onBackFromSignIn={this._onBackFromSignIn}
      onForgotPass = {this._onForgotPass} />
    : null

    const signUp = this.state.signUp ?
      <SignUpForm
      onBackFromSignUp={this._onBackFromSignUp} />
    : null

    const fogotPass = this.state.forgotPass ?
      <ForgotPassForm
      onBackFromForgotPass={this._onBackFromForgotPass} />
    : null

    return (
      <View style={styles.container}>
      <Background imgSrouce={require('../assets/images/bk.png')}/>
      <KeyboardAwareScrollView contentContainerStyle={styles.scrollContainer} >
        <StatusBar
          backgroundColor={getColor('googleBlue700')}
          barStyle='light-content'
          animated={true}
        />
        <View style={styles.logoContainer}>
          <TouchableOpacity onPress={this._onLogoClicked}>
            <Image source={require('../assets/images/jsapp.png')} style={styles.logoImage}/>
          </TouchableOpacity>
        </View>
        { initialView }
        { signIn }
        { signUp }
        { fogotPass }
      </KeyboardAwareScrollView>
      </View>
    )
  }

  _onLogoClicked = () => {
    this.setState({
      initialScreen: true,
      signIn: false,
      signUp: false,
      forgotPass: false
    })
  }

  _onSignIn = () => {
    this.setState({
      initialScreen: false,
      signIn: true
    })
  }

  _onBackFromSignIn = () => {
    this.setState({
      initialScreen: true,
      signIn: false
    })
  }

  _onSignUp = () => {
    this.setState({
      initialScreen: false,
      signUp: true
    })
  }

  _onBackFromSignUp = () => {
    this.setState({
      initialScreen: true,
      signUp: false
    })
  }

  _onForgotPass = () => {
    this.setState({
      initialScreen: false,
      signIn: false,
      signUp: false,
      forgotPass: true
    })
  }

  _onBackFromForgotPass = () => {
    this.setState({
      initialScreen: true,
      forgotPass: false
    })
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
  },
  scrollContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  logoContainer: {
  },
  logoImage : {
    height: 240,
    width: 240,
  },
})
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    replace = require('gulp-replace'),
    bump = require("gulp-bump"),
    rename = require("gulp-rename"),
    del = require('del'),
    css = require('gulp-clean-css');
    js = require('gulp-uglify');

gulp.task('css', ['clean'], function () {
    return gulp.src('./src/stable/css/tableexport.css')
        .pipe(gulp.dest('./dist/css/'))
        .pipe(css())
        .pipe(rename({
            suffix: '.min'
        }))
        .pipe(gulp.dest('./dist/css/'));
});

gulp.task('js', ['clean'], function () {
    return gulp.src('./src/stable/js/tableexport.js')
        .pipe(gulp.dest('./dist/js/'))
        .pipe(js({output: {comments: /^!|@preserve|@license|@cc_on/i}}))
        .pipe(rename({
            suffix: '.min'
        }))
        .pipe(gulp.dest('./dist/js/'));
});

gulp.task('bump', ['bump-js', 'bump-css'], function(){
    return gulp.src(['./bower.json', './package.json', './src/stable.tableexport.js'])
        .pipe(bump())
        .pipe(gulp.dest('./'));
});

gulp.task('bump-js', function () {
    return gulp.src(['src/stable/js/tableexport.js'])
    .pipe(replace(/(v\d\.\d\.)(\d)/g, function (matches, match1, match2) {
        return match1 + (Number(match2)+1);
    }))
    .pipe(gulp.dest('src/stable/js/'))
    .on('end', function () {
        gulp.start('js');
    });
});

gulp.task('bump-css', function () {
    gulp.src(['src/stable/css/tableexport.css'])
        .pipe(replace(/(v\d\.\d\.)(\d)/g, function (matches, match1, match2) {
            return match1 + (Number(match2) + 1);
        }))
        .pipe(gulp.dest('src/stable/css/'))
        .on('end', function () {
            gulp.start('css');
        });
});

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

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

gulp.task('default', ['build']);

<commit_msg>gulp build updates<commit_after>var gulp = require('gulp'),
    replace = require('gulp-replace'),
    bump = require("gulp-bump"),
    rename = require("gulp-rename"),
    del = require('del'),
    css = require('gulp-clean-css');
    js = require('gulp-uglify');

gulp.task('css', ['clean'], function () {
    return gulp.src('./src/stable/css/tableexport.css')
        .pipe(gulp.dest('./dist/css/'))
        .pipe(css())
        .pipe(rename({
            suffix: '.min'
        }))
        .pipe(gulp.dest('./dist/css/'))
        .pipe(gulp.dest('./src/stable/css/'));
});

gulp.task('js', ['clean'], function () {
    return gulp.src('./src/stable/js/tableexport.js')
        .pipe(gulp.dest('./dist/js/'))
        .pipe(js({output: {comments: /^!|@preserve|@license|@cc_on/i}}))
        .pipe(rename({
            suffix: '.min'
        }))
        .pipe(gulp.dest('./dist/js/'))
        .pipe(gulp.dest('./src/stable/js/'));
});

gulp.task('bump', ['bump-js', 'bump-css'], function(){
    return gulp.src(['./bower.json', './package.json', './src/stable.tableexport.js'])
        .pipe(bump())
        .pipe(gulp.dest('./'));
});

gulp.task('bump-js', function () {
    return gulp.src(['src/stable/js/tableexport.js'])
        .pipe(replace(/(v\d\.\d\.)(\d)/g, function (matches, match1, match2) {
            return match1 + (Number(match2)+1);
        }))
        .pipe(gulp.dest('src/stable/js/'))
        .on('end', function () {
            gulp.start('js');
        });
});

gulp.task('bump-css', function () {
    gulp.src(['src/stable/css/tableexport.css'])
        .pipe(replace(/(v\d\.\d\.)(\d)/g, function (matches, match1, match2) {
            return match1 + (Number(match2) + 1);
        }))
        .pipe(gulp.dest('src/stable/css/'))
        .on('end', function () {
            gulp.start('css');
        });
});

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

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

gulp.task('default', ['build']);

<|endoftext|>


<commit_before>var gulp = require('gulp');

// include plug-ins
var jshint = require('gulp-jshint');
var mocha = require('gulp-mocha');

// JS hint task
gulp.task('jshint', function() {
  gulp.src('./src/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('default'));
});

gulp.task('mocha_test', function() {
  return gulp.src(['test/test-*.js'], { read: false })
    .pipe(mocha({
      reporter: 'spec',
      globals: {
        should: require('should')
      }
    }));
  });

gulp.task('default', function(){
  gulp.run('jshint', 'mocha_test');
  gulp.watch(scriptFiles, function(){
    gulp.run('jshint', 'mocha_test');
  });
});<commit_msg>Fix for gulp config file<commit_after>var gulp = require('gulp');

// include plug-ins
var jshint = require('gulp-jshint');
var mocha = require('gulp-mocha');

// JS hint task
gulp.task('jshint', function() {
  gulp.src('./src/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('default'));
});

gulp.task('mocha_test', function() {
  return gulp.src(['test/test-*.js'], { read: false })
    .pipe(mocha({
      reporter: 'spec',
      globals: {
        should: require('should')
      }
    }));
  });

gulp.task('default', function(){
  gulp.run('jshint', 'mocha_test');
  /*gulp.watch(scriptFiles, function(){
    gulp.run('jshint', 'mocha_test');
  });*/
});<|endoftext|>


<commit_before>var _             = require('lodash'),
    crypto        = require('crypto'),
    gulp  				= require('gulp'),
    gutil					= require('gulp-util'),
		iced					= require('gulp-iced'),
		concat				= require('gulp-concat'),
		clean					= require('gulp-clean'),
    stylus        = require('gulp-stylus'),
    path          = require('path'),
    bower         = require('gulp-bower'),
    htmlreplace   = require('gulp-html-replace'),
    htmlmin       = require('gulp-htmlmin'),
    bowerPath     = './bower_components',
		thirdPartyJs	= [
      'jquery/dist/jquery.min.js',
      'angular/angular.min.js',
      'angular-route/angular-route.min.js',
      'lodash/dist/lodash.min.js',
      'angular-classy/angular-classy.min.js',
      'angular-formly/dist/formly.bootstrap.min.js'
		],
		thirdPartyCss	= [
      'normalize.css/normalize.css',
      'bootstrap/dist/css/bootstrap.min.css',
      'bootstrap/dist/css/bootstrap-theme.min.css'
		],
		directories		= {
      clean: {
        server: './app/**/*.js',
        client: ['./public/**/*.js', './public/**/*.css']
      },
			server: {
				iced: { src: './src/server/**/*.iced', dest: './app' }
			},
			client: {
				iced: { src: ['./src/client/app/app.iced', './src/client/app/**/*.iced'], dest: './public/js' },
				styles: { src: ['./src/client/styles/app.styl', './src/client/styles/*.styl'], dest: './public/css' },
				images: { src: './src/client/images/**/*', dest: './public/images' },
        html: { src: './src/client/html/**/*.html', dest: './public/html' }
			}
		};

var idgen = function() {
  var seed = crypto.randomBytes(20);
  return crypto.createHash('sha1').update(seed).digest('hex');
};

// Clean
gulp.task('clean', [ 'clean:server', 'clean:client' ]);

gulp.task('clean:server', function() {
	gulp.src(directories.clean.server)
		.pipe(clean());
});

gulp.task('clean:client', function() {
	gulp.src(directories.clean.client)
		.pipe(clean());
});

// Bower
gulp.task('bower', function() {
  return bower();
});

// Server
gulp.task('server:compile', function() {
	gulp.src(directories.server.iced.src)
		.pipe(iced({ bare: false }).on('error', gutil.log))
		.pipe(gulp.dest(directories.server.iced.dest));
});

// Client
gulp.task('client:compile', function() {
  var hash = idgen(),
      appjs = 'app-' + hash + '.js',
      vendorjs = 'vendor-' + hash + '.js',
      appcss = 'app-' + hash + '.css',
      vendorcss = 'vendor-' + hash + '.css';

  gulp.src(directories.clean.client)
    .pipe(clean());

  gulp.src(directories.client.iced.src)
    .pipe(iced({ bare: false, runtime: 'window' }))
    .pipe(concat(appjs))
    .pipe(gulp.dest(directories.client.iced.dest));

  gulp.src(_(thirdPartyJs).chain().map(function(s) { return [ bowerPath, s ].join('/') }).value())
    .pipe(concat(vendorjs))
    .pipe(gulp.dest(directories.client.iced.dest));

  gulp.src(directories.client.styles.src)
    .pipe(stylus({set: ['compress']}))
    .pipe(concat(appcss))
    .pipe(gulp.dest(directories.client.styles.dest));

  gulp.src(_(thirdPartyCss).chain().map(function(s) { return [ bowerPath, s ].join('/') }).value())
    .pipe(concat(vendorcss))
    .pipe(gulp.dest(directories.client.styles.dest));

  gulp.src(directories.client.html.src)
    .pipe(htmlreplace({
      'css': [ '/static/css/' + vendorcss, '/static/css/' + appcss ],
      'js': [ '/static/js/' + vendorjs, '/static/js/' + appjs ]
    }))
    .pipe(htmlmin({ collapseWhitespace: true, removeComments: true }))
    .pipe(gulp.dest(directories.client.html.dest));

  gulp.src(directories.client.images.src)
    .pipe(gulp.dest(directories.client.styles.dest));
});

gulp.task('default', [ 'server:compile', 'client:compile' ]);
gulp.task('production', [ 'bower' ], function() {
  gulp.start('default');
});

// Development
gulp.task('dev:client', function() {
  gulp.watch('./src/client/**/*', ['default']);
});
<commit_msg>Replaced iced with normal coffee brew<commit_after>var _             = require('lodash'),
    crypto        = require('crypto'),
    gulp  				= require('gulp'),
    gutil					= require('gulp-util'),
		iced					= require('gulp-iced'),
    coffee        = require('gulp-coffee'),
		concat				= require('gulp-concat'),
		clean					= require('gulp-clean'),
    stylus        = require('gulp-stylus'),
    path          = require('path'),
    bower         = require('gulp-bower'),
    htmlreplace   = require('gulp-html-replace'),
    htmlmin       = require('gulp-htmlmin'),
    bowerPath     = './bower_components',
		thirdPartyJs	= [
      'jquery/dist/jquery.min.js',
      'angular/angular.min.js',
      'angular-route/angular-route.min.js',
      'lodash/dist/lodash.min.js',
      'angular-classy/angular-classy.min.js',
      'angular-formly/dist/formly.bootstrap.min.js'
		],
		thirdPartyCss	= [
      'normalize.css/normalize.css',
      'bootstrap/dist/css/bootstrap.min.css',
      'bootstrap/dist/css/bootstrap-theme.min.css'
		],
		directories		= {
      clean: {
        server: './app/**/*.js',
        client: ['./public/**/*.js', './public/**/*.css']
      },
			server: {
				iced: { src: './src/server/**/*.iced', dest: './app' }
			},
			client: {
				iced: { src: ['./src/client/app/app.iced', './src/client/app/**/*.iced'], dest: './public/js' },
				styles: { src: ['./src/client/styles/app.styl', './src/client/styles/*.styl'], dest: './public/css' },
				images: { src: './src/client/images/**/*', dest: './public/images' },
        html: { src: './src/client/html/**/*.html', dest: './public/html' }
			}
		};

var idgen = function() {
  var seed = crypto.randomBytes(20);
  return crypto.createHash('sha1').update(seed).digest('hex');
};

// Clean
gulp.task('clean', [ 'clean:server', 'clean:client' ]);

gulp.task('clean:server', function() {
	gulp.src(directories.clean.server)
		.pipe(clean());
});

gulp.task('clean:client', function() {
	gulp.src(directories.clean.client)
		.pipe(clean());
});

// Bower
gulp.task('bower', function() {
  return bower();
});

// Server
gulp.task('server:compile', function() {
	gulp.src(directories.server.iced.src)
		.pipe(iced({ bare: false }).on('error', gutil.log))
		.pipe(gulp.dest(directories.server.iced.dest));
});

// Client
gulp.task('client:compile', function() {
  var hash = idgen(),
      appjs = 'app-' + hash + '.js',
      vendorjs = 'vendor-' + hash + '.js',
      appcss = 'app-' + hash + '.css',
      vendorcss = 'vendor-' + hash + '.css';

  gulp.src(directories.clean.client)
    .pipe(clean());

  gulp.src(directories.client.iced.src)
    .pipe(coffee({ bare: false }))
    .pipe(concat(appjs))
    .pipe(gulp.dest(directories.client.iced.dest));

  gulp.src(_(thirdPartyJs).chain().map(function(s) { return [ bowerPath, s ].join('/') }).value())
    .pipe(concat(vendorjs))
    .pipe(gulp.dest(directories.client.iced.dest));

  gulp.src(directories.client.styles.src)
    .pipe(stylus({set: ['compress']}))
    .pipe(concat(appcss))
    .pipe(gulp.dest(directories.client.styles.dest));

  gulp.src(_(thirdPartyCss).chain().map(function(s) { return [ bowerPath, s ].join('/') }).value())
    .pipe(concat(vendorcss))
    .pipe(gulp.dest(directories.client.styles.dest));

  gulp.src(directories.client.html.src)
    .pipe(htmlreplace({
      'css': [ '/static/css/' + vendorcss, '/static/css/' + appcss ],
      'js': [ '/static/js/' + vendorjs, '/static/js/' + appjs ]
    }))
    .pipe(htmlmin({ collapseWhitespace: true, removeComments: true }))
    .pipe(gulp.dest(directories.client.html.dest));

  gulp.src(directories.client.images.src)
    .pipe(gulp.dest(directories.client.styles.dest));
});

gulp.task('default', [ 'server:compile', 'client:compile' ]);
gulp.task('production', [ 'bower' ], function() {
  gulp.start('default');
});

// Development
gulp.task('dev:client', function() {
  gulp.watch('./src/client/**/*', ['default']);
});
<|endoftext|>


<commit_before>/**
 * Gulpfile
 *
 * @see https://travismaynard.com/writing/getting-started-with-gulp
 *
 * @since 0.1.0
 */

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

// Include Our Plugins
var jshint = require( 'gulp-jshint' );
var uglify = require( 'gulp-uglify' );
var rename = require( 'gulp-rename' );
var rtlcss = require('gulp-rtlcss');
var cleanCSS = require( 'gulp-clean-css' );

// Files/Paths
var js_src = './src/assets/javascript';
var js_dest = './dist/assets/javascript';
var js_files = [ js_src + '/**/*.js' ];
var css_src = './src/assets/styles';
var css_dest = './dist/assets/styles';
var css_files = [ css_src + '/**/*.css' ];

// Lint Task
gulp.task( 'lint_js', function() {
    return gulp.src( js_files )
        .pipe( jshint() )
        .pipe( jshint.reporter( 'default' ) );
});

// Minify JS
gulp.task( 'minify_js', function() {
    return gulp.src( js_files )
        .pipe( uglify() )
        .pipe( rename({ 'suffix' : '.min' }) )
        .pipe( gulp.dest( js_dest ) );
});

// Minify CSS
gulp.task( 'minify_css', function() {
    return gulp.src( css_files )
        .pipe( cleanCSS() )
        .pipe( rename({ 'suffix' : '.min' }) )
        .pipe( gulp.dest( css_dest ) );
});

// RTL CSS
gulp.task( 'rtl_css', function() {
    return gulp.src( css_files )
        .pipe( rtlcss() )
        .pipe( cleanCSS() )
        .pipe( rename({ 'suffix' : '-rtl.min' }) )
        .pipe( gulp.dest( css_dest ) );
});

// Watch Files For Changes
gulp.task( 'watch', function() {
    gulp.watch( js_files, [ 'lint_js', 'minify_js' ]);
    gulp.watch( css_files, [ 'minify_css', 'rtl_css' ]);
});

// Default Task
gulp.task( 'default', [ 'lint_js', 'minify_js', 'minify_css', 'rtl_css', 'watch' ]);
<commit_msg>updated assets dir in gulpfile to reflect directory structure changes<commit_after>/**
 * Gulpfile
 *
 * @see https://travismaynard.com/writing/getting-started-with-gulp
 *
 * @since 0.1.0
 */

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

// Include Our Plugins
var jshint = require( 'gulp-jshint' );
var uglify = require( 'gulp-uglify' );
var rename = require( 'gulp-rename' );
var rtlcss = require('gulp-rtlcss');
var cleanCSS = require( 'gulp-clean-css' );

// Files/Paths
var js_src = './assets/javascript';
var js_dest = './dist/assets/javascript';
var js_files = [ js_src + '/**/*.js' ];
var css_src = './assets/styles';
var css_dest = './dist/assets/styles';
var css_files = [ css_src + '/**/*.css' ];

// Lint Task
gulp.task( 'lint_js', function() {
    return gulp.src( js_files )
        .pipe( jshint() )
        .pipe( jshint.reporter( 'default' ) );
});

// Minify JS
gulp.task( 'minify_js', function() {
    return gulp.src( js_files )
        .pipe( uglify() )
        .pipe( rename({ 'suffix' : '.min' }) )
        .pipe( gulp.dest( js_dest ) );
});

// Minify CSS
gulp.task( 'minify_css', function() {
    return gulp.src( css_files )
        .pipe( cleanCSS() )
        .pipe( rename({ 'suffix' : '.min' }) )
        .pipe( gulp.dest( css_dest ) );
});

// RTL CSS
gulp.task( 'rtl_css', function() {
    return gulp.src( css_files )
        .pipe( rtlcss() )
        .pipe( cleanCSS() )
        .pipe( rename({ 'suffix' : '-rtl.min' }) )
        .pipe( gulp.dest( css_dest ) );
});

// Watch Files For Changes
gulp.task( 'watch', function() {
    gulp.watch( js_files, [ 'lint_js', 'minify_js' ]);
    gulp.watch( css_files, [ 'minify_css', 'rtl_css' ]);
});

// Default Task
gulp.task( 'default', [ 'lint_js', 'minify_js', 'minify_css', 'rtl_css', 'watch' ]);
<|endoftext|>


<commit_before>const gulp = require('gulp');
const eslint = require('gulp-eslint');
const mocha = require('gulp-mocha-phantomjs');
const rename = require('gulp-rename');
const uglify = require('gulp-uglify');
const header = require('gulp-header');
const scsslint = require('gulp-scss-lint');
const sass = require('gulp-sass');
const autoprefixer = require('gulp-autoprefixer');
const webpack = require('webpack');
const webpackStream = require('webpack-stream');
const browserSync = require('browser-sync').create();
const webpackConfig = require('./webpack.config.js');
const testWebpackConfig = require('./webpack.test.config.js');
const pkg = require('./package.json');

const banner = '/*! <%= pkg.name %> - v<%= pkg.version %> | <%= new Date().getFullYear() %> */\n';

gulp.task('test-format', () => (
	gulp.src(['./src/d3-funnel/**/*.js'])
		.pipe(eslint())
		.pipe(eslint.format())
		.pipe(eslint.failOnError())
));

gulp.task('compile-test', () => (
	gulp.src(['./test/index.js'])
		.pipe(webpackStream(testWebpackConfig, webpack))
		.pipe(gulp.dest('./test/compiled/'))
));

gulp.task('test-mocha', ['compile-test'], () => (
	gulp.src(['test/test.html'])
		.pipe(mocha({ reporter: 'spec' }))
));

gulp.task('test', ['test-format', 'test-mocha']);

gulp.task('compile-build', () => (
	gulp.src(['./src/index.js'])
		.pipe(webpackStream(webpackConfig, webpack))
		.pipe(gulp.dest('./compiled/'))
));

gulp.task('build', ['test', 'compile-build'], () => (
	gulp.src(['./compiled/d3-funnel.js'])
		.pipe(gulp.dest('./dist/'))
		.pipe(rename({
			extname: '.min.js',
		}))
		.pipe(uglify())
		.pipe(header(banner, { pkg }))
		.pipe(gulp.dest('./dist/'))
));

gulp.task('build-examples-style', () => (
	gulp.src('./examples/src/sass/**/*.scss')
		.pipe(scsslint())
		.pipe(scsslint.failReporter())
		.pipe(sass({
			outputStyle: 'expanded',
		}).on('error', sass.logError))
		.pipe(autoprefixer({
			browsers: ['last 2 versions'],
		}))
		.pipe(gulp.dest('./examples/dist/css'))
		.pipe(browserSync.stream())
));

gulp.task('build-examples-script', () => (
	gulp.src(['./examples/src/js/index.js'])
		.pipe(webpackStream(testWebpackConfig, webpack))
		.pipe(gulp.dest('./examples/dist/js'))
		.pipe(browserSync.stream())
));

gulp.task('build-examples-html', () => (
	gulp.src('./examples/src/index.html')
		.pipe(gulp.dest('./examples/dist'))
		.pipe(browserSync.stream())
));

gulp.task('examples', ['build-examples-style', 'build-examples-script', 'build-examples-html'], () => {
	browserSync.init({ server: './examples/dist' });

	gulp.watch(['./src/**/*.js', './examples/src/**/*.js'], ['build-examples-script']);
	gulp.watch(['./examples/src/sass/**/*.scss'], ['build-examples-style']);
	gulp.watch(['./examples/src/**/*.html'], ['build-examples-html']).on('change', browserSync.reload);
});

gulp.task('watch', () =>
	gulp.watch(['./src/d3-funnel/**/*.js', './examples/src/**/*.js'], ['build-examples'])
);

gulp.task('default', ['build']);
<commit_msg>Remove unused build task<commit_after>const gulp = require('gulp');
const eslint = require('gulp-eslint');
const mocha = require('gulp-mocha-phantomjs');
const rename = require('gulp-rename');
const uglify = require('gulp-uglify');
const header = require('gulp-header');
const scsslint = require('gulp-scss-lint');
const sass = require('gulp-sass');
const autoprefixer = require('gulp-autoprefixer');
const webpack = require('webpack');
const webpackStream = require('webpack-stream');
const browserSync = require('browser-sync').create();
const webpackConfig = require('./webpack.config.js');
const testWebpackConfig = require('./webpack.test.config.js');
const pkg = require('./package.json');

const banner = '/*! <%= pkg.name %> - v<%= pkg.version %> | <%= new Date().getFullYear() %> */\n';

gulp.task('test-format', () => (
	gulp.src(['./src/d3-funnel/**/*.js'])
		.pipe(eslint())
		.pipe(eslint.format())
		.pipe(eslint.failOnError())
));

gulp.task('compile-test', () => (
	gulp.src(['./test/index.js'])
		.pipe(webpackStream(testWebpackConfig, webpack))
		.pipe(gulp.dest('./test/compiled/'))
));

gulp.task('test-mocha', ['compile-test'], () => (
	gulp.src(['test/test.html'])
		.pipe(mocha({ reporter: 'spec' }))
));

gulp.task('test', ['test-format', 'test-mocha']);

gulp.task('compile-build', () => (
	gulp.src(['./src/index.js'])
		.pipe(webpackStream(webpackConfig, webpack))
		.pipe(gulp.dest('./compiled/'))
));

gulp.task('build', ['test', 'compile-build'], () => (
	gulp.src(['./compiled/d3-funnel.js'])
		.pipe(gulp.dest('./dist/'))
		.pipe(rename({
			extname: '.min.js',
		}))
		.pipe(uglify())
		.pipe(header(banner, { pkg }))
		.pipe(gulp.dest('./dist/'))
));

gulp.task('build-examples-style', () => (
	gulp.src('./examples/src/sass/**/*.scss')
		.pipe(scsslint())
		.pipe(scsslint.failReporter())
		.pipe(sass({
			outputStyle: 'expanded',
		}).on('error', sass.logError))
		.pipe(autoprefixer({
			browsers: ['last 2 versions'],
		}))
		.pipe(gulp.dest('./examples/dist/css'))
		.pipe(browserSync.stream())
));

gulp.task('build-examples-script', () => (
	gulp.src(['./examples/src/js/index.js'])
		.pipe(webpackStream(testWebpackConfig, webpack))
		.pipe(gulp.dest('./examples/dist/js'))
		.pipe(browserSync.stream())
));

gulp.task('build-examples-html', () => (
	gulp.src('./examples/src/index.html')
		.pipe(gulp.dest('./examples/dist'))
		.pipe(browserSync.stream())
));

gulp.task('examples', ['build-examples-style', 'build-examples-script', 'build-examples-html'], () => {
	browserSync.init({ server: './examples/dist' });

	gulp.watch(['./src/**/*.js', './examples/src/**/*.js'], ['build-examples-script']);
	gulp.watch(['./examples/src/sass/**/*.scss'], ['build-examples-style']);
	gulp.watch(['./examples/src/**/*.html'], ['build-examples-html']).on('change', browserSync.reload);
});

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


<commit_before>var gulp = require('gulp'),
    uglify = require('gulp-uglify'),
    uglify = require('gulp-stylus'),
    typographic = require('typographic'),
    nib = require('nib'),
    plumber = require('gulp-plumber');

function errorLog(error){
    console.error.bind(error);
    this.emit('end');
}

/*uising errorLog
  You can put -->     .on('error',errorLog)
  Or you can use -->  .pipe(plumber())
*/

//scripts task
//Uglifies
gulp.task('scripts', function(){
  gulp.src('src/states/*.js')
    .pipe(plumber())
    .pipe(uglify())
    .pipe(gulp.dest('build/minjs/'));
});

//styles task
//run styles
gulp.task('styles', function(){
  gulp.src('src/assets/style/*.styl')
    .pipe(plumber())
    .pipe(stylus({
        use:[typographic(), nib()]
    }))
    .pipe(gulp.dest('build/style/'));
});

//watch task
//watching for changes
gulp.task('watch', function(){
  gulp.watch('src/states/*.js',['scripts']);
  gulp.watch('src/assets/style/*.styl',['styles']);

});

gulp.task('default', ['scripts', 'styles','watch']);
<commit_msg>grunt mond<commit_after>var gulp = require('gulp'),
    uglify = require('gulp-uglify'),
    uglify = require('gulp-stylus'),
    typographic = require('typographic'),
    nib = require('nib'),
    plumber = require('gulp-plumber');

function errorLog(error){
    console.error.bind(error);
    this.emit('end');
}

/*uising errorLog
  You can put -->     .on('error',errorLog)
  Or you can use -->  .pipe(plumber())
*/

//scripts task
//Uglifies
gulp.task('scripts', function(){
  gulp.src('src/states/*.js')
    .pipe(plumber())
    .pipe(uglify())
    .pipe(gulp.dest('build/minjs/'));
});

//styles task
//run styles
gulp.task('styles', function(){
  gulp.src('src/assets/style/*.styl')
    .pipe(plumber())
    .pipe(stylus({
        use:[typographic(), nib()]
    }))
    .pipe(gulp.dest('build/style/'));
});

//watch task
//watching for changes
gulp.task('watch', function(){
  gulp.watch('src/states/*.js',['scripts']);
  gulp.watch('src/assets/style/*.styl',['styles']);

});

gulp.task('default', ['scripts','watch']);
<|endoftext|>


<commit_before>'use strict';

var gulp     = require('gulp');
var gutil    = require('gulp-util');
var concat   = require('gulp-concat');
var gulpif   = require('gulp-if');
var cached   = require('gulp-cached');
var remember = require('gulp-remember');

var del      = require('del');
var minimist = require('minimist');

var sass       = require('gulp-sass');
var minifyCSS  = require('gulp-minify-css');
var sourcemaps = require('gulp-sourcemaps');

var minifyHTML  = require('gulp-minify-html');

var browserSync = require('browser-sync');
var reload      = browserSync.reload;

var ngAnnotate = require('gulp-ng-annotate');
var minifyJS   = require('gulp-uglify');

var knownOptions = {
    string: 'env',
    default: { env: process.env.NODE_ENV || 'development'}
};

var options = minimist(process.argv.slice(2), knownOptions);

gulp.task('build', ['scss', 'js', 'html', 'fonts', 'copy-res'], function() {
    gutil.log('Finished building app to folder www');
});

gulp.task('scss', function() {
   return gulp.src('app/scss/*.scss')
       .pipe(cached('scss'))
       .pipe(gulpif(options.env === 'development', sourcemaps.init()))
       .pipe(sass())
       .on('error', sass.logError)
       .pipe(gulpif(options.env !== 'development', minifyCSS()))
       .pipe(remember('scss'))
       .pipe(concat('app.css'))
       .pipe(gulpif(options.env === 'development', sourcemaps.write()))
       .pipe(gulp.dest('./www/css/'))
       .pipe(reload({stream: true}))
});

gulp.task('html', function() {
    return gulp.src(['./app/**/*.html', '!./app/vendor/**/*.html'])
       .pipe(cached('html'))
       .pipe(gulpif(options.env !== 'development', minifyHTML()))
       .pipe(gulp.dest('./www/'))
       .pipe(reload({stream: true}))
});

gulp.task('vendor-js', function() {
   return gulp.src(
       ['./app/vendor/ionic/js/ionic.bundle.min.js',
        './app/vendor/ngCordova/dist/*.js',
        './app/vendor/peerjs/peer.min.js',
        './app/vendor/lodash/lodash.min.js',
        './app/vendor/ngstorage/ngStorage.min.js',
        './app/vendor/angular-translate/angular-translate.min.js',
        './app/vendor/angular-translate-loader-static-files/angular-translate-loader-static-files.min.js',
        './app/vendor/fabric.js/dist/fabric.js'],
       { base: './app' })
       .pipe(gulp.dest('./www/'))
});

gulp.task('copy-res', function() {
   return gulp.src(['./app/res/**/*'],
       { base: './app' })
       .pipe(cached('res'))
       .pipe(gulp.dest('./www/'))
       .pipe(reload({stream: true}))
});

gulp.task('fonts', function() {
    return gulp.src(['./app/vendor/ionic/fonts/*'])
    .pipe(gulp.dest('./www/fonts'))
});

gulp.task('js', ['vendor-js'], function() {
    return gulp.src('./app/js/**/*')
        .pipe(ngAnnotate())
        .pipe(gulpif(options.env !== 'development', minifyJS()))
        .pipe(cached('js'))
        .pipe(gulp.dest('./www/js/'))
        .pipe(reload({stream: true}))
});

gulp.task('watch', ['build'], function() {
    browserSync({
        server: { baseDir: 'www/' },
        open:   false
    });

    var scss = gulp.watch('./app/scss/*.scss', ['scss'], {cwd: 'www'}, reload);
    var html = gulp.watch(['./app/**/*.html', '!./app/vendor/**/*.html'], ['html'], {cwd: 'www'}, reload);
    var js   = gulp.watch('./app/js/**/*', ['js'], {cwd: 'www'}, reload);
    var res  = gulp.watch('./app/res/**/*', ['copy-res'],  {cwd: 'www'}, reload);

    scss.on('change', function(event) {
        if (event.type === 'deleted') {
            gutil.log('Forgetting scss: ' + event.path);
            delete cached.caches.scss[event.path];
            remember.forget('scss', event.path);
        }
    });

    html.on('change', function(event) {
        if (event.type === 'deleted') {
            gutil.log('Forgetting html: ' + event.path);
            delete cached.caches.html[event.path];
        }
    });

    js.on('change', function(event) {
        if (event.type === 'deleted') {
            gutil.log('Forgetting js: ' + event.path);
            delete cached.caches.js[event.path];
        }
    });

    res.on('change', function(event) {
        if (event.type === 'deleted') {
            gutil.log('Forgetting res: ' + event.path);
            delete cached.caches.res[event.path];
        }
    });
});

gulp.task('clean', function() {
    return del('www');
});
<commit_msg>Add newline to end of gulpfile<commit_after>'use strict';

var gulp     = require('gulp');
var gutil    = require('gulp-util');
var concat   = require('gulp-concat');
var gulpif   = require('gulp-if');
var cached   = require('gulp-cached');
var remember = require('gulp-remember');

var del      = require('del');
var minimist = require('minimist');

var sass       = require('gulp-sass');
var minifyCSS  = require('gulp-minify-css');
var sourcemaps = require('gulp-sourcemaps');

var minifyHTML  = require('gulp-minify-html');

var browserSync = require('browser-sync');
var reload      = browserSync.reload;

var ngAnnotate = require('gulp-ng-annotate');
var minifyJS   = require('gulp-uglify');

var knownOptions = {
    string: 'env',
    default: { env: process.env.NODE_ENV || 'development'}
};

var options = minimist(process.argv.slice(2), knownOptions);

gulp.task('build', ['scss', 'js', 'html', 'fonts', 'copy-res'], function() {
    gutil.log('Finished building app to folder www');
});

gulp.task('scss', function() {
   return gulp.src('app/scss/*.scss')
       .pipe(cached('scss'))
       .pipe(gulpif(options.env === 'development', sourcemaps.init()))
       .pipe(sass())
       .on('error', sass.logError)
       .pipe(gulpif(options.env !== 'development', minifyCSS()))
       .pipe(remember('scss'))
       .pipe(concat('app.css'))
       .pipe(gulpif(options.env === 'development', sourcemaps.write()))
       .pipe(gulp.dest('./www/css/'))
       .pipe(reload({stream: true}))
});

gulp.task('html', function() {
    return gulp.src(['./app/**/*.html', '!./app/vendor/**/*.html'])
       .pipe(cached('html'))
       .pipe(gulpif(options.env !== 'development', minifyHTML()))
       .pipe(gulp.dest('./www/'))
       .pipe(reload({stream: true}))
});

gulp.task('vendor-js', function() {
   return gulp.src(
       ['./app/vendor/ionic/js/ionic.bundle.min.js',
        './app/vendor/ngCordova/dist/*.js',
        './app/vendor/peerjs/peer.min.js',
        './app/vendor/lodash/lodash.min.js',
        './app/vendor/ngstorage/ngStorage.min.js',
        './app/vendor/angular-translate/angular-translate.min.js',
        './app/vendor/angular-translate-loader-static-files/angular-translate-loader-static-files.min.js',
        './app/vendor/fabric.js/dist/fabric.js'],
       { base: './app' })
       .pipe(gulp.dest('./www/'))
});

gulp.task('copy-res', function() {
   return gulp.src(['./app/res/**/*'],
       { base: './app' })
       .pipe(cached('res'))
       .pipe(gulp.dest('./www/'))
       .pipe(reload({stream: true}))
});

gulp.task('fonts', function() {
    return gulp.src(['./app/vendor/ionic/fonts/*'])
    .pipe(gulp.dest('./www/fonts'))
});

gulp.task('js', ['vendor-js'], function() {
    return gulp.src('./app/js/**/*')
        .pipe(ngAnnotate())
        .pipe(gulpif(options.env !== 'development', minifyJS()))
        .pipe(cached('js'))
        .pipe(gulp.dest('./www/js/'))
        .pipe(reload({stream: true}))
});

gulp.task('watch', ['build'], function() {
    browserSync({
        server: { baseDir: 'www/' },
        open:   false
    });

    var scss = gulp.watch('./app/scss/*.scss', ['scss'], {cwd: 'www'}, reload);
    var html = gulp.watch(['./app/**/*.html', '!./app/vendor/**/*.html'], ['html'], {cwd: 'www'}, reload);
    var js   = gulp.watch('./app/js/**/*', ['js'], {cwd: 'www'}, reload);
    var res  = gulp.watch('./app/res/**/*', ['copy-res'],  {cwd: 'www'}, reload);

    scss.on('change', function(event) {
        if (event.type === 'deleted') {
            gutil.log('Forgetting scss: ' + event.path);
            delete cached.caches.scss[event.path];
            remember.forget('scss', event.path);
        }
    });

    html.on('change', function(event) {
        if (event.type === 'deleted') {
            gutil.log('Forgetting html: ' + event.path);
            delete cached.caches.html[event.path];
        }
    });

    js.on('change', function(event) {
        if (event.type === 'deleted') {
            gutil.log('Forgetting js: ' + event.path);
            delete cached.caches.js[event.path];
        }
    });

    res.on('change', function(event) {
        if (event.type === 'deleted') {
            gutil.log('Forgetting res: ' + event.path);
            delete cached.caches.res[event.path];
        }
    });
});

gulp.task('clean', function() {
    return del('www');
});

<|endoftext|>


<commit_before>function getMarginLeft(offsetLeft, offsetWidth, innerWidth) {
    // -marginLeft/offsetWidth=(-marginLeft+offsetLeft)/innerWidth
    // marginLeft/innerWidth-marginLeft/offsetWidth=offsetLeft/innerWidth
    // marginLeft*offsetWidth-marginLeft*innerWidth=offsetLeft*offsetWidth
    // marginLeft(offsetWidth-innerWidth)=offsetLeft*offsetWidth
    // marginLeft=offsetLeft*offsetWidth/(offsetWidth-innerWidth)
    if (offsetWidth === +innerWidth) return -offsetWidth / 2;
    return offsetLeft * offsetWidth / (offsetWidth - innerWidth);
}
function drag(target, event, overflow = false) {
    var saved_delta = { x: target.offsetLeft - event.clientX, y: target.offsetTop - event.clientY };
    var cancelmousemove = onmousemove(window, function (event) {
        if (event.defaultPrevented) return;
        if (!saved_delta.ing) {
            var abs = Math.abs;
            if (abs(target.offsetLeft - event.clientX - saved_delta.x < 3) && abs(target.offsetTop - event.clientY - saved_delta.y) < 3) return;
            saved_delta.ing = true;
        }
        event.preventDefault();
        var offsetLeft = saved_delta.x + event.clientX;
        var offsetTop = saved_delta.y + event.clientY;
        var {
            offsetHeight,
            offsetWidth
        } = target;
        if (!overflow) {
            if (offsetLeft + offsetWidth > innerWidth) {
                offsetLeft = innerWidth - offsetWidth;
            }
            if (offsetTop + offsetHeight > innerHeight) {
                offsetTop = innerHeight - offsetHeight;
            }
            if (offsetLeft < 0) {
                offsetLeft = 0;
            }
            if (offsetTop < 0) {
                offsetTop = 0;
            }
        }
        var marginLeft = getMarginLeft(offsetLeft, offsetWidth, innerWidth);
        var marginTop = getMarginLeft(offsetTop, offsetHeight, innerHeight);
        var left = offsetLeft - marginLeft;
        var top = offsetTop - marginTop;
        css(target, `left:${left * 100 / innerWidth}%;top:${top * 100 / innerHeight}%;margin-left:${marginLeft}px;margin-top:${marginTop}px`);
    });
    var cancelmouseup = onmouseup(window, function (event) {
        saved_delta = null;
        cancelmousemove();
        cancelmouseup();
    });
}<commit_msg>支持拖动非绝对定位的元素<commit_after>function getMarginLeft(offsetLeft, offsetWidth, innerWidth) {
    // -marginLeft/offsetWidth=(-marginLeft+offsetLeft)/innerWidth
    // marginLeft/innerWidth-marginLeft/offsetWidth=offsetLeft/innerWidth
    // marginLeft*offsetWidth-marginLeft*innerWidth=offsetLeft*offsetWidth
    // marginLeft(offsetWidth-innerWidth)=offsetLeft*offsetWidth
    // marginLeft=offsetLeft*offsetWidth/(offsetWidth-innerWidth)
    if (offsetWidth === +innerWidth) return -offsetWidth / 2;
    return offsetLeft * offsetWidth / (offsetWidth - innerWidth);
}
function drag(target, event, overflow = false) {
    var saved_delta = { x: target.offsetLeft - event.clientX, y: target.offsetTop - event.clientY };
    var clone;
    var saved_opacity = target.style.opacity;
    var cancelmousemove = onmousemove(window, function (event) {
        if (event.defaultPrevented) return;
        if (!saved_delta.ing) {
            var abs = Math.abs;
            if (event.buttons !== 1) return clear();
            if (abs(target.offsetLeft - event.clientX - saved_delta.x < 3) && abs(target.offsetTop - event.clientY - saved_delta.y) < 3) return;
            saved_delta.ing = true;
            if (!/absolute|fixed/.test(getComputedStyle(target).position)) {
                clone = cloneVisible(target);
                var position = getScreenPosition(target);
                css(target, "opacity:0");
                css(clone, `position:absolute;left:${position.left}px;top:${position.top}px;`);
                appendChild(document.body, clone);
                saved_delta.x += clone.offsetLeft - target.offsetLeft;
                saved_delta.y += clone.offsetTop - target.offsetTop;
            } else {
                clone = target;
            }
        }
        event.preventDefault();
        var offsetLeft = saved_delta.x + event.clientX;
        var offsetTop = saved_delta.y + event.clientY;
        var {
            offsetHeight,
            offsetWidth
        } = target;
        if (!overflow) {
            if (offsetLeft + offsetWidth > innerWidth) {
                offsetLeft = innerWidth - offsetWidth;
            }
            if (offsetTop + offsetHeight > innerHeight) {
                offsetTop = innerHeight - offsetHeight;
            }
            if (offsetLeft < 0) {
                offsetLeft = 0;
            }
            if (offsetTop < 0) {
                offsetTop = 0;
            }
        }
        var marginLeft = getMarginLeft(offsetLeft, offsetWidth, innerWidth);
        var marginTop = getMarginLeft(offsetTop, offsetHeight, innerHeight);
        var left = offsetLeft - marginLeft;
        var top = offsetTop - marginTop;
        css(clone, `left:${left * 100 / innerWidth}%;top:${top * 100 / innerHeight}%;margin-left:${marginLeft}px;margin-top:${marginTop}px`);
    });
    var clear = function () {
        saved_delta = null;
        if (clone !== target) remove(clone), css(target, { opacity: saved_opacity });
        cancelmousemove();
        cancelmouseup();
    };
    var cancelmouseup = onmouseup(window, clear);
}<|endoftext|>


<commit_before>/*
Data structure:

drafts: {
  'post-add': {
    0: 'Text1',
  }
  'post-update': {
    'postId1': 'Text1',
    'postId2': 'Text2',
    ...
  }
  'comment-add': {
    'postId1': 'Text1',
    'postId2': 'Text2',
    ...
  }
  'comment-update': {
    'commentId1': 'Text1',
    'commentId2': 'Text2',
    ...
  }
}

*/

function setDraft(section, id, text) {
  const drafts = JSON.parse(window.localStorage.getItem('drafts') ?? '{}');

  if (drafts[section] === undefined) {
    drafts[section] = {};
  }

  if (text?.trim().length > 0) {
    drafts[section][id] = text.trim();
  } else {
    delete drafts[section][id];
  }

  window.localStorage.setItem('drafts', JSON.stringify(drafts));
}

function getDraft(section, id) {
  const drafts = JSON.parse(window.localStorage.getItem('drafts') ?? '{}');
  return drafts?.[section]?.[id];
}

export function setDraftPA(text) { setDraft('post-add', 0, text); }
export function setDraftPU(id, text) { setDraft('post-update', id, text); }
export function setDraftCA(id, text) { setDraft('comment-add', id, text); }
export function setDraftCU(id, text) { setDraft('comment-update', id, text); }

export function getDraftPA() { return getDraft('post-add', 0); }
export function getDraftPU(id) { return getDraft('post-update', id); }
export function getDraftCA(id) { return getDraft('comment-add', id); }
export function getDraftCU(id) { return getDraft('comment-update', id); }
<commit_msg>drafts: Optimize LocalStorage reads/writes<commit_after>import _ from 'lodash';

/*
Data structure:

drafts: {
  'post-add': {
    0: 'Text1',
  }
  'post-update': {
    'postId1': 'Text1',
    'postId2': 'Text2',
    ...
  }
  'comment-add': {
    'postId1': 'Text1',
    'postId2': 'Text2',
    ...
  }
  'comment-update': {
    'commentId1': 'Text1',
    'commentId2': 'Text2',
    ...
  }
}

*/

// Use local cache for faster reading...
let drafts;

// ...but sync with LocalStorage occasionally, in case it was updated from the other tab
const readFromLocalStorage = _.throttle(() => {
  drafts = JSON.parse(window.localStorage.getItem('drafts') ?? '{}');
}, 1000);

// Actually, writes should be throttled as well, for the fast typers among us
const writeToLocalStorage = _.throttle(() => {
  window.localStorage.setItem('drafts', JSON.stringify(drafts));
}, 200);

function setDraft(section, id, text) {
  readFromLocalStorage();

  if (drafts[section] === undefined) {
    drafts[section] = {};
  }

  if (text?.trim().length > 0) {
    drafts[section][id] = text.trim();
  } else {
    delete drafts[section][id];
  }

  writeToLocalStorage();
}

function getDraft(section, id) {
  readFromLocalStorage();
  return drafts?.[section]?.[id];
}

export function setDraftPA(text) { setDraft('post-add', 0, text); }
export function setDraftPU(id, text) { setDraft('post-update', id, text); }
export function setDraftCA(id, text) { setDraft('comment-add', id, text); }
export function setDraftCU(id, text) { setDraft('comment-update', id, text); }

export function getDraftPA() { return getDraft('post-add', 0); }
export function getDraftPU(id) { return getDraft('post-update', id); }
export function getDraftCA(id) { return getDraft('comment-add', id); }
export function getDraftCU(id) { return getDraft('comment-update', id); }
<|endoftext|>


<commit_before>/*
  This utility will convert the nested data structure
  returned from an ElasticSearch query into a tabular
  data structure represented as an array of row objects.

  Inspired by Kibana's implementation, found at
  https://github.com/elastic/kibana/blob/master/src/ui/public/agg_response/tabify/tabify.js
*/
export default function tabify(response) {
    const tree = collectBucket(response.aggregations);
    const table = flatten(tree);

    console.log("Results from tabify():");

    // This one shows where there are "undefined" values.
    console.log(table)

    // This one shows the full structure pretty-printed.
    console.log(JSON.stringify(table, null, 2))

    return table;
}

function collectBucket(node, stack=[]) {
    if (!node)
        return;

    const keys = Object.keys(node);

    // Use old school `for` so we can break control flow by returning.
    for(let i = 0; i < keys.length; i++) {
        const key = keys[i];
        const value = node[key];
        if (typeof value === 'object') {
            if (Array.isArray(value)) {
                return extractTree(value, [...stack, key]);
            }
            return collectBucket(value, [...stack, key]);
        }
    }
}

function extractTree(buckets, stack) {
    return buckets.map((bucket) => {
        return Object.keys(bucket).reduce(function (tree, key) {
            let value = bucket[key];

            if (typeof value === "object") {
                if("value" in value){
                    value = value.value;
                } else {
                    value = collectBucket(value, [...stack, key]);
                }
            }

            if(key === "key"){
                key = stack[stack.length - 2]
            }

            tree[key] = value;

            return tree;
        }, {});
    });
}

function flatten(tree, parentNode={}){
    return tree

        // Have the child node inherit values from the parent.
        .map((childNode) => Object.assign({}, parentNode, childNode))

        // Each node object here has values inherited from its parent.
        .map((node) => {

            // Detect properties whose values are arrays.
            const childTrees = Object.keys(node)
                .map((key) => {
                    const value = node[key];
                    if (Array.isArray(value)) {
                        return value;
                    }
                })
                .filter((d) => d);

            switch (childTrees.length) {

                // Leaf node case, return the node.
                case 0:
                    return node;

                // Non-leaf node case, recurse on the child nodes.
                case 1:
                    const childTree = childTrees[0];
                    if(childTree.length === 0){
                        return node;
                    } else {
                        return flatten(childTree, node);
                    }
                default:
                    throw new Error("This case should never happen");
            }
        })

        // Flatten the nested arrays.
        .reduce((a, b) => a.concat(b), []);
}
<commit_msg>Fix build warning in tabify<commit_after>/*
  This utility will convert the nested data structure
  returned from an ElasticSearch query into a tabular
  data structure represented as an array of row objects.

  Inspired by Kibana's implementation, found at
  https://github.com/elastic/kibana/blob/master/src/ui/public/agg_response/tabify/tabify.js
*/
export default function tabify(response) {
    const tree = collectBucket(response.aggregations);
    const table = flatten(tree);

    console.log("Results from tabify():");

    // This one shows where there are "undefined" values.
    console.log(table)

    // This one shows the full structure pretty-printed.
    console.log(JSON.stringify(table, null, 2))

    return table;
}

function collectBucket(node, stack=[]) {
    if (!node)
        return;

    const keys = Object.keys(node);

    // Use old school `for` so we can break control flow by returning.
    for(let i = 0; i < keys.length; i++) {
        const key = keys[i];
        const value = node[key];
        if (typeof value === 'object') {
            if (Array.isArray(value)) {
                return extractTree(value, [...stack, key]);
            }
            return collectBucket(value, [...stack, key]);
        }
    }
}

function extractTree(buckets, stack) {
    return buckets.map((bucket) => {
        return Object.keys(bucket).reduce(function (tree, key) {
            let value = bucket[key];

            if (typeof value === "object") {
                if("value" in value){
                    value = value.value;
                } else {
                    value = collectBucket(value, [...stack, key]);
                }
            }

            if(key === "key"){
                key = stack[stack.length - 2]
            }

            tree[key] = value;

            return tree;
        }, {});
    });
}

function flatten(tree, parentNode={}){
    return tree

        // Have the child node inherit values from the parent.
        .map((childNode) => Object.assign({}, parentNode, childNode))

        // Each node object here has values inherited from its parent.
        .map((node) => {

            // Detect properties whose values are arrays.
            const childTrees = Object.keys(node)
                .map((key) => {
                    const value = node[key];
                    if (Array.isArray(value)) {
                        return value;
                    }
                    return false;
                })
                .filter((d) => d);

            switch (childTrees.length) {

                // Leaf node case, return the node.
                case 0:
                    return node;

                // Non-leaf node case, recurse on the child nodes.
                case 1:
                    const childTree = childTrees[0];
                    if(childTree.length === 0){
                        return node;
                    } else {
                        return flatten(childTree, node);
                    }
                default:
                    throw new Error("This case should never happen");
            }
        })

        // Flatten the nested arrays.
        .reduce((a, b) => a.concat(b), []);
}
<|endoftext|>


<commit_before>/**
 * Copyright 2018 The AMP Authors. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Fetches the latest production RTV. This is used as a filter
 * to prevent reports for old errors from getting through.
 */

const Request = require('./request');
const Cache = require('./cache');
const logs = require('./log');

const url = 'https://cdn.ampproject.org/rtv/metadata';
const fiveMin = 5 * 60 * 1000;
const fiftyMin = 50 * 60 * 1000;
const cache = new Cache(fiveMin, fiftyMin);

module.exports = function() {
  if (cache.has(url)) {
    return cache.get(url);
  }
  const req = new Promise((resolve, reject) => {
    Request.request(url, (err, _, body) => {
      if (err) {
        reject(err);
      } else {
        try {
          const { ampRuntimeVersion, diversions } = JSON.parse(body);
          resolve([ampRuntimeVersion].concat(diversions));
        } catch (e) {
          reject(e);
        }
      }
    });
  }).catch(err => {
    logs.generic.entry(
      {
        labels: {
          'appengine.googleapis.com/instance_name': process.env.GAE_INSTANCE,
        },
        resource: {
          type: 'gae_app',
          labels: {
            module_id: process.env.GAE_SERVICE,
            version_id: process.env.GAE_VERSION,
          },
        },
        severity: 500, // Error.
      },
      `failed to fetch RTV metadata: ${err.message}`
    );

    cache.delete(url);
    return [];
  });

  cache.set(url, req);
  return req;
};
<commit_msg>Write RTV fetch failures to the log...<commit_after>/**
 * Copyright 2018 The AMP Authors. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Fetches the latest production RTV. This is used as a filter
 * to prevent reports for old errors from getting through.
 */

const Request = require('./request');
const Cache = require('./cache');
const logs = require('./log');

const url = 'https://cdn.ampproject.org/rtv/metadata';
const fiveMin = 5 * 60 * 1000;
const fiftyMin = 50 * 60 * 1000;
const cache = new Cache(fiveMin, fiftyMin);

module.exports = function() {
  if (cache.has(url)) {
    return cache.get(url);
  }
  const req = new Promise((resolve, reject) => {
    Request.request(url, (err, _, body) => {
      if (err) {
        reject(err);
      } else {
        try {
          const { ampRuntimeVersion, diversions } = JSON.parse(body);
          resolve([ampRuntimeVersion].concat(diversions));
        } catch (e) {
          reject(e);
        }
      }
    });
  }).catch(err => {
    const entry = logs.generic.entry(
      {
        labels: {
          'appengine.googleapis.com/instance_name': process.env.GAE_INSTANCE,
        },
        resource: {
          type: 'gae_app',
          labels: {
            module_id: process.env.GAE_SERVICE,
            version_id: process.env.GAE_VERSION,
          },
        },
        severity: 500, // Error.
      },
      `failed to fetch RTV metadata: ${err.message}`
    );
    logs.generic.write(entry, err => {
      console.error(err);
    });

    cache.delete(url);
    return [];
  });

  cache.set(url, req);
  return req;
};
<|endoftext|>


<commit_before>'use strict';

function addTemplate(request, reply) {
  console.log(request.params.templateId);
  reply('Oooohhhh, new template');
}

function getTemplate(request, reply) {
  console.log(request.params.templateId);
  reply('Heres a template');
}

function updateTemplate(request, reply) {
  console.log(request.params.templateId);
  reply('Template updated, sir');
}

function deleteTemplate(request, reply) {
  console.log(request.params);
  reply('Oooohhhh, This template is so gone');
}

function getTemplates(request, reply) {
  console.log(request.params);
  reply('Heres all the templates');
}

function addForm(request, reply) {
  console.log(request.params.formId);
  reply('Oooohhhh, new form added');
}

function getForm(request, reply) {
  console.log(request.params.formId);
  reply('Heres the form');
}

function updateForm(request, reply) {
  console.log(request.params.formId);
  reply('Form updated, madam');
}

function deleteForm(request, reply) {
  console.log(request.params);
  reply('Oooohhhh, This form is so gone');
}

function getForms(request, reply) {
  console.log(request.params);
  reply('Heres all the forms');
}

module.exports.addTemplate = addTemplate;

module.exports.getTemplate = getTemplate;

module.exports.updateTemplate = updateTemplate;

module.exports.deleteTemplate = deleteTemplate;

module.exports.getTemplates = getTemplates;

module.exports.addForm = addForm;

module.exports.getForm = getForm;

module.exports.updateForm = updateForm;

module.exports.deleteForm = deleteForm;

module.exports.getForms = getForms;
<commit_msg>Initial commit<commit_after>'use strict';

var mongojs = require('mongojs');
var config = require('./config');
var db = mongojs(config.DB);
var forms = db.collection('forms');
var templates = db.collection('formtemplates');

function addTemplate(request, reply) {
  templates.save(request.payload, function(err, docs) {
    if (err) {
      reply(err);
    } else {
      reply(docs);
    }
  });
}

function getTemplate(request, reply) {
  templates.find({_id:mongojs.ObjectId(request.params.templateId)}, function(err, data) {
    if (err) {
      reply(err);
    } else {
      reply(data);
    }
  });
}

function updateTemplate(request, reply) {
  templates.update({_id:mongojs.ObjectId(request.params.templateId)}, request.payload, function(err, data) {
    if (err) {
      reply(err);
    } else {
      reply(data);
    }
  });
}

function deleteTemplate(request, reply) {
  templates.remove({_id:mongojs.ObjectId(request.params.templateId)}, function(err, data) {
    if (err) {
      reply(err);
    } else {
      reply(data);
    }
  });
}

function getTemplates(request, reply) {
  templates.find({}, function(err, data) {
    if (err) {
      reply(err);
    } else {
      reply(data);
    }
  });
}

function addForm(request, reply) {
  forms.save(request.payload, function(err, data) {
    if (err) {
      reply(err);
    } else {
      reply(data);
    }
  });
}

function getForm(request, reply) {
  forms.find({_id:mongojs.ObjectId(request.params.formId)}, function(err, data) {
    if (err) {
      reply(err);
    } else {
      reply(data);
    }
  });
}

function updateForm(request, reply) {
  forms.update({_id:mongojs.ObjectId(request.params.formId)}, request.payload, function(err, data) {
    if (err) {
      reply(err);
    } else {
      reply(data);
    }
  });
}

function deleteForm(request, reply) {
  forms.remove({_id:mongojs.ObjectId(request.params.formId)}, function(err, data) {
    if (err) {
      reply(err);
    } else {
      reply(data);
    }
  });
}

function getForms(request, reply) {
  forms.find({}, function(err, data) {
    if (err) {
      reply(err);
    } else {
      reply(data);
    }
  });
}

module.exports.addTemplate = addTemplate;

module.exports.getTemplate = getTemplate;

module.exports.updateTemplate = updateTemplate;

module.exports.deleteTemplate = deleteTemplate;

module.exports.getTemplates = getTemplates;

module.exports.addForm = addForm;

module.exports.getForm = getForm;

module.exports.updateForm = updateForm;

module.exports.deleteForm = deleteForm;

module.exports.getForms = getForms;
<|endoftext|>