<commit_before>'use strict';

/**
 * CONFIGURATION
 */

// Modules
var argv         = require('yargs').argv;
var autoprefixer = require('gulp-autoprefixer');
var browserSync  = require('browser-sync');
var cleanCSS     = require('gulp-clean-css');
var concat       = require('gulp-concat');
var cp           = require('child_process');
var del          = require('del');
var gulp         = require('gulp');
var runSequence  = require('run-sequence');
var sass         = require('gulp-sass');
var sourcemaps   = require('gulp-sourcemaps');
var uglify       = require('gulp-uglify');

// Local settings
var config = require('./gulp.config.js');
var paths  = config.paths;
var jekyll = config.jekyll;

/**
 * PRIMARY TASKS
 */

/**
 * `gulp`
 * Default task cleans, compiles assets and builds _site/
 */
gulp.task('default', function(done) {
  runSequence('clean', 'build-assets', 'build-jekyll', 'serve', done);
});

/**
 * Build assets: CSS & JS
 */
gulp.task('build-assets', function(done) {
  runSequence('sass', 'js', done);
});

/**
 * `gulp build`
 * Builds _site directory
 *
 * Set JEKYLL_ENV
 * --development (default)
 * --production
 * --debug
 *
 * Remove dependencies and assets, then recompile
 * --clean
 */
 gulp.task('build', function(done) {
  if (argv.clean) {
    runSequence('default', done);
  } else {
    runSequence('build-jekyll', done);
  }
 })

/**
 * `gulp serve`
 * Builds and serves _site directory
 *
 * See `gulp build` for command line options
 */
gulp.task('serve', function(done) {
  runSequence('browser-sync', 'watch', done)
});

/**
 * `gulp netlify`
 * Compiles assets, builds _site/ for production
 *
 * Note: Netlify automatically installs package.json and Gemfile dependencies
 */
gulp.task('netlify', function(done) {
  argv.production = true;
  runSequence('build-assets', 'build-jekyll', done);
})

/**
 * SECONDARY TASKS
 */

// Generates Jekyll _site directory
gulp.task('build-jekyll', function(done) {

  var env = function() {
    if (argv.production) {
      process.env.JEKYLL_ENV = 'production';
    } else if (argv.debug) {
      process.env.JEKYLL_ENV = 'debug';
    } else {
      process.env.JEKYLL_ENV = 'development';
    }

    return process.env;
  }();

  browserSync.notify('Building jekyll:' + env.JEKYLL_ENV);

  var args = ['exec','jekyll','build'].concat(jekyll.build[env.JEKYLL_ENV]);
  var opts = {stdio: 'inherit', env: env};

  return cp.spawn('bundle', args, opts).on('close', done);
})

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

// Compile sass to minified & mapped css files
gulp.task('sass', function() {
  browserSync.notify('Compiling stylesheet')
  return gulp.src(paths.sass + '/**/*')
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(autoprefixer())
    .pipe(cleanCSS())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(paths.css))
    .pipe(browserSync.stream());
});

// Minify js files
gulp.task('js', function() {
  browserSync.notify('Compiling JavaScript')
  return gulp.src(paths.js + '/**/*')
    .pipe(sourcemaps.init())
    .pipe(concat('main.js'))
    .pipe(uglify())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(paths.script))
})

// Watch for changes
gulp.task('watch', function() {
  gulp.watch(paths.js + '/**/*', ['js'])
  gulp.watch(paths.sass + '/**/*', ['sass'])
  gulp.watch(jekyll.watch, ['rebuild-jekyll']);
});

// Serve generated _site with BrowserSync
gulp.task('browser-sync', function() {
  browserSync({
    port: config.port,
    server: {
      baseDir: paths.dest
    },
    host: config.host
  });
});

// Deletes build files, _site dir and compiled CSS and JS
gulp.task('clean', function() {
  return del(config.clean)
})

/**
 * REFERENCES (aka people I stole from)
 *
 * https://gist.github.com/agragregra/79be7c57271c81258a51
 * http://savaslabs.com/2016/10/19/optimizing-jekyll-with-gulp.html
 * https://aaronlasseigne.com/2016/02/03/using-gulp-with-jekyll/
 */<commit_msg>Add bundle task -- again<commit_after>'use strict';

/**
 * CONFIGURATION
 */

// Modules
var argv         = require('yargs').argv;
var autoprefixer = require('gulp-autoprefixer');
var browserSync  = require('browser-sync');
var cleanCSS     = require('gulp-clean-css');
var concat       = require('gulp-concat');
var cp           = require('child_process');
var del          = require('del');
var gulp         = require('gulp');
var runSequence  = require('run-sequence');
var sass         = require('gulp-sass');
var sourcemaps   = require('gulp-sourcemaps');
var uglify       = require('gulp-uglify');

// Local settings
var config = require('./gulp.config.js');
var paths  = config.paths;
var jekyll = config.jekyll;

/**
 * PRIMARY TASKS
 */

/**
 * `gulp`
 * Default task cleans, compiles assets and builds _site/
 */
gulp.task('default', function(done) {
  runSequence('clean', 'bundle', 'build-assets', 'build-jekyll', 'serve', done);
});

/**
 * Build assets: CSS & JS
 */
gulp.task('build-assets', function(done) {
  runSequence('sass', 'js', done);
});

/**
 * `gulp build`
 * Builds _site directory
 *
 * Set JEKYLL_ENV
 * --development (default)
 * --production
 * --debug
 *
 * Remove dependencies and assets, then recompile
 * --clean
 */
 gulp.task('build', function(done) {
  if (argv.clean) {
    runSequence('default', done);
  } else {
    runSequence('build-jekyll', done);
  }
 })

/**
 * `gulp serve`
 * Builds and serves _site directory
 *
 * See `gulp build` for command line options
 */
gulp.task('serve', function(done) {
  runSequence('browser-sync', 'watch', done)
});

/**
 * `gulp netlify`
 * Compiles assets, builds _site/ for production
 *
 * Note: Netlify automatically installs package.json and Gemfile dependencies
 */
gulp.task('netlify', function(done) {
  argv.production = true;
  runSequence('build-assets', 'build-jekyll', done);
})

/**
 * SECONDARY TASKS
 */

// Generates Jekyll _site directory
gulp.task('build-jekyll', function(done) {

  var env = function() {
    if (argv.production) {
      process.env.JEKYLL_ENV = 'production';
    } else if (argv.debug) {
      process.env.JEKYLL_ENV = 'debug';
    } else {
      process.env.JEKYLL_ENV = 'development';
    }

    return process.env;
  }();

  browserSync.notify('Building jekyll:' + env.JEKYLL_ENV);

  var args = ['exec','jekyll','build'].concat(jekyll.build[env.JEKYLL_ENV]);
  var opts = {stdio: 'inherit', env: env};

  return cp.spawn('bundle', args, opts).on('close', done);
})

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

// Compile sass to minified & mapped css files
gulp.task('sass', function() {
  browserSync.notify('Compiling stylesheet')
  return gulp.src(paths.sass + '/**/*')
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(autoprefixer())
    .pipe(cleanCSS())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(paths.css))
    .pipe(browserSync.stream());
});

// Minify js files
gulp.task('js', function() {
  browserSync.notify('Compiling JavaScript')
  return gulp.src(paths.js + '/**/*')
    .pipe(sourcemaps.init())
    .pipe(concat('main.js'))
    .pipe(uglify())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest(paths.script))
})

// Watch for changes
gulp.task('watch', function() {
  gulp.watch(paths.js + '/**/*', ['js'])
  gulp.watch(paths.sass + '/**/*', ['sass'])
  gulp.watch(jekyll.watch, ['rebuild-jekyll']);
});

// Serve generated _site with BrowserSync
gulp.task('browser-sync', function() {
  browserSync({
    port: config.port,
    server: {
      baseDir: paths.dest
    },
    host: config.host
  });
});

// Installs gem bundle
gulp.task('bundle', function(done) {
  cp.spawn('bundle', ['install'], {stdio: 'inherit'})
    .on('close', done);
})

// Deletes build files, _site dir and compiled CSS and JS
gulp.task('clean', function() {
  return del(config.clean)
})

/**
 * REFERENCES (aka people I stole from)
 *
 * https://gist.github.com/agragregra/79be7c57271c81258a51
 * http://savaslabs.com/2016/10/19/optimizing-jekyll-with-gulp.html
 * https://aaronlasseigne.com/2016/02/03/using-gulp-with-jekyll/
 */<|endoftext|>


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

var minimist = require('minimist');

var options = minimist(process.argv.slice(2), {
	string: 'example',
	alias: {
		'example': 'x'
	}
})
console.log(options);

gulp.task('watch', function() {
	gulp.watch('src/examples/' + options.example + '/**', ['build']);
	gulp.watch('src/**/*.ts', ['build']);
});

gulp.task('build', ['buildSrc'], shell.task([
	"./scripts/updateExample.sh " + options.example
]));

gulp.task('init', ['clean', 'buildSrc'], shell.task([
	"./scripts/setupExample.sh " + options.example
]));

gulp.task('clean', shell.task([
	"rm -rf dist/" + options.example
]));

gulp.task('open', shell.task([
	"open dist/" + options.example + "/" + options.example + ".xcodeproj"
]));

gulp.task('cleanAll', shell.task([
	"rm -rf dist"
]));

gulp.task('buildSrc', shell.task([
	"cd src && ../scripts/pruneAngular2.sh",
	"cd src/node_modules && ../../node_modules/.bin/tsc"
]));

gulp.task('bundle', function() {
	return require('./tools/bundler').bundle(options.example);
})<commit_msg>chore(publish): add gulp task for npm publish<commit_after>var gulp = require('gulp');
var shell = require('gulp-shell');

var minimist = require('minimist');

var options = minimist(process.argv.slice(2), {
	string: 'example',
	alias: {
		'example': 'x'
	}
})
console.log(options);

gulp.task('watch', function() {
	gulp.watch('src/examples/' + options.example + '/**', ['build']);
	gulp.watch('src/**/*.ts', ['build']);
});

gulp.task('build', ['buildSrc'], shell.task([
	"./scripts/updateExample.sh " + options.example
]));

gulp.task('init', ['clean', 'buildSrc'], shell.task([
	"./scripts/setupExample.sh " + options.example
]));

gulp.task('clean', shell.task([
	"rm -rf dist/" + options.example
]));

gulp.task('open', shell.task([
	"open dist/" + options.example + "/" + options.example + ".xcodeproj"
]));

gulp.task('cleanAll', shell.task([
	"rm -rf dist"
]));

gulp.task('buildSrc', shell.task([
	"cd src && ../scripts/pruneAngular2.sh",
	"cd src/node_modules && ../../node_modules/.bin/tsc"
]));

gulp.task('publish', ['buildSrc'], shell.task([
	"cd src && npm publish"
]));

gulp.task('bundle', function() {
	return require('./tools/bundler').bundle(options.example);
})<|endoftext|>


<commit_before>var gulp                 = require('gulp'),
    useref               = require('gulp-useref'),
    filter               = require('gulp-filter'),
    filelog              = require('gulp-filelog'),
    ngAnnotate           = require('gulp-ng-annotate'),
    uglify               = require('gulp-uglify'),
    rev                  = require('gulp-rev'),
    angularTemplateCache = require('gulp-angular-templatecache'),
    concat               = require('gulp-concat'),
    inject               = require('gulp-inject'),
    minifyCss            = require('gulp-minify-css'),
    minifyHtml           = require('gulp-minify-html'),

    addStream            = require('add-stream'),
    browserSync          = require('browser-sync'),
    del                  = require('del'),
    streamSplicer        = require('stream-splicer'),
    karma                = require('karma').server;

gulp.task('gh-pages', ['build'], function() {
  console.log('Copying files to project root:')

  // copy stuff in build dir to project root
  return gulp.src('build/**/*')
    .pipe(gulp.dest('.'))
    .pipe(filelog());
});

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

gulp.task('prep-index.html', ['clean', 'prep-scripts', 'prep-styles'], function() {
  var vendorScripts = gulp.src('build/scripts/vendor-*.js', {read: false});
  var appScripts = gulp.src('build/scripts/app-*.js', {read: false});

  var vendorStyles = gulp.src('build/styles/vendor-*.css', {read: false});

  return gulp.src('app/index.html')
    // replace script tags in inject/endinject with vendor.js
    .pipe(inject(vendorScripts, {
      addRootSlash: false,
      ignorePath: 'build/',
      name: 'inject-vendor-scripts'
    }))
    // replace script tags in inject/endinject with app.js
    .pipe(inject(appScripts, {
      addRootSlash: false,
      ignorePath: 'build/',
      name: 'inject-app-scripts'
    }))
    .pipe(minifyIncomingHtml())
    .pipe(gulp.dest('build'));
});

gulp.task('prep-scripts', ['prep-app.js', 'prep-vendor.js']);

gulp.task('prep-app.js', ['clean'], function() {
  return gulp.src('app/index.html')
    // concat files between build/endbuild comments into a file named according
    // to build block params
    .pipe(useref.assets())
    // filter down to just app file
    .pipe(filter('app.js'))
    // tack inlined templates onto app.js
    .pipe(addStream.obj(inlineTemplates()))
    .pipe(concat('app.js'))
    // make our angular code minifiable
    .pipe(ngAnnotate())
    .pipe(minifyRevAndWrite());
});

function inlineTemplates() {
  var justTemplates = filter(function(vinylFile) {
    var path = vinylFile.path;

    // nothing from bower and not the main html page
    return !/app\/bower_components/.test(path) && !/index.html/.test(path);
  });

  return gulp.src('app/**/*.html')
    .pipe(justTemplates)
    .pipe(minifyIncomingHtml())
    // create js file that puts html in angular's $templateCache
    .pipe(angularTemplateCache({
      module: 'app.templates'
    }));
}

function minifyIncomingHtml() {
  // remove marker comments and other stuff
  return minifyHtml({
    // preserve empty attributes (removing would break our angular stuff)
    empty: true,
    // preserve quotes
    quotes: true
  });
}

function minifyRevAndWrite() {
  return streamSplicer.obj([
    // minify
    uglify(),
    // give unique name based on file contents
    rev(),
    gulp.dest('build/scripts')
  ]);
}

gulp.task('prep-vendor.js', ['clean'], function() {
  return gulp.src('app/index.html')
    // concat files between build/endbuild comments into a file named according
    // to build block params
    .pipe(useref.assets())
    // filter down to just vendor file
    .pipe(filter('vendor.js'))
    .pipe(minifyRevAndWrite());
});

gulp.task('prep-styles', ['clean'], function() {
  return gulp.src('app/index.html')
    // concat files between build/endbuild comments into a file named according
    // to build block params
    .pipe(useref.assets())
    // filter down to just css files
    .pipe(filter('*.css'))
    // minify
    .pipe(minifyCss())
    // give unique filename based on file contents
    .pipe(rev())
    .pipe(gulp.dest('build/styles'));
});

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

gulp.task('watch', function(cb) {
  browserSync({
    server: {
      baseDir: './app/',
      // don't mirror clicks, scroll, forms across browsers
      ghostMode: false
    }
  },
  function() {
    gulp.watch([
      'app/**/*.html',
      'app/**/*.js',
      'app/**/*.css'
    ], {}, browserSync.reload);

    // signal to gulp that this task is done
    cb();
  });
});

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

gulp.task('default', function() {
  console.log();
  console.log('Available tasks:');
  console.log();
  console.log('  watch      Serve page locally with auto-refresh');
  console.log('  build      Create deployable files in build/');
  console.log('  gh-pages   Move deployable files to project root dir');
  console.log('  test       Run karma once. Use `npm run karma` to auto-test on every change');
  console.log();
});
<commit_msg>npm test is good enough for running tests<commit_after>var gulp                 = require('gulp'),
    useref               = require('gulp-useref'),
    filter               = require('gulp-filter'),
    filelog              = require('gulp-filelog'),
    ngAnnotate           = require('gulp-ng-annotate'),
    uglify               = require('gulp-uglify'),
    rev                  = require('gulp-rev'),
    angularTemplateCache = require('gulp-angular-templatecache'),
    concat               = require('gulp-concat'),
    inject               = require('gulp-inject'),
    minifyCss            = require('gulp-minify-css'),
    minifyHtml           = require('gulp-minify-html'),

    addStream            = require('add-stream'),
    browserSync          = require('browser-sync'),
    del                  = require('del'),
    streamSplicer        = require('stream-splicer'),
    karma                = require('karma').server;

gulp.task('gh-pages', ['build'], function() {
  console.log('Copying files to project root:')

  // copy stuff in build dir to project root
  return gulp.src('build/**/*')
    .pipe(gulp.dest('.'))
    .pipe(filelog());
});

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

gulp.task('prep-index.html', ['clean', 'prep-scripts', 'prep-styles'], function() {
  var vendorScripts = gulp.src('build/scripts/vendor-*.js', {read: false});
  var appScripts = gulp.src('build/scripts/app-*.js', {read: false});

  var vendorStyles = gulp.src('build/styles/vendor-*.css', {read: false});

  return gulp.src('app/index.html')
    // replace script tags in inject/endinject with vendor.js
    .pipe(inject(vendorScripts, {
      addRootSlash: false,
      ignorePath: 'build/',
      name: 'inject-vendor-scripts'
    }))
    // replace script tags in inject/endinject with app.js
    .pipe(inject(appScripts, {
      addRootSlash: false,
      ignorePath: 'build/',
      name: 'inject-app-scripts'
    }))
    .pipe(minifyIncomingHtml())
    .pipe(gulp.dest('build'));
});

gulp.task('prep-scripts', ['prep-app.js', 'prep-vendor.js']);

gulp.task('prep-app.js', ['clean'], function() {
  return gulp.src('app/index.html')
    // concat files between build/endbuild comments into a file named according
    // to build block params
    .pipe(useref.assets())
    // filter down to just app file
    .pipe(filter('app.js'))
    // tack inlined templates onto app.js
    .pipe(addStream.obj(inlineTemplates()))
    .pipe(concat('app.js'))
    // make our angular code minifiable
    .pipe(ngAnnotate())
    .pipe(minifyRevAndWrite());
});

function inlineTemplates() {
  var justTemplates = filter(function(vinylFile) {
    var path = vinylFile.path;

    // nothing from bower and not the main html page
    return !/app\/bower_components/.test(path) && !/index.html/.test(path);
  });

  return gulp.src('app/**/*.html')
    .pipe(justTemplates)
    .pipe(minifyIncomingHtml())
    // create js file that puts html in angular's $templateCache
    .pipe(angularTemplateCache({
      module: 'app.templates'
    }));
}

function minifyIncomingHtml() {
  // remove marker comments and other stuff
  return minifyHtml({
    // preserve empty attributes (removing would break our angular stuff)
    empty: true,
    // preserve quotes
    quotes: true
  });
}

function minifyRevAndWrite() {
  return streamSplicer.obj([
    // minify
    uglify(),
    // give unique name based on file contents
    rev(),
    gulp.dest('build/scripts')
  ]);
}

gulp.task('prep-vendor.js', ['clean'], function() {
  return gulp.src('app/index.html')
    // concat files between build/endbuild comments into a file named according
    // to build block params
    .pipe(useref.assets())
    // filter down to just vendor file
    .pipe(filter('vendor.js'))
    .pipe(minifyRevAndWrite());
});

gulp.task('prep-styles', ['clean'], function() {
  return gulp.src('app/index.html')
    // concat files between build/endbuild comments into a file named according
    // to build block params
    .pipe(useref.assets())
    // filter down to just css files
    .pipe(filter('*.css'))
    // minify
    .pipe(minifyCss())
    // give unique filename based on file contents
    .pipe(rev())
    .pipe(gulp.dest('build/styles'));
});

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

gulp.task('watch', function(cb) {
  browserSync({
    server: {
      baseDir: './app/',
      // don't mirror clicks, scroll, forms across browsers
      ghostMode: false
    }
  },
  function() {
    gulp.watch([
      'app/**/*.html',
      'app/**/*.js',
      'app/**/*.css'
    ], {}, browserSync.reload);

    // signal to gulp that this task is done
    cb();
  });
});

gulp.task('default', function() {
  console.log();
  console.log('Available tasks:');
  console.log();
  console.log('  watch      Serve page locally with auto-refresh');
  console.log('  build      Create deployable files in build/');
  console.log('  gh-pages   Move deployable files to project root dir');
  console.log();
});
<|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/'))
        .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']);

<commit_msg>fix version bump gulp task related to double-digit patch versions<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');
var concat = require('gulp-concat');

gulp.task('default', function() {
    gulp.src(['app/bower_components/**/*.min.js'])
      .pipe(concat('app/dist_components.js'))
      .pipe(gulp.dest('.'))

    gulp.src(['app/app.js', 'app/new/new.js', 'app/change/change.js', 'app/list/list.js'])
      .pipe(concat('app/dist.js'))
      .pipe(gulp.dest('.'))

    gulp.src(['app/bower_components/bootstrap/dist/css/bootstrap.min.css', 'app/bower_components/angular-ui-select/dist/select.min.css', 'app/bower_components/angucomplete-alt/angucomplete-alt.css'])
      .pipe(concat('app/dist.css'))
      .pipe(gulp.dest('.'))
});

gulp.task('js', function() {
    gulp.src(['app/app.js', 'app/new/new.js', 'app/change/change.js', 'app/list/list.js'])
      .pipe(concat('app/dist.js'))
      .pipe(gulp.dest('.'))
});

gulp.task('css', function() {
    gulp.src(['app/bower_components/bootstrap/dist/css/bootstrap.min.css', 'app/bower_components/angular-ui-select/dist/select.min.css', 'app/bower_components/angucomplete-alt/angucomplete-alt.css'])
      .pipe(concat('app/dist.css'))
      .pipe(gulp.dest('.'))
});
<commit_msg>rewriting the gulpfile and adding a watch task for convenience<commit_after>var gulp = require('gulp');
var concat = require('gulp-concat');
var paths = {
  code: ['app/app.js', 'app/new/new.js', 'app/change/change.js', 'app/list/list.js']
};

gulp.task('deps', function() {
    gulp.src(['app/bower_components/**/*.min.js'])
      .pipe(concat('app/dist_components.js'))
      .pipe(gulp.dest('.'))

    gulp.src(['app/bower_components/bootstrap/dist/css/bootstrap.min.css', 'app/bower_components/angular-ui-select/dist/select.min.css', 'app/bower_components/angucomplete-alt/angucomplete-alt.css'])
      .pipe(concat('app/dist.css'))
      .pipe(gulp.dest('.'))
});

gulp.task('js', function() {
    gulp.src(paths.code)
      .pipe(concat('app/dist.js'))
      .pipe(gulp.dest('.'))
});

gulp.task('css', function() {
    gulp.src(['app/bower_components/bootstrap/dist/css/bootstrap.min.css', 'app/bower_components/angular-ui-select/dist/select.min.css', 'app/bower_components/angucomplete-alt/angucomplete-alt.css'])
      .pipe(concat('app/dist.css'))
      .pipe(gulp.dest('.'))
});

gulp.task('watch', function() {
    gulp.watch(paths.code, ['js']);
});

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


<commit_before>var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var colors = require('colors/safe');

var sassMainPath = 'src/main.scss';
var distPath = 'dist/';

var demoScss = 'demo/demo.scss';
var demoFolder = 'demo/';

gulp
    .task('default', ['watch', 'scss', 'demo-scss'])
    .task('scss', function() {
        sassBuild(sassMainPath, distPath);
    })
    .task('demo-scss', function() {
        sassBuild(demoScss, demoFolder);
    })
    .task('watch', function () {
        $.livereload.listen();
        gulp.watch('src/**/*.scss', ['scss']);
        gulp.watch(demoScss, ['demo-scss']);
    });

function sassBuild(sassMainPath, distPath) {
    gulp.src(sassMainPath)
        .pipe($.plumber())
        .pipe($.sourcemaps.init())
        .pipe($.sass({
            outputStyle: 'nested',
            errLogToConsole: false,
            onError: function(err) {
                return console.log(
                    colors.red.underline(err.message + "\nin " + err.file + "\non " + err.line + ":" + err.column)
                );
            }
        }))
        .pipe($.autoprefixer())
        .pipe($.sourcemaps.write('./'))
        .pipe(gulp.dest(distPath))
        .pipe($.livereload());
}<commit_msg>Added to livereload watching demo/index.html<commit_after>var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var colors = require('colors/safe');

var sassMainPath = 'src/main.scss';
var distPath = 'dist/';

var demoScss = 'demo/demo.scss';
var demoFolder = 'demo/';

gulp
    .task('default', ['watch', 'scss', 'demo-scss'])
    .task('scss', function() {
        sassBuild(sassMainPath, distPath);
    })
    .task('demo-scss', function() {
        sassBuild(demoScss, demoFolder);
    })
    .task('watch', function () {
        $.livereload.listen();
        gulp.watch('src/**/*.scss', ['scss']);
        gulp.watch(demoScss, ['demo-scss']);

        gulp.watch('demo/index.html')
            .on('change', function (e) {
                $.livereload.changed(e.path);
            });
    });

function sassBuild(sassMainPath, distPath) {
    gulp.src(sassMainPath)
        .pipe($.plumber())
        .pipe($.sourcemaps.init())
        .pipe($.sass({
            outputStyle: 'nested',
            errLogToConsole: false,
            onError: function(err) {
                return console.log(
                    colors.red.underline(err.message + "\nin " + err.file + "\non " + err.line + ":" + err.column)
                );
            }
        }))
        .pipe($.autoprefixer())
        .pipe($.sourcemaps.write('./'))
        .pipe(gulp.dest(distPath))
        .pipe($.livereload());
}<|endoftext|>


<commit_before>// -- SETUP --------------------------------------------------------------------

var gulp = require("gulp");
var sourcemaps = require("gulp-sourcemaps");
var liveReload = require("gulp-livereload");
var uglify = require("gulp-uglify");
var newer = require("gulp-newer");
var ghPages = require("gulp-gh-pages");
var open = require("gulp-open");
var gutil = require("gulp-util");
var jshint = require("gulp-jshint"); // Requires npm jshint
var stylish = require("jshint-stylish");
var browserify = require("browserify");
var source = require("vinyl-source-stream");
var buffer = require("vinyl-buffer");
var del = require("del");
var express = require("express");
var path = require("path");
var fs = require("fs");
var runSequence = require("run-sequence");
var gulpif = require("gulp-if");
var rename = require("gulp-rename");

// Check the command line to see if this is a production build
var isProduction = (gutil.env.p || gutil.env.production);
console.log("Build environment: " + (isProduction ? "production" : "debug"));

// -- PATHS --------------------------------------------------------------------

var globalName = "BboxAlignedText";
var mainFilename = "bbox-aligned-text.js";
var paths = {
    examples: "examples/",
    jsLib: ["lib/**/*.js"],
    jsEntry: ["lib/" + mainFilename],
    dest: "dist"
};

// -- BUILD TASKS --------------------------------------------------------------
// These gulp tasks take everything that is in src/, process them and output
// them into lib/.

// Combine, sourcemap and uglify JS libraries into main.js. This uses browserify
// (CommonJS-style modules).
gulp.task("js-browserify", function() {
    var b = browserify({
        entries: paths.jsEntry,
        debug: true,
        // Build module in a universal way, so that it can be loaded with
        // CommonJS or can be loaded to a global variable
        standalone: globalName
    })
    return b.bundle()
        .on("error", gutil.log)
        .pipe(source(mainFilename))
        .pipe(buffer())
        .pipe(gulp.dest(paths.dest))
        .pipe(sourcemaps.init({ loadMaps: true }))
            .pipe(uglify())
            .on("error", gutil.log)
        .pipe(sourcemaps.write())
        .pipe(rename({ extname: ".min.js" }))
        .pipe(gulp.dest(paths.dest))
        .pipe(liveReload());
});

// Lint only our custom JS.
gulp.task("jslint", function() {
    return gulp.src(paths.jsLib)
        .pipe(jshint())
        .pipe(jshint.reporter(stylish));
});

// The build task will run all the individual build-related tasks above.
gulp.task("build", [
    "jslint",
    "js-browserify"
]);

// -- RUNNING TASKS ------------------------------------------------------------
// These gulp tasks handle everything related to running the lib.  Starting a
// local server, watching for changes to files, opening a browser, etc.

// Watch for changes and then trigger the appropraite build task.  This also
// starts a LiveReload server that can tell the browser to refresh the page.
gulp.task("watch", function () {
    liveReload.listen(); // Start the LiveReload server
    gulp.watch(paths.jsLib, ["jslint", "js-browserify"]);
});

// Start an express server that serves everything in examples/ & dist/ to
// localhost:8080/.
gulp.task("express-server", function () {
    var app = express();
    app.use(express.static(path.join(__dirname, paths.dest)));
    app.use(express.static(path.join(__dirname, paths.examples)));
    app.listen(8080);
});

// Automatically open localhost:8080/ in the browser using whatever the default
// browser.
gulp.task("open", function() {
    return gulp.src(__filename)
        .pipe(open({ uri: "http://127.0.0.1:8080" }));
});

// The build task will run all the individual run-related tasks above.
gulp.task("run", [
    "watch",
    "express-server",
    "open"
]);

// -- DEPLOYING TASKS ----------------------------------------------------------
// These gulp tasks handle everything related to deploying the site to live
// server(s).

// Push files in build/ to a gh-pages branch
gulp.task("push:gh-pages", function () {
    return gulp.src("./" + paths.dest + "/**/*")
        .pipe(ghPages({
            // PLACE REAL URL HERE
            remoteUrl: "https://github.com/blahblah/blahblah.git"
        }));
});

// Build & deploy build/ folder to gh-pages and then clean up
gulp.task("deploy:gh-pages", function () {
    return runSequence("build", "push:gh-pages", "clean:publish");
});

// -- CLEANING TASKS ----------------------------------------------------------
// These gulp tasks handle deleting files.

// Delete all of the build folder contents.
gulp.task("clean:lib", function () {
    return del(["./lib/**/*"]);
});

// Clean up after the gh-pages deploy
gulp.task("clean:publish", function () {
    return del(["./.publish"]);
});

// -- DEFAULT TASK -------------------------------------------------------------
// This gulp task runs automatically when you don't specify task.

// Build and then run it.
gulp.task("default", function(callback) {
    runSequence("build", "run", callback);
});<commit_msg>Gulp - serve dist/ from "dist/" mount point<commit_after>// -- SETUP --------------------------------------------------------------------

var gulp = require("gulp");
var sourcemaps = require("gulp-sourcemaps");
var liveReload = require("gulp-livereload");
var uglify = require("gulp-uglify");
var newer = require("gulp-newer");
var ghPages = require("gulp-gh-pages");
var open = require("gulp-open");
var gutil = require("gulp-util");
var jshint = require("gulp-jshint"); // Requires npm jshint
var stylish = require("jshint-stylish");
var browserify = require("browserify");
var source = require("vinyl-source-stream");
var buffer = require("vinyl-buffer");
var del = require("del");
var express = require("express");
var path = require("path");
var fs = require("fs");
var runSequence = require("run-sequence");
var gulpif = require("gulp-if");
var rename = require("gulp-rename");

// Check the command line to see if this is a production build
var isProduction = (gutil.env.p || gutil.env.production);
console.log("Build environment: " + (isProduction ? "production" : "debug"));

// -- PATHS --------------------------------------------------------------------

var globalName = "BboxAlignedText";
var mainFilename = "bbox-aligned-text.js";
var paths = {
    examples: "examples/",
    jsLib: ["lib/**/*.js"],
    jsEntry: ["lib/" + mainFilename],
    dest: "dist"
};

// -- BUILD TASKS --------------------------------------------------------------
// These gulp tasks take everything that is in src/, process them and output
// them into lib/.

// Combine, sourcemap and uglify JS libraries into main.js. This uses browserify
// (CommonJS-style modules).
gulp.task("js-browserify", function() {
    var b = browserify({
        entries: paths.jsEntry,
        debug: true,
        // Build module in a universal way, so that it can be loaded with
        // CommonJS or can be loaded to a global variable
        standalone: globalName
    })
    return b.bundle()
        .on("error", gutil.log)
        .pipe(source(mainFilename))
        .pipe(buffer())
        .pipe(gulp.dest(paths.dest))
        .pipe(sourcemaps.init({ loadMaps: true }))
            .pipe(uglify())
            .on("error", gutil.log)
        .pipe(sourcemaps.write())
        .pipe(rename({ extname: ".min.js" }))
        .pipe(gulp.dest(paths.dest))
        .pipe(liveReload());
});

// Lint only our custom JS.
gulp.task("jslint", function() {
    return gulp.src(paths.jsLib)
        .pipe(jshint())
        .pipe(jshint.reporter(stylish));
});

// The build task will run all the individual build-related tasks above.
gulp.task("build", [
    "jslint",
    "js-browserify"
]);

// -- RUNNING TASKS ------------------------------------------------------------
// These gulp tasks handle everything related to running the lib.  Starting a
// local server, watching for changes to files, opening a browser, etc.

// Watch for changes and then trigger the appropraite build task.  This also
// starts a LiveReload server that can tell the browser to refresh the page.
gulp.task("watch", function () {
    liveReload.listen(); // Start the LiveReload server
    gulp.watch(paths.jsLib, ["jslint", "js-browserify"]);
});

// Start an express server that serves everything in examples/ & dist/ to
// localhost:8080/.
gulp.task("express-server", function () {
    var app = express();
    app.use(express.static(path.join(__dirname, paths.examples)));
    // Serve up dist/ on the server, mounted at "dist/". This way the examples
    // appear to be looking in the right place for the script.
    app.use("/" + paths.dest, express.static(path.join(__dirname, paths.dest)));
    app.listen(8080);
});

// Automatically open localhost:8080/ in the browser using whatever the default
// browser.
gulp.task("open", function() {
    return gulp.src(__filename)
        .pipe(open({ uri: "http://127.0.0.1:8080" }));
});

// The build task will run all the individual run-related tasks above.
gulp.task("run", [
    "watch",
    "express-server",
    "open"
]);

// -- DEPLOYING TASKS ----------------------------------------------------------
// These gulp tasks handle everything related to deploying the site to live
// server(s).

// Push files in build/ to a gh-pages branch
gulp.task("push:gh-pages", function () {
    return gulp.src("./" + paths.dest + "/**/*")
        .pipe(ghPages({
            // PLACE REAL URL HERE
            remoteUrl: "https://github.com/blahblah/blahblah.git"
        }));
});

// Build & deploy build/ folder to gh-pages and then clean up
gulp.task("deploy:gh-pages", function () {
    return runSequence("build", "push:gh-pages", "clean:publish");
});

// -- CLEANING TASKS ----------------------------------------------------------
// These gulp tasks handle deleting files.

// Delete all of the build folder contents.
gulp.task("clean:lib", function () {
    return del(["./lib/**/*"]);
});

// Clean up after the gh-pages deploy
gulp.task("clean:publish", function () {
    return del(["./.publish"]);
});

// -- DEFAULT TASK -------------------------------------------------------------
// This gulp task runs automatically when you don't specify task.

// Build and then run it.
gulp.task("default", function(callback) {
    runSequence("build", "run", callback);
});<|endoftext|>


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

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

var shell = require('gulp-shell');
var git = require('gulp-git');
var watch;

gulp.task('package', function(callback){
    watch = false;
    browserifyShare(callback);
});

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

gulp.task('package-watch', function(callback){
    watch = true;
    browserifyShare(callback);
});

gulp.task('watch', ['package-watch'], function(){

    //Start live reload server
    livereload.listen();
});

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

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

    var tsResult = gulp.src(['./tests/**/*.ts', './node_modules/awayjs-**/build/*.d.ts', './build/awayjs-player.d.ts'])
        .pipe(sourcemaps.init())
        .pipe(typescript(tsProject));

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

function browserifyShare(callback) {
    var b = browserify({
        debug: true,
        paths: ['../'],
        cache: {},
        packageCache: {},
        fullPaths: true
    });

    b.plugin('tsify', {target:'ES5', sourceRoot:'../', noExternalResolve: true, declarationFiles: './node_modules/awayjs-**/build/*.d.ts', declarationOutput: './build/awayjs-player.d.ts'});

    glob('./node_modules/awayjs-**/lib/**/*.ts', {}, function (error, files) {
        files.forEach(function (file) {
            b.external(file);
        });
    });

    glob('./lib/**/*.ts', {}, function (error, files) {

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

        if (watch) {
            b = watchify(b);
            b.on('update', function(){
                return b.bundle()
                    .pipe(source('awayjs-player.js'))
                    .pipe(gulp.dest('./build'))
                    .pipe(livereload());
            });
        }

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

function unixStylePath(filePath) {
    return filePath.split(path.sep).join('/');
}

gulp.task('commit', ['package-min'], function(callback){

    git.status({args:'--porcelain'}, function(err, stdout) {
        var buildModified = false;
        var packageModified = false;

        if (err)
            throw err;

        stdout = stdout.split('\n');
        stdout.forEach(function (line) {
            if (line.indexOf('build/') != -1)
                buildModified = true;
            else if (line.indexOf(' M ') != -1)
                packageModified = true;
        });

        if (packageModified) {
            console.log('un-commited changes detected in package');
            console.log('Please git commit all changes outside of build before continuing');
        } else {
            if (buildModified) {
                gulp.src('./build/*')
                    .pipe(git.commit('update build files'))
                    .on('error', function(err) {
                        throw err;
                    })
                    .on('end', callback);
            } else {
                callback();
            }
        }
    });
});

gulp.task('version', ['commit'], function(callback){
    gulp.src('')
        .pipe(shell([
            'npm version patch'
        ])).on('error', function(err) {
            throw err;
        }).on('end', callback);
});

gulp.task('push', ['version'], function(callback){
    gulp.src('')
        .pipe(shell([
            'git push origin dev --tags'
        ])).on('error', function(err) {
            throw err;
        }).on('end', callback);
});

gulp.task('publish', ['push'], function(callback){
    gulp.src('')
        .pipe(shell([
            'npm publish'
        ])).on('error', function(err) {
            throw err;
        }).on('end', callback);
});<commit_msg>node.js support<commit_after>var gulp = require('gulp');
var glob = require('glob');
var path = require('path');
var browserify  = require('browserify');
var source = require('vinyl-source-stream');
var transform = require('vinyl-transform');
var exorcist = require('exorcist');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var watchify = require('watchify');
var livereload = require('gulp-livereload');

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

var shell = require('gulp-shell');
var git = require('gulp-git');
var watch;

gulp.task('package', function(callback){
    watch = false;
    browserifyShare(callback);
});

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

gulp.task('package-watch', function(callback){
    watch = true;
    browserifyShare(callback);
});

gulp.task('watch', ['package-watch'], function(){

    //Start live reload server
    livereload.listen();
});

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

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

    var tsResult = gulp.src(['./tests/**/*.ts', './node_modules/awayjs-**/build/*.d.ts', './build/awayjs-player.d.ts'])
        .pipe(sourcemaps.init())
        .pipe(typescript(tsProject));

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

function browserifyShare(callback) {
    var b = browserify({
        debug: true,
        paths: ['../'],
        cache: {},
        packageCache: {},
        fullPaths: true
    });

    b.plugin('tsify', {target:'ES5', sourceRoot:'../', noExternalResolve: true, declarationFiles: './node_modules/awayjs-**/build/*.d.ts', declarationOutput: './build/awayjs-player.d.ts'});

    glob('./node_modules/awayjs-**/lib/**/*.ts', {}, function (error, files) {
        files.forEach(function (file) {
            b.external(file);
        });
    });

    glob('./lib/**/*.ts', {}, function (error, files) {

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

        if (watch) {
            b = watchify(b);
            b.on('update', function(){
                return b.bundle()
                    .pipe(source('awayjs-player.js'))
                    .pipe(gulp.dest('./build'))
                    .pipe(livereload());
            });
        }

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

function unixStylePath(filePath) {
    return filePath.split(path.sep).join('/');
}

gulp.task('commit', ['package-min'], function(callback){

    git.status({args:'--porcelain'}, function(err, stdout) {
        var buildModified = false;
        var packageModified = false;

        if (err)
            throw err;

        stdout = stdout.split('\n');
        stdout.forEach(function (line) {
            if (line.indexOf('build/') != -1)
                buildModified = true;
            else if (line.indexOf(' M ') != -1)
                packageModified = true;
        });

        if (packageModified) {
            console.log('un-commited changes detected in package');
            console.log('Please git commit all changes outside of build before continuing');
        } else {
            if (buildModified) {
                gulp.src('./build/*')
                    .pipe(git.commit('update build files'))
                    .on('error', function(err) {
                        throw err;
                    })
                    .on('end', callback);
            } else {
                callback();
            }
        }
    });
});

gulp.task('version', ['commit'], function(callback){
    gulp.src('')
        .pipe(shell([
            'npm version patch'
        ])).on('error', function(err) {
            throw err;
        }).on('end', callback);
});

gulp.task('push', ['version'], function(callback){
    gulp.src('')
        .pipe(shell([
            'git push origin dev --tags'
        ])).on('error', function(err) {
            throw err;
        }).on('end', callback);
});

gulp.task('publish', ['push'], function(callback){
    gulp.src('')
        .pipe(shell([
            'npm publish'
        ])).on('error', function(err) {
            throw err;
        }).on('end', callback);
});
gulp.task('compile', function() {
    var tsProject = typescript.createProject({
        declarationFiles: true,
        noExternalResolve: true,
        target: 'ES5',
        module: 'commonjs',
        sourceRoot: './awayjs-player/lib/',
        moduleResolution: 'classic'
    });

    var tsResult = gulp.src([
        './lib/**/*.ts',
        './node_modules/awayjs-**/build/*.d.ts'
    ])
        //.pipe(sourcemaps.init())
        .pipe(typescript(tsProject));

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


<commit_before>export const serviceurl = {
  // Local

/*   apiURLSSOManager: "http://localhost:9002/sso-manager",
  apiURLDatiGov: "http://localhost:9000/dati-gov/v1",
  apiURLCatalog: "http://localhost:9001/catalog-manager/v1",
  apiURLIngestion: "http://localhost:9002/ingestion-manager/v1",
  apiURLSecurity: "http://localhost:9002/security-manager/v1", */

  //MOCK
/*   apiURLDatiGov: "http://localhost:3001/dati-gov/v1",
  apiURLCatalog: "http://localhost:3001/catalog-manager/v1",
  apiURLIngestion: "http://localhost:3001/ingestion-manager/v1",
  apiURLSecurity: "http://localhost:3001/catalog-manager/v1",
  apiURLSSOManager: "http://localhost:3001/sso-manager/v1",
*/
  // INTERNAL
/*  apiURLSSOManager: "http://security-manager.default.svc.cluster.local:9000/security-manager/sso-manager",
 apiURLDatiGov: "http://datipubblici.default.svc.cluster.local:9000/dati-gov/v1",
 apiURLCatalog: "http://catalog-manager.default.svc.cluster.local:9000/catalog-manager/v1",
 apiURLSecurity : "http://security-manager.default.svc.cluster.local:9000/security-manager/v1", */

 // EXTERNAL
 apiURLSSOManager: "https://api.daf.teamdigitale.it/sso-manager",
 apiURLDatiGov: "https://api.daf.teamdigitale.it/dati-gov/v1",
 apiURLCatalog: "https://api.daf.teamdigitale.it/catalog-manager/v1",
 apiURLSecurity : "https://api.daf.teamdigitale.it/security-manager/v1",
 apiURLDataset : "https://api.daf.teamdigitale.it/dataset-manager/v1",

 urlMetabase: 'https://graph.daf.teamdigitale.it',
 urlSuperset: 'https://bi.daf.teamdigitale.it',
 urlJupiter: 'https://datascience.daf.teamdigitale.it',

 // TEST
 //apiURLSSOManager: "http://datipubblici-private.integrazione.daf:9002/sso-manager",
 //apiURLDatiGov: "http://datipubblici-private.integrazione.daf:9000/dati-gov/v1",
 //apiURLCatalog: "http://datipubblici-private.integrazione.daf:9001/catalog-manager/v1",
 //apiURLIngestion: "http://service:9002/ingestion-manager/v1",
 //apiURLSecurity: "http://datipubblici-private.integrazione.daf9002/security-manager/v1",

/*  urlMetabase: 'http://metabase.integrazione.daf',
 urlSuperset: 'http://superset.integrazione.daf',
 urlJupiter: 'http://datascience.daf.teamdigitale.governo.it', */

 // URL ONTONETHUB
 urlSemantic: "https://api.daf.teamdigitale.it/stanbol/ontonethub/ontologies/find",
 // URL CNR
 //urlSemantic: 'http://stlab.istc.cnr.it/ontonethub/api/find',

 domain: ".daf.teamdigitale.it"
 /* domain: ".integrazione.daf", */
}<commit_msg>fix serviceurl<commit_after>export const serviceurl = {
  // Local

/*   apiURLSSOManager: "http://localhost:9002/sso-manager",
  apiURLDatiGov: "http://localhost:9000/dati-gov/v1",
  apiURLCatalog: "http://localhost:9001/catalog-manager/v1",
  apiURLIngestion: "http://localhost:9002/ingestion-manager/v1",
  apiURLSecurity: "http://localhost:9002/security-manager/v1", */

  //MOCK
/*   apiURLDatiGov: "http://localhost:3001/dati-gov/v1",
  apiURLCatalog: "http://localhost:3001/catalog-manager/v1",
  apiURLIngestion: "http://localhost:3001/ingestion-manager/v1",
  apiURLSecurity: "http://localhost:3001/catalog-manager/v1",
  apiURLSSOManager: "http://localhost:3001/sso-manager/v1",
*/
  // INTERNAL
/*  apiURLSSOManager: "http://security-manager.default.svc.cluster.local:9000/security-manager/sso-manager",
 apiURLDatiGov: "http://datipubblici.default.svc.cluster.local:9000/dati-gov/v1",
 apiURLCatalog: "http://catalog-manager.default.svc.cluster.local:9000/catalog-manager/v1",
 apiURLSecurity : "http://security-manager.default.svc.cluster.local:9000/security-manager/v1", */

 // EXTERNAL
/*  apiURLSSOManager: "https://api.daf.teamdigitale.it/sso-manager",
 apiURLDatiGov: "https://api.daf.teamdigitale.it/dati-gov/v1",
 apiURLCatalog: "https://api.daf.teamdigitale.it/catalog-manager/v1",
 apiURLSecurity : "https://api.daf.teamdigitale.it/security-manager/v1",
 apiURLDataset : "https://api.daf.teamdigitale.it/dataset-manager/v1", */

 apiURLSSOManager: "https://security-manager.daf.teamdigitale.it/sso-manager",
 apiURLDatiGov: "https://datipubblici.daf.teamdigitale.it/dati-gov/v1",
 apiURLCatalog: "https://catalog-manager.daf.teamdigitale.it/catalog-manager/v1",
 apiURLSecurity : "https://security-manager.daf.teamdigitale.it/security-manager/v1",
 apiURLDataset : "https://dataset-manager.daf.teamdigitale.it/dataset-manager/v1",

 urlMetabase: 'https://graph.daf.teamdigitale.it',
 urlSuperset: 'https://bi.daf.teamdigitale.it',
 urlJupiter: 'https://datascience.daf.teamdigitale.it',

 // TEST
 //apiURLSSOManager: "http://datipubblici-private.integrazione.daf:9002/sso-manager",
 //apiURLDatiGov: "http://datipubblici-private.integrazione.daf:9000/dati-gov/v1",
 //apiURLCatalog: "http://datipubblici-private.integrazione.daf:9001/catalog-manager/v1",
 //apiURLIngestion: "http://service:9002/ingestion-manager/v1",
 //apiURLSecurity: "http://datipubblici-private.integrazione.daf9002/security-manager/v1",

/*  urlMetabase: 'http://metabase.integrazione.daf',
 urlSuperset: 'http://superset.integrazione.daf',
 urlJupiter: 'http://datascience.daf.teamdigitale.governo.it', */

 // URL ONTONETHUB
 urlSemantic: "https://api.daf.teamdigitale.it/stanbol/ontonethub/ontologies/find",
 // URL CNR
 //urlSemantic: 'http://stlab.istc.cnr.it/ontonethub/api/find',

 domain: ".daf.teamdigitale.it"
 /* domain: ".integrazione.daf", */
}<|endoftext|>


<commit_before>import React from 'react';
import { QueryRenderer, graphql } from 'react-relay';
import { Link } from 'react-router-dom';
import relay from '../relay.js';

const defaultNestingOrder = ['countyCode', 'functionalClass', 'factorGroup']; //allow hierarchy by factorGroup via toggle

const q = graphql`
  query RegionStationsQuery(
    $ctyCond: NysCountyCondition!
    $metaCond: StationMetadatumCondition!
    $locCond: StationLocationDatumCondition!
  ) {
    allNysdotSeasonalAdjustmentFactorGroupDescriptions {
      edges {
        node {
          factorGroup
          shortDescription
          longDescription
        }
      }
    }
    allNysdotFunctionalClassificationCodeDescriptions {
      edges {
        node {
          code
          distinctor
          description
        }
      }
    }
    allNysCounties(condition: $ctyCond) {
      edges {
        node {
          rc
          name
        }
      }
    }
    allStationLocationData(condition: $locCond) {
      edges {
        node {
          stationId
          muni
          tdvRoute
          begindesc
          enddesc
        }
      }
    }
    allStationMetadata(condition: $metaCond) {
      edges {
        node {
          stationId
          countyCode
          functionalClass
          factorGroup
        }
      }
    }
  }
`;

function parser(d, nestingOrder = defaultNestingOrder) {
  const {
    allNysdotSeasonalAdjustmentFactorGroupDescriptions: adjustmentFactors,
    allNysdotFunctionalClassificationCodeDescriptions: functionalClassifications,
    allNysCounties: counties,
    allStationLocationData: stationLocationData,
    allStationMetadata: stationMetadata
  } = d;

  const decoder = {
    countyCode: counties.edges.reduce((acc, { node: n }) => {
      acc[n.rc] = `${n.name} County`;
      return acc;
    }, {}),

    functionalClass: functionalClassifications.edges.reduce(
      (acc, { node: n }) => {
        const { code, distinctor, description } = n;

        const prefix = distinctor
          .split('_')
          .pop()
          .split('')
          .map((c, i) => (i > 0 ? c.toLowerCase() : c))
          .join('');
        acc[code] = `Functional Class ${code}: ${prefix} ${description}`;
        return acc;
      },
      {}
    ),

    factorGroup: adjustmentFactors.edges.reduce((acc, { node: n }) => {
      // acc[n.factorGroup] = n.shortDescription;
      acc[n.factorGroup] = `Seasonal Factor Group ${n.factorGroup}`;
      return acc;
    }, {})
  };

  const stationLocations = stationLocationData.edges.reduce(
    (acc, { node: n }) => {
      const muni =
        n.muni &&
        n.muni
          .split(' ')
          .map(s =>
            s
              .split('')
              .map((c, i) => (i > 0 ? c.toLowerCase() : c))
              .join('')
          )
          .join(' ');
      acc[n.stationId] = n.tdvRoute
        ? `${muni}: ${n.tdvRoute} from ${n.begindesc} to ${n.enddesc}`
        : '';
      return acc;
    },
    {}
  );

  const stationData = stationMetadata.edges.reduce((acc, { node: n }) => {
    const [primary, secondary, tertiary] = [
      n[nestingOrder[0]],
      n[nestingOrder[1]],
      n[nestingOrder[2]]
    ];

    const p = acc[primary] || (acc[primary] = {});
    const s = p[secondary] || (p[secondary] = {});
    const t = s[tertiary] || (s[tertiary] = {});

    t[n.stationId] = stationLocations[n.stationId];

    return acc;
  }, {});

  console.log(stationData);

  return { decoder, stationData };
}

export default function Region(props) {
  const { region } = props.match.params;
  const cond = { region };

  // Later offer a UI component that allows user to control nesting order.
  const nestingOrder = defaultNestingOrder;

  const [primary, secondary, tertiary] = nestingOrder;

  return (

Region {region}

      <QueryRenderer
        environment={relay}
        query={q}
        variables={{
          locCond: cond,
          metaCond: cond,
          ctyCond: cond
        }}
        render={({ error, props }) => {
          if (error) {
            return
{error.message}
;
          } else if (props) {
            const { decoder, stationData } = parser(props, nestingOrder);

            // Ummm... yeah... I know.
            return (

                {Object.keys(stationData)
                  .sort()
                  .reduce((accP, primaryKey) => {
                    const secondaryLevel = stationData[primaryKey];
                    accP.push(

{decoder[primary][primaryKey]}

                          {Object.keys(secondaryLevel)
                            .sort()
                            .reduce((accS, secondaryKey) => {
                              const tertiaryLevel =
                                secondaryLevel[secondaryKey];
                              accS.push(

{decoder[secondary][secondaryKey]}

                                    {Object.keys(tertiaryLevel)
                                      .sort()
                                      .reduce((accT, tertiaryKey) => {
                                        const stationsInfo =
                                          tertiaryLevel[tertiaryKey];
                                        accT.push(

                                              {decoder[tertiary][tertiaryKey]}

                                              {Object.keys(stationsInfo)
                                                .sort()
                                                .reduce((accL, stationId) => {
                                                  const location =
                                                    stationsInfo[stationId];
                                                  accL.push(

                                                        <Link
                                                          to={`/station-info/${stationId}`}
                                                        >
                                                           {stationId}
                                                        </Link>

                                                      {location}

                                                  );
                                                  return accL;
                                                }, [])}

                                        );
                                        return accT;
                                      }, [])}

                              );
                              return accS;
                            }, [])}

                    );

                    return accP;
                  }, [])}

            );
          }
          return
Loading
;
        }}
      />

  );
}
<commit_msg>region nested list element sorting.<commit_after>import React from 'react';
import { QueryRenderer, graphql } from 'react-relay';
import { Link } from 'react-router-dom';
import relay from '../relay.js';

const defaultNestingOrder = ['countyCode', 'functionalClass', 'factorGroup']; //allow hierarchy by factorGroup via toggle

const sorters = {
  functionalClass: (a, b) => +a - +b,
  countyCode: null,
  factorGroup: null
};

const q = graphql`
  query RegionStationsQuery(
    $ctyCond: NysCountyCondition!
    $metaCond: StationMetadatumCondition!
    $locCond: StationLocationDatumCondition!
  ) {
    allNysdotSeasonalAdjustmentFactorGroupDescriptions {
      edges {
        node {
          factorGroup
          shortDescription
          longDescription
        }
      }
    }
    allNysdotFunctionalClassificationCodeDescriptions {
      edges {
        node {
          code
          distinctor
          description
        }
      }
    }
    allNysCounties(condition: $ctyCond) {
      edges {
        node {
          rc
          name
        }
      }
    }
    allStationLocationData(condition: $locCond) {
      edges {
        node {
          stationId
          muni
          tdvRoute
          begindesc
          enddesc
        }
      }
    }
    allStationMetadata(condition: $metaCond) {
      edges {
        node {
          stationId
          countyCode
          functionalClass
          factorGroup
        }
      }
    }
  }
`;

function parser(d, nestingOrder = defaultNestingOrder) {
  const {
    allNysdotSeasonalAdjustmentFactorGroupDescriptions: adjustmentFactors,
    allNysdotFunctionalClassificationCodeDescriptions: functionalClassifications,
    allNysCounties: counties,
    allStationLocationData: stationLocationData,
    allStationMetadata: stationMetadata
  } = d;

  const decoder = {
    countyCode: counties.edges.reduce((acc, { node: n }) => {
      acc[n.rc] = `${n.name} County`;
      return acc;
    }, {}),

    functionalClass: functionalClassifications.edges.reduce(
      (acc, { node: n }) => {
        const { code, distinctor, description } = n;

        const prefix = distinctor
          .split('_')
          .pop()
          .split('')
          .map((c, i) => (i > 0 ? c.toLowerCase() : c))
          .join('');
        acc[code] = `Functional Class ${code}: ${prefix} ${description}`;
        return acc;
      },
      {}
    ),

    factorGroup: adjustmentFactors.edges.reduce((acc, { node: n }) => {
      // acc[n.factorGroup] = n.shortDescription;
      acc[n.factorGroup] = `Seasonal Factor Group ${n.factorGroup}`;
      return acc;
    }, {})
  };

  const stationLocations = stationLocationData.edges.reduce(
    (acc, { node: n }) => {
      const muni =
        n.muni &&
        n.muni
          .split(' ')
          .map(s =>
            s
              .split('')
              .map((c, i) => (i > 0 ? c.toLowerCase() : c))
              .join('')
          )
          .join(' ');
      acc[n.stationId] = n.tdvRoute
        ? `${muni}: ${n.tdvRoute} from ${n.begindesc} to ${n.enddesc}`
        : '';
      return acc;
    },
    {}
  );

  const stationData = stationMetadata.edges.reduce((acc, { node: n }) => {
    const [primary, secondary, tertiary] = [
      n[nestingOrder[0]],
      n[nestingOrder[1]],
      n[nestingOrder[2]]
    ];

    const p = acc[primary] || (acc[primary] = {});
    const s = p[secondary] || (p[secondary] = {});
    const t = s[tertiary] || (s[tertiary] = {});

    t[n.stationId] = stationLocations[n.stationId];

    return acc;
  }, {});

  console.log(stationData);

  return { decoder, stationData };
}

export default function Region(props) {
  const { region } = props.match.params;
  const cond = { region };

  // Later offer a UI component that allows user to control nesting order.
  const nestingOrder = defaultNestingOrder;

  const [primary, secondary, tertiary] = nestingOrder;

  return (

Region {region}

      <QueryRenderer
        environment={relay}
        query={q}
        variables={{
          locCond: cond,
          metaCond: cond,
          ctyCond: cond
        }}
        render={({ error, props }) => {
          if (error) {
            return
{error.message}
;
          } else if (props) {
            const { decoder, stationData } = parser(props, nestingOrder);

            // Ummm... yeah... I know.
            return (

                {Object.keys(stationData)
                  .sort(sorters[primary])
                  .reduce((accP, primaryKey) => {
                    const secondaryLevel = stationData[primaryKey];
                    accP.push(

{decoder[primary][primaryKey]}

                          {Object.keys(secondaryLevel)
                            .sort(sorters[secondary])
                            .reduce((accS, secondaryKey) => {
                              const tertiaryLevel =
                                secondaryLevel[secondaryKey];
                              accS.push(

{decoder[secondary][secondaryKey]}

                                    {Object.keys(tertiaryLevel)
                                      .sort(sorters[tertiary])
                                      .reduce((accT, tertiaryKey) => {
                                        const stationsInfo =
                                          tertiaryLevel[tertiaryKey];
                                        accT.push(

                                              {decoder[tertiary][tertiaryKey]}

                                              {Object.keys(stationsInfo)
                                                .sort()
                                                .reduce((accL, stationId) => {
                                                  const location =
                                                    stationsInfo[stationId];
                                                  accL.push(

                                                        <Link
                                                          to={`/station-info/${stationId}`}
                                                        >
                                                           {stationId}
                                                        </Link>

                                                      {location}

                                                  );
                                                  return accL;
                                                }, [])}

                                        );
                                        return accT;
                                      }, [])}

                              );
                              return accS;
                            }, [])}

                    );

                    return accP;
                  }, [])}

            );
          }
          return
Loading
;
        }}
      />

  );
}
<|endoftext|>


<commit_before>var Spot = require('spot-framework');
var PageView = require('./base');
var templates = require('../templates');
var app = require('ampersand-app');
var csv = require('csv');
var $ = require('jquery');

var DatasetCollectionView = require('./datasets/dataset-collection');

module.exports = PageView.extend({
  template: templates.datasets.page,
  initialize: function () {
    this.pageName = 'datasets';
  },
  events: {
    'change [data-hook~=json-upload-input]': 'uploadJSON',
    'change [data-hook~=csv-upload-input]': 'uploadCSV',
    'click [data-hook~=server-connect]': 'connectToServer',

    'input [data-hook~=dataset-selector]': 'input',
    'click [data-hook~=search-button]': 'search',
    'click [data-hook~=clear-button]': 'clear',

    'click [data-hook~=CSV-settings-button]': 'showCSVSettings',
    'click [data-hook~=CSV-settings-close]': 'closeCSVSettings',

    'click #CSV-separator-comma': function () { app.CSVSeparator = ','; },
    'click #CSV-separator-colon': function () { app.CSVSeparator = ':'; },
    'click #CSV-separator-semicolon': function () { app.CSVSeparator = ';'; },
    'click #CSV-separator-pipe': function () { app.CSVSeparator = '|'; },
    'click #CSV-separator-tab': function () { app.CSVSeparator = '\t'; },
    'click #CSV-header-columns': function () { app.CSVHeaders = this.query('#CSV-header-columns').checked; },
    'click #CSV-quote-single': function () { app.CSVQuote = '\''; },
    'click #CSV-quote-double': function () { app.CSVQuote = '"'; },
    'click #CSV-quote-none': function () { app.CSVQuote = null; }

  },
  render: function () {
    // Reset the CSV parsing dialog.
    // NOTE: we could do this via bindings, but this is easier (less code)
    this.renderWithTemplate(this);
    this.query('#CSV-header-columns').checked = app.CSVHeaders;

    if (app.CSVSeparator === ',') {
      this.query('#CSV-separator-comma').checked = true;
    } else if (app.CSVSeparator === ':') {
      this.query('#CSV-separator-colon').checked = true;
    } else if (app.CSVSeparator === ';') {
      this.query('#CSV-separator-semicolon').checked = true;
    } else if (app.CSVSeparator === '|') {
      this.query('#CSV-separator-pipe').checked = true;
    } else if (app.CSVSeparator === '\t') {
      this.query('#CSV-separator-tab').checked = true;
    }

    if (app.CSVQuote === '"') {
      this.query('#CSV-quote-double').checked = true;
    } else if (app.CSVQuote === '\'') {
      this.query('#CSV-quote-single').checked = true;
    } else if (app.CSVQuote === null) {
      this.query('#CSV-quote-none').checked = true;
    }
  },
  session: {
    needle: 'string',
    showSearch: 'boolean'
  },
  subviews: {
    datasets: {
      hook: 'dataset-items',
      constructor: DatasetCollectionView
    }
  },
  bindings: {
    'model.isLockedDown': {
      type: 'toggle',
      hook: 'add-datasets-div',
      invert: true
    },
    'showSearch': {
      type: 'toggle',
      hook: 'search-bar'
    },
    'needle': {
      type: 'value',
      hook: 'dataset-selector'
    }
  },
  input: function () {
    var select = this.el.querySelector('[data-hook~="dataset-selector"]');
    this.needle = select.value;

    this.update();
  },
  search: function () {
    this.showSearch = !this.showSearch;
    if (this.showSearch) {
      this.queryByHook('dataset-selector').focus();
    }
  },
  clear: function () {
    this.needle = '';
    this.update();
  },
  update: function () {
    // build regexp for searching
    try {
      var regexp = new RegExp(this.needle, 'i'); // case insensitive search

      // search through collection, check both name and description
      this.model.datasets.forEach(function (e) {
        var hay = e.name + e.URL + e.description;
        e.show = regexp.test(hay.toLowerCase());
      });
    } catch (error) {
    }
  },
  uploadJSON: function () {
    var fileLoader = this.queryByHook('json-upload-input');
    var uploadedFile = fileLoader.files[0];
    var reader = new window.FileReader();
    var dataURL = fileLoader.files[0].name;

    // TODO: enforce spot.driver === 'client'

    var dataset = app.me.datasets.add({
      name: dataURL,
      URL: dataURL,
      description: 'uploaded JSON file'
    });

    reader.onload = function (ev) {
      app.message({
        text: 'Processing',
        type: 'ok'
      });
      try {
        dataset.data = JSON.parse(ev.target.result);

        // automatically analyze dataset
        dataset.scan();
        dataset.facets.forEach(function (facet, i) {
          if (i < 20) {
            facet.isActive = true;

            if (facet.isCategorial) {
              facet.setCategories();
            } else if (facet.isContinuous || facet.isDatetime || facet.isDuration) {
              facet.setMinMax();
            }
          }
        });
        app.message({
          text: dataURL + ' was uploaded succesfully. Configured ' + dataset.facets.length + ' facets',
          type: 'ok'
        });
        window.componentHandler.upgradeDom();

        // Automatically activate dataset if it is the only one
        if (app.me.datasets.length === 1) {
          $('.mdl-switch').click(); // only way to get the switch in the 'on' position
        }
      } catch (ev) {
        app.me.datasets.remove(dataset);
        app.message({
          text: 'Error parsing JSON file: ' + ev,
          type: 'error',
          error: ev
        });
      }
    };

    reader.onerror = function (ev) {
      var error = ev.srcElement.error;

      app.message({
        text: 'File loading problem: ' + error,
        type: 'error',
        error: ev
      });
    };

    reader.onprogress = function (ev) {
      if (ev.lengthComputable) {
        // ev.loaded and ev.total are ProgressEvent properties
        app.progress(parseInt(100.0 * ev.loaded / ev.total));
      }
    };

    reader.readAsText(uploadedFile);
  },
  uploadCSV: function () {
    var fileLoader = this.queryByHook('csv-upload-input');
    var uploadedFile = fileLoader.files[0];
    var reader = new window.FileReader();
    var dataURL = fileLoader.files[0].name;

    // TODO: enforce spot.driver === 'client'

    var dataset = app.me.datasets.add({
      name: dataURL,
      URL: dataURL,
      description: 'uploaded CSV file'
    });

    reader.onload = function (ev) {
      app.message({
        text: 'Processing',
        type: 'ok'
      });
      var options = {
        columns: app.CSVHeaders, // treat first line as header with column names
        relax_column_count: false, // accept malformed lines
        delimiter: app.CSVSeparator, // field delimieter
        quote: app.CSVQuote, // String quoting character
        comment: '', // Treat all the characters after this one as a comment.
        trim: true // ignore white space around delimiter
      };

      csv.parse(ev.target.result, options, function (err, data) {
        if (err) {
          app.me.datasets.remove(dataset);
          app.message({
            text: 'Error parsing CSV file: ' + err.message,
            type: 'error',
            error: ev
          });
        } else {
          dataset.data = data;

          // automatically analyze dataset
          dataset.scan();
          dataset.facets.forEach(function (facet, i) {
            if (i < 20) {
              facet.isActive = true;

              if (facet.isCategorial) {
                facet.setCategories();
              } else if (facet.isContinuous || facet.isDatetime || facet.isDuration) {
                facet.setMinMax();
              }
            }
          });
          app.message({
            text: dataURL + ' was uploaded succesfully. Configured ' + dataset.facets.length + ' facets',
            type: 'ok'
          });
          window.componentHandler.upgradeDom();

          // Automatically activate dataset if it is the only one
          if (app.me.datasets.length === 1) {
            $('.mdl-switch').click(); // only way to get the switch in the 'on' position
          }
        }
      });
    };

    reader.onerror = function (ev) {
      app.me.datasets.remove(dataset);
      app.message({
        text: 'File loading problem: ' + reader.error,
        type: 'error',
        error: reader.error
      });
    };

    reader.onprogress = function (ev) {
      if (ev.lengthComputable) {
        // ev.loaded and ev.total are ProgressEvent properties
        app.progress(parseInt(100.0 * ev.loaded / ev.total));
      }
    };

    reader.readAsText(uploadedFile);
  },
  connectToServer: function () {
    app.me = new Spot({
      sessionType: 'server'
    });
    app.navigate('/');
    app.message({
      text: 'Connecting to server at ' + window.location.origin,
      type: 'ok'
    });

    app.me.isLockedDown = true;
    app.me.connectToServer();
    app.me.socket.emit('getDatasets');
  },
  showCSVSettings: function () {
    var dialog = this.queryByHook('CSV-settings');
    dialog.showModal();
  },
  closeCSVSettings: function () {
    var dialog = this.queryByHook('CSV-settings');
    dialog.close();
  }
});
<commit_msg>BUGFIX: connect to server navigates to home<commit_after>var Spot = require('spot-framework');
var PageView = require('./base');
var templates = require('../templates');
var app = require('ampersand-app');
var csv = require('csv');
var $ = require('jquery');

var DatasetCollectionView = require('./datasets/dataset-collection');

module.exports = PageView.extend({
  template: templates.datasets.page,
  initialize: function () {
    this.pageName = 'datasets';
  },
  events: {
    'change [data-hook~=json-upload-input]': 'uploadJSON',
    'change [data-hook~=csv-upload-input]': 'uploadCSV',
    'click [data-hook~=server-connect]': 'connectToServer',

    'input [data-hook~=dataset-selector]': 'input',
    'click [data-hook~=search-button]': 'search',
    'click [data-hook~=clear-button]': 'clear',

    'click [data-hook~=CSV-settings-button]': 'showCSVSettings',
    'click [data-hook~=CSV-settings-close]': 'closeCSVSettings',

    'click #CSV-separator-comma': function () { app.CSVSeparator = ','; },
    'click #CSV-separator-colon': function () { app.CSVSeparator = ':'; },
    'click #CSV-separator-semicolon': function () { app.CSVSeparator = ';'; },
    'click #CSV-separator-pipe': function () { app.CSVSeparator = '|'; },
    'click #CSV-separator-tab': function () { app.CSVSeparator = '\t'; },
    'click #CSV-header-columns': function () { app.CSVHeaders = this.query('#CSV-header-columns').checked; },
    'click #CSV-quote-single': function () { app.CSVQuote = '\''; },
    'click #CSV-quote-double': function () { app.CSVQuote = '"'; },
    'click #CSV-quote-none': function () { app.CSVQuote = null; }
  },
  render: function () {
    // Reset the CSV parsing dialog.
    // NOTE: we could do this via bindings, but this is easier (less code)
    this.renderWithTemplate(this);
    this.query('#CSV-header-columns').checked = app.CSVHeaders;

    if (app.CSVSeparator === ',') {
      this.query('#CSV-separator-comma').checked = true;
    } else if (app.CSVSeparator === ':') {
      this.query('#CSV-separator-colon').checked = true;
    } else if (app.CSVSeparator === ';') {
      this.query('#CSV-separator-semicolon').checked = true;
    } else if (app.CSVSeparator === '|') {
      this.query('#CSV-separator-pipe').checked = true;
    } else if (app.CSVSeparator === '\t') {
      this.query('#CSV-separator-tab').checked = true;
    }

    if (app.CSVQuote === '"') {
      this.query('#CSV-quote-double').checked = true;
    } else if (app.CSVQuote === '\'') {
      this.query('#CSV-quote-single').checked = true;
    } else if (app.CSVQuote === null) {
      this.query('#CSV-quote-none').checked = true;
    }
  },
  session: {
    needle: 'string',
    showSearch: 'boolean'
  },
  subviews: {
    datasets: {
      hook: 'dataset-items',
      constructor: DatasetCollectionView
    }
  },
  bindings: {
    'model.isLockedDown': {
      type: 'toggle',
      hook: 'add-datasets-div',
      invert: true
    },
    'showSearch': {
      type: 'toggle',
      hook: 'search-bar'
    },
    'needle': {
      type: 'value',
      hook: 'dataset-selector'
    }
  },
  input: function () {
    var select = this.el.querySelector('[data-hook~="dataset-selector"]');
    this.needle = select.value;

    this.update();
  },
  search: function () {
    this.showSearch = !this.showSearch;
    if (this.showSearch) {
      this.queryByHook('dataset-selector').focus();
    }
  },
  clear: function () {
    this.needle = '';
    this.update();
  },
  update: function () {
    // build regexp for searching
    try {
      var regexp = new RegExp(this.needle, 'i'); // case insensitive search

      // search through collection, check both name and description
      this.model.datasets.forEach(function (e) {
        var hay = e.name + e.URL + e.description;
        e.show = regexp.test(hay.toLowerCase());
      });
    } catch (error) {
    }
  },
  uploadJSON: function () {
    var fileLoader = this.queryByHook('json-upload-input');
    var uploadedFile = fileLoader.files[0];
    var reader = new window.FileReader();
    var dataURL = fileLoader.files[0].name;

    // TODO: enforce spot.driver === 'client'

    var dataset = app.me.datasets.add({
      name: dataURL,
      URL: dataURL,
      description: 'uploaded JSON file'
    });

    reader.onload = function (ev) {
      app.message({
        text: 'Processing',
        type: 'ok'
      });
      try {
        dataset.data = JSON.parse(ev.target.result);

        // automatically analyze dataset
        dataset.scan();
        dataset.facets.forEach(function (facet, i) {
          if (i < 20) {
            facet.isActive = true;

            if (facet.isCategorial) {
              facet.setCategories();
            } else if (facet.isContinuous || facet.isDatetime || facet.isDuration) {
              facet.setMinMax();
            }
          }
        });
        app.message({
          text: dataURL + ' was uploaded succesfully. Configured ' + dataset.facets.length + ' facets',
          type: 'ok'
        });
        window.componentHandler.upgradeDom();

        // Automatically activate dataset if it is the only one
        if (app.me.datasets.length === 1) {
          $('.mdl-switch').click(); // only way to get the switch in the 'on' position
        }
      } catch (ev) {
        app.me.datasets.remove(dataset);
        app.message({
          text: 'Error parsing JSON file: ' + ev,
          type: 'error',
          error: ev
        });
      }
    };

    reader.onerror = function (ev) {
      var error = ev.srcElement.error;

      app.message({
        text: 'File loading problem: ' + error,
        type: 'error',
        error: ev
      });
    };

    reader.onprogress = function (ev) {
      if (ev.lengthComputable) {
        // ev.loaded and ev.total are ProgressEvent properties
        app.progress(parseInt(100.0 * ev.loaded / ev.total));
      }
    };

    reader.readAsText(uploadedFile);
  },
  uploadCSV: function () {
    var fileLoader = this.queryByHook('csv-upload-input');
    var uploadedFile = fileLoader.files[0];
    var reader = new window.FileReader();
    var dataURL = fileLoader.files[0].name;

    // TODO: enforce spot.driver === 'client'

    var dataset = app.me.datasets.add({
      name: dataURL,
      URL: dataURL,
      description: 'uploaded CSV file'
    });

    reader.onload = function (ev) {
      app.message({
        text: 'Processing',
        type: 'ok'
      });
      var options = {
        columns: app.CSVHeaders, // treat first line as header with column names
        relax_column_count: false, // accept malformed lines
        delimiter: app.CSVSeparator, // field delimieter
        quote: app.CSVQuote, // String quoting character
        comment: '', // Treat all the characters after this one as a comment.
        trim: true // ignore white space around delimiter
      };

      csv.parse(ev.target.result, options, function (err, data) {
        if (err) {
          app.me.datasets.remove(dataset);
          app.message({
            text: 'Error parsing CSV file: ' + err.message,
            type: 'error',
            error: ev
          });
        } else {
          dataset.data = data;

          // automatically analyze dataset
          dataset.scan();
          dataset.facets.forEach(function (facet, i) {
            if (i < 20) {
              facet.isActive = true;

              if (facet.isCategorial) {
                facet.setCategories();
              } else if (facet.isContinuous || facet.isDatetime || facet.isDuration) {
                facet.setMinMax();
              }
            }
          });
          app.message({
            text: dataURL + ' was uploaded succesfully. Configured ' + dataset.facets.length + ' facets',
            type: 'ok'
          });
          window.componentHandler.upgradeDom();

          // Automatically activate dataset if it is the only one
          if (app.me.datasets.length === 1) {
            $('.mdl-switch').click(); // only way to get the switch in the 'on' position
          }
        }
      });
    };

    reader.onerror = function (ev) {
      app.me.datasets.remove(dataset);
      app.message({
        text: 'File loading problem: ' + reader.error,
        type: 'error',
        error: reader.error
      });
    };

    reader.onprogress = function (ev) {
      if (ev.lengthComputable) {
        // ev.loaded and ev.total are ProgressEvent properties
        app.progress(parseInt(100.0 * ev.loaded / ev.total));
      }
    };

    reader.readAsText(uploadedFile);
  },
  connectToServer: function () {
    app.me = new Spot({
      sessionType: 'server'
    });
    app.message({
      text: 'Connecting to server at ' + window.location.origin,
      type: 'ok'
    });
    app.me.connectToServer();
    app.me.socket.emit('getDatasets');

    app.navigate('home');
    setTimeout(function () {
      app.navigate('datasets');
    }, 100);
  },
  showCSVSettings: function () {
    var dialog = this.queryByHook('CSV-settings');
    dialog.showModal();
  },
  closeCSVSettings: function () {
    var dialog = this.queryByHook('CSV-settings');
    dialog.close();
  }
});
<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Helmet from 'react-helmet';
import { withReducer, withHandlers, withProps, compose } from 'recompose';

import { postJSON } from 'services/postJSON';
import Back from 'components/Back';
import FeedbackForm from 'components/FeedbackForm';

const reducer = withReducer(
  'state',
  'dispatch',
  (state, action) => {
    switch (action.type) {
      case 'SET_COMMENT':
        return Object.assign(state, { comment: action.payload });
      case 'SET_ERROR':
        return Object.assign(state, { error: true });
      case 'SET_SCORE':
        return Object.assign(state, { score: action.payload });
      case 'SET_SUBMITTED':
        return Object.assign(state, { submitted: action.payload });
      case 'SET_SUBMITTING':
        return Object.assign(state, { submitting: action.payload });
      default:
        return state;
    }
  },
  {
    comment: '',
    error: false,
    score: null,
    submitted: false,
    submitting: false,
  }
);

const handlers = withHandlers({
  setComment: ({ dispatch }) => payload => dispatch({ type: 'SET_COMMENT', payload }),
  setScore: ({ dispatch }) => payload => dispatch({ type: 'SET_SCORE', payload }),
  submit: ({ dispatch }) => event => {
    event.preventDefault();
    console.log(event);
    // dispatch({ type: 'SET_SUBMITTING', payload: false });
    // const data = {
    //   question: question,
    //   score: score,
    //   comment: comment,
    // };
    //
    // postJSON(url, data)
    //   .then(response => {
    //     dispatch({ type: 'SET_SUBMITTING', payload: false });
    //     dispatch({ type: 'SET_SUBMITTED', payload: true });
    //   })
    //   .catch(error => {
    //     dispatch({ type: 'SET_SUBMITTING', payload: false });
    //     dispatch({ type: 'SET_ERROR' });
    //   });
  },
});

const enhance = compose(reducer, handlers);

const FeedbackPure = enhance(props => {
  const {
    question,
    setComment,
    setError,
    setScore,
    state: { comment, error, score, submitted, submitting },
    submit,
    url,
  } = props;

  return [
    <Helmet key="helmet" title={question} />,
    <Back key="back" />,
    <FeedbackForm
      key="form"
      submitted={submitted}
      submitting={submitting}
      score={score}
      error={error}
      handleScore={setScore}
      handleComment={setComment}
      onSubmit={submit}
      question={question}
    />,
  ];
});

class Feedback extends PureComponent {
  constructor() {
    super();
    this.state = {
      comment: '',
      error: false,
      question: null,
      score: null,
      submitted: false,
      submitting: true,
    };

    this.setScore = this.setScore.bind(this);
    this.setComment = this.setComment.bind(this);
    this.submitFeedback = this.submitFeedback.bind(this);
  }

  setScore(event) {
    this.setState({ score: event });
  }

  setComment(event) {
    this.setState({ comment: event.target.value });
  }

  submitFeedback(event) {
    event.preventDefault();
    this.setState({ submitting: true });
    const url = this.props.url;
    const data = {
      question: this.state.question,
      score: this.state.score,
      comment: this.state.comment,
    };

    postJSON(url, data)
      .then(response => {
        this.setState({
          submitted: true,
          submitting: false,
        });
      })
      .catch(error => {
        this.setState({
          submitting: false,
          error: true,
        });
      });
  }

  componentDidMount() {
    this.setState({ submitting: false });
  }

  render() {
    const { question } = this.props;
    const { error, score, submitted, submitting } = this.state;

    return [
      <Helmet key="helmet" title={question} />,
      <Back key="back" />,
      <FeedbackForm
        key="form"
        submitted={submitted}
        submitting={submitting}
        score={score}
        error={error}
        handleScore={this.setScore}
        handleSelection={this.setComment}
        onSubmit={this.submitFeedback}
        question={question}
      />,
    ];
  }
}

Feedback.propTypes = {
  question: PropTypes.string.isRequired,
  url: PropTypes.string.isRequired,
};

export const pageQuery = graphql`
  query FeedbackForm {
    site {
      siteMetadata {
        feedback {
          api {
            url
          }
          questions
        }
      }
    }
  }
`;

const resolveFeedbackFormProps = () =>
  withProps(props => {
    const questions = props.data.site.siteMetadata.feedback.questions;
    return {
      url: props.data.site.siteMetadata.feedback.api.url,
      question: questions[Math.floor(Math.random() * questions.length)],
    };
  });

export default resolveFeedbackFormProps()(FeedbackPure);
<commit_msg>Rewrite Feedback with recompose<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import Helmet from 'react-helmet';
import { withReducer, withHandlers, withProps, compose } from 'recompose';

import { postJSON } from 'services/postJSON';
import Back from 'components/Back';
import FeedbackForm from 'components/FeedbackForm';

export const pageQuery = graphql`
  query Feedback {
    site {
      siteMetadata {
        feedback {
          api {
            url
          }
          questions
        }
      }
    }
  }
`;

const resolveFeedbackProps = () =>
  withProps(props => {
    const questions = props.data.site.siteMetadata.feedback.questions;
    return {
      url: props.data.site.siteMetadata.feedback.api.url,
      question: questions[Math.floor(Math.random() * questions.length)],
    };
  });

const reducer = withReducer(
  'state',
  'dispatch',
  (state, action) => {
    switch (action.type) {
      case 'SET_COMMENT':
        return Object.assign(state, { comment: action.payload });
      case 'SET_ERROR':
        return Object.assign(state, { error: true });
      case 'SET_SCORE':
        return Object.assign(state, { score: action.payload });
      case 'SET_SUBMITTED':
        return Object.assign(state, { submitted: action.payload });
      case 'SET_SUBMITTING':
        return Object.assign(state, { submitting: action.payload });
      default:
        return state;
    }
  },
  {
    comment: '',
    error: false,
    score: null,
    submitted: false,
    submitting: false,
  }
);

const handlers = withHandlers({
  setComment: ({ dispatch }) => payload => dispatch({ type: 'SET_COMMENT', payload }),
  setScore: ({ dispatch }) => payload => dispatch({ type: 'SET_SCORE', payload }),
  submit: ({ dispatch, state: { score, comment }, question, url }) => event => {
    event.preventDefault();
    dispatch({ type: 'SET_SUBMITTING', payload: false });
    const data = {
      question: question,
      score: score,
      comment: comment,
    };

    postJSON(url, data)
      .then(response => {
        dispatch({ type: 'SET_SUBMITTING', payload: false });
        dispatch({ type: 'SET_SUBMITTED', payload: true });
      })
      .catch(error => {
        dispatch({ type: 'SET_SUBMITTING', payload: false });
        dispatch({ type: 'SET_ERROR' });
      });
  },
});

const enhance = compose(reducer, handlers);

const Feedback = enhance(
  ({ question, setComment, setScore, state: { comment, error, score, submitted, submitting }, submit, url }) => [
    <Helmet key="helmet" title={question} />,
    <Back key="back" />,
    <FeedbackForm
      key="form"
      submitted={submitted}
      submitting={submitting}
      score={score}
      error={error}
      handleScore={setScore}
      handleComment={setComment}
      onSubmit={submit}
      question={question}
    />,
  ]
);

Feedback.propTypes = {
  question: PropTypes.string.isRequired,
  url: PropTypes.string.isRequired,
  setComment: PropTypes.func,
  state: PropTypes.shape({
    comment: PropTypes.string,
    error: PropTypes.bool.isRequired,
    score: PropTypes.number,
    submitted: PropTypes.bool.isRequired,
    submitting: PropTypes.bool.isRequired,
  }),
  submit: PropTypes.func,
  url: PropTypes.string.isRequired,
};

export default resolveFeedbackProps()(Feedback);
<|endoftext|>