<commit_before>// fix problems with undefined Promise class
// http://stackoverflow.com/questions/32490328/gulp-autoprefixer-throwing-referenceerror-promise-is-not-defined
require('es6-promise').polyfill();

// Load plugins
var gulp = require('gulp'),
sass = require('gulp-sass'),
autoprefixer = require('gulp-autoprefixer'),
cssnano = require('gulp-cssnano'),
jshint = require('gulp-jshint'),
uglify = require('gulp-uglify'),
imagemin = require('gulp-imagemin'),
rename = require('gulp-rename'),
concat = require('gulp-concat'),
notify = require('gulp-notify'),
cache = require('gulp-cache'),
browsersync = require('browser-sync'),
sourcemaps = require('gulp-sourcemaps'),
del = require('del'),
gulpif = require('gulp-if'),
runSequence = require('run-sequence');

var PATHS = {
    sass: [
        'vendor/zurb/foundation/scss',
        'vendor/bower/motion-ui/src/',
        'vendor/bower/font-awesome/scss/'
    ],
    javascript: [
        'vendor/bower/jquery/dist/jquery.js',
        'vendor/bower/what-input/what-input.js',
        'vendor/zurb/foundation/js/foundation.core.js',
        'vendor/zurb/foundation/js/foundation.util.*.js',
        // Paths to individual JS components defined below
        'vendor/zurb/foundation/js/foundation.abide.js',
        'vendor/zurb/foundation/js/foundation.accordion.js',
        'vendor/zurb/foundation/js/foundation.accordionMenu.js',
        'vendor/zurb/foundation/js/foundation.drilldown.js',
        'vendor/zurb/foundation/js/foundation.dropdown.js',
        'vendor/zurb/foundation/js/foundation.dropdownMenu.js',
        'vendor/zurb/foundation/js/foundation.equalizer.js',
        'vendor/zurb/foundation/js/foundation.interchange.js',
        'vendor/zurb/foundation/js/foundation.magellan.js',
        'vendor/zurb/foundation/js/foundation.offcanvas.js',
        'vendor/zurb/foundation/js/foundation.orbit.js',
        'vendor/zurb/foundation/js/foundation.responsiveMenu.js',
        'vendor/zurb/foundation/js/foundation.responsiveToggle.js',
        'vendor/zurb/foundation/js/foundation.reveal.js',
        'vendor/zurb/foundation/js/foundation.slider.js',
        'vendor/zurb/foundation/js/foundation.sticky.js',
        'vendor/zurb/foundation/js/foundation.tabs.js',
        'vendor/zurb/foundation/js/foundation.toggler.js',
        'vendor/zurb/foundation/js/foundation.tooltip.js',
        // Yii2 scrips
        "vendor/yiisoft/yii2/assets/yii.js",
        "vendor/yiisoft/yii2/assets/yii.validation.js",
        "vendor/yiisoft/yii2/assets/yii.activeForm.js",
        // Custom scripts
        'js/**/!(custom).js',
        'js/custom.js'
    ]
};

var sassOptions = {
    errLogToConsole: true,
    outputStyle: 'expanded',
    includePaths: PATHS.sass
};

var autoprefixerOptions = {
    browsers: ['last 2 versions', '> 5%', 'Firefox ESR']
};

// Styles
gulp.task('styles', function() {
    return gulp.src('scss/all.scss')
    .pipe(sourcemaps.init())
    .pipe(sass(sassOptions).on('error', sass.logError))
    .pipe(autoprefixer(autoprefixerOptions))
    .pipe(sourcemaps.write('.', { sourceRoot: '../../scss/' }))
    .pipe(gulp.dest('web/css'))
    .pipe(gulpif('*.css', rename({ suffix: '.min' })))
    .pipe(gulpif('*.css', cssnano()))
    .pipe(gulpif('*.css', gulp.dest('web/css')))
    .pipe(gulpif('*.css', notify({ message: 'Styles task complete' })));
});

// Scripts
gulp.task('scripts', function() {
    return gulp.src(PATHS.javascript)
    //.pipe(jshint('.jshintrc'))
    //.pipe(jshint.reporter('default'))
    .pipe(sourcemaps.init())
    .pipe(concat('all.js'))
    .pipe(sourcemaps.write('.', { sourceRoot: '../../js/' }))
    .pipe(gulp.dest('web/js'))
    .pipe(gulpif('*.js', rename({ suffix: '.min' })))
    .pipe(gulpif('*.js', uglify()))
    .pipe(gulpif('*.js', gulp.dest('web/js')))
    .pipe(gulpif('*.js', notify({ message: 'Scripts task complete' })));
});

// Images
gulp.task('images', function() {
    return gulp.src('img/**/*')
    .pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
    .pipe(gulp.dest('web/img'))
    .pipe(notify({ message: 'Images task complete' }));
});

// Copy fonts
gulp.task('fonts', function() {
    return gulp.src([
        'vendor/bower/font-awesome/fonts/*'
    ])
    .pipe(gulp.dest('./web/fonts'));
});

// Clean
gulp.task('clean', function() {
    return del(['web/css/*', 'web/js/*', 'web/fonts/*']);
});

// Build the "web" folder by running all of the above tasks
gulp.task('build', function(callback) {
    runSequence('clean', ['styles', 'scripts', 'fonts'], callback);
});

// Watch
gulp.task('watch', function() {

    // Initialize Browsersync
    browsersync.init({
        proxy: "http://foundationtest.dev"
    });

    // Watch .scss files
    gulp.watch('scss/**/*.scss', ['styles']);

    // Watch .js files
    gulp.watch('js/**/*.js', ['scripts']);

    // Watch image files
    //gulp.watch('img/**/*', ['images']);

    // Watch any view files in 'views', reload on change
    gulp.watch(['views/**/*.php']).on('change', browsersync.reload);

    // Watch any files in 'web', reload on change
    gulp.watch(['web/js/*']).on('change', browsersync.reload);
    gulp.watch(['web/css/*']).on('change', browsersync.reload);
});

gulp.task('default', ['build', 'watch'], function() {});
<commit_msg>Path corrected to Zurb<commit_after>// fix problems with undefined Promise class
// http://stackoverflow.com/questions/32490328/gulp-autoprefixer-throwing-referenceerror-promise-is-not-defined
require('es6-promise').polyfill();

// Load plugins
var gulp = require('gulp'),
sass = require('gulp-sass'),
autoprefixer = require('gulp-autoprefixer'),
cssnano = require('gulp-cssnano'),
jshint = require('gulp-jshint'),
uglify = require('gulp-uglify'),
imagemin = require('gulp-imagemin'),
rename = require('gulp-rename'),
concat = require('gulp-concat'),
notify = require('gulp-notify'),
cache = require('gulp-cache'),
browsersync = require('browser-sync'),
sourcemaps = require('gulp-sourcemaps'),
del = require('del'),
gulpif = require('gulp-if'),
runSequence = require('run-sequence');

var PATHS = {
    sass: [
        'vendor/bower/foundation-sites/scss',
        'vendor/bower/motion-ui/src/',
        'vendor/bower/font-awesome/scss/'
    ],
    javascript: [
        'vendor/bower/jquery/dist/jquery.js',
        'vendor/bower/what-input/what-input.js',
        'vendor/bower/foundation-sites/js/foundation.core.js',
        'vendor/bower/foundation-sites/js/foundation.util.*.js',
        // Paths to individual JS components defined below
        'vendor/bower/foundation-sites/js/foundation.abide.js',
        'vendor/bower/foundation-sites/js/foundation.accordion.js',
        'vendor/bower/foundation-sites/js/foundation.accordionMenu.js',
        'vendor/bower/foundation-sites/js/foundation.drilldown.js',
        'vendor/bower/foundation-sites/js/foundation.dropdown.js',
        'vendor/bower/foundation-sites/js/foundation.dropdownMenu.js',
        'vendor/bower/foundation-sites/js/foundation.equalizer.js',
        'vendor/bower/foundation-sites/js/foundation.interchange.js',
        'vendor/bower/foundation-sites/js/foundation.magellan.js',
        'vendor/bower/foundation-sites/js/foundation.offcanvas.js',
        'vendor/bower/foundation-sites/js/foundation.orbit.js',
        'vendor/bower/foundation-sites/js/foundation.responsiveMenu.js',
        'vendor/bower/foundation-sites/js/foundation.responsiveToggle.js',
        'vendor/bower/foundation-sites/js/foundation.reveal.js',
        'vendor/bower/foundation-sites/js/foundation.slider.js',
        'vendor/bower/foundation-sites/js/foundation.sticky.js',
        'vendor/bower/foundation-sites/js/foundation.tabs.js',
        'vendor/bower/foundation-sites/js/foundation.toggler.js',
        'vendor/bower/foundation-sites/js/foundation.tooltip.js',
        // Yii2 scrips
        "vendor/yiisoft/yii2/assets/yii.js",
        "vendor/yiisoft/yii2/assets/yii.validation.js",
        "vendor/yiisoft/yii2/assets/yii.activeForm.js",
        // Custom scripts
        'js/**/!(custom).js',
        'js/custom.js'
    ]
};

var sassOptions = {
    errLogToConsole: true,
    outputStyle: 'expanded',
    includePaths: PATHS.sass
};

var autoprefixerOptions = {
    browsers: ['last 2 versions', '> 5%', 'Firefox ESR']
};

// Styles
gulp.task('styles', function() {
    return gulp.src('scss/all.scss')
    .pipe(sourcemaps.init())
    .pipe(sass(sassOptions).on('error', sass.logError))
    .pipe(autoprefixer(autoprefixerOptions))
    .pipe(sourcemaps.write('.', { sourceRoot: '../../scss/' }))
    .pipe(gulp.dest('web/css'))
    .pipe(gulpif('*.css', rename({ suffix: '.min' })))
    .pipe(gulpif('*.css', cssnano()))
    .pipe(gulpif('*.css', gulp.dest('web/css')))
    .pipe(gulpif('*.css', notify({ message: 'Styles task complete' })));
});

// Scripts
gulp.task('scripts', function() {
    return gulp.src(PATHS.javascript)
    //.pipe(jshint('.jshintrc'))
    //.pipe(jshint.reporter('default'))
    .pipe(sourcemaps.init())
    .pipe(concat('all.js'))
    .pipe(sourcemaps.write('.', { sourceRoot: '../../js/' }))
    .pipe(gulp.dest('web/js'))
    .pipe(gulpif('*.js', rename({ suffix: '.min' })))
    .pipe(gulpif('*.js', uglify()))
    .pipe(gulpif('*.js', gulp.dest('web/js')))
    .pipe(gulpif('*.js', notify({ message: 'Scripts task complete' })));
});

// Images
gulp.task('images', function() {
    return gulp.src('img/**/*')
    .pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
    .pipe(gulp.dest('web/img'))
    .pipe(notify({ message: 'Images task complete' }));
});

// Copy fonts
gulp.task('fonts', function() {
    return gulp.src([
        'vendor/bower/font-awesome/fonts/*'
    ])
    .pipe(gulp.dest('./web/fonts'));
});

// Clean
gulp.task('clean', function() {
    return del(['web/css/*', 'web/js/*', 'web/fonts/*']);
});

// Build the "web" folder by running all of the above tasks
gulp.task('build', function(callback) {
    runSequence('clean', ['styles', 'scripts', 'fonts'], callback);
});

// Watch
gulp.task('watch', function() {

    // Initialize Browsersync
    browsersync.init({
        proxy: "http://foundationtest.dev"
    });

    // Watch .scss files
    gulp.watch('scss/**/*.scss', ['styles']);

    // Watch .js files
    gulp.watch('js/**/*.js', ['scripts']);

    // Watch image files
    //gulp.watch('img/**/*', ['images']);

    // Watch any view files in 'views', reload on change
    gulp.watch(['views/**/*.php']).on('change', browsersync.reload);

    // Watch any files in 'web', reload on change
    gulp.watch(['web/js/*']).on('change', browsersync.reload);
    gulp.watch(['web/css/*']).on('change', browsersync.reload);
});

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


<commit_before>import React, { Component } from 'react';

import {
  StyleSheet,
  Text,
  View,
  ListView,
  TouchableHighlight,
} from 'react-native';

import Search from './search.js'

class Home extends Component{
  constructor(props) {
    super(props);
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      dataSource: ds.cloneWithRows([
        'Bilbo', 'Aragorn', 'Frodo', 'Legolas', 'Saruman', 'Elrond', 'Smeagol', 'Gimli', 'Bilbo', 'Aragorn', 'Frodo', 'Legolas', 'Saruman', 'Elrond', 'Smeagol', 'Gimli', 'Bilbo', 'Aragorn', 'Frodo', 'Legolas', 'Saruman', 'Elrond', 'Smeagol', 'Gimli','Bilbo', 'Aragorn', 'Frodo', 'Legolas', 'Saruman', 'Elrond', 'Smeagol', 'Gimli', 'Bilbo', 'Aragorn', 'Frodo', 'Legolas', 'Saruman', 'Elrond', 'Smeagol', 'Gimli', 'Bilbo', 'Aragorn', 'Frodo', 'Legolas', 'Saruman', 'Elrond', 'Smeagol', 'Gimli'
      ])
    };
  }
  _onPressLogin() {
  }

  _onPressRegister() {
  }

  _onPressStory() {
    // this.props.navigator.push({
    //   title: 'Story',
    //   component: Story
    // })
  }

  featuredStory() {
      return(
        <View style={{backgroundColor: 'lightgrey'}}>
        <Text>"My day today was very interesting. First I woke up late and I couldn't find my clean clothes and my mom......"</Text>
        <Text style={{color: 'purple', textAlign: 'right'}}>-Ahmed</Text>
        </View>
      )
  }

  fetchUserData() {
    fetch('http:///simulnos.herokuapp.com/api/users').then(function(response){
      return response.json()
    })
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.title}>HOME YA</Text>
        <TouchableHighlight onPress={ () => this._onPressLogin()}><Text style={styles.nav}>Login</Text></TouchableHighlight>
        <TouchableHighlight onPress={ () => this._onPressRegister()}><Text style={styles.nav}>Register</Text></TouchableHighlight>
        <Search />
        <ListView
          style={styles.listItems}
          dataSource={this.state.dataSource}
          renderRow={(rowData) => <TouchableHighlight onPress={ () => this._onPressStory()}><Text style={
             styles.listText}>{rowData}</Text></TouchableHighlight>}
          renderHeader={ () => this.featuredStory() } />
      </View>
    )
  }
};

var styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    backgroundColor: '#27c2dc',
    paddingTop: 80,
  },
  title: {
    flex: .5,
    backgroundColor: 'white',
    fontSize: 20,
    textAlign: 'center',
  },
  listItems: {
    flex: 9,
    backgroundColor: 'powderblue',
  },
  listText: {
    color: '#32161F',
    textAlign: 'center',
  },
  nav: {
    flex: .25,
    alignItems: 'center',
    color: 'white',
    fontFamily: 'Farah',
    backgroundColor: '#FFB30F',
    textAlign: 'center',
  }
});

module.exports = Home;
<commit_msg>Add login nav functionality to Home<commit_after>import React, { Component } from 'react';

import {
  StyleSheet,
  Text,
  View,
  ListView,
  TouchableHighlight,
} from 'react-native';

import Search from './search'
import Login from './login'

class Home extends Component{
  constructor(props) {
    super(props);
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      dataSource: ds.cloneWithRows([
        'Bilbo', 'Aragorn', 'Frodo', 'Legolas', 'Saruman', 'Elrond', 'Smeagol', 'Gimli', 'Bilbo', 'Aragorn', 'Frodo', 'Legolas', 'Saruman', 'Elrond', 'Smeagol', 'Gimli', 'Bilbo', 'Aragorn', 'Frodo', 'Legolas', 'Saruman', 'Elrond', 'Smeagol', 'Gimli','Bilbo', 'Aragorn', 'Frodo', 'Legolas', 'Saruman', 'Elrond', 'Smeagol', 'Gimli', 'Bilbo', 'Aragorn', 'Frodo', 'Legolas', 'Saruman', 'Elrond', 'Smeagol', 'Gimli', 'Bilbo', 'Aragorn', 'Frodo', 'Legolas', 'Saruman', 'Elrond', 'Smeagol', 'Gimli'
      ])
    };
  }
  _onPressLogin() {
    this.props.navigator.push({
      title: 'Login',
      component: Login
    })
  }

  _onPressRegister() {
  }

  _onPressStory() {
    // this.props.navigator.push({
    //   title: 'Story',
    //   component: Story
    // })
  }

  featuredStory() {
      return(
        <View style={{backgroundColor: 'lightgrey'}}>
        <Text>"My day today was very interesting. First I woke up late and I couldn't find my clean clothes and my mom......"</Text>
        <Text style={{color: 'purple', textAlign: 'right'}}>-Ahmed</Text>
        </View>
      )
  }

  fetchUserData() {
    fetch('http:///simulnos.herokuapp.com/api/users').then(function(response){
      return response.json()
    })
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.title}>HOME YA</Text>
        <TouchableHighlight onPress={ () => this._onPressLogin()}><Text style={styles.nav}>Login</Text></TouchableHighlight>
        <TouchableHighlight onPress={ () => this._onPressRegister()}><Text style={styles.nav}>Register</Text></TouchableHighlight>
        <Search />
        <ListView
          style={styles.listItems}
          dataSource={this.state.dataSource}
          renderRow={(rowData) => <TouchableHighlight onPress={ () => this._onPressStory()}><Text style={
             styles.listText}>{rowData}</Text></TouchableHighlight>}
          renderHeader={ () => this.featuredStory() } />
      </View>
    )
  }
};

var styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    backgroundColor: '#27c2dc',
    paddingTop: 80,
  },
  title: {
    flex: .5,
    backgroundColor: 'white',
    fontSize: 20,
    textAlign: 'center',
  },
  listItems: {
    flex: 9,
    backgroundColor: 'powderblue',
  },
  listText: {
    color: '#32161F',
    textAlign: 'center',
  },
  nav: {
    flex: .25,
    alignItems: 'center',
    color: 'white',
    fontFamily: 'Farah',
    backgroundColor: '#FFB30F',
    textAlign: 'center',
  }
});

module.exports = Home;
<|endoftext|>


<commit_before>(function (window, document, undefined) {

// exit if we already have a script in place doing this task
if (window.jsbinified !== undefined) return;

/*!
  * domready (c) Dustin Diaz 2012 - License MIT
  */
!function (name, definition) {
  if (typeof module != 'undefined') module.exports = definition()
  else if (typeof define == 'function' && typeof define.amd == 'object') define(definition)
  else this[name] = definition()
}('domready', function (ready) {

  var fns = [], fn, f = false
    , doc = document
    , testEl = doc.documentElement
    , hack = testEl.doScroll
    , domContentLoaded = 'DOMContentLoaded'
    , addEventListener = 'addEventListener'
    , onreadystatechange = 'onreadystatechange'
    , readyState = 'readyState'
    , loaded = /^loade|c/.test(doc[readyState])

  function flush(f) {
    loaded = 1
    while (f = fns.shift()) f()
  }

  doc[addEventListener] && doc[addEventListener](domContentLoaded, fn = function () {
    doc.removeEventListener(domContentLoaded, fn, f)
    flush()
  }, f)

  hack && doc.attachEvent(onreadystatechange, fn = function () {
    if (/^c/.test(doc[readyState])) {
      doc.detachEvent(onreadystatechange, fn)
      flush()
    }
  })

  return (ready = hack ?
    function (fn) {
      self != top ?
        loaded ? fn() : fns.push(fn) :
        function () {
          try {
            testEl.doScroll('left')
          } catch (e) {
            return setTimeout(function() { ready(fn) }, 50)
          }
          fn()
        }()
    } :
    function (fn) {
      loaded ? fn() : fns.push(fn)
    })
});

function getQuery(querystring) {
  var query = {};

  querystring.replace(/\b([^&=]*)=([^&=]*)\b/g, function (m, a, d) {
    if (typeof query[a] != 'undefined') {
      query[a] += ',' + d;
    } else {
      query[a] = d;
    }
  });

  return query;
}

// ---- here begins the jsbin embed - based on the embedding doc: https://github.com/remy/jsbin/blob/master/docs/embedding.md

var innerText = document.createElement('i').innerText === undefined ? 'textContent' : 'innerText';

// 1. find all links with class=jsbin
function getLinks() {
  var links = [], alllinks, i = 0, length;
  alllinks = document.getElementsByTagName('a');
  length = alllinks.length;
  for (; i < length; i++) {
    if ((' ' + alllinks[i].className).indexOf(' jsbin-') !== -1) {
      links.push(alllinks[i]);
    }
  }

  return links;
}

function findCodeInParent(element) {
  var match = element;

  while (match = match.previousSibling) {
    if (match.nodeName === 'PRE') {
      break;
    }
    if (match.getElementsByTagName) {
      match = match.getElementsByTagName('pre');
      if (match.length) {
        match = match[0]; // only grabs the first
        break;
      }
    }
  }

  if (match) return match;

  match = element.parentNode.getElementsByTagName('pre');

  if (!match.length) {
    if (element.parentNode) {
      return findCodeInParent(element.parentNode);
    } else {
      return null;
    }
  }

  return match[0];
}

function findCode(link) {
  var rel = link.rel,
      query = link.search.substring(1),
      element,
      code,
      panels = [];

  if (rel && (element = document.getElementById(rel.substring(1)))) {
    code = element[innerText];
  // else - try to support multiple targets for each panel...
  // } else if (query.indexOf('=') !== -1) {
  //   // assumes one of the panels points to an ID
  //   query.replace(/([^,=]*)=([^,=]*)/g, function (all, key, value) {
  //     code = document.getElementById(value.substring(1))[innerText];

  //   });
  } else {
    // go looking through it's parents
    element = findCodeInParent(link);
    if (element) {
      code = element[innerText];
    }
  }

  return code;
}

function detectLanguage(code) {
  var htmlcount = (code.split("<").length - 1),
      csscount = (code.split("{").length - 1),
      jscount = (code.split(".").length - 1);

  if (htmlcount > csscount && htmlcount > jscount) {
    return 'html';
  } else if (csscount > htmlcount && csscount > jscount) {
    return 'css';
  } else {
    return 'javascript';
  }
}

function scoop(link) {
  var code = findCode(link),
      language = detectLanguage(code),
      query = link.search.substring(1);

  if (language === 'html' && code.toLowerCase().indexOf('<html') === -1) {
    // assume this is an HTML fragment - so try to insert in the %code% position
    language = 'code';
  }

  if (query.indexOf(language) === -1) {
    query += ',' + language + '=' + encodeURIComponent(code);
  } else {
    query = query.replace(language, language + '=' + encodeURIComponent(code));
  }

  link.search = '?' + query;
}

function embed(link) {
  var iframe = document.createElement('iframe'),
      resize = document.createElement('div'),
      url = link.href.replace(/edit/, 'embed');
  iframe.src = url;
  iframe._src = url; // support for google slide embed
  iframe.className = link.className; // inherit all the classes from the link
  iframe.id = link.id; // also inherit, giving more style control to the user
  iframe.style.border = '1px solid #aaa';

  var query = getQuery(link.search);
  iframe.style.width = query.width || '100%';
  iframe.style.minHeight = query.height || '300px';
  if (query.height) {
    iframe.style.maxHeight = query.height;
  }
  link.parentNode.replaceChild(iframe, link);

  var onmessage = function (event) {
    event || (event = window.event);
    iframe.style.height = event.data.height + 'px';
  };

  if (window.addEventListener) {
    window.addEventListener('message', onmessage, false);
  } else {
    window.attachEvent('onmessage', onmessage);
  }
}

var useDOMReady = true,
    scripts = document.getElementsByTagName('script'),
    last = scripts[scripts.length - 1],
    link;

// this supports early embeding - probably only applies to Google's slides.js
if (last.nodeName === 'SCRIPT') { // then it's us
  link = last.previousSibling;
  if (link.nodeName === 'A' && (' ' + link.className + ' ').indexOf(' jsbin-embed ') !== -1) {
    // we have a winner
    useDOMReady = false;
    link.className = link.className.replace(/jsbin\-embed/, '');
    embed(link);
  }
}

if (useDOMReady) {
  window.jsbinified = true;

  domready(function () {
    // 2. process link based on subclass - jsbin-scoop to start with
    var links = getLinks(),
        i = 0,
        length = links.length,
        className = '';

    for (; i < length; i++) {
      className = ' ' + links[i].className + ' ';
      if (className.indexOf(' jsbin-scoop ') !== -1) {
        scoop(links[i]);
      } else if (className.indexOf(' jsbin-embed ') !== -1) {
        embed(links[i]);
      }
    }
  });
}
}(this, document));<commit_msg>Fixed getQuery<commit_after>(function (window, document, undefined) {

// exit if we already have a script in place doing this task
if (window.jsbinified !== undefined) return;

/*!
  * domready (c) Dustin Diaz 2012 - License MIT
  */
!function (name, definition) {
  if (typeof module != 'undefined') module.exports = definition()
  else if (typeof define == 'function' && typeof define.amd == 'object') define(definition)
  else this[name] = definition()
}('domready', function (ready) {

  var fns = [], fn, f = false
    , doc = document
    , testEl = doc.documentElement
    , hack = testEl.doScroll
    , domContentLoaded = 'DOMContentLoaded'
    , addEventListener = 'addEventListener'
    , onreadystatechange = 'onreadystatechange'
    , readyState = 'readyState'
    , loaded = /^loade|c/.test(doc[readyState])

  function flush(f) {
    loaded = 1
    while (f = fns.shift()) f()
  }

  doc[addEventListener] && doc[addEventListener](domContentLoaded, fn = function () {
    doc.removeEventListener(domContentLoaded, fn, f)
    flush()
  }, f)

  hack && doc.attachEvent(onreadystatechange, fn = function () {
    if (/^c/.test(doc[readyState])) {
      doc.detachEvent(onreadystatechange, fn)
      flush()
    }
  })

  return (ready = hack ?
    function (fn) {
      self != top ?
        loaded ? fn() : fns.push(fn) :
        function () {
          try {
            testEl.doScroll('left')
          } catch (e) {
            return setTimeout(function() { ready(fn) }, 50)
          }
          fn()
        }()
    } :
    function (fn) {
      loaded ? fn() : fns.push(fn)
    })
});

function getQuery(querystring) {
  var query = {};

  var pairs = querystring.split('&'),
      length = pairs.length,
      keyval = [],
      i = 0;

  for (; i < length; i++) {
    keyval = pairs[i].split('=', 2);
    try {
      keyval[0] = decodeURIComponent(keyval[0]); // key
      keyval[1] = decodeURIComponent(keyval[1]); // value
    } catch (e) {}

    if (query[keyval[0]] === undefined) {
      query[keyval[0]] = keyval[1];
    } else {
      query[keyval[0]] += ',' + keyval[1];
    }
  }

  return query;
}

// ---- here begins the jsbin embed - based on the embedding doc: https://github.com/remy/jsbin/blob/master/docs/embedding.md

var innerText = document.createElement('i').innerText === undefined ? 'textContent' : 'innerText';

// 1. find all links with class=jsbin
function getLinks() {
  var links = [], alllinks, i = 0, length;
  alllinks = document.getElementsByTagName('a');
  length = alllinks.length;
  for (; i < length; i++) {
    if ((' ' + alllinks[i].className).indexOf(' jsbin-') !== -1) {
      links.push(alllinks[i]);
    }
  }

  return links;
}

function findCodeInParent(element) {
  var match = element;

  while (match = match.previousSibling) {
    if (match.nodeName === 'PRE') {
      break;
    }
    if (match.getElementsByTagName) {
      match = match.getElementsByTagName('pre');
      if (match.length) {
        match = match[0]; // only grabs the first
        break;
      }
    }
  }

  if (match) return match;

  match = element.parentNode.getElementsByTagName('pre');

  if (!match.length) {
    if (element.parentNode) {
      return findCodeInParent(element.parentNode);
    } else {
      return null;
    }
  }

  return match[0];
}

function findCode(link) {
  var rel = link.rel,
      query = link.search.substring(1),
      element,
      code,
      panels = [];

  if (rel && (element = document.getElementById(rel.substring(1)))) {
    code = element[innerText];
  // else - try to support multiple targets for each panel...
  // } else if (query.indexOf('=') !== -1) {
  //   // assumes one of the panels points to an ID
  //   query.replace(/([^,=]*)=([^,=]*)/g, function (all, key, value) {
  //     code = document.getElementById(value.substring(1))[innerText];

  //   });
  } else {
    // go looking through it's parents
    element = findCodeInParent(link);
    if (element) {
      code = element[innerText];
    }
  }

  return code;
}

function detectLanguage(code) {
  var htmlcount = (code.split("<").length - 1),
      csscount = (code.split("{").length - 1),
      jscount = (code.split(".").length - 1);

  if (htmlcount > csscount && htmlcount > jscount) {
    return 'html';
  } else if (csscount > htmlcount && csscount > jscount) {
    return 'css';
  } else {
    return 'javascript';
  }
}

function scoop(link) {
  var code = findCode(link),
      language = detectLanguage(code),
      query = link.search.substring(1);

  if (language === 'html' && code.toLowerCase().indexOf('<html') === -1) {
    // assume this is an HTML fragment - so try to insert in the %code% position
    language = 'code';
  }

  if (query.indexOf(language) === -1) {
    query += ',' + language + '=' + encodeURIComponent(code);
  } else {
    query = query.replace(language, language + '=' + encodeURIComponent(code));
  }

  link.search = '?' + query;
}

function embed(link) {
  var iframe = document.createElement('iframe'),
      resize = document.createElement('div'),
      url = link.href.replace(/edit/, 'embed');
  iframe.src = url;
  iframe._src = url; // support for google slide embed
  iframe.className = link.className; // inherit all the classes from the link
  iframe.id = link.id; // also inherit, giving more style control to the user
  iframe.style.border = '1px solid #aaa';

  var query = getQuery(link.search);
  iframe.style.width = query.width || '100%';
  iframe.style.minHeight = query.height || '300px';
  if (query.height) {
    iframe.style.maxHeight = query.height;
  }
  link.parentNode.replaceChild(iframe, link);

  var onmessage = function (event) {
    event || (event = window.event);
    iframe.style.height = event.data.height + 'px';
  };

  if (window.addEventListener) {
    window.addEventListener('message', onmessage, false);
  } else {
    window.attachEvent('onmessage', onmessage);
  }
}

var useDOMReady = true,
    scripts = document.getElementsByTagName('script'),
    last = scripts[scripts.length - 1],
    link;

// this supports early embeding - probably only applies to Google's slides.js
if (last.nodeName === 'SCRIPT') { // then it's us
  link = last.previousSibling;
  if (link.nodeName === 'A' && (' ' + link.className + ' ').indexOf(' jsbin-embed ') !== -1) {
    // we have a winner
    useDOMReady = false;
    link.className = link.className.replace(/jsbin\-embed/, '');
    embed(link);
  }
}

if (useDOMReady) {
  window.jsbinified = true;

  domready(function () {
    // 2. process link based on subclass - jsbin-scoop to start with
    var links = getLinks(),
        i = 0,
        length = links.length,
        className = '';

    for (; i < length; i++) {
      className = ' ' + links[i].className + ' ';
      if (className.indexOf(' jsbin-scoop ') !== -1) {
        scoop(links[i]);
      } else if (className.indexOf(' jsbin-embed ') !== -1) {
        embed(links[i]);
      }
    }
  });
}
}(this, document));<|endoftext|>


<commit_before>export default (connection, Sequelize) => {
  const Message = connection.define('message', {
    messageId: {
      type: Sequelize.UUID,
      defaultValue: Sequelize.UUIDV4,
      primaryKey: true
    },
    inGroup: {
      type: Sequelize.UUID,
      allowNull: false
    },
    author: {
      type: Sequelize.UUID,
      allowNull: false
    },
    body: {
      type: Sequelize.TEXT,
      allowNull: false,
      unique: true
    },
    priority: {
      type: Sequelize.ENUM,
      values: ['normal', 'urgent', 'critical'],
      allowNull: false
    }
  }, {
    paranoid: true
  });
  return Message;
};
<commit_msg>Add messages model<commit_after>export default (connection, Sequelize) => {
  const Message = connection.define('message', {
    messageId: {
      type: Sequelize.UUID,
      defaultValue: Sequelize.UUIDV4,
      primaryKey: true
    },
    inGroup: {
      type: Sequelize.UUID,
      allowNull: false
    },
    author: {
      type: Sequelize.UUID,
      allowNull: false
    },
    body: {
      type: Sequelize.TEXT,
      allowNull: false
    },
    priority: {
      type: Sequelize.ENUM,
      values: ['normal', 'urgent', 'critical'],
      allowNull: false
    }
  }, {
    paranoid: true
  });
  return Message;
};
<|endoftext|>


<commit_before>/*
===============================================================================

    Class defines UI: HUD (head-up display) with player stats and menu GUI.

===============================================================================
*/
function UI() {
    if ( !(this instanceof UI) ) return new UI();

    this.camera = new THREE.OrthographicCamera( DOA.Settings.width  / -2, DOA.Settings.width  /  2,
                                                DOA.Settings.height /  2, DOA.Settings.height / -2,
                                                DOA.Settings.minView, DOA.Settings.maxView );
    /*
     * If camera rotation on Y is 0, not PI radian, all objects visible by
     * camera must have negative Z coordinates. In this case, the backside
     * of the object is visible only, and Material.side should be set to
     * THREE.DoubleSide, so the object can be drawn.
     */
    this.camera.rotateY( Math.PI );

    this.scene = new THREE.Scene();

    this.menu = null;
}

/*
================
init
    Creates objects of user interface.
================
*/
UI.prototype.init = function () {
    // Interface

    // Menu
    this.menu = new dat.GUI();
    this.menu.domElement.style.display = 'none';
    this.buildSettingsMenu();
};

/*
================
updateSize
    Updates camera size and projection in accordance with window size.
================
*/
UI.prototype.updateSize = function () {
    this.camera.left   = DOA.Settings.width  / - 2;
    this.camera.right  = DOA.Settings.width  /   2;
    this.camera.top    = DOA.Settings.height /   2;
    this.camera.bottom = DOA.Settings.height / - 2;
    this.camera.updateProjectionMatrix();
};

/*
================
updateHudSize
    Updates HUD elements texture size.
================
*/
UI.prototype.updateHud = function () {
};

/*
================
clearMenu
    Removes all elements from the menu recursively.
================
*/
UI.prototype.clearMenu = function ( menu ) {
    menu = menu || this.menu;
    var k;

    for ( k in menu.__controllers ) {
        menu.remove( menu.__controllers[ k ] );
        delete menu.__controllers[ k ];
        delete menu.__listening[ k ];
    }

    menu.__controllers = [];
    menu.__listening = [];

    for ( k in menu.__folders ) {
        UI.prototype.clearMenu( menu.__folders[ k ] );
        menu.__folders[ k ].domElement.parentNode.remove();
        delete menu.__folders[ k ];
    }
};

/*
================
resetMenu
    Resets menu values to the remembered ones.
================
*/
UI.prototype.resetMenu = function () {
    try {
        this.menu.revert();
    } catch ( ex ) {
        // Cannot read property 'selectedIndex' of undefined
    }
};

/*
================
buildSettingsMenu
    Creates new set of controllers, based on DOA.Settings.
================
*/
UI.prototype.buildSettingsMenu = function () {
    this.clearMenu();
    var folder = this.menu.addFolder( 'Common' );
    folder.add( DOA.Settings, 'fps', [ 30, 60 ] ).name( 'fps counter' ).listen();
    folder.addColor( DOA.Settings.colors, 'mesh' ).name( 'blank color' ).listen();
    folder.open();

    folder = this.menu.addFolder( 'Graphics' );
    folder.add( DOA.Settings, 'minView', 0.1, 1.0 ).step( 0.1 ).name( 'min view' ).listen();
    folder.add( DOA.Settings, 'maxView', 100, 9000 ).step( 100 ).name( 'max view' ).listen();
    folder.add( DOA.Settings, 'fov', 30, 120 ).step( 15 ).name( 'filed of view' ).listen();
    folder.add( DOA.Settings, 'anisotropy', 1, 16 ).step( 1 ).name( 'anisotropy' ).listen();
    folder.open();

    folder = this.menu.addFolder( 'Player' );
    folder.add( DOA.Settings, 'mouseSensitivity', 0.05, 0.5 ).step( 0.05 ).name( 'mouse speed' ).listen();
    folder.add( DOA.Settings, 'hudSize', { normal : 32, big : 64, large : 128 } ).name( 'HUD size' ).listen();
    folder.add( DOA.Settings, 'hudOpacity', 0.0, 1.0 ).step( 0.01 ).name( 'HUD opacity' ).listen();
    folder.open();

    this.menu.add( DOA.UI, 'resetMenu' ).name( 'Reset' );
    this.menu.add( DOA.Settings, 'quickSave' ).name( 'Save' );
    this.menu.add( DOA.Settings, 'quickLoad' ).name( 'Load' );
};

/*
---------------------------------------------------------------------------
DOA
---------------------------------------------------------------------------
*/
DOA.UI = new UI();
<commit_msg>Update code style.<commit_after>/*
===============================================================================

    Class defines UI: HUD (head-up display) with player stats and menu GUI.

===============================================================================
*/
function UI() {
    if ( !(this instanceof UI) ) return new UI();

    this.camera = new THREE.OrthographicCamera( DOA.Settings.width  / -2, DOA.Settings.width  /  2,
                                                DOA.Settings.height /  2, DOA.Settings.height / -2,
                                                DOA.Settings.minView, DOA.Settings.maxView );
    /*
     * If camera rotation on Y is 0, not PI radian, all objects visible by
     * camera must have negative Z coordinates. In this case, the backside
     * of the object is visible only, and Material.side should be set to
     * THREE.DoubleSide, so the object can be drawn.
     */
    this.camera.rotateY( Math.PI );

    this.scene = new THREE.Scene();

    this.menu = null;
}

/*
================
init
    Creates objects of user interface.
================
*/
UI.prototype.init = function () {
    // Interface

    // Menu
    this.menu = new dat.GUI();
    this.menu.domElement.style.display = 'none';
    this.buildSettingsMenu();
};

/*
================
updateSize
    Updates camera size and projection in accordance with window size.
================
*/
UI.prototype.updateSize = function () {
    this.camera.left   = DOA.Settings.width  / -2;
    this.camera.right  = DOA.Settings.width  /  2;
    this.camera.top    = DOA.Settings.height /  2;
    this.camera.bottom = DOA.Settings.height / -2;
    this.camera.updateProjectionMatrix();
};

/*
================
updateHudSize
    Updates HUD elements texture size.
================
*/
UI.prototype.updateHud = function () {
};

/*
================
clearMenu
    Removes all elements from the menu recursively.
================
*/
UI.prototype.clearMenu = function ( menu ) {
    menu = menu || this.menu;
    var k;

    for ( k in menu.__controllers ) {
        menu.remove( menu.__controllers[ k ] );
        delete menu.__controllers[ k ];
        delete menu.__listening[ k ];
    }

    menu.__controllers = [];
    menu.__listening = [];

    for ( k in menu.__folders ) {
        UI.prototype.clearMenu( menu.__folders[ k ] );
        menu.__folders[ k ].domElement.parentNode.remove();
        delete menu.__folders[ k ];
    }
};

/*
================
resetMenu
    Resets menu values to the remembered ones.
================
*/
UI.prototype.resetMenu = function () {
    try {
        this.menu.revert();
    } catch ( ex ) {
        // Cannot read property 'selectedIndex' of undefined
    }
};

/*
================
buildSettingsMenu
    Creates new set of controllers, based on DOA.Settings.
================
*/
UI.prototype.buildSettingsMenu = function () {
    this.clearMenu();
    var folder = this.menu.addFolder( 'Common' );
    folder.add( DOA.Settings, 'fps', [ 30, 60 ] ).name( 'fps counter' ).listen();
    folder.addColor( DOA.Settings.colors, 'mesh' ).name( 'blank color' ).listen();
    folder.open();

    folder = this.menu.addFolder( 'Graphics' );
    folder.add( DOA.Settings, 'minView', 0.1, 1.0 ).step( 0.1 ).name( 'min view' ).listen();
    folder.add( DOA.Settings, 'maxView', 100, 9000 ).step( 100 ).name( 'max view' ).listen();
    folder.add( DOA.Settings, 'fov', 30, 120 ).step( 15 ).name( 'filed of view' ).listen();
    folder.add( DOA.Settings, 'anisotropy', 1, 16 ).step( 1 ).name( 'anisotropy' ).listen();
    folder.open();

    folder = this.menu.addFolder( 'Player' );
    folder.add( DOA.Settings, 'mouseSensitivity', 0.05, 0.5 ).step( 0.05 ).name( 'mouse speed' ).listen();
    folder.add( DOA.Settings, 'hudSize', { normal : 32, big : 64, large : 128 } ).name( 'HUD size' ).listen();
    folder.add( DOA.Settings, 'hudOpacity', 0.0, 1.0 ).step( 0.01 ).name( 'HUD opacity' ).listen();
    folder.open();

    this.menu.add( DOA.UI, 'resetMenu' ).name( 'Reset' );
    this.menu.add( DOA.Settings, 'quickSave' ).name( 'Save' );
    this.menu.add( DOA.Settings, 'quickLoad' ).name( 'Load' );
};

/*
---------------------------------------------------------------------------
DOA
---------------------------------------------------------------------------
*/
DOA.UI = new UI();
<|endoftext|>


<commit_before>/**
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you 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.
*/

/* jshint node:true, bitwise:true, undef:true, trailing:true, quotmark:true,
          indent:4, unused:vars, latedef:nofunc,
          unused:false, expr:true
*/

var platform_modules   = require('./platforms'),
    path               = require('path'),
    through            = require('through2'),
    config_changes     = require('./util/config-changes'),
    xml_helpers        = require('../util/xml-helpers'),
    wp8                = require('./platforms/wp8'),
    windows            = require('./platforms/windows'),
    common             = require('./platforms/common'),
    fs                 = require('fs'),
    childProcess       = require('child_process'),
    shell              = require('shelljs'),
    util               = require('util'),
    events             = require('../events'),
    plugman            = require('./plugman'),
    et                 = require('elementtree'),
    prepareNamespace   = require('./util/prepare-namespace'),
    bundle             = require('cordova-js/tasks/lib/bundle-browserify'),
    requireTr          = require('cordova-js/tasks/lib/require-tr'),
    writeLicenseHeader = require('cordova-js/tasks/lib/write-license-header'),
    Q                  = require('q'),
    computeCommitId    = require('cordova-js/tasks/lib/compute-commit-id');

function uninstallQueuedPlugins(platform_json, wwwDir) {
    // Check if there are any plugins queued for uninstallation, and if so, remove any of their plugin web assets loaded in
    // via <js-module> elements
    var plugins_to_uninstall = platform_json.prepare_queue.uninstalled;
    if (plugins_to_uninstall && plugins_to_uninstall.length) {
        var plugins_www = path.join(wwwDir, 'plugins');
        if (fs.existsSync(plugins_www)) {
            plugins_to_uninstall.forEach(function(plug) {
                var id = plug.id;
                var plugin_modules = path.join(plugins_www, id);
                if (fs.existsSync(plugin_modules)) {
                    events.emit('verbose', 'Removing plugins directory from www "'+plugin_modules+'"');
                    shell.rm('-rf', plugin_modules);
                }
            });
        }
    }
}

function generateFinalBundle(platform, libraryRelease, outReleaseFile, commitId, platformVersion) {

    var deferred = Q.defer();
    var outReleaseFileStream = fs.createWriteStream(outReleaseFile);
    var time = new Date().valueOf();
    var symbolList = null;

    var addSymbolList = through.obj(function(row, enc, next) {
        if(symbolList === null) {
            symbolList = requireTr.getModules();
            this.push(util.format('var symbolList = %s;\n%s\n', JSON.stringify(symbolList), row));
        } else {
            this.push(row);
        }
        next();
    });

    libraryRelease.pipeline.get('wrap').push(addSymbolList);

    writeLicenseHeader(outReleaseFileStream, platform, commitId, platformVersion);

    var releaseBundle = libraryRelease.bundle();

    releaseBundle.pipe(outReleaseFileStream);

    outReleaseFileStream.on('finish', function() {
        var newtime = new Date().valueOf() - time;
        plugman.emit('verbose', 'generated cordova.' + platform + '.js @ ' + commitId + ' in ' + newtime + 'ms');
        deferred.resolve();
        // TODO clean up all the *.browserify files
    });

    outReleaseFileStream.on('error', function(err) {
        var newtime = new Date().valueOf() - time;
        events.emit('log', 'error while generating cordova.js');
        deferred.reject();
    });
    return deferred.promise;
}

function computeCommitIdSync() {
    var deferred = Q.defer();
    computeCommitId(function(cId){
        deferred.resolve(cId);
    });
    return deferred.promise;
}

function getPlatformVersion(cId, project_dir) {
    var deferred = Q.defer();
    //run version script for each platform to get platformVersion
    var versionPath = path.join(project_dir, '/cordova/version');
    childProcess.exec(versionPath, function(err, stdout, stderr) {
        if (err) {
            events.emit('log', 'Error running platform version script');
            events.emit('log', err);
            deferred.resolve('N/A');
        } else {
            deferred.resolve(stdout.trim());
        }
    });
    return deferred.promise;
}

// Called on --prepare.
// Sets up each plugin's Javascript code to be loaded properly.
// Expects a path to the project (platforms/android in CLI, . in plugman-only),
// a path to where the plugins are downloaded, the www dir, and the platform ('android', 'ios', etc.).
module.exports = function handlePrepare(project_dir, platform, plugins_dir, www_dir, is_top_level) {
    // Process:
    // - Do config munging by calling into config-changes module
    // - List all plugins in plugins_dir
    // - Load and parse their plugin.xml files.
    // - Skip those without support for this platform. (No <platform> tags means JS-only!)
    // - Build a list of all their js-modules, including platform-specific js-modules.
    // - For each js-module (general first, then platform) build up an object storing the path and any clobbers, merges and runs for it.
    events.emit('verbose', 'Preparing ' + platform + ' browserify project');
    var platform_json = config_changes.get_platform_json(plugins_dir, platform);
    var wwwDir = www_dir || platform_modules[platform].www_dir(project_dir);
    var scripts = [];

    uninstallQueuedPlugins(platform_json, www_dir);

    events.emit('verbose', 'Processing configuration changes for plugins.');
    config_changes.process(plugins_dir, project_dir, platform);

    if(!is_top_level) {
        return Q();
    }
    requireTr.init(platform);

    var commitId;
    return computeCommitIdSync()
    .then(function(cId){
        commitId = cId;
        return getPlatformVersion(commitId, project_dir);
    }).then(function(platformVersion){
        var libraryRelease = bundle(platform, false, commitId, platformVersion);

        platform_json = config_changes.get_platform_json(plugins_dir, platform);
        var plugins = Object.keys(platform_json.installed_plugins).concat(Object.keys(platform_json.dependent_plugins));
        events.emit('verbose', 'Iterating over installed plugins:', plugins);

        plugins && plugins.forEach(function(plugin) {
            var pluginDir = path.join(plugins_dir, plugin),
                pluginXML = path.join(pluginDir, 'plugin.xml');
            if (!fs.existsSync(pluginXML)) {
                plugman.emit('warn', 'Missing file: ' + pluginXML);
                return Q();
            }
            var xml = xml_helpers.parseElementtreeSync(pluginXML);

            var plugin_id = xml.getroot().attrib.id;

            // add the plugins dir to the platform's www.
            var platformPluginsDir = path.join(wwwDir, 'plugins');
            // XXX this should not be here if there are no js-module. It leaves an empty plugins/ directory
            shell.mkdir('-p', platformPluginsDir);

            var jsModules = xml.findall('./js-module');
            var assets = xml.findall('asset');
            var platformTag = xml.find(util.format('./platform[@name="%s"]', platform));

            if (platformTag) {
                assets = assets.concat(platformTag.findall('./asset'));
                jsModules = jsModules.concat(platformTag.findall('./js-module'));
            }

            // Copy www assets described in <asset> tags.
            assets = assets || [];
            assets.forEach(function(asset) {
                common.asset.install(asset, pluginDir, wwwDir);
            });
            jsModules.forEach(function(module) {
                // Copy the plugin's files into the www directory.
                // NB: We can't always use path.* functions here, because they will use platform slashes.
                // But the path in the plugin.xml and in the cordova_plugins.js should be always forward slashes.
                var pathParts = module.attrib.src.split('/');

                var fsDirname = path.join.apply(path, pathParts.slice(0, -1));
                var fsDir = path.join(platformPluginsDir, plugin_id, fsDirname);
                shell.mkdir('-p', fsDir);

                // Read in the file, prepend the cordova.define, and write it back out.
                var moduleName = plugin_id + '.';
                if (module.attrib.name) {
                    moduleName += module.attrib.name;
                } else {
                    moduleName += path.basename(module.attrib.src, '.js');
                }

                var fsPath = path.join.apply(path, pathParts);
                var scriptPath = path.join(pluginDir, fsPath);

                if(requireTr.hasModule(moduleName) === false) {
                    requireTr.addModule({symbol: moduleName, path: scriptPath});
                }

                module.getchildren().forEach(function(child) {
                    if (child.tag.toLowerCase() == 'clobbers') {
                        fs.appendFileSync(scriptPath,
                          prepareNamespace(child.attrib.target, 'c'),
                          'utf-8');
                    } else if (child.tag.toLowerCase() == 'merges') {
                        fs.appendFileSync(scriptPath,
                          prepareNamespace(child.attrib.target, 'm'),
                          'utf-8');
                    }
                });
                scripts.push(scriptPath);
            });
        });

        libraryRelease.transform(requireTr.transform);

        scripts.forEach(function(script) {
            libraryRelease.add(script);
        });

        var outReleaseFile = path.join(wwwDir, 'cordova.js');
        return generateFinalBundle(platform, libraryRelease, outReleaseFile, commitId, platformVersion, requireTr.getModules());
    });
};
<commit_msg>CB-8153 generate cordova_plugins.json for browserify based projects<commit_after>/**
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you 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.
*/

/* jshint node:true, bitwise:true, undef:true, trailing:true, quotmark:true,
          indent:4, unused:vars, latedef:nofunc,
          unused:false, expr:true
*/

var platform_modules   = require('./platforms'),
    path               = require('path'),
    through            = require('through2'),
    config_changes     = require('./util/config-changes'),
    xml_helpers        = require('../util/xml-helpers'),
    wp8                = require('./platforms/wp8'),
    windows            = require('./platforms/windows'),
    common             = require('./platforms/common'),
    fs                 = require('fs'),
    childProcess       = require('child_process'),
    shell              = require('shelljs'),
    util               = require('util'),
    events             = require('../events'),
    plugman            = require('./plugman'),
    et                 = require('elementtree'),
    prepareNamespace   = require('./util/prepare-namespace'),
    bundle             = require('cordova-js/tasks/lib/bundle-browserify'),
    requireTr          = require('cordova-js/tasks/lib/require-tr'),
    writeLicenseHeader = require('cordova-js/tasks/lib/write-license-header'),
    Q                  = require('q'),
    computeCommitId    = require('cordova-js/tasks/lib/compute-commit-id');

function uninstallQueuedPlugins(platform_json, wwwDir) {
    // Check if there are any plugins queued for uninstallation, and if so, remove any of their plugin web assets loaded in
    // via <js-module> elements
    var plugins_to_uninstall = platform_json.prepare_queue.uninstalled;
    if (plugins_to_uninstall && plugins_to_uninstall.length) {
        var plugins_www = path.join(wwwDir, 'plugins');
        if (fs.existsSync(plugins_www)) {
            plugins_to_uninstall.forEach(function(plug) {
                var id = plug.id;
                var plugin_modules = path.join(plugins_www, id);
                if (fs.existsSync(plugin_modules)) {
                    events.emit('verbose', 'Removing plugins directory from www "'+plugin_modules+'"');
                    shell.rm('-rf', plugin_modules);
                }
            });
        }
    }
}

function generateFinalBundle(platform, libraryRelease, outReleaseFile, commitId, platformVersion) {

    var deferred = Q.defer();
    var outReleaseFileStream = fs.createWriteStream(outReleaseFile);
    var time = new Date().valueOf();
    var symbolList = null;

    var addSymbolList = through.obj(function(row, enc, next) {
        if(symbolList === null) {
            symbolList = requireTr.getModules();
            this.push(util.format('var symbolList = %s;\n%s\n', JSON.stringify(symbolList), row));
        } else {
            this.push(row);
        }
        next();
    });

    libraryRelease.pipeline.get('wrap').push(addSymbolList);

    writeLicenseHeader(outReleaseFileStream, platform, commitId, platformVersion);

    var releaseBundle = libraryRelease.bundle();

    releaseBundle.pipe(outReleaseFileStream);

    outReleaseFileStream.on('finish', function() {
        var newtime = new Date().valueOf() - time;
        plugman.emit('verbose', 'generated cordova.' + platform + '.js @ ' + commitId + ' in ' + newtime + 'ms');
        deferred.resolve();
        // TODO clean up all the *.browserify files
    });

    outReleaseFileStream.on('error', function(err) {
        var newtime = new Date().valueOf() - time;
        events.emit('log', 'error while generating cordova.js');
        deferred.reject();
    });
    return deferred.promise;
}

function computeCommitIdSync() {
    var deferred = Q.defer();
    computeCommitId(function(cId){
        deferred.resolve(cId);
    });
    return deferred.promise;
}

function getPlatformVersion(cId, project_dir) {
    var deferred = Q.defer();
    //run version script for each platform to get platformVersion
    var versionPath = path.join(project_dir, '/cordova/version');
    childProcess.exec(versionPath, function(err, stdout, stderr) {
        if (err) {
            events.emit('log', 'Error running platform version script');
            events.emit('log', err);
            deferred.resolve('N/A');
        } else {
            deferred.resolve(stdout.trim());
        }
    });
    return deferred.promise;
}

// Called on --prepare.
// Sets up each plugin's Javascript code to be loaded properly.
// Expects a path to the project (platforms/android in CLI, . in plugman-only),
// a path to where the plugins are downloaded, the www dir, and the platform ('android', 'ios', etc.).
module.exports = function handlePrepare(project_dir, platform, plugins_dir, www_dir, is_top_level) {
    // Process:
    // - Do config munging by calling into config-changes module
    // - List all plugins in plugins_dir
    // - Load and parse their plugin.xml files.
    // - Skip those without support for this platform. (No <platform> tags means JS-only!)
    // - Build a list of all their js-modules, including platform-specific js-modules.
    // - For each js-module (general first, then platform) build up an object storing the path and any clobbers, merges and runs for it.
    // Write this object into www/cordova_plugins.json.
    // This file is not really used. Maybe cordova app harness
    events.emit('verbose', 'Preparing ' + platform + ' browserify project');
    var platform_json = config_changes.get_platform_json(plugins_dir, platform);
    var wwwDir = www_dir || platform_modules[platform].www_dir(project_dir);
    var scripts = [];

    uninstallQueuedPlugins(platform_json, www_dir);

    events.emit('verbose', 'Processing configuration changes for plugins.');
    config_changes.process(plugins_dir, project_dir, platform);

    if(!is_top_level) {
        return Q();
    }
    requireTr.init(platform);

    var commitId;
    return computeCommitIdSync()
    .then(function(cId){
        commitId = cId;
        return getPlatformVersion(commitId, project_dir);
    }).then(function(platformVersion){
        var libraryRelease = bundle(platform, false, commitId, platformVersion);

        platform_json = config_changes.get_platform_json(plugins_dir, platform);
        var plugins = Object.keys(platform_json.installed_plugins).concat(Object.keys(platform_json.dependent_plugins));
        var pluginMetadata = {};
        events.emit('verbose', 'Iterating over installed plugins:', plugins);

        plugins && plugins.forEach(function(plugin) {
            var pluginDir = path.join(plugins_dir, plugin),
                pluginXML = path.join(pluginDir, 'plugin.xml');
            if (!fs.existsSync(pluginXML)) {
                plugman.emit('warn', 'Missing file: ' + pluginXML);
                return Q();
            }
            var xml = xml_helpers.parseElementtreeSync(pluginXML);

            var plugin_id = xml.getroot().attrib.id;
            // pluginMetadata is a mapping from plugin IDs to versions.
            pluginMetadata[plugin_id] = xml.getroot().attrib.version;

            var cordova_plugins = "module.exports.metadata = \n";
            cordova_plugins += JSON.stringify(pluginMetadata, null, '     ') + "\n";
            cordova_plugins += "modules.exports = modules.exports.metadata;";

            events.emit('verbose', 'Writing out cordova_plugins.js...');
            fs.writeFileSync(path.join(wwwDir, 'cordova_plugins.js'), cordova_plugins, 'utf8');
            var plugin_id = xml.getroot().attrib.id;

            // add the plugins dir to the platform's www.
            var platformPluginsDir = path.join(wwwDir, 'plugins');
            // XXX this should not be here if there are no js-module. It leaves an empty plugins/ directory
            shell.mkdir('-p', platformPluginsDir);

            var jsModules = xml.findall('./js-module');
            var assets = xml.findall('asset');
            var platformTag = xml.find(util.format('./platform[@name="%s"]', platform));

            if (platformTag) {
                assets = assets.concat(platformTag.findall('./asset'));
                jsModules = jsModules.concat(platformTag.findall('./js-module'));
            }

            // Copy www assets described in <asset> tags.
            assets = assets || [];
            assets.forEach(function(asset) {
                common.asset.install(asset, pluginDir, wwwDir);
            });
            jsModules.forEach(function(module) {
                // Copy the plugin's files into the www directory.
                // NB: We can't always use path.* functions here, because they will use platform slashes.
                // But the path in the plugin.xml and in the cordova_plugins.js should be always forward slashes.
                var pathParts = module.attrib.src.split('/');

                var fsDirname = path.join.apply(path, pathParts.slice(0, -1));
                var fsDir = path.join(platformPluginsDir, plugin_id, fsDirname);
                shell.mkdir('-p', fsDir);

                // Read in the file, prepend the cordova.define, and write it back out.
                var moduleName = plugin_id + '.';
                if (module.attrib.name) {
                    moduleName += module.attrib.name;
                } else {
                    moduleName += path.basename(module.attrib.src, '.js');
                }

                var fsPath = path.join.apply(path, pathParts);
                var scriptPath = path.join(pluginDir, fsPath);

                if(requireTr.hasModule(moduleName) === false) {
                    requireTr.addModule({symbol: moduleName, path: scriptPath});
                }

                module.getchildren().forEach(function(child) {
                    if (child.tag.toLowerCase() == 'clobbers') {
                        fs.appendFileSync(scriptPath,
                          prepareNamespace(child.attrib.target, 'c'),
                          'utf-8');
                    } else if (child.tag.toLowerCase() == 'merges') {
                        fs.appendFileSync(scriptPath,
                          prepareNamespace(child.attrib.target, 'm'),
                          'utf-8');
                    }
                });
                scripts.push(scriptPath);
            });
        });

        libraryRelease.transform(requireTr.transform);

        scripts.forEach(function(script) {
            libraryRelease.add(script);
        });

        var outReleaseFile = path.join(wwwDir, 'cordova.js');
        return generateFinalBundle(platform, libraryRelease, outReleaseFile, commitId, platformVersion, requireTr.getModules());
    });
};
<|endoftext|>


<commit_before>require.config({
    paths: {
        "text": "vendor/text"
    }
});

define(function(require) {
    var app = require('durandal/app');

    app.start().then(function() {
        app.makeFit();
        app.setRoot('samples/widgets/shell');
    });
});<commit_msg>Setting default sample back to advanced nav.<commit_after>require.config({
    paths: {
        "text": "vendor/text"
    }
});

define(function(require) {
    var app = require('durandal/app');

    app.start().then(function() {
        app.makeFit();
        app.setRoot('samples/navigationAdvanced/shell');
    });
});<|endoftext|>


<commit_before>/**
 * Created by Marian on 09/12/2015.
 */

var paths = {
    tmp: './tmp',
    src: './app',
    pub: './public'
};

var gulp         = require('gulp');
var jade         = require('gulp-jade');
var data         = require('gulp-data');
var debug        = require('gulp-debug');
var browserSync  = require('browser-sync');
var sass         = require('gulp-sass');
var rev          = require('gulp-rev');
var clean        = require('gulp-clean');
var inject       = require('gulp-inject');
var sourcemaps   = require('gulp-sourcemaps');
var plumber      = require('gulp-plumber');
var autoprefixer = require('gulp-autoprefixer');
var htmlMin      = require('gulp-html-minifier');
var sassdoc      = require('sassdoc');

var autoprefixerOptions = {
    browsers: ['last 2 versions', '> 5%', 'Firefox ESR']
};

var sassOptions = {
    dev : {
        errLogToConsole: true,
        outputStyle    : 'expanded'
    },
    prod: {
        outputStyle: 'compressed'
    }
};

function browserSyncInit(baseDir, files) {
    browserSync.instances = browserSync.init(files, {
        startPath: '/',
        server   : { baseDir }
    });
}

gulp.task('clean:tmp', function () {
    return gulp
        .src([
            paths.tmp + '/**/*.css',
            paths.tmp + '/**/*.html'
        ])
        .pipe(clean());
});

gulp.task('assets', function () {
    gulp.src(paths.src + '/assets/fonts/**/*')
        .pipe(gulp.dest(paths.tmp + '/fonts'));
});

gulp.task('index', ['clean:tmp', 'assets', 'sass:dev'], function () {
    // return gulp.src(paths.src + '/index.html')
    return gulp.src(paths.src + '/*.jade')
        .pipe(data((file) => require('./app/data/cv.json')))
        .pipe(jade({ pretty: true }))
        .pipe(inject(
            gulp.src(paths.tmp + '/stylesheets/**/*.css', {
                read: false
            }).pipe(debug()),
            {
                relative    : false,
                addRootSlash: true
            }
        ))
        .pipe(gulp.dest(paths.tmp));
});

gulp.task('serve', ['index'], function () {
    // Initialize browser sync server
    browserSyncInit([
        paths.tmp
    ]);

    // Watch for sass
    gulp.watch([paths.src + '/**/*.scss', paths.src + '/**/_*.scss'], ['sass:dev']);
    //
    // // Watch for HTML
    // gulp.watch(paths.src + '/**/*.html', ['index']);
    gulp.watch(paths.src + '/**/*.jade', ['index']).on('change', function(event) {
        console.log('File src' + event.path + ' was ' + event.type + ', running tasks...');
        browserSync.reload;
    });
    gulp.watch(paths.tmp + '/index.html').on('change', function(event) {
        console.log('File tmp' + event.path + ' was ' + event.type + ', running tasks...');
        browserSync.reload;
    });
});

gulp.task('sass:dev', function () {
    return gulp
    // Find all `.scss` files from the `stylesheets/` folder
        .src(paths.src + '/stylesheets/**/*.scss')
        .pipe(plumber())
        // Run Sass on those files
        .pipe(sass(sassOptions.dev).on('error', sass.logError))
        .pipe(sourcemaps.write(paths.tmp + '/stylesheets/maps'))
        // Write the resulting CSS in the output folder
        .pipe(gulp.dest(paths.tmp + '/stylesheets'))
        .pipe(browserSync.stream())
});

gulp.task('sass:prod', function () {
    return gulp
    // Find all `.scss` files from the `stylesheets/` folder
        .src(paths.src + '/stylesheets/**/*.scss')
        .pipe(plumber())
        // Run Sass on those files
        .pipe(sass(sassOptions.prod).on('error', sass.logError))
        .pipe(sourcemaps.write(paths.pub + '/stylesheets/maps'))
        .pipe(autoprefixer(autoprefixerOptions))
        // Write the resulting CSS in the output folder
        .pipe(gulp.dest(paths.pub + '/stylesheets'));
});

gulp.task('minify', ['assets', 'sass:prod'], function () {
    // gulp.src(paths.src + '/**/*.html')
    gulp.src(paths.src + '/**/*.jade')
        .pipe(data((file) => require('./app/data/cv.json')))
        .pipe(jade())
        .pipe(inject(
            gulp.src(paths.pub + '/**/*.css', {
                read: false
            }),
            {
                relative    : false,
                addRootSlash: true,
                transform   : function (filepath, file, i, length) {
                    var regexp = new RegExp(paths.pub.slice(1))
                    filepath   = filepath.replace(regexp, '');
                    return `<link rel="stylesheet" href="${filepath}">`;
                }
            }
        ))
        .pipe(htmlMin({
            collapseWhitespace: true
        }))
        .pipe(gulp.dest(paths.pub))
});

gulp.task('prod', ['minify'], function () {
});

gulp.task('default', ['serve']);
<commit_msg>Update the build process to build assets in the correct path.<commit_after>/**
 * Created by Marian on 09/12/2015.
 */

var paths = {
    tmp: './tmp',
    src: './app',
    pub: './public'
};

var gulp         = require('gulp');
var jade         = require('gulp-jade');
var data         = require('gulp-data');
var debug        = require('gulp-debug');
var browserSync  = require('browser-sync');
var sass         = require('gulp-sass');
var rev          = require('gulp-rev');
var clean        = require('gulp-clean');
var inject       = require('gulp-inject');
var sourcemaps   = require('gulp-sourcemaps');
var plumber      = require('gulp-plumber');
var autoprefixer = require('gulp-autoprefixer');
var htmlMin      = require('gulp-html-minifier');
var sassdoc      = require('sassdoc');

var autoprefixerOptions = {
    browsers: ['last 2 versions', '> 5%', 'Firefox ESR']
};

var sassOptions = {
    dev : {
        errLogToConsole: true,
        outputStyle    : 'expanded'
    },
    prod: {
        outputStyle: 'compressed'
    }
};

function browserSyncInit(baseDir, files) {
    browserSync.instances = browserSync.init(files, {
        startPath: '/',
        server   : { baseDir }
    });
}

gulp.task('clean:tmp', function () {
    return gulp
        .src([
            paths.tmp + '/**/*.css',
            paths.tmp + '/**/*.html'
        ])
        .pipe(clean());
});

gulp.task('assets:dev', function () {
    gulp.src(paths.src + '/assets/fonts/**/*')
        .pipe(gulp.dest(paths.tmp + '/fonts'));
});

gulp.task('assets:build', function () {
    gulp.src(paths.src + '/assets/fonts/**/*')
        .pipe(gulp.dest(paths.pub + '/fonts'));
});

gulp.task('index', ['clean:tmp', 'assets:dev', 'sass:dev'], function () {
    // return gulp.src(paths.src + '/index.html')
    return gulp.src(paths.src + '/*.jade')
        .pipe(data((file) => require('./app/data/cv.json')))
        .pipe(jade({ pretty: true }))
        .pipe(inject(
            gulp.src(paths.tmp + '/stylesheets/**/*.css', {
                read: false
            }).pipe(debug()),
            {
                relative    : false,
                addRootSlash: true
            }
        ))
        .pipe(gulp.dest(paths.tmp));
});

gulp.task('serve', ['index'], function () {
    // Initialize browser sync server
    browserSyncInit([
        paths.tmp
    ]);

    // Watch for sass
    gulp.watch([paths.src + '/**/*.scss', paths.src + '/**/_*.scss'], ['sass:dev']);
    //
    // // Watch for HTML
    // gulp.watch(paths.src + '/**/*.html', ['index']);
    gulp.watch(paths.src + '/**/*.jade', ['index']).on('change', function(event) {
        console.log('File src' + event.path + ' was ' + event.type + ', running tasks...');
        browserSync.reload;
    });
    gulp.watch(paths.tmp + '/index.html').on('change', function(event) {
        console.log('File tmp' + event.path + ' was ' + event.type + ', running tasks...');
        browserSync.reload;
    });
});

gulp.task('sass:dev', function () {
    return gulp
    // Find all `.scss` files from the `stylesheets/` folder
        .src(paths.src + '/stylesheets/**/*.scss')
        .pipe(plumber())
        // Run Sass on those files
        .pipe(sass(sassOptions.dev).on('error', sass.logError))
        .pipe(sourcemaps.write(paths.tmp + '/stylesheets/maps'))
        // Write the resulting CSS in the output folder
        .pipe(gulp.dest(paths.tmp + '/stylesheets'))
        .pipe(browserSync.stream())
});

gulp.task('sass:prod', function () {
    return gulp
    // Find all `.scss` files from the `stylesheets/` folder
        .src(paths.src + '/stylesheets/**/*.scss')
        .pipe(plumber())
        // Run Sass on those files
        .pipe(sass(sassOptions.prod).on('error', sass.logError))
        .pipe(sourcemaps.write(paths.pub + '/stylesheets/maps'))
        .pipe(autoprefixer(autoprefixerOptions))
        // Write the resulting CSS in the output folder
        .pipe(gulp.dest(paths.pub + '/stylesheets'));
});

gulp.task('minify', ['assets:build', 'sass:prod'], function () {
    // gulp.src(paths.src + '/**/*.html')
    gulp.src(paths.src + '/**/*.jade')
        .pipe(data((file) => require('./app/data/cv.json')))
        .pipe(jade())
        .pipe(inject(
            gulp.src(paths.pub + '/**/*.css', {
                read: false
            }),
            {
                relative    : false,
                addRootSlash: true,
                transform   : function (filepath, file, i, length) {
                    var regexp = new RegExp(paths.pub.slice(1))
                    filepath   = filepath.replace(regexp, '');
                    return `<link rel="stylesheet" href="${filepath}">`;
                }
            }
        ))
        .pipe(htmlMin({
            collapseWhitespace: true
        }))
        .pipe(gulp.dest(paths.pub))
});

gulp.task('prod', ['minify'], function () {
});

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


<commit_before>import PropTypes from 'prop-types'

import React from 'react'
import Page, {mapDispatchToProps, jumpToTop, propTypes as pagePropTypes} from 'components/Page'
import {Grid, Row, FormControl, FormGroup, ControlLabel, Button} from 'react-bootstrap'
import {Link} from 'react-router-dom'
import moment from 'moment'
import autobind from 'autobind-decorator'
import GQL from 'graphqlapi'

import Fieldset from 'components/Fieldset'
import Messages from 'components/Messages'
import SavedSearchTable from 'components/SavedSearchTable'
import searchFilters from 'components/SearchFilters'

import GuidedTour from 'components/GuidedTour'
import {userTour, superUserTour} from 'pages/HopscotchTour'

import {Person, Report} from 'models'

import API from 'api'
import Settings from 'Settings'

import ConfirmDelete from 'components/ConfirmDelete'

import AppContext from 'components/AppContext'
import { withRouter } from 'react-router-dom'
import { connect } from 'react-redux'

import { SEARCH_OBJECT_TYPES } from 'actions'
import {LAST_WEEK, AFTER} from 'dateUtils'
import {deserializeQueryParams} from 'searchUtils'

class BaseHome extends Page {

	static propTypes = {
		...pagePropTypes,
		currentUser: PropTypes.instanceOf(Person),
	}

	constructor(props) {
		super(props)
		this.ALL_FILTERS = searchFilters.searchFilters()
		this.state = {
			success: null,
			error: null,
			tileCounts: [],
			savedSearches: [],
			selectedSearch: null,
		}
	}

	adminQueries(currentUser) {
		return [ this.allDraft(), this.allPending(), this.pendingMe(currentUser), this.allUpcoming(), this.mySensitiveInfo(), this.allApproved() ]
	}

	approverQueries(currentUser) {
		return [ this.myDraft(currentUser), this.pendingMe(currentUser), this.myOrgRecent(currentUser), this.myOrgFuture(currentUser),
		         this.mySensitiveInfo() ]
	}

	advisorQueries(currentUser) {
		return [ this.myDraft(currentUser), this.myPending(currentUser), this.myOrgRecent(currentUser), this.myOrgFuture(currentUser),
		         this.mySensitiveInfo() ]
	}

	allDraft() { return {
		title: "All draft reports",
		query: { state: [Report.STATE.DRAFT, Report.STATE.REJECTED] },
	}}

	myDraft(currentUser) {
		return {
			title: "My draft reports",
			query: { state: [Report.STATE.DRAFT, Report.STATE.REJECTED], authorUuid: currentUser.uuid },
		}
	}

	myPending(currentUser) {
		return {
			title: "My reports pending approval",
			query: { authorUuid: currentUser.uuid, state: [Report.STATE.PENDING_APPROVAL]},
		}
	}

	pendingMe(currentUser) {
		return {
			title: "Reports pending my approval",
			query: { pendingApprovalOf: currentUser.uuid },
		}
	}

	allPending() {
		return {
			title: "All reports pending approval",
			query: { state: [Report.STATE.PENDING_APPROVAL] },
		}
	}

	allApproved() { return {
		title: "All approved reports",
		query: { state: [Report.STATE.APPROVED], sortOrder: 'ASC' },
	}}

	myOrgRecent(currentUser) {
		if (!currentUser.position || !currentUser.position.organization) { return { query: {}} }
		return {
			title: currentUser.position.organization.shortName + "'s reports in the last 7 days",
			query: {
				orgUuid: currentUser.position.organization.uuid,
				includeOrgChildren: false,
				createdAtStart: LAST_WEEK,
				state: [Report.STATE.RELEASED, Report.STATE.CANCELLED, Report.STATE.PENDING_APPROVAL]
			},
		}
	}

	myOrgFuture(currentUser) {
		if (!currentUser.position || !currentUser.position.organization) { return { query: {}} }
		return {
			title: currentUser.position.organization.shortName + "'s upcoming engagements",
			query: {
				orgUuid: currentUser.position.organization.uuid,
				includeOrgChildren: false,
				state: [Report.STATE.FUTURE],
				sortOrder: 'ASC'
			},
		}
	}

	allUpcoming() {
		return {
			title: "All upcoming engagements",
			query: { state: [Report.STATE.FUTURE], sortOrder: 'ASC' },
		}
	}

	mySensitiveInfo() {
		return {
			title: "Reports with sensitive information",
			query: { state: [Report.STATE.RELEASED], sensitiveInfo: true },
		}
	}

	getQueriesForUser(currentUser) {
		if (currentUser.isAdmin()) {
			return this.adminQueries(currentUser)
		} else if (currentUser.position && currentUser.position.isApprover) {
			return this.approverQueries(currentUser)
		} else {
			return this.advisorQueries(currentUser)
		}
	}

	fetchData(props) {
		//If we don't have the currentUser yet (i.e. page is still loading, don't run these queries)
		const { currentUser } = props
		if (!currentUser || !currentUser._loaded) { return }
		//queries will contain the queries that will show up on the home tiles
		//Based on the users role. They are all report searches
		let queries = this.getQueriesForUser(currentUser)
		let queryParts = []  // GQL query parts
		queries.forEach((q, index) => {
			q.query.pageNum = 0
			q.query.pageSize = 1  // we're only interested in the totalCount, so just get at most one report
			queryParts.push(
				new GQL.Part(/* GraphQL */`tile`+index+`
					: reportList(query:$query` + index + `) { totalCount}`)
				.addVariable("query" + index, "ReportSearchQueryInput", q.query)
			)
		})
		queryParts.push(new GQL.Part(/* GraphQL */`
			savedSearches: mySearches {uuid, name, objectType, query}`))
		GQL.run(queryParts).then(data => {
			let selectedSearch = data.savedSearches && data.savedSearches.length > 0 ? data.savedSearches[0] : null
			this.setState({
				tileCounts: queries.map((q, index) => data['tile'+index].totalCount),
				savedSearches: data.savedSearches,
				selectedSearch: selectedSearch
			})
		})
	}

	render() {
		const { currentUser } = this.props
		const alertStyle = {top:132, marginBottom: '1rem', textAlign: 'center'}
		const supportEmail = Settings.SUPPORT_EMAIL_ADDR
		const supportEmailMessage = supportEmail ? `at ${supportEmail}` : ''
		let queries = this.getQueriesForUser(currentUser)
		return (

					<GuidedTour
						title="Take a guided tour of the home page."
						tour={currentUser.isSuperUser() ? superUserTour : userTour}
						autostart={localStorage.newUser === 'true' && localStorage.hasSeenHomeTour !== 'true'}
						onEnd={() => localStorage.hasSeenHomeTour = 'true'}
					/>

				{!currentUser.hasAssignedPosition() &&

						You are not assigned to a {Settings.fields.advisor.position.name} position.

						Please contact your organization's super user(s) to assign you to a {Settings.fields.advisor.position.name} position.

						If you are unsure, you can also contact the support team {supportEmailMessage}.

				}
				{currentUser.hasAssignedPosition() && !currentUser.hasActivePosition() &&

						Your {Settings.fields.advisor.position.name} position has an inactive status.

						Please contact your organization's super users to change your position to an active status.

						If you are unsure, you can also contact the support team {supportEmailMessage}.

				}
				<Messages error={this.state.error} success={this.state.success} />

				<Fieldset className="home-tile-row" title="My ANET snapshot">
					<Grid fluid>
						<Row>
							{queries.map((query, index) =>{
									return <Button bsStyle="link" onClick={this.onClickDashboard.bind(this, query)} className="home-tile" key={index}>

{this.state.tileCounts[index]}

										{query.title}
									</Button>
							})}
						</Row>
					</Grid>
				</Fieldset>

				<Fieldset title="Saved searches">
					<FormGroup controlId="savedSearchSelect">
						<ControlLabel>Select a saved search</ControlLabel>
						<FormControl componentClass="select" onChange={this.onSaveSearchSelect}>
							{this.state.savedSearches && this.state.savedSearches.map( savedSearch =>
								<option value={savedSearch.uuid} key={savedSearch.uuid}>{savedSearch.name}</option>
							)}
						</FormControl>
					</FormGroup>

					{this.state.selectedSearch &&

								<Button style={{marginRight: 12}} onClick={this.showSearch} >
									Show Search
								</Button>
								<ConfirmDelete
									onConfirmDelete={this.onConfirmDelete}
									objectType="search"
									objectDisplay={this.state.selectedSearch.name}
									bsStyle="danger"
									buttonLabel="Delete Search" />

							<SavedSearchTable search={this.state.selectedSearch} />

					}
				</Fieldset>

		)
	}

	@autobind
	onClickDashboard(queryDetails, event) {
		deserializeQueryParams(SEARCH_OBJECT_TYPES.REPORTS, queryDetails.query, this.deserializeCallback)
		event.preventDefault()
		event.stopPropagation()
	}

	@autobind
	onSaveSearchSelect(event) {
		let uuid = event && event.target ? event.target.value : event
		let search = this.state.savedSearches.find(el => el.uuid === uuid)
		this.setState({selectedSearch: search})
	}

	@autobind
	showSearch() {
		let search = this.state.selectedSearch
		if (search) {
			const objType = SEARCH_OBJECT_TYPES[search.objectType]
			const queryParams = JSON.parse(search.query)
			deserializeQueryParams(objType, queryParams, this.deserializeCallback)
		}
	}

	@autobind
	deserializeCallback(objectType, filters, text) {
		// We update the Redux state
		this.props.setSearchQuery({
			objectType: objectType,
			filters: filters,
			text: text
		})
		this.props.history.push({
			pathname: '/search'
		})
	}

	@autobind
	onConfirmDelete() {
		const search = this.state.selectedSearch
		const index = this.state.savedSearches.findIndex(s => s.uuid === search.uuid)
		const operation = 'deleteSavedSearch'
		let graphql = operation + '(uuid: $uuid)'
		const variables = { uuid: search.uuid }
		const variableDef = '($uuid: String!)'
		API.mutation(graphql, variables, variableDef)
			.then(data => {
				let savedSearches = this.state.savedSearches
				savedSearches.splice(index, 1)
				let nextSelect = savedSearches.length > 0 ? savedSearches[0] : null
				this.setState({ savedSearches: savedSearches, selectedSearch : nextSelect })
			}).catch(error => {
				this.setState({success:null, error: error})
				jumpToTop()
			})
	}

}

const Home = (props) => (
	<AppContext.Consumer>
		{context =>
			<BaseHome currentUser={context.currentUser} {...props} />
		}
	</AppContext.Consumer>
)

export default connect(null, mapDispatchToProps)(withRouter(Home))
<commit_msg>NCI-Agency/anet#1252: Sort approved reports on dashboard<commit_after>import PropTypes from 'prop-types'

import React from 'react'
import Page, {mapDispatchToProps, jumpToTop, propTypes as pagePropTypes} from 'components/Page'
import {Grid, Row, FormControl, FormGroup, ControlLabel, Button} from 'react-bootstrap'
import {Link} from 'react-router-dom'
import moment from 'moment'
import autobind from 'autobind-decorator'
import GQL from 'graphqlapi'

import Fieldset from 'components/Fieldset'
import Messages from 'components/Messages'
import SavedSearchTable from 'components/SavedSearchTable'
import searchFilters from 'components/SearchFilters'

import GuidedTour from 'components/GuidedTour'
import {userTour, superUserTour} from 'pages/HopscotchTour'

import {Person, Report} from 'models'

import API from 'api'
import Settings from 'Settings'

import ConfirmDelete from 'components/ConfirmDelete'

import AppContext from 'components/AppContext'
import { withRouter } from 'react-router-dom'
import { connect } from 'react-redux'

import { SEARCH_OBJECT_TYPES } from 'actions'
import {LAST_WEEK, AFTER} from 'dateUtils'
import {deserializeQueryParams} from 'searchUtils'

class BaseHome extends Page {

	static propTypes = {
		...pagePropTypes,
		currentUser: PropTypes.instanceOf(Person),
	}

	constructor(props) {
		super(props)
		this.ALL_FILTERS = searchFilters.searchFilters()
		this.state = {
			success: null,
			error: null,
			tileCounts: [],
			savedSearches: [],
			selectedSearch: null,
		}
	}

	adminQueries(currentUser) {
		return [ this.allDraft(), this.allPending(), this.pendingMe(currentUser), this.allUpcoming(), this.mySensitiveInfo(), this.allApproved() ]
	}

	approverQueries(currentUser) {
		return [ this.myDraft(currentUser), this.pendingMe(currentUser), this.myOrgRecent(currentUser), this.myOrgFuture(currentUser),
		         this.mySensitiveInfo() ]
	}

	advisorQueries(currentUser) {
		return [ this.myDraft(currentUser), this.myPending(currentUser), this.myOrgRecent(currentUser), this.myOrgFuture(currentUser),
		         this.mySensitiveInfo() ]
	}

	allDraft() { return {
		title: "All draft reports",
		query: { state: [Report.STATE.DRAFT, Report.STATE.REJECTED] },
	}}

	myDraft(currentUser) {
		return {
			title: "My draft reports",
			query: { state: [Report.STATE.DRAFT, Report.STATE.REJECTED], authorUuid: currentUser.uuid },
		}
	}

	myPending(currentUser) {
		return {
			title: "My reports pending approval",
			query: { authorUuid: currentUser.uuid, state: [Report.STATE.PENDING_APPROVAL]},
		}
	}

	pendingMe(currentUser) {
		return {
			title: "Reports pending my approval",
			query: { pendingApprovalOf: currentUser.uuid },
		}
	}

	allPending() {
		return {
			title: "All reports pending approval",
			query: { state: [Report.STATE.PENDING_APPROVAL] },
		}
	}

	allApproved() { return {
		title: "All approved reports",
		query: { state: [Report.STATE.APPROVED], sortBy: 'UPDATED_AT', sortOrder: 'ASC' },
	}}

	myOrgRecent(currentUser) {
		if (!currentUser.position || !currentUser.position.organization) { return { query: {}} }
		return {
			title: currentUser.position.organization.shortName + "'s reports in the last 7 days",
			query: {
				orgUuid: currentUser.position.organization.uuid,
				includeOrgChildren: false,
				createdAtStart: LAST_WEEK,
				state: [Report.STATE.RELEASED, Report.STATE.CANCELLED, Report.STATE.PENDING_APPROVAL]
			},
		}
	}

	myOrgFuture(currentUser) {
		if (!currentUser.position || !currentUser.position.organization) { return { query: {}} }
		return {
			title: currentUser.position.organization.shortName + "'s upcoming engagements",
			query: {
				orgUuid: currentUser.position.organization.uuid,
				includeOrgChildren: false,
				state: [Report.STATE.FUTURE],
				sortOrder: 'ASC'
			},
		}
	}

	allUpcoming() {
		return {
			title: "All upcoming engagements",
			query: { state: [Report.STATE.FUTURE], sortOrder: 'ASC' },
		}
	}

	mySensitiveInfo() {
		return {
			title: "Reports with sensitive information",
			query: { state: [Report.STATE.RELEASED], sensitiveInfo: true },
		}
	}

	getQueriesForUser(currentUser) {
		if (currentUser.isAdmin()) {
			return this.adminQueries(currentUser)
		} else if (currentUser.position && currentUser.position.isApprover) {
			return this.approverQueries(currentUser)
		} else {
			return this.advisorQueries(currentUser)
		}
	}

	fetchData(props) {
		//If we don't have the currentUser yet (i.e. page is still loading, don't run these queries)
		const { currentUser } = props
		if (!currentUser || !currentUser._loaded) { return }
		//queries will contain the queries that will show up on the home tiles
		//Based on the users role. They are all report searches
		let queries = this.getQueriesForUser(currentUser)
		let queryParts = []  // GQL query parts
		queries.forEach((q, index) => {
			q.query.pageNum = 0
			q.query.pageSize = 1  // we're only interested in the totalCount, so just get at most one report
			queryParts.push(
				new GQL.Part(/* GraphQL */`tile`+index+`
					: reportList(query:$query` + index + `) { totalCount}`)
				.addVariable("query" + index, "ReportSearchQueryInput", q.query)
			)
		})
		queryParts.push(new GQL.Part(/* GraphQL */`
			savedSearches: mySearches {uuid, name, objectType, query}`))
		GQL.run(queryParts).then(data => {
			let selectedSearch = data.savedSearches && data.savedSearches.length > 0 ? data.savedSearches[0] : null
			this.setState({
				tileCounts: queries.map((q, index) => data['tile'+index].totalCount),
				savedSearches: data.savedSearches,
				selectedSearch: selectedSearch
			})
		})
	}

	render() {
		const { currentUser } = this.props
		const alertStyle = {top:132, marginBottom: '1rem', textAlign: 'center'}
		const supportEmail = Settings.SUPPORT_EMAIL_ADDR
		const supportEmailMessage = supportEmail ? `at ${supportEmail}` : ''
		let queries = this.getQueriesForUser(currentUser)
		return (

					<GuidedTour
						title="Take a guided tour of the home page."
						tour={currentUser.isSuperUser() ? superUserTour : userTour}
						autostart={localStorage.newUser === 'true' && localStorage.hasSeenHomeTour !== 'true'}
						onEnd={() => localStorage.hasSeenHomeTour = 'true'}
					/>

				{!currentUser.hasAssignedPosition() &&

						You are not assigned to a {Settings.fields.advisor.position.name} position.

						Please contact your organization's super user(s) to assign you to a {Settings.fields.advisor.position.name} position.

						If you are unsure, you can also contact the support team {supportEmailMessage}.

				}
				{currentUser.hasAssignedPosition() && !currentUser.hasActivePosition() &&

						Your {Settings.fields.advisor.position.name} position has an inactive status.

						Please contact your organization's super users to change your position to an active status.

						If you are unsure, you can also contact the support team {supportEmailMessage}.

				}
				<Messages error={this.state.error} success={this.state.success} />

				<Fieldset className="home-tile-row" title="My ANET snapshot">
					<Grid fluid>
						<Row>
							{queries.map((query, index) =>{
									return <Button bsStyle="link" onClick={this.onClickDashboard.bind(this, query)} className="home-tile" key={index}>

{this.state.tileCounts[index]}

										{query.title}
									</Button>
							})}
						</Row>
					</Grid>
				</Fieldset>

				<Fieldset title="Saved searches">
					<FormGroup controlId="savedSearchSelect">
						<ControlLabel>Select a saved search</ControlLabel>
						<FormControl componentClass="select" onChange={this.onSaveSearchSelect}>
							{this.state.savedSearches && this.state.savedSearches.map( savedSearch =>
								<option value={savedSearch.uuid} key={savedSearch.uuid}>{savedSearch.name}</option>
							)}
						</FormControl>
					</FormGroup>

					{this.state.selectedSearch &&

								<Button style={{marginRight: 12}} onClick={this.showSearch} >
									Show Search
								</Button>
								<ConfirmDelete
									onConfirmDelete={this.onConfirmDelete}
									objectType="search"
									objectDisplay={this.state.selectedSearch.name}
									bsStyle="danger"
									buttonLabel="Delete Search" />

							<SavedSearchTable search={this.state.selectedSearch} />

					}
				</Fieldset>

		)
	}

	@autobind
	onClickDashboard(queryDetails, event) {
		deserializeQueryParams(SEARCH_OBJECT_TYPES.REPORTS, queryDetails.query, this.deserializeCallback)
		event.preventDefault()
		event.stopPropagation()
	}

	@autobind
	onSaveSearchSelect(event) {
		let uuid = event && event.target ? event.target.value : event
		let search = this.state.savedSearches.find(el => el.uuid === uuid)
		this.setState({selectedSearch: search})
	}

	@autobind
	showSearch() {
		let search = this.state.selectedSearch
		if (search) {
			const objType = SEARCH_OBJECT_TYPES[search.objectType]
			const queryParams = JSON.parse(search.query)
			deserializeQueryParams(objType, queryParams, this.deserializeCallback)
		}
	}

	@autobind
	deserializeCallback(objectType, filters, text) {
		// We update the Redux state
		this.props.setSearchQuery({
			objectType: objectType,
			filters: filters,
			text: text
		})
		this.props.history.push({
			pathname: '/search'
		})
	}

	@autobind
	onConfirmDelete() {
		const search = this.state.selectedSearch
		const index = this.state.savedSearches.findIndex(s => s.uuid === search.uuid)
		const operation = 'deleteSavedSearch'
		let graphql = operation + '(uuid: $uuid)'
		const variables = { uuid: search.uuid }
		const variableDef = '($uuid: String!)'
		API.mutation(graphql, variables, variableDef)
			.then(data => {
				let savedSearches = this.state.savedSearches
				savedSearches.splice(index, 1)
				let nextSelect = savedSearches.length > 0 ? savedSearches[0] : null
				this.setState({ savedSearches: savedSearches, selectedSearch : nextSelect })
			}).catch(error => {
				this.setState({success:null, error: error})
				jumpToTop()
			})
	}

}

const Home = (props) => (
	<AppContext.Consumer>
		{context =>
			<BaseHome currentUser={context.currentUser} {...props} />
		}
	</AppContext.Consumer>
)

export default connect(null, mapDispatchToProps)(withRouter(Home))
<|endoftext|>