<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import {MenuItem, ButtonMenu, BallMenu} from 'tocco-ui'
import {FormattedMessage} from 'react-intl'
import styled from 'styled-components'

import {
  StyledHeader,
  StyledConfig,
  StyledBackgroundLogo
} from './StyledComponents'
import AboutTocco from '../AboutTocco'

const StyledBallMenuWrapper = styled.span`
  margin-top: 2px;
`

const Header = ({
  username,
  currentBusinessUnit,
  businessUnits,
  loadBusinessUnits,
  changeBusinessUnit,
  doLogout,
  runEnv,
  niceVersion,
  openModalComponent
}) => {
  const handleBusinessUnitOpen = () => {
    if (businessUnits.length === 0) {
      loadBusinessUnits()
    }
  }

  return <>
    <StyledBackgroundLogo runEnv={runEnv}/>
    <StyledHeader>
      <StyledConfig>
        <ButtonMenu label={currentBusinessUnit.label} onOpen={handleBusinessUnitOpen}>
          {
            businessUnits.map(bU =>
              <MenuItem
                key={`buMenu-${bU.id}`}
                disabled={bU.id === currentBusinessUnit.id}
                onClick={() => {
                  changeBusinessUnit(bU.id)
                }}
              >
                {bU.label}
              </MenuItem>
            )
          }
        </ButtonMenu>
        <ButtonMenu label={username}>
          <MenuItem onClick={doLogout}><FormattedMessage id="client.admin.menu.logout"/></MenuItem>
        </ButtonMenu>
        <StyledBallMenuWrapper>
          <BallMenu buttonProps={{icon: 'info'}}>
            {niceVersion && <MenuItem onClick={() => {
              window.open(
                  `https://${niceVersion.replace('.', '')}.docs.tocco.ch/de/`,
                  '_blank'
              )
            }}>
              <FormattedMessage id="client.admin.menu.doc"/>
            </MenuItem>}
            <MenuItem onClick={() => {
              window.open(
                '/nice2/swagger',
                '_blank'
              )
            }}>
              <FormattedMessage id="client.admin.menu.restDoc"/>
            </MenuItem>
            <MenuItem onClick={() => {
              openModalComponent('about', 'client.admin.menu.aboutToccoTitle', null, () => <AboutTocco/>, true)
            }}>
              <FormattedMessage id="client.admin.menu.aboutToccoTitle"/>
            </MenuItem>
          </BallMenu>
        </StyledBallMenuWrapper>
      </StyledConfig>
    </StyledHeader>
  </>
}

const bUPropType = PropTypes.shape({
  id: PropTypes.string,
  label: PropTypes.string
})

Header.propTypes = {
  username: PropTypes.string,
  currentBusinessUnit: bUPropType,
  businessUnits: PropTypes.arrayOf(bUPropType),
  doLogout: PropTypes.func.isRequired,
  changeBusinessUnit: PropTypes.func.isRequired,
  loadBusinessUnits: PropTypes.func.isRequired,
  runEnv: PropTypes.string,
  niceVersion: PropTypes.string,
  openModalComponent: PropTypes.func.isRequired
}

export default Header
<commit_msg>refactor(admin): change header ball icon<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import {MenuItem, ButtonMenu, BallMenu, StyledBall, scale} from 'tocco-ui'
import {FormattedMessage} from 'react-intl'
import styled from 'styled-components'

import {
  StyledHeader,
  StyledConfig,
  StyledBackgroundLogo
} from './StyledComponents'
import AboutTocco from '../AboutTocco'

const StyledBallMenuWrapper = styled.span`
  margin-top: 2px;

  ${StyledBall} {
    font-size: ${scale.font(1)};
  }
`

const Header = ({
  username,
  currentBusinessUnit,
  businessUnits,
  loadBusinessUnits,
  changeBusinessUnit,
  doLogout,
  runEnv,
  niceVersion,
  openModalComponent
}) => {
  const handleBusinessUnitOpen = () => {
    if (businessUnits.length === 0) {
      loadBusinessUnits()
    }
  }

  return <>
    <StyledBackgroundLogo runEnv={runEnv}/>
    <StyledHeader>
      <StyledConfig>
        <ButtonMenu label={currentBusinessUnit.label} onOpen={handleBusinessUnitOpen}>
          {
            businessUnits.map(bU =>
              <MenuItem
                key={`buMenu-${bU.id}`}
                disabled={bU.id === currentBusinessUnit.id}
                onClick={() => {
                  changeBusinessUnit(bU.id)
                }}
              >
                {bU.label}
              </MenuItem>
            )
          }
        </ButtonMenu>
        <ButtonMenu label={username}>
          <MenuItem onClick={doLogout}><FormattedMessage id="client.admin.menu.logout"/></MenuItem>
        </ButtonMenu>
        <StyledBallMenuWrapper>
          <BallMenu buttonProps={{icon: 'question-circle'}}>
            {niceVersion && <MenuItem onClick={() => {
              window.open(
                  `https://${niceVersion.replace('.', '')}.docs.tocco.ch/de/`,
                  '_blank'
              )
            }}>
              <FormattedMessage id="client.admin.menu.doc"/>
            </MenuItem>}
            <MenuItem onClick={() => {
              window.open(
                '/nice2/swagger',
                '_blank'
              )
            }}>
              <FormattedMessage id="client.admin.menu.restDoc"/>
            </MenuItem>
            <MenuItem onClick={() => {
              openModalComponent('about', 'client.admin.menu.aboutToccoTitle', null, () => <AboutTocco/>, true)
            }}>
              <FormattedMessage id="client.admin.menu.aboutToccoTitle"/>
            </MenuItem>
          </BallMenu>
        </StyledBallMenuWrapper>
      </StyledConfig>
    </StyledHeader>
  </>
}

const bUPropType = PropTypes.shape({
  id: PropTypes.string,
  label: PropTypes.string
})

Header.propTypes = {
  username: PropTypes.string,
  currentBusinessUnit: bUPropType,
  businessUnits: PropTypes.arrayOf(bUPropType),
  doLogout: PropTypes.func.isRequired,
  changeBusinessUnit: PropTypes.func.isRequired,
  loadBusinessUnits: PropTypes.func.isRequired,
  runEnv: PropTypes.string,
  niceVersion: PropTypes.string,
  openModalComponent: PropTypes.func.isRequired
}

export default Header
<|endoftext|>


<commit_before>/*!
 * micromatch <https://github.com/jonschlinkert/micromatch>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

var diff = require('arr-diff');
var debug = require('debug')('micromatch');
var typeOf = require('kind-of');
var omit = require('object.omit');
var cache = require('regex-cache');
var isGlob = require('is-glob');
var expand = require('./lib/expand');
var utils = require('./lib/utils');

/**
 * The main function. Pass an array of filepaths,
 * and a string or array of glob patterns
 *
 * @param  {Array|String} `files`
 * @param  {Array|String} `patterns`
 * @param  {Object} `opts`
 * @return {Array} Array of matches
 */

function micromatch(files, patterns, opts) {
  if (!files || !patterns) return [];
  opts = opts || {};

  if (typeof opts.cache === 'undefined') {
    opts.cache = true;
  }

  if (!Array.isArray(patterns)) {
    return match(files, patterns, opts);
  }

  var len = patterns.length, i = 0;
  var omit = [], keep = [];

  while (len--) {
    var glob = patterns[i++];
    if (glob.charCodeAt(0) === 33 /* ! */) {
      omit.push.apply(omit, match(files, glob.slice(1), opts));
    } else {
      keep.push.apply(keep, match(files, glob, opts));
    }
  }
  return diff(keep, omit);
}

/**
 * Pass an array of files and a glob pattern as a string.
 *
 * This function is called by the main `micromatch` function
 * If you only need to pass a single pattern you might get
 * very minor speed improvements using this function.
 *
 * @param  {Array} `files`
 * @param  {Array} `pattern`
 * @param  {Object} `options`
 * @return {Array}
 */

function match(files, pattern, opts) {
  if (typeOf(files) !== 'string' && !Array.isArray(files)) {
    throw new Error(msg('match', 'files', 'a string or array'));
  }

  files = utils.arrayify(files);
  opts = opts || {};

  var negate = opts.negate || false;
  var orig = pattern;

  if (typeof pattern === 'string' && opts.nonegate !== true) {
    negate = pattern.charAt(0) === '!';
    if (negate) {
      pattern = pattern.slice(1);
    }
  }

  var _isMatch = matcher(pattern, opts);
  var len = files.length, i = 0;
  var res = [];

  while (i < len) {
    var file = files[i++];
    var fp = utils.unixify(file, opts);

    if (!_isMatch(fp)) { continue; }
    res.push(fp);
  }

  if (res.length === 0) {
    if (opts.failglob === true) {
      throw new Error('micromatch.match() found no matches for: "' + orig + '".');
    }

    if (opts.nonull || opts.nullglob) {
      res.push(utils.unescapeGlob(orig));
    }
  }

  // if `negate` was defined, diff negated files
  if (negate) { res = diff(files, res); }

  // if `ignore` was defined, diff ignored filed
  if (opts.ignore && opts.ignore.length) {
    pattern = opts.ignore;
    opts = omit(opts, ['ignore']);
    return diff(res, micromatch(res, pattern, opts));
  }
  return res;
}

/**
 * Returns a function that takes a glob pattern or array of glob patterns
 * to be used with `Array#filter()`. (Internally this function generates
 * the matching function using the [matcher] method).
 *
 * ```js
 * var fn = mm.filter('[a-c]');
 * ['a', 'b', 'c', 'd', 'e'].filter(fn);
 * //=> ['a', 'b', 'c']
 * ```
 *
 * @param  {String|Array} `patterns` Can be a glob or array of globs.
 * @param  {Options} `opts` Options to pass to the [matcher] method.
 * @return {Function} Filter function to be passed to `Array#filter()`.
 */

function filter(patterns, opts) {
  if (!Array.isArray(patterns) && typeof patterns !== 'string') {
    throw new TypeError(msg('filter', 'patterns', 'a string or array'));
  }

  patterns = utils.arrayify(patterns);
  return function (fp) {
    if (fp == null) return [];
    var len = patterns.length, i = 0;
    var res = true;

    fp = utils.unixify(fp, opts);
    while (i < len) {
      var fn = matcher(patterns[i++], opts);
      if (!fn(fp)) {
        res = false;
        break;
      }
    }
    return res;
  };
}

/**
 * Returns true if the filepath contains the given
 * pattern. Can also return a function for matching.
 *
 * ```js
 * isMatch('foo.md', '*.md', {});
 * //=> true
 *
 * isMatch('*.md', {})('foo.md')
 * //=> true
 * ```
 *
 * @param  {String} `fp`
 * @param  {String} `pattern`
 * @param  {Object} `opts`
 * @return {Boolean}
 */

function isMatch(fp, pattern, opts) {
  if (typeof fp !== 'string') {
    throw new TypeError(msg('isMatch', 'filepath', 'a string'));
  }

  fp = utils.unixify(fp, opts);
  if (typeOf(pattern) === 'object') {
    return matcher(fp, pattern);
  }
  return matcher(pattern, opts)(fp);
}

/**
 * Returns true if the filepath matches the
 * given pattern.
 */

function contains(fp, pattern, opts) {
  if (typeof fp !== 'string') {
    throw new TypeError(msg('contains', 'pattern', 'a string'));
  }

  opts = opts || {};
  opts.contains = (pattern !== '');
  fp = utils.unixify(fp, opts);

  if (opts.contains && !isGlob(pattern)) {
    return fp.indexOf(pattern) !== -1;
  }
  return matcher(pattern, opts)(fp);
}

/**
 * Returns true if a file path matches any of the
 * given patterns.
 *
 * @param  {String} `fp` The filepath to test.
 * @param  {String|Array} `patterns` Glob patterns to use.
 * @param  {Object} `opts` Options to pass to the `matcher()` function.
 * @return {String}
 */

function any(fp, patterns, opts) {
  if (!Array.isArray(patterns) && typeof patterns !== 'string') {
    throw new TypeError(msg('any', 'patterns', 'a string or array'));
  }

  patterns = utils.arrayify(patterns);
  var len = patterns.length;

  fp = utils.unixify(fp, opts);
  while (len--) {
    var isMatch = matcher(patterns[len], opts);
    if (isMatch(fp)) {
      return true;
    }
  }
  return false;
}

/**
 * Filter the keys of an object with the given `glob` pattern
 * and `options`
 *
 * @param  {Object} `object`
 * @param  {Pattern} `object`
 * @return {Array}
 */

function matchKeys(obj, glob, options) {
  if (typeOf(obj) !== 'object') {
    throw new TypeError(msg('matchKeys', 'first argument', 'an object'));
  }

  var fn = matcher(glob, options);
  var res = {};

  for (var key in obj) {
    if (obj.hasOwnProperty(key) && fn(key)) {
      res[key] = obj[key];
    }
  }
  return res;
}

/**
 * Return a function for matching based on the
 * given `pattern` and `options`.
 *
 * @param  {String} `pattern`
 * @param  {Object} `options`
 * @return {Function}
 */

function matcher(pattern, opts) {
  // pattern is a function
  if (typeof pattern === 'function') {
    return pattern;
  }
  // pattern is a regex
  if (pattern instanceof RegExp) {
    return function(fp) {
      return pattern.test(fp);
    };
  }

  // strings, all the way down...
  pattern = utils.unixify(pattern, opts);

  // pattern is a non-glob string
  if (!isGlob(pattern)) {
    return utils.matchPath(pattern, opts);
  }
  // pattern is a glob string
  var re = makeRe(pattern, opts);

  // `matchBase` is defined
  if (opts && opts.matchBase) {
    return utils.hasFilename(re, opts);
  }
  // `matchBase` is not defined
  return function(fp) {
    fp = utils.unixify(fp, opts);
    return re.test(fp);
  };
}

/**
 * Create and cache a regular expression for matching
 * file paths.
 *
 * If the leading character in the `glob` is `!`, a negation
 * regex is returned.
 *
 * @param  {String} `glob`
 * @param  {Object} `options`
 * @return {RegExp}
 */

function toRegex(glob, options) {
  if (typeOf(glob) !== 'string') {
    throw new Error(msg('toRegex', 'glob', 'a string'));
  }

  // clone options to prevent  mutating the original object
  var opts = Object.create(options || {});
  var flags = opts.flags || '';
  if (opts.nocase && flags.indexOf('i') === -1) {
    flags += 'i';
  }

  var parsed = expand(glob, opts);

  // pass in tokens to avoid parsing more than once
  opts.negated = opts.negated || parsed.negated;
  opts.negate = opts.negated;
  glob = wrapGlob(parsed.pattern, opts);
  var re;

  try {
    re = new RegExp(glob, flags);
    return re;
  } catch (err) {
    var msg = 'micromatch invalid regex: (' + re + ')';
    if (opts.strict) throw new SyntaxError(msg + err);
  }
  return /$^/;
}

/**
 * Create the regex to do the matching. If the leading
 * character in the `glob` is `!` a negation regex is returned.
 *
 * @param {String} `glob`
 * @param {Boolean} `negate`
 */

function wrapGlob(glob, opts) {
  var prefix = (opts && !opts.contains) ? '^' : '';
  var after = (opts && !opts.contains) ? '$' : '';
  glob = ('(?:' + glob + ')' + after);
  if (opts && opts.negate) {
    return prefix + ('(?!^' + glob + ').*$');
  }
  return prefix + glob;
}

/**
 * Wrap `toRegex` to memoize the generated regex
 * the string and options don't change
 */

function makeRe(glob, opts) {
  return cache(toRegex, glob, opts);
}

/**
 * Make error messages consistent. Follows this format:
 *
 * ```js
 * msg(methodName, argNumber, nativeType);
 * // example:
 * msg('matchKeys', 'first', 'an object');
 * ```
 *
 * @param  {String} `method`
 * @param  {String} `num`
 * @param  {String} `type`
 * @return {String}
 */

function msg(method, what, type) {
  return 'micromatch.' + method + '(): ' + what + ' should be ' + type + '.';
}

/**
 * Public methods
 */

micromatch.any       = any;
micromatch.braces    = micromatch.braceExpand = require('braces');
micromatch.contains  = contains;
micromatch.expand    = expand;
micromatch.filter    = filter;
micromatch.isMatch   = isMatch;
micromatch.makeRe    = makeRe;
micromatch.match     = match;
micromatch.matcher   = matcher;
micromatch.matchKeys = matchKeys;

/**
 * Expose `micromatch`
 */

module.exports = micromatch;
<commit_msg>remove debug<commit_after>/*!
 * micromatch <https://github.com/jonschlinkert/micromatch>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

var diff = require('arr-diff');
var typeOf = require('kind-of');
var omit = require('object.omit');
var cache = require('regex-cache');
var isGlob = require('is-glob');
var expand = require('./lib/expand');
var utils = require('./lib/utils');

/**
 * The main function. Pass an array of filepaths,
 * and a string or array of glob patterns
 *
 * @param  {Array|String} `files`
 * @param  {Array|String} `patterns`
 * @param  {Object} `opts`
 * @return {Array} Array of matches
 */

function micromatch(files, patterns, opts) {
  if (!files || !patterns) return [];
  opts = opts || {};

  if (typeof opts.cache === 'undefined') {
    opts.cache = true;
  }

  if (!Array.isArray(patterns)) {
    return match(files, patterns, opts);
  }

  var len = patterns.length, i = 0;
  var omit = [], keep = [];

  while (len--) {
    var glob = patterns[i++];
    if (glob.charCodeAt(0) === 33 /* ! */) {
      omit.push.apply(omit, match(files, glob.slice(1), opts));
    } else {
      keep.push.apply(keep, match(files, glob, opts));
    }
  }
  return diff(keep, omit);
}

/**
 * Pass an array of files and a glob pattern as a string.
 *
 * This function is called by the main `micromatch` function
 * If you only need to pass a single pattern you might get
 * very minor speed improvements using this function.
 *
 * @param  {Array} `files`
 * @param  {Array} `pattern`
 * @param  {Object} `options`
 * @return {Array}
 */

function match(files, pattern, opts) {
  if (typeOf(files) !== 'string' && !Array.isArray(files)) {
    throw new Error(msg('match', 'files', 'a string or array'));
  }

  files = utils.arrayify(files);
  opts = opts || {};

  var negate = opts.negate || false;
  var orig = pattern;

  if (typeof pattern === 'string' && opts.nonegate !== true) {
    negate = pattern.charAt(0) === '!';
    if (negate) {
      pattern = pattern.slice(1);
    }
  }

  var _isMatch = matcher(pattern, opts);
  var len = files.length, i = 0;
  var res = [];

  while (i < len) {
    var file = files[i++];
    var fp = utils.unixify(file, opts);

    if (!_isMatch(fp)) { continue; }
    res.push(fp);
  }

  if (res.length === 0) {
    if (opts.failglob === true) {
      throw new Error('micromatch.match() found no matches for: "' + orig + '".');
    }

    if (opts.nonull || opts.nullglob) {
      res.push(utils.unescapeGlob(orig));
    }
  }

  // if `negate` was defined, diff negated files
  if (negate) { res = diff(files, res); }

  // if `ignore` was defined, diff ignored filed
  if (opts.ignore && opts.ignore.length) {
    pattern = opts.ignore;
    opts = omit(opts, ['ignore']);
    return diff(res, micromatch(res, pattern, opts));
  }
  return res;
}

/**
 * Returns a function that takes a glob pattern or array of glob patterns
 * to be used with `Array#filter()`. (Internally this function generates
 * the matching function using the [matcher] method).
 *
 * ```js
 * var fn = mm.filter('[a-c]');
 * ['a', 'b', 'c', 'd', 'e'].filter(fn);
 * //=> ['a', 'b', 'c']
 * ```
 *
 * @param  {String|Array} `patterns` Can be a glob or array of globs.
 * @param  {Options} `opts` Options to pass to the [matcher] method.
 * @return {Function} Filter function to be passed to `Array#filter()`.
 */

function filter(patterns, opts) {
  if (!Array.isArray(patterns) && typeof patterns !== 'string') {
    throw new TypeError(msg('filter', 'patterns', 'a string or array'));
  }

  patterns = utils.arrayify(patterns);
  return function (fp) {
    if (fp == null) return [];
    var len = patterns.length, i = 0;
    var res = true;

    fp = utils.unixify(fp, opts);
    while (i < len) {
      var fn = matcher(patterns[i++], opts);
      if (!fn(fp)) {
        res = false;
        break;
      }
    }
    return res;
  };
}

/**
 * Returns true if the filepath contains the given
 * pattern. Can also return a function for matching.
 *
 * ```js
 * isMatch('foo.md', '*.md', {});
 * //=> true
 *
 * isMatch('*.md', {})('foo.md')
 * //=> true
 * ```
 *
 * @param  {String} `fp`
 * @param  {String} `pattern`
 * @param  {Object} `opts`
 * @return {Boolean}
 */

function isMatch(fp, pattern, opts) {
  if (typeof fp !== 'string') {
    throw new TypeError(msg('isMatch', 'filepath', 'a string'));
  }

  fp = utils.unixify(fp, opts);
  if (typeOf(pattern) === 'object') {
    return matcher(fp, pattern);
  }
  return matcher(pattern, opts)(fp);
}

/**
 * Returns true if the filepath matches the
 * given pattern.
 */

function contains(fp, pattern, opts) {
  if (typeof fp !== 'string') {
    throw new TypeError(msg('contains', 'pattern', 'a string'));
  }

  opts = opts || {};
  opts.contains = (pattern !== '');
  fp = utils.unixify(fp, opts);

  if (opts.contains && !isGlob(pattern)) {
    return fp.indexOf(pattern) !== -1;
  }
  return matcher(pattern, opts)(fp);
}

/**
 * Returns true if a file path matches any of the
 * given patterns.
 *
 * @param  {String} `fp` The filepath to test.
 * @param  {String|Array} `patterns` Glob patterns to use.
 * @param  {Object} `opts` Options to pass to the `matcher()` function.
 * @return {String}
 */

function any(fp, patterns, opts) {
  if (!Array.isArray(patterns) && typeof patterns !== 'string') {
    throw new TypeError(msg('any', 'patterns', 'a string or array'));
  }

  patterns = utils.arrayify(patterns);
  var len = patterns.length;

  fp = utils.unixify(fp, opts);
  while (len--) {
    var isMatch = matcher(patterns[len], opts);
    if (isMatch(fp)) {
      return true;
    }
  }
  return false;
}

/**
 * Filter the keys of an object with the given `glob` pattern
 * and `options`
 *
 * @param  {Object} `object`
 * @param  {Pattern} `object`
 * @return {Array}
 */

function matchKeys(obj, glob, options) {
  if (typeOf(obj) !== 'object') {
    throw new TypeError(msg('matchKeys', 'first argument', 'an object'));
  }

  var fn = matcher(glob, options);
  var res = {};

  for (var key in obj) {
    if (obj.hasOwnProperty(key) && fn(key)) {
      res[key] = obj[key];
    }
  }
  return res;
}

/**
 * Return a function for matching based on the
 * given `pattern` and `options`.
 *
 * @param  {String} `pattern`
 * @param  {Object} `options`
 * @return {Function}
 */

function matcher(pattern, opts) {
  // pattern is a function
  if (typeof pattern === 'function') {
    return pattern;
  }
  // pattern is a regex
  if (pattern instanceof RegExp) {
    return function(fp) {
      return pattern.test(fp);
    };
  }

  // strings, all the way down...
  pattern = utils.unixify(pattern, opts);

  // pattern is a non-glob string
  if (!isGlob(pattern)) {
    return utils.matchPath(pattern, opts);
  }
  // pattern is a glob string
  var re = makeRe(pattern, opts);

  // `matchBase` is defined
  if (opts && opts.matchBase) {
    return utils.hasFilename(re, opts);
  }
  // `matchBase` is not defined
  return function(fp) {
    fp = utils.unixify(fp, opts);
    return re.test(fp);
  };
}

/**
 * Create and cache a regular expression for matching
 * file paths.
 *
 * If the leading character in the `glob` is `!`, a negation
 * regex is returned.
 *
 * @param  {String} `glob`
 * @param  {Object} `options`
 * @return {RegExp}
 */

function toRegex(glob, options) {
  if (typeOf(glob) !== 'string') {
    throw new Error(msg('toRegex', 'glob', 'a string'));
  }

  // clone options to prevent  mutating the original object
  var opts = Object.create(options || {});
  var flags = opts.flags || '';
  if (opts.nocase && flags.indexOf('i') === -1) {
    flags += 'i';
  }

  var parsed = expand(glob, opts);

  // pass in tokens to avoid parsing more than once
  opts.negated = opts.negated || parsed.negated;
  opts.negate = opts.negated;
  glob = wrapGlob(parsed.pattern, opts);
  var re;

  try {
    re = new RegExp(glob, flags);
    return re;
  } catch (err) {
    var msg = 'micromatch invalid regex: (' + re + ')';
    if (opts.strict) throw new SyntaxError(msg + err);
  }
  return /$^/;
}

/**
 * Create the regex to do the matching. If the leading
 * character in the `glob` is `!` a negation regex is returned.
 *
 * @param {String} `glob`
 * @param {Boolean} `negate`
 */

function wrapGlob(glob, opts) {
  var prefix = (opts && !opts.contains) ? '^' : '';
  var after = (opts && !opts.contains) ? '$' : '';
  glob = ('(?:' + glob + ')' + after);
  if (opts && opts.negate) {
    return prefix + ('(?!^' + glob + ').*$');
  }
  return prefix + glob;
}

/**
 * Wrap `toRegex` to memoize the generated regex
 * the string and options don't change
 */

function makeRe(glob, opts) {
  return cache(toRegex, glob, opts);
}

/**
 * Make error messages consistent. Follows this format:
 *
 * ```js
 * msg(methodName, argNumber, nativeType);
 * // example:
 * msg('matchKeys', 'first', 'an object');
 * ```
 *
 * @param  {String} `method`
 * @param  {String} `num`
 * @param  {String} `type`
 * @return {String}
 */

function msg(method, what, type) {
  return 'micromatch.' + method + '(): ' + what + ' should be ' + type + '.';
}

/**
 * Public methods
 */

micromatch.any       = any;
micromatch.braces    = micromatch.braceExpand = require('braces');
micromatch.contains  = contains;
micromatch.expand    = expand;
micromatch.filter    = filter;
micromatch.isMatch   = isMatch;
micromatch.makeRe    = makeRe;
micromatch.match     = match;
micromatch.matcher   = matcher;
micromatch.matchKeys = matchKeys;

/**
 * Expose `micromatch`
 */

module.exports = micromatch;
<|endoftext|>


<commit_before>// @flow
import styled, { css } from "styled-components";

import colorTypes from "../constants/colorTypes";
import { MEDIUM } from "../constants/buttonSizes";
import { NEUTRAL } from "../constants/buttonTypes";

const Button = styled.button`
  display: flex;
  align-items: flex-end;

  border: solid 1px rgba(0, 0, 0, 0.16);
  border-radius: 4px;
  box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.16);

  color: white;

  line-height: 16px;
  font-size: 16px;
  font-family: lato, sans-serif;
  font-weight: 600;
  -webkit-font-smoothing: antialiased !important;

  white-space: nowrap;
  text-overflow: ellipsis;
  outline: 0;

  cursor: pointer;

  .icon {
    color: rgba(255, 255, 255, 0.56);
  }

  &:hover {
    box-shadow: 0 4px 4px 0 rgba(0, 0, 0, 0.16);
  }

  &:focus {
    box-shadow: none;
  }

  &:hover .icon,
  &:focus .icon {
    color: white;
  }

  ${fluidStyle};
  ${loadingStyle};
  ${typeStyle};
  ${paddingStyle};

  &:disabled,
  &:disabled .icon,
  &:disabled :hover {
    color: rgba(0, 0, 0, 0.32);
  }

  &:disabled {
    background-color: rgba(0, 0, 0, 0.16);
    box-shadow: none;
  }
`;

Button.displayName = "StyledButton";

function isIconOnly(props) {
  return !props.text;
}

function paddingStyle(props) {
  const isMedium = props.size === MEDIUM;
  let padding = "8px 16px";
  if (isMedium) {
    padding = "16px 16px";
  } else if (isIconOnly(props)) {
    padding = "8px 8px";
  }
  return css`
    padding: ${padding};
  `;
}

function neutralStyle(props) {
  const { textColor, iconColor, textHoverColor, color } = colorTypes[NEUTRAL];
  const activatedNeutralStyle = css`
    color: ${textHoverColor};
    border-color: ${textHoverColor};
    > .icon {
      color: ${textHoverColor};
    }
  `;
  return css`
    background-color: ${color};
    color: ${textColor};
    > .icon {
      color: ${iconColor};
    }
    ${props => props.activated && activatedNeutralStyle};

    &:hover,
    &:focus {
      ${activatedNeutralStyle};
    }
  `;
}

function typeStyle(props) {
  if (props.type === NEUTRAL) {
    return neutralStyle(props);
  }
  const { color, hoverColor } = colorTypes[props.type];

  return css`
    transition: background 0.3s ease;
    background-color: ${color};

    &:hover {
      background-color: ${hoverColor};
    }

    &:focus {
      background-color: ${hoverColor};
    }
  `;
}

function loadingStyle(props) {
  return (
    props.loading &&
    css`
      > .icon {
        animation: spin 1.1s infinite linear;
        @keyframes spin {
          0% {
            transform: rotate(0deg);
          }

          100% {
            transform: rotate(360deg);
          }
        }
      }
    `
  );
}

function fluidStyle(props) {
  return (
    props.fluid &&
    css`
      max-width: 100%;
      width: 100%;
    `
  );
}

export default Button;
<commit_msg>Fix fluid button text alignment<commit_after>// @flow
import styled, { css } from "styled-components";

import colorTypes from "../constants/colorTypes";
import { MEDIUM } from "../constants/buttonSizes";
import { NEUTRAL } from "../constants/buttonTypes";

const Button = styled.button`
  display: flex;
  align-items: flex-end;
  justify-content: center;

  border: solid 1px rgba(0, 0, 0, 0.16);
  border-radius: 4px;
  box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.16);

  color: white;

  line-height: 16px;
  font-size: 16px;
  font-family: lato, sans-serif;
  font-weight: 600;
  -webkit-font-smoothing: antialiased !important;

  white-space: nowrap;
  text-overflow: ellipsis;
  outline: 0;

  cursor: pointer;

  .icon {
    color: rgba(255, 255, 255, 0.56);
  }

  &:hover {
    box-shadow: 0 4px 4px 0 rgba(0, 0, 0, 0.16);
  }

  &:focus {
    box-shadow: none;
  }

  &:hover .icon,
  &:focus .icon {
    color: white;
  }

  ${fluidStyle};
  ${loadingStyle};
  ${typeStyle};
  ${paddingStyle};

  &:disabled,
  &:disabled .icon,
  &:disabled :hover {
    color: rgba(0, 0, 0, 0.32);
  }

  &:disabled {
    background-color: rgba(0, 0, 0, 0.16);
    box-shadow: none;
  }
`;

Button.displayName = "StyledButton";

function isIconOnly(props) {
  return !props.text;
}

function paddingStyle(props) {
  const isMedium = props.size === MEDIUM;
  let padding = "8px 16px";
  if (isMedium) {
    padding = "16px 16px";
  } else if (isIconOnly(props)) {
    padding = "8px 8px";
  }
  return css`
    padding: ${padding};
  `;
}

function neutralStyle(props) {
  const { textColor, iconColor, textHoverColor, color } = colorTypes[NEUTRAL];
  const activatedNeutralStyle = css`
    color: ${textHoverColor};
    border-color: ${textHoverColor};
    > .icon {
      color: ${textHoverColor};
    }
  `;
  return css`
    background-color: ${color};
    color: ${textColor};
    > .icon {
      color: ${iconColor};
    }
    ${props => props.activated && activatedNeutralStyle};

    &:hover,
    &:focus {
      ${activatedNeutralStyle};
    }
  `;
}

function typeStyle(props) {
  if (props.type === NEUTRAL) {
    return neutralStyle(props);
  }
  const { color, hoverColor } = colorTypes[props.type];

  return css`
    transition: background 0.3s ease;
    background-color: ${color};

    &:hover {
      background-color: ${hoverColor};
    }

    &:focus {
      background-color: ${hoverColor};
    }
  `;
}

function loadingStyle(props) {
  return (
    props.loading &&
    css`
      > .icon {
        animation: spin 1.1s infinite linear;
        @keyframes spin {
          0% {
            transform: rotate(0deg);
          }

          100% {
            transform: rotate(360deg);
          }
        }
      }
    `
  );
}

function fluidStyle(props) {
  return (
    props.fluid &&
    css`
      max-width: 100%;
      width: 100%;
    `
  );
}

export default Button;
<|endoftext|>


<commit_before>/**
 * Called when a whole column is selected/deselected
 */
function selectAll(columnsToDisable, columnsToHighlight, columnIndex, tableid) {
    $$('.selectable').each(function(item) {
       if(item.id.split("_")[1] == columnIndex) {
           item.checked = $('selectedObjects_' + columnIndex).checked;
           $w(item.className).each(function(className){
              if(className.startsWith('id_')) {
                 objectId = className;
                // Hightlight all cells for this object
                $$("td."+objectId).each(function(cell){
                    if(item.checked) {
                        cell.addClassName('highlightCell');
                    } else {
                        cell.removeClassName('highlightCell');
                    }
                });
              }
           });
       }
    });
    if($('selectedObjects_' + columnIndex).checked) {
        AjaxServices.selectAll(columnIndex, tableid);
        $('selectedIdFields').update(' All selected on all pages');
    } else {
        AjaxServices.selectAll(-1, tableid);
        $('selectedIdFields').update('');
    }
    setToolbarAvailability(!$('selectedObjects_' + columnIndex).checked);
    if (isClear()) {
        enableAll();
    }
}

/**
 * Enables all checkboxes
 */
function enableAll() {
    $$('input.selectable').each(function(item) {
    	item.disabled = false;
    });
}

/**
 * Checks that nothing is selected
 */
function isClear() {
    var selectedIdFields = $('selectedIdFields');
    return (selectedIdFields.innerHTML.strip() == '');
}

/**
 * Disable columns with a different class
 */
function disableOtherColumns(className, checkedColumn) {
    $$('input.selectable').each(function(input){
            if (! input.hasClassName(className)) {
                input.disabled = true;
            }

            if (input.id != 'selectedObjects_'  + checkedColumn
                && !input.id.startsWith('selectedObjects_'  + checkedColumn + '_')) {
                input.disabled = true;
            }
        });
}

/**
 * Run when a user selects a keyfield in the results table.  internal is true
 * when called from other methods in this file (ie. not from an onclick in table.jsp)
 **/
function itemChecked(columnsToDisable, columnsToHighlight, checkedRow, checkedColumn, tableid, checkbox, internal) {
    /*if (bagType == null) {
        var columnsToDisableArray = columnsToDisable[checkedColumn];
        if (columnsToDisableArray != null) {
        	columnsToDisableArray.each(function(item) {
        	  disableColumn(item);
        	});
        }
        bagType = checkedColumn;
    }*/

    /*if (!internal) {
        unselectColumnCheckbox(checkedColumn);
    }*/

    var objectId;
    var objectClass;
    $w(checkbox.className).each(function(className){
      	if(className.startsWith('id_')) {
      		objectId = className.sub('id_','');
      	}
        if(className.startsWith('class_')) {
            objectClass = className;
        }
    })

    // Update list and save selected state
    if(checkbox.checked) {
        AjaxServices.selectId(objectId,tableid,
            function(selectedIds) {
            	$('selectedIdFields').update(selectedIds.join(', '));
        });
/*        if($('selectedIds').value.strip() != '') {
          var splitted = $('selectedIds').value.split(',');
          splitted.push(objectId);
        } else {
          var splitted=objectId;
        }
        $('selectedIds').value=splitted;
*/
    } else {
        AjaxServices.deSelectId(objectId,tableid, function(selectedIds) {
                $('selectedIdFields').update(selectedIds.join(', '));
        });
/*
        var splitted = $('selectedIds').value.split(',');
        var count=0;
        splitted.each(function(item){
           if(item.strip() == objectId) {
           	 index = count;
           }
           count++;
        })
        var removed = splitted.splice(index,1);
        $('selectedIds').value=splitted;
*/
    }

    // Hightlight all cells for this object
    $$("td.id_"+objectId).each(function(cell){
        if(checkbox.checked) {
            cell.addClassName('highlightCell');
        } else {
            cell.removeClassName('highlightCell');
        }
    });

    $$("input.id_"+objectId).each(function(box){
        box.checked = checkbox.checked;
    });

        // Disable/enable other classes columns
    if (isClear()) {
        enableAll();
        AjaxServices.setClassForId('', tableid);
        bagType = null;
    } else {
        disableOtherColumns(objectClass, checkedColumn);
        AjaxServices.setClassForId(objectClass.sub('class_',''), tableid);
    }

    setToolbarAvailability($('selectedIdFields').innerHTML.strip() == '');

    /*var columnsToHighlightArray = columnsToHighlight[checkedColumn]
    $$('td').each(function(item){
    	var splitter = item.id.split(',');
    	if(splitter[2] == checkedRow || (checkedRow == null && splitter[0].startsWith('cell'))) {
    		columnsToHighlightArray.each(function(item2) {
    		  if(item2 == splitter[1]) {
    		  	if(checkbox.checked) {
    		  		item.addClassName('highlightCell');
    		  		var classes = $w(item.className);
    		  		for(var i=0; i<classes.length; i++) {
    		  			var clazz = classes[i];
    		  			if(!isNaN(parseFloat(clazz))) {
    		  				AjaxServices.selectId(clazz,tableid);
    		  			}
    		  		}
    		  	} else {
    		  		item.removeClassName('highlightCell');
    		  	}
    		  }
    		})
    	}
    });*/
}

/**
 * disables all checkboxes in the given column
 **/
/*function disableColumn(index){
	$$('.selectable').each(function (item) {
		if (item.id.split('_')[1] == index) {
			item.disabled = 'true';
		}
	});
}*/

/**
 * de-selects a whole column of a given number
 **/
function unselectColumnCheckbox(column) {
	var enabled = true;
    $('selectedObjects_' + column).checked = false;
        $$('.selectable').each(function (item) {
        if ((item.id.split('_')[1] == column) && (item.checked)) {
           enabled = false;
           //setToolbarAvailability(false);
           return;
        }
    });
	setToolbarAvailability(enabled);
}

function setToolbarAvailability(status) {
$('newBagName').disabled = status;
    $('saveNewBag').disabled = status;
    if($('addToBag')){
            with($('addToBag')) {
                $('addToBag').disabled = status;
            }
    }
}

function onSaveBagEnter(formName) {
	var frm = document.forms[formName];
	frm.operationButton.value = 'saveNewBag';
}
<commit_msg>Call AjaxServices.selectId() and deSelectId() synchronously to fix problems with disabling of checkboxes.<commit_after>/**
 * Called when a whole column is selected/deselected
 */
function selectAll(columnsToDisable, columnsToHighlight, columnIndex, tableid) {
    $$('.selectable').each(function(item) {
       if(item.id.split("_")[1] == columnIndex) {
           item.checked = $('selectedObjects_' + columnIndex).checked;
           $w(item.className).each(function(className){
              if(className.startsWith('id_')) {
                 objectId = className;
                // Hightlight all cells for this object
                $$("td."+objectId).each(function(cell){
                    if(item.checked) {
                        cell.addClassName('highlightCell');
                    } else {
                        cell.removeClassName('highlightCell');
                    }
                });
              }
           });
       }
    });
    if($('selectedObjects_' + columnIndex).checked) {
        AjaxServices.selectAll(columnIndex, tableid);
        $('selectedIdFields').update(' All selected on all pages');
    } else {
        AjaxServices.selectAll(-1, tableid);
        $('selectedIdFields').update('');
    }
    setToolbarAvailability(!$('selectedObjects_' + columnIndex).checked);
    if (isClear()) {
        enableAll();
    }
}

/**
 * Enables all checkboxes
 */
function enableAll() {
    $$('input.selectable').each(function(item) {
    	item.disabled = false;
    });
}

/**
 * Checks that nothing is selected
 */
function isClear() {
    var selectedIdFields = $('selectedIdFields');
    return (selectedIdFields.innerHTML.strip() == '');
}

/**
 * Disable columns with a different class
 */
function disableOtherColumns(className, checkedColumn) {
    $$('input.selectable').each(function(input){
            if (! input.hasClassName(className)) {
                input.disabled = true;
            }

            if (input.id != 'selectedObjects_'  + checkedColumn
                && !input.id.startsWith('selectedObjects_'  + checkedColumn + '_')) {
                input.disabled = true;
            }
        });
}

/**
 * Run when a user selects a keyfield in the results table.  internal is true
 * when called from other methods in this file (ie. not from an onclick in table.jsp)
 **/
function itemChecked(columnsToDisable, columnsToHighlight, checkedRow, checkedColumn, tableid, checkbox, internal) {
    /*if (bagType == null) {
        var columnsToDisableArray = columnsToDisable[checkedColumn];
        if (columnsToDisableArray != null) {
        	columnsToDisableArray.each(function(item) {
        	  disableColumn(item);
        	});
        }
        bagType = checkedColumn;
    }*/

    /*if (!internal) {
        unselectColumnCheckbox(checkedColumn);
    }*/

    var objectId;
    var objectClass;
    $w(checkbox.className).each(function(className){
      	if(className.startsWith('id_')) {
      		objectId = className.sub('id_','');
      	}
        if(className.startsWith('class_')) {
            objectClass = className;
        }
    })

    // Update list and save selected state
    if(checkbox.checked) {
        AjaxServices.selectId(objectId,tableid, {
              callback: function(selectedIds) {
                    $('selectedIdFields').update(selectedIds.join(', '));
                },
              async:false
            }
         );
/*        if($('selectedIds').value.strip() != '') {
          var splitted = $('selectedIds').value.split(',');
          splitted.push(objectId);
        } else {
          var splitted=objectId;
        }
        $('selectedIds').value=splitted;
*/
    } else {
        AjaxServices.deSelectId(objectId,tableid, {
              callback: function(selectedIds) {
                $('selectedIdFields').update(selectedIds.join(', '));
              },
             async:false
         });
/*
        var splitted = $('selectedIds').value.split(',');
        var count=0;
        splitted.each(function(item){
           if(item.strip() == objectId) {
           	 index = count;
           }
           count++;
        })
        var removed = splitted.splice(index,1);
        $('selectedIds').value=splitted;
*/
    }

    // Hightlight all cells for this object
    $$("td.id_"+objectId).each(function(cell){
        if(checkbox.checked) {
            cell.addClassName('highlightCell');
        } else {
            cell.removeClassName('highlightCell');
        }
    });

    $$("input.id_"+objectId).each(function(box){
        box.checked = checkbox.checked;
    });

        // Disable/enable other classes columns
    if (isClear()) {
        enableAll();
        AjaxServices.setClassForId('', tableid);
        bagType = null;
    } else {
        disableOtherColumns(objectClass, checkedColumn);
        AjaxServices.setClassForId(objectClass.sub('class_',''), tableid);
    }

    setToolbarAvailability($('selectedIdFields').innerHTML.strip() == '');

    /*var columnsToHighlightArray = columnsToHighlight[checkedColumn]
    $$('td').each(function(item){
    	var splitter = item.id.split(',');
    	if(splitter[2] == checkedRow || (checkedRow == null && splitter[0].startsWith('cell'))) {
    		columnsToHighlightArray.each(function(item2) {
    		  if(item2 == splitter[1]) {
    		  	if(checkbox.checked) {
    		  		item.addClassName('highlightCell');
    		  		var classes = $w(item.className);
    		  		for(var i=0; i<classes.length; i++) {
    		  			var clazz = classes[i];
    		  			if(!isNaN(parseFloat(clazz))) {
    		  				AjaxServices.selectId(clazz,tableid);
    		  			}
    		  		}
    		  	} else {
    		  		item.removeClassName('highlightCell');
    		  	}
    		  }
    		})
    	}
    });*/
}

/**
 * disables all checkboxes in the given column
 **/
/*function disableColumn(index){
	$$('.selectable').each(function (item) {
		if (item.id.split('_')[1] == index) {
			item.disabled = 'true';
		}
	});
}*/

/**
 * de-selects a whole column of a given number
 **/
function unselectColumnCheckbox(column) {
	var enabled = true;
    $('selectedObjects_' + column).checked = false;
        $$('.selectable').each(function (item) {
        if ((item.id.split('_')[1] == column) && (item.checked)) {
           enabled = false;
           //setToolbarAvailability(false);
           return;
        }
    });
	setToolbarAvailability(enabled);
}

function setToolbarAvailability(status) {
$('newBagName').disabled = status;
    $('saveNewBag').disabled = status;
    if($('addToBag')){
            with($('addToBag')) {
                $('addToBag').disabled = status;
            }
    }
}

function onSaveBagEnter(formName) {
	var frm = document.forms[formName];
	frm.operationButton.value = 'saveNewBag';
}
<|endoftext|>


<commit_before>// @flow
import React, { Component } from 'react'
import { Provider } from 'react-redux'

import DragDropContext from '../DragDropContext'
import HotKeyDecorator from '../HotKey/Decorator'
import { editable } from '../../selector/editable'
import PluginService from '../../service/plugin'
import Inner from './Inner'

import type { Store } from '../../types/redux'
import { shouldPureComponentUpdate } from '../../helper/shouldComponentUpdate'

class Editable extends Component {
  componentDidMount() {
    if (!this.props.id) {
      throw new Error('The state must have an unique id')
    }

    this.unsubscribe = this.props.editor.store.subscribe(this.onChange)
    this.previousState = null
  }

  componentWillUnmount() {
    this.unsubscribe();
  }

  shouldComponentUpdate = shouldPureComponentUpdate

  previousState: any = {}

  props: {
    id: string,
    editor: {
      plugins: PluginService,
      store: Store,
      defaultPlugin: any
    },
    onChange?: Function
  }

  onChange = () => {
    const { onChange } = this.props
    if (typeof onChange !== 'function') {
      return
    }

    const state: any = editable(this.props.editor.store.getState(), {
      id: this.props.id
    })
    if (state === this.previousState || !state) {
      return
    }

    const serialized = this.props.editor.plugins.serialize(state)
    onChange(serialized)
  }

  render() {
    const { id, editor: { store, defaultPlugin } } = this.props

    return (
      <Provider store={store}>
        <DragDropContext>
          <HotKeyDecorator id={id}>
            <Inner id={id} defaultPlugin={defaultPlugin} />
          </HotKeyDecorator>
        </DragDropContext>
      </Provider>
    )
  }
}

export default Editable
<commit_msg>core: resolve flow issues in editable (#406)<commit_after>// @flow
import React, { Component } from 'react'
import { Provider } from 'react-redux'

import DragDropContext from '../DragDropContext'
import HotKeyDecorator from '../HotKey/Decorator'
import { editable } from '../../selector/editable'
import PluginService from '../../service/plugin'
import Inner from './Inner'

import type { Store } from '../../types/redux'
import { shouldPureComponentUpdate } from '../../helper/shouldComponentUpdate'

class Editable extends Component {
  componentDidMount() {
    if (!this.props.id) {
      throw new Error('The state must have an unique id')
    }

    this.unsubscribe = this.props.editor.store.subscribe(this.onChange)
    this.previousState = null
  }

  componentWillUnmount() {
    this.unsubscribe();
  }

  shouldComponentUpdate = shouldPureComponentUpdate

  unsubscribe: Function
  previousState: any = {}

  props: {
    id: string,
    editor: {
      plugins: PluginService,
      store: Store,
      defaultPlugin: any
    },
    onChange?: Function
  }

  onChange = () => {
    const { onChange } = this.props
    if (typeof onChange !== 'function') {
      return
    }

    const state: any = editable(this.props.editor.store.getState(), {
      id: this.props.id
    })
    if (state === this.previousState || !state) {
      return
    }

    const serialized = this.props.editor.plugins.serialize(state)
    onChange(serialized)
  }

  render() {
    const { id, editor: { store, defaultPlugin } } = this.props

    return (
      <Provider store={store}>
        <DragDropContext>
          <HotKeyDecorator id={id}>
            <Inner id={id} defaultPlugin={defaultPlugin} />
          </HotKeyDecorator>
        </DragDropContext>
      </Provider>
    )
  }
}

export default Editable
<|endoftext|>


<commit_before>'use strict';

var es				= require("event-stream"),
	fs				= require("fs"),
	PluginError		= require("gulp-util").PluginError;

module.exports = function(options) {
	options = options || {};

	var pluginName = 'gulp-inc',
		regex = options.regex || /#=\s*include\s+([^\s]+)/gm,
		preproccesor = options.preproccesor || null;

	if( typeof preproccesor == 'function')
		preproccesor = preproccesor;
	else
		preproccesor = function(contents){ return content; }

    function inc(file, callback) {

    	if (file.isNull())
    		return; // ignore
        if (file.isStream())
        	return this.emit('error', new PluginError(pluginName,  'Streaming not supported'));

		if (file.isBuffer()) {

			var content = String(file.contents);
			var result = content,
				matches;

			while (matches = regex.exec(content)) {

				var match 	= matches[0],
					path	= file.base + matches[1].replace(/['"]/g, '');

				if (fs.existsSync(path)) {

					var contentToInclude = preproccesor(String(fs.readFileSync(path)));
					result = result.split(match).join("\n" + contentToInclude + "\n");

				} else
					throw new PluginError(pluginName, 'File not found: ' + path);

			}
			file.contents = new Buffer(result);
		}
		callback(null, file);
	}
    return es.map(inc);
}
<commit_msg>content->contents<commit_after>'use strict';

var es				= require("event-stream"),
	fs				= require("fs"),
	PluginError		= require("gulp-util").PluginError;

module.exports = function(options) {
	options = options || {};

	var pluginName = 'gulp-inc',
		regex = options.regex || /#=\s*include\s+([^\s]+)/gm,
		preproccesor = options.preproccesor || null;

	if( typeof preproccesor == 'function')
		preproccesor = preproccesor;
	else
		preproccesor = function(contents){ return contents; }

    function inc(file, callback) {

    	if (file.isNull())
    		return; // ignore
        if (file.isStream())
        	return this.emit('error', new PluginError(pluginName,  'Streaming not supported'));

		if (file.isBuffer()) {

			var content = String(file.contents);
			var result = content,
				matches;

			while (matches = regex.exec(content)) {

				var match 	= matches[0],
					path	= file.base + matches[1].replace(/['"]/g, '');

				if (fs.existsSync(path)) {

					var contentToInclude = preproccesor(String(fs.readFileSync(path)));
					result = result.split(match).join("\n" + contentToInclude + "\n");

				} else
					throw new PluginError(pluginName, 'File not found: ' + path);

			}
			file.contents = new Buffer(result);
		}
		callback(null, file);
	}
    return es.map(inc);
}
<|endoftext|>


<commit_before>import { EMPTY, ComponentTreeCache, VTree, Transaction } from './util/types';
import globalThis from './util/global';
import onceEnded from './once-ended';
import componentWillUnmount from './lifecycle/component-will-unmount';
import renderComponent from './render-component';

const { assign } = Object;

/**
 * @param {VTree} oldTree
 * @param {VTree} newTree
 *
 * @returns {VTree | null}
 */
function render(oldTree, newTree) {
  let oldComponentTree = null;

  // When there is an oldTree and it has childNodes, attempt to look up first
  // by the top-level element, or by the first element.
  if (oldTree && oldTree.childNodes) {
    // First try and lookup the old tree as a component.
    oldComponentTree = ComponentTreeCache.get(oldTree);

    // If that fails, try looking up it's first child.
    if (!oldComponentTree) {
      oldComponentTree = ComponentTreeCache.get(oldTree.childNodes[0]);
    }
  }

  // If there is no old component, or if the components do not match, then we
  // are rendering a brand new component.
  if (!oldComponentTree || oldComponentTree.rawNodeName !== newTree.rawNodeName) {
    return renderComponent(newTree);
  }

  // Otherwise re-use the existing component if the constructors are the same.
  if (oldComponentTree) {
    // Update the incoming props/attrs.
    assign(oldComponentTree.attributes, newTree.attributes);

    return renderComponent(oldComponentTree);
  }

  return oldTree;
}

/**
 * @param {VTree} vTree
 */
const releaseHook = vTree => componentWillUnmount(vTree);

/**
 * @param {VTree} vTree
 */
const createTreeHook = vTree => {
  const { customElements } = globalThis;
  const Constructor = customElements && customElements.get(vTree.nodeName);

  if (typeof vTree.rawNodeName === 'function' || Constructor) {
    vTree.attributes.children = vTree.attributes.children || vTree.childNodes;
  }
};

/**
 * @param {VTree} vTree
 */
const createNodeHook = vTree => {
  // Only look up elements with a dash in the name.
  if (!vTree.nodeName.includes('-')) return;

  // Convert this to globalThis
  const { customElements } = globalThis;
  const Constructor = customElements && customElements.get(vTree.nodeName);

  if (Constructor) {
    return new Constructor(vTree.attributes);
  }
};

/**
 * @param {VTree} oldTree
 * @param {VTree} newTree
 */
const syncTreeHook = (oldTree, newTree) => {
  // Render components during synchronization.
  if (
    // When child is a Component
    typeof newTree.rawNodeName === 'function' &&
    // If there is an oldTree and it's not the existing component, trigger a
    // render.
    (oldTree && oldTree.rawNodeName ? oldTree.rawNodeName !== newTree.rawNodeName : false)
  ) {
    return render(oldTree, newTree);
  }

  if (!newTree.childNodes) {
    return oldTree;
  }

  // Loop through childNodes seeking out components to render.
  for (let i = 0; i < newTree.childNodes.length; i++) {
    const newChildTree = newTree.childNodes[i];
    const oldChildTree = (oldTree.childNodes && oldTree.childNodes[i]) || EMPTY.OBJ;

    const isOldFunction = Boolean(ComponentTreeCache.get(oldChildTree));
    const isNewFunction = typeof newChildTree.rawNodeName === 'function';

    // Previous slot was a component and the new slot is not, therefore we
    // should be indicating this component is unmounting.
    if (isOldFunction && !isNewFunction) {
        releaseHook(oldChildTree);
    }

    // If the old slot was not a component, and the new tree is, then we are
    // rendering a brand new component.
    if (typeof newChildTree.rawNodeName === 'function') {
      const renderTree = render(oldChildTree, newChildTree);

      // If nothing was rendered, return the oldTree.
      if (!renderTree) {
        return oldTree;
      }

      // Inject the rendered tree into the position.
      if (renderTree) {
        newTree.childNodes[i] = renderTree;

        // If the rendered tree is a fragment, splice in the children, as this
        // is simply a container for the nodes.
        if (renderTree.nodeType === 11) {
          // If a function was returned, re-run the inspection over this
          // element.
          if (typeof renderTree.rawNodeName === 'function') {
            i = i - 1;
          }
          // Replace the fragment with the rendered elements. This reduces and
          // flattens the fragments into their respective nodes. If there are
          // none, then they are removed from the DOM and nothing is rendered.
          else {
            newTree.childNodes.splice(i, 1, ...renderTree.childNodes);
          }
        }
      }
    }
  }
};

export default () => assign(
  (/** @type {Transaction} */transaction) => transaction.onceEnded(onceEnded),
  {
    displayName: 'componentTask',
    syncTreeHook,
    createNodeHook,
    createTreeHook,
    releaseHook,
  },
);
<commit_msg>Remove unnecessary release causing problems<commit_after>import { EMPTY, ComponentTreeCache, VTree, Transaction } from './util/types';
import globalThis from './util/global';
import onceEnded from './once-ended';
import componentWillUnmount from './lifecycle/component-will-unmount';
import renderComponent from './render-component';

const { assign } = Object;

/**
 * @param {VTree} oldTree
 * @param {VTree} newTree
 *
 * @returns {VTree | null}
 */
function render(oldTree, newTree) {
  let oldComponentTree = null;

  // When there is an oldTree and it has childNodes, attempt to look up first
  // by the top-level element, or by the first element.
  if (oldTree && oldTree.childNodes) {
    // First try and lookup the old tree as a component.
    oldComponentTree = ComponentTreeCache.get(oldTree);

    // If that fails, try looking up it's first child.
    if (!oldComponentTree) {
      oldComponentTree = ComponentTreeCache.get(oldTree.childNodes[0]);
    }
  }

  // If there is no old component, or if the components do not match, then we
  // are rendering a brand new component.
  if (!oldComponentTree || oldComponentTree.rawNodeName !== newTree.rawNodeName) {
    return renderComponent(newTree);
  }

  // Otherwise re-use the existing component if the constructors are the same.
  if (oldComponentTree) {
    // Update the incoming props/attrs.
    assign(oldComponentTree.attributes, newTree.attributes);

    return renderComponent(oldComponentTree);
  }

  return oldTree;
}

/**
 * @param {VTree} vTree
 */
const releaseHook = vTree => componentWillUnmount(vTree);

/**
 * @param {VTree} vTree
 */
const createTreeHook = vTree => {
  const { customElements } = globalThis;
  const Constructor = customElements && customElements.get(vTree.nodeName);

  if (typeof vTree.rawNodeName === 'function' || Constructor) {
    vTree.attributes.children = vTree.attributes.children || vTree.childNodes;
  }
};

/**
 * @param {VTree} vTree
 */
const createNodeHook = vTree => {
  // Only look up elements with a dash in the name.
  if (!vTree.nodeName.includes('-')) return;

  // Convert this to globalThis
  const { customElements } = globalThis;
  const Constructor = customElements && customElements.get(vTree.nodeName);

  if (Constructor) {
    return new Constructor(vTree.attributes);
  }
};

/**
 * @param {VTree} oldTree
 * @param {VTree} newTree
 */
const syncTreeHook = (oldTree, newTree) => {
  // Render components during synchronization.
  if (
    // When child is a Component
    typeof newTree.rawNodeName === 'function' &&
    // If there is an oldTree and it's not the existing component, trigger a
    // render.
    (oldTree && oldTree.rawNodeName ? oldTree.rawNodeName !== newTree.rawNodeName : false)
  ) {
    return render(oldTree, newTree);
  }

  if (!newTree.childNodes) {
    return oldTree;
  }

  // Loop through childNodes seeking out components to render.
  for (let i = 0; i < newTree.childNodes.length; i++) {
    const newChildTree = newTree.childNodes[i];
    const oldChildTree = (oldTree.childNodes && oldTree.childNodes[i]) || EMPTY.OBJ;

    // If the old slot was not a component, and the new tree is, then we are
    // rendering a brand new component.
    if (typeof newChildTree.rawNodeName === 'function') {
      const renderTree = render(oldChildTree, newChildTree);

      // If nothing was rendered, return the oldTree.
      if (!renderTree) {
        return oldTree;
      }

      // Inject the rendered tree into the position.
      if (renderTree) {
        newTree.childNodes[i] = renderTree;

        // If the rendered tree is a fragment, splice in the children, as this
        // is simply a container for the nodes.
        if (renderTree.nodeType === 11) {
          // If a function was returned, re-run the inspection over this
          // element.
          if (typeof renderTree.rawNodeName === 'function') {
            i = i - 1;
          }
          // Replace the fragment with the rendered elements. This reduces and
          // flattens the fragments into their respective nodes. If there are
          // none, then they are removed from the DOM and nothing is rendered.
          else {
            newTree.childNodes.splice(i, 1, ...renderTree.childNodes);
          }
        }
      }
    }
  }
};

export default () => assign(
  (/** @type {Transaction} */transaction) => transaction.onceEnded(onceEnded),
  {
    displayName: 'componentTask',
    syncTreeHook,
    createNodeHook,
    createTreeHook,
    releaseHook,
  },
);
<|endoftext|>


<commit_before>import {createCell} from '../reducers/board'
import {createBoundary} from '../reducers/boundary'
import {createPlayer, updatePlayer} from '../reducers/player'
import {createDanger} from '../reducers/danger'
import {createPoi} from '../reducers/victim'
import firebase from 'APP/fire'
import {loadPlayers, sendPlayersToFirebase} from '../components/promises'

`
Legend for Cells:
----------------------
0 = empty, 1 = smoke, 2 = fire
Legend for Boundaries:
----------------------
door: 0 = closed, 1 = open, 2 = destroyed
wall: 0 = intact, 1 = 1 damage, 2 = 2 damage (destroyed)
`

const initialWallCoords = () => {
  const cellsWithSouthWall = [1, 2, 3, 4, 5, 7, 8, 23, 24, 25, 26, 27, 41, 42, 43, 45, 46, 47, 48, 61, 62, 64, 65, 66, 67, 68]
  const cellsWithEastWall = [10, 15, 18, 20, 23, 28, 36, 38, 40, 42, 50, 55, 57, 58, 60, 68]

  return cellsWithSouthWall.map(num => [num, num + 10])
  .concat(cellsWithEastWall.map(num => [num, num + 1]))
}

const initialClosedDoorCoords = () => {
  const cellsWithSouthDoor = [28, 44]
  const cellsWithEastDoor = [13, 25, 32, 46, 65, 67]

  return cellsWithSouthDoor.map(num => [num, num + 10])
  .concat(cellsWithEastDoor.map(num => [num, num + 1]))
}

const initialOpenDoorCoords = () => {
  const cellsWithSouthOpenDoor = [6, 63]
  const cellsWithEastOpenDoor = [30, 48]

  return cellsWithSouthOpenDoor.map(num => [num, num + 10])
  .concat(cellsWithEastOpenDoor.map(num => [num, num + 1]))
}

const cellsWithPlayer = [6, 30, 73, 49]
const cellsWithFire = [14, 18, 25, 37, 43, 56, 53, 68]
const colors = ['blue', 'green', 'purple', 'orange']

const initialFire = [
  [14, 'fire', 1],
  [37, 'fire', 1],
  [43, 'fire', 1],
  [56, 'fire', 1],
  [53, 'fire', 1],
  [68, 'fire', 1],
  [25, 'fire', 1],
  [18, 'fire', 1]
]

const initialPoiList = [
  [11, 0, 24], // id, status, location
  [0, 0, 52],
  [4, 0, 58]
]

// create rest of 12 POIs here with status -1
// TODO: randomize every game
const hiddenPoiList = () => {
  const poiIdList = [3, 7, 1, 8, 5, 10, 14, 6, 9, 2, 13, 12]
  return poiIdList.map(id => [id, -1, 0]) // id, status, location (0 is a placeholder)
}
//

export const setupBoard = () => dispatch => {
  for (let idx = 0; idx < 80; idx++) {
    dispatch(createCell(idx))
  }
  initialFire.forEach(fire => {
    dispatch(createDanger(fire[0], fire[1], fire[2]))
  })
  initialPoiList.forEach(poi => {
    dispatch(createPoi(poi[0], poi[1], poi[2]))
  })
  hiddenPoiList().forEach(poi => {
    dispatch(createPoi(poi[0], poi[1], poi[2]))
  })
  initialWallCoords().forEach(wallCoord => {
    dispatch(createBoundary(wallCoord, 'wall', 0))
  })
  initialClosedDoorCoords().forEach(doorCoord => {
    dispatch(createBoundary(doorCoord, 'door', 0))
  })
  initialOpenDoorCoords().forEach(doorCoord => {
    dispatch(createBoundary(doorCoord, 'door', 1))
  })
}<commit_msg>Update setup.js<commit_after>import {createCell} from '../reducers/board'
import {createBoundary} from '../reducers/boundary'
import {createPlayer, updatePlayer} from '../reducers/player'
import {createDanger} from '../reducers/danger'
import {createPoi} from '../reducers/victim'
import firebase from 'APP/fire'
import {loadPlayers, sendPlayersToFirebase} from '../components/promises'

`
Legend for Cells:
----------------------
0 = empty, 1 = smoke, 2 = fire
Legend for Boundaries:
----------------------
door: 0 = closed, 1 = open, 2 = destroyed
wall: 0 = intact, 1 = 1 damage, 2 = 2 damage (destroyed)
`

const initialWallCoords = () => {
  const cellsWithSouthWall = [1, 2, 3, 4, 5, 7, 8, 23, 24, 25, 26, 27, 41, 42, 43, 45, 46, 47, 48, 61, 62, 64, 65, 66, 67, 68]
  const cellsWithEastWall = [10, 15, 18, 20, 23, 28, 36, 38, 40, 42, 50, 55, 57, 58, 60, 68]

  return cellsWithSouthWall.map(num => [num, num + 10])
  .concat(cellsWithEastWall.map(num => [num, num + 1]))
}

const initialClosedDoorCoords = () => {
  const cellsWithSouthDoor = [28, 44]
  const cellsWithEastDoor = [13, 25, 32, 46, 65, 67]

  return cellsWithSouthDoor.map(num => [num, num + 10])
  .concat(cellsWithEastDoor.map(num => [num, num + 1]))
}

const initialOpenDoorCoords = () => {
  const cellsWithSouthOpenDoor = [6, 63]
  const cellsWithEastOpenDoor = [30, 48]

  return cellsWithSouthOpenDoor.map(num => [num, num + 10])
  .concat(cellsWithEastOpenDoor.map(num => [num, num + 1]))
}

const cellsWithPlayer = [6, 30, 73, 49]
const cellsWithFire = [14, 18, 25, 37, 43, 56, 53, 68]
const colors = ['blue', 'green', 'purple', 'orange']

const initialFire = [
  [14, 'fire', 1],
  [37, 'fire', 1],
  [43, 'fire', 1],
  [56, 'fire', 1],
  [53, 'fire', 1],
  [68, 'fire', 1],
  [25, 'fire', 1],
  [18, 'fire', 1]
]

const initialPoiList = [
  [11, 0, 24], // id, status, location
  [0, 0, 52],
  [4, 0, 58]
]

// create rest of 12 POIs here with status -1
// TODO: randomize every game
const hiddenPoiList = () => {
  const poiIdList = [3, 7, 1, 8, 5, 10, 14, 6, 9, 2, 13, 12]
  return poiIdList.map(id => [id, -1, 0]) // id, status, location (0 is a placeholder)
}
//

export const setupBoard = () => dispatch => {
  for (let idx = 0; idx < 80; idx++) {
    dispatch(createCell(idx))
  }
  initialFire.forEach(fire => {
    dispatch(createDanger(fire[0], fire[1], fire[2]))
  })
  initialPoiList.forEach(poi => {
    dispatch(createPoi(poi[0], poi[1], poi[2]))
  })
  hiddenPoiList().forEach(poi => {
    dispatch(createPoi(poi[0], poi[1], poi[2]))
  })
  initialWallCoords().forEach(wallCoord => {
    dispatch(createBoundary(wallCoord, 'wall', 0))
  })
  initialClosedDoorCoords().forEach(doorCoord => {
    dispatch(createBoundary(doorCoord, 'door', 0))
  })
  initialOpenDoorCoords().forEach(doorCoord => {
    dispatch(createBoundary(doorCoord, 'door', 1))
  })
}
<|endoftext|>


<commit_before>const combine = (combiner, ...observables) => next => {
  let state = Array(observables.length)

  observables.forEach((base, index) => base(value => {
    state[index] = value

    if(Object.keys(state).length === state.length)
      next(combiner(...state))
  }))
}

const constant = (base, value) => map(base, () => value)

const debounce = (base, interval) => next => {
  let stamp = Date.now() - interval;
  base(value => {
    const now = Date.now()
    if(now >= stamp + interval) {
      next(value)
      stamp = now
    }
  })
}

const delay = (base, interval) => next =>
  base(value => setTimeout(() => next(value), interval))

const endWhen = (base, limiter) => next => {
  let emit = true

  limiter(() => emit = false)
  base(value => emit && next(value))
}

const filter = (base, predicate) => next =>
  base(value => predicate(value) && next(value))

const flatMap = (base, mapper) => next =>
  base(value => mapper(value)(next))

const from = values => next => values.forEach(next)

const just = value => next => next(value)

const map = (base, mapper) => next =>
  base(value => next(mapper(value)))

const merge = (...observables) => next =>
  observables.forEach(base => base(next))

const periodic = interval => next => setInterval(next, interval)

const scan = (base, reducer, initial) => next => {
  let state = initial
  next(state)
  base(value => {
    state = reducer(state, value)
    next(state)
  })
}

const take = (base, ammount) => next =>
  base(value => ammount-- > 0 && next(value))

const zip = (merger, ...observables) => next => {
  const stock = Array.from({length} = observables, () => []),
    checkStock = () => stock.every(list => list.length),
    emit = () => next(merger(...stock.map(list => list.shift())))

  observables.forEach((base, index) => base(value => {
    stock[index].push(value)

    checkStock() && emit()
  }))
}

export {
  combine,
  constant,
  debounce,
  delay,
  endWhen,
  filter,
  flatMap,
  from,
  just,
  map,
  merge,
  periodic,
  scan,
  take,
  zip,
}
<commit_msg>Run prettier<commit_after>const combine = (combiner, ...observables) => next => {
  let state = Array(observables.length)

  observables.forEach((base, index) =>
    base(value => {
      state[index] = value

      if (Object.keys(state).length === state.length) next(combiner(...state))
    })
  )
}

const constant = (base, value) => map(base, () => value)

const debounce = (base, interval) => next => {
  let stamp = Date.now() - interval
  base(value => {
    const now = Date.now()
    if (now >= stamp + interval) {
      next(value)
      stamp = now
    }
  })
}

const delay = (base, interval) => next =>
  base(value => setTimeout(() => next(value), interval))

const endWhen = (base, limiter) => next => {
  let emit = true

  limiter(() => (emit = false))
  base(value => emit && next(value))
}

const filter = (base, predicate) => next =>
  base(value => predicate(value) && next(value))

const flatMap = (base, mapper) => next => base(value => mapper(value)(next))

const from = values => next => values.forEach(next)

const just = value => next => next(value)

const map = (base, mapper) => next => base(value => next(mapper(value)))

const merge = (...observables) => next =>
  observables.forEach(base => base(next))

const periodic = interval => next => setInterval(next, interval)

const scan = (base, reducer, initial) => next => {
  let state = initial
  next(state)
  base(value => {
    state = reducer(state, value)
    next(state)
  })
}

const take = (base, ammount) => next =>
  base(value => ammount-- > 0 && next(value))

const zip = (merger, ...observables) => next => {
  const stock = Array.from(({ length } = observables), () => []),
    checkStock = () => stock.every(list => list.length),
    emit = () => next(merger(...stock.map(list => list.shift())))

  observables.forEach((base, index) =>
    base(value => {
      stock[index].push(value)

      checkStock() && emit()
    })
  )
}

export {
  combine,
  constant,
  debounce,
  delay,
  endWhen,
  filter,
  flatMap,
  from,
  just,
  map,
  merge,
  periodic,
  scan,
  take,
  zip
}
<|endoftext|>


<commit_before>const expand    = require('toolz/src/string/expand')
const iterate   = require('toolz/src/async/iterate')
const readFile  = require('toolz/src/file/readFile')
const writeFile = require('toolz/src/file/writeFile')
const isOr      = require('toolz/src/lang/isOr')
const display   = require('./display')
const path      = require('path')
const fs        = require('fs')
const assert    = require('assert')

function tmpls (opts, cb) {
  const license = opts.meta.license
  const tmpl = opts.files
  var files = []
  var filePath

  Object.keys(tmpl).forEach(function (name) {
    if (tmpl[name]) {
      if (isOr(name, 'gitignore', 'eslintrc')) return files.push(name)
      if (isOr(name, 'index', 'test')) return files.push(name + '.js')
      if (name === 'package') return files.push(name + '.json')
      if (name === 'readme') return files.push(name.toUpperCase() + '.md')
      if (name === 'travis') return files.push(name + '.yml')
      if (name === 'license') {
        if (license === 'ISC') return files.push(name.toUpperCase() + '-ISC')
        else if (license === 'MIT') return files.push(name.toUpperCase() + '-MIT')
        else return files.push(name.toUpperCase() + '-UN')
      }
    }
  })
  // console.log(files)

  display.heading('Templates')

  iterate.each(files, function (file, key, next) {
    if (isOr(file, 'gitignore', 'travis.yml', 'eslintrc')) {
      filePath = './.' + file
    } else if (isOr(file, 'LICENSE-MIT', 'LICENSE-ISC', 'LICENSE-UN')) {
      filePath = './' + file.replace(/-(MIT|ISC|UN)/, '')
    } else {
      filePath = './' + file
    }

    return readFile(path.join(__dirname, '../lib/' + file), function (err, res) {
      assert.ifError(err)
      var tmpl = expand(res, opts.meta)
      writeFile(filePath, tmpl, function (err) {
        assert.ifError(err)
        display.event('create:', file, 'white')
        next(null)
      })
    })
  }, function (err, results) {
    assert.ifError(err)
    cb(null)
  })
}

module.exports = tmpls
<commit_msg>refactor: process templates concurrently. (fixed)<commit_after>const expand     = require('toolz/src/string/expand')
const concurrent = require('toolz/src/async/concurrent')
const readFile   = require('toolz/src/file/readFile')
const writeFile  = require('toolz/src/file/writeFile')
const isOr       = require('toolz/src/lang/isOr')
const display    = require('./display')
const path       = require('path')
const fs         = require('fs')
const assert     = require('assert')

function tmpls (opts, cb) {
  const license = opts.meta.license
  const tmpl = opts.files
  var files = []
  var filePath

  Object.keys(tmpl).forEach(function (name) {
    if (tmpl[name]) {
      if (isOr(name, 'gitignore', 'eslintrc')) return files.push(name)
      if (isOr(name, 'index', 'test')) return files.push(name + '.js')
      if (name === 'package') return files.push(name + '.json')
      if (name === 'readme') return files.push(name.toUpperCase() + '.md')
      if (name === 'travis') return files.push(name + '.yml')
      if (name === 'license') {
        if (license === 'ISC') return files.push(name.toUpperCase() + '-ISC')
        else if (license === 'MIT') return files.push(name.toUpperCase() + '-MIT')
        else return files.push(name.toUpperCase() + '-UN')
      }
    }
  })

  display.heading('Templates')

  concurrent.each(files, function (file, key, next) {
    if (isOr(file, 'gitignore', 'travis.yml', 'eslintrc')) {
      filePath = './.' + file
    } else if (isOr(file, 'LICENSE-MIT', 'LICENSE-ISC', 'LICENSE-UN')) {
      filePath = './' + file.replace(/-(MIT|ISC|UN)/, '')
    } else {
      filePath = './' + file
    }

    processFile(filePath, file, opts, function () {
      next(null)
    })
  }, function (err, results) {
    assert.ifError(err)
    cb(null)
  })
}

function processFile (filePath, file, opts, done) {
  return readFile(path.join(__dirname, '../lib/' + file), function (err, res) {
    assert.ifError(err)
    var tmpl = expand(res, opts.meta)
    writeFile(filePath, tmpl, function (err) {
      assert.ifError(err)
      display.event('create:', file, 'white')
      done()
    })
  })
}

module.exports = tmpls
<|endoftext|>


<commit_before>// Copyright 2016 Yahoo Inc.
// Licensed under the terms of the MIT license. Please see LICENSE file in the project root for terms.

module.exports = {
  extends: 'eslint:recommended',

  rules: {
    'block-scoped-var': 'error',
    'block-spacing': 'error',
    'brace-style': ['error', '1tbs', {allowSingleLine: true}],
    camelcase: ['error', {properties: 'never'}],
    'comma-spacing': 'error',
    'comma-style': 'error',
    'computed-property-spacing': 'error',
    curly: 'error',
    'eol-last': 'error',
    eqeqeq: 'error',
    'handle-callback-err': 'error',
    'key-spacing': 'error',
    'keyword-spacing': 'error',
    'linebreak-style': 'error',
    'max-depth': ['error', 2 + 3],
    'max-params': ['error', 8],
    'newline-after-var': 'error',
    'no-array-constructor': 'error',
    'no-caller': 'error',
    'no-console': 'warn',
    'no-eq-null': 'error',
    'no-eval': 'error',
    'no-invalid-this': 'error',
    'no-iterator': 'error',
    'no-lonely-if': 'error',
    'no-loop-func': 'error',
    'no-mixed-spaces-and-tabs': ['error', 'smart-tabs'],
    'no-multi-spaces': 'error',
    'no-multi-str': 'error',
    'no-multiple-empty-lines': 'error',
    'no-nested-ternary': 'error',
    'no-new': 'error',
    'no-new-func': 'error',
    'no-new-object': 'error',
    'no-new-wrappers': 'error',
    'no-proto': 'error',
    'no-script-url': 'error',
    'no-sequences': 'error',
    'no-shadow': 'error',
    'no-spaced-func': 'error',
    'no-throw-literal': 'error',
    'no-trailing-spaces': 'error',
    'no-undef': 'error',
    'no-unneeded-ternary': 'error',
    'no-unused-expressions': 'error',
    'no-unused-vars': 'error',
    'no-use-before-define': 'error',
    'no-useless-escape': 'error',
    'no-whitespace-before-property': 'error',
    'no-with': 'error',
    'operator-linebreak': 'error',
    'quote-props': ['error', 'as-needed'],
    // TODO re-enable when eslint/eslint#6238 is resolved
    // @see https://github.com/eslint/eslint/issues/6238
    // 'require-jsdoc': 'error',
    semi: 'error',
    'semi-spacing': 'error',
    'space-before-blocks': 'error',
    'space-before-function-paren': ['error', {anonymous: 'always', named: 'never'}],
    'space-in-parens': 'error',
    'space-infix-ops': 'error',
    'space-unary-ops': 'error',
    'spaced-comment': 'error',
    // TODO re-enable when eslint/eslint#6238 is resolved
    // @see https://github.com/eslint/eslint/issues/6238
    // 'valid-jsdoc': ['error', {requireReturnDescription: false}],
    'vars-on-top': 'error',
    'wrap-iife': 'error'
  }
};
<commit_msg>Allow a bang marker in block comments<commit_after>// Copyright 2016 Yahoo Inc.
// Licensed under the terms of the MIT license. Please see LICENSE file in the project root for terms.

module.exports = {
  extends: 'eslint:recommended',

  rules: {
    'block-scoped-var': 'error',
    'block-spacing': 'error',
    'brace-style': ['error', '1tbs', {allowSingleLine: true}],
    camelcase: ['error', {properties: 'never'}],
    'comma-spacing': 'error',
    'comma-style': 'error',
    'computed-property-spacing': 'error',
    curly: 'error',
    'eol-last': 'error',
    eqeqeq: 'error',
    'handle-callback-err': 'error',
    'key-spacing': 'error',
    'keyword-spacing': 'error',
    'linebreak-style': 'error',
    'max-depth': ['error', 2 + 3],
    'max-params': ['error', 8],
    'newline-after-var': 'error',
    'no-array-constructor': 'error',
    'no-caller': 'error',
    'no-console': 'warn',
    'no-eq-null': 'error',
    'no-eval': 'error',
    'no-invalid-this': 'error',
    'no-iterator': 'error',
    'no-lonely-if': 'error',
    'no-loop-func': 'error',
    'no-mixed-spaces-and-tabs': ['error', 'smart-tabs'],
    'no-multi-spaces': 'error',
    'no-multi-str': 'error',
    'no-multiple-empty-lines': 'error',
    'no-nested-ternary': 'error',
    'no-new': 'error',
    'no-new-func': 'error',
    'no-new-object': 'error',
    'no-new-wrappers': 'error',
    'no-proto': 'error',
    'no-script-url': 'error',
    'no-sequences': 'error',
    'no-shadow': 'error',
    'no-spaced-func': 'error',
    'no-throw-literal': 'error',
    'no-trailing-spaces': 'error',
    'no-undef': 'error',
    'no-unneeded-ternary': 'error',
    'no-unused-expressions': 'error',
    'no-unused-vars': 'error',
    'no-use-before-define': 'error',
    'no-useless-escape': 'error',
    'no-whitespace-before-property': 'error',
    'no-with': 'error',
    'operator-linebreak': 'error',
    'quote-props': ['error', 'as-needed'],
    // TODO re-enable when eslint/eslint#6238 is resolved
    // @see https://github.com/eslint/eslint/issues/6238
    // 'require-jsdoc': 'error',
    semi: 'error',
    'semi-spacing': 'error',
    'space-before-blocks': 'error',
    'space-before-function-paren': ['error', {anonymous: 'always', named: 'never'}],
    'space-in-parens': 'error',
    'space-infix-ops': 'error',
    'space-unary-ops': 'error',
    'spaced-comment': ['error', 'always', {block: {markers: ['!']}}],
    // TODO re-enable when eslint/eslint#6238 is resolved
    // @see https://github.com/eslint/eslint/issues/6238
    // 'valid-jsdoc': ['error', {requireReturnDescription: false}],
    'vars-on-top': 'error',
    'wrap-iife': 'error'
  }
};
<|endoftext|>


<commit_before>/**
 * Gamepad controls for A-Frame.
 *
 * For more information about the Gamepad API, see:
 * https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API
 */

var GamepadButton = require('./lib/GamepadButton'),
    GamepadButtonEvent = require('./lib/GamepadButtonEvent');

var MAX_DELTA = 0.2,
    PI_2 = Math.PI / 2;

var JOYSTICK_EPS = 0.2;

module.exports = {

  /*******************************************************************
  * Statics
  */

  GamepadButton: GamepadButton,

  /*******************************************************************
  * Schema
  */

  schema: {
    // Controller 0-3
    controller:        { default: 0, oneOf: [0, 1, 2, 3] },

    // Enable/disable features
    enabled:           { default: true },
    movementEnabled:   { default: true },
    lookEnabled:       { default: 'auto', oneOf: ['auto', 'true', 'false']},
    flyEnabled:        { default: false },

    // Constants
    easing:            { default: 20 },
    acceleration:      { default: 65 },
    sensitivity:       { default: 0.04 },

    // Control axes
    pitchAxis:         { default: 'x', oneOf: [ 'x', 'y', 'z' ] },
    yawAxis:           { default: 'y', oneOf: [ 'x', 'y', 'z' ] },
    rollAxis:          { default: 'z', oneOf: [ 'x', 'y', 'z' ] },

    // Debugging
    debug:             { default: false }
  },

  /*******************************************************************
  * Core
  */

  /**
   * Called once when component is attached. Generally for initial setup.
   */
  init: function () {
    var scene = this.el.sceneEl;
    this.prevTime = window.performance.now();

    // Movement
    this.velocity = new THREE.Vector3(0, 0, 0);
    this.direction = new THREE.Vector3(0, 0, 0);
    this.rotation = new THREE.Euler(0, 0, 0, 'YXZ');

    // Rotation
    this.pitch = new THREE.Object3D();
    this.yaw = new THREE.Object3D();
    this.yaw.position.y = 10;
    this.yaw.add(this.pitch);

    // Button state
    this.buttons = {};

    scene.addBehavior(this);

    if (!this.getGamepad()) {
      console.warn(
        'Gamepad #%d not found. Connect controller and press any button to continue.',
        this.data.controller
      );
    }
  },

  /**
   * Called when component is attached and when component data changes.
   * Generally modifies the entity based on the data.
   */
  update: function (previousData) {
    this.updateRotation();
    this.updatePosition(!!previousData);
    this.updateButtonState();
  },

  /**
   * Called when a component is removed (e.g., via removeAttribute).
   * Generally undoes all modifications to the entity.
   */
  remove: function () { },

  /*******************************************************************
  * Movement
  */

  updatePosition: function (reset) {
    var data = this.data;
    var acceleration = data.acceleration;
    var easing = data.easing;
    var velocity = this.velocity;
    var time = window.performance.now();
    var delta = (time - this.prevTime) / 1000;
    var rollAxis = data.rollAxis;
    var pitchAxis = data.pitchAxis;
    var el = this.el;
    var gamepad = this.getGamepad();
    this.prevTime = time;

    // If data has changed or FPS is too low
    // we reset the velocity
    if (reset || delta > MAX_DELTA) {
      velocity[rollAxis] = 0;
      velocity[pitchAxis] = 0;
      return;
    }

    velocity[rollAxis] -= velocity[rollAxis] * easing * delta;
    velocity[pitchAxis] -= velocity[pitchAxis] * easing * delta;

    var position = el.getComputedAttribute('position');

    if (data.enabled && data.movementEnabled && gamepad) {
      var dpad = this.getDpad(),
          inputX = dpad.x || this.getJoystick(0).x,
          inputY = dpad.y || this.getJoystick(0).y;
      if (Math.abs(inputX) > JOYSTICK_EPS) {
        velocity[pitchAxis] += inputX * acceleration * delta;
      }
      if (Math.abs(inputY) > JOYSTICK_EPS) {
        velocity[rollAxis] += inputY * acceleration * delta;
      }
    }

    var movementVector = this.getMovementVector(delta);

    el.object3D.translateX(movementVector.x);
    el.object3D.translateY(movementVector.y);
    el.object3D.translateZ(movementVector.z);

    el.setAttribute('position', {
      x: position.x + movementVector.x,
      y: position.y + movementVector.y,
      z: position.z + movementVector.z
    });
  },

  getMovementVector: function (delta) {
    var elRotation = this.el.getAttribute('rotation');
    this.direction.copy(this.velocity);
    this.direction.multiplyScalar(delta);
    if (!elRotation) { return this.direction; }
    if (!this.data.flyEnabled) { elRotation.x = 0; }
    this.rotation.set(
      THREE.Math.degToRad(elRotation.x),
      THREE.Math.degToRad(elRotation.y),
      0
    );
    this.direction.applyEuler(this.rotation);
    return this.direction;
  },

  /*******************************************************************
  * Rotation
  */

  updateRotation: function () {
    if (this.isLookEnabled() && this.getGamepad()) {
      var lookVector = this.getJoystick(1);
      if (Math.abs(lookVector.x) <= JOYSTICK_EPS) lookVector.x = 0;
      if (Math.abs(lookVector.y) <= JOYSTICK_EPS) lookVector.y = 0;
      lookVector.multiplyScalar(this.data.sensitivity);
      this.yaw.rotation.y -= lookVector.x;
      this.pitch.rotation.x -= lookVector.y;
      this.pitch.rotation.x = Math.max(-PI_2, Math.min(PI_2, this.pitch.rotation.x));

      this.el.setAttribute('rotation', {
        x: THREE.Math.radToDeg(this.pitch.rotation.x),
        y: THREE.Math.radToDeg(this.yaw.rotation.y),
        z: 0
      });
    }
  },

  /*******************************************************************
  * Button events
  */

  updateButtonState: function () {
    var gamepad = this.getGamepad();
    if (this.data.enabled && gamepad) {

      // Fire DOM events for button state changes.
      for (var i = 0; i < gamepad.buttons.length; i++) {
        if (gamepad.buttons[i].pressed && !this.buttons[i]) {
          this.emit(new GamepadButtonEvent('gamepadbuttondown', i, gamepad.buttons[i]));
        } else if (!gamepad.buttons[i].pressed && this.buttons[i]) {
          this.emit(new GamepadButtonEvent('gamepadbuttonup', i, gamepad.buttons[i]));
        }
        this.buttons[i] = gamepad.buttons[i].pressed;
      }

    } else if (Object.keys(this.buttons)) {
      // Reset state if controls are disabled or controller is lost.
      this.buttons = {};
    }
  },

  emit: function (event) {
    // Emit original event.
    this.el.emit(event.type, event);

    // Emit convenience event, identifying button index.
    this.el.emit(
      event.type + ':' + event.index,
      new GamepadButtonEvent(event.type, event.index, event)
    );
  },

  /*******************************************************************
  * Gamepad state
  */

  /**
   * Returns the Gamepad instance attached to the component. If connected,
   * a proxy-controls component may provide access to Gamepad input from a
   * remote device.
   *
   * @return {Gamepad}
   */
  getGamepad: function () {
    var localGamepad = navigator.getGamepads
          && navigator.getGamepads()[this.data.controller],
        proxyControls = this.el.components['proxy-controls'],
        proxyGamepad = proxyControls && proxyControls.isConnected()
          && proxyControls.getGamepad(this.data.controller);
    return proxyGamepad || localGamepad;
  },

  /**
   * Returns the state of the given button.
   * @param  {number} index The button (0-N) for which to find state.
   * @return {GamepadButton}
   */
  getButton: function (index) {
    return this.getGamepad().buttons[index];
  },

  /**
   * Returns state of the given axis. Axes are labelled 0-N, where 0-1 will
   * represent X/Y on the first joystick, and 2-3 X/Y on the second.
   * @param  {number} index The axis (0-N) for which to find state.
   * @return {number} On the interval [-1,1].
   */
  getAxis: function (index) {
    return this.getGamepad().axes[index];
  },

  /**
   * Returns the state of the given joystick (0 or 1) as a THREE.Vector2.
   * @param  {number} id The joystick (0, 1) for which to find state.
   * @return {THREE.Vector2}
   */
  getJoystick: function (index) {
    var gamepad = this.getGamepad();
    switch (index) {
      case 0: return new THREE.Vector2(gamepad.axes[0], gamepad.axes[1]);
      case 1: return new THREE.Vector2(gamepad.axes[2], gamepad.axes[3]);
      default: throw new Error('Unexpected joystick index "%d".', index);
    }
  },

  /**
   * Returns the state of the dpad as a THREE.Vector2.
   * @return {THREE.Vector2}
   */
  getDpad: function () {
    var gamepad = this.getGamepad();
    if (!gamepad.buttons[GamepadButton.DPAD_RIGHT]) {
      return new THREE.Vector2();
    }
    return new THREE.Vector2(
      (gamepad.buttons[GamepadButton.DPAD_RIGHT].pressed ? 1 : 0)
      + (gamepad.buttons[GamepadButton.DPAD_LEFT].pressed ? -1 : 0),
      (gamepad.buttons[GamepadButton.DPAD_UP].pressed ? -1 : 0)
      + (gamepad.buttons[GamepadButton.DPAD_DOWN].pressed ? 1 : 0)
    );
  },

  /**
   * Returns true if the gamepad is currently connected to the system.
   * @return {boolean}
   */
  isConnected: function () {
    var gamepad = this.getGamepad();
    return !!(gamepad && gamepad.connected);
  },

  /**
   * Returns a string containing some information about the controller. Result
   * may vary across browsers, for a given controller.
   * @return {string}
   */
  getID: function () {
    return this.getGamepad().id;
  },

  isLookEnabled: function () {
    if (this.data.lookEnabled !== 'auto') return this.data.lookEnabled === 'true';

    // For 'auto' setting, look-controls component takes priority in VR mode.
    // TODO: This isn't a reliable way to detect VR mode.
    var isVRMode = document.fullscreen || document.mozFullScreen || document.webkitIsFullScreen,
        hasLookControls = !!this.el.components['look-controls'];
    return !(isVRMode && hasLookControls);
  }

};
<commit_msg>Expect proxy-controls on scene, not element.<commit_after>/**
 * Gamepad controls for A-Frame.
 *
 * For more information about the Gamepad API, see:
 * https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API
 */

var GamepadButton = require('./lib/GamepadButton'),
    GamepadButtonEvent = require('./lib/GamepadButtonEvent');

var MAX_DELTA = 0.2,
    PI_2 = Math.PI / 2;

var JOYSTICK_EPS = 0.2;

module.exports = {

  /*******************************************************************
  * Statics
  */

  GamepadButton: GamepadButton,

  /*******************************************************************
  * Schema
  */

  schema: {
    // Controller 0-3
    controller:        { default: 0, oneOf: [0, 1, 2, 3] },

    // Enable/disable features
    enabled:           { default: true },
    movementEnabled:   { default: true },
    lookEnabled:       { default: 'auto', oneOf: ['auto', 'true', 'false']},
    flyEnabled:        { default: false },

    // Constants
    easing:            { default: 20 },
    acceleration:      { default: 65 },
    sensitivity:       { default: 0.04 },

    // Control axes
    pitchAxis:         { default: 'x', oneOf: [ 'x', 'y', 'z' ] },
    yawAxis:           { default: 'y', oneOf: [ 'x', 'y', 'z' ] },
    rollAxis:          { default: 'z', oneOf: [ 'x', 'y', 'z' ] },

    // Debugging
    debug:             { default: false }
  },

  /*******************************************************************
  * Core
  */

  /**
   * Called once when component is attached. Generally for initial setup.
   */
  init: function () {
    var scene = this.el.sceneEl;
    this.prevTime = window.performance.now();

    // Movement
    this.velocity = new THREE.Vector3(0, 0, 0);
    this.direction = new THREE.Vector3(0, 0, 0);
    this.rotation = new THREE.Euler(0, 0, 0, 'YXZ');

    // Rotation
    this.pitch = new THREE.Object3D();
    this.yaw = new THREE.Object3D();
    this.yaw.position.y = 10;
    this.yaw.add(this.pitch);

    // Button state
    this.buttons = {};

    scene.addBehavior(this);

    if (!this.getGamepad()) {
      console.warn(
        'Gamepad #%d not found. Connect controller and press any button to continue.',
        this.data.controller
      );
    }
  },

  /**
   * Called when component is attached and when component data changes.
   * Generally modifies the entity based on the data.
   */
  update: function (previousData) {
    this.updateRotation();
    this.updatePosition(!!previousData);
    this.updateButtonState();
  },

  /**
   * Called when a component is removed (e.g., via removeAttribute).
   * Generally undoes all modifications to the entity.
   */
  remove: function () { },

  /*******************************************************************
  * Movement
  */

  updatePosition: function (reset) {
    var data = this.data;
    var acceleration = data.acceleration;
    var easing = data.easing;
    var velocity = this.velocity;
    var time = window.performance.now();
    var delta = (time - this.prevTime) / 1000;
    var rollAxis = data.rollAxis;
    var pitchAxis = data.pitchAxis;
    var el = this.el;
    var gamepad = this.getGamepad();
    this.prevTime = time;

    // If data has changed or FPS is too low
    // we reset the velocity
    if (reset || delta > MAX_DELTA) {
      velocity[rollAxis] = 0;
      velocity[pitchAxis] = 0;
      return;
    }

    velocity[rollAxis] -= velocity[rollAxis] * easing * delta;
    velocity[pitchAxis] -= velocity[pitchAxis] * easing * delta;

    var position = el.getComputedAttribute('position');

    if (data.enabled && data.movementEnabled && gamepad) {
      var dpad = this.getDpad(),
          inputX = dpad.x || this.getJoystick(0).x,
          inputY = dpad.y || this.getJoystick(0).y;
      if (Math.abs(inputX) > JOYSTICK_EPS) {
        velocity[pitchAxis] += inputX * acceleration * delta;
      }
      if (Math.abs(inputY) > JOYSTICK_EPS) {
        velocity[rollAxis] += inputY * acceleration * delta;
      }
    }

    var movementVector = this.getMovementVector(delta);

    el.object3D.translateX(movementVector.x);
    el.object3D.translateY(movementVector.y);
    el.object3D.translateZ(movementVector.z);

    el.setAttribute('position', {
      x: position.x + movementVector.x,
      y: position.y + movementVector.y,
      z: position.z + movementVector.z
    });
  },

  getMovementVector: function (delta) {
    var elRotation = this.el.getAttribute('rotation');
    this.direction.copy(this.velocity);
    this.direction.multiplyScalar(delta);
    if (!elRotation) { return this.direction; }
    if (!this.data.flyEnabled) { elRotation.x = 0; }
    this.rotation.set(
      THREE.Math.degToRad(elRotation.x),
      THREE.Math.degToRad(elRotation.y),
      0
    );
    this.direction.applyEuler(this.rotation);
    return this.direction;
  },

  /*******************************************************************
  * Rotation
  */

  updateRotation: function () {
    if (this.isLookEnabled() && this.getGamepad()) {
      var lookVector = this.getJoystick(1);
      if (Math.abs(lookVector.x) <= JOYSTICK_EPS) lookVector.x = 0;
      if (Math.abs(lookVector.y) <= JOYSTICK_EPS) lookVector.y = 0;
      lookVector.multiplyScalar(this.data.sensitivity);
      this.yaw.rotation.y -= lookVector.x;
      this.pitch.rotation.x -= lookVector.y;
      this.pitch.rotation.x = Math.max(-PI_2, Math.min(PI_2, this.pitch.rotation.x));

      this.el.setAttribute('rotation', {
        x: THREE.Math.radToDeg(this.pitch.rotation.x),
        y: THREE.Math.radToDeg(this.yaw.rotation.y),
        z: 0
      });
    }
  },

  /*******************************************************************
  * Button events
  */

  updateButtonState: function () {
    var gamepad = this.getGamepad();
    if (this.data.enabled && gamepad) {

      // Fire DOM events for button state changes.
      for (var i = 0; i < gamepad.buttons.length; i++) {
        if (gamepad.buttons[i].pressed && !this.buttons[i]) {
          this.emit(new GamepadButtonEvent('gamepadbuttondown', i, gamepad.buttons[i]));
        } else if (!gamepad.buttons[i].pressed && this.buttons[i]) {
          this.emit(new GamepadButtonEvent('gamepadbuttonup', i, gamepad.buttons[i]));
        }
        this.buttons[i] = gamepad.buttons[i].pressed;
      }

    } else if (Object.keys(this.buttons)) {
      // Reset state if controls are disabled or controller is lost.
      this.buttons = {};
    }
  },

  emit: function (event) {
    // Emit original event.
    this.el.emit(event.type, event);

    // Emit convenience event, identifying button index.
    this.el.emit(
      event.type + ':' + event.index,
      new GamepadButtonEvent(event.type, event.index, event)
    );
  },

  /*******************************************************************
  * Gamepad state
  */

  /**
   * Returns the Gamepad instance attached to the component. If connected,
   * a proxy-controls component may provide access to Gamepad input from a
   * remote device.
   *
   * @return {Gamepad}
   */
  getGamepad: function () {
    var localGamepad = navigator.getGamepads
          && navigator.getGamepads()[this.data.controller],
        proxyControls = this.el.sceneEl.components['proxy-controls'],
        proxyGamepad = proxyControls && proxyControls.isConnected()
          && proxyControls.getGamepad(this.data.controller);
    return proxyGamepad || localGamepad;
  },

  /**
   * Returns the state of the given button.
   * @param  {number} index The button (0-N) for which to find state.
   * @return {GamepadButton}
   */
  getButton: function (index) {
    return this.getGamepad().buttons[index];
  },

  /**
   * Returns state of the given axis. Axes are labelled 0-N, where 0-1 will
   * represent X/Y on the first joystick, and 2-3 X/Y on the second.
   * @param  {number} index The axis (0-N) for which to find state.
   * @return {number} On the interval [-1,1].
   */
  getAxis: function (index) {
    return this.getGamepad().axes[index];
  },

  /**
   * Returns the state of the given joystick (0 or 1) as a THREE.Vector2.
   * @param  {number} id The joystick (0, 1) for which to find state.
   * @return {THREE.Vector2}
   */
  getJoystick: function (index) {
    var gamepad = this.getGamepad();
    switch (index) {
      case 0: return new THREE.Vector2(gamepad.axes[0], gamepad.axes[1]);
      case 1: return new THREE.Vector2(gamepad.axes[2], gamepad.axes[3]);
      default: throw new Error('Unexpected joystick index "%d".', index);
    }
  },

  /**
   * Returns the state of the dpad as a THREE.Vector2.
   * @return {THREE.Vector2}
   */
  getDpad: function () {
    var gamepad = this.getGamepad();
    if (!gamepad.buttons[GamepadButton.DPAD_RIGHT]) {
      return new THREE.Vector2();
    }
    return new THREE.Vector2(
      (gamepad.buttons[GamepadButton.DPAD_RIGHT].pressed ? 1 : 0)
      + (gamepad.buttons[GamepadButton.DPAD_LEFT].pressed ? -1 : 0),
      (gamepad.buttons[GamepadButton.DPAD_UP].pressed ? -1 : 0)
      + (gamepad.buttons[GamepadButton.DPAD_DOWN].pressed ? 1 : 0)
    );
  },

  /**
   * Returns true if the gamepad is currently connected to the system.
   * @return {boolean}
   */
  isConnected: function () {
    var gamepad = this.getGamepad();
    return !!(gamepad && gamepad.connected);
  },

  /**
   * Returns a string containing some information about the controller. Result
   * may vary across browsers, for a given controller.
   * @return {string}
   */
  getID: function () {
    return this.getGamepad().id;
  },

  isLookEnabled: function () {
    if (this.data.lookEnabled !== 'auto') return this.data.lookEnabled === 'true';

    // For 'auto' setting, look-controls component takes priority in VR mode.
    // TODO: This isn't a reliable way to detect VR mode.
    var isVRMode = document.fullscreen || document.mozFullScreen || document.webkitIsFullScreen,
        hasLookControls = !!this.el.components['look-controls'];
    return !(isVRMode && hasLookControls);
  }

};
<|endoftext|>


<commit_before>define(
  'tinymce.themes.mobile.style.Styles',

  [
    'ephox.katamari.api.Fun'
  ],

  function (Fun) {
    var resolve = function (p) {
      return 'tinymce-mobile-' + p;
    };

    return {
      resolve: resolve,
      prefix: Fun.constant('tinymce-mobile')
    };
  }
);
<commit_msg>TM-60: PR fix<commit_after>define(
  'tinymce.themes.mobile.style.Styles',

  [
    'ephox.katamari.api.Fun'
  ],

  function (Fun) {
    var prefix = 'tinymce-mobile';

    var resolve = function (p) {
      return prefix + '-' + p;
    };

    return {
      resolve: resolve,
      prefix: Fun.constant(prefix)
    };
  }
);
<|endoftext|>