<commit_before>// common dependencies
var fs = require('fs');
var url = require('url');
var colors = require('colors');
var debug = require('debug')('express-basic-app:setup');

// express dependencies
var morgan = require('morgan');
var bodyParser = require('body-parser');
var favicon = require('serve-favicon');
var methodOverride = require('method-override');
var errorHandler = require('errorhandler');

// 404 / error handling dependencies
var nodejsx = require('node-jsx').install();
var notFoundPage = require('../client/javascript/404');

// configure express
module.exports.configureExpress = function(options, app, config) {
    // json pretty response
    app.set('json spaces', 2);

    // express common config
    app.use(options.express.static(options.dir + '/client/public'));
    app.use(morgan('dev'));
    app.use(options.cookieParser());
    app.use(bodyParser());
    app.use(methodOverride());
    app.use(options.session({
        secret: config.get('server.secret'),
        store: options.store,
        key: config.get('session.key')
    }));
    app.use(favicon(options.dir + '/client/public/favicon.ico'));

    // express dev config
    if ('development' == config.get('env')) {
        app.use(errorHandler());
    }
};

// create session store
module.exports.sessions = function(SessionStore, config) {
    var authObject;

    if (config.get('database.redis.url')) {
        var parsedUrl = url.parse(config.get('database.redis.url'));
        authObject = {
            prefix: config.get('database.redis.prefix'),
            host: parsedUrl.hostname,
            port: parsedUrl.port,
            db: config.get('database.redis.db'),
            pass: parsedUrl.auth ? parsedUrl.auth.split(":")[1] : null,
            secret: config.get('server.secret')
        };
    }

    return new SessionStore(authObject);
};

// handle express errors
module.exports.handleExpressError = function(app, helpers) {
    // handle 404 not found
    app.use(function(req, res, next) {
        res.status(404);

        // respond with html page
        if (req.accepts('html')) {
            helpers.react.renderMarkupToString({
                component: notFoundPage,
                clientScripts: ['/javascript/404.js'],
                context: {
                    url: req.url,
                    title: '404 - not found',
                    descriptions: ''
                },
                staticPage: false,
                callback: function(err, markup) {
                    if (err) return next(err);
                    res.send(markup);
                }
            });
            return;
        }

        // respond with json
        if (req.accepts('json')) {
            res.send({
                error: 'Not found'
            });
            return;
        }

        // default to plain-text. send()
        res.type('txt').send('Not found');
    });

    // handling other errors
    app.use(function(err, req, res, next) {
        console.error(err.stack);
        res.send(500, 'Something broke!');
    });
};

module.exports.db = function (mongoose, config){
    function connect() {
        mongoose.connect(config.get('database.mongo.url'));
    }

    // connection is open and ready
    mongoose.connection.on('open', function (ref) {
        debug('open connection to mongo server.');
    });

    // mongoose is connected to server
    mongoose.connection.on('connected', function (ref) {
        debug('connected to mongo server.');
    });

    // mongoose has disconnected
    mongoose.connection.on('disconnected', function (ref) {
        debug('disconnected from mongo server.');

        debug('retrying connection in 2 seconds..');
        setTimeout(function() {
            connect();
        }.bind(this), 2000);
    });

    // mongoose connection has closed
    mongoose.connection.on('close', function (ref) {
        debug('closed connection to mongo server');
    });

    // error has occured for mongoose connection
    mongoose.connection.on('error', function (err) {
        debug('error connection to mongo server!');
        debug(err);
    });

    // mongoose is reconnecting
    mongoose.connection.on('reconnect', function (ref) {
        debug('reconnect to mongo server.');
    });

    // initial connect
    connect();
};

// bind server to port
module.exports.run = function(server, config) {
    server.listen(config.get('server.port'), function() {
        debug('listening on port %d'.green, server.address().port);
    });
};
<commit_msg>codestyle<commit_after>// common dependencies
var fs = require('fs');
var url = require('url');
var colors = require('colors');
var debug = require('debug')('express-basic-app:setup');

// express dependencies
var morgan = require('morgan');
var bodyParser = require('body-parser');
var favicon = require('serve-favicon');
var methodOverride = require('method-override');
var errorHandler = require('errorhandler');

// 404 / error handling dependencies
var nodejsx = require('node-jsx').install();
var notFoundPage = require('../client/javascript/404');

// configure express
module.exports.configureExpress = function(options, app, config) {
    // json pretty response
    app.set('json spaces', 2);

    // express common config
    app.use(options.express.static(options.dir + '/client/public'));
    app.use(morgan('dev'));
    app.use(options.cookieParser());
    app.use(bodyParser());
    app.use(methodOverride());
    app.use(options.session({
        secret: config.get('server.secret'),
        store: options.store,
        key: config.get('session.key')
    }));
    app.use(favicon(options.dir + '/client/public/favicon.ico'));

    // express dev config
    if ('development' == config.get('env')) {
        app.use(errorHandler());
    }
};

// create session store
module.exports.sessions = function(SessionStore, config) {
    var authObject;

    if (config.get('database.redis.url')) {
        var parsedUrl = url.parse(config.get('database.redis.url'));
        authObject = {
            prefix: config.get('database.redis.prefix'),
            host: parsedUrl.hostname,
            port: parsedUrl.port,
            db: config.get('database.redis.db'),
            pass: parsedUrl.auth ? parsedUrl.auth.split(":")[1] : null,
            secret: config.get('server.secret')
        };
    }

    return new SessionStore(authObject);
};

// handle express errors
module.exports.handleExpressError = function(app, helpers) {
    // handle 404 not found
    app.use(function(req, res, next) {
        res.status(404);

        // respond with html page
        if (req.accepts('html')) {
            helpers.react.renderMarkupToString({
                component: notFoundPage,
                clientScripts: ['/javascript/404.js'],
                context: {
                    url: req.url,
                    title: '404 - not found',
                    descriptions: ''
                },
                staticPage: false,
                callback: function(err, markup) {
                    if (err) return next(err);
                    res.send(markup);
                }
            });
            return;
        }

        // respond with json
        if (req.accepts('json')) {
            res.send({
                error: 'Not found'
            });
            return;
        }

        // default to plain-text. send()
        res.type('txt').send('Not found');
    });

    // handling other errors
    app.use(function(err, req, res, next) {
        console.error(err.stack);
        res.send(500, 'Something broke!');
    });
};

module.exports.db = function(mongoose, config) {
    function connect() {
        mongoose.connect(config.get('database.mongo.url'));
    }

    // connection is open and ready
    mongoose.connection.on('open', function(ref) {
        debug('open connection to mongo server.');
    });

    // mongoose is connected to server
    mongoose.connection.on('connected', function(ref) {
        debug('connected to mongo server.');
    });

    // mongoose has disconnected
    mongoose.connection.on('disconnected', function(ref) {
        debug('disconnected from mongo server.');

        debug('retrying connection in 2 seconds..');
        setTimeout(function() {
            connect();
        }.bind(this), 2000);
    });

    // mongoose connection has closed
    mongoose.connection.on('close', function(ref) {
        debug('closed connection to mongo server');
    });

    // error has occured for mongoose connection
    mongoose.connection.on('error', function(err) {
        debug('error connection to mongo server!');
        debug(err);
    });

    // mongoose is reconnecting
    mongoose.connection.on('reconnect', function(ref) {
        debug('reconnect to mongo server.');
    });

    // initial connect
    connect();
};

// bind server to port
module.exports.run = function(server, config) {
    server.listen(config.get('server.port'), function() {
        debug('listening on port %d'.green, server.address().port);
    });
};
<|endoftext|>


<commit_before>// Generated on <%= (new Date).toISOString().split('T')[0] %> using <%= pkg.name %> <%= pkg.version %>
'use strict';

var gulp = require('gulp'),
    $ = require('gulp-load-plugins')();

var paths = {
  styles: 'app/styles/**/*.scss',
  scripts: 'app/scripts/**/*.js',
  images: 'app/images/**/*.{gif,jpg,png,svg,webp}',
  extras: 'app/*.*',
  html: ['app/**/*.html'],
  index: 'app/templates/_layout.html',
  clean: ['.tmp/*', 'public/**/*',
      '!public/assets', '!public/assets/**/*',
      '!public/index.php', '!public/.htaccess']
};

var knownOptions = {
  string: 'env',
  default: { env: process.env.NODE_ENV || 'production' }
};

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

/**
 * gulp deploy-init
 */
gulp.task('deploy-init', function() {
  var server = options.env === 'production'
    ? '<%= remoteProduction %>'
    : '<%= remoteStaging %>';

  var branch = options.env === 'production'
    ? 'dokku-production'
    : 'dokku-staging';

  var slug = '<%= _.slugify(slug) %>',
      buildpack = 'https://github.com/CHH/heroku-buildpack-php';

  return $.shell.task([
    'git remote add ' + branch + ' dokku@' + server + ':' + slug,
    'git push ' + branch + ' master',
    'ssh dokku@' + server + ' config:set  BUILDPACK_URL=' + buildpackUrl,
    'ssh dokku@' + server + ' mariadb:create ' + slug,
    'ssh dokku@' + server + ' mariadb:link ' + slug + ' ' + slug + ''
  ]);
});

/**
 * gulp deploy
 */
gulp.task('deploy', function() {
  var branch = options.env === 'production'
    ? 'dokku-production'
    : 'dokku-staging';

  return $.shell.task([
    'git push ' + branch + ' master'
  ]);
});

/**
 * gulp db-dump-local
 */
gulp.task('db-dump-local', ['build'], function() {
  var slug = '<%= _.slugify(slug) %>';

  return $.shell.task([
    '[ -d ".tmp" ] || mkdir .tmp',
    'vagrant ssh --command "mysqldump -uroot -proot ' + slug + ' > /vagrant/.tmp/local.sql"'
  ]);
});

/**
 * gulp db-dump-remote
 */
gulp.task('db-dump-remote', ['build'], function() {
  var server = options.env === 'production'
    ? '<%= remoteProduction %>'
    : '<%= remoteStaging %>';

  var file = options.env === 'production'
    ? 'remote--production.sql'
    : 'remote--staging.sql';

  var slug = '<%= _.slugify(slug) %>';

  return $.shell.task([
    '[ -d ".tmp" ] || mkdir .tmp',
    'ssh dokku@' + server + ' mariadb:dumpraw ' + slug + ' | tee .tmp/' + file + ' > /dev/null'
  ]);
});

/**
 * gulp db-push
 */
gulp.task('db-push', ['db-dump-local'], function() {
  var server = options.env === 'production'
    ? '<%= remoteProduction %>'
    : '<%= remoteStaging %>';

  var slug = '<%= _.slugify(slug) %>';

  return $.shell.task([
    'ssh dokku@' + server + ' mariadb:console ' + slug + ' < .tmp/local.sql'
  ]);
});

/**
 * gulp db-pull
 */
gulp.task('db-pull', ['db-dump-remote'], function(){
  var file = options.env === 'production'
    ? 'remote--production.sql'
    : 'remote--staging.sql';

  var slug = '<%= _.slugify(slug) %>';

  $.shell.task([
    'vagrant ssh --command "mysql -uroot -proot ' + slug + ' < /vagrant/.tmp/ ' + file + '"'
  ]);
});

/**
 * gulp db-dump
 */
gulp.task('db-dump', [
    'clean',
    'db-dump-local',
    'db-dump-remote'
  ], function() {
    var file = options.env === 'production'
      ? 'remote--production.sql'
      : 'remote--staging.sql';

    return gulp.src([
        '.tmp/local.sql',
        '.tmp/ ' + file
      ])
      .pipe(gulp.dest('databases'));
});

/**
 * gulp styles
 */
gulp.task('styles', function() {
  return gulp.src([paths.styles, 'bower_components/**/*.scss'])
    .pipe($.plumber())
    .pipe($.rubySass({
      style: 'expanded',
      precision: 10
    }))
    .pipe(gulpif(options.env === 'production', $.autoprefixer('last 1 version')))
    .pipe(gulpif(options.env === 'production', $.csso()))
    .pipe(gulp.dest('public/styles'))
});

/**
 * gulp scripts
 */
gulp.task('scripts', function() {
  return gulp.src(paths.scripts)
    .pipe($.changed('public/scripts'))
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe(gulpif(options.env === 'production', $.uglify()))
    .pipe(gulp.dest('public/scripts'));
});

/**
 * gulp images
 */
gulp.task('images', function () {
  return gulp.src(paths.images)
    .pipe($.changed('public/images'))
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('public/images'));
});

/**
 * gulp extras
 */
gulp.task('extras', function() {
  return gulp.src(paths.extras, { dot: true })
    .pipe($.changed('public'))
    .pipe(gulp.dest('public'));
});

/**
 * gulp clean
 */
gulp.task('clean', function(cb) {
  require('del')(paths.clean, cb);
});

/**
 * gulp html
 */
gulp.task('html', function() {
  return gulp.src(paths.html)
    .pipe($.changed('public/templates'))
    .pipe(gulp.dest('public/templates'));
})

/**
 * gulp build
 */
gulp.task('build', ['clean'], function() {
  gulp.start('build-useref');
});

/**
 * gulp build-useref
 */
gulp.task('build-useref', [
    'html',
    'images',
    'scripts',
    'styles',
    'extras'
  ], function() {
  var assets = $.useref.assets({searchPath: '{public, app}'});

  return gulp.src(paths.index)
    .pipe(assets)
    .pipe(assets.restore())
    .pipe($.useref())
    .pipe(gulp.dest('public/templates'));
});

/**
 * gulp watch
 */
gulp.task('watch', function() {
  gulp.start('build-useref');

  livereload.listen();
  gulp.watch('public/**/*', $.livereload.changed);

  gulp.watch(paths.extras,  ['extras']);
  gulp.watch(paths.html,    ['html']);
  gulp.watch(paths.index,   ['build-useref']);
  gulp.watch(paths.scripts, ['scripts']);
  gulp.watch(paths.styles,  ['styles']);
  gulp.watch(paths.images,  ['images']);
});

/**
 * gulp
 */
gulp.task('default', ['build']);<commit_msg>Require minimist, gulpif fix<commit_after>// Generated on <%= (new Date).toISOString().split('T')[0] %> using <%= pkg.name %> <%= pkg.version %>
'use strict';

var gulp = require('gulp'),
    $ = require('gulp-load-plugins')(),
    minimist = require('minimist');

var paths = {
  styles: 'app/styles/**/*.scss',
  scripts: 'app/scripts/**/*.js',
  images: 'app/images/**/*.{gif,jpg,png,svg,webp}',
  extras: 'app/*.*',
  html: ['app/**/*.html'],
  index: 'app/templates/_layout.html',
  clean: ['.tmp/*', 'public/**/*',
      '!public/assets', '!public/assets/**/*',
      '!public/index.php', '!public/.htaccess']
};

var knownOptions = {
  string: 'env',
  default: { env: process.env.NODE_ENV || 'production' }
};

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

/**
 * gulp deploy-init
 */
gulp.task('deploy-init', function() {
  var server = options.env === 'production'
    ? '<%= remoteProduction %>'
    : '<%= remoteStaging %>';

  var branch = options.env === 'production'
    ? 'dokku-production'
    : 'dokku-staging';

  var slug = '<%= _.slugify(slug) %>',
      buildpack = 'https://github.com/CHH/heroku-buildpack-php';

  return $.shell.task([
    'git remote add ' + branch + ' dokku@' + server + ':' + slug,
    'git push ' + branch + ' master',
    'ssh dokku@' + server + ' config:set  BUILDPACK_URL=' + buildpackUrl,
    'ssh dokku@' + server + ' mariadb:create ' + slug,
    'ssh dokku@' + server + ' mariadb:link ' + slug + ' ' + slug + ''
  ]);
});

/**
 * gulp deploy
 */
gulp.task('deploy', function() {
  var branch = options.env === 'production'
    ? 'dokku-production'
    : 'dokku-staging';

  return $.shell.task([
    'git push ' + branch + ' master'
  ]);
});

/**
 * gulp db-dump-local
 */
gulp.task('db-dump-local', ['build'], function() {
  var slug = '<%= _.slugify(slug) %>';

  return $.shell.task([
    '[ -d ".tmp" ] || mkdir .tmp',
    'vagrant ssh --command "mysqldump -uroot -proot ' + slug + ' > /vagrant/.tmp/local.sql"'
  ]);
});

/**
 * gulp db-dump-remote
 */
gulp.task('db-dump-remote', ['build'], function() {
  var server = options.env === 'production'
    ? '<%= remoteProduction %>'
    : '<%= remoteStaging %>';

  var file = options.env === 'production'
    ? 'remote--production.sql'
    : 'remote--staging.sql';

  var slug = '<%= _.slugify(slug) %>';

  return $.shell.task([
    '[ -d ".tmp" ] || mkdir .tmp',
    'ssh dokku@' + server + ' mariadb:dumpraw ' + slug + ' | tee .tmp/' + file + ' > /dev/null'
  ]);
});

/**
 * gulp db-push
 */
gulp.task('db-push', ['db-dump-local'], function() {
  var server = options.env === 'production'
    ? '<%= remoteProduction %>'
    : '<%= remoteStaging %>';

  var slug = '<%= _.slugify(slug) %>';

  return $.shell.task([
    'ssh dokku@' + server + ' mariadb:console ' + slug + ' < .tmp/local.sql'
  ]);
});

/**
 * gulp db-pull
 */
gulp.task('db-pull', ['db-dump-remote'], function(){
  var file = options.env === 'production'
    ? 'remote--production.sql'
    : 'remote--staging.sql';

  var slug = '<%= _.slugify(slug) %>';

  $.shell.task([
    'vagrant ssh --command "mysql -uroot -proot ' + slug + ' < /vagrant/.tmp/ ' + file + '"'
  ]);
});

/**
 * gulp db-dump
 */
gulp.task('db-dump', [
    'clean',
    'db-dump-local',
    'db-dump-remote'
  ], function() {
    var file = options.env === 'production'
      ? 'remote--production.sql'
      : 'remote--staging.sql';

    return gulp.src([
        '.tmp/local.sql',
        '.tmp/ ' + file
      ])
      .pipe(gulp.dest('databases'));
});

/**
 * gulp styles
 */
gulp.task('styles', function() {
  return gulp.src([paths.styles, 'bower_components/**/*.scss'])
    .pipe($.plumber())
    .pipe($.rubySass({
      style: 'expanded',
      precision: 10
    }))
    .pipe($.if(options.env === 'production', $.autoprefixer('last 1 version')))
    .pipe($.if(options.env === 'production', $.csso()))
    .pipe(gulp.dest('public/styles'))
});

/**
 * gulp scripts
 */
gulp.task('scripts', function() {
  return gulp.src(paths.scripts)
    .pipe($.changed('public/scripts'))
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(options.env === 'production', $.uglify()))
    .pipe(gulp.dest('public/scripts'));
});

/**
 * gulp images
 */
gulp.task('images', function () {
  return gulp.src(paths.images)
    .pipe($.changed('public/images'))
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('public/images'));
});

/**
 * gulp extras
 */
gulp.task('extras', function() {
  return gulp.src(paths.extras, { dot: true })
    .pipe($.changed('public'))
    .pipe(gulp.dest('public'));
});

/**
 * gulp clean
 */
gulp.task('clean', function(cb) {
  require('del')(paths.clean, cb);
});

/**
 * gulp html
 */
gulp.task('html', function() {
  return gulp.src(paths.html)
    .pipe($.changed('public/templates'))
    .pipe(gulp.dest('public/templates'));
})

/**
 * gulp build
 */
gulp.task('build', ['clean'], function() {
  gulp.start('build-useref');
});

/**
 * gulp build-useref
 */
gulp.task('build-useref', [
    'html',
    'images',
    'scripts',
    'styles',
    'extras'
  ], function() {
  var assets = $.useref.assets({searchPath: '{public, app}'});

  return gulp.src(paths.index)
    .pipe(assets)
    .pipe(assets.restore())
    .pipe($.useref())
    .pipe(gulp.dest('public/templates'));
});

/**
 * gulp watch
 */
gulp.task('watch', function() {
  gulp.start('build-useref');

  livereload.listen();
  gulp.watch('public/**/*', $.livereload.changed);

  gulp.watch(paths.extras,  ['extras']);
  gulp.watch(paths.html,    ['html']);
  gulp.watch(paths.index,   ['build-useref']);
  gulp.watch(paths.scripts, ['scripts']);
  gulp.watch(paths.styles,  ['styles']);
  gulp.watch(paths.images,  ['images']);
});

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


<commit_before>/*
in-class exercice:
Create a very simple webserver, which can distribute any found file and handle the case when no file exists
You can start with the help of the about page of the nodejs website: https://nodejs.org/en/about/
*/

var http = require('http'); // We require the http module, needed to handle http request
var fs = require('fs'); // We require the file system to access files

// We create the server
var proxy = http.createServer(function (req, res) {

  var arrayString = req.url.split("?");
  var argString = arrayString[1];
  var agmts = argString.split("&");
  var paramObjet = {};

  for (var i=0; i< agmts.length; i++) {
    var argument = agmts[i].split ("=");
    paramObjet [argument[0]] = argument [1];
  }

  console.log("paramObjet", paramObjet.website);

  if (/favicon.ico/i.test(req.url)) {
    res.writeHead(404, {'Content-Type': 'text/html'});
    res.end();
    return;
  }

  var options = {

  		hostname: paramObjet.website

  };

  	http.get(options, function(resp) {
  		resp.on('data', function(chunk) {
  			res.end(chunk);
  		});
  	}).on ('error', function(e) {
  		console.log("Got error: " + e.message);

  	});

  console.log(req.url);

});

proxy.listen(1337, "127.0.0.1");

console.log('Server running at http://127.0.0.1:1337/');
<commit_msg>Work proxy server<commit_after>/*
in-class exercice:
Create a very simple webserver, which can distribute any found file and handle the case when no file exists
You can start with the help of the about page of the nodejs website: https://nodejs.org/en/about/
*/

var http = require('http'); // We require the http module, needed to handle http request
var fs = require('fs'); // We require the file system to access files

// We create the server
var proxy = http.createServer(function (browserRequest, proxyResponse) {

  if (/favicon.ico/i.test(browserRequest.url)) {
    proxyResponse.writeHead(404, {'Content-Type': 'text/html'});
    proxyResponse.end();
    return;
  }

  var arrayString = browserRequest.url.split("?");
  var argString = arrayString[1];
  var agmts = argString.split("&");
  var paramObjet = {};

  for (var i=0; i< agmts.length; i++) {
    var argument = agmts[i].split ("=");
    paramObjet [argument[0]] = argument [1];
  }

  console.log(paramObjet.website);

  var options = {

  		hostname: paramObjet.website

  };

  	http.get(options, function(websiteResponse) {
  		//init dataAll
      var dataAll = '';
      websiteResponse.on('data', function(data) {
        dataAll += data;

  		});

      websiteResponse.on('end', function() {
    		proxyResponse.end(dataAll);
    	});
    });
      console.log(browserRequest.url);

  });

proxy.listen(1337, "127.0.0.1");

console.log('Server running at http://127.0.0.1:1337/');

<|endoftext|>


<commit_before>import React from 'react'
import ReactDOM from 'react-dom'
import {Provider} from 'react-redux'
import {addLocaleData} from 'react-intl'
import {IntlProvider} from 'react-intl-redux'
import consoleLogger from '../consoleLogger'
import _union from 'lodash/union'
import _merge from 'lodash/merge'
import {ThemeProvider} from 'styled-components'

import de from 'react-intl/locale-data/de'
import en from 'react-intl/locale-data/en'
import fr from 'react-intl/locale-data/fr'
import it from 'react-intl/locale-data/it'

import {LoadMask} from 'tocco-ui'
import {ToccoTheme} from 'tocco-theme'
import InjectFontRoboto from 'tocco-ui/src/Typography'

import intl from '../intl'
import errorLogging from '../errorLogging'

export const createApp = (name,
  content,
  store,
  {
    input = {},
    actions = undefined,
    publicPath = undefined,
    textResourceModules = [],
    customTheme = {}
  }) => {
  try {
    const theme = _merge({}, ToccoTheme, customTheme)

    if (publicPath) {
      setWebpacksPublicPath(publicPath)
    }

    if (actions) {
      dispatchActions(actions, store)
    }

    const initIntlPromise = setupIntl(input, store, name, textResourceModules)
    const component = getAppComponent(store, initIntlPromise, name, content, theme)

    return {
      renderComponent: () => component,
      store,
      methods: {
        setLocale: locale => intl.setLocale(store, textResourceModules, locale)
      }
    }
  } catch (error) {
    try {
      store.dispatch(errorLogging.logError('Error', 'Error creating react application: ', error))
    } catch (loggingError) {
      consoleLogger.logError('Error creating react application: ', error)
      consoleLogger.logError('Unable to log error: ', loggingError)
    }
  }
}

export const renderApp = (app, mountElementName = 'root') => {
  const mountElement = document.getElementById(mountElementName)
  let render = () => {
    ReactDOM.render(app, mountElement)
  }

  if (__DEV__ && module.hot) {
    const renderApp = render
    const renderError = error => {
      const RedBox = require('redbox-react')

      ReactDOM.render(<RedBox error={error}/>, mountElement)
    }
    render = () => {
      try {
        renderApp()
      } catch (error) {
        renderError(error)
      }
    }
  }
  render()
}

export const reloadApp = (app, mountElementName = 'root') => {
  const mountElement = document.getElementById(mountElementName)
  ReactDOM.unmountComponentAtNode(mountElement)
  renderApp(app, mountElementName)
}

export const registerAppInRegistry = (appName, initFunction) => {
  if (window.reactRegistry) {
    window.reactRegistry.register(appName, initFunction)
  }
}

const dispatchActions = (actions, store) => {
  actions.forEach(action => {
    store.dispatch(action)
  })
}

const setWebpacksPublicPath = publicPath => {
  /* eslint camelcase: 0 */
  __webpack_public_path__ = publicPath
}

const getAppComponent = (store, initIntlPromise, name, content, theme) => (
  <ThemeProvider theme={theme}>

      <InjectFontRoboto theme={theme}/>
      <Provider store={store}>
        <LoadMask promises={[initIntlPromise]}>
          <IntlProvider>
            <div className={`tocco-${name}`}>
              {content}

          </IntlProvider>
        </LoadMask>
      </Provider>

  </ThemeProvider>
)

const setupIntl = (input, store, module, textResourceModules) => {
  const modules = _union([module], textResourceModules)
  addLocaleData([...de, ...en, ...fr, ...it])
  const locale = input ? input.locale : null
  return intl.initIntl(store, modules, locale)
}
<commit_msg>fix(tocco-ui): import InjectFontRoboto correctly<commit_after>import React from 'react'
import ReactDOM from 'react-dom'
import {Provider} from 'react-redux'
import {addLocaleData} from 'react-intl'
import {IntlProvider} from 'react-intl-redux'
import consoleLogger from '../consoleLogger'
import _union from 'lodash/union'
import _merge from 'lodash/merge'
import {ThemeProvider} from 'styled-components'

import de from 'react-intl/locale-data/de'
import en from 'react-intl/locale-data/en'
import fr from 'react-intl/locale-data/fr'
import it from 'react-intl/locale-data/it'

import {LoadMask} from 'tocco-ui'
import {ToccoTheme} from 'tocco-theme'
import {InjectFontRoboto} from 'tocco-ui/src/Typography'

import intl from '../intl'
import errorLogging from '../errorLogging'

export const createApp = (name,
  content,
  store,
  {
    input = {},
    actions = undefined,
    publicPath = undefined,
    textResourceModules = [],
    customTheme = {}
  }) => {
  try {
    const theme = _merge({}, ToccoTheme, customTheme)

    if (publicPath) {
      setWebpacksPublicPath(publicPath)
    }

    if (actions) {
      dispatchActions(actions, store)
    }

    const initIntlPromise = setupIntl(input, store, name, textResourceModules)
    const component = getAppComponent(store, initIntlPromise, name, content, theme)

    return {
      renderComponent: () => component,
      store,
      methods: {
        setLocale: locale => intl.setLocale(store, textResourceModules, locale)
      }
    }
  } catch (error) {
    try {
      store.dispatch(errorLogging.logError('Error', 'Error creating react application: ', error))
    } catch (loggingError) {
      consoleLogger.logError('Error creating react application: ', error)
      consoleLogger.logError('Unable to log error: ', loggingError)
    }
  }
}

export const renderApp = (app, mountElementName = 'root') => {
  const mountElement = document.getElementById(mountElementName)
  let render = () => {
    ReactDOM.render(app, mountElement)
  }

  if (__DEV__ && module.hot) {
    const renderApp = render
    const renderError = error => {
      const RedBox = require('redbox-react')

      ReactDOM.render(<RedBox error={error}/>, mountElement)
    }
    render = () => {
      try {
        renderApp()
      } catch (error) {
        renderError(error)
      }
    }
  }
  render()
}

export const reloadApp = (app, mountElementName = 'root') => {
  const mountElement = document.getElementById(mountElementName)
  ReactDOM.unmountComponentAtNode(mountElement)
  renderApp(app, mountElementName)
}

export const registerAppInRegistry = (appName, initFunction) => {
  if (window.reactRegistry) {
    window.reactRegistry.register(appName, initFunction)
  }
}

const dispatchActions = (actions, store) => {
  actions.forEach(action => {
    store.dispatch(action)
  })
}

const setWebpacksPublicPath = publicPath => {
  /* eslint camelcase: 0 */
  __webpack_public_path__ = publicPath
}

const getAppComponent = (store, initIntlPromise, name, content, theme) => (
  <ThemeProvider theme={theme}>

      <InjectFontRoboto theme={theme}/>
      <Provider store={store}>
        <LoadMask promises={[initIntlPromise]}>
          <IntlProvider>
            <div className={`tocco-${name}`}>
              {content}

          </IntlProvider>
        </LoadMask>
      </Provider>

  </ThemeProvider>
)

const setupIntl = (input, store, module, textResourceModules) => {
  const modules = _union([module], textResourceModules)
  addLocaleData([...de, ...en, ...fr, ...it])
  const locale = input ? input.locale : null
  return intl.initIntl(store, modules, locale)
}
<|endoftext|>


<commit_before>document.getElementById('save_user_hosts').addEventListener('click', (event) => {

	let hostsTextarea = document.getElementById('user_defined_hosts');
	let hosts = hostsTextarea.value.
		replace(/,/g, ' ').
		replace(/;/g, ' ').
		replace(/\t+/g, ' ').
		replace(/\r+/g, ' ').
		replace(/\n+/g, ' ').
		trim().
		split(' ').
		filter(host => {
			return !!host; // This removes empty hosts
		});

	if (hosts.length > 0) {
		chrome.storage.sync.get('user_defined_hosts', oldhosts => {
			let uniqueHosts = [...new Set(hosts)];
			chrome.storage.sync.set({'user_defined_hosts': uniqueHosts});
			populateTextArea();
			chrome.extension.getBackgroundPage().handleUserDefinedHosts();
		});
	}
});

populateTextArea();
chrome.extension.getBackgroundPage().handleExtensionClick();

function populateTextArea() {
	let hostsTextarea = document.getElementById('user_defined_hosts');
	chrome.storage.sync.get('user_defined_hosts', oldhost => {
		hostsTextarea.value = [...new Set(oldhost.user_defined_hosts)].join("\r\n");
	});
}

<commit_msg>Correct code review comments<commit_after>document.getElementById('save_user_hosts').addEventListener('click', (event) => {

	let hostsTextarea = document.getElementById('user_defined_hosts');
	let hosts = hostsTextarea.value.
		replace(/[,;\r\n\t]+/g, ' ').
		trim().
		split(' ').
		filter(Boolean);

	if (hosts.length > 0) {
		chrome.storage.sync.get('user_defined_hosts', oldhosts => {
			let uniqueHosts = [...new Set(hosts)];
			chrome.storage.sync.set({'user_defined_hosts': uniqueHosts});
			populateTextArea();
			chrome.extension.getBackgroundPage().handleUserDefinedHosts();
		});
	}
});

populateTextArea();
chrome.extension.getBackgroundPage().handleExtensionClick();

function populateTextArea() {
	let hostsTextarea = document.getElementById('user_defined_hosts');
	chrome.storage.sync.get('user_defined_hosts', oldhost => {
		hostsTextarea.value = [...new Set(oldhost.user_defined_hosts)].join("\r\n");
	});
}

<|endoftext|>


<commit_before>/* @flow */

import * as babylon from 'babylon';

import type Program from './elements/types/Program';
import type Location from './elements/Element';

import visitorKeys from './visitorKeys';
import elementIndex from './elements/elementIndex';
import Token from './elements/Token';

export type BabylonToken = {
    type: string,
    value: string,
    start: number,
    end: number,
    loc?: Location,
    sourceCode: string
};

/**
 * Creates CST using AST and token list.
 *
 * @param {Object} ast
 * @param {Array} tokens
 * @returns {Program}
 */
export function buildElementTree(ast: Object, tokens: Array<BabylonToken>): Program {
    var firstToken = tokens[0];
    ast.start = firstToken.start;
    ast.end = tokens[tokens.length - 1].end;
    return ((buildElementTreeItem(ast, {
        tokens,
        token: firstToken,
        pos: 0
    }): any): Program);
}

type ElementTreeItemState = {
    tokens: Array<BabylonToken>,
    token: BabylonToken,
    pos: number
};

/**
 * @param {Object} ast
 * @param {{tokens: Array, token: Object, pos: Number}} state
 * @returns {Element}
 */
function buildElementTreeItem(ast: Object, state: ElementTreeItemState): ?Element {
    var elementType = ast.type;
    let childProps = visitorKeys[elementType];

    if (!childProps) {
        let error = new SyntaxError(`Cannot iterate using ${elementType}`);
        error.loc = ast.loc.start;
        throw error;
    }

    let childElements = [];
    for (let i = 0; i < childProps.length; i++) {
        let childAst = ast[childProps[i]];

        if (!childAst) {
            continue;
        }

        if (Array.isArray(childAst)) {
            for (let j = 0; j < childAst.length; j++) {
                if (childAst[j] === null) {
                    continue;
                }

                // Skip first `Identifier` for ({ test = 1 } = {})
                // since it is already used in `AssignmentPattern`
                // Need to fix this one day (See https://github.com/babel/babylon/issues/49)
                if (
                    childAst[j].type === 'ObjectProperty' &&
                    childAst[j].value.type === 'AssignmentPattern'
                ) {
                    delete childAst[j].key;
                }

                childElements[childElements.length] = childAst[j];
            }
        } else {
            childElements[childElements.length] = childAst;
        }
    }

    childElements.sort((ast1, ast2) => {
        return ast1.start < ast2.start ? -1 : (ast1.start > ast2.start ? 1 : 0);
    });

    let NodeClass = elementIndex[elementType];

    if (!NodeClass) {
        throw new Error(`Cannot create ${elementType} instance`);
    }

    let children = [];
    let childElementIndex = 0;
    let childElement = childElements[0];
    let end = ast.end;

    do {
        if (childElement && state.token.start === childElement.start) {
            if (state.token.end > childElement.end) {
                let EmptyNodeClass = elementIndex[childElement.type];
                if (!EmptyNodeClass) {
                    throw new Error(`Cannot create ${childElement.type} instance`);
                }

                children[children.length] = new EmptyNodeClass([]);
                childElement = childElements[++childElementIndex];
            } else {
                let nextChild = childElements[childElementIndex + 1];

                children[children.length] = buildElementTreeItem(childElement, state);
                childElement = childElements[++childElementIndex];

                if (!state.token ||
                    (state.token.start === end && (state.token.end !== end || elementType !== 'Program'))
                ) {
                    return new NodeClass(children);
                }
            }
        } else {
            let endOfAstReached = state.token.end === end;
            let addedTokenType = state.token.type;

            if (endOfAstReached && ast.type === 'Identifier' && addedTokenType === 'Keyword') {
                state.token.type = addedTokenType = 'Identifier';
            }

            children[children.length] = Token.createFromToken(state.token);

            state.pos++;
            state.token = state.tokens[state.pos];

            if (elementType === 'Program' && addedTokenType !== 'EOF') {
                continue;
            }

            if (endOfAstReached) {
                return new NodeClass(children);
            }
        }
    } while (state.token);
}

/**
 * Build single token list using code tokens, comments and whitespace.
 *
 * @param {Array} codeTokens
 * @param {String} code
 * @returns {Array}
 */
export function buildTokenList(codeTokens: Array<BabylonToken>, code: string): Array<BabylonToken> {
    let prevPos = 0;
    let result = [];

    for (var i = 0; i < codeTokens.length; i++) {
        let token = processToken(codeTokens[i], code);

        let pos = token.start;
        if (prevPos !== pos) {
            let value = code.substring(prevPos, pos);
            result[result.length] = {
                type: 'Whitespace',
                value,
                sourceCode: value,
                start: prevPos,
                end: pos
            };
        }
        result[result.length] = token;

        prevPos = token.end;
    }

    return result;
}

/**
 * Babylon token types.
 */
let tt = babylon.tokTypes;

/**
 * Transforms Babylon-style token to Esprima-style token.
 *
 * @param {Object} token
 * @param {String} source
 */
function processToken(token: Object, source: string): BabylonToken {
    var type = token.type;

    if (type === tt.name) {
        token.type = 'Identifier';
    } else if (type === tt.semi || type === tt.comma ||
        type === tt.parenL || type === tt.parenR ||
        type === tt.braceL || type === tt.braceR ||
        type === tt.slash || type === tt.dot ||
        type === tt.bracketL || type === tt.bracketR ||
        type === tt.ellipsis || type === tt.arrow ||
        type === tt.star || type === tt.incDec ||
        type === tt.colon || type === tt.question ||
        type === tt.backQuote ||
        type === tt.dollarBraceL || type === tt.at ||
        type === tt.logicalOR || type === tt.logicalAND ||
        type === tt.bitwiseOR || type === tt.bitwiseXOR ||
        type === tt.bitwiseAND || type === tt.equality ||
        type === tt.relational || type === tt.bitShift ||
        type === tt.plusMin || type === tt.modulo ||
        type === tt.exponent || type === tt.prefix ||
        type === tt.doubleColon ||
        type.isAssign) {
        token.type = 'Punctuator';
        if (!token.value) {
            token.sourceCode = token.value = type.label;
        }
    } else if (type === tt.template) {
        token.type = 'Template';
        token.sourceCode = token.value;
    } else if (type === tt.jsxTagStart) {
        token.type = 'Punctuator';
        token.sourceCode = token.value = '<';
    } else if (type === tt.jsxTagEnd) {
        token.type = 'Punctuator';
        token.sourceCode = token.value = '>';
    } else if (type === tt.jsxName) {
        token.type = 'JSXIdentifier';
    } else if (type === tt.jsxText) {
        token.type = 'JSXText';
    } else if (type.keyword === 'null') {
        token.type = 'Null';
        token.value = null;
    } else if (type.keyword === 'false' || type.keyword === 'true') {
        token.type = 'Boolean';
        token.value = type.keyword === 'true';
    } else if (type.keyword) {
        token.type = 'Keyword';
    } else if (type === tt.num) {
        token.type = 'Numeric';
    } else if (type === tt.string) {
        token.type = 'String';
    } else if (type === tt.regexp) {
        token.type = 'RegularExpression';
    } else if (type === 'CommentLine') {
        token.sourceCode = '//' + token.value;
    } else if (type === 'CommentBlock') {
        token.sourceCode = '/*' + token.value + '*/';
    } else if (type === tt.eof) {
        token.type = 'EOF';
        token.sourceCode = token.value = '';
    }

    if (!('sourceCode' in token)) {
        token.sourceCode = source.slice(token.start, token.end);
    }

    return token;
}
<commit_msg>Another simplification for hacks<commit_after>/* @flow */

import * as babylon from 'babylon';

import type Program from './elements/types/Program';
import type Location from './elements/Element';

import visitorKeys from './visitorKeys';
import elementIndex from './elements/elementIndex';
import Token from './elements/Token';

export type BabylonToken = {
    type: string,
    value: string,
    start: number,
    end: number,
    loc?: Location,
    sourceCode: string
};

/**
 * Creates CST using AST and token list.
 *
 * @param {Object} ast
 * @param {Array} tokens
 * @returns {Program}
 */
export function buildElementTree(ast: Object, tokens: Array<BabylonToken>): Program {
    var firstToken = tokens[0];
    ast.start = firstToken.start;
    ast.end = tokens[tokens.length - 1].end;
    return ((buildElementTreeItem(ast, {
        tokens,
        token: firstToken,
        pos: 0
    }): any): Program);
}

type ElementTreeItemState = {
    tokens: Array<BabylonToken>,
    token: BabylonToken,
    pos: number
};

/**
 * @param {Object} ast
 * @param {{tokens: Array, token: Object, pos: Number}} state
 * @returns {Element}
 */
function buildElementTreeItem(ast: Object, state: ElementTreeItemState): ?Element {
    var elementType = ast.type;
    let childProps = visitorKeys[elementType];

    // Skip first `Identifier` for ({ test = 1 } = {})
    // since it is already used in `AssignmentPattern`
    // Need to fix this one day (See https://github.com/babel/babylon/issues/49)
    if (
        ast.type === 'ObjectProperty' &&
        ast.value.type === 'AssignmentPattern'
    ) {
        delete ast.key;
    }

    if (!childProps) {
        let error = new SyntaxError(`Cannot iterate using ${elementType}`);
        error.loc = ast.loc.start;
        throw error;
    }

    let childElements = [];
    for (let i = 0; i < childProps.length; i++) {
        let childAst = ast[childProps[i]];

        if (!childAst) {
            continue;
        }

        if (Array.isArray(childAst)) {
            for (let j = 0; j < childAst.length; j++) {
                if (childAst[j] === null) {
                    continue;
                }

                childElements[childElements.length] = childAst[j];
            }
        } else {
            childElements[childElements.length] = childAst;
        }
    }

    childElements.sort((ast1, ast2) => {
        return ast1.start < ast2.start ? -1 : (ast1.start > ast2.start ? 1 : 0);
    });

    let NodeClass = elementIndex[elementType];

    if (!NodeClass) {
        throw new Error(`Cannot create ${elementType} instance`);
    }

    let children = [];
    let childElementIndex = 0;
    let childElement = childElements[0];
    let end = ast.end;

    do {
        if (childElement && state.token.start === childElement.start) {
            if (state.token.end > childElement.end) {
                let EmptyNodeClass = elementIndex[childElement.type];
                if (!EmptyNodeClass) {
                    throw new Error(`Cannot create ${childElement.type} instance`);
                }

                children[children.length] = new EmptyNodeClass([]);
                childElement = childElements[++childElementIndex];
            } else {
                let nextChild = childElements[childElementIndex + 1];

                children[children.length] = buildElementTreeItem(childElement, state);
                childElement = childElements[++childElementIndex];

                if (!state.token ||
                    (state.token.start === end && (state.token.end !== end || elementType !== 'Program'))
                ) {
                    return new NodeClass(children);
                }
            }
        } else {
            let endOfAstReached = state.token.end === end;
            let addedTokenType = state.token.type;

            if (endOfAstReached && ast.type === 'Identifier' && addedTokenType === 'Keyword') {
                state.token.type = addedTokenType = 'Identifier';
            }

            children[children.length] = Token.createFromToken(state.token);

            state.pos++;
            state.token = state.tokens[state.pos];

            if (elementType === 'Program' && addedTokenType !== 'EOF') {
                continue;
            }

            if (endOfAstReached) {
                return new NodeClass(children);
            }
        }
    } while (state.token);
}

/**
 * Build single token list using code tokens, comments and whitespace.
 *
 * @param {Array} codeTokens
 * @param {String} code
 * @returns {Array}
 */
export function buildTokenList(codeTokens: Array<BabylonToken>, code: string): Array<BabylonToken> {
    let prevPos = 0;
    let result = [];

    for (var i = 0; i < codeTokens.length; i++) {
        let token = processToken(codeTokens[i], code);

        let pos = token.start;
        if (prevPos !== pos) {
            let value = code.substring(prevPos, pos);
            result[result.length] = {
                type: 'Whitespace',
                value,
                sourceCode: value,
                start: prevPos,
                end: pos
            };
        }
        result[result.length] = token;

        prevPos = token.end;
    }

    return result;
}

/**
 * Babylon token types.
 */
let tt = babylon.tokTypes;

/**
 * Transforms Babylon-style token to Esprima-style token.
 *
 * @param {Object} token
 * @param {String} source
 */
function processToken(token: Object, source: string): BabylonToken {
    var type = token.type;

    if (type === tt.name) {
        token.type = 'Identifier';
    } else if (type === tt.semi || type === tt.comma ||
        type === tt.parenL || type === tt.parenR ||
        type === tt.braceL || type === tt.braceR ||
        type === tt.slash || type === tt.dot ||
        type === tt.bracketL || type === tt.bracketR ||
        type === tt.ellipsis || type === tt.arrow ||
        type === tt.star || type === tt.incDec ||
        type === tt.colon || type === tt.question ||
        type === tt.backQuote ||
        type === tt.dollarBraceL || type === tt.at ||
        type === tt.logicalOR || type === tt.logicalAND ||
        type === tt.bitwiseOR || type === tt.bitwiseXOR ||
        type === tt.bitwiseAND || type === tt.equality ||
        type === tt.relational || type === tt.bitShift ||
        type === tt.plusMin || type === tt.modulo ||
        type === tt.exponent || type === tt.prefix ||
        type === tt.doubleColon ||
        type.isAssign) {
        token.type = 'Punctuator';
        if (!token.value) {
            token.sourceCode = token.value = type.label;
        }
    } else if (type === tt.template) {
        token.type = 'Template';
        token.sourceCode = token.value;
    } else if (type === tt.jsxTagStart) {
        token.type = 'Punctuator';
        token.sourceCode = token.value = '<';
    } else if (type === tt.jsxTagEnd) {
        token.type = 'Punctuator';
        token.sourceCode = token.value = '>';
    } else if (type === tt.jsxName) {
        token.type = 'JSXIdentifier';
    } else if (type === tt.jsxText) {
        token.type = 'JSXText';
    } else if (type.keyword === 'null') {
        token.type = 'Null';
        token.value = null;
    } else if (type.keyword === 'false' || type.keyword === 'true') {
        token.type = 'Boolean';
        token.value = type.keyword === 'true';
    } else if (type.keyword) {
        token.type = 'Keyword';
    } else if (type === tt.num) {
        token.type = 'Numeric';
    } else if (type === tt.string) {
        token.type = 'String';
    } else if (type === tt.regexp) {
        token.type = 'RegularExpression';
    } else if (type === 'CommentLine') {
        token.sourceCode = '//' + token.value;
    } else if (type === 'CommentBlock') {
        token.sourceCode = '/*' + token.value + '*/';
    } else if (type === tt.eof) {
        token.type = 'EOF';
        token.sourceCode = token.value = '';
    }

    if (!('sourceCode' in token)) {
        token.sourceCode = source.slice(token.start, token.end);
    }

    return token;
}
<|endoftext|>


<commit_before>;(function ($, window, document, undefined) {
  'use strict';

  Foundation.libs.interchange = {
    name : 'interchange',

    version : '5.1.1',

    cache : {},

    images_loaded : false,
    nodes_loaded : false,

    settings : {
      load_attr : 'interchange',

      named_queries : {
        'default' : 'only screen',
        small : Foundation.media_queries.small,
        medium : Foundation.media_queries.medium,
        large : Foundation.media_queries.large,
        xlarge : Foundation.media_queries.xlarge,
        xxlarge: Foundation.media_queries.xxlarge,
        landscape : 'only screen and (orientation: landscape)',
        portrait : 'only screen and (orientation: portrait)',
        retina : 'only screen and (-webkit-min-device-pixel-ratio: 2),' +
          'only screen and (min--moz-device-pixel-ratio: 2),' +
          'only screen and (-o-min-device-pixel-ratio: 2/1),' +
          'only screen and (min-device-pixel-ratio: 2),' +
          'only screen and (min-resolution: 192dpi),' +
          'only screen and (min-resolution: 2dppx)'
      },

      directives : {
        replace: function (el, path, trigger) {
          // The trigger argument, if called within the directive, fires
          // an event named after the directive on the element, passing
          // any parameters along to the event that you pass to trigger.
          //
          // ex. trigger(), trigger([a, b, c]), or trigger(a, b, c)
          //
          // This allows you to bind a callback like so:
          // $('#interchangeContainer').on('replace', function (e, a, b, c) {
          //   console.log($(this).html(), a, b, c);
          // });

          if (/IMG/.test(el[0].nodeName)) {
            var orig_path = el[0].src;

            if (new RegExp(path, 'i').test(orig_path)) return;

            el[0].src = path;

            return trigger(el[0].src);
          }
          var last_path = el.data(this.data_attr + '-last-path');

          if (last_path == path) return;

          return $.get(path, function (response) {
            el.html(response);
            el.data(this.data_attr + '-last-path', path);
            trigger();
          });

        }
      }
    },

    init : function (scope, method, options) {
      Foundation.inherit(this, 'throttle random_str');

      this.data_attr = this.set_data_attr();
      $.extend(true, this.settings, method, options);

      this.bindings(method, options);
      this.load('images');
      this.load('nodes');
    },

    get_media_hash : function() {
        var media_hash='';
        for (var queryName in this.settings.named_queries ) {
            mediaHash += matchMedia(this.settings.named_queries[queryName]).matches.toString();
        }
        return mediaHash;
    },

    events : function () {
      var self = this, prevMediaHash;

      $(window)
        .off('.interchange')
        .on('resize.fndtn.interchange', self.throttle(function () {
            var currMediaHash = self.get_media_hash();
            if (currMediaHash !== prevMediaHash) {
                self.resize();
            }
            prevMediaHash = currMediaHash;
        }, 50));

      return this;
    },

    resize : function () {
      var cache = this.cache;

      if(!this.images_loaded || !this.nodes_loaded) {
        setTimeout($.proxy(this.resize, this), 50);
        return;
      }

      for (var uuid in cache) {
        if (cache.hasOwnProperty(uuid)) {
          var passed = this.results(uuid, cache[uuid]);

          if (passed) {
            this.settings.directives[passed
              .scenario[1]].call(this, passed.el, passed.scenario[0], function () {
                if (arguments[0] instanceof Array) {
                  var args = arguments[0];
                } else {
                  var args = Array.prototype.slice.call(arguments, 0);
                }

                passed.el.trigger(passed.scenario[1], args);
              });
          }
        }
      }

    },

    results : function (uuid, scenarios) {
      var count = scenarios.length;

      if (count > 0) {
        var el = this.S('[' + this.add_namespace('data-uuid') + '="' + uuid + '"]');

        while (count--) {
          var mq, rule = scenarios[count][2];
          if (this.settings.named_queries.hasOwnProperty(rule)) {
            mq = matchMedia(this.settings.named_queries[rule]);
          } else {
            mq = matchMedia(rule);
          }
          if (mq.matches) {
            return {el: el, scenario: scenarios[count]};
          }
        }
      }

      return false;
    },

    load : function (type, force_update) {
      if (typeof this['cached_' + type] === 'undefined' || force_update) {
        this['update_' + type]();
      }

      return this['cached_' + type];
    },

    update_images : function () {
      var images = this.S('img[' + this.data_attr + ']'),
          count = images.length,
          i = count,
          loaded_count = 0,
          data_attr = this.data_attr;

      this.cache = {};
      this.cached_images = [];
      this.images_loaded = (count === 0);

      while (i--) {
        loaded_count++;
        if (images[i]) {
          var str = images[i].getAttribute(data_attr) || '';

          if (str.length > 0) {
            this.cached_images.push(images[i]);
          }
        }

        if (loaded_count === count) {
          this.images_loaded = true;
          this.enhance('images');
        }
      }

      return this;
    },

    update_nodes : function () {
      var nodes = this.S('[' + this.data_attr + ']').not('img'),
          count = nodes.length,
          i = count,
          loaded_count = 0,
          data_attr = this.data_attr;

      this.cached_nodes = [];
      // Set nodes_loaded to true if there are no nodes
      // this.nodes_loaded = false;
      this.nodes_loaded = (count === 0);

      while (i--) {
        loaded_count++;
        var str = nodes[i].getAttribute(data_attr) || '';

        if (str.length > 0) {
          this.cached_nodes.push(nodes[i]);
        }

        if(loaded_count === count) {
          this.nodes_loaded = true;
          this.enhance('nodes');
        }
      }

      return this;
    },

    enhance : function (type) {
      var i = this['cached_' + type].length;

      while (i--) {
        this.object($(this['cached_' + type][i]));
      }

      return $(window).trigger('resize');
    },

    parse_params : function (path, directive, mq) {
      return [this.trim(path), this.convert_directive(directive), this.trim(mq)];
    },

    convert_directive : function (directive) {
      var trimmed = this.trim(directive);

      if (trimmed.length > 0) {
        return trimmed;
      }

      return 'replace';
    },

    object : function(el) {
      var raw_arr = this.parse_data_attr(el),
          scenarios = [],
          i = raw_arr.length;

      if (i > 0) {
        while (i--) {
          var split = raw_arr[i].split(/\((.*?)(\))$/);

          if (split.length > 1) {
            var cached_split = split[0].split(','),
                params = this.parse_params(cached_split[0],
                  cached_split[1], split[1]);

            scenarios.push(params);
          }
        }
      }

      return this.store(el, scenarios);
    },

    uuid : function (separator) {
      var delim = separator || "-",
          self = this;

      function S4() {
        return self.random_str(6);
      }

      return (S4() + S4() + delim + S4() + delim + S4()
        + delim + S4() + delim + S4() + S4() + S4());
    },

    store : function (el, scenarios) {
      var uuid = this.uuid(),
          current_uuid = el.data(this.add_namespace('uuid', true));

      if (this.cache[current_uuid]) return this.cache[current_uuid];

      el.attr(this.add_namespace('data-uuid'), uuid);

      return this.cache[uuid] = scenarios;
    },

    trim : function(str) {
      if (typeof str === 'string') {
        return $.trim(str);
      }

      return str;
    },

    set_data_attr: function (init) {
      if (init) {
        if (this.namespace.length > 0) {
          return this.namespace + '-' + this.settings.load_attr;
        }

        return this.settings.load_attr;
      }

      if (this.namespace.length > 0) {
        return 'data-' + this.namespace + '-' + this.settings.load_attr;
      }

      return 'data-' + this.settings.load_attr;
    },

    parse_data_attr : function (el) {
      var raw = el.attr(this.attr_name()).split(/\[(.*?)\]/),
          i = raw.length,
          output = [];

      while (i--) {
        if (raw[i].replace(/[\W\d]+/, '').length > 4) {
          output.push(raw[i]);
        }
      }

      return output;
    },

    reflow : function () {
      this.load('images', true);
      this.load('nodes', true);
    }

  };

}(jQuery, this, this.document));
<commit_msg>Fix interchange typo.<commit_after>;(function ($, window, document, undefined) {
  'use strict';

  Foundation.libs.interchange = {
    name : 'interchange',

    version : '5.1.1',

    cache : {},

    images_loaded : false,
    nodes_loaded : false,

    settings : {
      load_attr : 'interchange',

      named_queries : {
        'default' : 'only screen',
        small : Foundation.media_queries.small,
        medium : Foundation.media_queries.medium,
        large : Foundation.media_queries.large,
        xlarge : Foundation.media_queries.xlarge,
        xxlarge: Foundation.media_queries.xxlarge,
        landscape : 'only screen and (orientation: landscape)',
        portrait : 'only screen and (orientation: portrait)',
        retina : 'only screen and (-webkit-min-device-pixel-ratio: 2),' +
          'only screen and (min--moz-device-pixel-ratio: 2),' +
          'only screen and (-o-min-device-pixel-ratio: 2/1),' +
          'only screen and (min-device-pixel-ratio: 2),' +
          'only screen and (min-resolution: 192dpi),' +
          'only screen and (min-resolution: 2dppx)'
      },

      directives : {
        replace: function (el, path, trigger) {
          // The trigger argument, if called within the directive, fires
          // an event named after the directive on the element, passing
          // any parameters along to the event that you pass to trigger.
          //
          // ex. trigger(), trigger([a, b, c]), or trigger(a, b, c)
          //
          // This allows you to bind a callback like so:
          // $('#interchangeContainer').on('replace', function (e, a, b, c) {
          //   console.log($(this).html(), a, b, c);
          // });

          if (/IMG/.test(el[0].nodeName)) {
            var orig_path = el[0].src;

            if (new RegExp(path, 'i').test(orig_path)) return;

            el[0].src = path;

            return trigger(el[0].src);
          }
          var last_path = el.data(this.data_attr + '-last-path');

          if (last_path == path) return;

          return $.get(path, function (response) {
            el.html(response);
            el.data(this.data_attr + '-last-path', path);
            trigger();
          });

        }
      }
    },

    init : function (scope, method, options) {
      Foundation.inherit(this, 'throttle random_str');

      this.data_attr = this.set_data_attr();
      $.extend(true, this.settings, method, options);

      this.bindings(method, options);
      this.load('images');
      this.load('nodes');
    },

    get_media_hash : function() {
        var mediaHash='';
        for (var queryName in this.settings.named_queries ) {
            mediaHash += matchMedia(this.settings.named_queries[queryName]).matches.toString();
        }
        return mediaHash;
    },

    events : function () {
      var self = this, prevMediaHash;

      $(window)
        .off('.interchange')
        .on('resize.fndtn.interchange', self.throttle(function () {
            var currMediaHash = self.get_media_hash();
            if (currMediaHash !== prevMediaHash) {
                self.resize();
            }
            prevMediaHash = currMediaHash;
        }, 50));

      return this;
    },

    resize : function () {
      var cache = this.cache;

      if(!this.images_loaded || !this.nodes_loaded) {
        setTimeout($.proxy(this.resize, this), 50);
        return;
      }

      for (var uuid in cache) {
        if (cache.hasOwnProperty(uuid)) {
          var passed = this.results(uuid, cache[uuid]);

          if (passed) {
            this.settings.directives[passed
              .scenario[1]].call(this, passed.el, passed.scenario[0], function () {
                if (arguments[0] instanceof Array) {
                  var args = arguments[0];
                } else {
                  var args = Array.prototype.slice.call(arguments, 0);
                }

                passed.el.trigger(passed.scenario[1], args);
              });
          }
        }
      }

    },

    results : function (uuid, scenarios) {
      var count = scenarios.length;

      if (count > 0) {
        var el = this.S('[' + this.add_namespace('data-uuid') + '="' + uuid + '"]');

        while (count--) {
          var mq, rule = scenarios[count][2];
          if (this.settings.named_queries.hasOwnProperty(rule)) {
            mq = matchMedia(this.settings.named_queries[rule]);
          } else {
            mq = matchMedia(rule);
          }
          if (mq.matches) {
            return {el: el, scenario: scenarios[count]};
          }
        }
      }

      return false;
    },

    load : function (type, force_update) {
      if (typeof this['cached_' + type] === 'undefined' || force_update) {
        this['update_' + type]();
      }

      return this['cached_' + type];
    },

    update_images : function () {
      var images = this.S('img[' + this.data_attr + ']'),
          count = images.length,
          i = count,
          loaded_count = 0,
          data_attr = this.data_attr;

      this.cache = {};
      this.cached_images = [];
      this.images_loaded = (count === 0);

      while (i--) {
        loaded_count++;
        if (images[i]) {
          var str = images[i].getAttribute(data_attr) || '';

          if (str.length > 0) {
            this.cached_images.push(images[i]);
          }
        }

        if (loaded_count === count) {
          this.images_loaded = true;
          this.enhance('images');
        }
      }

      return this;
    },

    update_nodes : function () {
      var nodes = this.S('[' + this.data_attr + ']').not('img'),
          count = nodes.length,
          i = count,
          loaded_count = 0,
          data_attr = this.data_attr;

      this.cached_nodes = [];
      // Set nodes_loaded to true if there are no nodes
      // this.nodes_loaded = false;
      this.nodes_loaded = (count === 0);

      while (i--) {
        loaded_count++;
        var str = nodes[i].getAttribute(data_attr) || '';

        if (str.length > 0) {
          this.cached_nodes.push(nodes[i]);
        }

        if(loaded_count === count) {
          this.nodes_loaded = true;
          this.enhance('nodes');
        }
      }

      return this;
    },

    enhance : function (type) {
      var i = this['cached_' + type].length;

      while (i--) {
        this.object($(this['cached_' + type][i]));
      }

      return $(window).trigger('resize');
    },

    parse_params : function (path, directive, mq) {
      return [this.trim(path), this.convert_directive(directive), this.trim(mq)];
    },

    convert_directive : function (directive) {
      var trimmed = this.trim(directive);

      if (trimmed.length > 0) {
        return trimmed;
      }

      return 'replace';
    },

    object : function(el) {
      var raw_arr = this.parse_data_attr(el),
          scenarios = [],
          i = raw_arr.length;

      if (i > 0) {
        while (i--) {
          var split = raw_arr[i].split(/\((.*?)(\))$/);

          if (split.length > 1) {
            var cached_split = split[0].split(','),
                params = this.parse_params(cached_split[0],
                  cached_split[1], split[1]);

            scenarios.push(params);
          }
        }
      }

      return this.store(el, scenarios);
    },

    uuid : function (separator) {
      var delim = separator || "-",
          self = this;

      function S4() {
        return self.random_str(6);
      }

      return (S4() + S4() + delim + S4() + delim + S4()
        + delim + S4() + delim + S4() + S4() + S4());
    },

    store : function (el, scenarios) {
      var uuid = this.uuid(),
          current_uuid = el.data(this.add_namespace('uuid', true));

      if (this.cache[current_uuid]) return this.cache[current_uuid];

      el.attr(this.add_namespace('data-uuid'), uuid);

      return this.cache[uuid] = scenarios;
    },

    trim : function(str) {
      if (typeof str === 'string') {
        return $.trim(str);
      }

      return str;
    },

    set_data_attr: function (init) {
      if (init) {
        if (this.namespace.length > 0) {
          return this.namespace + '-' + this.settings.load_attr;
        }

        return this.settings.load_attr;
      }

      if (this.namespace.length > 0) {
        return 'data-' + this.namespace + '-' + this.settings.load_attr;
      }

      return 'data-' + this.settings.load_attr;
    },

    parse_data_attr : function (el) {
      var raw = el.attr(this.attr_name()).split(/\[(.*?)\]/),
          i = raw.length,
          output = [];

      while (i--) {
        if (raw[i].replace(/[\W\d]+/, '').length > 4) {
          output.push(raw[i]);
        }
      }

      return output;
    },

    reflow : function () {
      this.load('images', true);
      this.load('nodes', true);
    }

  };

}(jQuery, this, this.document));
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Sun Mar 20 2016 23:19:01 GMT+0100 (CET)

module.exports = function( config ) {
	config.set( {

		// base path that will be used to resolve all patterns (eg. files, exclude)
		basePath: '../../',

		// frameworks to use
		// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
		frameworks: [
			'mocha',
			'sinon-chai',
			'fixture'
		],

		// list of files / patterns to load in the browser
		files: [
			'tests/**/*.js',
			'tests/support/fixtures/**/*'
		],

		// list of files to exclude
		exclude: [
			'tests/support/**/*.js'
		],

		// preprocess matching files before serving them to the browser
		// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
		preprocessors: {
			'tests/**/*.js': [ 'rollup', 'coverage' ],
			'tests/support/fixtures/**/*.html': [ 'html2js' ],
			'tests/support/fixtures/**/*.json': [ 'json_fixtures' ]
		},

		// test results reporter to use
		// possible values: 'dots', 'progress'
		// available reporters: https://npmjs.org/browse/keyword/karma-reporter
		reporters: [
			'progress',
			'coverage'
		],

		// web server port
		port: 9876,

		// enable / disable colors in the output (reporters and logs)
		colors: true,

		// level of logging
		// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
		logLevel: config.LOG_INFO,

		// enable / disable watching file and executing tests whenever any file changes
		autoWatch: false,

		// start these browsers
		// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
		browsers: [
			'Firefox'
		],

		// Continuous Integration mode
		// if true, Karma captures browsers, runs the tests and exits
		singleRun: true,

		// Concurrency level
		// how many browser should be started simultaneous
		concurrency: 1,

		rollupPreprocessor: {
			rollup: {
				plugins: [
					require( 'rollup-plugin-mockr' )( require( '../mockr/default' ) ),
					require( 'rollup-plugin-commonjs' )(),
					require( 'rollup-plugin-node-resolve' )()
				]
			},
			bundle: {
				format: 'iife'
			}
		},

		jsonFixturesPreprocessor: {
			variableName: '__json__'
		},

		coverageReporter: {
			type: 'text-summary'
		}
	} );
};
<commit_msg>[ci skip] Simplified CI configuration.<commit_after>// Karma configuration
// Generated on Sun Mar 20 2016 23:19:01 GMT+0100 (CET)

module.exports = function( config ) {
	require( './default' )( config );

	config.browsers = [
		'Firefox'
	];
};
<|endoftext|>


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

"use strict";

const functions = require("firebase-functions");
const onCreateUser = require("./on-create-user");
const exportCsv = require("./export-csv");
const exportKml = require("./export-kml");
const importCsv = require("./import-csv");
const updateColumns = require("./update-columns");
const onCreateRecord = require("./on-create-record");
const onUpdateRecord = require("./on-update-record");
const cors = require("cors")({ origin: true });

/**
 * Wrapper for HTTP request handlers. Captures uncaught exceptions to prevent
 * debug details from being returned to user.
 */
function onHttpsRequest(handler) {
  return functions.https.onRequest((req, res) =>
    cors(req, res, () => handler(req, res).catch((err) => onError(res, err)))
  );
}

function onError(res, err) {
  console.error(err);
  res.status(500).send("Internal error");
}

// Create user profile in database when user first logs in.
exports.onCreateUser = functions.auth.user().onCreate(onCreateUser);

exports.importCsv = onHttpsRequest(importCsv);

exports.exportCsv = onHttpsRequest(exportCsv);

exports.exportKml = onHttpsRequest(exportKml);

// Test via shell:
// updateColumns.get('/?project=R06MucQJSWvERdE7SiL1&featureType=aaaaaaaa&form=1234567')
exports.updateColumns = onHttpsRequest(updateColumns);

// Test via shell:
// onCreateRecord({featureTypeId: 'households', formId: '1', responses: {'interviewer': 'Nikola Tesla'}}, {params: {projectId: 'R06MucQJSWvERdE7SiL1', featureId: 'p9lyePfXYPOByUFpnIVp', recordId: 'newRecord'}});
exports.onCreateRecord = functions.firestore
  .document("projects/{projectId}/features/{featureId}/records/{recordId}")
  .onCreate((change, context) => onCreateRecord(change, context));

// Test via shell:
// onUpdateRecord({after: {featureTypeId: 'households', formId: '1', responses: {'interviewer': 'George Washington'}}}, {params: {projectId: 'R06MucQJSWvERdE7SiL1', featureId: 'p9lyePfXYPOByUFpnIVp', recordId: 'newRecord'}});
exports.onUpdateRecord = functions.firestore
  .document("projects/{projectId}/features/{featureId}/records/{recordId}")
  .onUpdate((change, context) => onUpdateRecord(change, context));
<commit_msg>Temporarily delete broken functions<commit_after>/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

"use strict";

const functions = require("firebase-functions");
const onCreateUser = require("./on-create-user");
const exportCsv = require("./export-csv");
const exportKml = require("./export-kml");
const importCsv = require("./import-csv");
const updateColumns = require("./update-columns");
const onCreateRecord = require("./on-create-record");
const onUpdateRecord = require("./on-update-record");
const cors = require("cors")({ origin: true });

/**
 * Wrapper for HTTP request handlers. Captures uncaught exceptions to prevent
 * debug details from being returned to user.
 */
function onHttpsRequest(handler) {
  return functions.https.onRequest((req, res) =>
    cors(req, res, () => handler(req, res).catch((err) => onError(res, err)))
  );
}

function onError(res, err) {
  console.error(err);
  res.status(500).send("Internal error");
}

// Create user profile in database when user first logs in.
exports.onCreateUser = functions.auth.user().onCreate(onCreateUser);

exports.importCsv = onHttpsRequest(importCsv);

exports.exportCsv = onHttpsRequest(exportCsv);
<|endoftext|>


<commit_before>'use strict';

var Runtime = require('../.');
var Promise = require('es6-promise').Promise;

var runtime = Runtime.create({
  reduceStack: function(stack, site){
    if(typeof site !== 'function'){
      stack.push({
        fn: site,
        label: site.stack instanceof this.Stack
          ? site.stack.tree().label
          : site.name
      });
    }
  },
  onHandle: function(site, stack){

    if(!site.time){
      console.log('`%s` started', site.label);
      site.time = process.hrtime();
    } else {
      var diff = process.hrtime(site.time);
      console.log('`%s` ended after %s ms',
        site.label, diff[0]*1e+3 + Math.floor(diff[1]*1e-6)
      );
    }
  },
  onHandleError: function(error){
    console.log('ups something broke');
    throw error;
  }
});

function foo(next, value){
  console.log('received `%s`', value);
  setTimeout(function(){
    next(null, 'Callback');
  }, Math.random()*10);
}

function bar(next, value){
  return new Promise(function(resolve){
    setTimeout(function(){
      resolve(value + 'Promise');
    }, Math.random()*10);
  });
}

var fs = require('fs');
function baz(next, value){
  var stream = fs.createReadStream(__filename);

  return stream.once('end', function(){
    next(null, value + 'Stream');
  });
}

var composed = runtime.stack(foo, bar, baz, {wait: true});

composed('insert args here', function done(err, result){
  if(err){ return this.onHandleError(err); }
  console.log('result: `%s`', result);
});

// how does it look like?
console.log('Stack tree -> %s',
  require('archy')(composed.stack.tree())
);
<commit_msg>docs: fix reduceStack on example<commit_after>'use strict';

var Runtime = require('../.');
var Promise = require('es6-promise').Promise;

var runtime = Runtime.create({
  reduceStack: function(stack, site){
    if(typeof site === 'function'){
      stack.push({
        fn: site,
        label: site.stack instanceof this.Stack
          ? site.stack.tree().label
          : site.name
      });
    }
  },
  onHandle: function(site, stack){
    if(!site.time){
      console.log('`%s` started', site.label);
      site.time = process.hrtime();
    } else {
      var diff = process.hrtime(site.time);
      console.log('`%s` ended after %s ms',
        site.label, diff[0]*1e+3 + Math.floor(diff[1]*1e-6)
      );
    }
  },
  onHandleError: function(error){
    console.log('ups something broke');
    throw error;
  }
});

function foo(next, value){
  console.log('received `%s`', value);
  setTimeout(function(){
    next(null, 'Callback');
  }, Math.random()*10);
}

function bar(next, value){
  return new Promise(function(resolve){
    setTimeout(function(){
      resolve(value + 'Promise');
    }, Math.random()*10);
  });
}

var fs = require('fs');
function baz(next, value){
  var stream = fs.createReadStream(__filename);

  return stream.once('end', function(){
    next(null, value + 'Stream');
  });
}

var composed = runtime.stack(foo, bar, baz, {wait: true});

composed('insert args here', function done(err, result){
  if(err){ return this.onHandleError(err); }
  console.log('result: `%s`', result);
});

// how does it look like?
console.log('Stack tree -> %s',
  require('archy')(composed.stack.tree())
);
<|endoftext|>


<commit_before>import VSelect from './VSelect'
import VOverflowBtn from '../VOverflowBtn'
import VAutocomplete from '../VAutocomplete'
import VCombobox from '../VCombobox'
import rebuildSlots from '../../util/rebuildFunctionalSlots'
import dedupeModelListeners from '../../util/dedupeModelListeners'
import { deprecate } from '../../util/console'

/* @vue/component */
const wrapper = {
  functional: true,

  $_wrapperFor: VSelect,

  props: {
    // VAutoComplete
    /** @deprecated */
    autocomplete: Boolean,
    /** @deprecated */
    combobox: Boolean,
    multiple: Boolean,
    /** @deprecated */
    tags: Boolean,
    // VOverflowBtn
    /** @deprecated */
    editable: Boolean,
    /** @deprecated */
    overflow: Boolean,
    /** @deprecated */
    segmented: Boolean
  },

  render (h, { props, data, slots, parent }) {
    dedupeModelListeners(data)
    const children = rebuildSlots(slots(), h)

    if (props.autocomplete) {
      deprecate('<v-select autocomplete>', '<v-autocomplete>', wrapper, parent)
    }
    if (props.combobox) {
      deprecate('<v-select combobox>', '<v-combobox>', wrapper, parent)
    }
    if (props.tags) {
      deprecate('<v-select tags>', '<v-combobox multiple>', wrapper, parent)
    }

    if (props.overflow) {
      deprecate('<v-select overflow>', '<v-overflow-btn>', wrapper, parent)
    }
    if (props.segmented) {
      deprecate('<v-select segmented>', '<v-overflow-btn segmented>', wrapper, parent)
    }
    if (props.editable) {
      deprecate('<v-select editable>', '<v-overflow-btn editable>', wrapper, parent)
    }

    if (props.combobox || props.tags) {
      data.attrs.multiple = props.tags
      return h(VCombobox, data, children)
    } else if (props.autocomplete) {
      data.attrs.multiple = props.multiple
      return h(VAutocomplete, data, children)
    } else if (props.overflow || props.segmented || props.editable) {
      data.attrs.segmented = props.segmented
      data.attrs.editable = props.editable
      return h(VOverflowBtn, data, children)
    } else {
      data.attrs.multiple = props.multiple
      return h(VSelect, data, children)
    }
  }
}

export { wrapper as VSelect }

export default wrapper
<commit_msg>fix(VSelect): fix rendering without attrs (#5973)<commit_after>import VSelect from './VSelect'
import VOverflowBtn from '../VOverflowBtn'
import VAutocomplete from '../VAutocomplete'
import VCombobox from '../VCombobox'
import rebuildSlots from '../../util/rebuildFunctionalSlots'
import dedupeModelListeners from '../../util/dedupeModelListeners'
import { deprecate } from '../../util/console'

/* @vue/component */
const wrapper = {
  functional: true,

  $_wrapperFor: VSelect,

  props: {
    // VAutoComplete
    /** @deprecated */
    autocomplete: Boolean,
    /** @deprecated */
    combobox: Boolean,
    multiple: Boolean,
    /** @deprecated */
    tags: Boolean,
    // VOverflowBtn
    /** @deprecated */
    editable: Boolean,
    /** @deprecated */
    overflow: Boolean,
    /** @deprecated */
    segmented: Boolean
  },

  render (h, { props, data, slots, parent }) { // eslint-disable-line max-statements
    dedupeModelListeners(data)
    const children = rebuildSlots(slots(), h)

    if (props.autocomplete) {
      deprecate('<v-select autocomplete>', '<v-autocomplete>', wrapper, parent)
    }
    if (props.combobox) {
      deprecate('<v-select combobox>', '<v-combobox>', wrapper, parent)
    }
    if (props.tags) {
      deprecate('<v-select tags>', '<v-combobox multiple>', wrapper, parent)
    }

    if (props.overflow) {
      deprecate('<v-select overflow>', '<v-overflow-btn>', wrapper, parent)
    }
    if (props.segmented) {
      deprecate('<v-select segmented>', '<v-overflow-btn segmented>', wrapper, parent)
    }
    if (props.editable) {
      deprecate('<v-select editable>', '<v-overflow-btn editable>', wrapper, parent)
    }

    data.attrs = data.attrs || {}

    if (props.combobox || props.tags) {
      data.attrs.multiple = props.tags
      return h(VCombobox, data, children)
    } else if (props.autocomplete) {
      data.attrs.multiple = props.multiple
      return h(VAutocomplete, data, children)
    } else if (props.overflow || props.segmented || props.editable) {
      data.attrs.segmented = props.segmented
      data.attrs.editable = props.editable
      return h(VOverflowBtn, data, children)
    } else {
      data.attrs.multiple = props.multiple
      return h(VSelect, data, children)
    }
  }
}

export { wrapper as VSelect }

export default wrapper
<|endoftext|>


<commit_before>import './embed.less';
import {
  Container,
  HelpPlugin,
  CaptionsPlugin,
  SoundPlugin,
  PausePlugin,
  UserDataPlugin
} from 'springroll-container';
import '../libs/jquery.mobile.custom';
import '../plugins/jquery-menuToggle';

const frame = $('#frame');
const captionsToggle = $('#captionsToggle');
const soundToggle = $('#soundToggle');
const title = $('#appTitle');
captionsToggle.hide();
soundToggle.hide();

const captions = new CaptionsPlugin('#captionsButton');
const container = new Container({
  iframeSelector: '#appContainer',
  plugins: [
    new UserDataPlugin(),
    new HelpPlugin('#helpButton'),
    captions,
    new PausePlugin('#pauseButton, #resumeButton'),
    new SoundPlugin({
      voButton: '#voButton',
      soundButton: '#soundButton',
      sfxButton: '#sfxButton',
      musicButton: '#musicButton',
      voSlider: '#voiceRange',
      musicSlider: '#musicRange',
      sfxSlider: '#sfxRange',
      soundSlider: '#mainVolume'
    })
  ]
});

function pauseOverlay({ data }) {
  data.paused ? frame.addClass('paused') : frame.removeClass('paused');
}

function onLoadComplete() {
  frame.removeClass('loading');
  title.text(container.release.game.title);
}

function onCaptionStyles({ currentTarget }) {
  const { name, value } = currentTarget;
  captions.setCaptionsStyles(name, value);
}

$('#captionsStyles select').change(onCaptionStyles.bind(this));

container.client.on('paused', pauseOverlay);
container.client.on('resumed', pauseOverlay);
container.client.on('loadDone', onLoadComplete);
container.client.on('loaded', onLoadComplete);
container.client.on('features', ({ data }) => {
  if (data.captions) {
    captionsToggle.removeClass('disabled');
    captionsToggle.show();
  }
  if (data.sound) {
    soundToggle.removeClass('disabled');
    soundToggle.show();
  }

  if (data.soundVolume) {
    $('#divVolumeRange').removeClass('--disabled');
  }

  if (data.voVolume) {
    $('#divVoiceRange').removeClass('--disabled');
  }

  if (data.musicVolume) {
    $('#divMusicRange').removeClass('--disabled');
  }

  if (data.sfxVolume) {
    $('#divSfxRange').removeClass('--disabled');
  }

  $('button[data-toggle-div]')['menuToggle']();
});

container.setupPlugins();

$('form').submit(() => false);

const parseQuery = queryString => {
  var params = {};
  var entries = queryString.split('&');
  for (var i in entries) {
    var parts = entries[i].split('=');
    params[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
  }
  return params;
};

const start = () => {
  // Open via api
  let api = location.pathname.replace('/embed/', '/api/release/');
  let playOptions = null;
  let singlePlay = false;
  let apiArgs = [];
  const queryArgs = [];

  if (location.search) {
    const params = parseQuery(location.search.substr(1));

    // API configurations
    ['version', 'status', 'commitId', 'token'].forEach(function(param) {
      if (params[param]) {
        apiArgs.push(param + '=' + params[param]);
        delete params[param];
      }
    });

    // Check for debug
    if (params.debug) {
      apiArgs.push('debug=true');
      delete params.debug;
    }

    // Show the controls
    if (params.controls) {
      delete params.controls;
      frame.addClass('show-controls');
    }

    // Show the title
    if (params.title) {
      frame.addClass('show-title');

      delete params.title;
    }

    // Add the arguments
    if (apiArgs.length) {
      api += '?' + apiArgs.join('&');
    }

    // Single play
    if (params.singlePlay) {
      singlePlay = params.singlePlay == 'true' || params.singlePlay == '1';
      delete params.singlePlay;
    }

    // Play options
    if (params.playOptions) {
      try {
        playOptions = JSON.parse(params.playOptions);
      } catch (e) {} // ignore invalid JSON parse
      delete params.playOptions;
    }

    // Get any other options and pass them to the query string
    for (var param in params) {
      queryArgs.push(param + '=' + params[param]);
    }
  }

  container
    .openRemote(api, {
      singlePlay,
      playOptions,
      query: queryArgs.length ? '?' + queryArgs.join('&') : ''
    })
    .catch(err => {
      err.json().then(({ error }) => alert(error));
    })
};

start();
<commit_msg>Making sure to reenable the pause button<commit_after>import './embed.less';
import {
  Container,
  HelpPlugin,
  CaptionsPlugin,
  SoundPlugin,
  PausePlugin,
  UserDataPlugin
} from 'springroll-container';
import '../libs/jquery.mobile.custom';
import '../plugins/jquery-menuToggle';

const frame = $('#frame');
const captionsToggle = $('#captionsToggle');
const soundToggle = $('#soundToggle');
const title = $('#appTitle');
captionsToggle.hide();
soundToggle.hide();

const captions = new CaptionsPlugin('#captionsButton');
const container = new Container({
  iframeSelector: '#appContainer',
  plugins: [
    new UserDataPlugin(),
    new HelpPlugin('#helpButton'),
    captions,
    new PausePlugin('#pauseButton, #resumeButton'),
    new SoundPlugin({
      voButton: '#voButton',
      soundButton: '#soundButton',
      sfxButton: '#sfxButton',
      musicButton: '#musicButton',
      voSlider: '#voiceRange',
      musicSlider: '#musicRange',
      sfxSlider: '#sfxRange',
      soundSlider: '#mainVolume'
    })
  ]
});

function pauseOverlay({ data }) {
  data.paused ? frame.addClass('paused') : frame.removeClass('paused');
}

function onLoadComplete() {
  frame.removeClass('loading');
  title.text(container.release.game.title);
  document.querySelector('#pauseButton').classList.remove('disabled');
}

function onCaptionStyles({ currentTarget }) {
  const { name, value } = currentTarget;
  captions.setCaptionsStyles(name, value);
}

$('#captionsStyles select').change(onCaptionStyles.bind(this));

container.client.on('paused', pauseOverlay);
container.client.on('resumed', pauseOverlay);
container.client.on('loadDone', onLoadComplete);
container.client.on('loaded', onLoadComplete);
container.client.on('features', ({ data }) => {
  if (data.captions) {
    captionsToggle.removeClass('disabled');
    captionsToggle.show();
  }
  if (data.sound) {
    soundToggle.removeClass('disabled');
    soundToggle.show();
  }

  if (data.soundVolume) {
    $('#divVolumeRange').removeClass('--disabled');
  }

  if (data.voVolume) {
    $('#divVoiceRange').removeClass('--disabled');
  }

  if (data.musicVolume) {
    $('#divMusicRange').removeClass('--disabled');
  }

  if (data.sfxVolume) {
    $('#divSfxRange').removeClass('--disabled');
  }

  $('button[data-toggle-div]')['menuToggle']();
});

container.setupPlugins();

$('form').submit(() => false);

const parseQuery = queryString => {
  var params = {};
  var entries = queryString.split('&');
  for (var i in entries) {
    var parts = entries[i].split('=');
    params[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
  }
  return params;
};

const start = () => {
  // Open via api
  let api = location.pathname.replace('/embed/', '/api/release/');
  let playOptions = null;
  let singlePlay = false;
  let apiArgs = [];
  const queryArgs = [];

  if (location.search) {
    const params = parseQuery(location.search.substr(1));

    // API configurations
    ['version', 'status', 'commitId', 'token'].forEach(function(param) {
      if (params[param]) {
        apiArgs.push(param + '=' + params[param]);
        delete params[param];
      }
    });

    // Check for debug
    if (params.debug) {
      apiArgs.push('debug=true');
      delete params.debug;
    }

    // Show the controls
    if (params.controls) {
      delete params.controls;
      frame.addClass('show-controls');
    }

    // Show the title
    if (params.title) {
      frame.addClass('show-title');

      delete params.title;
    }

    // Add the arguments
    if (apiArgs.length) {
      api += '?' + apiArgs.join('&');
    }

    // Single play
    if (params.singlePlay) {
      singlePlay = params.singlePlay == 'true' || params.singlePlay == '1';
      delete params.singlePlay;
    }

    // Play options
    if (params.playOptions) {
      try {
        playOptions = JSON.parse(params.playOptions);
      } catch (e) {} // ignore invalid JSON parse
      delete params.playOptions;
    }

    // Get any other options and pass them to the query string
    for (var param in params) {
      queryArgs.push(param + '=' + params[param]);
    }
  }

  container
    .openRemote(api, {
      singlePlay,
      playOptions,
      query: queryArgs.length ? '?' + queryArgs.join('&') : ''
    })
    .catch(err => {
      err.json().then(({ error }) => alert(error));
    })
};

start();
<|endoftext|>