<commit_before>'use strict';

// -----------------------------------------------------------------------------
// Dependencies
// -----------------------------------------------------------------------------
var p = require('./package.json');
var gulp = require('gulp');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var concat = require('gulp-concat');
var zip = require('gulp-zip');
var gulpIgnore = require('gulp-ignore');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var livereload = require('gulp-livereload');
var svgSymbols = require('gulp-svg-symbols');
var sourcemaps = require('gulp-sourcemaps');
var filter = require('gulp-filter');

// -----------------------------------------------------------------------------
// Configuration
// -----------------------------------------------------------------------------

// var themeNameSlug = 'OriginTheme';
var themeNameSlug = p.name;
var svgInput = './src/svg/*.svg';
var sassInput = './src/scss/**/*.scss';
var sassOutput = './dist/';
var autoprefixerOptions = { browsers: ['last 2 versions', '> 5%', 'Firefox ESR'] };

var jsInput = './src/js/**.js';

var jsPlugins = [
  'src/js/utils.js',
  'src/js/app.js'
];

// -----------------------------------------------------------------------------
// Sass compilation
// -----------------------------------------------------------------------------

gulp.task('sass', function () {
  return gulp
    .src(sassInput)
    .pipe(sourcemaps.init())
    .pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
    .pipe(autoprefixer(autoprefixerOptions))
    .pipe(rename('app.min.css'))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(sassOutput))
    .pipe(filter("**/*.css"))
    .pipe(livereload());
});

// -----------------------------------------------------------------------------
// SVG Sprite
// -----------------------------------------------------------------------------

gulp.task('svg_sprite', function () {
  return gulp.src(svgInput)
    .pipe(svgSymbols())
    .pipe(gulp.dest('dist'));
});

// -----------------------------------------------------------------------------
// Concat JS files
// -----------------------------------------------------------------------------

gulp.task('scripts', function(){
  return gulp.src(jsPlugins)
    .pipe(concat('app.js'))
    .pipe(gulp.dest('dist'))
    .pipe(rename('app.min.js'))
    .pipe(uglify())
    .pipe(gulp.dest('dist'))
    .pipe(livereload());
});

// -----------------------------------------------------------------------------
// Watchers
// -----------------------------------------------------------------------------

gulp.task('watch', function() {
  livereload.listen();

  gulp.watch([sassInput], ['sass'])
    .on('change', function(event) {
      console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    });

  gulp.watch([jsInput], ['scripts'])
    .on('change', function(event) {
      console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    });

  gulp.watch([svgInput], ['svg_sprite'])
    .on('change', function(event) {
      console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    });
});

// -----------------------------------------------------------------------------
// Production build
// -----------------------------------------------------------------------------

gulp.task('release', function () {
  return gulp.src(['**/*', '!' + themeNameSlug + '.zip', '!./node_modules', '!./node_modules/**', '!.git'])
    .pipe(zip(themeNameSlug + '.zip'))
    .pipe(gulp.dest('./'));
});

// -----------------------------------------------------------------------------
// Build task
// -----------------------------------------------------------------------------

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

// -----------------------------------------------------------------------------
// Default task
// -----------------------------------------------------------------------------

gulp.task('default', ['svg_sprite', 'sass', 'scripts', 'watch']);
<commit_msg>Prevent svgSymbols gulp task from outputting CSS<commit_after>'use strict';

// -----------------------------------------------------------------------------
// Dependencies
// -----------------------------------------------------------------------------
var p = require('./package.json');
var gulp = require('gulp');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var concat = require('gulp-concat');
var zip = require('gulp-zip');
var gulpIgnore = require('gulp-ignore');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var livereload = require('gulp-livereload');
var svgSymbols = require('gulp-svg-symbols');
var sourcemaps = require('gulp-sourcemaps');
var filter = require('gulp-filter');

// -----------------------------------------------------------------------------
// Configuration
// -----------------------------------------------------------------------------

// var themeNameSlug = 'OriginTheme';
var themeNameSlug = p.name;
var svgInput = './src/svg/*.svg';
var sassInput = './src/scss/**/*.scss';
var sassOutput = './dist/';
var autoprefixerOptions = { browsers: ['last 2 versions', '> 5%', 'Firefox ESR'] };

var jsInput = './src/js/**.js';

var jsPlugins = [
  'src/js/utils.js',
  'src/js/app.js'
];

// -----------------------------------------------------------------------------
// Sass compilation
// -----------------------------------------------------------------------------

gulp.task('sass', function () {
  return gulp
    .src(sassInput)
    .pipe(sourcemaps.init())
    .pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
    .pipe(autoprefixer(autoprefixerOptions))
    .pipe(rename('app.min.css'))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(sassOutput))
    .pipe(filter("**/*.css"))
    .pipe(livereload());
});

// -----------------------------------------------------------------------------
// SVG Sprite
// -----------------------------------------------------------------------------

gulp.task('svg_sprite', function () {
  return gulp.src(svgInput)
    .pipe(svgSymbols({
      templates: ['default-svg']
    }))
    .pipe(gulp.dest('dist'));
});

// -----------------------------------------------------------------------------
// Concat JS files
// -----------------------------------------------------------------------------

gulp.task('scripts', function(){
  return gulp.src(jsPlugins)
    .pipe(concat('app.js'))
    .pipe(gulp.dest('dist'))
    .pipe(rename('app.min.js'))
    .pipe(uglify())
    .pipe(gulp.dest('dist'))
    .pipe(livereload());
});

// -----------------------------------------------------------------------------
// Watchers
// -----------------------------------------------------------------------------

gulp.task('watch', function() {
  livereload.listen();

  gulp.watch([sassInput], ['sass'])
    .on('change', function(event) {
      console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    });

  gulp.watch([jsInput], ['scripts'])
    .on('change', function(event) {
      console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    });

  gulp.watch([svgInput], ['svg_sprite'])
    .on('change', function(event) {
      console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
    });
});

// -----------------------------------------------------------------------------
// Production build
// -----------------------------------------------------------------------------

gulp.task('release', function () {
  return gulp.src(['**/*', '!' + themeNameSlug + '.zip', '!./node_modules', '!./node_modules/**', '!.git'])
    .pipe(zip(themeNameSlug + '.zip'))
    .pipe(gulp.dest('./'));
});

// -----------------------------------------------------------------------------
// Build task
// -----------------------------------------------------------------------------

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

// -----------------------------------------------------------------------------
// Default task
// -----------------------------------------------------------------------------

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


<commit_before>/* jshint node: true */
var gulp = require('gulp');
var gulpif = require('gulp-if');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var replace = require('gulp-replace');
var imagemin = require('gulp-imagemin');
var autoprefixer = require('gulp-autoprefixer');
var minifyCss = require('gulp-minify-css');
var minifyHtml = require('gulp-minify-html');
var argv = require('yargs').argv;
var shell = require('gulp-shell');
var uglify = require('gulp-uglify');
var runSequence = require('run-sequence');
var ngAnnotate = require('gulp-ng-annotate');

// allows for watch to continue after errors
function handleError(error) {
  console.error(error);
  this.emit('end');
};

// fixes runsequence always exiting with 0 even on errors
// http://dev.topheman.com/gulp-fail-run-sequence-with-a-correct-exit-code/
var handleSequenceError = function (error, done) {
  //if any error happened in the previous tasks, exit with a code > 0
  if (error) {
    var exitCode = 2;
    console.log('[ERROR] gulp sequenced task failed', error);
    console.log('[FAIL] gulp sequenced task failed - exiting with code ' + exitCode);
    return process.exit(exitCode);
  }
  else {
    return done();
  }
};

var basePaths = {
  root: './',
  dev: './toc/',
  devApp: './toc/app/',
  prod: './www/',
  prodApp: './www/app/',
  mobile: './mobile/',
  platforms: './platforms/',
  cordova: './cordova-bundles/'
};

var paths = {
  sass: {
    app: [
      basePaths.devApp + 'components/**/*.scss',
      basePaths.devApp + 'libraries/**/*.scss',
      basePaths.devApp + 'views/**/*.scss',
      basePaths.devApp + 'app.scss'
    ],
    init: [
      basePaths.devApp + 'initialize.scss'
    ],
    landing: [
      basePaths.dev + 'landing.scss'
    ]
  },
  js: [
    basePaths.devApp + 'components/**/*.js',
    basePaths.devApp + 'libraries/**/*.js',
    basePaths.devApp + 'services/**/*.js',
    basePaths.devApp + 'views/**/*.js',
    basePaths.devApp + '*.js',
    basePaths.dev + '*.js',
    basePaths.root + '*.js'
  ],
  html: [
    basePaths.devApp + 'components/**/*.html',
    basePaths.devApp + 'views/**/*.html',
    basePaths.devApp + '*.html',
    basePaths.dev + '*.html'
  ],
  asset: [
    basePaths.devApp + 'assets/**'
  ],
  cordova: [
    basePaths.cordova + 'android/cordova.js',
    basePaths.cordova + 'android/plugins/*.js'
  ]
};

gulp.task('nil');

gulp.task('watch', function watch() {
  gulp.watch(paths.sass.app, ['bundle-sass-app']);
  gulp.watch(paths.sass.init, ['bundle-sass-init']);
  gulp.watch(paths.sass.landing, ['bundle-sass-landing']);
});

gulp.task('version', function version() {
  var tocVersion = require('./package.json').version;
  return gulp.src(basePaths.root + 'config.xml')
    .pipe(replace(
      /<widget id="net\.lewisl\.toc-im" version="[0-9]+(\.[0-9]+)*"/,
      '<widget id="net.lewisl.toc-im" version="' + tocVersion + '"'
    ))
    .pipe(gulp.dest(basePaths.root));
});

gulp.task('serve', function serve() {
  var serveCommand = argv.prod ?
    'http-server www -p 8100' :
    // 'cd app && jspm-server --no-browser --port=8100 --ignore-exts=".scss"';
    'ionic serve --lab ' +
      '--address=$(hostname -i) -i 8101 --nobrowser --nocordovamock';
  return gulp.src('')
    .pipe(shell(serveCommand));
});

gulp.task('clean', ['clean-build', 'clean-package']);

gulp.task('clean-build', function clean() {
  return gulp.src('')
    .pipe(shell('rm -rf ' + basePaths.prod));
});

gulp.task('build', function build(done) {
  return runSequence(
    'clean-build',
    'uncache-jspm',
    ['build-js', 'build-html', 'build-sass', 'build-asset'],
    // 'cache-jspm',
    function (error) {
      return handleSequenceError(error, done);
    }
  );
});

gulp.task('package', function package(done) {
  var handlePackageError = function (error) {
    runSequence(
      ['uninject-cordova', 'uninject-livereload', 'unfix-ionic'],
      function() {
        return handleSequenceError(error, done);
      }
    );
  };

  if (argv.dev) {
    var packageAndroidTask = argv.packagedev ?
      ['package-android'] :
      ['nil'];
    var packageIosTask = argv.packagedev ?
      ['package-ios'] :
      ['nil'];

    var downloadTask = argv.packagedev ?
      (argv.skipdownload ? ['nil'] : ['download']) :
      ['nil'];

    return runSequence(
      ['inject-cordova', 'inject-livereload', 'fix-ionic'],
      packageIosTask,
      packageAndroidTask,
      ['unfix-ionic', 'uninject-livereload'],
      downloadTask,
      ['serve'],
      ['uninject-cordova'],
      handlePackageError
    );
  }

  var buildTask = argv.skipbuild ? ['nil'] : ['build'];
  var downloadTask = argv.skipdownload ? ['nil'] : ['download'];

  return runSequence(
    buildTask,
    ['inject-cordova', 'fix-ionic'],
    ['package-ios'],
    ['package-android'],
    ['uninject-cordova', 'unfix-ionic'],
    downloadTask,
    handlePackageError
  );
});

gulp.task('package-android', function packageAndroid() {
  var packageCommandDev = '/bin/bash scripts/toc-package-android.sh';
  var packageCommandProd = packageCommandDev + ' prod';

  var packageCommand = argv.prod ? packageCommandProd : packageCommandDev;
  return gulp.src('')
    .pipe(shell(packageCommand));
});

gulp.task('package-ios', function packageIos() {
  var packageCommandDev = '/bin/bash scripts/toc-package-ios.sh';
  var packageCommandProd = packageCommandDev + ' prod';

  var packageCommand = argv.prod ? packageCommandProd : packageCommandDev;
  return gulp.src('')
    .pipe(shell(packageCommand));
});

gulp.task('download', ['download-android', 'download-ios']);

gulp.task('download-android', function downloadAndroid() {
  return gulp.src('')
    .pipe(shell('/bin/bash scripts/toc-package-download.sh android'));
});

gulp.task('download-ios', function downloadIos() {
  return gulp.src('')
    .pipe(shell('/bin/bash scripts/toc-package-download.sh ios'));
});

gulp.task('inject-livereload', function injectLivereload() {
  var hostIp = process.env['TOC_HOST_IP'] || argv.hostip;

  if (!hostIp) {
    throw new Error('Please provide a host IP through the --hostip parameter or TOC_HOST_IP environment variable');
  }

  return gulp.src([
      basePaths.root + 'config.xml'
    ], {
      base: basePaths.root
    })
    .pipe(replace(
      '<content src="app/index.html"/>',
      '<content src="http://' + process.env['TOC_HOST_IP'] +
        ':8100/app/index.html" original-src="app/index.html"/>'
    ))
    .pipe(gulp.dest(basePaths.root));
});

gulp.task('uninject-livereload', function uninjectLivereload() {
  var hostIp = process.env['TOC_HOST_IP'] || argv.hostip;

  return gulp.src([
      basePaths.root + 'config.xml'
    ], {
      base: basePaths.root
    })
    .pipe(replace(
      '<content src="http://' + process.env['TOC_HOST_IP'] +
        ':8100/app/index.html" original-src="app/index.html"/>',
      '<content src="app/index.html"/>'
    ))
    .pipe(gulp.dest(basePaths.root));
});

gulp.task('inject-cordova', function injectCordova() {
  var basePath = argv.dev ? basePaths.dev : basePaths.prod;
  var baseAppPath = argv.dev ? basePaths.devApp : basePaths.prodApp;

  return gulp.src([
      baseAppPath + 'index.html'
    ], {
      base: baseAppPath
    })
    .pipe(replace(
      '',
      ''
    ))
    .pipe(gulp.dest(baseAppPath))
    .pipe(gulpif(argv.dev, shell(
      'cp -r ' + basePaths.cordova + 'android/cordova.js ' + basePath + ' && ' +
      'cp -r ' + basePaths.cordova + 'android/plugins ' + basePath
    )));
});

gulp.task('uninject-cordova', function injectCordova() {
  var basePath = argv.dev ? basePaths.dev : basePaths.prod;
  var baseAppPath = argv.dev ? basePaths.devApp : basePaths.prodApp;

  return gulp.src([
      baseAppPath + 'index.html'
    ], {
      base: baseAppPath
    })
    .pipe(replace(
      '',
      ''
    ))
    .pipe(gulp.dest(baseAppPath))
    .pipe(gulpif(argv.dev, shell(
      'rm -rf ' + basePath + 'cordova.js && ' +
      'rm -rf ' + basePath + 'plugins'
    )));
});

gulp.task('fix-ionic', function fixIonic() {
  //FIXME: workaround for
  // https://github.com/driftyco/ionic-cli/issues/620
  return gulp.src(basePaths.root + 'ionic.project')
    .pipe(replace(
      '"documentRoot": "toc"',
      '"documentRoot": "www"'
    ))
    .pipe(gulp.dest(basePaths.root));
});

gulp.task('unfix-ionic', function unfixIonic() {
  return gulp.src(basePaths.root + 'ionic.project')
    .pipe(replace(
      '"documentRoot": "www"',
      '"documentRoot": "toc"'
    ))
    .pipe(gulp.dest(basePaths.root));
});

gulp.task('build-js', ['replace-js', 'build-jspm'], function buildJs() {
  return gulp.src([
      basePaths.devApp + 'dependencies/system-csp-production.src.js',
      basePaths.devApp + 'dependencies/system-polyfills.js',
      basePaths.devApp + 'jspm-config.js'
    ], {
      base: basePaths.dev
    })
    .pipe(gulpif(argv.prod, uglify()))
    .pipe(gulp.dest(basePaths.prod));
});

gulp.task('replace-js', function replaceJs() {
  var tocVersion = require('./package.json').version;
  return gulp.src([
      basePaths.devApp + 'initialize.js',
      basePaths.dev + 'landing.js'
    ], {
      base: basePaths.dev
    })
    .pipe(replace(
      'window.tocVersion = \'dev\';',
      'window.tocVersion = \'' + tocVersion + '\';'
    ))
    .pipe(gulpif(argv.prod, replace(
      'window.tocProd = false',
      'window.tocProd = true'
    )))
    .pipe(gulpif(argv.prod, uglify()))
    .pipe(gulp.dest(basePaths.prod));
});

gulp.task('build-jspm', ['bundle-jspm'], function buildJspm() {
  return gulp.src(basePaths.prodApp + 'app.js')
    .pipe(gulpif(argv.prod, ngAnnotate()))
    .pipe(gulpif(argv.prod, uglify()))
    .pipe(gulp.dest(basePaths.prodApp));
});

gulp.task('bundle-jspm', function bundleJspm() {
  return gulp.src('')
    .pipe(shell([
      //clear depcache config first
      'jspm bundle app ' + basePaths.prodApp +
        'app.js --skip-source-maps'
    ]));
});

gulp.task('uncache-jspm', function uncacheJspm() {
  return gulp.src('')
    .pipe(shell([
      'jspm unbundle'
    ]));
});

gulp.task('cache-jspm', function cacheJspm() {
  return gulp.src('')
    .pipe(shell([
      'jspm depcache app'
    ]));
});

gulp.task('build-html', ['replace-html'], function buildHtml() {
  return gulp.src([
      basePaths.dev + 'index.html'
    ], {
      base: basePaths.dev
    })
    .pipe(gulpif(argv.prod, minifyHtml()))
    .pipe(gulp.dest(basePaths.prod));
});

gulp.task('replace-html', function replaceHtml() {
  return gulp.src([
      basePaths.devApp + 'index.html'
    ], {
      base: basePaths.dev
    })
    .pipe(replace(
      'dependencies/system.src.js',
      'dependencies/system-csp-production.src.js'
    ))
    .pipe(gulpif(argv.prod, replace(' http://*:8101', '')))
    .pipe(gulpif(argv.prod, minifyHtml()))
    .pipe(gulp.dest(basePaths.prod));
});

gulp.task('build-asset', ['build-image', 'build-font']);

gulp.task('build-font', function buildFont() {
  return gulp.src([
      basePaths.devApp + 'assets/fonts/**'
    ], {
      base: basePaths.dev
    })
    .pipe(gulp.dest(basePaths.prod));
});

gulp.task('build-image', function buildImage() {
  return gulp.src([
      basePaths.devApp + 'assets/images/*.svg'
      // PNGs have been pre-minified
      // basePaths.devApp + 'assets/images/**'
    ], {
      base: basePaths.dev
    })
    .pipe(gulpif(argv.prod, imagemin({
      // optimizationLevel: 7,
      multipass: true
    })))
    .pipe(gulp.dest(basePaths.prod));
});

gulp.task('build-sass', ['bundle-sass'], function buildSass() {
  return gulp.src([
      basePaths.devApp + 'app.css',
      basePaths.devApp + 'initialize.css',
      basePaths.dev + 'landing.css'
    ], {
      base: basePaths.dev
    })
    .pipe(gulp.dest(basePaths.prod))
    .on('error', handleError);
});

gulp.task('bundle-sass', [
  'bundle-sass-app',
  'bundle-sass-init',
  'bundle-sass-landing'
]);

var makeSassTask = function makeSassTask(sassPath) {
  return gulp.src(sassPath, { base: basePaths.dev })
    .pipe(gulpif(!argv.prod, sourcemaps.init()))
    .pipe(sass())
    .on('error', handleError)
    .pipe(autoprefixer({ browsers: ['last 2 versions'] }))
    .on('error', handleError)
    .pipe(gulpif(argv.prod, minifyCss()))
    .pipe(gulpif(!argv.prod, sourcemaps.write()))
    .pipe(gulp.dest(basePaths.dev))
    .on('error', handleError);
};

gulp.task('bundle-sass-app', function bundleSass() {
  return makeSassTask(basePaths.devApp + 'app.scss');
});

gulp.task('bundle-sass-init', function bundleSass() {
  return makeSassTask(basePaths.devApp + 'initialize.scss');
});

gulp.task('bundle-sass-landing', function bundleSass() {
  return makeSassTask(basePaths.dev + 'landing.scss');
});
<commit_msg>Fixed missing pngs in builds<commit_after>/* jshint node: true */
var gulp = require('gulp');
var gulpif = require('gulp-if');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var replace = require('gulp-replace');
var imagemin = require('gulp-imagemin');
var autoprefixer = require('gulp-autoprefixer');
var minifyCss = require('gulp-minify-css');
var minifyHtml = require('gulp-minify-html');
var argv = require('yargs').argv;
var shell = require('gulp-shell');
var uglify = require('gulp-uglify');
var runSequence = require('run-sequence');
var ngAnnotate = require('gulp-ng-annotate');

// allows for watch to continue after errors
function handleError(error) {
  console.error(error);
  this.emit('end');
};

// fixes runsequence always exiting with 0 even on errors
// http://dev.topheman.com/gulp-fail-run-sequence-with-a-correct-exit-code/
var handleSequenceError = function (error, done) {
  //if any error happened in the previous tasks, exit with a code > 0
  if (error) {
    var exitCode = 2;
    console.log('[ERROR] gulp sequenced task failed', error);
    console.log('[FAIL] gulp sequenced task failed - exiting with code ' + exitCode);
    return process.exit(exitCode);
  }
  else {
    return done();
  }
};

var basePaths = {
  root: './',
  dev: './toc/',
  devApp: './toc/app/',
  prod: './www/',
  prodApp: './www/app/',
  mobile: './mobile/',
  platforms: './platforms/',
  cordova: './cordova-bundles/'
};

var paths = {
  sass: {
    app: [
      basePaths.devApp + 'components/**/*.scss',
      basePaths.devApp + 'libraries/**/*.scss',
      basePaths.devApp + 'views/**/*.scss',
      basePaths.devApp + 'app.scss'
    ],
    init: [
      basePaths.devApp + 'initialize.scss'
    ],
    landing: [
      basePaths.dev + 'landing.scss'
    ]
  },
  js: [
    basePaths.devApp + 'components/**/*.js',
    basePaths.devApp + 'libraries/**/*.js',
    basePaths.devApp + 'services/**/*.js',
    basePaths.devApp + 'views/**/*.js',
    basePaths.devApp + '*.js',
    basePaths.dev + '*.js',
    basePaths.root + '*.js'
  ],
  html: [
    basePaths.devApp + 'components/**/*.html',
    basePaths.devApp + 'views/**/*.html',
    basePaths.devApp + '*.html',
    basePaths.dev + '*.html'
  ],
  asset: [
    basePaths.devApp + 'assets/**'
  ],
  cordova: [
    basePaths.cordova + 'android/cordova.js',
    basePaths.cordova + 'android/plugins/*.js'
  ]
};

gulp.task('nil');

gulp.task('watch', function watch() {
  gulp.watch(paths.sass.app, ['bundle-sass-app']);
  gulp.watch(paths.sass.init, ['bundle-sass-init']);
  gulp.watch(paths.sass.landing, ['bundle-sass-landing']);
});

gulp.task('version', function version() {
  var tocVersion = require('./package.json').version;
  return gulp.src(basePaths.root + 'config.xml')
    .pipe(replace(
      /<widget id="net\.lewisl\.toc-im" version="[0-9]+(\.[0-9]+)*"/,
      '<widget id="net.lewisl.toc-im" version="' + tocVersion + '"'
    ))
    .pipe(gulp.dest(basePaths.root));
});

gulp.task('serve', function serve() {
  var serveCommand = argv.prod ?
    'http-server www -p 8100' :
    // 'cd app && jspm-server --no-browser --port=8100 --ignore-exts=".scss"';
    'ionic serve --lab ' +
      '--address=$(hostname -i) -i 8101 --nobrowser --nocordovamock';
  return gulp.src('')
    .pipe(shell(serveCommand));
});

gulp.task('clean', ['clean-build', 'clean-package']);

gulp.task('clean-build', function clean() {
  return gulp.src('')
    .pipe(shell('rm -rf ' + basePaths.prod));
});

gulp.task('build', function build(done) {
  return runSequence(
    'clean-build',
    'uncache-jspm',
    ['build-js', 'build-html', 'build-sass', 'build-asset'],
    // 'cache-jspm',
    function (error) {
      return handleSequenceError(error, done);
    }
  );
});

gulp.task('package', function package(done) {
  var handlePackageError = function (error) {
    runSequence(
      ['uninject-cordova', 'uninject-livereload', 'unfix-ionic'],
      function() {
        return handleSequenceError(error, done);
      }
    );
  };

  if (argv.dev) {
    var packageAndroidTask = argv.packagedev ?
      ['package-android'] :
      ['nil'];
    var packageIosTask = argv.packagedev ?
      ['package-ios'] :
      ['nil'];

    var downloadTask = argv.packagedev ?
      (argv.skipdownload ? ['nil'] : ['download']) :
      ['nil'];

    return runSequence(
      ['inject-cordova', 'inject-livereload', 'fix-ionic'],
      packageIosTask,
      packageAndroidTask,
      ['unfix-ionic', 'uninject-livereload'],
      downloadTask,
      ['serve'],
      ['uninject-cordova'],
      handlePackageError
    );
  }

  var buildTask = argv.skipbuild ? ['nil'] : ['build'];
  var downloadTask = argv.skipdownload ? ['nil'] : ['download'];

  return runSequence(
    buildTask,
    ['inject-cordova', 'fix-ionic'],
    ['package-ios'],
    ['package-android'],
    ['uninject-cordova', 'unfix-ionic'],
    downloadTask,
    handlePackageError
  );
});

gulp.task('package-android', function packageAndroid() {
  var packageCommandDev = '/bin/bash scripts/toc-package-android.sh';
  var packageCommandProd = packageCommandDev + ' prod';

  var packageCommand = argv.prod ? packageCommandProd : packageCommandDev;
  return gulp.src('')
    .pipe(shell(packageCommand));
});

gulp.task('package-ios', function packageIos() {
  var packageCommandDev = '/bin/bash scripts/toc-package-ios.sh';
  var packageCommandProd = packageCommandDev + ' prod';

  var packageCommand = argv.prod ? packageCommandProd : packageCommandDev;
  return gulp.src('')
    .pipe(shell(packageCommand));
});

gulp.task('download', ['download-android', 'download-ios']);

gulp.task('download-android', function downloadAndroid() {
  return gulp.src('')
    .pipe(shell('/bin/bash scripts/toc-package-download.sh android'));
});

gulp.task('download-ios', function downloadIos() {
  return gulp.src('')
    .pipe(shell('/bin/bash scripts/toc-package-download.sh ios'));
});

gulp.task('inject-livereload', function injectLivereload() {
  var hostIp = process.env['TOC_HOST_IP'] || argv.hostip;

  if (!hostIp) {
    throw new Error('Please provide a host IP through the --hostip parameter or TOC_HOST_IP environment variable');
  }

  return gulp.src([
      basePaths.root + 'config.xml'
    ], {
      base: basePaths.root
    })
    .pipe(replace(
      '<content src="app/index.html"/>',
      '<content src="http://' + process.env['TOC_HOST_IP'] +
        ':8100/app/index.html" original-src="app/index.html"/>'
    ))
    .pipe(gulp.dest(basePaths.root));
});

gulp.task('uninject-livereload', function uninjectLivereload() {
  var hostIp = process.env['TOC_HOST_IP'] || argv.hostip;

  return gulp.src([
      basePaths.root + 'config.xml'
    ], {
      base: basePaths.root
    })
    .pipe(replace(
      '<content src="http://' + process.env['TOC_HOST_IP'] +
        ':8100/app/index.html" original-src="app/index.html"/>',
      '<content src="app/index.html"/>'
    ))
    .pipe(gulp.dest(basePaths.root));
});

gulp.task('inject-cordova', function injectCordova() {
  var basePath = argv.dev ? basePaths.dev : basePaths.prod;
  var baseAppPath = argv.dev ? basePaths.devApp : basePaths.prodApp;

  return gulp.src([
      baseAppPath + 'index.html'
    ], {
      base: baseAppPath
    })
    .pipe(replace(
      '',
      ''
    ))
    .pipe(gulp.dest(baseAppPath))
    .pipe(gulpif(argv.dev, shell(
      'cp -r ' + basePaths.cordova + 'android/cordova.js ' + basePath + ' && ' +
      'cp -r ' + basePaths.cordova + 'android/plugins ' + basePath
    )));
});

gulp.task('uninject-cordova', function injectCordova() {
  var basePath = argv.dev ? basePaths.dev : basePaths.prod;
  var baseAppPath = argv.dev ? basePaths.devApp : basePaths.prodApp;

  return gulp.src([
      baseAppPath + 'index.html'
    ], {
      base: baseAppPath
    })
    .pipe(replace(
      '',
      ''
    ))
    .pipe(gulp.dest(baseAppPath))
    .pipe(gulpif(argv.dev, shell(
      'rm -rf ' + basePath + 'cordova.js && ' +
      'rm -rf ' + basePath + 'plugins'
    )));
});

gulp.task('fix-ionic', function fixIonic() {
  //FIXME: workaround for
  // https://github.com/driftyco/ionic-cli/issues/620
  return gulp.src(basePaths.root + 'ionic.project')
    .pipe(replace(
      '"documentRoot": "toc"',
      '"documentRoot": "www"'
    ))
    .pipe(gulp.dest(basePaths.root));
});

gulp.task('unfix-ionic', function unfixIonic() {
  return gulp.src(basePaths.root + 'ionic.project')
    .pipe(replace(
      '"documentRoot": "www"',
      '"documentRoot": "toc"'
    ))
    .pipe(gulp.dest(basePaths.root));
});

gulp.task('build-js', ['replace-js', 'build-jspm'], function buildJs() {
  return gulp.src([
      basePaths.devApp + 'dependencies/system-csp-production.src.js',
      basePaths.devApp + 'dependencies/system-polyfills.js',
      basePaths.devApp + 'jspm-config.js'
    ], {
      base: basePaths.dev
    })
    .pipe(gulpif(argv.prod, uglify()))
    .pipe(gulp.dest(basePaths.prod));
});

gulp.task('replace-js', function replaceJs() {
  var tocVersion = require('./package.json').version;
  return gulp.src([
      basePaths.devApp + 'initialize.js',
      basePaths.dev + 'landing.js'
    ], {
      base: basePaths.dev
    })
    .pipe(replace(
      'window.tocVersion = \'dev\';',
      'window.tocVersion = \'' + tocVersion + '\';'
    ))
    .pipe(gulpif(argv.prod, replace(
      'window.tocProd = false',
      'window.tocProd = true'
    )))
    .pipe(gulpif(argv.prod, uglify()))
    .pipe(gulp.dest(basePaths.prod));
});

gulp.task('build-jspm', ['bundle-jspm'], function buildJspm() {
  return gulp.src(basePaths.prodApp + 'app.js')
    .pipe(gulpif(argv.prod, ngAnnotate()))
    .pipe(gulpif(argv.prod, uglify()))
    .pipe(gulp.dest(basePaths.prodApp));
});

gulp.task('bundle-jspm', function bundleJspm() {
  return gulp.src('')
    .pipe(shell([
      //clear depcache config first
      'jspm bundle app ' + basePaths.prodApp +
        'app.js --skip-source-maps'
    ]));
});

gulp.task('uncache-jspm', function uncacheJspm() {
  return gulp.src('')
    .pipe(shell([
      'jspm unbundle'
    ]));
});

gulp.task('cache-jspm', function cacheJspm() {
  return gulp.src('')
    .pipe(shell([
      'jspm depcache app'
    ]));
});

gulp.task('build-html', ['replace-html'], function buildHtml() {
  return gulp.src([
      basePaths.dev + 'index.html'
    ], {
      base: basePaths.dev
    })
    .pipe(gulpif(argv.prod, minifyHtml()))
    .pipe(gulp.dest(basePaths.prod));
});

gulp.task('replace-html', function replaceHtml() {
  return gulp.src([
      basePaths.devApp + 'index.html'
    ], {
      base: basePaths.dev
    })
    .pipe(replace(
      'dependencies/system.src.js',
      'dependencies/system-csp-production.src.js'
    ))
    .pipe(gulpif(argv.prod, replace(' http://*:8101', '')))
    .pipe(gulpif(argv.prod, minifyHtml()))
    .pipe(gulp.dest(basePaths.prod));
});

gulp.task('build-asset', ['build-image', 'build-font']);

gulp.task('build-font', function buildFont() {
  return gulp.src([
      basePaths.devApp + 'assets/fonts/**'
    ], {
      base: basePaths.dev
    })
    .pipe(gulp.dest(basePaths.prod));
});

gulp.task('build-image', ['build-png'], function buildImage() {
  return gulp.src([
      basePaths.devApp + 'assets/images/*.svg'
      // basePaths.devApp + 'assets/images/**'
    ], {
      base: basePaths.dev
    })
    .pipe(gulpif(argv.prod, imagemin({
      // optimizationLevel: 7,
      multipass: true
    })))
    .pipe(gulp.dest(basePaths.prod));
});

gulp.task('build-png', function buildPng() {
  // PNGs have been pre-minified, just need to copy
  return gulp.src([
      basePaths.devApp + 'assets/images/*.png'
    ], {
      base: basePaths.dev
    })
    .pipe(gulp.dest(basePaths.prod));
});

gulp.task('build-sass', ['bundle-sass'], function buildSass() {
  return gulp.src([
      basePaths.devApp + 'app.css',
      basePaths.devApp + 'initialize.css',
      basePaths.dev + 'landing.css'
    ], {
      base: basePaths.dev
    })
    .pipe(gulp.dest(basePaths.prod))
    .on('error', handleError);
});

gulp.task('bundle-sass', [
  'bundle-sass-app',
  'bundle-sass-init',
  'bundle-sass-landing'
]);

var makeSassTask = function makeSassTask(sassPath) {
  return gulp.src(sassPath, { base: basePaths.dev })
    .pipe(gulpif(!argv.prod, sourcemaps.init()))
    .pipe(sass())
    .on('error', handleError)
    .pipe(autoprefixer({ browsers: ['last 2 versions'] }))
    .on('error', handleError)
    .pipe(gulpif(argv.prod, minifyCss()))
    .pipe(gulpif(!argv.prod, sourcemaps.write()))
    .pipe(gulp.dest(basePaths.dev))
    .on('error', handleError);
};

gulp.task('bundle-sass-app', function bundleSass() {
  return makeSassTask(basePaths.devApp + 'app.scss');
});

gulp.task('bundle-sass-init', function bundleSass() {
  return makeSassTask(basePaths.devApp + 'initialize.scss');
});

gulp.task('bundle-sass-landing', function bundleSass() {
  return makeSassTask(basePaths.dev + 'landing.scss');
});
<|endoftext|>


<commit_before>'use strict'

var gulp = require('gulp')
var ghPages = require('gh-pages')
var sequence = require('run-sequence')

// load gulp plugins
var $ = require('gulp-load-plugins')()
var connect = $.connect

// Build variables (default to local config)
var jekyllConfigs = {
  PROD: 'config/jekyll.yml',
  LOCAL: 'config/jekyll.local.yml'
}

var jekyllConfig = jekyllConfigs.LOCAL

// Sources
var sources = {
  content: 'app/**/*.{markdown,md,html,txt,yml,yaml}',
  styles: 'app/_assets/stylesheets/**/*.{less,css}',
  js: 'app/_assets/javascripts/**/*.js',
  images: 'app/_assets/images/**/*',
  fonts: 'bower_components/font-awesome/fonts/**/*.*'
}

gulp.task('styles', function () {
  var glob = require('glob')
  // TODO: add LESS linting

  // thibaultcha:
  // 1. gulp-less has plugins (minifier and prefixer) we can run in $.less(plugins: [clean, prefix])
  // but they throw errors if we use them. Let's use gulp-autoprefixer and gulp-minify-css.
  // 2. If we want to use uncss, we need to minify after it runs, otherwise it unminifies the css
  // another reason not to use gulp-less plugins.
  // 3. the source maps still don't work if used along with gulp-autoprefixer
  // 4. uncss and gulpminify-css seem to behave fine and is not having an impact on sourcemaps
  return gulp.src('app/_assets/stylesheets/index.less')
    .pipe($.plumber())
    .pipe($.less())
    //.pipe($.uncss({ html: glob.sync('dist/**/*.html') }))
    .pipe($.autoprefixer())
    .pipe($.minifyCss())
    .pipe($.rename('styles.css'))
    .pipe(gulp.dest('dist/assets/'))
    .pipe($.size())
    .pipe(connect.reload())
})

gulp.task('javascripts', function () {
  return gulp.src(sources.js)
    .pipe($.plumber())
    .pipe($.jshint())
    .pipe($.jshint.reporter(require('jshint-stylish')))
    .pipe($.sourcemaps.init())
    .pipe($.concat('app.js'))
    .pipe($.uglify())
    .pipe($.sourcemaps.write('maps'))
    .pipe(gulp.dest('dist/assets'))
    .pipe($.size())
    .pipe(connect.reload())
})

gulp.task('images', function () {
  return gulp.src(sources.images)
    .pipe($.plumber())
    .pipe(gulp.dest('dist/assets/images'))
    .pipe($.size())
    .pipe(connect.reload())
})

gulp.task('fonts', function () {
  return gulp.src(sources.fonts)
      .pipe($.plumber())
      .pipe(gulp.dest('dist/assets/fonts'))
      .pipe($.size())
      .pipe(connect.reload())
})

gulp.task('jekyll', function (next) {
  var command = 'bundle exec jekyll build --config ' + jekyllConfig + ' --destination dist'

  require('child_process').exec(command, function (err, stdout, stderr) {
    console.log(stdout)
    console.error(stderr)
    next(err)
  })
})

gulp.task('html', ['jekyll'], function () {
  return gulp.src('dist/**/*.html')
    .pipe($.plumber())
    .pipe($.htmlmin({
      minifyJS: true,
      minifyCSS: true,
      removeComments: true,
      collapseWhitespace: true,
      conservativeCollapse: true,
      removeEmptyAttributes: true,
      collapseBooleanAttributes: true,
      removeScriptTypeAttributes: true,
      removeStyleLinkTypeAttributes: true
    }))
    .pipe(gulp.dest('dist'))
    .pipe($.size())
    .pipe(connect.reload())
})

gulp.task('clean', function (cb) {
  ghPages.clean()
  require('del')(['dist', '.gh-pages'], cb)
})

gulp.task('build', ['javascripts', 'images', 'fonts'], function (cb) {
  sequence('html', 'styles', cb)
})

gulp.task('build:prod', function (cb) {
  jekyllConfig = jekyllConfigs.PROD
  sequence('build', cb)
})

gulp.task('connect', function () {
  connect.server({
    port: 9000,
    root: 'dist',
    livereload: true,
    fallback: 'dist/404.html'
  })
})

gulp.task('gh-pages', function (next) {
  var path = require('path')
  var config = {
    message: 'Update ' + new Date().toISOString()
  }

  ghPages.publish(path.join(__dirname, 'dist'), config, next)
})

gulp.task('deploy:prod', function (cb) {
  sequence('build:prod', 'gh-pages', cb)
})

gulp.task('watch', function () {
  gulp.watch(sources.content, ['build'])
  gulp.watch(sources.styles, ['styles'])
  gulp.watch(sources.images, ['images'])
  gulp.watch(sources.js, ['javascripts'])
})

gulp.task('default', ['clean'], function (cb) {
  sequence('build', 'connect', 'watch', cb)
})
<commit_msg>bring back gulp uncss and add some selectors to ignore<commit_after>'use strict'

var gulp = require('gulp')
var ghPages = require('gh-pages')
var sequence = require('run-sequence')

// load gulp plugins
var $ = require('gulp-load-plugins')()
var connect = $.connect

// Build variables (default to local config)
var jekyllConfigs = {
  PROD: 'config/jekyll.yml',
  LOCAL: 'config/jekyll.local.yml'
}

var jekyllConfig = jekyllConfigs.LOCAL

// Sources
var sources = {
  content: 'app/**/*.{markdown,md,html,txt,yml,yaml}',
  styles: 'app/_assets/stylesheets/**/*.{less,css}',
  js: 'app/_assets/javascripts/**/*.js',
  images: 'app/_assets/images/**/*',
  fonts: 'bower_components/font-awesome/fonts/**/*.*'
}

gulp.task('styles', function () {
  var glob = require('glob')
  // TODO: add LESS linting

  // thibaultcha:
  // 1. gulp-less has plugins (minifier and prefixer) we can run in $.less(plugins: [clean, prefix])
  // but they throw errors if we use them. Let's use gulp-autoprefixer and gulp-minify-css.
  // 2. If we want to use uncss, we need to minify after it runs, otherwise it unminifies the css
  // another reason not to use gulp-less plugins.
  // 3. the source maps still don't work if used along with gulp-autoprefixer
  // 4. uncss and gulpminify-css seem to behave fine and is not having an impact on sourcemaps
  return gulp.src('app/_assets/stylesheets/index.less')
    .pipe($.plumber())
    .pipe($.less())
    .pipe($.uncss({
      html: glob.sync('dist/**/*.html'),
      ignore: ['.open > .dropdown-menu', '.open > a']
    }))
    .pipe($.autoprefixer())
    .pipe($.minifyCss())
    .pipe($.rename('styles.css'))
    .pipe(gulp.dest('dist/assets/'))
    .pipe($.size())
    .pipe(connect.reload())
})

gulp.task('javascripts', function () {
  return gulp.src(sources.js)
    .pipe($.plumber())
    .pipe($.jshint())
    .pipe($.jshint.reporter(require('jshint-stylish')))
    .pipe($.sourcemaps.init())
    .pipe($.concat('app.js'))
    .pipe($.uglify())
    .pipe($.sourcemaps.write('maps'))
    .pipe(gulp.dest('dist/assets'))
    .pipe($.size())
    .pipe(connect.reload())
})

gulp.task('images', function () {
  return gulp.src(sources.images)
    .pipe($.plumber())
    .pipe(gulp.dest('dist/assets/images'))
    .pipe($.size())
    .pipe(connect.reload())
})

gulp.task('fonts', function () {
  return gulp.src(sources.fonts)
      .pipe($.plumber())
      .pipe(gulp.dest('dist/assets/fonts'))
      .pipe($.size())
      .pipe(connect.reload())
})

gulp.task('jekyll', function (next) {
  var command = 'bundle exec jekyll build --config ' + jekyllConfig + ' --destination dist'

  require('child_process').exec(command, function (err, stdout, stderr) {
    console.log(stdout)
    console.error(stderr)
    next(err)
  })
})

gulp.task('html', ['jekyll'], function () {
  return gulp.src('dist/**/*.html')
    .pipe($.plumber())
    .pipe($.htmlmin({
      minifyJS: true,
      minifyCSS: true,
      removeComments: true,
      collapseWhitespace: true,
      conservativeCollapse: true,
      removeEmptyAttributes: true,
      collapseBooleanAttributes: true,
      removeScriptTypeAttributes: true,
      removeStyleLinkTypeAttributes: true
    }))
    .pipe(gulp.dest('dist'))
    .pipe($.size())
    .pipe(connect.reload())
})

gulp.task('clean', function (cb) {
  ghPages.clean()
  require('del')(['dist', '.gh-pages'], cb)
})

gulp.task('build', ['javascripts', 'images', 'fonts'], function (cb) {
  sequence('html', 'styles', cb)
})

gulp.task('build:prod', function (cb) {
  jekyllConfig = jekyllConfigs.PROD
  sequence('build', cb)
})

gulp.task('connect', function () {
  connect.server({
    port: 9000,
    root: 'dist',
    livereload: true,
    fallback: 'dist/404.html'
  })
})

gulp.task('gh-pages', function (next) {
  var path = require('path')
  var config = {
    message: 'Update ' + new Date().toISOString()
  }

  ghPages.publish(path.join(__dirname, 'dist'), config, next)
})

gulp.task('deploy:prod', function (cb) {
  sequence('build:prod', 'gh-pages', cb)
})

gulp.task('watch', function () {
  gulp.watch(sources.content, ['build'])
  gulp.watch(sources.styles, ['styles'])
  gulp.watch(sources.images, ['images'])
  gulp.watch(sources.js, ['javascripts'])
})

gulp.task('default', ['clean'], function (cb) {
  sequence('build', 'connect', 'watch', cb)
})
<|endoftext|>


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

tasks.config({
    build_directory: "./",
    js_files: [
        "js/ender.min.js",
        "js/app.js"
    ],
    css_files: [
        "css/app.css"
    ],
    icon_files: "node_modules/geomicons-open/icons/*.svg",
    build: function () {

        var nunjucks = require('nunjucks');
        var engine = require('static-engine');
        var site = engine('./', nunjucks.render);
        var push = function (literal) {

            return function (pages, next) {

                pages.push(literal);

                next(pages);
            };
        };

        nunjucks.configure('./templates/', {
            autoescape: true
        });

        site.route('/').use(push({
            controls: {
                'Work': {'interval': 25, 'message': 'Take a break!'},
                'Break': {'interval': 5, 'message': 'Back to work!'}
            },
            colors: [
                '#AAAAAA',
                '#FF851B',
                '#2ECC40',
                '#0074D9',
                '#F012BE'
            ]
        })).render('index.html');

        return site.build();
    }
});

tasks();
<commit_msg>Update gulpfile with api changes<commit_after>
var tasks = require('gulp-tasks');

tasks.config({
    directory: "./",
    js: [
        "js/ender.min.js",
        "js/app.js"
    ],
    css: [
        "css/app.css"
    ],
    icons: "node_modules/geomicons-open/icons/*.svg",
    build: function () {

        var nunjucks = require('nunjucks');
        var engine = require('static-engine');
        var site = engine('./', nunjucks.render);
        var push = function (literal) {

            return function (pages, next) {

                pages.push(literal);

                next(pages);
            };
        };

        nunjucks.configure('./templates/', {
            autoescape: true
        });

        site.route('/').use(push({
            controls: {
                'Work': {'interval': 25, 'message': 'Take a break!'},
                'Break': {'interval': 5, 'message': 'Back to work!'}
            },
            colors: [
                '#AAAAAA',
                '#FF851B',
                '#2ECC40',
                '#0074D9',
                '#F012BE'
            ]
        })).render('index.html');

        return site.build();
    }
});

tasks();
<|endoftext|>


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

/**
 * External dependencies
 */
import PropTypes from 'prop-types';

/**
 * WordPress dependencies
 */
import { useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import Data from 'googlesitekit-data';
import {
	MODULES_SEARCH_CONSOLE,
	DATE_RANGE_OFFSET,
} from '../../../datastore/constants';
import { CORE_USER } from '../../../../../googlesitekit/datastore/user/constants';
import { isZeroReport } from '../../../util';
import PreviewBlock from '../../../../../components/PreviewBlock';
import Header from './Header';
import Overview from './Overview';
import Stats from './Stats';
const { useSelect } = Data;

const ModuleOverviewWidget = ( {
	Widget,
	WidgetReportZero,
	WidgetReportError,
} ) => {
	const [ selectedStats, setSelectedStats ] = useState( 0 );
	const { endDate, compareStartDate } = useSelect( ( select ) =>
		select( CORE_USER ).getDateRangeDates( {
			compare: true,
			offsetDays: DATE_RANGE_OFFSET,
		} )
	);
	const reportArgs = {
		startDate: compareStartDate,
		endDate,
		dimensions: 'date',
	};
	const data = useSelect( ( select ) =>
		select( MODULES_SEARCH_CONSOLE ).getReport( reportArgs )
	);
	const error = useSelect( ( select ) =>
		select( MODULES_SEARCH_CONSOLE ).getErrorForSelector( 'getReport', [
			reportArgs,
		] )
	);
	const loading = useSelect(
		( select ) =>
			! select(
				MODULES_SEARCH_CONSOLE
			).hasFinishedResolution( 'getReport', [ reportArgs ] )
	);
	const dateRangeLength = useSelect( ( select ) =>
		select( CORE_USER ).getDateRangeNumberOfDays()
	);

	const WidgetHeader = () => (
		<Header
			metrics={ ModuleOverviewWidget.metrics }
			selectedStats={ selectedStats }
		/>
	);

	if ( loading ) {
		return (
			<Widget Header={ WidgetHeader } noPadding>
				<PreviewBlock width="100%" height="190px" padding />
				<PreviewBlock width="100%" height="270px" padding />
			</Widget>
		);
	}

	if ( error ) {
		return (
			<Widget Header={ WidgetHeader }>
				<WidgetReportError
					moduleSlug="search-console"
					error={ error }
				/>
			</Widget>
		);
	}

	if ( isZeroReport( data ) ) {
		return (
			<Widget Header={ WidgetHeader }>
				<WidgetReportZero moduleSlug="search-console" />
			</Widget>
		);
	}

	return (
		<Widget noPadding Header={ WidgetHeader }>
			<Overview
				data={ data }
				handleStatsSelection={ setSelectedStats }
				selectedStats={ selectedStats }
				dateRangeLength={ dateRangeLength }
			/>

			<Stats
				data={ data }
				dateRangeLength={ dateRangeLength }
				selectedStats={ selectedStats }
				metrics={ ModuleOverviewWidget.metrics }
			/>
		</Widget>
	);
};

ModuleOverviewWidget.metrics = [
	{
		color: '#4285f4',
		label: __( 'Clicks', 'google-site-kit' ),
		metric: 'clicks',
	},
	{
		color: '#27bcd4',
		label: __( 'Impressions', 'google-site-kit' ),
		metric: 'impressions',
	},
	{
		color: '#1b9688',
		label: __( 'CTR', 'google-site-kit' ),
		metric: 'ctr',
	},
	{
		color: '#673ab7',
		label: __( 'Position', 'google-site-kit' ),
		metric: 'position',
	},
];

ModuleOverviewWidget.propTypes = {
	Widget: PropTypes.elementType.isRequired,
	WidgetReportZero: PropTypes.elementType.isRequired,
	WidgetReportError: PropTypes.elementType.isRequired,
};

export default ModuleOverviewWidget;
<commit_msg>Update the ModuleOverviewWidget component.<commit_after>/**
 * ModuleOverviewWidget component.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * External dependencies
 */
import PropTypes from 'prop-types';

/**
 * WordPress dependencies
 */
import { useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
 * Internal dependencies
 */
import Data from 'googlesitekit-data';
import {
	MODULES_SEARCH_CONSOLE,
	DATE_RANGE_OFFSET,
} from '../../../datastore/constants';
import { CORE_USER } from '../../../../../googlesitekit/datastore/user/constants';
import { isZeroReport } from '../../../util';
import PreviewBlock from '../../../../../components/PreviewBlock';
import Header from './Header';
import Overview from './Overview';
import Stats from './Stats';
const { useSelect } = Data;

export default function ModuleOverviewWidget( props ) {
	const { Widget, WidgetReportZero, WidgetReportError } = props;

	const [ selectedStats, setSelectedStats ] = useState( 0 );
	const { endDate, compareStartDate } = useSelect( ( select ) =>
		select( CORE_USER ).getDateRangeDates( {
			compare: true,
			offsetDays: DATE_RANGE_OFFSET,
		} )
	);

	const isGatheringData = useSelect( ( select ) =>
		select( MODULES_SEARCH_CONSOLE ).isGatheringData()
	);

	const reportArgs = {
		startDate: compareStartDate,
		endDate,
		dimensions: 'date',
	};

	const data = useSelect( ( select ) =>
		select( MODULES_SEARCH_CONSOLE ).getReport( reportArgs )
	);
	const error = useSelect( ( select ) =>
		select( MODULES_SEARCH_CONSOLE ).getErrorForSelector( 'getReport', [
			reportArgs,
		] )
	);
	const loading = useSelect(
		( select ) =>
			! select(
				MODULES_SEARCH_CONSOLE
			).hasFinishedResolution( 'getReport', [ reportArgs ] )
	);
	const dateRangeLength = useSelect( ( select ) =>
		select( CORE_USER ).getDateRangeNumberOfDays()
	);

	const WidgetHeader = () => (
		<Header
			metrics={ ModuleOverviewWidget.metrics }
			selectedStats={ selectedStats }
		/>
	);

	if ( loading || isGatheringData === undefined ) {
		return (
			<Widget Header={ WidgetHeader } noPadding>
				<PreviewBlock width="100%" height="190px" padding />
				<PreviewBlock width="100%" height="270px" padding />
			</Widget>
		);
	}

	if ( error ) {
		return (
			<Widget Header={ WidgetHeader }>
				<WidgetReportError
					moduleSlug="search-console"
					error={ error }
				/>
			</Widget>
		);
	}

	if ( isGatheringData && isZeroReport( data ) ) {
		return (
			<Widget Header={ WidgetHeader }>
				<WidgetReportZero moduleSlug="search-console" />
			</Widget>
		);
	}

	return (
		<Widget noPadding Header={ WidgetHeader }>
			<Overview
				data={ data }
				handleStatsSelection={ setSelectedStats }
				selectedStats={ selectedStats }
				dateRangeLength={ dateRangeLength }
			/>

			<Stats
				data={ data }
				dateRangeLength={ dateRangeLength }
				selectedStats={ selectedStats }
				metrics={ ModuleOverviewWidget.metrics }
			/>
		</Widget>
	);
}

ModuleOverviewWidget.metrics = [
	{
		color: '#4285f4',
		label: __( 'Clicks', 'google-site-kit' ),
		metric: 'clicks',
	},
	{
		color: '#27bcd4',
		label: __( 'Impressions', 'google-site-kit' ),
		metric: 'impressions',
	},
	{
		color: '#1b9688',
		label: __( 'CTR', 'google-site-kit' ),
		metric: 'ctr',
	},
	{
		color: '#673ab7',
		label: __( 'Position', 'google-site-kit' ),
		metric: 'position',
	},
];

ModuleOverviewWidget.propTypes = {
	Widget: PropTypes.elementType.isRequired,
	WidgetReportZero: PropTypes.elementType.isRequired,
	WidgetReportError: PropTypes.elementType.isRequired,
};
<|endoftext|>


<commit_before>/* eslint-env node */
/* eslint-disable import/unambiguous */
/* eslint-disable import/no-commonjs */
/* eslint-disable import/no-nodejs-modules */

const fs = require('fs');
const path = require('path');
const https = require('https');
const gulp = require('gulp');
const concat = require('gulp-concat');
const sourcemaps = require('gulp-sourcemaps');
const cssnano = require('cssnano');
const forOwn = require('lodash/forOwn');
const git = require('git-rev-sync');
const postcss = require('gulp-postcss');
const cssnext = require('postcss-cssnext');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const cloudflare = require('cloudflare');
const BrowserSync = require('browser-sync');
const pify = require('pify');
const config = require('./src/config');
const webpackConfiguration = require('./webpack.config');

const browserSync = BrowserSync.create();
const srcDir = 'src';
const distDir = 'dist';
const stylesheetsDir = path.join(srcDir, 'css');
const highlightStylesheetsDir = 'node_modules/highlight.js/styles';
const staticDir = path.join(srcDir, 'static');
const bowerComponents = 'bower_components';

const cssnextBrowsers = [];
const supportedBrowsers =
  JSON.parse(fs.readFileSync('./config/browsers.json'));
forOwn(supportedBrowsers, (version, browser) => {
  let browserForCssnext = browser;
  if (browser === 'msie') {
    browserForCssnext = 'ie';
  }
  cssnextBrowsers.push(`${browserForCssnext} >= ${version}`);
});

gulp.task('env', () => {
  process.env.GIT_REVISION = git.short();
});

gulp.task('static', () => gulp.
  src(path.join(staticDir, '**/*')).
  pipe(gulp.dest(distDir)),
);

gulp.task('fonts', () => gulp.
  src([
    path.join(
      bowerComponents,
      'inconsolata-webfont/fonts/inconsolata-regular.*',
    ),
    path.join(bowerComponents, 'fontawesome/fonts/fontawesome-webfont.*'),
    path.join(
      bowerComponents,
      'roboto-webfont-bower/fonts/Roboto-{Bold,Regular}-webfont.*',
    ),
  ]).
  pipe(gulp.dest(path.join(distDir, 'fonts'))),
);

gulp.task('css', () => {
  const processors = [cssnext({browsers: cssnextBrowsers})];
  if (process.env.NODE_ENV === 'production') {
    processors.push(cssnano());
  }

  return gulp.
    src([
      path.join(bowerComponents, 'normalize-css/normalize.css'),
      path.join(highlightStylesheetsDir, 'github.css'),
      path.join(stylesheetsDir, '**/*.css'),
    ]).
    pipe(concat('application.css')).
    pipe(sourcemaps.init({loadMaps: true})).
    pipe(postcss(processors)).
    pipe(sourcemaps.write('./')).
    pipe(gulp.dest(distDir)).
    pipe(browserSync.stream());
});

gulp.task('js', ['env'], () =>
  pify(webpack)(webpackConfiguration(process.env.NODE_ENV)),
);

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

gulp.task('syncFirebase', async() => {
  const data = await pify(fs).readFile(
    path.resolve(__dirname, 'config/firebase-auth.json'),
  );
  const firebaseSecret = process.env.FIREBASE_SECRET;
  if (!firebaseSecret) {
    throw new Error('Missing environment variable FIREBASE_SECRET');
  }

  return new Promise((resolve, reject) => {
    const req = https.request({
      hostname: `${config.firebaseApp}.firebaseio.com`,
      path: `/.settings/rules.json?auth=${firebaseSecret}`,
      method: 'PUT',
    }, (res) => {
      if (res.statusCode === 200) {
        resolve();
      } else {
        res.on('data', reject);
      }
    });

    req.write(data);
    req.end();
  });
});

gulp.task('dev', ['browserSync', 'static', 'fonts', 'css'], () => {
  gulp.watch(path.join(staticDir, '/**/*'), ['static']);
  gulp.watch(path.join(stylesheetsDir, '**/*.css'), ['css']);
  gulp.watch(path.join(distDir, '*')).on('change', browserSync.reload);
});

gulp.task('browserSync', ['static'], () => {
  const compiler = webpack(webpackConfiguration(process.env.NODE_ENV));
  compiler.plugin('invalid', browserSync.reload);
  browserSync.init({
    server: {
      baseDir: distDir,
      middleware: [
        webpackDevMiddleware(
          compiler,
          {
            lazy: false,
            stats: 'errors-only',
          },
        ),
      ],
    },
  });
});

gulp.task('purgeCache', () =>
  cloudflare({
    email: process.env.CLOUDFLARE_EMAIL,
    key: process.env.CLOUDFLARE_KEY,
  }).zones.purgeCache(
    process.env.CLOUDFLARE_ZONE,
    {purge_everything: true},
  ),
);
<commit_msg>Only purge HTML and CSS from Cloudflare cache<commit_after>/* eslint-env node */
/* eslint-disable import/unambiguous */
/* eslint-disable import/no-commonjs */
/* eslint-disable import/no-nodejs-modules */

const fs = require('fs');
const path = require('path');
const https = require('https');
const gulp = require('gulp');
const concat = require('gulp-concat');
const sourcemaps = require('gulp-sourcemaps');
const cssnano = require('cssnano');
const forOwn = require('lodash/forOwn');
const git = require('git-rev-sync');
const postcss = require('gulp-postcss');
const cssnext = require('postcss-cssnext');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const cloudflare = require('cloudflare');
const BrowserSync = require('browser-sync');
const pify = require('pify');
const config = require('./src/config');
const webpackConfiguration = require('./webpack.config');

const browserSync = BrowserSync.create();
const srcDir = 'src';
const distDir = 'dist';
const stylesheetsDir = path.join(srcDir, 'css');
const highlightStylesheetsDir = 'node_modules/highlight.js/styles';
const staticDir = path.join(srcDir, 'static');
const bowerComponents = 'bower_components';

const cssnextBrowsers = [];
const supportedBrowsers =
  JSON.parse(fs.readFileSync('./config/browsers.json'));
forOwn(supportedBrowsers, (version, browser) => {
  let browserForCssnext = browser;
  if (browser === 'msie') {
    browserForCssnext = 'ie';
  }
  cssnextBrowsers.push(`${browserForCssnext} >= ${version}`);
});

gulp.task('env', () => {
  process.env.GIT_REVISION = git.short();
});

gulp.task('static', () => gulp.
  src(path.join(staticDir, '**/*')).
  pipe(gulp.dest(distDir)),
);

gulp.task('fonts', () => gulp.
  src([
    path.join(
      bowerComponents,
      'inconsolata-webfont/fonts/inconsolata-regular.*',
    ),
    path.join(bowerComponents, 'fontawesome/fonts/fontawesome-webfont.*'),
    path.join(
      bowerComponents,
      'roboto-webfont-bower/fonts/Roboto-{Bold,Regular}-webfont.*',
    ),
  ]).
  pipe(gulp.dest(path.join(distDir, 'fonts'))),
);

gulp.task('css', () => {
  const processors = [cssnext({browsers: cssnextBrowsers})];
  if (process.env.NODE_ENV === 'production') {
    processors.push(cssnano());
  }

  return gulp.
    src([
      path.join(bowerComponents, 'normalize-css/normalize.css'),
      path.join(highlightStylesheetsDir, 'github.css'),
      path.join(stylesheetsDir, '**/*.css'),
    ]).
    pipe(concat('application.css')).
    pipe(sourcemaps.init({loadMaps: true})).
    pipe(postcss(processors)).
    pipe(sourcemaps.write('./')).
    pipe(gulp.dest(distDir)).
    pipe(browserSync.stream());
});

gulp.task('js', ['env'], () =>
  pify(webpack)(webpackConfiguration(process.env.NODE_ENV)),
);

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

gulp.task('syncFirebase', async() => {
  const data = await pify(fs).readFile(
    path.resolve(__dirname, 'config/firebase-auth.json'),
  );
  const firebaseSecret = process.env.FIREBASE_SECRET;
  if (!firebaseSecret) {
    throw new Error('Missing environment variable FIREBASE_SECRET');
  }

  return new Promise((resolve, reject) => {
    const req = https.request({
      hostname: `${config.firebaseApp}.firebaseio.com`,
      path: `/.settings/rules.json?auth=${firebaseSecret}`,
      method: 'PUT',
    }, (res) => {
      if (res.statusCode === 200) {
        resolve();
      } else {
        res.on('data', reject);
      }
    });

    req.write(data);
    req.end();
  });
});

gulp.task('dev', ['browserSync', 'static', 'fonts', 'css'], () => {
  gulp.watch(path.join(staticDir, '/**/*'), ['static']);
  gulp.watch(path.join(stylesheetsDir, '**/*.css'), ['css']);
  gulp.watch(path.join(distDir, '*')).on('change', browserSync.reload);
});

gulp.task('browserSync', ['static'], () => {
  const compiler = webpack(webpackConfiguration(process.env.NODE_ENV));
  compiler.plugin('invalid', browserSync.reload);
  browserSync.init({
    server: {
      baseDir: distDir,
      middleware: [
        webpackDevMiddleware(
          compiler,
          {
            lazy: false,
            stats: 'errors-only',
          },
        ),
      ],
    },
  });
});

gulp.task('purgeCache', () =>
  cloudflare({
    email: process.env.CLOUDFLARE_EMAIL,
    key: process.env.CLOUDFLARE_KEY,
  }).zones.purgeCache(
    process.env.CLOUDFLARE_ZONE,
    {
      files: [
        'https://popcode.org/index.html',
        'https://popcode.org/application.css',
      ],
    },
  ),
);
<|endoftext|>


<commit_before>var exec = require('child_process').exec;
var gulp = require('gulp');

gulp.task('test', function() {
  var path = './node_modules/mocha-phantomjs/bin/mocha-phantomjs';
  var command = '/test/index.html';

  exec(path + ' ' + command, function (error, stdout, stderr) {
    if (stdout) {
      console.log(stdout);
    } else if (stderr) {
      console.log(stderr);
    } else if (error) {
      console.log(error);
    }
  });
});
<commit_msg>Concat test files to serve only one test file to mocha-phantomjs.<commit_after>var exec = require('child_process').exec,

    gulp = require('gulp'),
    size = require('gulp-size'),
    concat = require('gulp-concat')

gulp.task('build_tests', function() {
  return gulp.src('./test/**/!(tests)**.js')
    .pipe(concat('tests.js'))
    .pipe(size())
    .pipe(gulp.dest('./test'))
});

gulp.task('test', ['build_tests'], function() {
  var path = './node_modules/mocha-phantomjs/bin/mocha-phantomjs';
  var command = '/test/index.html';

  exec(path + ' ' + command, function (error, stdout, stderr) {
    if (stdout) {
      console.log(stdout);
    } else if (stderr) {
      console.log(stderr);
    } else if (error) {
      console.log(error);
    }
  });
});
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
({
    assertBodyComponentDefRef: function(cmp) {
        var value = cmp.find("iteration").getValue("v.body");
        $A.test.assertEquals("ArrayValue", value.toString());
        $A.test.assertEquals(1, value.getLength());
        value = value.get(0);
        $A.test.assertTrue(typeof value === "object");
        $A.test.assertEquals(undefined, value.auraType);
        $A.test.assertEquals(undefined, value.getDef);
        $A.test.assertEquals("markup://aura:expression", value.componentDef.descriptor);
    },

    /**
     * Iteration body is rendered by renderIf
     */
    testSanity:{
        attributes:{ items:"alpha,omega" },
        test:function(cmp){
            // Verify renderIf
            var value = cmp.find("if").getValue("v.body");
            $A.test.assertEquals("ArrayValue", value.toString());
            $A.test.assertEquals(1, value.getLength());
            value = value.get(0);
            var iteration = cmp.find("iteration");
            $A.test.assertEquals(iteration, value);

            this.assertBodyComponentDefRef(cmp);

            var realbody = iteration.getValue("v.realbody");
            $A.test.assertEquals("ArrayValue", realbody.toString());
            $A.test.assertEquals(2, realbody.getLength());
            value = realbody.get(0);
            $A.test.assertTrue(typeof value === "object");
            $A.test.assertEquals("Component", value.auraType);
            $A.test.assertEquals("markup://aura:expression", value.getDef().getDescriptor().getQualifiedName());
            $A.test.assertEquals("0:alpha,", value.get("v.value"));
            value = realbody.get(1);
            $A.test.assertTrue(typeof value === "object");
            $A.test.assertEquals("Component", value.auraType);
            $A.test.assertEquals("markup://aura:expression", value.getDef().getDescriptor().getQualifiedName());
            $A.test.assertEquals("1:omega,", value.get("v.value"));
        }
    },

    /**
     * Iteration body is not rendered by renderIf
     */
    testNotRendered:{
        attributes:{ showIteration:false, items:"alpha,omega" },
        test:function(cmp){
            // Verify renderIf
            var value = cmp.find("if").getValue("v.body");
            $A.test.assertEquals("ArrayValue", value.toString());
            $A.test.assertEquals(1, value.getLength());
            value = value.get(0);
            var iteration = cmp.find("iteration");
            $A.test.assertEquals(iteration, value);

            this.assertBodyComponentDefRef(cmp);

            var realbody = iteration.getValue("v.realbody");
            $A.test.assertEquals("ArrayValue", realbody.toString());
            $A.test.assertEquals(2, realbody.getLength());
            $A.test.assertFalse(iteration.isRendered());
            $A.test.assertTrue(undefined === iteration.getElements());

            value = realbody.get(0);
            $A.test.assertTrue(typeof value === "object");
            $A.test.assertEquals("Component", value.auraType);
            $A.test.assertEquals("markup://aura:expression", value.getDef().getDescriptor().getQualifiedName());
            $A.test.assertEquals("0:alpha,", value.get("v.value"));
            $A.test.assertFalse(value.isRendered());
            $A.test.assertTrue(undefined === value.getElements());
            value = realbody.get(1);
            $A.test.assertTrue(typeof value === "object");
            $A.test.assertEquals("Component", value.auraType);
            $A.test.assertEquals("markup://aura:expression", value.getDef().getDescriptor().getQualifiedName());
            $A.test.assertEquals("1:omega,", value.get("v.value"));
            $A.test.assertFalse(value.isRendered());
            $A.test.assertTrue(undefined === value.getElements());
        }
    },

    /**
     * Iteration is empty if items is empty
     */
    testItemsEmpty:{
        test:function(cmp){
            this.assertBodyComponentDefRef(cmp);
            var realbody = cmp.find("iteration").getValue("v.realbody");
            $A.test.assertEquals("ArrayValue", realbody.toString());
            $A.test.assertEquals(0, realbody.getLength());
        }
    },

    testStartAndEnd:{
        attributes:{ items:"a,b,c,d,e", start:2, end:3 },
        test:function(cmp){
            this.assertBodyComponentDefRef(cmp);
            var realbody = cmp.find("iteration").getValue("v.realbody");
            $A.test.assertEquals(1, realbody.getLength());
            value = realbody.get(0);
            $A.test.assertTrue(typeof value === "object");
            $A.test.assertEquals("2:c,", value.get("v.value"));
        }
    },

    /**
     * Iteration is empty if start greater than items length
     */
    testStartGreaterThanLength:{
        attributes:{ items:"a,b,c,d,e", start:99 },
        test:function(cmp){
            this.assertBodyComponentDefRef(cmp);
            var realbody = cmp.find("iteration").getValue("v.realbody");
            $A.test.assertEquals("ArrayValue", realbody.toString());
            $A.test.assertEquals(0, realbody.getLength());
        }
    },

    /**
     * Iteration is empty if start greater than end
     */
    testStartGreaterThanEnd:{
        attributes:{ items:"a,b,c,d,e", start:3, end:2 },
        test:function(cmp){
            this.assertBodyComponentDefRef(cmp);
            var realbody = cmp.find("iteration").getValue("v.realbody");
            $A.test.assertEquals("ArrayValue", realbody.toString());
            $A.test.assertEquals(0, realbody.getLength());
        }
    },

    /**
     * Iteration starts at start and contains remainder of list, without end
     */
    testStartWithoutEnd:{
        attributes:{ items:"a,b,c,d,e", start:3 },
        test:function(cmp){
            this.assertBodyComponentDefRef(cmp);
            var realbody = cmp.find("iteration").getValue("v.realbody");
            $A.test.assertEquals(2, realbody.getLength());
            value = realbody.get(0);
            $A.test.assertEquals("3:d,", value.get("v.value"));
            value = realbody.get(1);
            $A.test.assertEquals("4:e,", value.get("v.value"));
        }
    },

    /**
     * Iteration starts with first item and ends before end, without start
     */
    testEndWithoutStart:{
        attributes:{ items:"a,b,c,d,e", end:3 },
        test:function(cmp){
            this.assertBodyComponentDefRef(cmp);
            var realbody = cmp.find("iteration").getValue("v.realbody");
            $A.test.assertEquals(3, realbody.getLength());
            value = realbody.get(0);
            $A.test.assertEquals("0:a,", value.get("v.value"));
            value = realbody.get(1);
            $A.test.assertEquals("1:b,", value.get("v.value"));
            value = realbody.get(2);
            $A.test.assertEquals("2:c,", value.get("v.value"));
        }
    },

    /**
     * Iteration starts with first item and ends before end, without start
     */
    testStartNegative:{
        attributes:{ items:"delta,gamma", start:-3 },
        test:function(cmp){
            this.assertBodyComponentDefRef(cmp);
            var realbody = cmp.find("iteration").getValue("v.realbody");
            $A.test.assertEquals(2, realbody.getLength());
            value = realbody.get(0);
            $A.test.assertEquals("0:delta,", value.get("v.value"));
            value = realbody.get(1);
            $A.test.assertEquals("1:gamma,", value.get("v.value"));
        }
    },

    /**
     * Iteration with decimal start value is treated as integer
     */
    testStartDecimal:{
        attributes:{ items:"alpha,beta", start: 0.000001 },
        test:function(cmp){
            this.assertBodyComponentDefRef(cmp);
            var realbody = cmp.find("iteration").getValue("v.realbody");
            $A.test.assertEquals(2, realbody.getLength());
            value = realbody.get(0);
            $A.test.assertEquals("0:alpha,", value.get("v.value"));
            value = realbody.get(1);
            $A.test.assertEquals("1:beta,", value.get("v.value"));
        }
    },

    /** Iteration rerender stays stable */
    testEmptyAndFill:{
        attributes:{ items:"alpha,beta" },
        test:[function(cmp) {
            var items = cmp.getValue("v.items");
            items.remove(0);
        },
        function(cmp) {
            var items = cmp.getValue("v.items");
            items.remove(0);
        },
        function(cmp) {
            var items = cmp.getValue("v.items");
            items.push("xyz");
        },
        function(cmp) {
            var realbody = cmp.find("iteration").getValue("v.realbody");
            // This assertion isn't the big one; it doesn't show the render state.
            // But we do want to be sure it's right:
            $A.test.assertEquals(1, realbody.getLength());
            $A.test.assertEquals("0:xyz,", realbody.get(0).get("v.value"));

            // Now, this is the more useful part:
            var refNode = realbody.getReferenceNode();
            $A.test.assertTrue(refNode !== undefined, "No reference node found!");
            $A.test.assertTruthy(refNode.parentElement, "Reference has no parent");
            $A.test.assertEquals("BODY", refNode.parentElement.tagName,
                    "Reference parent isn't right component");
        }]
    }
})
<commit_msg>Iteration test fix for IE<commit_after>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
({
    assertBodyComponentDefRef: function(cmp) {
        var value = cmp.find("iteration").getValue("v.body");
        $A.test.assertEquals("ArrayValue", value.toString());
        $A.test.assertEquals(1, value.getLength());
        value = value.get(0);
        $A.test.assertTrue(typeof value === "object");
        $A.test.assertEquals(undefined, value.auraType);
        $A.test.assertEquals(undefined, value.getDef);
        $A.test.assertEquals("markup://aura:expression", value.componentDef.descriptor);
    },

    /**
     * Iteration body is rendered by renderIf
     */
    testSanity:{
        attributes:{ items:"alpha,omega" },
        test:function(cmp){
            // Verify renderIf
            var value = cmp.find("if").getValue("v.body");
            $A.test.assertEquals("ArrayValue", value.toString());
            $A.test.assertEquals(1, value.getLength());
            value = value.get(0);
            var iteration = cmp.find("iteration");
            $A.test.assertEquals(iteration, value);

            this.assertBodyComponentDefRef(cmp);

            var realbody = iteration.getValue("v.realbody");
            $A.test.assertEquals("ArrayValue", realbody.toString());
            $A.test.assertEquals(2, realbody.getLength());
            value = realbody.get(0);
            $A.test.assertTrue(typeof value === "object");
            $A.test.assertEquals("Component", value.auraType);
            $A.test.assertEquals("markup://aura:expression", value.getDef().getDescriptor().getQualifiedName());
            $A.test.assertEquals("0:alpha,", value.get("v.value"));
            value = realbody.get(1);
            $A.test.assertTrue(typeof value === "object");
            $A.test.assertEquals("Component", value.auraType);
            $A.test.assertEquals("markup://aura:expression", value.getDef().getDescriptor().getQualifiedName());
            $A.test.assertEquals("1:omega,", value.get("v.value"));
        }
    },

    /**
     * Iteration body is not rendered by renderIf
     */
    testNotRendered:{
        attributes:{ showIteration:false, items:"alpha,omega" },
        test:function(cmp){
            // Verify renderIf
            var value = cmp.find("if").getValue("v.body");
            $A.test.assertEquals("ArrayValue", value.toString());
            $A.test.assertEquals(1, value.getLength());
            value = value.get(0);
            var iteration = cmp.find("iteration");
            $A.test.assertEquals(iteration, value);

            this.assertBodyComponentDefRef(cmp);

            var realbody = iteration.getValue("v.realbody");
            $A.test.assertEquals("ArrayValue", realbody.toString());
            $A.test.assertEquals(2, realbody.getLength());
            $A.test.assertFalse(iteration.isRendered());
            $A.test.assertTrue(undefined === iteration.getElements());

            value = realbody.get(0);
            $A.test.assertTrue(typeof value === "object");
            $A.test.assertEquals("Component", value.auraType);
            $A.test.assertEquals("markup://aura:expression", value.getDef().getDescriptor().getQualifiedName());
            $A.test.assertEquals("0:alpha,", value.get("v.value"));
            $A.test.assertFalse(value.isRendered());
            $A.test.assertTrue(undefined === value.getElements());
            value = realbody.get(1);
            $A.test.assertTrue(typeof value === "object");
            $A.test.assertEquals("Component", value.auraType);
            $A.test.assertEquals("markup://aura:expression", value.getDef().getDescriptor().getQualifiedName());
            $A.test.assertEquals("1:omega,", value.get("v.value"));
            $A.test.assertFalse(value.isRendered());
            $A.test.assertTrue(undefined === value.getElements());
        }
    },

    /**
     * Iteration is empty if items is empty
     */
    testItemsEmpty:{
        test:function(cmp){
            this.assertBodyComponentDefRef(cmp);
            var realbody = cmp.find("iteration").getValue("v.realbody");
            $A.test.assertEquals("ArrayValue", realbody.toString());
            $A.test.assertEquals(0, realbody.getLength());
        }
    },

    testStartAndEnd:{
        attributes:{ items:"a,b,c,d,e", start:2, end:3 },
        test:function(cmp){
            this.assertBodyComponentDefRef(cmp);
            var realbody = cmp.find("iteration").getValue("v.realbody");
            $A.test.assertEquals(1, realbody.getLength());
            value = realbody.get(0);
            $A.test.assertTrue(typeof value === "object");
            $A.test.assertEquals("2:c,", value.get("v.value"));
        }
    },

    /**
     * Iteration is empty if start greater than items length
     */
    testStartGreaterThanLength:{
        attributes:{ items:"a,b,c,d,e", start:99 },
        test:function(cmp){
            this.assertBodyComponentDefRef(cmp);
            var realbody = cmp.find("iteration").getValue("v.realbody");
            $A.test.assertEquals("ArrayValue", realbody.toString());
            $A.test.assertEquals(0, realbody.getLength());
        }
    },

    /**
     * Iteration is empty if start greater than end
     */
    testStartGreaterThanEnd:{
        attributes:{ items:"a,b,c,d,e", start:3, end:2 },
        test:function(cmp){
            this.assertBodyComponentDefRef(cmp);
            var realbody = cmp.find("iteration").getValue("v.realbody");
            $A.test.assertEquals("ArrayValue", realbody.toString());
            $A.test.assertEquals(0, realbody.getLength());
        }
    },

    /**
     * Iteration starts at start and contains remainder of list, without end
     */
    testStartWithoutEnd:{
        attributes:{ items:"a,b,c,d,e", start:3 },
        test:function(cmp){
            this.assertBodyComponentDefRef(cmp);
            var realbody = cmp.find("iteration").getValue("v.realbody");
            $A.test.assertEquals(2, realbody.getLength());
            value = realbody.get(0);
            $A.test.assertEquals("3:d,", value.get("v.value"));
            value = realbody.get(1);
            $A.test.assertEquals("4:e,", value.get("v.value"));
        }
    },

    /**
     * Iteration starts with first item and ends before end, without start
     */
    testEndWithoutStart:{
        attributes:{ items:"a,b,c,d,e", end:3 },
        test:function(cmp){
            this.assertBodyComponentDefRef(cmp);
            var realbody = cmp.find("iteration").getValue("v.realbody");
            $A.test.assertEquals(3, realbody.getLength());
            value = realbody.get(0);
            $A.test.assertEquals("0:a,", value.get("v.value"));
            value = realbody.get(1);
            $A.test.assertEquals("1:b,", value.get("v.value"));
            value = realbody.get(2);
            $A.test.assertEquals("2:c,", value.get("v.value"));
        }
    },

    /**
     * Iteration starts with first item and ends before end, without start
     */
    testStartNegative:{
        attributes:{ items:"delta,gamma", start:-3 },
        test:function(cmp){
            this.assertBodyComponentDefRef(cmp);
            var realbody = cmp.find("iteration").getValue("v.realbody");
            $A.test.assertEquals(2, realbody.getLength());
            value = realbody.get(0);
            $A.test.assertEquals("0:delta,", value.get("v.value"));
            value = realbody.get(1);
            $A.test.assertEquals("1:gamma,", value.get("v.value"));
        }
    },

    /**
     * Iteration with decimal start value is treated as integer
     */
    testStartDecimal:{
        attributes:{ items:"alpha,beta", start: 0.000001 },
        test:function(cmp){
            this.assertBodyComponentDefRef(cmp);
            var realbody = cmp.find("iteration").getValue("v.realbody");
            $A.test.assertEquals(2, realbody.getLength());
            value = realbody.get(0);
            $A.test.assertEquals("0:alpha,", value.get("v.value"));
            value = realbody.get(1);
            $A.test.assertEquals("1:beta,", value.get("v.value"));
        }
    },

    /** Iteration rerender stays stable */
    testEmptyAndFill:{
        attributes:{ items:"alpha,beta" },
        test:[function(cmp) {
            var items = cmp.getValue("v.items");
            items.remove(0);
        },
        function(cmp) {
            var items = cmp.getValue("v.items");
            items.remove(0);
        },
        function(cmp) {
            var items = cmp.getValue("v.items");
            items.push("xyz");
        },
        function(cmp) {
            var realbody = cmp.find("iteration").getValue("v.realbody");
            // This assertion isn't the big one; it doesn't show the render state.
            // But we do want to be sure it's right:
            $A.test.assertEquals(1, realbody.getLength());
            $A.test.assertEquals("0:xyz,", realbody.get(0).get("v.value"));

            // Now, this is the more useful part:
            var refNode = realbody.getReferenceNode();
            $A.test.assertTrue(refNode !== undefined, "No reference node found!");
            var parent;
            if ($A.util.isIE) {
                parent = refNode.parentNode;
            } else {
                parent = refNode.parentElement;
            }
            $A.test.assertTruthy(parent, "Reference has no parent");
            $A.test.assertEquals("BODY", parent.tagName,
                    "Reference parent isn't right component");
        }]
    }
})
<|endoftext|>