<commit_before>var gulp = require('gulp'),
    usemin = require('gulp-usemin'),
    wrap = require('gulp-wrap'),
    connect = require('gulp-connect'),
    watch = require('gulp-watch'),
    minifyCss = require('gulp-minify-css'),
    minifyJs = require('gulp-uglify'),
    concat = require('gulp-concat'),
    less = require('gulp-less'),
    rename = require('gulp-rename'),
    filter = require('gulp-filter'),
    minifyHTML = require('gulp-minify-html'),
    Server = require('karma').Server,
    runSequence = require('run-sequence'),
    del = require('del'),
    protractor = require("gulp-protractor").protractor;

var paths = {
    app_scripts: 'src/app/**/*.js',
    app_less: 'src/assets/less/**/*.*',
    app_images: 'src/assets/img/**/*.*',
    app_html: 'src/**/*.html',

    generated_app_html: 'build/**/*.html',
    generated_app_css: 'build/css/**/*.min.css',
    generated_lib_css: 'build/lib/css/**/*.min.css',
    generated_lib_scripts: 'build/lib/js/*.min.js',

    index: 'src/index.html',

    bower_fonts: 'build/libs/**/*.{ttf,woff,woff2,eof,svg}'
};

/**
 * Building assets
 */
gulp.task('build-assets', ['compile-less']);

gulp.task('compile-less', function() {
    return gulp.src(paths.app_less)
        .pipe(less())
        .pipe(gulp.dest('build/css/'));
});

/**
 * Build html, and concat resources files
 */
gulp.task('build-html', function() {
    return gulp.src(paths.index)
        .pipe(usemin({
            js: [minifyJs(), 'concat'],
            css: [minifyCss({keepSpecialComments: 0}), 'concat']
        }))
        .pipe(gulp.dest('build/'));
});

gulp.task('build-html-dev', function() {
    return gulp.src(paths.index)
        .pipe(usemin({
            js: ['concat'],
            css: ['concat'],
        }))
        .pipe(gulp.dest('build/'));
});

/**
 * Distribution of all the assets
 */
gulp.task('build-dist', ['lib-css', 'lib-scripts', 'lib-fonts', 'app-images', 'app-css', 'app-html']);

gulp.task('app-images', function() {
    return gulp.src(paths.app_images)
        .pipe(gulp.dest('dist/img/'));
});

gulp.task('app-css', function() {
    return gulp.src(paths.generated_app_css)
        .pipe(gulp.dest('dist/css/'));
});

gulp.task('app-html', function() {
    return gulp.src(paths.generated_app_html)
        .pipe(gulp.dest('dist/'));
});

gulp.task('lib-css', function() {
    return gulp.src(paths.generated_lib_css)
        .pipe(gulp.dest('dist/lib/css/'));
});

gulp.task('lib-fonts', function() {
    return gulp.src(paths.bower_fonts)
        .pipe(rename({
            dirname: '/fonts'
        }))
        .pipe(gulp.dest('dist/lib/'));
});

gulp.task('lib-scripts', function() {
    return gulp.src(paths.generated_lib_scripts)
        .pipe(gulp.dest('dist/lib/js/'));
});

/**
 * Clean tasks
 */
gulp.task('clean', function(callback) {
    return del(['build', 'dist'], callback);
});

/**
 * Watch custom files
 */
gulp.task('watchResources', function() {
    gulp.watch(paths.app_less, ['compile-less']);
    gulp.watch(paths.app_images, ['custom-images']);
    gulp.watch(paths.index, ['usemin']);
});

/**
 * Live reload server
 */
gulp.task('webserver', function() {
    connect.server({
        root: 'dist',
        livereload: true,
        port: 8888
    });
});

gulp.task('livereload', function() {
    gulp.src(['dist/**/*.*'])
        .pipe(connect.reload());
});

/**
 * Gulp tasks
 */
gulp.task('build', function(callback) {
  runSequence('clean',
              'build-assets',
              'build-html',
              'build-dist',
              callback);
});

gulp.task('buildDev', ['build-assets', 'build-html-dev', 'dist']);
gulp.task('default', ['build', 'webserver', 'livereload', 'watchResources']);

/**
 * Run test once and exit
 */
gulp.task('unit', function (done) {
  new Server({
    configFile: __dirname + '/tests/karma.conf.js',
    singleRun: true
  }, done).start();
});

gulp.task('e2e', function (done) {
  var args = ['--baseUrl', 'http://127.0.0.1:8888'];
  gulp.src(["./tests/**/*.js"])
    .pipe(protractor({
      configFile: "tests/protractor.conf.js",
      args: args
    }))
    .on('error', function(e) { throw e; });
});
<commit_msg>fixing watch resources task<commit_after>var gulp = require('gulp'),
    usemin = require('gulp-usemin'),
    wrap = require('gulp-wrap'),
    connect = require('gulp-connect'),
    watch = require('gulp-watch'),
    minifyCss = require('gulp-minify-css'),
    minifyJs = require('gulp-uglify'),
    concat = require('gulp-concat'),
    less = require('gulp-less'),
    rename = require('gulp-rename'),
    filter = require('gulp-filter'),
    minifyHTML = require('gulp-minify-html'),
    Server = require('karma').Server,
    runSequence = require('run-sequence'),
    del = require('del'),
    protractor = require("gulp-protractor").protractor;

var paths = {
    app_scripts: 'src/app/**/*.js',
    app_less: 'src/assets/less/**/*.*',
    app_images: 'src/assets/img/**/*.*',
    app_html: 'src/**/*.html',

    generated_app_html: 'build/**/*.html',
    generated_app_css: 'build/css/**/*.min.css',
    generated_lib_css: 'build/lib/css/**/*.min.css',
    generated_lib_scripts: 'build/lib/js/*.min.js',

    index: 'src/index.html',

    bower_fonts: 'build/libs/**/*.{ttf,woff,woff2,eof,svg}'
};

/**
 * Building assets
 */
gulp.task('build-assets', ['compile-less']);

gulp.task('compile-less', function() {
    return gulp.src(paths.app_less)
        .pipe(less())
        .pipe(gulp.dest('build/css/'));
});

/**
 * Build html, and concat resources files
 */
gulp.task('build-html', function() {
    return gulp.src(paths.index)
        .pipe(usemin({
            js: [minifyJs(), 'concat'],
            css: [minifyCss({keepSpecialComments: 0}), 'concat']
        }))
        .pipe(gulp.dest('build/'));
});

gulp.task('build-html-dev', function() {
    return gulp.src(paths.index)
        .pipe(usemin({
            js: ['concat'],
            css: ['concat'],
        }))
        .pipe(gulp.dest('build/'));
});

/**
 * Distribution of all the assets
 */
gulp.task('dist', ['lib-css', 'lib-scripts', 'lib-fonts', 'app-images', 'app-css', 'app-html']);

gulp.task('app-images', function() {
    return gulp.src(paths.app_images)
        .pipe(gulp.dest('dist/img/'));
});

gulp.task('app-css', function() {
    return gulp.src(paths.generated_app_css)
        .pipe(gulp.dest('dist/css/'));
});

gulp.task('app-html', function() {
    return gulp.src(paths.generated_app_html)
        .pipe(gulp.dest('dist/'));
});

gulp.task('lib-css', function() {
    return gulp.src(paths.generated_lib_css)
        .pipe(gulp.dest('dist/lib/css/'));
});

gulp.task('lib-fonts', function() {
    return gulp.src(paths.bower_fonts)
        .pipe(rename({
            dirname: '/fonts'
        }))
        .pipe(gulp.dest('dist/lib/'));
});

gulp.task('lib-scripts', function() {
    return gulp.src(paths.generated_lib_scripts)
        .pipe(gulp.dest('dist/lib/js/'));
});

/**
 * Clean tasks
 */
gulp.task('clean', function(callback) {
    return del(['build', 'dist'], callback);
});

/**
 * Watch custom files
 */
gulp.task('watchResources', function() {
    gulp.watch(paths.app_less, ['build-assets', 'dist']);
    gulp.watch(paths.app_images, ['app-images']);
    gulp.watch(paths.index, ['build-html-dev', 'dist']);
});

/**
 * Live reload server
 */
gulp.task('webserver', function() {
    connect.server({
        root: 'dist',
        livereload: true,
        port: 8888
    });
});

gulp.task('livereload', function() {
    gulp.src(['dist/**/*.*'])
        .pipe(connect.reload());
});

/**
 * Gulp tasks
 */
gulp.task('build', function(callback) {
  runSequence('clean',
              'build-assets',
              'build-html',
              'dist',
              callback);
});

gulp.task('buildDev', function(callback) {
  runSequence('clean',
              'build-assets',
              'build-html-dev',
              'dist',
              callback);
});

gulp.task('default', function(callback) {
  runSequence('build',
              'webserver',
              'livereload',
              'watchResources',
              callback);
});

/**
 * Run test once and exit
 */
gulp.task('unit', function (done) {
  new Server({
    configFile: __dirname + '/tests/karma.conf.js',
    singleRun: true
  }, done).start();
});

gulp.task('e2e', function (done) {
  var args = ['--baseUrl', 'http://127.0.0.1:8888'];
  gulp.src(["./tests/**/*.js"])
    .pipe(protractor({
      configFile: "tests/protractor.conf.js",
      args: args
    }))
    .on('error', function(e) { throw e; });
});
<|endoftext|>


<commit_before>/* jshint node:true */
'use strict';

var gulp = require('gulp');
var browserify = require('browserify');
var transform = require('vinyl-transform');
var source = require('vinyl-source-stream');
var $ = require('gulp-load-plugins')({
  rename: {
    'gulp-gh-pages': 'ghPages'
  }
});

var AUTOPREFIXER_BROWSERS = [
  'ie >= 10',
  'ie_mob >= 10',
  'ff >= 30',
  'chrome >= 34',
  'safari >= 7',
  'opera >= 23',
  'ios >= 7',
  'android >= 4.4',
  'bb >= 10'
];

gulp.task('styles', function () {
  return gulp.src(['app/styles/main.css'])
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    .pipe(gulp.dest('.tmp/styles'));
});

// Lint JavaScript
gulp.task('jshint', function () {
  return gulp.src('app/scripts/**/*.js')
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.jshint.reporter('fail'));
});

gulp.task('javascript', function () {
  return browserify({
    entries:['app/scripts/edit.js'],
    debug: true
  }).bundle()
    .pipe(source('edit.bundle.js'))
    .pipe($.buffer())
    .pipe($.sourcemaps.init({loadMaps: true}))
      .pipe($.uglify())
    .pipe($.sourcemaps.write('./'))
    .pipe(gulp.dest('dist/js'));
});

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

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

//Optimize images
gulp.task('images', function () {
  return gulp.src([
      'app/images/**/aws*.png',
      'app/images/**/unknown.png'
    ])
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/images')).pipe($.size({title: 'images'}));
});

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

gulp.task('extras', function () {
  return gulp.src([
    'app/*.*',
    '!app/*.html',
    '!app/**/*~',
    '!app/**/*swp',
    'node_modules/apache-server-configs/dist/.htaccess'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'));
});

// clear all caches created by gulp-cache
// do this if weird stuff happens with for instance images
gulp.task('clear', function (done) {
  return $.cache.clearAll(done);
});

gulp.task('clean', ['clear'], function () {
  require('del').bind(null, ['.tmp', 'dist']);
});

gulp.task('connect', function () {
  var serveStatic = require('serve-static');
  var serveIndex = require('serve-index');
  var app = require('connect')()
    .use(require('connect-livereload')({port: 35729}))
    .use(serveStatic('.tmp'))
    .use(serveStatic('app'))
    .use(serveStatic('dist'))
    // paths to bower_components should be relative to the current file
    // e.g. in app/index.html you should use ../bower_components
    .use('/bower_components', serveStatic('bower_components'))
    .use(serveIndex('app'));

  require('http').createServer(app)
    .listen(9000)
    .on('listening', function () {
      console.log('Started connect web server on http://localhost:9000');
    });
});

gulp.task('serve', ['connect', 'watch'], function () {
  require('opn')('http://localhost:9000');
});

// serve from build to ensure everything is there
gulp.task('serve-build', ['clean'], function () {
  gulp.start('build');
  var serveStatic = require('serve-static');
  var serveIndex = require('serve-index');
  var app = require('connect')().use(serveStatic('dist')).use(serveIndex('dist'));
  require('http').createServer(app).listen(9000).on('listening', function () {
    console.log('Serving distribution at http://localhost:9000');
  });
});

// inject bower components
gulp.task('wiredep', function () {
  var wiredep = require('wiredep').stream;

  gulp.src('app/*.html')
    .pipe(wiredep())
    .pipe(gulp.dest('app'));
});

gulp.task('watch', ['connect'], function () {
  $.livereload.listen();

  // watch for changes
  gulp.watch([
    'app/*.html',
    '.tmp/styles/**/*.css',
    '.tmp/js/**/*.js',
    'app/images/**/*'
  ]).on('change', $.livereload.changed);

  gulp.watch('app/styles/**/*.css', ['styles']);
  gulp.watch('app/scripts/**/*.js', ['javascript']);
  gulp.watch('bower.json', ['wiredep']);
});

gulp.task('test', function () {
  var jasmine = require("gulp-jasmine");
  gulp.src('specs/**.js')
    .pipe(jasmine());
});

gulp.task('test-watch', function () {
    gulp.watch([
      'specs/**.js',
      'app/scripts/**.js'
    ], ['test']);
});

gulp.task('build', ['jshint', 'html', 'images', 'fonts', 'extras'], function () {
  gulp.src([
      'bower_components/ace-builds/src-min-noconflict/theme-tomorrow_night_eighties.js',
      'bower_components/ace-builds/src-min-noconflict/worker-json.js',
      'bower_components/ace-builds/src-min-noconflict/mode-json.js'
    ])
    .pipe($.size({title: 'copy ace js'}))
    .pipe(gulp.dest('dist/js/ace/'));
  return gulp.src('dist/**').pipe($.size({title: 'build', gzip: true}));
});

gulp.task('deploy', function() {
  return gulp.src('dist/**').pipe($.ghPages());
});

gulp.task('default', ['clean'], function () {
  gulp.start('build');
});
<commit_msg>watch the cycss file too, eventhough it's statically served<commit_after>/* jshint node:true */
'use strict';

var gulp = require('gulp');
var browserify = require('browserify');
var transform = require('vinyl-transform');
var source = require('vinyl-source-stream');
var $ = require('gulp-load-plugins')({
  rename: {
    'gulp-gh-pages': 'ghPages'
  }
});

var AUTOPREFIXER_BROWSERS = [
  'ie >= 10',
  'ie_mob >= 10',
  'ff >= 30',
  'chrome >= 34',
  'safari >= 7',
  'opera >= 23',
  'ios >= 7',
  'android >= 4.4',
  'bb >= 10'
];

gulp.task('styles', function () {
  return gulp.src(['app/styles/main.css'])
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    .pipe(gulp.dest('.tmp/styles'));
});

// Lint JavaScript
gulp.task('jshint', function () {
  return gulp.src('app/scripts/**/*.js')
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.jshint.reporter('fail'));
});

gulp.task('javascript', function () {
  return browserify({
    entries:['app/scripts/edit.js'],
    debug: true
  }).bundle()
    .pipe(source('edit.bundle.js'))
    .pipe($.buffer())
    .pipe($.sourcemaps.init({loadMaps: true}))
      .pipe($.uglify())
    .pipe($.sourcemaps.write('./'))
    .pipe(gulp.dest('dist/js'));
});

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

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

//Optimize images
gulp.task('images', function () {
  return gulp.src([
      'app/images/**/aws*.png',
      'app/images/**/unknown.png'
    ])
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/images')).pipe($.size({title: 'images'}));
});

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

gulp.task('extras', function () {
  return gulp.src([
    'app/*.*',
    '!app/*.html',
    '!app/**/*~',
    '!app/**/*swp',
    'node_modules/apache-server-configs/dist/.htaccess'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'));
});

// clear all caches created by gulp-cache
// do this if weird stuff happens with for instance images
gulp.task('clear', function (done) {
  return $.cache.clearAll(done);
});

gulp.task('clean', ['clear'], function () {
  require('del').bind(null, ['.tmp', 'dist']);
});

gulp.task('connect', function () {
  var serveStatic = require('serve-static');
  var serveIndex = require('serve-index');
  var app = require('connect')()
    .use(require('connect-livereload')({port: 35729}))
    .use(serveStatic('.tmp'))
    .use(serveStatic('app'))
    .use(serveStatic('dist'))
    // paths to bower_components should be relative to the current file
    // e.g. in app/index.html you should use ../bower_components
    .use('/bower_components', serveStatic('bower_components'))
    .use(serveIndex('app'));

  require('http').createServer(app)
    .listen(9000)
    .on('listening', function () {
      console.log('Started connect web server on http://localhost:9000');
    });
});

gulp.task('serve', ['connect', 'watch'], function () {
  require('opn')('http://localhost:9000');
});

// serve from build to ensure everything is there
gulp.task('serve-build', ['clean'], function () {
  gulp.start('build');
  var serveStatic = require('serve-static');
  var serveIndex = require('serve-index');
  var app = require('connect')().use(serveStatic('dist')).use(serveIndex('dist'));
  require('http').createServer(app).listen(9000).on('listening', function () {
    console.log('Serving distribution at http://localhost:9000');
  });
});

// inject bower components
gulp.task('wiredep', function () {
  var wiredep = require('wiredep').stream;

  gulp.src('app/*.html')
    .pipe(wiredep())
    .pipe(gulp.dest('app'));
});

gulp.task('watch', ['connect'], function () {
  $.livereload.listen();

  // watch for changes
  gulp.watch([
    'app/*.html',
    '.tmp/styles/**/*.css',
    '.tmp/styles/**/*.cycss',
    '.tmp/js/**/*.js',
    'app/images/**/*'
  ]).on('change', $.livereload.changed);

  gulp.watch('app/styles/**/*.css', ['styles']);
  gulp.watch('app/scripts/**/*.js', ['javascript']);
  gulp.watch('bower.json', ['wiredep']);
});

gulp.task('test', function () {
  var jasmine = require("gulp-jasmine");
  gulp.src('specs/**.js')
    .pipe(jasmine());
});

gulp.task('test-watch', function () {
    gulp.watch([
      'specs/**.js',
      'app/scripts/**.js'
    ], ['test']);
});

gulp.task('build', ['jshint', 'html', 'images', 'fonts', 'extras'], function () {
  gulp.src([
      'bower_components/ace-builds/src-min-noconflict/theme-tomorrow_night_eighties.js',
      'bower_components/ace-builds/src-min-noconflict/worker-json.js',
      'bower_components/ace-builds/src-min-noconflict/mode-json.js'
    ])
    .pipe($.size({title: 'copy ace js'}))
    .pipe(gulp.dest('dist/js/ace/'));
  return gulp.src('dist/**').pipe($.size({title: 'build', gzip: true}));
});

gulp.task('deploy', function() {
  return gulp.src('dist/**').pipe($.ghPages());
});

gulp.task('default', ['clean'], function () {
  gulp.start('build');
});
<|endoftext|>


<commit_before>//Import dependencies
var rmr = require('rmr');
var gulp = require('gulp');
var path = require('path');
var svgstore = require('gulp-svgstore');
var svgmin = require('gulp-svgmin');
var rename = require("gulp-rename");
var handlebars = require('gulp-compile-handlebars');
var fs = require('fs');

//Clean the dist folder
gulp.task('clean', function()
{
  //Clean the dist folder
  return rmr.sync('./dist');
});

//Build the svg sprite task
gulp.task('sprite', function()
{
  //Get the svg files
  gulp.src('./svg/*.svg', { base: './src' })

  //Minimize each file
  .pipe(svgmin(function(file)
  {
    //Get the icon prefix
    var prefix = path.basename(file.relative, path.extname(file.relative));

    //Display in console
    console.log('Processing ' + prefix);

    //Return the prefix plugin
    return { plugins: [ { cleanupIDs: { prefix: prefix + '-',  minify: true } } ] };
  }))

  //Build the sprite
  .pipe(svgstore())

  //Rename the output file
  .pipe(rename({ basename: 'siimple-icons' }))

  //Save the sprite image
  .pipe(gulp.dest('./dist'));
});

//Create the example files
gulp.task('examples', function()
{
  //Initialize the data object
  var data = { files: [] };

  //Get the files
  data.files = fs.readdirSync('./svg/').filter(function(el)
  {
    return el !== '.DS_Store';
  }).map(function(el)
  {
    return path.basename(el, '.svg');
  });

  //Select the templates
  gulp.src('./templates/*.handlebars')

  //Compile using handlebars
  .pipe(handlebars(data, {}))

  //Rename the files
  .pipe(rename({ extname: '.html' }))

  //Save to examples
  .pipe(gulp.dest('./examples/'));
});

//Default task
gulp.task('default', [ 'clean', 'sprite' ]);
<commit_msg>gulpfile.js: added tasks to build font in svg, ttf and woff2 formats<commit_after>//Import dependencies
var rmr = require('rmr');
var fs = require('fs');
var path = require('path');
var gulp = require('gulp');
var svgstore = require('gulp-svgstore');
var svgmin = require('gulp-svgmin');
var rename = require("gulp-rename");
var handlebars = require('gulp-compile-handlebars');
var SVGIcons2SVGFontStream = require('svgicons2svgfont');
var svg2ttf = require('gulp-svg2ttf');
var ttf2woff2 = require('gulp-ttf2woff2');
var utily = require('utily');

//Clean the dist folder
gulp.task('clean', function()
{
  //Clean the dist folder
  return rmr.sync('./dist');
});

//Build the font task
gulp.task('build-font-svg', function()
{
  //Create the new font stream
  var fontStream = new SVGIcons2SVGFontStream({ fontName: 'siimple-icons', normalize: true, fontHeight: 1000 });

  //Setting the font destination
  fontStream.pipe(fs.createWriteStream('dist/siimple-icons.font.svg'));

  //Error event
  fontStream.on('error', function(error){ console.log(error); });

  //Read the icons list
  utily.json.read('./icons.json', function(error, icons)
  {
    //Check the error
    if(error){ throw error; }

    //For each icon object in the list
    icons.forEach(function(icon)
    {
      //Get the icon readable stream
      var reader = fs.createReadStream(icon.path);

      //Set the icon metadata
      reader.metadata = { unicode: [ icon.unicode ], name: icon.id };

      //Write the icon
      fontStream.write(reader);
    });

    //End the stream
    fontStream.end();
  });
});

//Build font in ttf formt
gulp.task('build-font-ttf', function()
{
  //Convert the svg font to ttf
  gulp.src('./dist/siimple-icons.font.svg').pipe(svg2ttf()).pipe(gulp.dest('./dist'));
});

//Build font in woff2 format
gulp.task('build-font-woff2', function()
{
  //Convert the ttf font to woff2
  gulp.src('./dist/siimple-icons.font.ttf').pipe(ttf2woff2()).pipe(gulp.dest('./dist'));
});

//Build the svg sprite task
gulp.task('sprite', function()
{
  //Get the svg files
  gulp.src('./svg/*.svg', { base: './src' })

  //Minimize each file
  .pipe(svgmin(function(file)
  {
    //Get the icon prefix
    var prefix = path.basename(file.relative, path.extname(file.relative));

    //Display in console
    console.log('Processing ' + prefix);

    //Return the prefix plugin
    return { plugins: [ { cleanupIDs: { prefix: prefix + '-',  minify: true } } ] };
  }))

  //Build the sprite
  .pipe(svgstore())

  //Rename the output file
  .pipe(rename({ basename: 'siimple-icons' }))

  //Save the sprite image
  .pipe(gulp.dest('./dist'));
});

//Create the example files
gulp.task('examples', function()
{
  //Initialize the data object
  var data = { files: [] };

  //Get the files
  data.files = fs.readdirSync('./svg/').filter(function(el)
  {
    return el !== '.DS_Store';
  }).map(function(el)
  {
    return path.basename(el, '.svg');
  });

  //Select the templates
  gulp.src('./templates/*.handlebars')

  //Compile using handlebars
  .pipe(handlebars(data, {}))

  //Rename the files
  .pipe(rename({ extname: '.html' }))

  //Save to examples
  .pipe(gulp.dest('./examples/'));
});

//Default task
gulp.task('default', [ 'clean', 'sprite' ]);
<|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {
"use strict";

var dom = require("../lib/dom");
var lang = require("../lib/lang");
var event = require("../lib/event");
var searchboxCss = require("../requirejs/text!./searchbox.css");
var HashHandler = require("../keyboard/hash_handler").HashHandler;
var keyUtil = require("../lib/keys");

dom.importCssString(searchboxCss, "ace_searchbox");

var html = '
\
    <button type="button" action="hide" class="ace_searchbtn_close"></button>\

\
        <input class="ace_search_field" placeholder="Search for" spellcheck="false"></input>\
        <button type="button" action="findNext" class="ace_searchbtn next"></button>\
        <button type="button" action="findPrev" class="ace_searchbtn prev"></button>\

\

\
        <input class="ace_search_field" placeholder="Replace with" spellcheck="false"></input>\
        <button type="button" action="replace" class="ace_replacebtn">Replace</button>\
        <button type="button" action="replaceAll" class="ace_replacebtn">All</button>\

\

\
        .*\
        Aa\
        \\b\

\

'.replace(/>\s+/g, ">");

var SearchBox = function(editor, range, showReplaceForm) {
    var div = dom.createElement("div");
    div.innerHTML = html;
    this.element = div.firstChild;

    this.$init();
    this.setEditor(editor);
};

(function() {
    this.setEditor = function(editor) {
        editor.searchBox = this;
        editor.container.appendChild(this.element);
        this.editor = editor;
    };

    this.$init = function() {
        var sb = this.element;

        this.searchBox = sb.querySelector(".ace_search_form");
        this.replaceBox = sb.querySelector(".ace_replace_form");
        this.searchOptions = sb.querySelector(".ace_search_options");
        this.regExpOption = sb.querySelector("[action=toggleRegexpMode]");
        this.caseSensitiveOption = sb.querySelector("[action=toggleCaseSensitive]");
        this.wholeWordOption = sb.querySelector("[action=toggleWholeWords]");
        this.searchInput = this.searchBox.querySelector(".ace_search_field");
        this.replaceInput = this.replaceBox.querySelector(".ace_search_field");

        var _this = this;
        event.addListener(sb, "mousedown", function(e) {
            setTimeout(function(){
                _this.activeInput.focus();
            }, 0);
            event.stopPropagation(e);
        });
        event.addListener(sb, "click", function(e) {
            var t = e.target;
            var action = t.getAttribute("action");
            if (action && _this[action])
                _this[action]();
            else if (_this.$searchBarKb.commands[action])
                _this.$searchBarKb.commands[action].exec(_this);
            event.stopPropagation(e);
        });

        event.addCommandKeyListener(sb, function(e, hashId, keyCode) {
            var keyString = keyUtil.keyCodeToString(keyCode);
            var command = _this.$searchBarKb.findKeyCommand(hashId, keyString);
            if (command && command.exec) {
                command.exec(_this);
                event.stopEvent(e);
            }
        });

        this.$onChange = lang.delayedCall(function() {
            _this.find(false, false);
        });

        event.addListener(this.searchInput, "input", function() {
            _this.$onChange.schedule(20);
        });
        event.addListener(this.searchInput, "focus", function() {
            _this.activeInput = _this.searchInput;
        });
        event.addListener(this.replaceInput, "focus", function() {
            _this.activeInput = _this.replaceInput;
        });
        event.addListener(this.searchOptions, "change", function() {
            _this.find(false, false);
        });
    };

    //keybinging outsite of the searchbox
    this.$closeSearchBarKb = new HashHandler([{
        bindKey: "Esc",
        name: "closeSearchBar",
        exec: function(editor) {
            editor.searchBox.hide();
        }
    }]);

    //keybinging outsite of the searchbox
    this.$searchBarKb = new HashHandler();
    this.$searchBarKb.bindKeys({
        "Ctrl-f|Command-f|Ctrl-H|Command-Option-F": function(sb) {
            var isReplace = sb.isReplace = !sb.isReplace;
            sb.replaceBox.style.display = isReplace ? "" : "none";
            sb[isReplace ? "replaceInput" : "searchInput"].focus();
        },
        "Ctrl-G|Command-G": function(sb) {
            sb.findNext();
        },
        "Ctrl-Shift-G|Command-Shift-G": function(sb) {
            sb.findPrev();
        },
        "esc": function(sb) {
            setTimeout(function() { sb.hide();});
        },
        "Return": function(sb) {
            if (sb.activeInput == sb.replaceInput)
                sb.replace();
            sb.findNext();
        },
        "Shift-Return": function(sb) {
            if (sb.activeInput == sb.replaceInput)
                sb.replace();
            sb.findPrev();
        },
        "Tab": function(sb) {
            (sb.activeInput == sb.replaceInput ? sb.searchInput : sb.replaceInput).focus();
        }
    });

    this.$searchBarKb.addCommands([{
        name: "toggleRegexpMode",
        bindKey: {win: "Alt-R|Alt-/", mac: "Ctrl-Alt-R|Ctrl-Alt-/"},
        exec: function(sb) {
            sb.regExpOption.checked = !sb.regExpOption.checked;
            sb.$syncOptions();
        }
    }, {
        name: "toggleCaseSensitive",
        bindKey: {win: "Alt-C|Alt-I", mac: "Ctrl-Alt-R|Ctrl-Alt-I"},
        exec: function(sb) {
            sb.caseSensitiveOption.checked = !sb.caseSensitiveOption.checked;
            sb.$syncOptions();
        }
    }, {
        name: "toggleWholeWords",
        bindKey: {win: "Alt-B|Alt-W", mac: "Ctrl-Alt-B|Ctrl-Alt-W"},
        exec: function(sb) {
            sb.wholeWordOption.checked = !sb.wholeWordOption.checked;
            sb.$syncOptions();
        }
    }]);

    this.$syncOptions = function() {
        dom.setCssClass(this.regExpOption, "checked", this.regExpOption.checked);
        dom.setCssClass(this.wholeWordOption, "checked", this.wholeWordOption.checked);
        dom.setCssClass(this.caseSensitiveOption, "checked", this.caseSensitiveOption.checked);
    };

    this.find = function(skipCurrent, backwards) {
        var range = this.editor.find(this.searchInput.value, {
            skipCurrent: skipCurrent,
            backwards: backwards,
            wrap: true,
            regExp: this.regExpOption.checked,
            caseSensitive: this.caseSensitiveOption.checked,
            wholeWord: this.wholeWordOption.checked
        });
        dom.setCssClass(this.searchBox, "ace_nomatch", !range && this.searchInput.value);
        this.editor.session.highlight(this.editor.$search.$options.re);
    };
    this.findNext = function() {
        this.find(true, false);
    };
    this.findPrev = function() {
        this.find(true, true);
    };
    this.replace = function() {
        this.editor.replace(this.replaceInput.value);
    };
    this.replaceAll = function() {
        this.editor.replaceAll(this.replaceInput.value);
    };

    this.hide = function () {
        this.element.style.display = "none";
        this.editor.keyBinding.removeKeyboardHandler(this.$closeSearchBarKb);
        this.editor.focus();
    };
    this.show = function(value, isReplace) {
        this.element.style.display = "";
        this.replaceBox.style.display = isReplace ? "" : "none";

        this.isReplace = isReplace;

        if (value)
            this.searchInput.value = value;
        this.searchInput.focus();
        this.searchInput.select();

        this.editor.keyBinding.addKeyboardHandler(this.$closeSearchBarKb);
    };

}).call(SearchBox.prototype);

exports.SearchBox = SearchBox;

exports.Search = function(editor, isReplace) {
    var sb = editor.searchBox || new SearchBox(editor);
    sb.show(editor.session.getTextRange(), isReplace);
};

exports.ISearch = function(session, options) {
    this.$changeListener = this.$changeListener.bind(this);
    this.startRange = session.selection.toOrientedRange();
    this.options = options || {};
};

(function(){
    this.setSession = function(session) {
        if (this.session) {
            this.session.removeListener(this.$changeListener);
        }
        this.session = session;
        this.session.addListener(this.$changeListener);
    };
    this.setSearchString = function() {

    };
    this.getValue = function() {
        if (this.value == null)
            this.value = this.session.getValue();
        return this.value;
    };
    this.$changeListener = function() {
        this.value = null;
    };
    this.find = function() {

    };
    this.$edgeBefore = function() {
        this.cursor = this.startRange[this.options.backwards ? "start" : "end"];
    };
    this.$edgeAfter = function() {

    };
    this.next = function(dir) {

    };
}).call(exports.ISearch.prototype);

});

/* ------------------------------------------------------------------------------------------
 * TODO
 * --------------------------------------------------------------------------------------- */
/*
- move search form to the left if it masks current word
- includ all options that search has. ex: regex
- searchbox.searchbox is not that pretty. we should have just searchbox
- disable prev button if it makes sence
*/
<commit_msg>restart search after toggling option<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {
"use strict";

var dom = require("../lib/dom");
var lang = require("../lib/lang");
var event = require("../lib/event");
var searchboxCss = require("../requirejs/text!./searchbox.css");
var HashHandler = require("../keyboard/hash_handler").HashHandler;
var keyUtil = require("../lib/keys");

dom.importCssString(searchboxCss, "ace_searchbox");

var html = '
\
    <button type="button" action="hide" class="ace_searchbtn_close"></button>\

\
        <input class="ace_search_field" placeholder="Search for" spellcheck="false"></input>\
        <button type="button" action="findNext" class="ace_searchbtn next"></button>\
        <button type="button" action="findPrev" class="ace_searchbtn prev"></button>\

\

\
        <input class="ace_search_field" placeholder="Replace with" spellcheck="false"></input>\
        <button type="button" action="replace" class="ace_replacebtn">Replace</button>\
        <button type="button" action="replaceAll" class="ace_replacebtn">All</button>\

\

\
        .*\
        Aa\
        \\b\

\

'.replace(/>\s+/g, ">");

var SearchBox = function(editor, range, showReplaceForm) {
    var div = dom.createElement("div");
    div.innerHTML = html;
    this.element = div.firstChild;

    this.$init();
    this.setEditor(editor);
};

(function() {
    this.setEditor = function(editor) {
        editor.searchBox = this;
        editor.container.appendChild(this.element);
        this.editor = editor;
    };

    this.$init = function() {
        var sb = this.element;

        this.searchBox = sb.querySelector(".ace_search_form");
        this.replaceBox = sb.querySelector(".ace_replace_form");
        this.searchOptions = sb.querySelector(".ace_search_options");
        this.regExpOption = sb.querySelector("[action=toggleRegexpMode]");
        this.caseSensitiveOption = sb.querySelector("[action=toggleCaseSensitive]");
        this.wholeWordOption = sb.querySelector("[action=toggleWholeWords]");
        this.searchInput = this.searchBox.querySelector(".ace_search_field");
        this.replaceInput = this.replaceBox.querySelector(".ace_search_field");

        var _this = this;
        event.addListener(sb, "mousedown", function(e) {
            setTimeout(function(){
                _this.activeInput.focus();
            }, 0);
            event.stopPropagation(e);
        });
        event.addListener(sb, "click", function(e) {
            var t = e.target;
            var action = t.getAttribute("action");
            if (action && _this[action])
                _this[action]();
            else if (_this.$searchBarKb.commands[action])
                _this.$searchBarKb.commands[action].exec(_this);
            event.stopPropagation(e);
        });

        event.addCommandKeyListener(sb, function(e, hashId, keyCode) {
            var keyString = keyUtil.keyCodeToString(keyCode);
            var command = _this.$searchBarKb.findKeyCommand(hashId, keyString);
            if (command && command.exec) {
                command.exec(_this);
                event.stopEvent(e);
            }
        });

        this.$onChange = lang.delayedCall(function() {
            _this.find(false, false);
        });

        event.addListener(this.searchInput, "input", function() {
            _this.$onChange.schedule(20);
        });
        event.addListener(this.searchInput, "focus", function() {
            _this.activeInput = _this.searchInput;
        });
        event.addListener(this.replaceInput, "focus", function() {
            _this.activeInput = _this.replaceInput;
        });
    };

    //keybinging outsite of the searchbox
    this.$closeSearchBarKb = new HashHandler([{
        bindKey: "Esc",
        name: "closeSearchBar",
        exec: function(editor) {
            editor.searchBox.hide();
        }
    }]);

    //keybinging outsite of the searchbox
    this.$searchBarKb = new HashHandler();
    this.$searchBarKb.bindKeys({
        "Ctrl-f|Command-f|Ctrl-H|Command-Option-F": function(sb) {
            var isReplace = sb.isReplace = !sb.isReplace;
            sb.replaceBox.style.display = isReplace ? "" : "none";
            sb[isReplace ? "replaceInput" : "searchInput"].focus();
        },
        "Ctrl-G|Command-G": function(sb) {
            sb.findNext();
        },
        "Ctrl-Shift-G|Command-Shift-G": function(sb) {
            sb.findPrev();
        },
        "esc": function(sb) {
            setTimeout(function() { sb.hide();});
        },
        "Return": function(sb) {
            if (sb.activeInput == sb.replaceInput)
                sb.replace();
            sb.findNext();
        },
        "Shift-Return": function(sb) {
            if (sb.activeInput == sb.replaceInput)
                sb.replace();
            sb.findPrev();
        },
        "Tab": function(sb) {
            (sb.activeInput == sb.replaceInput ? sb.searchInput : sb.replaceInput).focus();
        }
    });

    this.$searchBarKb.addCommands([{
        name: "toggleRegexpMode",
        bindKey: {win: "Alt-R|Alt-/", mac: "Ctrl-Alt-R|Ctrl-Alt-/"},
        exec: function(sb) {
            sb.regExpOption.checked = !sb.regExpOption.checked;
            sb.$syncOptions();
        }
    }, {
        name: "toggleCaseSensitive",
        bindKey: {win: "Alt-C|Alt-I", mac: "Ctrl-Alt-R|Ctrl-Alt-I"},
        exec: function(sb) {
            sb.caseSensitiveOption.checked = !sb.caseSensitiveOption.checked;
            sb.$syncOptions();
        }
    }, {
        name: "toggleWholeWords",
        bindKey: {win: "Alt-B|Alt-W", mac: "Ctrl-Alt-B|Ctrl-Alt-W"},
        exec: function(sb) {
            sb.wholeWordOption.checked = !sb.wholeWordOption.checked;
            sb.$syncOptions();
        }
    }]);

    this.$syncOptions = function() {
        dom.setCssClass(this.regExpOption, "checked", this.regExpOption.checked);
        dom.setCssClass(this.wholeWordOption, "checked", this.wholeWordOption.checked);
        dom.setCssClass(this.caseSensitiveOption, "checked", this.caseSensitiveOption.checked);
        this.find(false, false);
    };

    this.find = function(skipCurrent, backwards) {
        var range = this.editor.find(this.searchInput.value, {
            skipCurrent: skipCurrent,
            backwards: backwards,
            wrap: true,
            regExp: this.regExpOption.checked,
            caseSensitive: this.caseSensitiveOption.checked,
            wholeWord: this.wholeWordOption.checked
        });
        dom.setCssClass(this.searchBox, "ace_nomatch", !range && this.searchInput.value);
        this.editor.session.highlight(this.editor.$search.$options.re);
    };
    this.findNext = function() {
        this.find(true, false);
    };
    this.findPrev = function() {
        this.find(true, true);
    };
    this.replace = function() {
        this.editor.replace(this.replaceInput.value);
    };
    this.replaceAll = function() {
        this.editor.replaceAll(this.replaceInput.value);
    };

    this.hide = function () {
        this.element.style.display = "none";
        this.editor.keyBinding.removeKeyboardHandler(this.$closeSearchBarKb);
        this.editor.focus();
    };
    this.show = function(value, isReplace) {
        this.element.style.display = "";
        this.replaceBox.style.display = isReplace ? "" : "none";

        this.isReplace = isReplace;

        if (value)
            this.searchInput.value = value;
        this.searchInput.focus();
        this.searchInput.select();

        this.editor.keyBinding.addKeyboardHandler(this.$closeSearchBarKb);
    };

}).call(SearchBox.prototype);

exports.SearchBox = SearchBox;

exports.Search = function(editor, isReplace) {
    var sb = editor.searchBox || new SearchBox(editor);
    sb.show(editor.session.getTextRange(), isReplace);
};

exports.ISearch = function(session, options) {
    this.$changeListener = this.$changeListener.bind(this);
    this.startRange = session.selection.toOrientedRange();
    this.options = options || {};
};

(function(){
    this.setSession = function(session) {
        if (this.session) {
            this.session.removeListener(this.$changeListener);
        }
        this.session = session;
        this.session.addListener(this.$changeListener);
    };
    this.setSearchString = function() {

    };
    this.getValue = function() {
        if (this.value == null)
            this.value = this.session.getValue();
        return this.value;
    };
    this.$changeListener = function() {
        this.value = null;
    };
    this.find = function() {

    };
    this.$edgeBefore = function() {
        this.cursor = this.startRange[this.options.backwards ? "start" : "end"];
    };
    this.$edgeAfter = function() {

    };
    this.next = function(dir) {

    };
}).call(exports.ISearch.prototype);

});

/* ------------------------------------------------------------------------------------------
 * TODO
 * --------------------------------------------------------------------------------------- */
/*
- move search form to the left if it masks current word
- includ all options that search has. ex: regex
- searchbox.searchbox is not that pretty. we should have just searchbox
- disable prev button if it makes sence
*/
<|endoftext|>


<commit_before>const ProtocolAction = require('./_base-action.js');

/**
 * Send a sequence of key strokes to the active element. The sequence is defined in the same format as the `sendKeys` command.
 * An object map with available keys and their respective UTF-8 characters, as defined on [W3C WebDriver draft spec](https://www.w3.org/TR/webdriver/#character-types), is loaded onto the main Nightwatch instance as `client.Keys`.
 *
 * Rather than the `setValue`, the modifiers are not released at the end of the call. The state of the modifier keys is kept between calls, so mouse interactions can be performed while modifier keys are depressed.
 *
 * @example
 * module.exports = {
 *  'demo Test': function(browser) {
 *    browser
 *      .setValue('input[type=search]', 'nightwatch')
 *      .keys(browser.Keys.ENTER)
 *   }
 * }
 *
 * @param {Array|string} keysToSend The keys sequence to be sent.
 * @param {function} [callback] Optional callback function to be called when the command finishes.
 * @api protocol.useractions
 */
module.exports = class Session extends ProtocolAction {
  command(keysToSend, callback) {
    if (!Array.isArray(keysToSend)) {
      keysToSend = [keysToSend];
    }

    return this.transportActions.sendKeys(keysToSend, callback);
  }
};
<commit_msg>api-docs: update keys (#2290)<commit_after>const ProtocolAction = require('./_base-action.js');

/**
 * Send a sequence of key strokes to the active element. The sequence is defined in the same format as the `sendKeys` command.
 * An object map with available keys and their respective UTF-8 characters, as defined on [W3C WebDriver draft spec](https://www.w3.org/TR/webdriver/#character-types), is loaded onto the main Nightwatch instance as `client.Keys`.
 *
 * Rather than the `setValue`, the modifiers are not released at the end of the call. The state of the modifier keys is kept between calls, so mouse interactions can be performed while modifier keys are depressed. Pass `client.keys.NULL` to the keys function to release modifiers.
 *
 * @example
 * module.exports = {
 *  'demo Test': function(browser) {
 *    browser
 *      .keys(browser.Keys.CONTROL) // hold down CONTROL key
 *      .click('#element')
 *      .keys(browser.Keys.NULL) // release all keys
 *   }
 * }
 *
 * @param {Array|string} keysToSend The keys sequence to be sent.
 * @param {function} [callback] Optional callback function to be called when the command finishes.
 * @api protocol.useractions
 */
module.exports = class Session extends ProtocolAction {
  command(keysToSend, callback) {
    if (!Array.isArray(keysToSend)) {
      keysToSend = [keysToSend];
    }

    return this.transportActions.sendKeys(keysToSend, callback);
  }
};
<|endoftext|>


<commit_before>var fs = require('fs'),
	path = require('path'),
	baseHelper = require('./base');

/**
 * @module {function} steal-tools/lib/build/helpers/cjs
 *
 * Provides helper methods that make exporting easier.
 *
 * ```js
 * var cjsBuildHelper = require('steal-tools/lib/build/helpers/cjs');
 *
 *
 * stealPluginifier: {
 * 	 dist: {
 * 	   system: {...},
 *     options: {...},
 *     outputs: {
 * 	     cjs: cjsBuildHelper()
 *     }
 *   }
 * }
 * ```
 *
 */
module.exports = baseHelper.makeHelper({
	/**
	 * @function
	 * By default, looks for a package.json's system.main or main file.
	 *
	 * @param {Array<>} modules An array of modules to overide the main file.
	 */
	graphs: function(modules){
		if(!Array.isArray(modules)) {
			var pkg = JSON.parse( fs.readFileSync( path.join(modules || process.cwd(), "package.json" ) ) );
			var main = (pkg.system && pkg.system.main) || pkg.main;
			return [main];
		}
	},
	format: function(){
		return "cjs";
	},
	useNormalizedDependencies: function(){
		return false;
	},
	/**
	 * @function
	 *
	 * Returns a function that makes everything not in node_modules relative.
	 * @param {Object} aliases
	 */
	normalize: function(aliases){
		aliases = aliases || {};

		return function(depName, depLoad, curName, curLoad, loader){
			if(aliases[depName]) {
				return aliases[depName];
			}
			// if both not in node_modules
			if(depLoad.address.indexOf("node_modules") === -1 && curLoad.address.indexOf("node_modules") === -1) {
				// provide its name relative
				depName = path.relative(path.dirname(curLoad.address), depLoad.address);
				if(depName[0] !== ".") {
					depName = "./"+depName;
				}
			}

			// if it ends in /
			if(depName[depName.length -1] === "/") {
				var parts = depName.split("/");
				parts[parts.length -1] = parts[parts.length -2];
				depName = parts.join("/");
			}

			// if the path is already relative ... good ... keep it that way
			if(depName.indexOf("./") === 0) {
				return path.dirname(depName)+"/"+baseHelper.basename(depLoad);
			}
			// if two relative paths that are not in node_modules

			return depName;
		};

	},
	/**
	 * @function
	 *
	 * Returns a `dest` function that names everything ending in .js or .css if it doesn't already have it and
	 * moves it to `dist/cjs`.
	 * @param {Object} aliases
	 */
	dest: function(aliases, root, dist){
		aliases = aliases || {};
		root = root || process.cwd();
		dist = dist || ".";

		return function(moduleName, moduleData, load){
			if(aliases[moduleName]) {
				return path.join(root, dist, aliases[moduleName]);
			}

			// move it to lib/cjs and rename it
			var address = path.dirname(baseHelper.cleanModuleName(moduleName));
			var basename = baseHelper.basename(load);

			return path.join(root, dist, address, basename);
		};
	},
	/**
	 * @function
	 *
	 * Ignores everything in _node_modules_.
	 * @param {Object} additional
	 */
	ignore: function(additional){
		return [function(name, load){
			if(load.address.indexOf("/node_modules/") >= 0 || load.metadata.format === "defined") {
				return true;
			}
		}].concat(additional || []);
	}
});
<commit_msg>improving helper<commit_after>var fs = require('fs'),
	path = require('path'),
	baseHelper = require('./base');

/**
 * @module {function} steal-tools/lib/build/helpers/cjs
 *
 * Provides helper methods that make exporting easier.
 *
 * ```js
 * var cjsBuildHelper = require('steal-tools/lib/build/helpers/cjs');
 *
 *
 * stealPluginifier: {
 * 	 dist: {
 * 	   system: {...},
 *     options: {...},
 *     outputs: {
 * 	     cjs: cjsBuildHelper()
 *     }
 *   }
 * }
 * ```
 *
 */
module.exports = baseHelper.makeHelper({
	/**
	 * @function
	 * By default, looks for a package.json's system.main or main file.
	 *
	 * @param {Array<>} modules An array of modules to overide the main file.
	 */
	graphs: function(modules){
		if(!Array.isArray(modules)) {
			var pkg = JSON.parse( fs.readFileSync( path.join(modules || process.cwd(), "package.json" ) ) );
			var main = (pkg.system && pkg.system.main) || pkg.main;
			return [main];
		}
	},
	format: function(){
		return "cjs";
	},
	useNormalizedDependencies: function(){
		return false;
	},
	/**
	 * @function
	 *
	 * Returns a function that makes everything not in node_modules relative.
	 * @param {Object} aliases
	 */
	normalize: function(aliases){
		aliases = aliases || {};

		return function(depName, depLoad, curName, curLoad, loader){
			if(aliases[depName]) {
				return aliases[depName];
			}
			// if both not in node_modules
			if(depLoad.address.indexOf("node_modules") === -1 && curLoad.address.indexOf("node_modules") === -1) {
				// provide its name relative
				depName = path.relative(path.dirname(curLoad.address), depLoad.address);
				if(depName[0] !== ".") {
					depName = "./"+depName;
				}
			}

			// if it ends in /
			if(depName[depName.length -1] === "/") {
				var parts = depName.split("/");
				parts[parts.length -1] = parts[parts.length -2];
				depName = parts.join("/");
			}

			// if the path is already relative ... good ... keep it that way
			if(depName[0] === ".") {
				depName = path.dirname(depName)+"/"+baseHelper.basename(depLoad);
			} else if(depLoad.address.indexOf("node_modules") !== -1){
				// this means its something like can/foo
				// make sure we are referencing the package name
				var parsed = parseModuleName(depLoad.name);
				if(!parsed.packageName || !parsed.version) {
					return depName;
				}
				// SYSTEM.NAME
				var pkg = loader.npm[parsed.packageName+"@"+parsed.version];
				var systemName = pkg.system && pkg.system.name;
				if(systemName && depName.indexOf(systemName) === 0) {
					depName = depName.replace(systemName, pkg.name);
				}
			}
			// if two relative paths that are not in node_modules

			return depName;
		};

	},
	/**
	 * @function
	 *
	 * Returns a `dest` function that names everything ending in .js or .css if it doesn't already have it and
	 * moves it to `dist/cjs`.
	 * @param {Object} aliases
	 */
	dest: function(aliases, root, dist){
		aliases = aliases || {};
		root = root || process.cwd();
		dist = dist || ".";

		return function(moduleName, moduleData, load){
			if(aliases[moduleName]) {
				return path.join(root, dist, aliases[moduleName]);
			}

			// move it to lib/cjs and rename it
			var address = path.dirname(baseHelper.cleanModuleName(moduleName));
			var basename = baseHelper.basename(load);

			return path.join(root, dist, address, basename);
		};
	},
	/**
	 * @function
	 *
	 * Ignores everything in _node_modules_.
	 * @param {Object} additional
	 */
	ignore: function(additional){
		return [function(name, load){
			if(load.address.indexOf("/node_modules/") >= 0 || load.metadata.format === "defined") {
				return true;
			}
		}].concat(additional || []);
	}
});
<|endoftext|>


<commit_before>/**
 * @fileOverview Meta hosted function object.
 */
define(['exports',
        'atum/compute',
        'atum/builtin/object',
        'atum/builtin/meta/base',
        'atum/operations/error',
        'atum/operations/func',
        'atum/operations/object',
        'atum/operations/value_reference',
        'atum/value/value'],
function(exports,
        compute,
        builtin_object,
        meta_base,
        error,
        func,
        object_operations,
        value_reference,
        value){
"use strict";

/* Function
 ******************************************************************************/
/**
 * Hosted function meta object.
 */
var Function = function(proto, props) {
    meta_base.Base.call(this, proto, props);
};
Function.prototype = new meta_base.Base;
Function.prototype.constructor = Function;

Function.prototype.cls = "Function";

/**
 * Construct computation.
 */
Function.prototype.construct = function(self, args) {
    return value_reference.dereferenceFrom(
        object_operations.get(self, 'prototype'),
        function(proto, protoRef) {
            return compute.bind(
                object_operations.create(value.isObject(proto) ?
                    protoRef :
                    builtin_object.ObjectPrototype),
                function(ref) {
                    return value_reference.dereferenceFrom(
                        func.apply(self, ref, args),
                        function(result, resultRef) {
                            return compute.just(value.isObject(result) ? resultRef : ref);
                        });
                });
        });
};

/**
 * Is computation `v` an instance of function `ref`.
 */
Function.prototype.hasInstance = (function(){
    var loop = function(v, o) {
        if (!v.proto)
            return compute.no;
        return compute.bind(
            value_reference.getFrom(compute.just(v.proto)),
            function(v) {
                return (v === o ?
                    compute.yes :
                    loop(v, o));
            });
    };

    return function(ref, v) {
        return compute.bind(
            value_reference.getFrom(compute.just(v)),
            function(v) {
                if (!value.isObject(v))
                    return compute.no;
                return compute.bind(
                    value_reference.getFrom(object_operations.get(ref, 'prototype')),
                    function(o) {
                        if (!value.isObject(o))
                            return error.typeError();
                        return loop(v, o);
                    });
            });
    };
}());

/* Export
 ******************************************************************************/
exports.Function = Function;

});<commit_msg>Further meta func construct refactoring<commit_after>/**
 * @fileOverview Meta hosted function object.
 */
define(['exports',
        'atum/compute',
        'atum/builtin/object',
        'atum/builtin/meta/base',
        'atum/operations/error',
        'atum/operations/func',
        'atum/operations/object',
        'atum/operations/value_reference',
        'atum/value/value'],
function(exports,
        compute,
        builtin_object,
        meta_base,
        error,
        func,
        object_operations,
        value_reference,
        value){
"use strict";

/* Function
 ******************************************************************************/
/**
 * Hosted function meta object.
 */
var Function = function(proto, props) {
    meta_base.Base.call(this, proto, props);
};
Function.prototype = new meta_base.Base;
Function.prototype.constructor = Function;

Function.prototype.cls = "Function";

/**
 * Construct computation.
 */
Function.prototype.construct = function(self, args) {
    return compute.bind(
        value_reference.dereferenceFrom(
            object_operations.get(self, 'prototype'),
            function(proto, protoRef) {
                return object_operations.create(value.isObject(proto) ?
                    protoRef :
                    builtin_object.ObjectPrototype);
            }),
        function(t) {
            return value_reference.dereferenceFrom(
                func.apply(self, t, args),
                function(result, resultRef) {
                    return compute.just(value.isObject(result) ? resultRef : t);
                });
        });
};

/**
 * Is computation `v` an instance of function `ref`.
 */
Function.prototype.hasInstance = (function(){
    var loop = function(v, o) {
        if (!v.proto)
            return compute.no;
        return compute.bind(
            value_reference.getFrom(compute.just(v.proto)),
            function(v) {
                return (v === o ?
                    compute.yes :
                    loop(v, o));
            });
    };

    return function(ref, v) {
        return compute.bind(
            value_reference.getFrom(compute.just(v)),
            function(v) {
                if (!value.isObject(v))
                    return compute.no;
                return compute.bind(
                    value_reference.getFrom(object_operations.get(ref, 'prototype')),
                    function(o) {
                        if (!value.isObject(o))
                            return error.typeError();
                        return loop(v, o);
                    });
            });
    };
}());

/* Export
 ******************************************************************************/
exports.Function = Function;

});<|endoftext|>


<commit_before>"use strict"; // run code in ES5 strict mode

var Class = require("nodeclass").Class,
    is = require("nodeclass").is,
    DisplayObject = require("./DisplayObject.class.js"),
    PageInitializer = require("./PageInitializer.class.js"),
    resolvePageURLs = require("../shared/helpers/resolvePaths.js").resolvePageURLs,
    pageRegistry = require("../shared/registries/pageRegistry.js"),
    _ = require("underscore");

/**
 * The currentLoadId is incremented every time Page.load() is called.
 * This is necessary to abort callbacks when Page.load() itself has been called in the meantime.
 *
 * @type {Number}
 */
var currentLoadId = -1;

var Page = new Class({

    Extends: DisplayObject,

    //Change it from public to private as it was use as private in setSubPage()
    __subPage: null, //Do you mean current subPage? It is possible that there are more subPages.

    $main: null, //Is this the reference to the main page?

    $load: function (pageURL, params) {
        var pageURLs;

        params = params || {};
        currentLoadId++;
        pageURLs = resolvePageURLs(pageURL);
        changePages(pageURLs, params, currentLoadId);
    },

    /**
     * @param {Page} subPage
     */
    setSubPage: function (subPage) {
        var self;

        if (is(subPage).notInstanceOf(Page)) {
            throw new TypeError("(alamid) Cannot set new subpage: The subpage must be an instance of Page");
        }

        //Why should the page be completely destroyed. I think it is useful to keep it somewhere.
        //This way the page mustn't be loaded again on "back-button"
        if (this.__subPage) {
            this.__subPage.dispose();
        }

        //@TODO: two event listeners are needed here if the DisplayObject is not refactored
        // https://github.com/peerigon/alamid/issues/54
        subPage.once("destroy", function onDestroy() {
            self.__subPage = null;
        });

        this.Super._append(subPage).at("page");

        this.__subPage = subPage; //I've added this line, because otherwise __subPage won't be never set.

        this.Super.emit("subPageChanged", subPage);
    },

    getAllSubPages: function () {
        //TODO invokes getAllSubPages() recursively on the sub page and returns an array with all sub pages
    }
});

//@TODO Make this function static
//That should be not a part of the page

}

module.exports = Page;<commit_msg>Remove Syntax-Error and require to deleted PageInitializer.js<commit_after>"use strict"; // run code in ES5 strict mode

var Class = require("nodeclass").Class,
    is = require("nodeclass").is,
    DisplayObject = require("./DisplayObject.class.js"),
    resolvePageURLs = require("../shared/helpers/resolvePaths.js").resolvePageURLs,
    pageRegistry = require("../shared/registries/pageRegistry.js"),
    _ = require("underscore");

/**
 * The currentLoadId is incremented every time Page.load() is called.
 * This is necessary to abort callbacks when Page.load() itself has been called in the meantime.
 *
 * @type {Number}
 */
var currentLoadId = -1;

var Page = new Class({

    Extends: DisplayObject,

    //Change it from public to private as it was use as private in setSubPage()
    __subPage: null, //Do you mean current subPage? It is possible that there are more subPages.

    $main: null, //Is this the reference to the main page?

    $load: function (pageURL, params) {
        var pageURLs;

        params = params || {};
        currentLoadId++;
        pageURLs = resolvePageURLs(pageURL);
        changePages(pageURLs, params, currentLoadId);
    },

    /**
     * @param {Page} subPage
     */
    setSubPage: function (subPage) {
        var self;

        if (is(subPage).notInstanceOf(Page)) {
            throw new TypeError("(alamid) Cannot set new subpage: The subpage must be an instance of Page");
        }

        //Why should the page be completely destroyed. I think it is useful to keep it somewhere.
        //This way the page mustn't be loaded again on "back-button"
        if (this.__subPage) {
            this.__subPage.dispose();
        }

        //@TODO: two event listeners are needed here if the DisplayObject is not refactored
        // https://github.com/peerigon/alamid/issues/54
        subPage.once("destroy", function onDestroy() {
            self.__subPage = null;
        });

        this.Super._append(subPage).at("page");

        this.__subPage = subPage; //I've added this line, because otherwise __subPage won't be never set.

        this.Super.emit("subPageChanged", subPage);
    },

    getAllSubPages: function () {
        //TODO invokes getAllSubPages() recursively on the sub page and returns an array with all sub pages
    }
});

module.exports = Page;<|endoftext|>


<commit_before>var CloudCommander;
var CloudFunc;
CloudCommander.keyBinding=(function(){
    "use strict";
    var key_event=function(event){
            var lCurrentFile;
            var lName;
            /* если клавиши можно обрабатывать*/
            if(CloudCommander.keyBinded){
                /* если нажали таб:
                 * переносим курсор на
                 * правую панель, если
                 * мы были на левой и
                 * наоборот
                 */
                if(event.keyCode===9){
                    console.log('Tab pressed');
                    try{
                        lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE)[0];
                    }catch(error){console.log(error);}
                }
                /* навигация по таблице файлов*/
                /* если нажали клавишу вверх*/
                else if(event.keyCode===38){
                    /* получаем выдленный файл*/
                    lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE);
                    /* если ненайдены выделенные файлы - выходим*/
                    if(lCurrentFile.length===0)return;
                    lCurrentFile=lCurrentFile[0];
                    /* если это строка существет и
                     * если она не заголовок
                     * файловой таблицы
                     */
                    if(lCurrentFile.previousSibling &&
                       lCurrentFile.previousSibling.className!=='fm_header' ){
                        /* убираем выделение с текущего элемента */
                        lCurrentFile.className='';
                        /* и выделяем предыдущую строку*/
                        lCurrentFile.previousSibling.className = CloudCommander.CURRENT_FILE;
                        console.log(lCurrentFile.nextSibling.offsetTop);
                        event.preventDefault();
                    }
                }
                /* если нажали клавишу в низ*/
                else if(event.keyCode===40){
                    /* получаем выдленный файл*/
                    lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE);
                    /* если ненайдены выделенные файлы - выходим*/
                    if(lCurrentFile.length===0)return;
                    lCurrentFile=lCurrentFile[0];
                    /* если это не последняя строка */
                    if(lCurrentFile.nextSibling){
                        /* убираем с него выделение */
                        lCurrentFile.className='';
                        /* выделяем следующую строку*/
                        lCurrentFile.nextSibling.className = CloudCommander.CURRENT_FILE;
                        console.log(lCurrentFile.nextSibling.offsetTop);
                        event.preventDefault();
                    }
                }
                /* если нажали клавишу page up или Home
                 * переходим к самому верхнему
                 * элементу
                 */
                else if(/*event.keyCode===33 ||*/ event.keyCode===36){
                        lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE)[0];
                        /* убираем выделение с текущего файла*/
                        lCurrentFile.className='';
                        /* получаем первый элемент*/
                        lCurrentFile.parentElement.firstElementChild
                        /* пропускаем путь и заголовки столбиков*/
                            .nextElementSibling.nextElementSibling
                            /* выделяем верхий файл */
                            .className=CloudCommander.CURRENT_FILE;
                }
                /* если нажали клавишу page down или End
                 * выделяем последний элемент
                 */
                else if(/*event.keyCode===34 ||*/ event.keyCode===35){
                        lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE)[0];
                        /* снимаем выделение с текущего файла*/
                        lCurrentFile.className='';
                        /* выделяем самый нижний файл */
                        lCurrentFile.parentElement.lastElementChild.className=CloudCommander.CURRENT_FILE;
                }
                /* если нажали Enter - открываем папку*/
                else if(event.keyCode===13){
                    lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE);
                    /* если ненайдены выделенные файлы - выходим*/
                    if(!lCurrentFile.length)return;
                    lCurrentFile=lCurrentFile[0];
                    /* из него достаём спан с именем файла*/
                    lName=lCurrentFile.getElementsByClassName('name');
                    /* если нету (что вряд ли) - выходим*/
                    if(!lName)return false;
                    /* достаём все ссылки*/
                    var lATag=lName[0].getElementsByTagName('a');
                    /* если нету - выходим */
                    if(!lATag)return false;

                    /* вызываем ajaxload привязанный через changelinks
                     * пробулем нажать на ссылку, если не получиться
                     * (opera, ie), вызываем событие onclick,
                     * которое пока не прописано у файлов
                     */

                     if(lCurrentFile.onclick)lCurrentFile.onclick(true);
                     else try{
                         lATag[0].click();
                     }
                     catch(error){
                         console.log(error);
                     }
                }
                /* если нажали <ctr>+r
                 * обновляем страницу,
                 * загружаем содержимое каталога
                 * при этом данные берём всегда с
                 * сервера, а не из кэша
                 * (обновляем кэш)
                 */
                else if(event.keyCode===82 &&
                    event.ctrlKey){
                    console.log('<ctrl>+r pressed');
                    console.log('reloading page...');
                    console.log('press <alt>+q to remove all key-handlers');
                    /* Программно нажимаем на кнопку перезагрузки
                     * содержимого каталога
                     */
                    var lRefreshIcon=document.getElementsByClassName(CloudFunc.REFRESHICON);
                    if(lRefreshIcon)lRefreshIcon=lRefreshIcon[0];
                    if(lRefreshIcon){
                        /* находим файл который сейчас выделен */
                         lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE);
                         if(lCurrentFile.length>0)lCurrentFile=lCurrentFile[0];
                         /* получаем название файла*/
                         var lSelectedName=lCurrentFile.getElementsByTagName('a')[0].textContent;
                         /* если нашли элемент нажимаем него
                          * а если не можем - нажимаем на
                          * ссылку, на которую повешен eventHandler
                          * onclick
                          */
                        if(lRefreshIcon.click)lRefreshIcon.parentElement.click();
                        else lRefreshIcon.parentElement.onclick();

                        /* перебираем файлы левой панели
                         * в поисках подсвеченого файла
                         */
                        var lLeft=document.getElementById('left');
                        if(lLeft){
                            /* перебираем все файлы в панели */
                            var lLi=lLeft.getElementsByTagName('li');
                            lCurrentFile.className='';
                            /* начинаем с 2-ух, по скольку
                             * 0 - это путь
                             * 1 - это заголовок файловой таблицы
                             */
                            for(var i=2;i<lLi.length;i++){
                                lName=lLi[i].getElementsByTagName('a')[0].textContent;
                                if(lSelectedName.length===lName.length &&
                                    !lSelectedName.indexOf(lName)){
                                        lLi[i].className=CloudCommander.CURRENT_FILE;
                                        break;
                                }
                            }
                        }

                        event.preventDefault();//запрет на дальнейшее действие
                    }
                }
                /* если нажали <ctrl>+d чистим кэш */
                else if(event.keyCode===68 &&
                    event.ctrlKey){
                        console.log('<ctrl>+d pressed');
                        console.log('clearing cache...');
                        console.log('press <alt>+q to remove all key-handlers');

                        var lClearCache=document.getElementById('clear-cache');
                        if(lClearCache && lClearCache.onclick)lClearCache.onclick();

                        event.preventDefault();//запрет на дальнейшее действие
                }
                /* если нажали <alt>+q
                 * убираем все обработчики
                 * нажатий клавиш
                 */
                else if(event.keyCode===81 &&
                    event.altKey){
                        //document.removeEventListener('keydown', key_event,false);
                        console.log('<alt>+q pressed');
                        console.log('<ctrl>+r reload key-handerl - removed');
                        console.log('<ctrl>+s clear cache key-handler - removed');
                        console.log('press <alt>+s to to set them');

                        /* обработчик нажатий клавиш снят*/
                        CloudCommander.keyBinded=false;
                }
            }
            /* если нажали <alt>+s
             * устанавливаем все обработчики
             * нажатий клавиш
             */
            else if(event.keyCode===83 &&
                event.altKey){
                    /*
                        document.addEventListener('keydown', key_event,false);
                    */
                    /* обрабатываем нажатия на клавиши*/
                    CloudCommander.keyBinded=true;

                    console.log('<alt>+s pressed');
                    console.log('<ctrl>+r reload key-handerl - set');
                    console.log('<ctrl>+s clear cache key-handler - set');
                    console.log('press <alt>+q to remove them');
            }

         return false;
    };
    /* добавляем обработчик клавишь */
    if(document.addEventListener)
        document.addEventListener('keydown', key_event,false);
    else document.onkeypress=key_event;
    /* клавиши назначены*/
    CloudCommander.keyBinded=true;
});<commit_msg>minor changes<commit_after>var CloudCommander;
var CloudFunc;
CloudCommander.keyBinding=(function(){
    "use strict";
    var key_event=function(event){
            var lCurrentFile;
            var lName;
            /* если клавиши можно обрабатывать*/
            if(CloudCommander.keyBinded){
                /* если нажали таб:
                 * переносим курсор на
                 * правую панель, если
                 * мы были на левой и
                 * наоборот
                 */
                if(event.keyCode===9){
                    console.log('Tab pressed');
                    try{
                        lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE)[0];
                    }catch(error){console.log(error);}
                }
                /* навигация по таблице файлов*/
                /* если нажали клавишу вверх*/
                else if(event.keyCode===38){
                    /* получаем выдленный файл*/
                    lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE);
                    /* если ненайдены выделенные файлы - выходим*/
                    if(lCurrentFile.length===0)return;
                    lCurrentFile=lCurrentFile[0];
                    /* если это строка существет и
                     * если она не заголовок
                     * файловой таблицы
                     */
                    if(lCurrentFile.previousSibling &&
                       lCurrentFile.previousSibling.className!=='fm_header' ){
                        /* убираем выделение с текущего элемента */
                        lCurrentFile.className='';
                        /* и выделяем предыдущую строку*/
                        lCurrentFile.previousSibling.className = CloudCommander.CURRENT_FILE;
                        console.log(lCurrentFile.previousSibling.offsetTop);
                        event.preventDefault();
                    }
                }
                /* если нажали клавишу в низ*/
                else if(event.keyCode===40){
                    /* получаем выдленный файл*/
                    lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE);
                    /* если ненайдены выделенные файлы - выходим*/
                    if(lCurrentFile.length===0)return;
                    lCurrentFile=lCurrentFile[0];
                    /* если это не последняя строка */
                    if(lCurrentFile.nextSibling){
                        /* убираем с него выделение */
                        lCurrentFile.className='';
                        /* выделяем следующую строку*/
                        lCurrentFile.nextSibling.className = CloudCommander.CURRENT_FILE;
                        console.log(lCurrentFile.nextSibling.offsetTop);
                        event.preventDefault();
                    }
                }
                /* если нажали клавишу page up или Home
                 * переходим к самому верхнему
                 * элементу
                 */
                else if(/*event.keyCode===33 ||*/ event.keyCode===36){
                        lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE)[0];
                        /* убираем выделение с текущего файла*/
                        lCurrentFile.className='';
                        /* получаем первый элемент*/
                        lCurrentFile.parentElement.firstElementChild
                        /* пропускаем путь и заголовки столбиков*/
                            .nextElementSibling.nextElementSibling
                            /* выделяем верхий файл */
                            .className=CloudCommander.CURRENT_FILE;
                }
                /* если нажали клавишу page down или End
                 * выделяем последний элемент
                 */
                else if(/*event.keyCode===34 ||*/ event.keyCode===35){
                        lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE)[0];
                        /* снимаем выделение с текущего файла*/
                        lCurrentFile.className='';
                        /* выделяем самый нижний файл */
                        lCurrentFile.parentElement.lastElementChild.className=CloudCommander.CURRENT_FILE;
                }
                /* если нажали Enter - открываем папку*/
                else if(event.keyCode===13){
                    lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE);
                    /* если ненайдены выделенные файлы - выходим*/
                    if(!lCurrentFile.length)return;
                    lCurrentFile=lCurrentFile[0];
                    /* из него достаём спан с именем файла*/
                    lName=lCurrentFile.getElementsByClassName('name');
                    /* если нету (что вряд ли) - выходим*/
                    if(!lName)return false;
                    /* достаём все ссылки*/
                    var lATag=lName[0].getElementsByTagName('a');
                    /* если нету - выходим */
                    if(!lATag)return false;

                    /* вызываем ajaxload привязанный через changelinks
                     * пробулем нажать на ссылку, если не получиться
                     * (opera, ie), вызываем событие onclick,
                     * которое пока не прописано у файлов
                     */

                     if(lCurrentFile.onclick)lCurrentFile.onclick(true);
                     else try{
                         lATag[0].click();
                     }
                     catch(error){
                         console.log(error);
                     }
                }
                /* если нажали <ctr>+r
                 * обновляем страницу,
                 * загружаем содержимое каталога
                 * при этом данные берём всегда с
                 * сервера, а не из кэша
                 * (обновляем кэш)
                 */
                else if(event.keyCode===82 &&
                    event.ctrlKey){
                    console.log('<ctrl>+r pressed');
                    console.log('reloading page...');
                    console.log('press <alt>+q to remove all key-handlers');
                    /* Программно нажимаем на кнопку перезагрузки
                     * содержимого каталога
                     */
                    var lRefreshIcon=document.getElementsByClassName(CloudFunc.REFRESHICON);
                    if(lRefreshIcon)lRefreshIcon=lRefreshIcon[0];
                    if(lRefreshIcon){
                        /* находим файл который сейчас выделен */
                         lCurrentFile=document.getElementsByClassName(CloudCommander.CURRENT_FILE);
                         if(lCurrentFile.length>0)lCurrentFile=lCurrentFile[0];
                         /* получаем название файла*/
                         var lSelectedName=lCurrentFile.getElementsByTagName('a')[0].textContent;
                         /* если нашли элемент нажимаем него
                          * а если не можем - нажимаем на
                          * ссылку, на которую повешен eventHandler
                          * onclick
                          */
                        if(lRefreshIcon.click)lRefreshIcon.parentElement.click();
                        else lRefreshIcon.parentElement.onclick();

                        /* перебираем файлы левой панели
                         * в поисках подсвеченого файла
                         */
                        var lLeft=document.getElementById('left');
                        if(lLeft){
                            /* перебираем все файлы в панели */
                            var lLi=lLeft.getElementsByTagName('li');
                            lCurrentFile.className='';
                            /* начинаем с 2-ух, по скольку
                             * 0 - это путь
                             * 1 - это заголовок файловой таблицы
                             */
                            for(var i=2;i<lLi.length;i++){
                                lName=lLi[i].getElementsByTagName('a')[0].textContent;
                                if(lSelectedName.length===lName.length &&
                                    !lSelectedName.indexOf(lName)){
                                        lLi[i].className=CloudCommander.CURRENT_FILE;
                                        break;
                                }
                            }
                        }

                        event.preventDefault();//запрет на дальнейшее действие
                    }
                }
                /* если нажали <ctrl>+d чистим кэш */
                else if(event.keyCode===68 &&
                    event.ctrlKey){
                        console.log('<ctrl>+d pressed');
                        console.log('clearing cache...');
                        console.log('press <alt>+q to remove all key-handlers');

                        var lClearCache=document.getElementById('clear-cache');
                        if(lClearCache && lClearCache.onclick)lClearCache.onclick();

                        event.preventDefault();//запрет на дальнейшее действие
                }
                /* если нажали <alt>+q
                 * убираем все обработчики
                 * нажатий клавиш
                 */
                else if(event.keyCode===81 &&
                    event.altKey){
                        //document.removeEventListener('keydown', key_event,false);
                        console.log('<alt>+q pressed');
                        console.log('<ctrl>+r reload key-handerl - removed');
                        console.log('<ctrl>+s clear cache key-handler - removed');
                        console.log('press <alt>+s to to set them');

                        /* обработчик нажатий клавиш снят*/
                        CloudCommander.keyBinded=false;
                }
            }
            /* если нажали <alt>+s
             * устанавливаем все обработчики
             * нажатий клавиш
             */
            else if(event.keyCode===83 &&
                event.altKey){
                    /*
                        document.addEventListener('keydown', key_event,false);
                    */
                    /* обрабатываем нажатия на клавиши*/
                    CloudCommander.keyBinded=true;

                    console.log('<alt>+s pressed');
                    console.log('<ctrl>+r reload key-handerl - set');
                    console.log('<ctrl>+s clear cache key-handler - set');
                    console.log('press <alt>+q to remove them');
            }

         return false;
    };
    /* добавляем обработчик клавишь */
    if(document.addEventListener)
        document.addEventListener('keydown', key_event,false);
    else document.onkeypress=key_event;
    /* клавиши назначены*/
    CloudCommander.keyBinded=true;
});<|endoftext|>


<commit_before>SchemaPlain.roles = {
    name: {
        type: String,
        unique: true,
        index: true,
        label: "Name"
    },
    groupId: {
        type: String,
        index:true
    }
};

Schemas.roles = new SimpleSchema(SchemaPlain.roles);
Meteor.roles.attachSchema(Schemas.roles);<commit_msg>made groupId optional<commit_after>SchemaPlain.roles = {
    name: {
        type: String,
        unique: true,
        index: true,
        label: "Name"
    },
    groupId: {
        type: String,
        index:true,
        optional:true
    }
};

Schemas.roles = new SimpleSchema(SchemaPlain.roles);
Meteor.roles.attachSchema(Schemas.roles);<|endoftext|>