<commit_before>// Gulpfile
var fs          = require('fs');
var path        = require('path');
var gulp        = require('gulp');
var gutil       = require('gulp-util');
var jscs        = require('gulp-jscs');
var karma       = require('karma').server;
var eslint      = require('gulp-eslint');
var mocha       = require('gulp-mocha');
var mochaSelenium = require('gulp-mocha-selenium');
var nodemon     = require('gulp-nodemon');
var connect     = require('gulp-connect');
var shell       = require('gulp-shell');
var sass        = require('gulp-sass');
var webpack     = require('webpack');
var del         = require('del');
var vinylPaths  = require('vinyl-paths');
var browserSync = require('browser-sync');
var reload      = browserSync.reload;

// Webpack configs
var buildCfg    = require('./webpack.config');
var buildDevCfg = require('./webpack.dev-config');

var src  = './client/';
var dest = './build/';

// ----------------------------------------------------------------------------
// Constants
// ----------------------------------------------------------------------------
var FRONTEND_FILES = [
  src + 'js/**/*.{js,jsx}'
];

var HTML_FILES = [
  src + 'index.html',
  src + 'style-guide.html'
];

var ASSETS = [
  src + 'assets/**/*'
];

var CSS = [
  src + 'css/**/*.css'
];

var BACKEND_FILES = [
  'test/server/**/*.js',
  '*.js'
];

// ----------------------------------------------------------------------------
// Helpers
// ----------------------------------------------------------------------------
// Strip comments from JsHint JSON files (naive).
var _jsonCfg = function(name) {
  var raw = fs.readFileSync(name).toString();
  return JSON.parse(raw.replace(/\/\/.*\n/g, ''));
};

var logReload = function() {
  console.log('reloading!');
  reload({stream: true});
};

// ----------------------------------------------------------------------------
// EsLint
// ----------------------------------------------------------------------------
gulp.task('eslint-frontend', function() {
  return gulp
    .src(FRONTEND_FILES)
    .pipe(eslint({
      configFile: './.eslintrc',
      envs: [
        'browser'
      ]
    }))
    .pipe(eslint.formatEach('stylish', process.stderr))
    .pipe(eslint.failOnError());
});

gulp.task('eslint-backend', function() {
  return gulp
    .src(BACKEND_FILES)
    .pipe(eslint({
      configGile: './.eslintrc',
      envs: [
        'node'
      ]
    }))
    .pipe(eslint.formatEach('stylish', process.stderr))
    .pipe(eslint.failOnError());
});

gulp.task('eslint', ['eslint-frontend', 'eslint-backend']);

// ----------------------------------------------------------------------------
// JSCS - JavaScript Code Style
// ----------------------------------------------------------------------------
gulp.task('jscs', function() {
  return gulp
    .src([].concat(
      FRONTEND_FILES,
      BACKEND_FILES
    ))
    .pipe(jscs(_jsonCfg('.jscsrc')));
});

// ----------------------------------------------------------------------------
// Check Code Quality
// ----------------------------------------------------------------------------
/* uncomment when eslint works
gulp.task('check', ['jscs', 'eslint']);
gulp.task('check:ci', ['jscs', 'eslint']);
gulp.task('check:all', ['jscs', 'eslint']);
*/
gulp.task('check', ['jscs']);
gulp.task('check:ci', ['jscs']);
gulp.task('check:all', ['jscs']);

// ----------------------------------------------------------------------------
// Cleaning
// ----------------------------------------------------------------------------
gulp.task('clean', function() {
  return gulp
    .src(dest, { read: false })
    .pipe(vinylPaths(del));
});

// ----------------------------------------------------------------------------
// Copying, Building and Watching
// ----------------------------------------------------------------------------

// copy static html files
gulp.task('copy:html', function() {
  gulp.src(HTML_FILES)
    .pipe(gulp.dest(dest));
});

// copy (mostly imported UW) assets
gulp.task('copy:assets', function() {
  gulp.src(ASSETS)
    .pipe(gulp.dest(path.join(dest, 'assets')));
});

// copy plain css
gulp.task('copy:css', function() {
  gulp.src(CSS)
    .pipe(gulp.dest(path.join(dest, 'css')));
});

// roll-up copy task
gulp.task('copy', ['copy:assets', 'copy:css', 'copy:html']);

// compile Sass
gulp.task('sass', function() {
  gulp.src(path.join(src, 'sass', '*.scss'))
    .pipe(sass(
      {
        sourcemap: true,
        includePaths: require('node-bourbon').includePaths
      }
    ))
    .pipe(gulp.dest(path.join(dest, 'css')))
    .pipe(reload({stream: true}));
});

// webpack the javascript
gulp.task('webpack', function(done) {

  webpack(buildDevCfg).run(function(err, stats) {
    if (err) { throw new gutil.PluginError('webpack', err); }

    gutil.log('[webpack]', stats.toString({
      hash: true,
      colors: true,
      cached: false
    }));

    done();
  });
});

// copy static and then build js
gulp.task('build:dev', ['copy', 'sass', 'webpack']);

gulp.task('watch', ['build:dev', 'browser-sync'], function() {
  gulp.watch([
    path.join(src, 'js', '**', '*.{js,jsx}'),
    path.join(src, 'sass', '**', '*.scss')
  ], ['webpack']).on('change', logReload);
});

gulp.task('browser-sync', function() {
  browserSync({
    ui: {
      port: 3003
    },
    files: [path.join(dest, '**', '*')],
    port: 3002,
    proxy: 'http://localhost:3000',
    open: false
  });
});

// ----------------------------------------------------------------------------
// Production
// ----------------------------------------------------------------------------
gulp.task('build:prod', function(done) {
  webpack(buildCfg).run(function(err, stats) {
    if (err) { throw new gutil.PluginError('webpack', err); }

    gutil.log('[webpack]', stats.toString({
      hash: true,
      colors: true,
      cached: false
    }));

    done();
  });
});

gulp.task('build:prod-full', ['clean'], function() {
  return gulp.run('build:prod');
});

gulp.task('watch:prod', function() {
  gulp.watch([
    path.join('build', '**', '*.{js,jsx}')
  ], ['build:prod']);
});

// ----------------------------------------------------------------------------
// Servers
// ----------------------------------------------------------------------------
// Dev. server with watch
var called = false;
gulp.task('server', function(cb) {
  return nodemon({
    script: 'server.js',
    ext: 'js,jsx',
    watch: [
      'server',
      src
    ]
  })
  .on('start', function onStart() {
    if (!called) { cb(); }
    called = true;
  })
  .on('restart', function onRestart() {
    //delay the browser reload
    setTimeout(function reload() {
      browserSync.reload({stream: false});
    }, 500);
  });
});

// Hot reload webpack server
gulp.task('webpack-server', shell.task(['node ./hot/server']));

// Source maps server
gulp.task('server:sources', function() {
  connect.server({
    root: __dirname,
    port: 3001
  });
});

// ----------------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------------

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

gulp.task('test:server', function(done) {
  // set port != 3000 in order to not conflict with karma and selenium
  process.env.PORT = 3010;
  return gulp.src(path.join('test', 'server', '**', '*-spec.js'), {read: false})
  .pipe(mocha({reporter: 'dot'}), done);
});

gulp.task('test:acceptance', function(done) {
  return gulp.src('test/acceptance/*-spec.js', {read: false})
    .pipe(mochaSelenium({
      browserName: 'firefox',
      // make sure to launch Selenium server in another terminal window first
      // `brew install selenium-server`
      // `npm -g install selenium-server`
      // or get the jar file:
      // `wget http://selenium-release.storage.googleapis.com/2.45/selenium-server-standalone-2.45.0.jar`
      // `java -jar selenium-server-standalone-2.45.0.jar > /dev/null &`
      host: 'localhost',
      port: '4444',
      // host: 'ondemand.saucelabs.com',
      // port: '80',
      // username: process.env.SAUCE_USERNAME,
      // accesskey: process.env.SAUCE_ACCESS_KEY,
      // useSystemPhantom: true,
      bail: true,
      reporter: 'dot',
      usePromises: true,
      timeout: 15000
    })
    .once('end', function() {
    /* eslint-disable no-process-exit */
      process.exit();
    /* eslint-enable no-process-exit */}
    ), done);

});

// ----------------------------------------------------------------------------
// Aggregations
// ----------------------------------------------------------------------------
gulp.task('serve', ['server']);
gulp.task('test', ['test:server', 'test:karma', 'test:acceptance']);
gulp.task('ls', ['build:ls', 'watch:ls', 'server:sources']);
gulp.task('dev', ['build:dev', 'watch', 'server', 'server:sources']);
gulp.task('hot', ['webpack-server']);
gulp.task('prod', ['build:prod', 'watch:prod', 'server', 'server:sources']);
gulp.task('build', ['build:prod-full']);
gulp.task('default', ['check', 'dev']);
<commit_msg>fix auto reloading of components<commit_after>// Gulpfile
var fs            = require('fs');
var path          = require('path');
var gulp          = require('gulp');
var gutil         = require('gulp-util');
var jscs          = require('gulp-jscs');
var karma         = require('karma').server;
var eslint        = require('gulp-eslint');
var mocha         = require('gulp-mocha');
var mochaSelenium = require('gulp-mocha-selenium');
var nodemon       = require('gulp-nodemon');
var connect       = require('gulp-connect');
var shell         = require('gulp-shell');
var sass          = require('gulp-sass');
var webpack       = require('webpack');
var del           = require('del');
var vinylPaths    = require('vinyl-paths');
var browserSync   = require('browser-sync');
var reload        = browserSync.reload;

// Webpack configs
var buildCfg    = require('./webpack.config');
var buildDevCfg = require('./webpack.dev-config');

var src  = './client/';
var dest = './build/';

// ----------------------------------------------------------------------------
// Constants
// ----------------------------------------------------------------------------
var FRONTEND_FILES = [
  src + 'js/**/*.{js,jsx}'
];

var HTML_FILES = [
  src + 'index.html',
  src + 'style-guide.html'
];

var ASSETS = [
  src + 'assets/**/*'
];

var STYLE_CSS = [
  src + 'css/**/*.css'
];

var BACKEND_FILES = [
  'test/server/**/*.js',
  '*.js'
];

// ----------------------------------------------------------------------------
// Helpers
// ----------------------------------------------------------------------------
// Strip comments from JsHint JSON files (naive).
var _jsonCfg = function(name) {
  var raw = fs.readFileSync(name).toString();
  return JSON.parse(raw.replace(/\/\/.*\n/g, ''));
};

var logReload = function() {
  console.log('reloading!');
  reload({stream: true});
};

// ----------------------------------------------------------------------------
// EsLint
// ----------------------------------------------------------------------------
gulp.task('eslint-frontend', function() {
  return gulp
    .src(FRONTEND_FILES)
    .pipe(eslint({
      configFile: './.eslintrc',
      envs: [
        'browser'
      ]
    }))
    .pipe(eslint.formatEach('stylish', process.stderr))
    .pipe(eslint.failOnError());
});

gulp.task('eslint-backend', function() {
  return gulp
    .src(BACKEND_FILES)
    .pipe(eslint({
      configFile: './.eslintrc',
      envs: [
        'node'
      ]
    }))
    .pipe(eslint.formatEach('stylish', process.stderr))
    .pipe(eslint.failOnError());
});

gulp.task('eslint', ['eslint-frontend', 'eslint-backend']);

// ----------------------------------------------------------------------------
// JSCS - JavaScript Code Style
// ----------------------------------------------------------------------------
gulp.task('jscs', function() {
  return gulp
    .src([].concat(
      FRONTEND_FILES,
      BACKEND_FILES
    ))
    .pipe(jscs(_jsonCfg('.jscsrc')));
});

// ----------------------------------------------------------------------------
// Check Code Quality
// ----------------------------------------------------------------------------

gulp.task('check', ['jscs', 'eslint']);
gulp.task('check:ci', ['jscs', 'eslint']);
gulp.task('check:all', ['jscs', 'eslint']);

// ----------------------------------------------------------------------------
// Cleaning
// ----------------------------------------------------------------------------
gulp.task('clean', function() {
  return gulp
    .src(dest, { read: false })
    .pipe(vinylPaths(del));
});

// ----------------------------------------------------------------------------
// Copying, Building and Watching
// ----------------------------------------------------------------------------

// copy static html files
gulp.task('copy:html', function() {
  gulp.src(HTML_FILES)
    .pipe(gulp.dest(dest));
});

// copy (mostly imported UW) assets
gulp.task('copy:assets', function() {
  gulp.src(ASSETS)
    .pipe(gulp.dest(path.join(dest, 'assets')));
});

// copy plain css
gulp.task('copy:css', function() {
  gulp.src(STYLE_CSS)
    .pipe(gulp.dest(path.join(dest, 'css')));
});

// roll-up copy task
gulp.task('copy', ['copy:assets', 'copy:css', 'copy:html']);

// compile Sass
gulp.task('sass', function() {
  gulp.src(path.join(src, 'sass', '*.scss'))
    .pipe(sass(
      {
        sourcemap: true,
        includePaths: require('node-bourbon').includePaths
      }
    ))
    .pipe(gulp.dest(path.join(dest, 'css')))
    .pipe(reload({stream: true}));
});

// webpack the javascript
gulp.task('webpack', function(done) {

  webpack(buildDevCfg).run(function(err, stats) {
    if (err) { throw new gutil.PluginError('webpack', err); }

    gutil.log('[webpack]', 'bundling');

    /* useful for debugging webpack
    gutil.log('[webpack]', stats.toString({
      hash: true,
      colors: true,
      cached: false
    }));
    */

    done();
  });
});

// copy static and then build js
gulp.task('build:dev', ['copy', 'sass', 'webpack']);

gulp.task('watch', function() {
  gulp.watch([
    path.join(src, 'js', '**', '*.{js,jsx}'),
    path.join(src, 'sass', '**', '*.scss'),
    path.join(src, 'index.html')
  ], ['webpack']).on('change', logReload);
});

gulp.task('browser-sync', function() {
  browserSync({
    ui: {
      port: 3003
    },
    files: [path.join(dest, '**', '*')],
    port: 3002,
    proxy: 'http://localhost:3000',
    open: false
  });
});

// ----------------------------------------------------------------------------
// Production
// ----------------------------------------------------------------------------
gulp.task('build:prod', function(done) {
  webpack(buildCfg).run(function(err, stats) {
    if (err) { throw new gutil.PluginError('webpack', err); }

    gutil.log('[webpack]', stats.toString({
      hash: true,
      colors: true,
      cached: false
    }));

    done();
  });
});

gulp.task('build:prod-full', ['clean'], function() {
  return gulp.run('build:prod');
});

gulp.task('watch:prod', function() {
  gulp.watch([
    path.join('build', '**', '*.{js,jsx}')
  ], ['build:prod']);
});

// ----------------------------------------------------------------------------
// Servers
// ----------------------------------------------------------------------------
// Dev. server
var called = false;
gulp.task('server', function(cb) {
  return nodemon({
    script: 'server.js',
    ext: 'js,jsx',
    watch: [
      'server',
      path.join(src, 'index.html')
    ]
  })
  .on('start', function onStart() {
    if (!called) { cb(); }

    called = true;
  })
  .on('restart', function onRestart() {
    //delay the browser reload
    setTimeout(function reload() {
      browserSync.reload({stream: false});
    }, 500);
  });
});

// Hot reload webpack server
gulp.task('webpack-server', shell.task(['node ./hot/server']));

// Source maps server
gulp.task('server:sources', function() {
  connect.server({
    root: __dirname,
    port: 3001
  });
});

// ----------------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------------

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

gulp.task('test:server', function(done) {
  // set port != 3000 in order to not conflict with karma and selenium
  process.env.PORT = 3010;
  return gulp.src(path.join('test', 'server', '**', '*-spec.js'), {read: false})
    .pipe(mocha({reporter: 'dot'}), done);
});

gulp.task('test:acceptance', function(done) {
  return gulp.src('test/acceptance/*-spec.js', {read: false})
    .pipe(mochaSelenium({
      browserName: 'firefox',

      // make sure to launch Selenium server in another terminal window first
      // `brew install selenium-server`
      // `npm -g install selenium-server`
      // or get the jar file:
      // `wget http://selenium-release.storage.googleapis.com/2.45/selenium-server-standalone-2.45.0.jar`
      // `java -jar selenium-server-standalone-2.45.0.jar > /dev/null &`
      host: 'localhost',
      port: '4444',

      // Config for using Sauce Labs
      // host: 'ondemand.saucelabs.com',
      // port: '80',
      // username: process.env.SAUCE_USERNAME,
      // accesskey: process.env.SAUCE_ACCESS_KEY,
      // useSystemPhantom: true,
      bail: true,
      reporter: 'dot',
      usePromises: true,
      timeout: 15000
    })
      .once('end', function() {
        /* eslint-disable no-process-exit */
        process.exit();

        /* eslint-enable no-process-exit */
      }

    ), done);

});

// ----------------------------------------------------------------------------
// Aggregations
// ----------------------------------------------------------------------------
gulp.task('serve', ['server']);
gulp.task('test', ['test:server', 'test:karma', 'test:acceptance']);
gulp.task('ls', ['build:ls', 'watch:ls', 'server:sources']);
gulp.task('dev', ['build:dev', 'watch', 'server', 'server:sources', 'browser-sync']);
gulp.task('hot', ['webpack-server']);
gulp.task('prod', ['build:prod', 'watch:prod', 'server', 'server:sources']);
gulp.task('build', ['build:prod-full']);
gulp.task('default', ['check', 'dev']);
<|endoftext|>


<commit_before>var gulp = require('gulp'),
  bump = require('gulp-bump'),
  git = require('gulp-git'),
  sourcemaps = require('gulp-sourcemaps'),
  tag_version = require('gulp-tag-version'),
  tslint = require('gulp-tslint'),
  ts = require('gulp-typescript'),
  PluginError = require('plugin-error'),
  minimist = require('minimist'),
  path = require('path');

const exec = require('child_process').exec;
const spawn = require('child_process').spawn;

const releaseOptions = {
  semver: '',
  githubToken: '',
};

// prettier
function runPrettier(command, done) {
  exec(command, function(err, stdout) {
    if (err) {
      return done(new PluginError('runPrettier', { message: err }));
    }

    if (!stdout) {
      return done();
    }

    var files = stdout
      .split(/\r?\n/)
      .filter(f => {
        return f.endsWith('.ts') || f.endsWith('.js');
      })
      .join(' ');

    if (!files) {
      return done();
    }

    const prettierPath = path.normalize('./node_modules/.bin/prettier');
    exec(
      `${prettierPath} --write --print-width 100 --single-quote --trailing-comma es5 ${files}`,
      function(err) {
        if (err) {
          return done(new PluginError('runPrettier', { message: err }));
        }
        return done();
      }
    );
  });
}

function createChangelog(done) {
  const imageName = 'jpoon/github-changelog-generator';
  const version = require('./package.json').version;

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

  if (!options.githubToken) {
    return done(
      new PluginError('createChangelog', {
        message: 'Missing `--githubToken` option. Please supply GitHub API Token.',
      })
    );
  }

  var dockerRunCmd = spawn(
    'docker',
    [
      'run',
      '-it',
      '--rm',
      '-v',
      process.cwd() + ':/usr/local/src/your-app',
      imageName,
      '--user',
      'vscodevim',
      '--project',
      'vim',
      '--token',
      options.githubToken,
      '--future-release',
      'v' + version,
    ],
    {
      cwd: process.cwd(),
      stdio: 'inherit',
    }
  );

  dockerRunCmd.on('exit', function(exitCode) {
    done(exitCode);
  });
}

function createGitTag() {
  return gulp.src(['./package.json']).pipe(tag_version());
}

function createGitCommit() {
  return gulp
    .src(['./package.json', './package-lock.json', 'CHANGELOG.md'])
    .pipe(git.commit('bump version'));
}

function updateVersion(done) {
  var options = minimist(process.argv.slice(2), releaseOptions);

  if (!options.semver) {
    return done(
      new PluginError('updateVersion', {
        message: 'Missing `--semver` option. Possible values: patch, minor, major',
      })
    );
  }

  return gulp
    .src(['./package.json', './package-lock.json'])
    .pipe(bump({ type: options.semver }))
    .pipe(gulp.dest('./'))
    .on('end', () => {
      done();
    });
}

gulp.task('tsc', function() {
  var isError = false;

  var tsProject = ts.createProject('tsconfig.json', { noEmitOnError: true });
  var tsResult = tsProject
    .src()
    .pipe(sourcemaps.init())
    .pipe(tsProject())
    .on('error', () => {
      isError = true;
    })
    .on('finish', () => {
      isError && process.exit(1);
    });

  return tsResult.js
    .pipe(sourcemaps.write('.', { includeContent: false, sourceRoot: '' }))
    .pipe(gulp.dest('out'));
});

gulp.task('tslint', function() {
  const program = require('tslint').Linter.createProgram('./tsconfig.json');
  return gulp
    .src(['**/*.ts', '!node_modules/**', '!typings/**'])
    .pipe(
      tslint({
        formatter: 'prose',
        program: program,
      })
    )
    .pipe(tslint.report({ summarizeFailureOutput: true }));
});

gulp.task('prettier', function(done) {
  // files changed
  runPrettier('git diff --name-only HEAD', done);
});

gulp.task('forceprettier', function(done) {
  // files managed by git
  runPrettier('git ls-files', done);
});

// test
gulp.task('test', function(done) {
  var spawn = require('child_process').spawn;
  const dockerTag = 'vscodevim';

  console.log('Building container...');
  var dockerBuildCmd = spawn(
    'docker',
    ['build', '-f', './build/Dockerfile', '.', '-t', dockerTag],
    {
      cwd: process.cwd(),
      stdio: 'inherit',
    }
  );

  dockerBuildCmd.on('exit', function(exitCode) {
    if (exitCode !== 0) {
      return done(
        new PluginError('test', {
          message: 'Docker build failed.',
        })
      );
    }

    console.log('Running tests inside container...');
    var dockerRunCmd = spawn('docker', ['run', '-it', '-v', process.cwd() + ':/app', dockerTag], {
      cwd: process.cwd(),
      stdio: 'inherit',
    });

    dockerRunCmd.on('exit', function(exitCode) {
      done(exitCode);
    });
  });
});

gulp.task('build', gulp.series('prettier', gulp.parallel('tsc', 'tslint')));
gulp.task('release', gulp.series(updateVersion, createChangelog, createGitCommit, createGitTag));
gulp.task('default', gulp.series('build', 'test'));
<commit_msg>fix: accept env var for setting token<commit_after>var gulp = require('gulp'),
  bump = require('gulp-bump'),
  git = require('gulp-git'),
  sourcemaps = require('gulp-sourcemaps'),
  tag_version = require('gulp-tag-version'),
  tslint = require('gulp-tslint'),
  ts = require('gulp-typescript'),
  PluginError = require('plugin-error'),
  minimist = require('minimist'),
  path = require('path');

const exec = require('child_process').exec;
const spawn = require('child_process').spawn;

const releaseOptions = {
  semver: '',
  githubToken: '',
};

// prettier
function runPrettier(command, done) {
  exec(command, function(err, stdout) {
    if (err) {
      return done(new PluginError('runPrettier', { message: err }));
    }

    if (!stdout) {
      return done();
    }

    var files = stdout
      .split(/\r?\n/)
      .filter(f => {
        return f.endsWith('.ts') || f.endsWith('.js');
      })
      .join(' ');

    if (!files) {
      return done();
    }

    const prettierPath = path.normalize('./node_modules/.bin/prettier');
    exec(
      `${prettierPath} --write --print-width 100 --single-quote --trailing-comma es5 ${files}`,
      function(err) {
        if (err) {
          return done(new PluginError('runPrettier', { message: err }));
        }
        return done();
      }
    );
  });
}

function validateArgs(done) {
  const options = minimist(process.argv.slice(2), releaseOptions);
  if (!options.semver) {
    return done(
      new PluginError('updateVersion', {
        message: 'Missing `--semver` option. Possible values: patch, minor, major',
      })
    );
  }

  if (!options.gitHubToken || process.env.CHANGELOG_GITHUB_TOKEN) {
    return done(
      new PluginError('createChangelog', {
        message:
          'Missing GitHub API Token. Supply token using `--githubToken` option or `CHANGELOG_GITHUB_TOKEN` environment variable.',
      })
    );
  }

  done();
}

function createChangelog(done) {
  const imageName = 'jpoon/github-changelog-generator';
  const version = require('./package.json').version;

  const options = minimist(process.argv.slice(2), releaseOptions);
  const gitHubToken = options.gitHubToken || process.env.CHANGELOG_GITHUB_TOKEN;

  var dockerRunCmd = spawn(
    'docker',
    [
      'run',
      '-it',
      '--rm',
      '-v',
      process.cwd() + ':/usr/local/src/your-app',
      imageName,
      '--user',
      'vscodevim',
      '--project',
      'vim',
      '--token',
      gitHubToken,
      '--future-release',
      'v' + version,
    ],
    {
      cwd: process.cwd(),
      stdio: 'inherit',
    }
  );

  dockerRunCmd.on('exit', function(exitCode) {
    done(exitCode);
  });
}

function createGitTag() {
  return gulp.src(['./package.json']).pipe(tag_version());
}

function createGitCommit() {
  return gulp
    .src(['./package.json', './package-lock.json', 'CHANGELOG.md'])
    .pipe(git.commit('bump version'));
}

function updateVersion(done) {
  var options = minimist(process.argv.slice(2), releaseOptions);

  return gulp
    .src(['./package.json', './package-lock.json'])
    .pipe(bump({ type: options.semver }))
    .pipe(gulp.dest('./'))
    .on('end', () => {
      done();
    });
}

gulp.task('tsc', function() {
  var isError = false;

  var tsProject = ts.createProject('tsconfig.json', { noEmitOnError: true });
  var tsResult = tsProject
    .src()
    .pipe(sourcemaps.init())
    .pipe(tsProject())
    .on('error', () => {
      isError = true;
    })
    .on('finish', () => {
      isError && process.exit(1);
    });

  return tsResult.js
    .pipe(sourcemaps.write('.', { includeContent: false, sourceRoot: '' }))
    .pipe(gulp.dest('out'));
});

gulp.task('tslint', function() {
  const program = require('tslint').Linter.createProgram('./tsconfig.json');
  return gulp
    .src(['**/*.ts', '!node_modules/**', '!typings/**'])
    .pipe(
      tslint({
        formatter: 'prose',
        program: program,
      })
    )
    .pipe(tslint.report({ summarizeFailureOutput: true }));
});

gulp.task('prettier', function(done) {
  // files changed
  runPrettier('git diff --name-only HEAD', done);
});

gulp.task('forceprettier', function(done) {
  // files managed by git
  runPrettier('git ls-files', done);
});

// test
gulp.task('test', function(done) {
  var spawn = require('child_process').spawn;
  const dockerTag = 'vscodevim';

  console.log('Building container...');
  var dockerBuildCmd = spawn(
    'docker',
    ['build', '-f', './build/Dockerfile', '.', '-t', dockerTag],
    {
      cwd: process.cwd(),
      stdio: 'inherit',
    }
  );

  dockerBuildCmd.on('exit', function(exitCode) {
    if (exitCode !== 0) {
      return done(
        new PluginError('test', {
          message: 'Docker build failed.',
        })
      );
    }

    console.log('Running tests inside container...');
    var dockerRunCmd = spawn('docker', ['run', '-it', '-v', process.cwd() + ':/app', dockerTag], {
      cwd: process.cwd(),
      stdio: 'inherit',
    });

    dockerRunCmd.on('exit', function(exitCode) {
      done(exitCode);
    });
  });
});

gulp.task('build', gulp.series('prettier', gulp.parallel('tsc', 'tslint')));
gulp.task(
  'release',
  gulp.series(validateArgs, updateVersion, createChangelog, createGitCommit, createGitTag)
);
gulp.task('default', gulp.series('build', 'test'));
<|endoftext|>


<commit_before>var React = require("react");
var pathRegexp = require('path-to-regexp');

module.exports = React.createClass({
    getInitialState:function(){
        for(var i = 0; i < this.props.routes.length; i++){
            var route = this.props.routes[i];
            if(typeof route.path == "string") route.path = pathRegexp(route.path);
        }
        this.route(this.props.path);
        return {};
    },
    componentDidMount:function(){
        window.addEventListener("click",this.onClick);
    },
    componentWillUnmount:function(){
        window.removeEventListener("click",this.onClick);
    },
    render:function(){
        console.log(this.props.view(this.props.data));
        return this.props.view.spec.render.call(this);
    },
    onClick:function(e){
        e.preventDefault();
        if(e.target.tagName == "A"){
            if(e.target.host == location.host){
                if(this.route(e.target.pathname)){
                    e.preventDefault();
                    history.pushState(null,null,e.target.href);
                    var self = this;
                    var req = new XMLHttpRequest();
                    req.open("GET",location.href);
                    req.setRequestHeader("Accept","application/json");
                    req.onreadystatechange = function(){
                        if(req.readyState == 4){
                            self.props.data = JSON.parse(req.responseText);
                            self.forceUpdate();
                        }
                    }
                    req.send();
                    console.log("preventing...");
                }
            }
        }

    },
    route:function(path){
        for(var i = 0; i < this.props.routes.length; i++){
            var route = this.props.routes[i];
            if(route.path.test(path)){
                this.props.view = route.view;
                return true;
            }
        }
    }
});<commit_msg>progress<commit_after>var React = require("react");
var pathRegexp = require('path-to-regexp');

module.exports = React.createClass({
    getInitialState:function(){
        for(var i = 0; i < this.props.routes.length; i++){
            var route = this.props.routes[i];
            if(typeof route.path == "string") route.path = pathRegexp(route.path);
        }
        this.route(this.props.path);
        return {};
    },
    componentDidMount:function(){
        window.addEventListener("click",this.onClick);
    },
    componentWillUnmount:function(){
        window.removeEventListener("click",this.onClick);
    },
    render:function(){
        return this.props.view.spec.render.call(this);
    },
    onClick:function(e){
        e.preventDefault();
        if(e.target.tagName == "A"){
            if(e.target.host == location.host){
                if(this.route(e.target.pathname)){
                    e.preventDefault();
                    history.pushState(null,null,e.target.href);
                    var self = this;
                    var req = new XMLHttpRequest();
                    req.open("GET",location.href);
                    req.setRequestHeader("Accept","application/json");
                    req.onreadystatechange = function(){
                        if(req.readyState == 4){
                            self.props.data = JSON.parse(req.responseText);
                            self.forceUpdate();
                        }
                    }
                    req.send();
                    console.log("preventing...");
                }
            }
        }

    },
    route:function(path){
        for(var i = 0; i < this.props.routes.length; i++){
            var route = this.props.routes[i];
            if(route.path.test(path)){
                this.props.view = route.view;
                return true;
            }
        }
    }
});<|endoftext|>


<commit_before>'use strict';

const child_process = require('child_process');
const del = require('del');
const gulp = require('gulp');
const loadPlugins = require('gulp-load-plugins');
const path = require('path');

/**
 * The task plugins.
 * @type {object}
 */
const plugins = loadPlugins({
  pattern: ['gulp-*', '@*/gulp-*', 'vinyl-*'],
  replaceString: /^(gulp|vinyl)-/
});

/**
 * Runs the default tasks.
 */
gulp.task('default', ['build']);

/**
 * Builds the sources.
 */
gulp.task('build', () => gulp.src('src/**/*.js')
  .pipe(plugins.babel())
  .pipe(gulp.dest('lib'))
);

/**
 * Checks the package dependencies.
 */
gulp.task('check', () => {
  const {david} = plugins.cedx.david;
  return gulp.src('package.json').pipe(david()).on('error', function(err) {
    console.error(err);
    this.emit('end');
  });
});

/**
 * Deletes all generated files and reset any saved state.
 */
gulp.task('clean', () => del('var/**/*'));

/**
 * Sends the results of the code coverage.
 */
gulp.task('coverage', ['test'], () => {
  let executable = path.join('node_modules/.bin', process.platform == 'win32' ? 'coveralls.cmd' : 'coveralls');
  return _exec(`${executable} --file=var/lcov.info`);
});

/**
 * Builds the documentation.
 */
gulp.task('doc', () => {
  let executable = path.join('node_modules/.bin', process.platform == 'win32' ? 'esdoc.cmd' : 'esdoc');
  return del('doc/api').then(() => _exec(executable));
});

/**
 * Fixes the coding standards issues.
 */
gulp.task('fix', () => gulp.src(['*.js', 'src/**/*.js', 'test/**/*.js'], {base: '.'})
  .pipe(plugins.eslint({fix: true}))
  .pipe(gulp.dest('.'))
);

/**
 * Performs static analysis of source code.
 */
gulp.task('lint', () => gulp.src(['*.js', 'src/**/*.js', 'test/**/*.js'])
  .pipe(plugins.eslint())
  .pipe(plugins.eslint.format())
  .pipe(plugins.eslint.failAfterError())
);

/**
 * Runs the unit tests.
 */
gulp.task('test', ['test:instrument'], () => gulp.src(['test/**/*.js'], {read: false})
  .pipe(plugins.mocha())
  .pipe(plugins.istanbul.writeReports({dir: 'var', reporters: ['lcovonly']}))
);

gulp.task('test:env', () =>
  'AKISMET_API_KEY' in process.env ? Promise.resolve() : Promise.reject(new Error('AKISMET_API_KEY environment variable not set.'))
);

gulp.task('test:instrument', ['test:setup'], () => gulp.src(['src/**/*.js'])
  .pipe(plugins.istanbul({instrumenter: require('isparta').Instrumenter}))
  .pipe(plugins.istanbul.hookRequire())
);

gulp.task('test:setup', ['test:env'], () => new Promise(resolve => {
  process.env.BABEL_DISABLE_CACHE = process.platform == 'win32' ? '1' : '0';
  require('babel-register');
  resolve();
}));

/**
 * Runs a command and returns its output.
 * @param {string} command The command to run, with space-separated arguments.
 * @param {object} [options] The settings to customize how the process is spawned.
 * @return {Promise<string>} The command output when it is finally terminated.
 */
function _exec(command, options = {}) {
  return new Promise((resolve, reject) => child_process.exec(command, options, (err, stdout) => {
    if (err) reject(err);
    else resolve(stdout.trim());
  }));
}
<commit_msg>Fixed the regressions<commit_after>'use strict';

const child_process = require('child_process');
const del = require('del');
const gulp = require('gulp');
const loadPlugins = require('gulp-load-plugins');
const path = require('path');

/**
 * The task plugins.
 * @type {object}
 */
const plugins = loadPlugins({
  pattern: ['gulp-*', '@*/gulp-*', 'vinyl-*'],
  replaceString: /^(gulp|vinyl)-/
});

/**
 * Runs the default tasks.
 */
gulp.task('default', ['build']);

/**
 * Builds the sources.
 */
gulp.task('build', () => gulp.src('src/**/*.js')
  .pipe(plugins.babel())
  .pipe(gulp.dest('lib'))
);

/**
 * Checks the package dependencies.
 */
gulp.task('check', () => {
  const {david} = plugins.cedx.david;
  return gulp.src('package.json').pipe(david()).on('error', function(err) {
    console.error(err);
    this.emit('end');
  });
});

/**
 * Deletes all generated files and reset any saved state.
 */
gulp.task('clean', () => del('var/**/*'));

/**
 * Sends the results of the code coverage.
 */
gulp.task('coverage', ['test'], () => {
  let executable = path.join('node_modules/.bin', process.platform == 'win32' ? 'coveralls.cmd' : 'coveralls');
  return _exec(`${executable} --file=var/lcov.info`);
});

/**
 * Builds the documentation.
 */
gulp.task('doc', () => {
  let executable = path.join('node_modules/.bin', process.platform == 'win32' ? 'esdoc.cmd' : 'esdoc');
  return del('doc/api').then(() => _exec(executable));
});

/**
 * Fixes the coding standards issues.
 */
gulp.task('fix', () => gulp.src(['*.js', 'src/**/*.js', 'test/**/*.js'], {base: '.'})
  .pipe(plugins.eslint({fix: true}))
  .pipe(gulp.dest('.'))
);

/**
 * Performs static analysis of source code.
 */
gulp.task('lint', () => gulp.src(['*.js', 'src/**/*.js', 'test/**/*.js'])
  .pipe(plugins.eslint())
  .pipe(plugins.eslint.format())
  .pipe(plugins.eslint.failAfterError())
);

/**
 * Runs the unit tests.
 */
gulp.task('test', ['test:instrument'], () => gulp.src(['test/**/*.js'], {read: false})
  .pipe(plugins.mocha({compilers: 'js:babel-register'}))
  .pipe(plugins.istanbul.writeReports({dir: 'var', reporters: ['lcovonly']}))
);

gulp.task('test:env', () =>
  'AKISMET_API_KEY' in process.env ? Promise.resolve() : Promise.reject(new Error('AKISMET_API_KEY environment variable not set.'))
);

gulp.task('test:instrument', ['test:setup'], () => gulp.src(['src/**/*.js'])
  .pipe(plugins.istanbul({instrumenter: require('isparta').Instrumenter}))
  .pipe(plugins.istanbul.hookRequire())
);

gulp.task('test:setup', ['test:env'], () => new Promise(resolve => {
  process.env.BABEL_DISABLE_CACHE = process.platform == 'win32' ? '1' : '0';
  require('babel-register');
  resolve();
}));

/**
 * Runs a command and returns its output.
 * @param {string} command The command to run, with space-separated arguments.
 * @param {object} [options] The settings to customize how the process is spawned.
 * @return {Promise<string>} The command output when it is finally terminated.
 */
function _exec(command, options = {}) {
  return new Promise((resolve, reject) => child_process.exec(command, options, (err, stdout) => {
    if (err) reject(err);
    else resolve(stdout.trim());
  }));
}
<|endoftext|>


<commit_before>var gulp   = require('gulp'),
    uglify = require('gulp-uglify'),
    jshint = require('gulp-jshint'),
    concat = require('gulp-concat'),
    cssmin = require('gulp-cssmin'),
    //jscs = require('gulp-jscs'),
    htmlreplace = require('gulp-html-replace'),
    templateCache = require('gulp-angular-templatecache'),
    del = require('del');

gulp.task('minify', ['templates'], function () {
    var scripts = [
        "src/app.js",
        "src/services/utils.js",
        "src/directives/widgetContent.js",
        "src/services/error.js",
        "src/services/filters.js",
        "src/controllers/filter.js",
        "src/directives/focus.js",
        "src/directives/pivot.js",
        "src/controllers/login.js",
        "src/services/interseptor.js",
        "src/services/connector.js",
        "src/controllers/menu.js",
        "src/controllers/dashboard.js",
        "src/controllers/dashboardList.js",
        "src/factories/baseWidget.js",
        "src/factories/baseChart.js",
        "src/factories/lineChart.js",
        "src/factories/areaChart.js",
        "src/factories/barChart.js",
        "src/factories/columnChart.js",
        "src/factories/pieChart.js",
        "src/factories/xyChart.js",
        "src/factories/timeChart.js",
        "src/factories/timeChart.js",
        "src/factories/hiLowChart.js",
        "src/factories/treeMapChart.js",
        "src/factories/bubbleChart.js",
        "src/factories/bullseyeChart.js",
        "src/factories/speedometerChart.js",
        "src/factories/fuelGaugeChart.js",
        "src/factories/pivotWidget.js",
        "src/directives/textWidget.js",
        "src/factories/textWidget.js",
        "src/services/typeMap.js",
        "src/controllers/widget.js",
        "src/services/lang.js",
        "build/src/templates.js"
    ];

    return gulp.src(scripts)
        //.pipe(jscs())
        .pipe(jshint())
        .pipe(jshint.reporter('default'))
        //.pipe(uglify())
        .pipe(uglify({mangle: false}))
        .pipe(concat('app.js'))
        .pipe(gulp.dest('build/src'));
});

gulp.task('cssminify', function () {
    gulp.src(['css/**/*.css', '!css/**/*.min.css'])
        .pipe(cssmin())
        .pipe(concat('main.css'))
        .pipe(gulp.dest('build/css'));
});

gulp.task('copyfiles', function () {
    gulp.src(['src/lib/*.js'])
        .pipe(gulp.dest('build/src/lib'));
    gulp.src(['css/*.min.css'])
        .pipe(gulp.dest('build/css'));
    gulp.src(['fonts/*'])
        .pipe(gulp.dest('build/fonts'));
    gulp.src(['img/*'])
        .pipe(gulp.dest('build/img'));
});

gulp.task('copyindex', function () {
    var scripts = [
        "src/lib/numeral.min.js",
        "src/lib/angular.min.js",
        "src/lib/angular-route.min.js",
        "src/lib/angular-cookies.min.js",
        "src/lib/angular-notify.min.js",
        "src/lib/ng-context-menu.min.js",
        "src/lib/ngDialog.js",
        "src/lib/jquery-2.1.3.min.js",
        "src/lib/bootstrap.min.js",
        "src/lib/angular-gridster.min.js",
        "src/lib/highstock.js",
        "src/lib/highcharts-more.js",
        "src/lib/heatmap.src.js",
        "src/lib/treemap.src.js",
        "src/lib/highcharts-ng.min.js",
        "src/lib/lightPivotTable.js",
        "src/app.js"
    ];
    gulp.src(['index.html'])
        .pipe(htmlreplace({ 'js': scripts }))
        .pipe(gulp.dest('build'));
});

gulp.task('templates', function() {
    return gulp.src(['src/views/*.html'])
        .pipe(templateCache({root:"src/views/"}))
        .pipe(gulp.dest('build/src'));
});

gulp.task('cleanup', ['minify'], function() {
    del(["build/src/templates.js"]);
});

gulp.task('default', ['minify', 'cssminify', 'copyfiles', 'copyindex', 'cleanup'], function () {});

<commit_msg>new build file<commit_after>var gulp   = require('gulp'),
    uglify = require('gulp-uglify'),
    jshint = require('gulp-jshint'),
    concat = require('gulp-concat'),
    cssmin = require('gulp-cssmin'),
    //jscs = require('gulp-jscs'),
    htmlreplace = require('gulp-html-replace'),
    templateCache = require('gulp-angular-templatecache'),
    del = require('del');

gulp.task('minify', ['templates'], function () {
    var scripts = [
        "src/app.js",
        "src/services/utils.js",
        "src/directives/widgetContent.js",
        "src/services/error.js",
        "src/services/filters.js",
        "src/controllers/filter.js",
        "src/directives/focus.js",
        "src/directives/pivot.js",
        "src/controllers/login.js",
        "src/services/interseptor.js",
        "src/services/connector.js",
        "src/controllers/menu.js",
        "src/controllers/dashboard.js",
        "src/controllers/dashboardList.js",
        "src/factories/baseWidget.js",
        "src/factories/emptyWidget.js",
        "src/factories/baseChart.js",
        "src/factories/lineChart.js",
        "src/factories/areaChart.js",
        "src/factories/barChart.js",
        "src/factories/columnChart.js",
        "src/factories/pieChart.js",
        "src/factories/xyChart.js",
        "src/factories/timeChart.js",
        "src/factories/timeChart.js",
        "src/factories/hiLowChart.js",
        "src/factories/treeMapChart.js",
        "src/factories/bubbleChart.js",
        "src/factories/bullseyeChart.js",
        "src/factories/speedometerChart.js",
        "src/factories/fuelGaugeChart.js",
        "src/factories/pivotWidget.js",
        "src/directives/textWidget.js",
        "src/factories/textWidget.js",
        "src/services/typeMap.js",
        "src/controllers/widget.js",
        "src/services/lang.js",
        "build/src/templates.js"
    ];

    return gulp.src(scripts)
        //.pipe(jscs())
        .pipe(jshint())
        .pipe(jshint.reporter('default'))
        //.pipe(uglify())
        .pipe(uglify({mangle: false}))
        .pipe(concat('app.js'))
        .pipe(gulp.dest('build/src'));
});

gulp.task('cssminify', function () {
    gulp.src(['css/**/*.css', '!css/**/*.min.css'])
        .pipe(cssmin())
        .pipe(concat('main.css'))
        .pipe(gulp.dest('build/css'));
});

gulp.task('copyfiles', function () {
    gulp.src(['src/lib/*.js'])
        .pipe(gulp.dest('build/src/lib'));
    gulp.src(['css/*.min.css'])
        .pipe(gulp.dest('build/css'));
    gulp.src(['fonts/*'])
        .pipe(gulp.dest('build/fonts'));
    gulp.src(['img/*'])
        .pipe(gulp.dest('build/img'));
});

gulp.task('copyindex', function () {
    var scripts = [
        "src/lib/numeral.min.js",
        "src/lib/angular.min.js",
        "src/lib/angular-route.min.js",
        "src/lib/angular-cookies.min.js",
        "src/lib/angular-notify.min.js",
        "src/lib/ng-context-menu.min.js",
        "src/lib/ngDialog.js",
        "src/lib/jquery-2.1.3.min.js",
        "src/lib/bootstrap.min.js",
        "src/lib/angular-gridster.min.js",
        "src/lib/highstock.js",
        "src/lib/exporting.js",
        "src/lib/no-data-to-display.src.js",
        "src/lib/highcharts-more.js",
        "src/lib/highcharts-3d.src.js",
        "src/lib/heatmap.src.js",
        "src/lib/treemap.src.js",
        "src/lib/highcharts-ng.min.js",
        "src/lib/lightPivotTable.js",
        "src/app.js"
    ];
    gulp.src(['index.html'])
        .pipe(htmlreplace({ 'js': scripts }))
        .pipe(gulp.dest('build'));
});

gulp.task('templates', function() {
    return gulp.src(['src/views/*.html'])
        .pipe(templateCache({root:"src/views/"}))
        .pipe(gulp.dest('build/src'));
});

gulp.task('cleanup', ['minify'], function() {
    del(["build/src/templates.js"]);
});

gulp.task('default', ['minify', 'cssminify', 'copyfiles', 'copyindex', 'cleanup'], function () {});

<|endoftext|>


<commit_before>/*设定页面返回功能*/
var page = sm("do_Page"),
    nf = sm("do_Notification"),
    iFlyVoice = sm("do_iFlyVoice"),
    baidulocation = sm("do_BaiduLocation"),
    rootview = ui("$"),
    initdata = sm("do_InitData"),
    storage = sm("do_Storage"),
    do_HashData = mm("do_HashData"),
    do_Alayout_Root = ui("do_Alayout_Root"),
    city_name = ui("city_name"),
    city_streetname = ui("city_streetname"),
	weather_status0 = ui("weather_status0"),
	weather_0 = ui("weather_0"),
	weather_1 = ui("weather_1"),
	action_iFlyVoice = ui("action_iFlyVoice"),
	weather_temperature = ui("weather_temperature"),
	weather_temperature_0 = ui("weather_temperature_0"),
	weather_temperature_1 = ui("weather_temperature_1"),
	do_ImageView_icoin_0 = ui("do_ImageView_icoin_0"),
	do_ImageView_icoin_1 = ui("do_ImageView_icoin_1"),
	do_ALayout_could = ui("do_ALayout_could"),
	do_ALayout_could1 = ui("do_ALayout_could1"),
	al_anim = ui("anim"),
	img_playpng = ui("playpng"),
    pngsView = ui("pngsView");
//定义一个2秒的动画过程：缩放比例1-》1.2，图片位置：(0,0)-》(-75, -133)
var img_anima = mm("do_Animation");
img_anima.fillAfter = true;
img_anima.scale({
    delay: 0,
    duration: 10000,
    curve: "Linear",
    autoReverse: false,
    scaleFromX: 1,
    scaleFromY: 1,
    scaleToX: 1.5,
    scaleToY: 1.5
}, "start1");
img_anima.transfer({
    delay: -100,
    duration: 20000,
    curve: "Linear",
    autoReverse: false,
    repeatCount:-1,
    fromX: 0,
    fromY: 0,
    toX: 750,
    toY: 0
}, "start2");

var temperature1 = "";
var temperature2 = "";
var status1 = "";
var new_city = ""

rootview.setMapping({
    "tag": "city"
});

var city1 = {};
rootview.on("dataRefreshed", function(){
	city1 = rootview.tag;
	var city = JSON.parse(city1)
	city_name.text = city.district;
	city_streetname.text = city.streetName;
	new_city = city.city;
	initdata.readFile("initdata://weather.json", function(d, e) {
		for (var key in d.body) {
				if (key == "0") {
					weather_0.text = d.body[key].status1;
					temperature1 = d.body[key].temperature1;
					temperature2 = d.body[key].temperature2;
					status1 = d.body[key].status1;
					weather_status0.text = d.body[key].status1;
					weather_temperature.text = d.body[key].temperature1+"℃";
					if(d.body[key].status1 == "多云"){
						do_ImageView_icoin_0.source = "source://image/weather_icoin/w1.png"
						do_Alayout_Root.bgImage = "source://image/weather_bg/bg_sunny_day.jpg"
						do_ALayout_could.bgImage = "source://image/weather_bg/fog_day_fog_middle.png"
						do_ALayout_could1.bgImage = "source://image/weather_bg/fog_day_fog_middle.png"
						do_ALayout_could.animate(img_anima)
						do_ALayout_could1.animate(img_anima)
					}else if(d.body[key].status1 == "晴"){
						do_ImageView_icoin_0.source = "source://image/weather_icoin/w0.png"
						do_Alayout_Root.bgImage = "source://image/weather_bg/bg_sunny_day.jpg"
						do_ALayout_could.bgImage = "source://image/weather_bg/fog_day_fog_bottom.png"
						do_ALayout_could1.bgImage = "source://image/weather_bg/fog_day_fog_bottom.png"
						do_ALayout_could.animate(img_anima)
						do_ALayout_could1.animate(img_anima)
					}else if(d.body[key].status1.indexOf("雨")!=-1){
						do_ImageView_icoin_0.source = "source://image/weather_icoin/w7.png"
						do_Alayout_Root.bgImage = "source://image/weather_bg/bg.jpg"
						do_ALayout_could.bgImage = "source://image/weather_bg/moderate_rain_cloud1.png"
						do_ALayout_could1.bgImage = "source://image/weather_bg/moderate_rain_cloud1.png"
						do_ALayout_could.animate(img_anima)
						do_ALayout_could1.animate(img_anima)
					}else{
						do_ImageView_icoin_0.source = "source://image/weather_icoin/w0.png"
						do_Alayout_Root.bgImage = "source://image/weather_bg/bg.jpg"
						do_ALayout_could.bgImage = "source://image/weather_bg/moderate_rain_cloud1.png"
						do_ALayout_could1.bgImage = "source://image/weather_bg/moderate_rain_cloud1.png"
						do_ALayout_could.animate(img_anima)
						do_ALayout_could1.animate(img_anima)
					}
					weather_temperature_0.text = d.body[key].temperature1+"/"+d.body[key].temperature2+"℃";
				}
				if (key == "1"){
					weather_1.text = d.body[key].status1;
					if(d.body[key].status1 == "多云"){
						do_ImageView_icoin_1.source = "source://image/weather_icoin/w1.png"
					}else if(d.body[key].status1 == "晴"){
						do_ImageView_icoin_1.source = "source://image/weather_icoin/w0.png"
					}else{
						do_ImageView_icoin_1.source = "source://image/weather_icoin/w7.png"
					}
					weather_temperature_1.text = d.body[key].temperature1+"/"+d.body[key].temperature2+"℃";
				}
		}
	});
})

//构建一组连续的图片，一共180张png图片
var pngs = [];
for (var i = 1; i <= 3; i++) {
	var a = {};
	// 设定每个图片播放的间隔都是50毫秒
	a.duration = 300;
	a.path = "source://image/broadcasting" + i + ".png";
	pngs.push(a);
}

var flag = 1;
al_anim.on("touch", function(d, e) {
	// 重复播放这组图片形成动画
	if(flag == 1)
	{
		img_playpng.visible = false;
		pngsView.visible = true;
		pngsView.startImages(pngs, -1);
		flag = 2;
		var text1 = "现在为您播报，今天白天到夜间," + status1 +",温度"+ temperature2+"到"+temperature1+"摄氏度";
		iFlyVoice.speak({text:text1})
	}else{
		img_playpng.visible = true;
		pngsView.visible = false;
		pngsView.stop();
		flag = 1;
		iFlyVoice.stop();
	}
});
<commit_msg>播放语音的点击区域弄的更大<commit_after>/*设定页面返回功能*/
var page = sm("do_Page"),
    nf = sm("do_Notification"),
    iFlyVoice = sm("do_iFlyVoice"),
    baidulocation = sm("do_BaiduLocation"),
    rootview = ui("$"),
    initdata = sm("do_InitData"),
    storage = sm("do_Storage"),
    do_HashData = mm("do_HashData"),
    do_Alayout_Root = ui("do_Alayout_Root"),
    city_name = ui("city_name"),
    city_streetname = ui("city_streetname"),
	weather_status0 = ui("weather_status0"),
	weather_0 = ui("weather_0"),
	weather_1 = ui("weather_1"),
	action_iFlyVoice = ui("action_iFlyVoice"),
	weather_temperature = ui("weather_temperature"),
	weather_temperature_0 = ui("weather_temperature_0"),
	weather_temperature_1 = ui("weather_temperature_1"),
	do_ImageView_icoin_0 = ui("do_ImageView_icoin_0"),
	do_ImageView_icoin_1 = ui("do_ImageView_icoin_1"),
	do_ALayout_could = ui("do_ALayout_could"),
	do_ALayout_could1 = ui("do_ALayout_could1"),
	al_anim = ui("anim"),
	img_playpng = ui("playpng"),
    pngsView = ui("pngsView");
//定义一个2秒的动画过程：缩放比例1-》1.2，图片位置：(0,0)-》(-75, -133)
var img_anima = mm("do_Animation");
img_anima.fillAfter = true;
img_anima.scale({
    delay: 0,
    duration: 10000,
    curve: "Linear",
    autoReverse: false,
    scaleFromX: 1,
    scaleFromY: 1,
    scaleToX: 1.5,
    scaleToY: 1.5
}, "start1");
img_anima.transfer({
    delay: -100,
    duration: 20000,
    curve: "Linear",
    autoReverse: false,
    repeatCount:-1,
    fromX: 0,
    fromY: 0,
    toX: 750,
    toY: 0
}, "start2");

var temperature1 = "";
var temperature2 = "";
var status1 = "";
var new_city = ""

rootview.setMapping({
    "tag": "city"
});

var city1 = {};
rootview.on("dataRefreshed", function(){
	city1 = rootview.tag;
	var city = JSON.parse(city1)
	city_name.text = city.district;
	city_streetname.text = city.streetName;
	new_city = city.city;
	initdata.readFile("initdata://weather.json", function(d, e) {
		for (var key in d.body) {
				if (key == "0") {
					weather_0.text = d.body[key].status1;
					temperature1 = d.body[key].temperature1;
					temperature2 = d.body[key].temperature2;
					status1 = d.body[key].status1;
					weather_status0.text = d.body[key].status1;
					weather_temperature.text = d.body[key].temperature1+"℃";
					if(d.body[key].status1 == "多云"){
						do_ImageView_icoin_0.source = "source://image/weather_icoin/w1.png"
						do_Alayout_Root.bgImage = "source://image/weather_bg/bg_sunny_day.jpg"
						do_ALayout_could.bgImage = "source://image/weather_bg/fog_day_fog_middle.png"
						do_ALayout_could1.bgImage = "source://image/weather_bg/fog_day_fog_middle.png"
						do_ALayout_could.animate(img_anima)
						do_ALayout_could1.animate(img_anima)
					}else if(d.body[key].status1 == "晴"){
						do_ImageView_icoin_0.source = "source://image/weather_icoin/w0.png"
						do_Alayout_Root.bgImage = "source://image/weather_bg/bg_sunny_day.jpg"
						do_ALayout_could.bgImage = "source://image/weather_bg/fog_day_fog_bottom.png"
						do_ALayout_could1.bgImage = "source://image/weather_bg/fog_day_fog_bottom.png"
						do_ALayout_could.animate(img_anima)
						do_ALayout_could1.animate(img_anima)
					}else if(d.body[key].status1.indexOf("雨")!=-1){
						do_ImageView_icoin_0.source = "source://image/weather_icoin/w7.png"
						do_Alayout_Root.bgImage = "source://image/weather_bg/bg.jpg"
						do_ALayout_could.bgImage = "source://image/weather_bg/moderate_rain_cloud1.png"
						do_ALayout_could1.bgImage = "source://image/weather_bg/moderate_rain_cloud1.png"
						do_ALayout_could.animate(img_anima)
						do_ALayout_could1.animate(img_anima)
					}else{
						do_ImageView_icoin_0.source = "source://image/weather_icoin/w0.png"
						do_Alayout_Root.bgImage = "source://image/weather_bg/bg.jpg"
						do_ALayout_could.bgImage = "source://image/weather_bg/moderate_rain_cloud1.png"
						do_ALayout_could1.bgImage = "source://image/weather_bg/moderate_rain_cloud1.png"
						do_ALayout_could.animate(img_anima)
						do_ALayout_could1.animate(img_anima)
					}
					weather_temperature_0.text = d.body[key].temperature1+"/"+d.body[key].temperature2+"℃";
				}
				if (key == "1"){
					weather_1.text = d.body[key].status1;
					if(d.body[key].status1 == "多云"){
						do_ImageView_icoin_1.source = "source://image/weather_icoin/w1.png"
					}else if(d.body[key].status1 == "晴"){
						do_ImageView_icoin_1.source = "source://image/weather_icoin/w0.png"
					}else{
						do_ImageView_icoin_1.source = "source://image/weather_icoin/w7.png"
					}
					weather_temperature_1.text = d.body[key].temperature1+"/"+d.body[key].temperature2+"℃";
				}
		}
	});
})

//构建一组连续的图片，一共180张png图片
var pngs = [];
for (var i = 1; i <= 3; i++) {
	var a = {};
	// 设定每个图片播放的间隔都是50毫秒
	a.duration = 300;
	a.path = "source://image/broadcasting" + i + ".png";
	pngs.push(a);
}

var flag = 1;
action_iFlyVoice.on("touch", function(d, e) {
	// 重复播放这组图片形成动画
	if(flag == 1)
	{
		img_playpng.visible = false;
		pngsView.visible = true;
		pngsView.startImages(pngs, -1);
		flag = 2;
		var text1 = "现在为您播报，今天白天到夜间," + status1 +",温度"+ temperature2+"到"+temperature1+"摄氏度";
		iFlyVoice.speak({text:text1})
	}else{
		img_playpng.visible = true;
		pngsView.visible = false;
		pngsView.stop();
		flag = 1;
		iFlyVoice.stop();
	}
});
<|endoftext|>


<commit_before>"use strict";
var router = module.exports = { };

var _ = {
  assign: require("lodash.assign"),
  omit: require("lodash.omit")
};
var express = require("express");
var app = express();
var server;
var bodyParser = require("body-parser");
var cookieParser = require("cookie-parser");
var jsonApi = require("./jsonApi.js");
var debug = require("./debugging.js");
var url = require("url");

app.use(function(req, res, next) {
  if (!req.headers["content-type"] && !req.headers.accept) return next();

  if (req.headers["content-type"]) {
    // 415 Unsupported Media Type
    if (req.headers["content-type"].match(/^application\/vnd\.api\+json;.+$/)) {
      return res.status(415).end();
    }

    // Convert "application/vnd.api+json" content type to "application/json".
    // This enables the express body parser to correctly parse the JSON payload.
    if (req.headers["content-type"].match(/^application\/vnd\.api\+json$/)) {
      req.headers["content-type"] = "application/json";
    }
  }

  if (req.headers.accept) {
    // 406 Not Acceptable
    var matchingTypes = req.headers.accept.split(/, ?/);
    matchingTypes = matchingTypes.filter(function(mediaType) {
      // Accept application/*, */vnd.api+json, */* and the correct JSON:API type.
      return mediaType.match(/^(\*|application)\/(\*|vnd\.api\+json)$/) || mediaType.match(/\*\/\*/);
    });

    if (matchingTypes.length === 0) {
      return res.status(406).end();
    }
  }

  return next();
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.disable("x-powered-by");
app.disable("etag");

var requestId = 0;
app.route("*").all(function(req, res, next) {
  debug.requestCounter(requestId++, req.method, req.url);
  if (requestId > 1000) requestId = 0;
  next();
});

router.listen = function(port) {
  if (!server) {
    server = app.listen(port);
  }
};

router.close = function() {
  server.close();
  server = null;
};

router.bindRoute = function(config, callback) {
  app[config.verb](jsonApi._apiConfig.base + config.path, function(req, res) {
    var request = router._getParams(req);
    var resourceConfig = jsonApi._resources[request.params.type];
    router._setResponseHeaders(request, res);
    request.resourceConfig = resourceConfig;
    router.authenticate(request, res, function() {
      return callback(request, resourceConfig, res);
    });
  });
};

router.authenticate = function(request, res, callback) {
  if (!router._authFunction) return callback();

  router._authFunction(request, function(err) {
    if (!err) return callback();

    res.status(401).end();
  });
};

router.authenticateWith = function(authFunction) {
  router._authFunction = authFunction;
};

router.bind404 = function(callback) {
  app.use(function(req, res) {
    var request = router._getParams(req);
    router._setResponseHeaders(request, res);
    return callback(request, res);
  });
};

router.bindErrorHandler = function(callback) {
  app.use(function(error, req, res, next) {
    var request = router._getParams(req);
    router._setResponseHeaders(request, res);
    return callback(request, res, error, next);
  });
};

router._getParams = function(req) {
  var urlParts = req.url.split(jsonApi._apiConfig.base);
  urlParts.shift();
  urlParts = urlParts.join("").split("?");

  var headersToRemove = [
    "host", "connection", "accept-encoding", "accept-language"
  ];

  return {
    params: _.assign(req.params, req.body, req.query),
    headers: req.headers,
    safeHeaders: _.omit(req.headers, headersToRemove),
    cookies: req.cookies,
    route: {
      verb: req.method,
      host: req.headers.host,
      base: jsonApi._apiConfig.base,
      path: urlParts.shift() || "",
      query: urlParts.shift() || "",
      combined: url.format({
        protocol: jsonApi._apiConfig.protocol,
        hostname: jsonApi._apiConfig.hostname,
        port: jsonApi._apiConfig.port
      }) + req.url
    }
  };
};

router._setResponseHeaders = function(request, res) {
  res.set({
    "Content-Type": "application/vnd.api+json",
    "Location": request.route.combined,
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "*"
  });
};

router.sendResponse = function(res, payload, httpCode) {
  res.status(httpCode).json(payload);
};
<commit_msg>Dont forward on content-length HTTP headers<commit_after>"use strict";
var router = module.exports = { };

var _ = {
  assign: require("lodash.assign"),
  omit: require("lodash.omit")
};
var express = require("express");
var app = express();
var server;
var bodyParser = require("body-parser");
var cookieParser = require("cookie-parser");
var jsonApi = require("./jsonApi.js");
var debug = require("./debugging.js");
var url = require("url");

app.use(function(req, res, next) {
  if (!req.headers["content-type"] && !req.headers.accept) return next();

  if (req.headers["content-type"]) {
    // 415 Unsupported Media Type
    if (req.headers["content-type"].match(/^application\/vnd\.api\+json;.+$/)) {
      return res.status(415).end();
    }

    // Convert "application/vnd.api+json" content type to "application/json".
    // This enables the express body parser to correctly parse the JSON payload.
    if (req.headers["content-type"].match(/^application\/vnd\.api\+json$/)) {
      req.headers["content-type"] = "application/json";
    }
  }

  if (req.headers.accept) {
    // 406 Not Acceptable
    var matchingTypes = req.headers.accept.split(/, ?/);
    matchingTypes = matchingTypes.filter(function(mediaType) {
      // Accept application/*, */vnd.api+json, */* and the correct JSON:API type.
      return mediaType.match(/^(\*|application)\/(\*|vnd\.api\+json)$/) || mediaType.match(/\*\/\*/);
    });

    if (matchingTypes.length === 0) {
      return res.status(406).end();
    }
  }

  return next();
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.disable("x-powered-by");
app.disable("etag");

var requestId = 0;
app.route("*").all(function(req, res, next) {
  debug.requestCounter(requestId++, req.method, req.url);
  if (requestId > 1000) requestId = 0;
  next();
});

router.listen = function(port) {
  if (!server) {
    server = app.listen(port);
  }
};

router.close = function() {
  server.close();
  server = null;
};

router.bindRoute = function(config, callback) {
  app[config.verb](jsonApi._apiConfig.base + config.path, function(req, res) {
    var request = router._getParams(req);
    var resourceConfig = jsonApi._resources[request.params.type];
    router._setResponseHeaders(request, res);
    request.resourceConfig = resourceConfig;
    router.authenticate(request, res, function() {
      return callback(request, resourceConfig, res);
    });
  });
};

router.authenticate = function(request, res, callback) {
  if (!router._authFunction) return callback();

  router._authFunction(request, function(err) {
    if (!err) return callback();

    res.status(401).end();
  });
};

router.authenticateWith = function(authFunction) {
  router._authFunction = authFunction;
};

router.bind404 = function(callback) {
  app.use(function(req, res) {
    var request = router._getParams(req);
    router._setResponseHeaders(request, res);
    return callback(request, res);
  });
};

router.bindErrorHandler = function(callback) {
  app.use(function(error, req, res, next) {
    var request = router._getParams(req);
    router._setResponseHeaders(request, res);
    return callback(request, res, error, next);
  });
};

router._getParams = function(req) {
  var urlParts = req.url.split(jsonApi._apiConfig.base);
  urlParts.shift();
  urlParts = urlParts.join("").split("?");

  var headersToRemove = [
    "host", "connection", "accept-encoding", "accept-language", "content-length"
  ];

  return {
    params: _.assign(req.params, req.body, req.query),
    headers: req.headers,
    safeHeaders: _.omit(req.headers, headersToRemove),
    cookies: req.cookies,
    route: {
      verb: req.method,
      host: req.headers.host,
      base: jsonApi._apiConfig.base,
      path: urlParts.shift() || "",
      query: urlParts.shift() || "",
      combined: url.format({
        protocol: jsonApi._apiConfig.protocol,
        hostname: jsonApi._apiConfig.hostname,
        port: jsonApi._apiConfig.port
      }) + req.url
    }
  };
};

router._setResponseHeaders = function(request, res) {
  res.set({
    "Content-Type": "application/vnd.api+json",
    "Location": request.route.combined,
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "*"
  });
};

router.sendResponse = function(res, payload, httpCode) {
  res.status(httpCode).json(payload);
};
<|endoftext|>


<commit_before>'use strict';
var gulp = require('gulp'),
    jasmine = require('gulp-jasmine'),
    babel = require('gulp-babel'),
    concat = require('gulp-concat');

gulp.task('build', () => {
  return gulp.src('src/**.js')
    .pipe(babel({
      presets: ['es2015'],
      plugins: ['transform-es2015-modules-umd']
    }))
    .pipe(concat('index.js'))
    .pipe(gulp.dest('./'));
});

gulp.task('test', () => {
  return gulp.src('spec/**.js')
    .pipe(jasmine({
      config: {
        "spec_dir": "spec",
        "spec_files": [
          "**/*[sS]pec.js"
        ],
        "helpers": [
          "helpers/**/*.js"
          ],
        "stopSpecOnExpectationFailure": false,
        "random": false
      }
    }));

});

gulp.task('watch', () => {
  gulp.watch('src/*.js', ['build', 'test']);
  gulp.watch(['spec/**/*.js', 'spec/*.js', 'spec/**/*.tale'], ['test']);
});

gulp.task('devel', ['default', 'watch']);
gulp.task('default',['build', 'test']);
<commit_msg>Fix the way to build and test<commit_after>'use strict';
var gulp = require('gulp'),
    jasmine = require('gulp-jasmine'),
    babel = require('gulp-babel'),
    concat = require('gulp-concat');

gulp.task('build', () => {
  return gulp.src('src/**.js')
    .pipe(babel({
      presets: ['es2015'],
      plugins: ['transform-es2015-modules-umd']
    }))
    .pipe(concat('index.js'))
    .pipe(gulp.dest('./'));
});

gulp.task('test', () => {
  return gulp.src('spec/**.js')
    .pipe(jasmine({
      config: {
        "spec_dir": "spec",
        "spec_files": [
          "**/*[sS]pec.js"
        ],
        "helpers": [
          "helpers/**/*.js"
          ],
        "stopSpecOnExpectationFailure": false,
        "random": false
      }
    }));

});

gulp.task('watch', () => {
  gulp.watch('src/*.js', ['build']);
  gulp.watch(['spec/**/*.js', 'spec/*.js', 'spec/**/*.tale', 'index.js'], ['test']);
});

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


<commit_before>/*
 * Copyright (c) 2014 ThoughtWorks, Inc.
 *
 * Pixelated is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Pixelated is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Pixelated. If not, see <http://www.gnu.org/licenses/>.
 */

define(
  [
    'flight/lib/component',
    'views/templates',
    'mail_view/ui/mail_actions',
    'helpers/view_helper',
    'mixins/with_hide_and_show',
    'mixins/with_mail_tagging',
    'page/events',
    'views/i18n'
  ],

  function (defineComponent, templates, mailActions, viewHelpers, withHideAndShow, withMailTagging, events, i18n) {
  'use strict';

    return defineComponent(mailView, mailActions, withHideAndShow, withMailTagging);

    function mailView() {
      this.defaultAttrs({
        tags: '.mail-read-view__header-tags-tag',
        newTagInput: '#new-tag-input',
        newTagButton: '#new-tag-button',
        addNew: '.mail-read-view__header-tags-new-button',
        trashButton: '#trash-button',
        archiveButton: '#archive-button',
        closeMailButton: '.close-mail-button'
      });

      this.displayMail = function (event, data) {
        this.attr.mail = data.mail;

        var signed, encrypted, attachments;

        data.mail.security_casing = data.mail.security_casing || {};
        signed = this.checkSigned(data.mail);
        encrypted = this.checkEncrypted(data.mail);
        attachments = data.mail.attachments.map(function (attachment) {
            attachment.received = true;
            return attachment;
        });

        if(data.mail.mailbox === 'sent') {
          encrypted = undefined;
        }

        this.$node.html(templates.mails.fullView({
          header: data.mail.header,
          body: [],
          statuses: viewHelpers.formatStatusClasses(data.mail.status),
          ident: data.mail.ident,
          tags: data.mail.tags,
          encryptionStatus: encrypted,
          signatureStatus: signed,
          attachments: attachments
        }));

        var $iframe = $("#read-sandbox");
        var iframe = $iframe[0];

        var content = viewHelpers.formatMailBody(data.mail);

        iframe.onload = function() {
          // use iframe-resizer to dynamically adapt iframe size to its content
          var config = {
            resizedCallback: scaleToFit,
            checkOrigin: false
          };
          $iframe.iFrameResize(config);

          // transform scale iframe to fit container width
          // necessary if iframe is wider than container
          function scaleToFit() {
              var parentWidth = $iframe.parent().width();
              var w = $iframe.width();
              var scale = 'none';

              // only scale html mails
              var mail = data.mail;
              if (mail && mail.htmlBody && (w > parentWidth)) {
                  scale = parentWidth / w;
                  scale = 'scale(' + scale + ',' + scale + ')';
              }

              $iframe.css({
                  '-webkit-transform-origin': '0 0',
                  '-moz-transform-origin': '0 0',
                  '-ms-transform-origin': '0 0',
                  'transform-origin': '0 0',
                  '-webkit-transform': scale,
                  '-moz-transform': scale,
                  '-ms-transform': scale,
                  'transform': scale
              });
          }

          iframe.contentWindow.postMessage({
            html: content
          }, '*');
        };

        this.trigger(document, events.search.highlightResults, {where: '.mail-read-view__header'});
        this.trigger(document, events.ui.replyBox.showReplyContainer);

        this.attachTagCompletion(this.attr.mail);

        this.select('tags').on('click', function (event) {
          this.removeTag($(event.target).text());
        }.bind(this));

        this.addTagLoseFocus();
        this.on(this.select('newTagButton'), 'click', this.showNewTagInput);
        this.on(this.select('newTagInput'), 'keydown', this.handleKeyDown);
        this.on(this.select('newTagInput'), 'blur', this.addTagLoseFocus);
        this.on(this.select('trashButton'), 'click', this.moveToTrash);
        this.on(this.select('closeMailButton'), 'click', this.openNoMessageSelectedPane);

        mailActions.attachTo('#mail-actions', data);
        this.resetScroll();
      };

      this.resetScroll = function(){
        $('#right-pane').scrollTop(0);
      };

      this.checkEncrypted = function(mail) {
        if(_.isEmpty(mail.security_casing.locks)) {
          return {
            cssClass: 'security-status__label--not-encrypted',
            label: 'not-encrypted'
          }
        }

        var statusClass = ['security-status__label--encrypted'];
        var statusLabel = ['encrypted'];

        var hasAnyEncryptionInfo = _.any(mail.security_casing.locks, function (lock) {
          return lock.state === 'valid';
        });

        if(hasAnyEncryptionInfo) {
          statusLabel.push('encryption-valid');
        } else {
          statusClass.push('--with-error');
          statusLabel.push('encryption-error');
        }

        return {
          cssClass: statusClass.join(''),
          label: statusLabel.join(' ')
        }
      };

      this.checkSigned = function(mail) {
        var statusNotSigned = {
          cssClass: 'security-status__label--not-signed',
          label: 'not-signed'
        };

        if(_.isEmpty(mail.security_casing.imprints)) {
          return statusNotSigned;
        }

        var hasNoSignatureInformation = _.any(mail.security_casing.imprints, function (imprint) {
          return imprint.state === 'no_signature_information';
        });

        if(hasNoSignatureInformation) {
          return statusNotSigned;
        }

        var statusClass = ['security-status__label--signed']
        var statusLabel = ['signed'];

        if(_.any(mail.security_casing.imprints, function(imprint) { return imprint.state === 'from_revoked'; })) {
          statusClass.push('--revoked');
          statusLabel.push('signature-revoked');
        }

        if(_.any(mail.security_casing.imprints, function(imprint) { return imprint.state === 'from_expired'; })) {
          statusClass.push('--expired');
          statusLabel.push('signature-expired');
        }

        if(this.isNotTrusted(mail)) {
          statusClass.push('--not-trusted');
          statusLabel.push('signature-not-trusted');
        }

        return {
          cssClass: statusClass.join(''),
          label: statusLabel.join(' ')
        }
      };

      this.isNotTrusted = function(mail){
        return _.any(mail.security_casing.imprints, function(imprint) {
          if(_.isNull(imprint.seal)){
            return true;
          }
          var currentTrust = _.isUndefined(imprint.seal.trust) ? imprint.seal.validity : imprint.seal.trust;
          return currentTrust === 'no_trust';
        });
      };

      this.openNoMessageSelectedPane = function(ev, data) {
        this.trigger(document, events.dispatchers.rightPane.openNoMessageSelected);
      };

      this.handleKeyDown = function(event) {
        var ENTER_KEY = 13;
        var ESC_KEY = 27;

        if (event.which === ENTER_KEY){
          event.preventDefault();
          if (this.select('newTagInput').val().trim() !== '') {
            this.createNewTag();
          }
        } else if (event.which === ESC_KEY) {
          event.preventDefault();
          this.addTagLoseFocus();
        }
      };

      this.addTagLoseFocus = function () {
        this.select('newTagInput').hide();
        this.select('newTagInput').typeahead('val', '');
        this.select('addNew').show();
      };

      this.showNewTagInput = function () {
        this.select('newTagInput').show();
        this.select('newTagInput').focus();
        this.select('addNew').hide();
      };

      this.removeTag = function (tag) {
        tag = tag.toString();
        var filteredTags = _.without(this.attr.mail.tags, tag);
        this.updateTags(this.attr.mail, filteredTags);
        this.trigger(document, events.dispatchers.tags.refreshTagList);
      };

      this.moveToTrash = function(){
        this.trigger(document, events.ui.mail.delete, { mail: this.attr.mail });
      };

      this.tagsUpdated = function(ev, data) {
        data = data || {};
        this.attr.mail.tags = data.tags;
        this.displayMail({}, { mail: this.attr.mail });
      };

      this.mailDeleted = function(ev, data) {
        if (_.contains(_.pluck(data.mails, 'ident'),  this.attr.mail.ident)) {
          this.openNoMessageSelectedPane();
        }
      };

      this.fetchMailToShow = function () {
        this.trigger(events.mail.want, {mail: this.attr.ident, caller: this});
      };

      this.highlightMailContent = function (event, data) {
        // we can't directly manipulate the iFrame to highlight the content
        // so we need to take an indirection where we directly manipulate
        // the mail content to accomodate the highlighting
        this.trigger(document, events.mail.highlightMailContent, data);
      };

      this.after('initialize', function () {
        this.on(this, events.mail.notFound, this.openNoMessageSelectedPane);
        this.on(this, events.mail.here, this.highlightMailContent);
        this.on(document, events.mail.display, this.displayMail);
        this.on(document, events.dispatchers.rightPane.clear, this.teardown);
        this.on(document, events.mail.tags.updated, this.tagsUpdated);
        this.on(document, events.mail.deleted, this.mailDeleted);
        this.fetchMailToShow();
      });
    }
  }
);
<commit_msg>Issue #647: Refactor security labels stylesheet<commit_after>/*
 * Copyright (c) 2014 ThoughtWorks, Inc.
 *
 * Pixelated is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Pixelated is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Pixelated. If not, see <http://www.gnu.org/licenses/>.
 */

define(
  [
    'flight/lib/component',
    'views/templates',
    'mail_view/ui/mail_actions',
    'helpers/view_helper',
    'mixins/with_hide_and_show',
    'mixins/with_mail_tagging',
    'page/events',
    'views/i18n'
  ],

  function (defineComponent, templates, mailActions, viewHelpers, withHideAndShow, withMailTagging, events, i18n) {
  'use strict';

    return defineComponent(mailView, mailActions, withHideAndShow, withMailTagging);

    function mailView() {
      this.defaultAttrs({
        tags: '.mail-read-view__header-tags-tag',
        newTagInput: '#new-tag-input',
        newTagButton: '#new-tag-button',
        addNew: '.mail-read-view__header-tags-new-button',
        trashButton: '#trash-button',
        archiveButton: '#archive-button',
        closeMailButton: '.close-mail-button'
      });

      this.displayMail = function (event, data) {
        this.attr.mail = data.mail;

        var signed, encrypted, attachments;

        data.mail.security_casing = data.mail.security_casing || {};
        signed = this.checkSigned(data.mail);
        encrypted = this.checkEncrypted(data.mail);
        attachments = data.mail.attachments.map(function (attachment) {
            attachment.received = true;
            return attachment;
        });

        if(data.mail.mailbox === 'sent') {
          encrypted = undefined;
        }

        this.$node.html(templates.mails.fullView({
          header: data.mail.header,
          body: [],
          statuses: viewHelpers.formatStatusClasses(data.mail.status),
          ident: data.mail.ident,
          tags: data.mail.tags,
          encryptionStatus: encrypted,
          signatureStatus: signed,
          attachments: attachments
        }));

        var $iframe = $("#read-sandbox");
        var iframe = $iframe[0];

        var content = viewHelpers.formatMailBody(data.mail);

        iframe.onload = function() {
          // use iframe-resizer to dynamically adapt iframe size to its content
          var config = {
            resizedCallback: scaleToFit,
            checkOrigin: false
          };
          $iframe.iFrameResize(config);

          // transform scale iframe to fit container width
          // necessary if iframe is wider than container
          function scaleToFit() {
              var parentWidth = $iframe.parent().width();
              var w = $iframe.width();
              var scale = 'none';

              // only scale html mails
              var mail = data.mail;
              if (mail && mail.htmlBody && (w > parentWidth)) {
                  scale = parentWidth / w;
                  scale = 'scale(' + scale + ',' + scale + ')';
              }

              $iframe.css({
                  '-webkit-transform-origin': '0 0',
                  '-moz-transform-origin': '0 0',
                  '-ms-transform-origin': '0 0',
                  'transform-origin': '0 0',
                  '-webkit-transform': scale,
                  '-moz-transform': scale,
                  '-ms-transform': scale,
                  'transform': scale
              });
          }

          iframe.contentWindow.postMessage({
            html: content
          }, '*');
        };

        this.trigger(document, events.search.highlightResults, {where: '.mail-read-view__header'});
        this.trigger(document, events.ui.replyBox.showReplyContainer);

        this.attachTagCompletion(this.attr.mail);

        this.select('tags').on('click', function (event) {
          this.removeTag($(event.target).text());
        }.bind(this));

        this.addTagLoseFocus();
        this.on(this.select('newTagButton'), 'click', this.showNewTagInput);
        this.on(this.select('newTagInput'), 'keydown', this.handleKeyDown);
        this.on(this.select('newTagInput'), 'blur', this.addTagLoseFocus);
        this.on(this.select('trashButton'), 'click', this.moveToTrash);
        this.on(this.select('closeMailButton'), 'click', this.openNoMessageSelectedPane);

        mailActions.attachTo('#mail-actions', data);
        this.resetScroll();
      };

      this.resetScroll = function(){
        $('#right-pane').scrollTop(0);
      };

      this.checkEncrypted = function(mail) {
        if(_.isEmpty(mail.security_casing.locks)) {
          return {
            cssClass: 'security-status__label--not-encrypted',
            label: 'not-encrypted'
          };
        }

        var statusClass = ['security-status__label--encrypted'];
        var statusLabel = ['encrypted'];

        var hasAnyEncryptionInfo = _.any(mail.security_casing.locks, function (lock) {
          return lock.state === 'valid';
        });

        if(hasAnyEncryptionInfo) {
          statusLabel.push('encryption-valid');
        } else {
          statusClass.push('--with-error');
          statusLabel.push('encryption-error');
        }

        return {
          cssClass: statusClass.join(''),
          label: statusLabel.join(' ')
        };
      };

      this.checkSigned = function(mail) {
        var statusNotSigned = {
          cssClass: 'security-status__label--not-signed',
          label: 'not-signed'
        };

        if(_.isEmpty(mail.security_casing.imprints)) {
          return statusNotSigned;
        }

        var hasNoSignatureInformation = _.any(mail.security_casing.imprints, function (imprint) {
          return imprint.state === 'no_signature_information';
        });

        if(hasNoSignatureInformation) {
          return statusNotSigned;
        }

        var statusClass = ['security-status__label--signed'];
        var statusLabel = ['signed'];

        if(_.any(mail.security_casing.imprints, function(imprint) { return imprint.state === 'from_revoked'; })) {
          statusClass.push('--revoked');
          statusLabel.push('signature-revoked');
        }

        if(_.any(mail.security_casing.imprints, function(imprint) { return imprint.state === 'from_expired'; })) {
          statusClass.push('--expired');
          statusLabel.push('signature-expired');
        }

        if(this.isNotTrusted(mail)) {
          statusClass.push('--not-trusted');
          statusLabel.push('signature-not-trusted');
        }

        return {
          cssClass: statusClass.join(''),
          label: statusLabel.join(' ')
        };
      };

      this.isNotTrusted = function(mail){
        return _.any(mail.security_casing.imprints, function(imprint) {
          if(_.isNull(imprint.seal)){
            return true;
          }
          var currentTrust = _.isUndefined(imprint.seal.trust) ? imprint.seal.validity : imprint.seal.trust;
          return currentTrust === 'no_trust';
        });
      };

      this.openNoMessageSelectedPane = function(ev, data) {
        this.trigger(document, events.dispatchers.rightPane.openNoMessageSelected);
      };

      this.handleKeyDown = function(event) {
        var ENTER_KEY = 13;
        var ESC_KEY = 27;

        if (event.which === ENTER_KEY){
          event.preventDefault();
          if (this.select('newTagInput').val().trim() !== '') {
            this.createNewTag();
          }
        } else if (event.which === ESC_KEY) {
          event.preventDefault();
          this.addTagLoseFocus();
        }
      };

      this.addTagLoseFocus = function () {
        this.select('newTagInput').hide();
        this.select('newTagInput').typeahead('val', '');
        this.select('addNew').show();
      };

      this.showNewTagInput = function () {
        this.select('newTagInput').show();
        this.select('newTagInput').focus();
        this.select('addNew').hide();
      };

      this.removeTag = function (tag) {
        tag = tag.toString();
        var filteredTags = _.without(this.attr.mail.tags, tag);
        this.updateTags(this.attr.mail, filteredTags);
        this.trigger(document, events.dispatchers.tags.refreshTagList);
      };

      this.moveToTrash = function(){
        this.trigger(document, events.ui.mail.delete, { mail: this.attr.mail });
      };

      this.tagsUpdated = function(ev, data) {
        data = data || {};
        this.attr.mail.tags = data.tags;
        this.displayMail({}, { mail: this.attr.mail });
      };

      this.mailDeleted = function(ev, data) {
        if (_.contains(_.pluck(data.mails, 'ident'),  this.attr.mail.ident)) {
          this.openNoMessageSelectedPane();
        }
      };

      this.fetchMailToShow = function () {
        this.trigger(events.mail.want, {mail: this.attr.ident, caller: this});
      };

      this.highlightMailContent = function (event, data) {
        // we can't directly manipulate the iFrame to highlight the content
        // so we need to take an indirection where we directly manipulate
        // the mail content to accomodate the highlighting
        this.trigger(document, events.mail.highlightMailContent, data);
      };

      this.after('initialize', function () {
        this.on(this, events.mail.notFound, this.openNoMessageSelectedPane);
        this.on(this, events.mail.here, this.highlightMailContent);
        this.on(document, events.mail.display, this.displayMail);
        this.on(document, events.dispatchers.rightPane.clear, this.teardown);
        this.on(document, events.mail.tags.updated, this.tagsUpdated);
        this.on(document, events.mail.deleted, this.mailDeleted);
        this.fetchMailToShow();
      });
    }
  }
);
<|endoftext|>