<commit_before>'use strict';

var _ = require('lodash');

var TOOLTIP_WIDTH = 275;  //min-width + padding

function init (majorPills, minorPills, statusPills, bgStatus, tooltip) {

  var pluginBase = { };

  pluginBase.forecastInfos = [];
  pluginBase.forecastPoints = [];

  function findOrCreatePill (plugin) {
    var container = null;

    if (plugin.pluginType === 'pill-major') {
      container = majorPills;
    } else if (plugin.pluginType === 'pill-status') {
      container = statusPills;
    } else if (plugin.pluginType === 'bg-status') {
      container = bgStatus;
    } else {
      container = minorPills;
    }

    var pillName = 'span.pill.' + plugin.name;
    var pill = container.find(pillName);

    var classes = 'pill ' + plugin.name;

    if (!pill || pill.length === 0) {
      pill = $('');
      var pillLabel = $('');
      var pillValue = $('');
      if (plugin.pillFlip) {
        pill.append(pillValue);
        pill.append(pillLabel);
      } else {
        pill.append(pillLabel);
        pill.append(pillValue);
      }

      container.append(pill);
    } else {
      //reset in case a pill class was added and needs to be removed
      pill.attr('class', classes);
    }

    return pill;
  }

  pluginBase.updatePillText = function updatePillText (plugin, options) {

    var pill = findOrCreatePill(plugin);

    if (options.hide) {
      pill.addClass('hidden');
    } else {
      pill.removeClass('hidden');
    }

    pill.addClass(options.pillClass);

    if (options.directHTML) {
      pill.html(options.label);
    } else {
      if (options.directText) {
        pill.text(options.label);
      } else {
        pill.find('label').attr('class', options.labelClass).text(options.label);
        pill.find('em')
          .attr('class', options.valueClass)
          .toggle(options.value != null)
          .text(options.value)
        ;
      }
    }

    if (options.info  && options.info.length) {
      var html = _.map(options.info, function mapInfo (i) {
        return '' + i.label + ' ' + i.value;
      }).join('
\n');

      pill.mouseover(function pillMouseover (event) {
        tooltip.transition().duration(200).style('opacity', .9);

        var windowWidth = $(tooltip).parent().parent().width();
        var left = event.pageX + TOOLTIP_WIDTH < windowWidth ? event.pageX : windowWidth - TOOLTIP_WIDTH - 10;
        tooltip.html(html)
          .style('left', left + 'px')
          .style('top', (event.pageY + 15) + 'px');
      });

      pill.mouseout(function pillMouseout ( ) {
        tooltip.transition()
          .duration(200)
          .style('opacity', 0);
      });
    }
  };

  pluginBase.addForecastPoints = function addForecastPoints (points, info) {
    _.each(points, function eachPoint (point) {
      point.type = 'forecast';
      point.info = info;
      if (point.mgdl < 13) {
        point.color = 'transparent';
      }
    });

    pluginBase.forecastInfos.push(info);
    pluginBase.forecastPoints = pluginBase.forecastPoints.concat(points);
  };

  return pluginBase;
}

module.exports = init;
<commit_msg>make sure old pill tooltips aren't shown if there isn't a new tooltip<commit_after>'use strict';

var _ = require('lodash');

var TOOLTIP_WIDTH = 275;  //min-width + padding

function init (majorPills, minorPills, statusPills, bgStatus, tooltip) {

  var pluginBase = { };

  pluginBase.forecastInfos = [];
  pluginBase.forecastPoints = [];

  function findOrCreatePill (plugin) {
    var container = null;

    if (plugin.pluginType === 'pill-major') {
      container = majorPills;
    } else if (plugin.pluginType === 'pill-status') {
      container = statusPills;
    } else if (plugin.pluginType === 'bg-status') {
      container = bgStatus;
    } else {
      container = minorPills;
    }

    var pillName = 'span.pill.' + plugin.name;
    var pill = container.find(pillName);

    var classes = 'pill ' + plugin.name;

    if (!pill || pill.length === 0) {
      pill = $('');
      var pillLabel = $('');
      var pillValue = $('');
      if (plugin.pillFlip) {
        pill.append(pillValue);
        pill.append(pillLabel);
      } else {
        pill.append(pillLabel);
        pill.append(pillValue);
      }

      container.append(pill);
    } else {
      //reset in case a pill class was added and needs to be removed
      pill.attr('class', classes);
    }

    return pill;
  }

  pluginBase.updatePillText = function updatePillText (plugin, options) {

    var pill = findOrCreatePill(plugin);

    if (options.hide) {
      pill.addClass('hidden');
    } else {
      pill.removeClass('hidden');
    }

    pill.addClass(options.pillClass);

    if (options.directHTML) {
      pill.html(options.label);
    } else {
      if (options.directText) {
        pill.text(options.label);
      } else {
        pill.find('label').attr('class', options.labelClass).text(options.label);
        pill.find('em')
          .attr('class', options.valueClass)
          .toggle(options.value != null)
          .text(options.value)
        ;
      }
    }

    if (options.info  && options.info.length) {
      var html = _.map(options.info, function mapInfo (i) {
        return '' + i.label + ' ' + i.value;
      }).join('
\n');

      pill.mouseover(function pillMouseover (event) {
        tooltip.transition().duration(200).style('opacity', .9);

        var windowWidth = $(tooltip).parent().parent().width();
        var left = event.pageX + TOOLTIP_WIDTH < windowWidth ? event.pageX : windowWidth - TOOLTIP_WIDTH - 10;
        tooltip.html(html)
          .style('left', left + 'px')
          .style('top', (event.pageY + 15) + 'px');
      });

      pill.mouseout(function pillMouseout ( ) {
        tooltip.transition()
          .duration(200)
          .style('opacity', 0);
      });
    } else {
      pill.off('mouseover');
    }
  };

  pluginBase.addForecastPoints = function addForecastPoints (points, info) {
    _.each(points, function eachPoint (point) {
      point.type = 'forecast';
      point.info = info;
      if (point.mgdl < 13) {
        point.color = 'transparent';
      }
    });

    pluginBase.forecastInfos.push(info);
    pluginBase.forecastPoints = pluginBase.forecastPoints.concat(points);
  };

  return pluginBase;
}

module.exports = init;
<|endoftext|>


<commit_before>var _          = require('lodash');
var config     = require('./config')
  , files      = require('./files')
  , browserify = require('./browserify')
  , plugins    = require('./karma_plugins');

plugins.push('karma-browserify');

var opts = {
  // 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: ['browserify', 'jasmine'].concat(config.get('frameworks'))
  // list of files / patterns to load in the browser
  , files: files
  // list of files to exclude
  , exclude: config.get('exclude')
  // preprocess matching files before serving them to the browser
  // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
  , preprocessors: browserify.preprocessors

  , browserify: browserify.browserify

  , babelPreprocessor: {
    options: {
      presets: ['es2015']
    }
  }

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

  , specReporter: {
    maxLogLines: 5 // limit number of lines logged per test
    , suppressErrorSummary: true  // do not print error summary
    , suppressFailed: false  // do not print information about failed tests
    , suppressPassed: false  // do not print information about passed tests
    , suppressSkipped: true  // do not print information about skipped tests
    , showSpecTiming: true // print the time elapsed for each spec
  }

  // enable / disable watching file and executing tests whenever any file changes
  , autoWatch: true
  // start these browsers
  // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
  , browsers: ['PhantomJS']
  // Continuous Integration mode
  // if true, Karma captures browsers, runs the tests and exits
  , singleRun: true
  // Concurrency level
  // how many browser should be started simultanous
  // concurrency: Infinity
  , plugins: plugins
};

module.exports = opts;
<commit_msg>show errors<commit_after>var _          = require('lodash');
var config     = require('./config')
  , files      = require('./files')
  , browserify = require('./browserify')
  , plugins    = require('./karma_plugins');

plugins.push('karma-browserify');

var opts = {
  // 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: ['browserify', 'jasmine'].concat(config.get('frameworks'))
  // list of files / patterns to load in the browser
  , files: files
  // list of files to exclude
  , exclude: config.get('exclude')
  // preprocess matching files before serving them to the browser
  // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
  , preprocessors: browserify.preprocessors

  , browserify: browserify.browserify

  , babelPreprocessor: {
    options: {
      presets: ['es2015']
    }
  }

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

  , specReporter: {
    maxLogLines: 5 // limit number of lines logged per test
    , suppressErrorSummary: false  // do not print error summary
    , suppressFailed: false  // do not print information about failed tests
    , suppressPassed: false  // do not print information about passed tests
    , suppressSkipped: true  // do not print information about skipped tests
    , showSpecTiming: true // print the time elapsed for each spec
  }

  // enable / disable watching file and executing tests whenever any file changes
  , autoWatch: true
  // start these browsers
  // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
  , browsers: ['PhantomJS']
  // Continuous Integration mode
  // if true, Karma captures browsers, runs the tests and exits
  , singleRun: true
  // Concurrency level
  // how many browser should be started simultanous
  // concurrency: Infinity
  , plugins: plugins
};

module.exports = opts;
<|endoftext|>


<commit_before>// ==========================================================================
// Project:   The M-Project - Mobile HTML5 Application Framework
// Copyright: (c) 2010 M-Way Solutions GmbH. All rights reserved.
// Creator:   Sebastian
// Date:      22.11.2010
// License:   Dual licensed under the MIT or GPL Version 2 licenses.
//            http://github.com/mwaylabs/The-M-Project/blob/master/MIT-LICENSE
//            http://github.com/mwaylabs/The-M-Project/blob/master/GPL-LICENSE
// ==========================================================================

m_require('core/foundation/object.js');

/**
 * A constant value for being offline.
 *
 * @type String
 */
M.OFFLINE = 'offline';

/**
 * A constant value for being online.
 *
 * @type String
 */
M.ONLINE = 'online';

/**
 * @class
 *
 * M.Environment encapsulates methods to retrieve information about the
 * environment, like browser used, platform, user agent (based on navigator
 * object) or whether or not the device is online (determined via an ajax
 * request).
 *
 * @extends M.Object
 */
M.Environment = M.Object.extend(
/** @scope M.Environment.prototype */ {

    /**
     * Checks the connection status by sending an ajax request
     * and waiting for the response to decide whether online or offline.
     *
     * The callback is called when the request returns successful or times out. The parameter to callback is a
     * string saying either offline or online.
     *
     * @param {function} callback The function to be called when request returns.
     * @param {String} url Optional. The request url. When not given, a request is made to google.com. (Note: Add a proxy: /google)
     * @param {Number} timeout Optional. Time in milliseconds until request is considered to be timed out. Defaults to 5 seconds.
     */
    getConnectionStatus: function(callback, url, timeout){
        M.Request.init({
            url: url ? url : '/google',
            isJSON: NO,
            timeout: timeout ? timeout : 5000,
            onSuccess: function(data){
                callback(M.ONLINE);
            },
            onError: function(data){
                callback(M.OFFLINE);
            }
        }).send();
    },

    /**
     * Returns the userAgent as received from navigator object.
     * E.g. "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.44 Safari/534.7"
     *
     * @returns {String} The user agent.
     */
    getUserAgent: function() {
        return navigator.userAgent;
    },

    /**
     * Returns the platform as received from navigator object.
     * E.g. "MacIntel"
     *
     * @returns {String} The user's platform.
     */
    getPlatform: function() {
        return navigator.platform;
    },

    /**
     * Returns the browser version as received from navigator object.
     * E.g. "5.0 (Macintosh; U; Intel Mac OS X 10_6_5; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.44 Safari/534.7"
     *
     * @returns {String} The user's browser.
     */
    getBrowserName: function() {
        return navigator.appName;
    },

    /**
     * Returns the currently available width and height of the browser window
     * as an array:
     *
     * 0 -> width
     * 1 -> height
     *
     * @returns {Array} The widht and height of the user's browser window.
     */
    getSize: function() {
        var viewportWidth;
        var viewportHeight;

        if(typeof window.innerWidth != 'undefined') {
            viewportWidth = window.innerWidth,
            viewportHeight = window.innerHeight
        } else if(typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) {
            viewportWidth = document.documentElement.clientWidth,
            viewportHeight = document.documentElement.clientHeight
        } else {
            viewportWidth = document.getElementsByTagName('body')[0].clientWidth,
            viewportHeight = document.getElementsByTagName('body')[0].clientHeight
        }

        return [viewportWidth, viewportHeight];
    },

    /**
     * Returns the currently available width of the browser window.
     *
     * @returns {Number} The width of the user's browser window.
     */
    getWidth: function() {
        return this.getSize()[0];
    },

    /**
     * Returns the currently available height of the browser window.
     *
     * @returns {Number} The height of the user's browser window.
     */
    getHeight: function() {
        return this.getSize()[1];
    }

});<commit_msg>Added getOrientation() to find out the device's current orientation<commit_after>// ==========================================================================
// Project:   The M-Project - Mobile HTML5 Application Framework
// Copyright: (c) 2010 M-Way Solutions GmbH. All rights reserved.
// Creator:   Sebastian
// Date:      22.11.2010
// License:   Dual licensed under the MIT or GPL Version 2 licenses.
//            http://github.com/mwaylabs/The-M-Project/blob/master/MIT-LICENSE
//            http://github.com/mwaylabs/The-M-Project/blob/master/GPL-LICENSE
// ==========================================================================

m_require('core/foundation/object.js');

/**
 * A constant value for being offline.
 *
 * @type String
 */
M.OFFLINE = 'offline';

/**
 * A constant value for being online.
 *
 * @type String
 */
M.ONLINE = 'online';

/**
 * A constant value for portrait orientation mode.
 *
 * @type String
 */
M.PORTRAIT = 0;

/**
 * A constant value for landscape right orientation mode.
 *
 * @type String
 */
M.LANDSCAPE_RIGHT = -90;

/**
 * A constant value for landscape left orientation mode.
 *
 * @type String
 */
M.LANDSCAPE_LEFT = 90;

/**
 * @class
 *
 * M.Environment encapsulates methods to retrieve information about the
 * environment, like browser used, platform, user agent (based on navigator
 * object) or whether or not the device is online (determined via an ajax
 * request).
 *
 * @extends M.Object
 */
M.Environment = M.Object.extend(
/** @scope M.Environment.prototype */ {

    /**
     * Checks the connection status by sending an ajax request
     * and waiting for the response to decide whether online or offline.
     *
     * The callback is called when the request returns successful or times out. The parameter to callback is a
     * string saying either offline or online.
     *
     * @param {function} callback The function to be called when request returns.
     * @param {String} url Optional. The request url. When not given, a request is made to google.com. (Note: Add a proxy: /google)
     * @param {Number} timeout Optional. Time in milliseconds until request is considered to be timed out. Defaults to 5 seconds.
     */
    getConnectionStatus: function(callback, url, timeout){
        M.Request.init({
            url: url ? url : '/google',
            isJSON: NO,
            timeout: timeout ? timeout : 5000,
            onSuccess: function(data){
                callback(M.ONLINE);
            },
            onError: function(data){
                callback(M.OFFLINE);
            }
        }).send();
    },

    /**
     * Returns the userAgent as received from navigator object.
     * E.g. "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.44 Safari/534.7"
     *
     * @returns {String} The user agent.
     */
    getUserAgent: function() {
        return navigator.userAgent;
    },

    /**
     * Returns the platform as received from navigator object.
     * E.g. "MacIntel"
     *
     * @returns {String} The user's platform.
     */
    getPlatform: function() {
        return navigator.platform;
    },

    /**
     * Returns the browser version as received from navigator object.
     * E.g. "5.0 (Macintosh; U; Intel Mac OS X 10_6_5; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.44 Safari/534.7"
     *
     * @returns {String} The user's browser.
     */
    getBrowserName: function() {
        return navigator.appName;
    },

    /**
     * Returns the currently available width and height of the browser window
     * as an array:
     *
     * 0 -> width
     * 1 -> height
     *
     * @returns {Array} The widht and height of the user's browser window.
     */
    getSize: function() {
        var viewportWidth;
        var viewportHeight;

        if(typeof window.innerWidth != 'undefined') {
            viewportWidth = window.innerWidth,
            viewportHeight = window.innerHeight
        } else if(typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) {
            viewportWidth = document.documentElement.clientWidth,
            viewportHeight = document.documentElement.clientHeight
        } else {
            viewportWidth = document.getElementsByTagName('body')[0].clientWidth,
            viewportHeight = document.getElementsByTagName('body')[0].clientHeight
        }

        return [viewportWidth, viewportHeight];
    },

    /**
     * Returns the currently available width of the browser window.
     *
     * @returns {Number} The width of the user's browser window.
     */
    getWidth: function() {
        return this.getSize()[0];
    },

    /**
     * Returns the currently available height of the browser window.
     *
     * @returns {Number} The height of the user's browser window.
     */
    getHeight: function() {
        return this.getSize()[1];
    },

    /**
     * This method returns the device's current orientation, depending on whether
     * or not the device is capable of detecting the current orientation. If the
     * device is unable to detect the current orientation, this method will return
     * NO.
     *
     * Possible return values are:
     *
     *   - M.PORTRAIT
     *   - M.LANDSCAPE_LEFT
     *   - M.LANDSCAPE_RIGHT
     *
     * @return {Number, Boolean} The orientation type as a constant value. (If the orientation can not be detected: NO.)
     */
    getOrientation: function() {
        switch(window.orientation) {
            case M.PORTRAIT:
                return M.PORTRAIT;
            case M.LANDSCAPE_LEFT:
                return M.LANDSCAPE_LEFT;
            case M.LANDSCAPE_RIGHT:
                return M.LANDSCAPE_RIGHT;
            default:
                M.Logger.log('This device does not support orientation detection.', M.WARN);
                return NO;
        }
    }

});<|endoftext|>


<commit_before>/**
 * @license MIT License
 *
 * Copyright (c) 2015 Tetsuharu OHZEKI <saneyuki.snyk@gmail.com>
 * Copyright (c) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
/*eslint quote-props: [2, "always"] */

'use strict';

// ESLint Configuration Files enables to include comments.
// http://eslint.org/docs/configuring/#comments-in-configuration-files
module.exports = {
    'extends': 'eslint:recommended',

    'ecmaFeatures': {
        'arrowFunctions': true,
        'blockBindings': true,
        'classes': true,
        'objectLiteralComputedProperties': true,
        'objectLiteralDuplicateProperties': true,
        'objectLiteralShorthandMethods': true,
        'objectLiteralShorthandProperties': true,
        'templateStrings': true,
        'spread': true
    },

    'env': {
        'node': true
    },

    'plugins': [
        'react' // for React/JSX
    ],

    'root': true,

    'rules': {
        // Possible Errors
        'comma-dangle': [0, 'never'],
        'no-constant-condition': 1,
        'no-console': 0,
        'no-debugger': 1,
        'no-dupe-keys': 2,
        'no-ex-assign': 2,
        'no-extra-boolean-cast': 0,
        'no-extra-parens': 0,
        'no-extra-semi': 1,
        'no-func-assign': 2,
        'no-sparse-arrays': 2,
        'no-unexpected-multiline': 1,
        'no-unreachable': 1,
        'valid-jsdoc': [2, {
            'requireReturn': true,
            'requireParamDescription': false,
            'requireReturnDescription': false
        }],
        'valid-typeof': 2,

        // Best Practices
        'block-scoped-var': 1,
        'consistent-return': 2,
        'curly': 2,
        'eqeqeq': 2,
        'no-alert': 1,
        'no-caller': 2,
        'no-case-declarations': 2,
        'no-div-regex': 2,
        'no-empty-pattern': 2,
        'no-eq-null': 2,
        'no-eval': 2,
        'no-fallthrough': 2,
        'no-implied-eval': 2,
        'no-invalid-this': 1,
        'no-new-func': 1,
        'no-new-wrappers': 2,
        'no-param-reassign': [1, {
            'props': true
        }],
        'no-throw-literal': 2,
        'no-unused-expressions': 2,
        'no-useless-call': 1,
        'no-useless-concat': 1,
        'no-with': 2,
        'radix': 2,

        // Strict Mode
        'strict': [2, 'global'],

        // Variables
        'init-declarations': [2, 'always'],
        'no-shadow': 0,
        'no-unused-vars': 0,
        'no-use-before-define': 0,

        // Node.js
        'global-require': 2,
        'no-mixed-requires': [2, {
            'grouping': true,
        }],
        'no-new-require': 2,
        'no-path-concat': 2,
        'no-process-exit': 0,
        'no-sync': 1, // Bann to use sync method. FIXME: enable this rules as an error.

        // Stylistic Issues
        'comma-spacing': [2, {
            'before': false,
            'after': true
        }],
        'comma-style': [2, 'last'],
        'indent': [2, 4, {
            'SwitchCase': 1
        }],
        'jsx-quotes': [1, 'prefer-single'],
        'linebreak-style': [2, 'unix'],
        'no-array-constructor': 2, // In almost case, we don't have to use `new Array()` without any comments.
        'no-new-object': 2, // In almost case, we don't have to use `new Object()` without any comments.
        'no-mixed-spaces-and-tabs': 2,
        'no-trailing-spaces': 2,
        'no-underscore-dangle': 0,
        'no-unneeded-ternary': 2,
        'operator-linebreak': [2, 'after'],
        'quotes': [2, 'single', 'avoid-escape'],
        'semi': [2, 'always'],
        'space-unary-ops': [2, {
            'words': true,
            'nonwords': false
        }],
        'spaced-comment': 0,

        // ECMAScript 6
        'arrow-body-style': [1, 'as-needed'],
        'arrow-parens': 1,
        'arrow-spacing': [1, {
            'before': true,
            'after': true
        }],
        'constructor-super': 2,
        'generator-star-spacing': [2, {
            'before': false,
            'after': true
        }],
        'no-arrow-condition': 2,
        'no-class-assign': 2,
        'no-const-assign': 2,
        'no-dupe-class-members': 2,
        'no-this-before-super': 2,
        'no-var': 1,
        'object-shorthand': 0,
        'prefer-const': 1,
        'prefer-reflect': 1,
        'prefer-spread': 1,
        'require-yield': 2,

        // ESLint-plugin-React
        // https://github.com/yannickcr/eslint-plugin-react
        'react/display-name': 0, // JSX transpiler creates displayName automatically.
        'react/forbid-prop-types': 0,
        'react/jsx-boolean-value': [2, 'always'], // Force boolean attribute explicitly.
        'react/jsx-closing-bracket-location': 0,
        'react/jsx-curly-spacing': 1,
        'react/jsx-indent-props': 0,
        'react/jsx-key': 1,
        'react/jsx-max-props-per-line': 0,
        'react/jsx-no-bind': 2,
        'react/jsx-no-duplicate-props': 2,
        'react/jsx-no-literals': 0,
        'react/jsx-no-undef': 2,
        'react/jsx-sort-props': 0,
        'react/jsx-sort-prop-types': [0, {
            'callbacksLast': true
        }],
        'react/jsx-uses-react': 1,
        'react/jsx-uses-vars': 1,
        'react/jsx-pascal-case': 2,
        'react/no-danger': 1,
        'react/no-did-mount-set-state': [1, 'allow-in-func'],
        'react/no-did-update-set-state': [1, 'allow-in-func'],
        'react/no-direct-mutation-state': 1,
        'react/no-multi-comp': 0,
        'react/no-set-state': 0, // FIXME: Enable this rule as a waring
        'react/no-unknown-property': 2,
        'react/prefer-es6-class': 2,
        'react/prop-types': 1,
        'react/react-in-jsx-scope': 1,
        'react/require-extension': 0,
        'react/self-closing-comp': 2,
        'react/sort-comp': [1, {
            'order': [
                'constructor',
                'metadata',
                'rendering',
                'lifecycle',
                'everything-else'
            ],
            'groups': {
                'metadata': [
                    'displayName',
                    'propTypes',
                    'contextTypes',
                    'childContextTypes',
                    'mixins',
                    'getDefaultProps',
                    'getInitialState',
                    'getChildContext'
                ],
                'rendering': [
                    'render',
                    '/^render.+$/'
                ]
            }
        }],
        'react/wrap-multilines': 2
    }
};
<commit_msg>eslint: Enable no-script-url.<commit_after>/**
 * @license MIT License
 *
 * Copyright (c) 2015 Tetsuharu OHZEKI <saneyuki.snyk@gmail.com>
 * Copyright (c) 2015 Yusuke Suzuki <utatane.tea@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
/*eslint quote-props: [2, "always"] */

'use strict';

// ESLint Configuration Files enables to include comments.
// http://eslint.org/docs/configuring/#comments-in-configuration-files
module.exports = {
    'extends': 'eslint:recommended',

    'ecmaFeatures': {
        'arrowFunctions': true,
        'blockBindings': true,
        'classes': true,
        'objectLiteralComputedProperties': true,
        'objectLiteralDuplicateProperties': true,
        'objectLiteralShorthandMethods': true,
        'objectLiteralShorthandProperties': true,
        'templateStrings': true,
        'spread': true
    },

    'env': {
        'node': true
    },

    'plugins': [
        'react' // for React/JSX
    ],

    'root': true,

    'rules': {
        // Possible Errors
        'comma-dangle': [0, 'never'],
        'no-constant-condition': 1,
        'no-console': 0,
        'no-debugger': 1,
        'no-dupe-keys': 2,
        'no-ex-assign': 2,
        'no-extra-boolean-cast': 0,
        'no-extra-parens': 0,
        'no-extra-semi': 1,
        'no-func-assign': 2,
        'no-sparse-arrays': 2,
        'no-unexpected-multiline': 1,
        'no-unreachable': 1,
        'valid-jsdoc': [2, {
            'requireReturn': true,
            'requireParamDescription': false,
            'requireReturnDescription': false
        }],
        'valid-typeof': 2,

        // Best Practices
        'block-scoped-var': 1,
        'consistent-return': 2,
        'curly': 2,
        'eqeqeq': 2,
        'no-alert': 1,
        'no-caller': 2,
        'no-case-declarations': 2,
        'no-div-regex': 2,
        'no-empty-pattern': 2,
        'no-eq-null': 2,
        'no-eval': 2,
        'no-fallthrough': 2,
        'no-implied-eval': 2,
        'no-invalid-this': 1,
        'no-new-func': 1,
        'no-new-wrappers': 2,
        'no-param-reassign': [1, {
            'props': true
        }],
        'no-throw-literal': 2,
        'no-unused-expressions': 2,
        'no-useless-call': 1,
        'no-useless-concat': 1,
        'no-script-url': 2,
        'no-with': 2,
        'radix': 2,

        // Strict Mode
        'strict': [2, 'global'],

        // Variables
        'init-declarations': [2, 'always'],
        'no-shadow': 0,
        'no-unused-vars': 0,
        'no-use-before-define': 0,

        // Node.js
        'global-require': 2,
        'no-mixed-requires': [2, {
            'grouping': true,
        }],
        'no-new-require': 2,
        'no-path-concat': 2,
        'no-process-exit': 0,
        'no-sync': 1, // Bann to use sync method. FIXME: enable this rules as an error.

        // Stylistic Issues
        'comma-spacing': [2, {
            'before': false,
            'after': true
        }],
        'comma-style': [2, 'last'],
        'indent': [2, 4, {
            'SwitchCase': 1
        }],
        'jsx-quotes': [1, 'prefer-single'],
        'linebreak-style': [2, 'unix'],
        'no-array-constructor': 2, // In almost case, we don't have to use `new Array()` without any comments.
        'no-new-object': 2, // In almost case, we don't have to use `new Object()` without any comments.
        'no-mixed-spaces-and-tabs': 2,
        'no-trailing-spaces': 2,
        'no-underscore-dangle': 0,
        'no-unneeded-ternary': 2,
        'operator-linebreak': [2, 'after'],
        'quotes': [2, 'single', 'avoid-escape'],
        'semi': [2, 'always'],
        'space-unary-ops': [2, {
            'words': true,
            'nonwords': false
        }],
        'spaced-comment': 0,

        // ECMAScript 6
        'arrow-body-style': [1, 'as-needed'],
        'arrow-parens': 1,
        'arrow-spacing': [1, {
            'before': true,
            'after': true
        }],
        'constructor-super': 2,
        'generator-star-spacing': [2, {
            'before': false,
            'after': true
        }],
        'no-arrow-condition': 2,
        'no-class-assign': 2,
        'no-const-assign': 2,
        'no-dupe-class-members': 2,
        'no-this-before-super': 2,
        'no-var': 1,
        'object-shorthand': 0,
        'prefer-const': 1,
        'prefer-reflect': 1,
        'prefer-spread': 1,
        'require-yield': 2,

        // ESLint-plugin-React
        // https://github.com/yannickcr/eslint-plugin-react
        'react/display-name': 0, // JSX transpiler creates displayName automatically.
        'react/forbid-prop-types': 0,
        'react/jsx-boolean-value': [2, 'always'], // Force boolean attribute explicitly.
        'react/jsx-closing-bracket-location': 0,
        'react/jsx-curly-spacing': 1,
        'react/jsx-indent-props': 0,
        'react/jsx-key': 1,
        'react/jsx-max-props-per-line': 0,
        'react/jsx-no-bind': 2,
        'react/jsx-no-duplicate-props': 2,
        'react/jsx-no-literals': 0,
        'react/jsx-no-undef': 2,
        'react/jsx-sort-props': 0,
        'react/jsx-sort-prop-types': [0, {
            'callbacksLast': true
        }],
        'react/jsx-uses-react': 1,
        'react/jsx-uses-vars': 1,
        'react/jsx-pascal-case': 2,
        'react/no-danger': 1,
        'react/no-did-mount-set-state': [1, 'allow-in-func'],
        'react/no-did-update-set-state': [1, 'allow-in-func'],
        'react/no-direct-mutation-state': 1,
        'react/no-multi-comp': 0,
        'react/no-set-state': 0, // FIXME: Enable this rule as a waring
        'react/no-unknown-property': 2,
        'react/prefer-es6-class': 2,
        'react/prop-types': 1,
        'react/react-in-jsx-scope': 1,
        'react/require-extension': 0,
        'react/self-closing-comp': 2,
        'react/sort-comp': [1, {
            'order': [
                'constructor',
                'metadata',
                'rendering',
                'lifecycle',
                'everything-else'
            ],
            'groups': {
                'metadata': [
                    'displayName',
                    'propTypes',
                    'contextTypes',
                    'childContextTypes',
                    'mixins',
                    'getDefaultProps',
                    'getInitialState',
                    'getChildContext'
                ],
                'rendering': [
                    'render',
                    '/^render.+$/'
                ]
            }
        }],
        'react/wrap-multilines': 2
    }
};
<|endoftext|>


<commit_before>/*!
 * KBPOnline
 * Author: Arun Chaganty, Ashwin Paranjape
 * Licensed under the MIT license
 */

define(['jquery', '../util'], function ($, util) {
  var RemoveSpanWidget = function(elem, cb) {
    var self = this;
    this.elem = elem;

    util.getDOMFromTemplate('/static/kbpo/html/RemoveSpanWidget.html', function(elem_) {
      self.elem.find("#remove-span").on("click.kbpo.RemoveSpanWidget", function(evt) {
        self.clickListeners.forEach(function (cb) {cb(true);});
      });

      cb();
    });
  };
  RemoveSpanWidget.prototype.clickListeners = [];
  RemoveSpanWidget.prototype.activate = function() {
    this.elem.removeClass("hidden");
  };
  RemoveSpanWidget.prototype.deactivate = function() {
    this.elem.addClass("hidden");
  };
  return RemoveSpanWidget;
});
<commit_msg>Fixed bug in removing span<commit_after>/*!
 * KBPOnline
 * Author: Arun Chaganty, Ashwin Paranjape
 * Licensed under the MIT license
 */

define(['jquery', '../util'], function ($, util) {
  var RemoveSpanWidget = function(elem, cb) {
    var self = this;
    this.elem = elem;

    util.getDOMFromTemplate('/static/kbpo/html/RemoveSpanWidget.html', function(elem_) {
      self.elem.html(elem_.html());
      self.elem.find("#remove-span").on("click.kbpo.RemoveSpanWidget", function(evt) {
        self.clickListeners.forEach(function (cb) {cb(true);});
      });

      cb();
    });
  };
  RemoveSpanWidget.prototype.clickListeners = [];
  RemoveSpanWidget.prototype.activate = function() {
    this.elem.removeClass("hidden");
  };
  RemoveSpanWidget.prototype.deactivate = function() {
    this.elem.addClass("hidden");
  };
  return RemoveSpanWidget;
});
<|endoftext|>


<commit_before>//TODO: Change these for actual group names

var groups = ['Group A', 'Group B','Group C'];
var activities = ['Outdoor recreation', 'Stretching/resistence training', 'Sensory stimulation',
            'Pet therapy','Gardening', 'Sewing','Painting'];

var facilitatorRoles = ['Caregiver', 'Volunteer', 'Family', 'Self'];

function randomDate(start, end) {
  return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}

function insert(collection, args, amount, insertFunctionOutcome) {
  //make copy of the object so we can get different faker data every time
  var argsWithValues;
  for (var i = 0; i < amount; i++) {
     argsWithValues = Object.assign({},args);

    for (var key in args) {
      if (insertFunctionOutcome) {
        if (typeof args[key] === 'function') {
          var func = args[key];
          argsWithValues[key] = func();
        }
      }
    }
    collection.insert(argsWithValues);

  }
}
function createMockGroups () {
  console.log('Creating mock groups');

  for (var i = 0; i < groups.length; i++) {
    var groupName = groups[i];
    console.log(groupName);
    Groups.insert({'name': groupName});
  }
}

function createMockRoles() {
  console.log('Creating mock roles');

  for (var i = 0; i < facilitatorRoles.length; i++) {
    var roleName = facilitatorRoles[i];
    console.log(roleName);
    Roles.createRole(roleName);
  }
}

function createMockHomes() {
  console.log('Creating mock homes');
  var amount = 3;
  var address = function() {return faker.address.city();};

  for (var i = 0; i < groups.length; i++) {
    var groupName = groups[i];
    console.log(groupName);
    var Group = Groups.findOne({'name': groupName});
    var args = {'name': address,'groupId': Group._id};
    insert(Homes, args, amount, true);
  }

}

function createMockResidents() {
  console.log('Creating mock residents');
  var amount = 6;
  var homes = Homes.find().fetch();
  var firstName = function() {return faker.name.firstName();};
  var lastInitial =  function() {return faker.name.lastName().charAt(0);};
  for (var i = 0; i < homes.length; i++) {
    var args = {'firstName': firstName, 'lastInitial': lastInitial, 'homeId': homes[i]._id};
    insert(Residents, args, amount,true);
  }

}
function createMockActivityTypes() {
  console.log('Creating mock activiity types');
  for (var i = 0; i < activities.length; i++) {
    ActivityTypes.insert({'name': activities[i]});
  }
}

function createMockActivities() {
  console.log('Creating mock activies');
  // Number of activities to create per resident
  var amount =  25;

  // Number, in days, for the earliest activity date
  var earliestActivityDate = 30;

  // Get list of residents
  var residents = Residents.find().fetch();

  // Get list of activity types
  var activityTypes = ActivityTypes.find().fetch();

  // Get a list of all roles
  var roles = Roles.getAllRoles.fetch();

  // Select a random facilitator role (ID)
  var roleId = function () {
    return roles[Math.floor(Math.random() * roles.length)]._id;
  }

  // Get a random activity type (ID)
  var activityType = function() {
    return activityTypes[Math.floor(Math.random() * activityTypes.length)]._id;
  };

  // Get random activity date
  var date = function() {
    var endDate = new Date();
    var startDate = new Date();
    startDate.setDate(endDate.getDate() - earliestActivityDate);
    return randomDate(endDate, startDate);
  };

  // Set random activity duration
  var duration = function() {
    return Math.floor((Math.random() * 60) + 1);
  };

  for (var i = 0; i < residents.length; i++) {
    var residentId = residents[i]._id;
    var args = {'activityTypeId': activityType, 'activityDate': date,'facilitatorRoleId': roleId,'duration': duration,'residentIds': [residentId]};
    insert(Activities, args, amount, true);
  }
}

Meteor.methods({
  'createMockData': function() {
    createMockGroups();
    createMockRoles();
    createMockHomes();
    createMockResidents();
    createMockActivityTypes();
    createMockActivities();
  },
  'removeAllData': function() {
    Groups._dropCollection();
    Homes._dropCollection();
    Residents._dropCollection();
    ActivityTypes._dropCollection();
    Activities._dropCollection();
  },
});
<commit_msg>Fix typo<commit_after>//TODO: Change these for actual group names

var groups = ['Group A', 'Group B','Group C'];
var activities = ['Outdoor recreation', 'Stretching/resistence training', 'Sensory stimulation',
            'Pet therapy','Gardening', 'Sewing','Painting'];

var facilitatorRoles = ['Caregiver', 'Volunteer', 'Family', 'Self'];

function randomDate(start, end) {
  return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}

function insert(collection, args, amount, insertFunctionOutcome) {
  //make copy of the object so we can get different faker data every time
  var argsWithValues;
  for (var i = 0; i < amount; i++) {
     argsWithValues = Object.assign({},args);

    for (var key in args) {
      if (insertFunctionOutcome) {
        if (typeof args[key] === 'function') {
          var func = args[key];
          argsWithValues[key] = func();
        }
      }
    }
    collection.insert(argsWithValues);

  }
}
function createMockGroups () {
  console.log('Creating mock groups');

  for (var i = 0; i < groups.length; i++) {
    var groupName = groups[i];
    console.log(groupName);
    Groups.insert({'name': groupName});
  }
}

function createMockRoles() {
  console.log('Creating mock roles');

  for (var i = 0; i < facilitatorRoles.length; i++) {
    var roleName = facilitatorRoles[i];
    console.log(roleName);
    Roles.createRole(roleName);
  }
}

function createMockHomes() {
  console.log('Creating mock homes');
  var amount = 3;
  var address = function() {return faker.address.city();};

  for (var i = 0; i < groups.length; i++) {
    var groupName = groups[i];
    console.log(groupName);
    var Group = Groups.findOne({'name': groupName});
    var args = {'name': address,'groupId': Group._id};
    insert(Homes, args, amount, true);
  }

}

function createMockResidents() {
  console.log('Creating mock residents');
  var amount = 6;
  var homes = Homes.find().fetch();
  var firstName = function() {return faker.name.firstName();};
  var lastInitial =  function() {return faker.name.lastName().charAt(0);};
  for (var i = 0; i < homes.length; i++) {
    var args = {'firstName': firstName, 'lastInitial': lastInitial, 'homeId': homes[i]._id};
    insert(Residents, args, amount,true);
  }

}
function createMockActivityTypes() {
  console.log('Creating mock activiity types');
  for (var i = 0; i < activities.length; i++) {
    ActivityTypes.insert({'name': activities[i]});
  }
}

function createMockActivities() {
  console.log('Creating mock activies');
  // Number of activities to create per resident
  var amount =  25;

  // Number, in days, for the earliest activity date
  var earliestActivityDate = 30;

  // Get list of residents
  var residents = Residents.find().fetch();

  // Get list of activity types
  var activityTypes = ActivityTypes.find().fetch();

  // Get a list of all roles
  var roles = Roles.getAllRoles().fetch();

  // Select a random facilitator role (ID)
  var roleId = function () {
    return roles[Math.floor(Math.random() * roles.length)]._id;
  }

  // Get a random activity type (ID)
  var activityType = function() {
    return activityTypes[Math.floor(Math.random() * activityTypes.length)]._id;
  };

  // Get random activity date
  var date = function() {
    var endDate = new Date();
    var startDate = new Date();
    startDate.setDate(endDate.getDate() - earliestActivityDate);
    return randomDate(endDate, startDate);
  };

  // Set random activity duration
  var duration = function() {
    return Math.floor((Math.random() * 60) + 1);
  };

  for (var i = 0; i < residents.length; i++) {
    var residentId = residents[i]._id;
    var args = {'activityTypeId': activityType, 'activityDate': date,'facilitatorRoleId': roleId,'duration': duration,'residentIds': [residentId]};
    insert(Activities, args, amount, true);
  }
}

Meteor.methods({
  'createMockData': function() {
    createMockGroups();
    createMockRoles();
    createMockHomes();
    createMockResidents();
    createMockActivityTypes();
    createMockActivities();
  },
  'removeAllData': function() {
    Groups._dropCollection();
    Homes._dropCollection();
    Residents._dropCollection();
    ActivityTypes._dropCollection();
    Activities._dropCollection();
  },
});
<|endoftext|>


<commit_before>/*
 * ba-content-massage
 * http://benalman.com/
 *
 * Copyright (c) 2012 "Cowboy" Ben Alman
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {
  grunt.initConfig({
    fetch: {
      content: {
        options: {
          src: 'http://benalman.com/ba-export.zip',
          dest: 'temp/ba-export.zip',
        }
      }
    },
    unzip: {
      content: {
        src: '<%= fetch.content.options.dest %>',
        dest: 'temp',
      }
    },
    clean: {
      dl: ['temp/ba-export*'],
      massage: ['temp/massaged'],
      www: ['temp/www'],
    },
    jshint: {
      js: {
        src: ['*.js', 'tasks/*.js'],
        options: {
          jshintrc: '.jshintrc'
        }
      }
    },
    massage: {
      posts: {
        expand: true,
        cwd: 'temp/ba-export',
        src: '*',
        dest: 'temp/massaged',
      }
    },
    build: {
      posts: {
        expand: true,
        cwd: 'temp/massaged',
        src: '*',
        dest: 'temp/www',
        ext: '.html',
      }
    },
    less: {
      options: {
        paths: ['src/less'],
      },
      'temp/www/site.css': 'src/less/site.less'
    },
    connect: {
      serve: {
        options: {
          port: 9001,
          base: 'temp/www',
          middleware: function(connect, options) {
            return [
              function(req, res, next) {
                var parts = req.url.slice(1).split('/');
                var actions = {
                  edit: function(id) {
                    grunt.log.ok('edit: ' + id);
                    grunt.util.spawn({
                      cmd: 'subl',
                      args: [
                        '-w',
                        'temp/ba-export/' + id,
                        'temp/ba-export/' + id + '/index.md',
                        'temp/massaged/' + id,
                        'temp/massaged/' + id + '/index.md'
                      ]
                    }, console.error);
                  }
                };
                var action = parts.shift();
                if (actions[action]) {
                  actions[action].apply(null, parts);
                } else {
                  next();
                }
              },
              connect.static(options.base),
              connect.directory(options.base)
            ];
          },
        }
      }
    },
    watch: {
      less: {
        options: {interrupt: true},
        files: ['src/less/**'],
        tasks: ['less'],
      },
      massage: {
        options: {interrupt: true},
        files: ['tasks/massage.js'],
        tasks: ['in', 'build'],
      },
      build: {
        options: {interrupt: true},
        files: ['src/jade/**', 'temp/massaged/**/*', 'tasks/build.js'],
        tasks: ['build'],
      },
    }
  });

  grunt.loadTasks('tasks');

  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-jade');
  grunt.loadNpmTasks('grunt-contrib-less');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-contrib-watch');

  grunt.registerTask('dl', ['clean:dl', 'fetch', 'unzip']);
  grunt.registerTask('in', ['clean:massage', 'massage']);
  grunt.registerTask('out', ['clean:www', 'build', 'less']);

  grunt.registerTask('init', ['dl', 'default']);

  grunt.registerTask('default', ['jshint', 'in', 'out', 'connect', 'watch']);
};
<commit_msg>Because @shama told me to.<commit_after>/*
 * ba-content-massage
 * http://benalman.com/
 *
 * Copyright (c) 2012 "Cowboy" Ben Alman
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {
  grunt.initConfig({
    fetch: {
      content: {
        options: {
          src: 'http://benalman.com/ba-export.zip',
          dest: 'temp/ba-export.zip',
        }
      }
    },
    unzip: {
      content: {
        src: '<%= fetch.content.options.dest %>',
        dest: 'temp',
      }
    },
    clean: {
      dl: ['temp/ba-export*'],
      massage: ['temp/massaged'],
      www: ['temp/www'],
    },
    jshint: {
      js: {
        src: ['*.js', 'tasks/*.js'],
        options: {
          jshintrc: '.jshintrc'
        }
      }
    },
    massage: {
      posts: {
        expand: true,
        cwd: 'temp/ba-export',
        src: '*',
        dest: 'temp/massaged',
      }
    },
    build: {
      posts: {
        expand: true,
        cwd: 'temp/massaged',
        src: '*',
        dest: 'temp/www',
        ext: '.html',
      }
    },
    less: {
      options: {
        paths: ['src/less'],
      },
      'temp/www/site.css': 'src/less/site.less'
    },
    connect: {
      serve: {
        options: {
          port: 9001,
          base: 'temp/www',
          middleware: function(connect, options) {
            return [
              function(req, res, next) {
                var parts = req.url.slice(1).split('/');
                var actions = {
                  edit: function(id) {
                    grunt.log.ok('edit: ' + id);
                    grunt.util.spawn({
                      cmd: 'subl',
                      args: [
                        '-w',
                        'temp/ba-export/' + id,
                        'temp/ba-export/' + id + '/index.md',
                        'temp/massaged/' + id,
                        'temp/massaged/' + id + '/index.md'
                      ]
                    }, console.error);
                  }
                };
                var action = parts.shift();
                if (actions[action]) {
                  actions[action].apply(null, parts);
                } else {
                  next();
                }
              },
              connect.static(options.base),
              connect.directory(options.base)
            ];
          },
        }
      }
    },
    watch: {
      less: {
        files: ['src/less/**'],
        tasks: ['less'],
      },
      massage: {
        files: ['tasks/massage.js'],
        tasks: ['in', 'build'],
      },
      build: {
        files: ['src/jade/**', 'temp/massaged/**/*', 'tasks/build.js'],
        tasks: ['build'],
      },
    }
  });

  grunt.loadTasks('tasks');

  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-jade');
  grunt.loadNpmTasks('grunt-contrib-less');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-contrib-watch');

  grunt.registerTask('dl', ['clean:dl', 'fetch', 'unzip']);
  grunt.registerTask('in', ['clean:massage', 'massage']);
  grunt.registerTask('out', ['clean:www', 'build', 'less']);

  grunt.registerTask('init', ['dl', 'default']);

  grunt.registerTask('default', ['jshint', 'in', 'out', 'connect', 'watch']);
};
<|endoftext|>


<commit_before>/* jshint indent: 2 */

// Generated on 2014-06-19 using generator-angular-fullstack 1.4.3
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

  // Load grunt tasks automatically
  require('load-grunt-tasks')(grunt);

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: {
      // configurable paths
      app: require('./bower.json').appPath || 'app',
      dist: 'dist'
    },
    express: {
      options: {
        port: process.env.PORT || 9000
      },
      dev: {
        options: {
          script: 'server.js',
          debug: true
        }
      },
      prod: {
        options: {
          script: 'server.js',
          node_env: 'production'
        }
      }
    },
    open: {
      server: {
        url: 'http://localhost:<%= express.options.port %>'
      }
    },
    watch: {
      js: {
        files: ['<%= yeoman.app %>/js/**/*.js'],
        tasks: ['newer:jshint:client'],
        options: {
          livereload: true
        }
      },
      jsTest: {
        files: ['test/spec/**/*.js'],
        tasks: ['newer:jshint:test', 'karma']
      },
      sass: {
        files: ['<%= yeoman.app %>/styles/**/*.{scss,sass}'],
        tasks: ['sass', 'autoprefixer']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        files: [
          '<%= yeoman.app %>/views/{,*//*}*.html',
          '{.tmp,<%= yeoman.app %>}/styles/{,*//*}*.css',
          '{.tmp,<%= yeoman.app %>}/js/{,*//*}*.js',
          '<%= yeoman.app %>/img/{,*//*}*.{png,jpg,jpeg,gif,webp,svg}'
        ],

        options: {
          livereload: true
        }
      },
      express: {
        files: [
          'server.js',
          'index.js'
        ],
        tasks: ['newer:jshint:node', 'express:dev', 'wait'],
        options: {
          livereload: true,
          nospawn: true //Without this option specified express won't be reloaded
        }
      }
    },
    jscs: {
        src: ['<%= yeoman.app %>/js/**/*.js'],
        options: {
            config: '.jscsrc',
            verbose: true // If you need output with rule names http://jscs.info/overview.html#verbose
        }
    },
    jshint: {
      options: {
        reporter: require('jshint-stylish'),
        node: true,
        bitwise: true,
        immed: true,
        indent: 4,
        latedef: true,
        newcap: true,
        noarg: true,
        quotmark: 'single',
        regexp: true,
        undef: true,
        unused: true,
        laxbreak: true
      },
      node: ['*.js'],
      client: {
        files: {
          src: ['<%= yeoman.app %>/js/**/*.js']
        },
        options: {
          browser: true,
          esnext: true,
          camelcase: true,
          strict: true,
          globalstrict: true,
          globals: {
            angular: true,
            moment: true,
            _: true,
            _s: true
          }
        }
      },
      test: {
        files: {
          src: ['test/spec/**/*.js']
        },
        options: {
          esnext: true,
          camelcase: false,
          curly: true,
          strict: true,
          globals: {
            after: false,
            afterEach: false,
            angular: false,
            before: false,
            beforeEach: false,
            browser: false,
            describe: false,
            expect: false,
            inject: false,
            it: false,
            jasmine: false,
            spyOn: false
          }
        }
      }
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= yeoman.dist %>/*'
          ]
        }]
      },
      server: '.tmp'
    },

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['last 1 version', 'firefox >= 20']
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Debugging with node inspector
    'node-inspector': {
      custom: {
        options: {
          'web-host': 'localhost'
        }
      }
    },

    // Use nodemon to run server in debug mode with an initial breakpoint
    nodemon: {
      debug: {
        script: 'server.js',
        options: {
          nodeArgs: ['--debug-brk'],
          env: {
            PORT: process.env.PORT || 9000
          },
          callback: function (nodemon) {
            nodemon.on('log', function (event) {
              console.log(event.colour);
            });

            // opens browser on initial server start
            nodemon.on('config:update', function () {
              setTimeout(function () {
                require('open')('http://localhost:8080/debug?port=5858');
              }, 500);
            });
          }
        }
      }
    },

    // Automatically inject Bower components into the app
    'bower-install': {
      app: {
        html: '<%= yeoman.app %>/views/front.html',
        ignorePath: '<%= yeoman.app %>/',
        exclude: ['bootstrap-sass', 'jquery']
      }
    },

    // Compiles Sass to CSS and generates necessary files if requested
    sass: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/styles',
          src: '**/*.scss',
          dest: 'dist/styles',
          ext: '.css'
        }],
        options: {
          includePaths: ['<%= yeoman.app %>/bower_components']
        }
      }
    },

    // Renames files for browser caching purposes
    rev: {
      dist: {
        files: {
          src: [
            '<%= yeoman.dist %>/js/{,*/}*.js',
            '<%= yeoman.dist %>/styles/{,*/}*.css',
            '<%= yeoman.dist %>/styles/fonts/*'
          ]
        }
      }
    },

    // Reads HTML for usemin blocks to enable smart builds that automatically
    // concat, minify and revision files. Creates configurations in memory so
    // additional tasks can operate on them
    useminPrepare: {
      html: ['<%= yeoman.app %>/views/front.html', '<%= yeoman.app %>/views/embed.html'],
      options: {
        dest: '<%= yeoman.dist %>'
      }
    },

    // Performs rewrites based on rev and the useminPrepare configuration
    usemin: {
      html: ['<%= yeoman.dist %>/views/{,*/}*.html'],
      options: {
        assetsDirs: ['<%= yeoman.dist %>']
      }
    },

    htmlmin: {
      dist: {
        options: {
          //collapseWhitespace: true,
          //collapseBooleanAttributes: true,
          //removeCommentsFromCDATA: true,
          //removeOptionalTags: true
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/views',
          src: ['*.html', 'partials/**/*.html'],
          dest: '<%= yeoman.dist %>/views'
        }]
      }
    },

    // Allow the use of non-minsafe AngularJS files. Automatically makes it
    // minsafe compatible so Uglify does not destroy the ng references
    ngAnnotate: {
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/concat/js',
          src: '*.js',
          dest: '.tmp/concat/js'
        }]
      }
    },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            'bower_components/**/*',
            'img/{,*/}*.{png,jpg,jpeg,gif}',
            'fonts/**/*',
            'resources/**/*',
            'documents/**/*',
            'styles/**/*.css'
          ]
        }, {
          expand: true,
          cwd: '.tmp/img',
          dest: '<%= yeoman.dist %>/img',
          src: ['generated/*']
        }]
      }
    },

    // Run some tasks in parallel to speed up the build process
    concurrent: {
      server: [
        'sass'
      ],
      test: [
        'sass'
      ],
      debug: {
        tasks: [
          'nodemon',
          'node-inspector'
        ],
        options: {
          logConcurrentOutput: true
        }
      },
      dist: [
        'sass:dist',
        'htmlmin'
      ]
    },

    // Test settings
    karma: {
      unit: {
        configFile: 'karma.conf.js',
        singleRun: true
      }
    },

    env: {
      test: {
        NODE_ENV: 'test'
      }
    },

    htmlrefs: {
      dist: {
        src: './dist/views/front.html',
        dest: './dist/views/front.html',
        options: {
          includes: {
            piwik: './piwik.inc'
          }
        }
      }
    }
  });

  // Used for delaying livereload until after server has restarted
  grunt.registerTask('wait', function () {
    grunt.log.ok('Waiting for server reload…');

    var done = this.async();

    setTimeout(function () {
      grunt.log.writeln('Done waiting!');
      done();
    }, 500);
  });

  grunt.registerTask('express-keepalive', 'Keep grunt running', function() {
    this.async();
  });

  grunt.registerTask('serve', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'express:prod', 'open', 'express-keepalive']);
    }

    if (target === 'debug') {
      return grunt.task.run([
        'clean:server',
        'bower-install',
        'concurrent:server',
        'autoprefixer',
        'concurrent:debug'
      ]);
    }

    grunt.task.run([
      'clean:server',
      'bower-install',
      'concurrent:server',
      'autoprefixer',
      'express:dev',
      'open',
      'watch'
    ]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'karma'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'bower-install',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'ngAnnotate',
    'copy:dist',
    'uglify',
    'rev',
    'usemin',
    'htmlrefs:dist'
  ]);

  grunt.registerTask('default', [
    'jshint',
    'jscs',
    'test',
    'build'
  ]);
};
<commit_msg>Remove grunt serve dist option<commit_after>/* jshint indent: 2 */

// Generated on 2014-06-19 using generator-angular-fullstack 1.4.3
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

  // Load grunt tasks automatically
  require('load-grunt-tasks')(grunt);

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: {
      // configurable paths
      app: require('./bower.json').appPath || 'app',
      dist: 'dist'
    },
    express: {
      options: {
        port: process.env.PORT || 9000
      },
      dev: {
        options: {
          script: 'server.js',
          debug: true
        }
      }
    },
    open: {
      server: {
        url: 'http://localhost:<%= express.options.port %>'
      }
    },
    watch: {
      js: {
        files: ['<%= yeoman.app %>/js/**/*.js'],
        tasks: ['newer:jshint:client'],
        options: {
          livereload: true
        }
      },
      jsTest: {
        files: ['test/spec/**/*.js'],
        tasks: ['newer:jshint:test', 'karma']
      },
      sass: {
        files: ['<%= yeoman.app %>/styles/**/*.{scss,sass}'],
        tasks: ['sass', 'autoprefixer']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        files: [
          '<%= yeoman.app %>/views/{,*//*}*.html',
          '{.tmp,<%= yeoman.app %>}/styles/{,*//*}*.css',
          '{.tmp,<%= yeoman.app %>}/js/{,*//*}*.js',
          '<%= yeoman.app %>/img/{,*//*}*.{png,jpg,jpeg,gif,webp,svg}'
        ],

        options: {
          livereload: true
        }
      },
      express: {
        files: [
          'server.js',
          'index.js'
        ],
        tasks: ['newer:jshint:node', 'express:dev', 'wait'],
        options: {
          livereload: true,
          nospawn: true //Without this option specified express won't be reloaded
        }
      }
    },
    jscs: {
        src: ['<%= yeoman.app %>/js/**/*.js'],
        options: {
            config: '.jscsrc',
            verbose: true // If you need output with rule names http://jscs.info/overview.html#verbose
        }
    },
    jshint: {
      options: {
        reporter: require('jshint-stylish'),
        node: true,
        bitwise: true,
        immed: true,
        indent: 4,
        latedef: true,
        newcap: true,
        noarg: true,
        quotmark: 'single',
        regexp: true,
        undef: true,
        unused: true,
        laxbreak: true
      },
      node: ['*.js'],
      client: {
        files: {
          src: ['<%= yeoman.app %>/js/**/*.js']
        },
        options: {
          browser: true,
          esnext: true,
          camelcase: true,
          strict: true,
          globalstrict: true,
          globals: {
            angular: true,
            moment: true,
            _: true,
            _s: true
          }
        }
      },
      test: {
        files: {
          src: ['test/spec/**/*.js']
        },
        options: {
          esnext: true,
          camelcase: false,
          curly: true,
          strict: true,
          globals: {
            after: false,
            afterEach: false,
            angular: false,
            before: false,
            beforeEach: false,
            browser: false,
            describe: false,
            expect: false,
            inject: false,
            it: false,
            jasmine: false,
            spyOn: false
          }
        }
      }
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= yeoman.dist %>/*'
          ]
        }]
      },
      server: '.tmp'
    },

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['last 1 version', 'firefox >= 20']
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Debugging with node inspector
    'node-inspector': {
      custom: {
        options: {
          'web-host': 'localhost'
        }
      }
    },

    // Use nodemon to run server in debug mode with an initial breakpoint
    nodemon: {
      debug: {
        script: 'server.js',
        options: {
          nodeArgs: ['--debug-brk'],
          env: {
            PORT: process.env.PORT || 9000
          },
          callback: function (nodemon) {
            nodemon.on('log', function (event) {
              console.log(event.colour);
            });

            // opens browser on initial server start
            nodemon.on('config:update', function () {
              setTimeout(function () {
                require('open')('http://localhost:8080/debug?port=5858');
              }, 500);
            });
          }
        }
      }
    },

    // Automatically inject Bower components into the app
    'bower-install': {
      app: {
        html: '<%= yeoman.app %>/views/front.html',
        ignorePath: '<%= yeoman.app %>/',
        exclude: ['bootstrap-sass', 'jquery']
      }
    },

    // Compiles Sass to CSS and generates necessary files if requested
    sass: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/styles',
          src: '**/*.scss',
          dest: 'dist/styles',
          ext: '.css'
        }],
        options: {
          includePaths: ['<%= yeoman.app %>/bower_components']
        }
      }
    },

    // Renames files for browser caching purposes
    rev: {
      dist: {
        files: {
          src: [
            '<%= yeoman.dist %>/js/{,*/}*.js',
            '<%= yeoman.dist %>/styles/{,*/}*.css',
            '<%= yeoman.dist %>/styles/fonts/*'
          ]
        }
      }
    },

    // Reads HTML for usemin blocks to enable smart builds that automatically
    // concat, minify and revision files. Creates configurations in memory so
    // additional tasks can operate on them
    useminPrepare: {
      html: ['<%= yeoman.app %>/views/front.html', '<%= yeoman.app %>/views/embed.html'],
      options: {
        dest: '<%= yeoman.dist %>'
      }
    },

    // Performs rewrites based on rev and the useminPrepare configuration
    usemin: {
      html: ['<%= yeoman.dist %>/views/{,*/}*.html'],
      options: {
        assetsDirs: ['<%= yeoman.dist %>']
      }
    },

    htmlmin: {
      dist: {
        options: {
          //collapseWhitespace: true,
          //collapseBooleanAttributes: true,
          //removeCommentsFromCDATA: true,
          //removeOptionalTags: true
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/views',
          src: ['*.html', 'partials/**/*.html'],
          dest: '<%= yeoman.dist %>/views'
        }]
      }
    },

    // Allow the use of non-minsafe AngularJS files. Automatically makes it
    // minsafe compatible so Uglify does not destroy the ng references
    ngAnnotate: {
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/concat/js',
          src: '*.js',
          dest: '.tmp/concat/js'
        }]
      }
    },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            'bower_components/**/*',
            'img/{,*/}*.{png,jpg,jpeg,gif}',
            'fonts/**/*',
            'resources/**/*',
            'documents/**/*',
            'styles/**/*.css'
          ]
        }, {
          expand: true,
          cwd: '.tmp/img',
          dest: '<%= yeoman.dist %>/img',
          src: ['generated/*']
        }]
      }
    },

    // Run some tasks in parallel to speed up the build process
    concurrent: {
      server: [
        'sass'
      ],
      test: [
        'sass'
      ],
      debug: {
        tasks: [
          'nodemon',
          'node-inspector'
        ],
        options: {
          logConcurrentOutput: true
        }
      },
      dist: [
        'sass:dist',
        'htmlmin'
      ]
    },

    // Test settings
    karma: {
      unit: {
        configFile: 'karma.conf.js',
        singleRun: true
      }
    },

    env: {
      test: {
        NODE_ENV: 'test'
      }
    },

    htmlrefs: {
      dist: {
        src: './dist/views/front.html',
        dest: './dist/views/front.html',
        options: {
          includes: {
            piwik: './piwik.inc'
          }
        }
      }
    }
  });

  // Used for delaying livereload until after server has restarted
  grunt.registerTask('wait', function () {
    grunt.log.ok('Waiting for server reload…');

    var done = this.async();

    setTimeout(function () {
      grunt.log.writeln('Done waiting!');
      done();
    }, 500);
  });

  grunt.registerTask('serve', function (target) {
    if (target === 'debug') {
      return grunt.task.run([
        'clean:server',
        'bower-install',
        'concurrent:server',
        'autoprefixer',
        'concurrent:debug'
      ]);
    }

    grunt.task.run([
      'clean:server',
      'bower-install',
      'concurrent:server',
      'autoprefixer',
      'express:dev',
      'open',
      'watch'
    ]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'karma'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'bower-install',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'ngAnnotate',
    'copy:dist',
    'uglify',
    'rev',
    'usemin',
    'htmlrefs:dist'
  ]);

  grunt.registerTask('default', [
    'jshint',
    'jscs',
    'test',
    'build'
  ]);
};
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2016 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import React from 'react'
import ReactDOM from 'react-dom'
import TestUtils from 'react-addons-test-utils'
import SwitchEditorControl from 'jsx/editor/SwitchEditorControl'
import RichContentEditor from 'jsx/shared/rce/RichContentEditor'

QUnit.module('SwitchEditorControl', {
  setup() {
    sinon.stub(RichContentEditor, 'callOnRCE')
  },

  teardown() {
    RichContentEditor.callOnRCE.restore()
  }
})

test('changes text on each click', () => {
  const textarea = {}
  const element = React.createElement(SwitchEditorControl, {textarea})
  const component = TestUtils.renderIntoDocument(element)
  const link = TestUtils.findRenderedDOMComponentWithTag(component, 'a')
  equal(link.props.className, 'switch-views__link__html')
  TestUtils.Simulate.click(ReactDOM.findDOMNode(link))
  equal(link.props.className, 'switch-views__link__rce')
})

test('passes textarea through to editor for toggling', () => {
  const textarea = {id: 'the text area'}
  const element = React.createElement(SwitchEditorControl, {textarea})
  const component = TestUtils.renderIntoDocument(element)
  const link = TestUtils.findRenderedDOMComponentWithTag(component, 'a')
  TestUtils.Simulate.click(ReactDOM.findDOMNode(link))
  ok(RichContentEditor.callOnRCE.calledWith(textarea))
})
<commit_msg>Spec: fix SwitchEditorControlSpec to work w/ react 15<commit_after>/*
 * Copyright (C) 2016 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import React from 'react'
import ReactDOM from 'react-dom'
import TestUtils from 'react-addons-test-utils'
import SwitchEditorControl from 'jsx/editor/SwitchEditorControl'
import RichContentEditor from 'jsx/shared/rce/RichContentEditor'

QUnit.module('SwitchEditorControl', {
  setup() {
    sinon.stub(RichContentEditor, 'callOnRCE')
  },

  teardown() {
    RichContentEditor.callOnRCE.restore()
  }
})

test('changes text on each click', () => {
  const textarea = {}
  const element = React.createElement(SwitchEditorControl, {textarea})
  const component = TestUtils.renderIntoDocument(element)
  const link = TestUtils.findRenderedDOMComponentWithTag(component, 'a')
  equal(link.className, 'switch-views__link__html')
  TestUtils.Simulate.click(ReactDOM.findDOMNode(link))
  equal(link.className, 'switch-views__link__rce')
})

test('passes textarea through to editor for toggling', () => {
  const textarea = {id: 'the text area'}
  const element = React.createElement(SwitchEditorControl, {textarea})
  const component = TestUtils.renderIntoDocument(element)
  const link = TestUtils.findRenderedDOMComponentWithTag(component, 'a')
  TestUtils.Simulate.click(ReactDOM.findDOMNode(link))
  ok(RichContentEditor.callOnRCE.calledWith(textarea))
})
<|endoftext|>


<commit_before>import express from 'express';
import userController from '../controllers/userController';
// import documentController from '../controllers/documentController';
import auth from '../middleware/auth';
// import utils    from '../middlewares/utils';

const user = express.Router();

user.route('/api/user')
  .get(auth.verifyToken, auth.adminAccess, userController.getAllUsers)
  .post(auth.verifyToken, userController.createUser);

user.route('/api/user/profile')
  .get(auth.verifyToken, userController.getProfile);

user.route('/api/user/admin')
  .get(auth.verifyToken, auth.adminAccess, userController.getAllAdmin)
  .post(auth.verifyToken, auth.adminAccess, userController.createUser);

user.route('/api/user/regular')
  .get(auth.verifyToken, userController.getAllRegular)
  .post(auth.verifyToken, userController.createUser);

user.route('/api/user/:id')
  .get(auth.verifyToken, userController.getUser)
  .put(auth.verifyToken, userController.updateUser)
  .delete(auth.verifyToken, userController.deleteUser);

// user.route('/api/user/:id/documents')
  // .all(auth.verifyToken)
//   .get(documentsController.getUserDocuments);

user.route('/api/user/login')
  .post(userController.login);

// user.route('/api/user/logout')
//   .post(auth.verifyToken, userController.logout);

module.exports = () => user;
<commit_msg>remove token verification from createuser<commit_after>import express from 'express';
import userController from '../controllers/userController';
// import documentController from '../controllers/documentController';
import auth from '../middleware/auth';
// import utils    from '../middlewares/utils';

const user = express.Router();

user.route('/api/user')
  .get(auth.verifyToken, auth.adminAccess, userController.getAllUsers)
  .post(userController.createUser);

user.route('/api/user/profile')
  .get(auth.verifyToken, userController.getProfile);

user.route('/api/user/admin')
  .get(auth.verifyToken, auth.adminAccess, userController.getAllAdmin)
  .post(auth.verifyToken, auth.adminAccess, userController.createUser);

user.route('/api/user/regular')
  .get(auth.verifyToken, userController.getAllRegular)
  .post(auth.verifyToken, userController.createUser);

user.route('/api/user/:id')
  .get(auth.verifyToken, userController.getUser)
  .put(auth.verifyToken, userController.updateUser)
  .delete(auth.verifyToken, userController.deleteUser);

// user.route('/api/user/:id/documents')
  // .all(auth.verifyToken)
//   .get(documentsController.getUserDocuments);

user.route('/api/user/login')
  .post(userController.login);

// user.route('/api/user/logout')
//   .post(auth.verifyToken, userController.logout);

module.exports = () => user;
<|endoftext|>


<commit_before>// Angular controller for room.html
angular.module('replyCtrl', [])

.controller('replyController', function (Replies, Rooms, $rootScope, $stateParams) {

  var vm = this;
  vm.org = $stateParams.org;
  // Value for toggling the reply option.
  vm.isReplying = false;
  // Gets the current user's username.
  vm.user = $rootScope.logInfo;
  vm.replyusername = vm.user.username;
  vm.profileImg = vm.user.pictureUrl;

  // Toggle to show the reply input box
  vm.toggleReplying = function() {
    this.isReplying = !(this.isReplying);
  };

  // Add reply to the current message
  vm.addReply = function (e, index) {
    if (e.keyCode === 13) {
      var roomName = Rooms.getCurrentName(vm.org);
      var userName = vm.replyusername || 'anon';
      Replies.addReply(userName, vm.profileImg, vm.replytext, index, roomName, vm.org);
      vm.replytext = '';
    }
  };

});

<commit_msg>(fix) reply message bug<commit_after>// Angular controller for room.html
angular.module('replyCtrl', [])

.controller('replyController', function (Replies, Rooms, $rootScope, $stateParams) {

  var vm = this;
  vm.org = $stateParams.org;
  vm.roomname = $stateParams.roomName;
  // Value for toggling the reply option.
  vm.isReplying = false;
  // Gets the current user's username.
  vm.user = $rootScope.logInfo;
  vm.replyusername = vm.user.username;
  vm.profileImg = vm.user.pictureUrl;

  // Toggle to show the reply input box
  vm.toggleReplying = function() {
    this.isReplying = !(this.isReplying);
  };

  // Add reply to the current message
  vm.addReply = function (e, index) {
    if (e.keyCode === 13) {
      Replies.addReply(vm.replyusername, vm.profileImg, vm.replytext, index, vm.roomname, vm.org);
      vm.replytext = '';
    }
  };

});

<|endoftext|>


<commit_before>var build = require('./build.js'),
    Promise = require('es6-promise').Promise,
    path = require('path'),
    config = require('./config.js');

module.exports = {
    getAsset: function(filePath, wrap) {
        filePath = path.resolve(config.assetPath, filePath);
        return new Promise(function(resolve, reject) {
            build.makeSingleNode(filePath, wrap).then(function(assetNode) {
                resolve(assetNode.content);
            }).catch(reject);
        });
    },
    getAssetList: function(filePath) {
        filePath = path.resolve(config.assetPath, filePath);
        return new Promise(function(resolve, reject) {
            build.makeNodeList(filePath).then(function(list) {
                list = list.map(function(file) {
                    return {
                        path: file.relativePath(),
                        wrap: file.wrap
                    };
                });
                resolve(list);
            }).catch(reject);
        });
    },
    bundle: function(filePath) {
        filePath = path.resolve(config.assetPath, filePath);
        return build.makeBundle(filePath);
    },
    config: function() {
        return config;
    },
    /**
     * @param {Array} filePaths list of file paths to include in build.
     * every file will generate it's dependency tree and modules list.
     * resulting value will be map of modules and corresponding bundle names
     * @example
     *  {
     *      "module1": "bundle1.js",
     *      "module2": "bundle1.js",
     *      "module3": "bundle2.js"
     *  }
     */
    manifest: function(filePaths) {
        var _this = this,
            promises = filePaths.map(function(filePath) {
            return _this.getAssetList(filePath);
        });
        return new Promise(function(resolve, reject) {
            Promise.all(promises).then(function() {
                resolve(arguments);
            }).catch(reject);
        });
    }
};
<commit_msg>Update api.js<commit_after>var build = require('./build.js'),
    Promise = require('es6-promise').Promise,
    path = require('path'),
    config = require('./config.js');

module.exports = {
    getAsset: function(filePath, wrap) {
        filePath = path.resolve(config.assetPath, filePath);
        return new Promise(function(resolve, reject) {
            build.makeSingleNode(filePath, wrap).then(function(assetNode) {
                resolve(assetNode.content);
            }).catch(reject);
        });
    },
    getAssetList: function(filePath) {
        filePath = path.resolve(config.assetPath, filePath);
        return new Promise(function(resolve, reject) {
            build.makeNodeList(filePath).then(function(list) {
                list = list.map(function(file) {
                    return {
                        path: file.relativePath(),
                        wrap: file.wrap
                    };
                });
                resolve(list);
            }).catch(reject);
        });
    },
    bundle: function(filePath) {
        filePath = path.resolve(config.assetPath, filePath);
        return build.makeBundle(filePath);
    },
    config: function() {
        return config;
    }
};
<|endoftext|>