<commit_before>/*
 * grunt-contrib-internal
 * http://gruntjs.com/
 *
 * Copyright (c) 2016 jQuery Foundation and other contributors
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {
  var path = require('path');
  grunt.registerTask('contrib-ci', 'Normalizes appveyor and travis ci configs.', function() {
    var travis = grunt.file.read(path.join(__dirname, '..', '.travis.yml'));
    var appveyor = grunt.file.read(path.join(__dirname, '..', 'appveyor.yml'));
    var taskTravis = path.join(process.cwd(), '.travis.yml');
    var taskAppveyor = path.join(process.cwd(), 'appveyor.yml');
    grunt.file.write(taskTravis, travis);
    grunt.file.write(taskAppveyor, appveyor);
    grunt.log.ok('Normalized .travis.yml and appveyor.yml for grunt-contrib.');
  });
};
<commit_msg>Fix license header.<commit_after>/*
 * grunt-contrib-internal
 * http://gruntjs.com/
 *
 * Copyright (c) 2016 Tyler Kellen, contributors
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {
  var path = require('path');
  grunt.registerTask('contrib-ci', 'Normalizes appveyor and travis ci configs.', function() {
    var travis = grunt.file.read(path.join(__dirname, '..', '.travis.yml'));
    var appveyor = grunt.file.read(path.join(__dirname, '..', 'appveyor.yml'));
    var taskTravis = path.join(process.cwd(), '.travis.yml');
    var taskAppveyor = path.join(process.cwd(), 'appveyor.yml');
    grunt.file.write(taskTravis, travis);
    grunt.file.write(taskAppveyor, appveyor);
    grunt.log.ok('Normalized .travis.yml and appveyor.yml for grunt-contrib.');
  });
};
<|endoftext|>


<commit_before>/*
 * grunt-haggerston
 * https://github.com/vitch/grunt-haggerston
 *
 * Copyright (c) 2013 Kelvin Luck
 * Licensed under the MIT license.
 */

'use strict';

var path = require('path');
var swig = require('swig');

var Haggerston = require('./lib/haggerston');

module.exports = function(grunt) {
  grunt.registerTask('haggerston', 'Your task description goes here.', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
          src: 'src',
          out: 'out'
        });

    if (!grunt.file.isDir(options.src)) {
      grunt.fail.warn('options.src is not a valid directory');
    }

    var contentPath = path.join(options.src, 'content');
    var templatesPath = path.join(options.src, 'templates');

    // Set base path that swig will look inside for template files
    swig.init({
      root: templatesPath,
      filters: require('./lib/haggerston-filters')
    });

    // Grab array of json file paths from the src folder
    var jsonFiles = grunt.file.expand(options.src + '/**/*.json');

    var haggerston = new Haggerston(contentPath, jsonFiles);

    // Render each file page to a file
    haggerston.pages.forEach(function(page) {
      console.log(page);
      var outFilePath = path.join(options.out, page.url);
      grunt.verbose.writeln('Generating ' + page.jsonFile.cyan + ' -> ' + outFilePath.cyan);
      grunt.file.write(outFilePath, page.render());
    });

  });
};
<commit_msg>Allowing the user to pass through filters, tags and extensions into the swig initialisation from their grunt file...<commit_after>/*
 * grunt-haggerston
 * https://github.com/vitch/grunt-haggerston
 *
 * Copyright (c) 2013 Kelvin Luck
 * Licensed under the MIT license.
 */

'use strict';

var path = require('path');
var swig = require('swig');
var _ = require('underscore');

var Haggerston = require('./lib/haggerston');

module.exports = function(grunt) {
  grunt.registerTask('haggerston', 'Your task description goes here.', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
          src: 'src',
          out: 'out',
          swigFilters: {},
          swigTags: {},
          swigExtensions: {}
        });

    if (!grunt.file.isDir(options.src)) {
      grunt.fail.warn('options.src is not a valid directory');
    }

    var contentPath = path.join(options.src, 'content');
    var templatesPath = path.join(options.src, 'templates');

    // Initialise swig with the relevant options
    swig.init({
      root: templatesPath,
      filters: _.extend(
        {},
        require('./lib/haggerston-filters'),
        options.swigFilters
      ),
      tags: options.swigTags,
      extensions: options.swigExtensions
    });

    // Grab array of json file paths from the src folder
    var jsonFiles = grunt.file.expand(options.src + '/**/*.json');

    var haggerston = new Haggerston(contentPath, jsonFiles);

    // Render each file page to a file
    haggerston.pages.forEach(function(page) {
      var outFilePath = path.join(options.out, page.url);
      grunt.verbose.writeln('Generating ' + page.jsonFile.cyan + ' -> ' + outFilePath.cyan);
      grunt.file.write(outFilePath, page.render());
    });

  });
};
<|endoftext|>


<commit_before>export default () => {
  let listeners = [];
  let _destroyed = false;

  const on = (fn) => {
    if (_destroyed) {
      return () => {};
    }

    if (typeof fn !== 'function') { // eslint-disable-line lodash/prefer-lodash-typecheck
      throw new TypeError('callback must be a function');
    }

    listeners.push(fn);

    let fired = false;

    return () => {
      if (fired) {
        return;
      }

      fired = true;

      listeners = listeners.filter((cb) => cb !== fn);
    };
  };

  return {
    emit: (...args) => {
      if (_destroyed) {
        return;
      }

      listeners.forEach((fn) => fn(...args));
    },

    destroy () {
      if (_destroyed) {
        return;
      }

      _destroyed = true;
      listeners = [];
    },

    cleanup () {
      if (_destroyed) {
        return;
      }

      listeners = [];
    },

    length () {
      if (_destroyed) {
        return 0;
      }

      return listeners.length;
    },

    once (fn) {
      let fired = false;

      const off = on((...args) => {
        if (fired) {
          return;
        }

        fired = true;

        off();
        fn(...args);
      });

      return off;
    },

    on
  };
};
<commit_msg>replace push to rest in EE<commit_after>export default () => {
  let listeners = [];
  let _destroyed = false;

  const on = (fn) => {
    if (_destroyed) {
      return () => {};
    }

    if (typeof fn !== 'function') { // eslint-disable-line lodash/prefer-lodash-typecheck
      throw new TypeError('callback must be a function');
    }

    listeners = [ ...listeners, fn ];

    let fired = false;

    return () => {
      if (fired) {
        return;
      }

      fired = true;

      listeners = listeners.filter((cb) => cb !== fn);
    };
  };

  return {
    emit: (...args) => {
      if (_destroyed) {
        return;
      }

      listeners.forEach((fn) => fn(...args));
    },

    destroy () {
      if (_destroyed) {
        return;
      }

      _destroyed = true;
      listeners = [];
    },

    cleanup () {
      if (_destroyed) {
        return;
      }

      listeners = [];
    },

    length () {
      if (_destroyed) {
        return 0;
      }

      return listeners.length;
    },

    once (fn) {
      let fired = false;

      const off = on((...args) => {
        if (fired) {
          return;
        }

        fired = true;

        off();
        fn(...args);
      });

      return off;
    },

    on
  };
};
<|endoftext|>


<commit_before>'use strict';
const Bluebird = require('bluebird');
const fs = require('fs');
const config = require('config');
const path = require('path');
const pkg = require(path.join(process.cwd(), 'package.json'));
const cliOpts = require('./cli-options.js');
const chalk = require('chalk');
const baseRoutePrefix = '/api/v' + pkg.version;
const baseRoutePath = path.join(__dirname, '../app-routes/');

const schema = JSON.parse(
    fs.readFileSync(config.get('permissionsSchemaPath'), 'utf8')
);

    const getAppRouteConfig = (relPath, prefix) => {
    let routePrefix = baseRoutePrefix;
    if (prefix) {
        routePrefix = path.join(baseRoutePrefix, prefix);
    }

    return {
        register: require(path.join(baseRoutePath, relPath)),
        registrationOptions: {
            routes: {
                prefix: routePrefix
            }
        }
    };
};

// Define plugins
var plugins = [
    require('inject-then'),
    require('hapi-auth-hawk'),
    {
        register: require('hapi-redis'),
        options: require('./get-redis-config.js')(),
        afterRegistration: function promisifyRedisClient(server) {
            var redis = server.plugins['hapi-redis'];
            Bluebird.promisifyAll(redis.client);
            return;
        }
    },
    {
        register: require('good'),
        options: require('./get-good-config.js')()
    },
    {
        register: require('hapi-bookshelf-models'),
        options: {
            knex: require('./get-knex-config.js')(),
            plugins: ['registry'],
            base: require('./get-base-model.js'),
            models: path.resolve(__dirname, '../models/')
        }
    },
    {
        register: require('hapi-relations'),
        options: {
            schema: schema,
            client: 'hapi-redis',
            clientType: 'redis',
            pluginClient: true
        }
    },
    {
        register: require('./response-formatter.js'),
        options: {
            excludeVarieties: ['view', 'file'],
            excludePlugins: ['hapi-swagger']
        }
    },
    require('./authentication.js'),
    require('inert'),
    require('vision'),
    {
        register: require('hapi-swagger'),
        options: {
            apiVersion: pkg.version
        },
        registrationOptions: {
            routes: {
                prefix: '/api/v' + pkg.version
            }
        }
    },
    getAppRouteConfig('common/auth/keys.js', 'auth'),
    getAppRouteConfig('common/auth/cookies.js', 'auth'),
    getAppRouteConfig('common/users.js'),
    getAppRouteConfig('coins/scans.js'),
    {
        register: require('./version-route.js'),
        registrationOptions: {
            routes: {
                prefix: '/api'
            }
        }
    }
];

if (cliOpts.coinstac) {
    console.log(chalk.blue('Including COINSTAC routes'));
    plugins.push({
        register: require('./houchdb.js'),
        options: config.get('coinstac.pouchdb.consortiaMeta')
    });
    plugins.push(getAppRouteConfig('coinstac/consortia.js', 'coinstac'));
}

module.exports = () => { return plugins; };
<commit_msg>remove bogus indent<commit_after>'use strict';
const Bluebird = require('bluebird');
const fs = require('fs');
const config = require('config');
const path = require('path');
const pkg = require(path.join(process.cwd(), 'package.json'));
const cliOpts = require('./cli-options.js');
const chalk = require('chalk');
const baseRoutePrefix = '/api/v' + pkg.version;
const baseRoutePath = path.join(__dirname, '../app-routes/');

const schema = JSON.parse(
    fs.readFileSync(config.get('permissionsSchemaPath'), 'utf8')
);

const getAppRouteConfig = (relPath, prefix) => {
    let routePrefix = baseRoutePrefix;
    if (prefix) {
        routePrefix = path.join(baseRoutePrefix, prefix);
    }

    return {
        register: require(path.join(baseRoutePath, relPath)),
        registrationOptions: {
            routes: {
                prefix: routePrefix
            }
        }
    };
};

// Define plugins
var plugins = [
    require('inject-then'),
    require('hapi-auth-hawk'),
    {
        register: require('hapi-redis'),
        options: require('./get-redis-config.js')(),
        afterRegistration: function promisifyRedisClient(server) {
            var redis = server.plugins['hapi-redis'];
            Bluebird.promisifyAll(redis.client);
            return;
        }
    },
    {
        register: require('good'),
        options: require('./get-good-config.js')()
    },
    {
        register: require('hapi-bookshelf-models'),
        options: {
            knex: require('./get-knex-config.js')(),
            plugins: ['registry'],
            base: require('./get-base-model.js'),
            models: path.resolve(__dirname, '../models/')
        }
    },
    {
        register: require('hapi-relations'),
        options: {
            schema: schema,
            client: 'hapi-redis',
            clientType: 'redis',
            pluginClient: true
        }
    },
    {
        register: require('./response-formatter.js'),
        options: {
            excludeVarieties: ['view', 'file'],
            excludePlugins: ['hapi-swagger']
        }
    },
    require('./authentication.js'),
    require('inert'),
    require('vision'),
    {
        register: require('hapi-swagger'),
        options: {
            apiVersion: pkg.version
        },
        registrationOptions: {
            routes: {
                prefix: '/api/v' + pkg.version
            }
        }
    },
    getAppRouteConfig('common/auth/keys.js', 'auth'),
    getAppRouteConfig('common/auth/cookies.js', 'auth'),
    getAppRouteConfig('common/users.js'),
    getAppRouteConfig('coins/scans.js'),
    {
        register: require('./version-route.js'),
        registrationOptions: {
            routes: {
                prefix: '/api'
            }
        }
    }
];

if (cliOpts.coinstac) {
    console.log(chalk.blue('Including COINSTAC routes'));
    plugins.push({
        register: require('./houchdb.js'),
        options: config.get('coinstac.pouchdb.consortiaMeta')
    });
    plugins.push(getAppRouteConfig('coinstac/consortia.js', 'coinstac'));
}

module.exports = () => { return plugins; };
<|endoftext|>


<commit_before>var $$cache = exports.$$cache || {};
var $$internals = exports.$$internals || {};
var $$pending = exports.$$pending || {};

var define = function (name) {
    var args = Array.prototype.slice.call(arguments);
    if (typeof args[1] === 'function') {
        exports[name] = args[1]();
    } else {
        $$cache[name] = args[2];
        $$cache[name].$inject = args[1];
        $$cache[name].$internal = false;
    }
};

var internal = function (name) {
    var args = Array.prototype.slice.call(arguments);
    if (typeof args[1] === 'function') {
        $$internals[name] = args[1]();
    } else {
        $$cache[name] = args[2];
        $$cache[name].$inject = args[1];
        $$cache[name].$internal = true;
    }
};

var resolve = function (name, fn) {

    $$pending[name] = true;

    var injections = fn.$inject;
    var args = [];
    var injectionName;
    for (var i in injections) {
        injectionName = injections[i];
        if ($$cache[injectionName]) {
            if ($$pending.hasOwnProperty(injectionName)) {
                throw new Error('Cyclical reference: "' + name + '" referencing "' + injectionName + '"');
            }
            resolve(injectionName, $$cache[injectionName]);
            delete $$cache[injectionName];
        }

    }

    if (!exports[name] && !$$internals[name]) {
        for (var n in injections) {
            injectionName = injections[n];
            args.push(exports[injectionName] || $$internals[injectionName]);
        }
        if (fn.$internal) {
            $$internals[name] = fn.apply(null, args) || true;
        } else {
            exports[name] = fn.apply(null, args) || true;
        }
    }

    exports.$$cache = $$cache;
    exports.$$internals = $$internals;
    exports.$$pending = $$pending;

    delete $$pending[name];
};<commit_msg>if no return val, defaults to name of definition<commit_after>var $$cache = exports.$$cache || {};
var $$internals = exports.$$internals || {};
var $$pending = exports.$$pending || {};

var define = function (name) {
    var args = Array.prototype.slice.call(arguments);
    if (typeof args[1] === 'function') {
        exports[name] = args[1]();
    } else {
        $$cache[name] = args[2];
        $$cache[name].$inject = args[1];
        $$cache[name].$internal = false;
    }
};

var internal = function (name) {
    var args = Array.prototype.slice.call(arguments);
    if (typeof args[1] === 'function') {
        $$internals[name] = args[1]();
    } else {
        $$cache[name] = args[2];
        $$cache[name].$inject = args[1];
        $$cache[name].$internal = true;
    }
};

var resolve = function (name, fn) {

    $$pending[name] = true;

    var injections = fn.$inject;
    var args = [];
    var injectionName;
    for (var i in injections) {
        injectionName = injections[i];
        if ($$cache[injectionName]) {
            if ($$pending.hasOwnProperty(injectionName)) {
                throw new Error('Cyclical reference: "' + name + '" referencing "' + injectionName + '"');
            }
            resolve(injectionName, $$cache[injectionName]);
            delete $$cache[injectionName];
        }

    }

    if (!exports[name] && !$$internals[name]) {
        for (var n in injections) {
            injectionName = injections[n];
            args.push(exports[injectionName] || $$internals[injectionName]);
        }
        if (fn.$internal) {
            $$internals[name] = fn.apply(null, args) || name;
        } else {
            exports[name] = fn.apply(null, args) || name;
        }
    }

    exports.$$cache = $$cache;
    exports.$$internals = $$internals;
    exports.$$pending = $$pending;

    delete $$pending[name];
};<|endoftext|>


<commit_before>// TODO refactor this smelly code!
const loaderDefaults = require('../config').loader;
const getAllModules = require('./get-all-modules');
const isModuleShouldBeExtracted = require('./is-module-should-be-extracted');
const getLoaderOptions = require('./get-loader-options');
const getLoadersRules = require('./get-loaders-rules');
const getMatchedRule = require('./get-matched-rule');
const getModuleChunk = require('./get-module-chunk');
const interpolate = require('./interpolate');

const spriteLoaderPath = require.resolve('../loader');

class MappedListItem {
  /**
   * @param {SpriteSymbol} symbol
   * @param {NormalModule} module
   * @param {string} spriteFilename
   */
  constructor(symbol, module, spriteFilename) {
    this.symbol = symbol;
    this.module = module;
    this.resource = symbol.request.file;
    this.spriteFilename = spriteFilename;
  }

  get url() {
    return `${this.spriteFilename}#${this.symbol.id}`;
  }

  get useUrl() {
    return `${this.spriteFilename}#${this.symbol.useId}`;
  }
}

class MappedList {
  /**
   * @param {SpriteSymbol[]} symbols
   * @param {Compilation} compilation
   */
  constructor(symbols, compilation, shouldLog = false) {
    const { compiler } = compilation;

    this.symbols = symbols;
    this.rules = getLoadersRules(compiler);
    this.allModules = getAllModules(compilation);
    this.spriteModules = this.allModules.filter(isModuleShouldBeExtracted);
    this.shouldLog = shouldLog;
    this.items = this.create();
  }

  /**
   * @param {MappedListItem[]} data
   * @return {Object<string, MappedListItem>}
   */
  static groupItemsBySpriteFilename(data) {
    return data
      .map(item => item.spriteFilename)
      .filter((value, index, self) => self.indexOf(value) === index)
      .reduce((acc, spriteFilename) => {
        acc[spriteFilename] = data.filter(item => item.spriteFilename === spriteFilename);
        return acc;
      }, {});
  }

  /**
   * @param {MappedListItem[]} data
   * @param {Function} [mapper] Custom grouper function
   * @return {Object<string, MappedListItem>}
   */
  static groupItemsBySymbolFile(data, mapper) {
    return data.reduce((acc, item) => {
      if (mapper) {
        mapper(acc, item);
      } else {
        acc[item.resource] = item;
      }
      return acc;
    }, {});
  }

  /**
   * @return {MappedListItem[]}
   */
  create() {
    const { symbols, spriteModules, allModules, rules } = this;
    const data = symbols.reduce((acc, symbol) => {
      const resource = symbol.request.file;
      const module = spriteModules.find(m => 'resource' in m
        ? m.resource.split('?')[0] === resource
        : false
      );
      const rule = getMatchedRule(resource, rules);
      const options = rule ? getLoaderOptions(spriteLoaderPath, rule) : null;
      let spriteFilename = (options && options.spriteFilename)
        ? options.spriteFilename
        : loaderDefaults.spriteFilename;

      const chunk = module ? getModuleChunk(module, allModules) : null;

      if (typeof spriteFilename !== 'function' && chunk && chunk.name) {
        spriteFilename = spriteFilename.replace('[chunkname]', chunk.name);
      } else if (typeof spriteFilename === 'function') {
        spriteFilename = spriteFilename(resource);
      }

      if (rule && module) {
        acc.push(new MappedListItem(symbol, module, spriteFilename));
      }

      return acc;
    }, []);

    // Additional pass to interpolate [hash] in spriteFilename
    const itemsBySpriteFilename = MappedList.groupItemsBySpriteFilename(data);
    const filenames = Object.keys(itemsBySpriteFilename);

    filenames.forEach((filename) => {
      if (!filename.includes('hash')) {
        return;
      }

      const items = itemsBySpriteFilename[filename];
      const spriteSymbols = items.map(item => item.symbol);
      const content = spriteSymbols.map(s => s.render()).join('');
      const interpolatedName = interpolate(filename, {
        resourcePath: filename,
        content
      });

      items
        .filter(item => item.spriteFilename !== interpolatedName)
        .forEach(item => item.spriteFilename = interpolatedName);
    });

    return data;
  }

  /**
   * @return {Object<string, MappedListItem>}
   */
  groupItemsBySpriteFilename() {
    return MappedList.groupItemsBySpriteFilename(this.items);
  }

  /**
   * @param {Function} [mapper] Custom grouper function
   * @return {Object<string, MappedListItem>}
   */
  groupItemsBySymbolFile(mapper) {
    return MappedList.groupItemsBySymbolFile(this.items, mapper);
  }
}

module.exports = MappedList;
<commit_msg>fix(utils): fix linting errors<commit_after>// TODO refactor this smelly code!
const loaderDefaults = require('../config').loader;
const getAllModules = require('./get-all-modules');
const isModuleShouldBeExtracted = require('./is-module-should-be-extracted');
const getLoaderOptions = require('./get-loader-options');
const getLoadersRules = require('./get-loaders-rules');
const getMatchedRule = require('./get-matched-rule');
const getModuleChunk = require('./get-module-chunk');
const interpolate = require('./interpolate');

const spriteLoaderPath = require.resolve('../loader');

class MappedListItem {
  /**
   * @param {SpriteSymbol} symbol
   * @param {NormalModule} module
   * @param {string} spriteFilename
   */
  constructor(symbol, module, spriteFilename) {
    this.symbol = symbol;
    this.module = module;
    this.resource = symbol.request.file;
    this.spriteFilename = spriteFilename;
  }

  get url() {
    return `${this.spriteFilename}#${this.symbol.id}`;
  }

  get useUrl() {
    return `${this.spriteFilename}#${this.symbol.useId}`;
  }
}

class MappedList {
  /**
   * @param {SpriteSymbol[]} symbols
   * @param {Compilation} compilation
   */
  constructor(symbols, compilation, shouldLog = false) {
    const { compiler } = compilation;

    this.symbols = symbols;
    this.rules = getLoadersRules(compiler);
    this.allModules = getAllModules(compilation);
    this.spriteModules = this.allModules.filter(isModuleShouldBeExtracted);
    this.shouldLog = shouldLog;
    this.items = this.create();
  }

  /**
   * @param {MappedListItem[]} data
   * @return {Object<string, MappedListItem>}
   */
  static groupItemsBySpriteFilename(data) {
    return data
      .map(item => item.spriteFilename)
      .filter((value, index, self) => self.indexOf(value) === index)
      .reduce((acc, spriteFilename) => {
        acc[spriteFilename] = data.filter(item => item.spriteFilename === spriteFilename);
        return acc;
      }, {});
  }

  /**
   * @param {MappedListItem[]} data
   * @param {Function} [mapper] Custom grouper function
   * @return {Object<string, MappedListItem>}
   */
  static groupItemsBySymbolFile(data, mapper) {
    return data.reduce((acc, item) => {
      if (mapper) {
        mapper(acc, item);
      } else {
        acc[item.resource] = item;
      }
      return acc;
    }, {});
  }

  /**
   * @return {MappedListItem[]}
   */
  create() {
    const { symbols, spriteModules, allModules, rules } = this;
    const data = symbols.reduce((acc, symbol) => {
      const resource = symbol.request.file;
      const module = spriteModules.find((m) => {
        return 'resource' in m ? m.resource.split('?')[0] === resource : false;
      });
      const rule = getMatchedRule(resource, rules);
      const options = rule ? getLoaderOptions(spriteLoaderPath, rule) : null;
      let spriteFilename = (options && options.spriteFilename)
        ? options.spriteFilename
        : loaderDefaults.spriteFilename;

      const chunk = module ? getModuleChunk(module, allModules) : null;

      if (typeof spriteFilename !== 'function' && chunk && chunk.name) {
        spriteFilename = spriteFilename.replace('[chunkname]', chunk.name);
      } else if (typeof spriteFilename === 'function') {
        spriteFilename = spriteFilename(resource);
      }

      if (rule && module) {
        acc.push(new MappedListItem(symbol, module, spriteFilename));
      }

      return acc;
    }, []);

    // Additional pass to interpolate [hash] in spriteFilename
    const itemsBySpriteFilename = MappedList.groupItemsBySpriteFilename(data);
    const filenames = Object.keys(itemsBySpriteFilename);

    filenames.forEach((filename) => {
      if (!filename.includes('hash')) {
        return;
      }

      const items = itemsBySpriteFilename[filename];
      const spriteSymbols = items.map(item => item.symbol);
      const content = spriteSymbols.map(s => s.render()).join('');
      const interpolatedName = interpolate(filename, {
        resourcePath: filename,
        content
      });

      items
        .filter(item => item.spriteFilename !== interpolatedName)
        .forEach(item => item.spriteFilename = interpolatedName);
    });

    return data;
  }

  /**
   * @return {Object<string, MappedListItem>}
   */
  groupItemsBySpriteFilename() {
    return MappedList.groupItemsBySpriteFilename(this.items);
  }

  /**
   * @param {Function} [mapper] Custom grouper function
   * @return {Object<string, MappedListItem>}
   */
  groupItemsBySymbolFile(mapper) {
    return MappedList.groupItemsBySymbolFile(this.items, mapper);
  }
}

module.exports = MappedList;
<|endoftext|>


<commit_before>/**
 * pty.js
 * Copyright (c) 2012, Christopher Jeffrey (MIT License)
 * Binding to the pseudo terminals.
 */

var net = require('net');
var tty = require('tty');
var pty = require('../build/Release/pty.node');

/**
 * Terminal
 */

// Example:
//  var term = new Terminal('bash', [], {
//    name: 'xterm-color',
//    cols: 80,
//    rows: 24,
//    cwd: process.env.HOME,
//    env: process.env
//  });

function Terminal(file, args, opt) {
  if (!(this instanceof Terminal)) {
    return new Terminal(file, args, opt);
  }

  var self = this
    , env
    , cwd
    , name
    , cols
    , rows
    , term;

  // backward compatibility
  if (typeof args === 'string') {
    opt = {
      name: arguments[1],
      cols: arguments[2],
      rows: arguments[3],
      cwd: process.env.HOME
    };
    args = [];
  }

  // arguments
  args = args || [];
  file = file || 'sh';
  opt = opt || {};

  cols = opt.cols || 80;
  rows = opt.rows || 24;

  if (opt.env && opt.sanitize) {
    env = merge({}, opt.env);
  } else {
    env = merge({}, process.env);

    // Make sure we didn't start our server from inside tmux.
    delete env.TMUX;
    delete env.TMUX_PANE;

    // Make sure we didn't start our server from inside screen.
    // http://web.mit.edu/gnu/doc/html/screen_20.html
    delete env.WINDOW;
    delete env.STY;

    // Delete some variables that might confuse our terminal.
    delete env.WINDOWID;
    delete env.TERMCAP;
    delete env.COLUMNS;
    delete env.LINES;

    env = merge(env, opt.env || {});

    // Set some basic env variables.
    // env.USER = ;
    // env.SHELL = ;
    // env.HOME = ;
    // env.LOGNAME = ;
    // env.WINDOWID = ;
  }

  cwd = opt.cwd || process.cwd();
  name = opt.name || env.TERM || 'xterm';
  env.TERM = name;

  env = environ(env);

  // fork
  term = opt.uid && opt.gid
    ? pty.fork(file, args, env, cwd, cols, rows, opt.uid, opt.gid)
    : pty.fork(file, args, env, cwd, cols, rows);

  this.socket = new tty.ReadStream(term.fd);
  this.socket.setEncoding('utf8');
  this.socket.resume();

  // setup
  this.socket.on('error', function(err) {
    // close
    self._close();

    // EIO, happens when someone closes our child
    // process: the only process in the terminal.
    // node < 0.6.14: errno 5
    // node >= 0.6.14: read EIO
    if (err.code) {
      if (~err.code.indexOf('errno 5')
          || ~err.code.indexOf('EIO')) return;
    }

    // throw anything else
    if (self.listeners('error').length < 2) {
      throw err;
    }
  });

  this.pid = term.pid;
  this.fd = term.fd;
  this.pty = term.pty;

  this.file = file;
  this.name = name;
  this.cols = cols;
  this.rows = rows;

  this.readable = true;
  this.writable = true;

  Terminal.total++;
  this.socket.on('close', function() {
    Terminal.total--;
    self._close();
    self.emit('exit', null);
  });

  env = null;
}

Terminal.fork =
Terminal.spawn =
Terminal.createTerminal = function(file, args, opt) {
  return new Terminal(file, args, opt);
};

/**
 * openpty
 */

Terminal.open = function(opt) {
  var self = Object.create(Terminal.prototype)
    , opt = opt || {};

  if (arguments.length > 1) {
    opt = {
      cols: arguments[1],
      rows: arguments[2]
    };
  }

  var cols = opt.cols || 80
    , rows = opt.rows || 24
    , term;

  // open
  term = pty.open(cols, rows);

  self.master = new net.Socket(term.master);
  self.master.setEncoding('utf8');
  self.master.resume();

  self.slave = new net.Socket(term.slave);
  self.slave.setEncoding('utf8');
  self.slave.resume();

  self.socket = self.master;
  self.pid = null;
  self.fd = term.master;
  self.pty = term.pty;

  self.file = process.argv[0] || 'node';
  self.name = process.env.TERM || '';
  self.cols = cols;
  self.rows = rows;

  self.readable = true;
  self.writable = true;

  self.socket.on('error', function(err) {
    self._close();
    if (self.listeners('error').length < 2) {
      throw err;
    }
  });

  Terminal.total++;
  self.socket.on('close', function() {
    Terminal.total--;
    self._close();
  });

  return self;
};

/**
 * Total
 */

// Keep track of the total
// number of terminals for
// the process.
Terminal.total = 0;

/**
 * Events
 */

// Don't inherit from net.Socket in
// order to avoid collisions.

Terminal.prototype.write = function(data) {
  return this.socket.write(data);
};

Terminal.prototype.end = function(data) {
  return this.socket.end(data);
};

Terminal.prototype.pipe = function(dest, options) {
  return this.socket.pipe(dest, options);
};

Terminal.prototype.pause = function() {
  this.socket.pause();
};

Terminal.prototype.resume = function() {
  this.socket.resume();
};

Terminal.prototype.setEncoding = function(enc) {
  if (this.socket._decoder) {
    delete this.socket._decoder;
  }
  if (enc) {
    this.socket.setEncoding(enc);
  }
};

Terminal.prototype.addListener =
Terminal.prototype.on = function(type, func) {
  this.socket.on(type, func);
  return this;
};

Terminal.prototype.emit = function() {
  return this.socket.emit.apply(this.socket, arguments);
};

Terminal.prototype.listeners = function(type) {
  return this.socket.listeners(type);
};

Terminal.prototype.removeListener = function(type, func) {
  this.socket.removeListener(type, func);
  return this;
};

Terminal.prototype.removeAllListeners = function(type) {
  this.socket.removeAllListeners(type);
  return this;
};

Terminal.prototype.once = function(type, func) {
  this.socket.once(type, func);
  return this;
};

Terminal.prototype.__defineGetter__('stdin', function() {
  return this;
});

Terminal.prototype.__defineGetter__('stdout', function() {
  return this;
});

Terminal.prototype.__defineGetter__('stderr', function() {
  throw new Error('No stderr.');
});

/**
 * TTY
 */

Terminal.prototype.resize = function(cols, rows) {
  cols = cols || 80;
  rows = rows || 24;

  this.cols = cols;
  this.rows = rows;

  pty.resize(this.fd, cols, rows);
};

Terminal.prototype.destroy = function() {
  var self = this;

  // close
  this._close();

  // Need to close the read stream so
  // node stops reading a dead file descriptor.
  // Then we can safely SIGHUP the shell.
  this.socket.once('close', function() {
    self.kill('SIGHUP');
  });

  this.socket.destroy();
};

Terminal.prototype.kill = function(sig) {
  try {
    process.kill(this.pid, sig || 'SIGHUP');
  } catch(e) {
    ;
  }
};

Terminal.prototype.__defineGetter__('process', function() {
  return pty.process(this.fd, this.pty) || this.file;
});

Terminal.prototype._close = function() {
  this.socket.writable = false;
  this.socket.readable = false;
  this.write = function() {};
  this.end = function() {};
  this.writable = false;
  this.readable = false;
};

/**
 * Helpers
 */

function merge(a) {
  var a = a || {}
    , keys
    , b
    , i
    , j;

  for (i = 1; i < arguments.length; i++) {
    b = arguments[i] || {};
    keys = Object.keys(b);
    for (j = 0; j < keys.length; j++) {
      a[keys[j]] = b[keys[j]];
    }
  }

  return a;
}

function environ(env) {
  var keys = Object.keys(env || {})
    , l = keys.length
    , i = 0
    , pairs = [];

  for (; i < l; i++) {
    pairs.push(keys[i] + '=' + env[keys[i]]);
  }

  return pairs;
}

/**
 * Expose
 */

exports = Terminal;
exports.Terminal = Terminal;
exports.native = pty;
module.exports = exports;
<commit_msg>conform to child_process.spawn behavior more.<commit_after>/**
 * pty.js
 * Copyright (c) 2012, Christopher Jeffrey (MIT License)
 * Binding to the pseudo terminals.
 */

var net = require('net');
var tty = require('tty');
var pty = require('../build/Release/pty.node');

/**
 * Terminal
 */

// Example:
//  var term = new Terminal('bash', [], {
//    name: 'xterm-color',
//    cols: 80,
//    rows: 24,
//    cwd: process.env.HOME,
//    env: process.env
//  });

function Terminal(file, args, opt) {
  if (!(this instanceof Terminal)) {
    return new Terminal(file, args, opt);
  }

  var self = this
    , env
    , cwd
    , name
    , cols
    , rows
    , term;

  // backward compatibility
  if (typeof args === 'string') {
    opt = {
      name: arguments[1],
      cols: arguments[2],
      rows: arguments[3],
      cwd: process.env.HOME
    };
    args = [];
  }

  // arguments
  args = args || [];
  file = file || 'sh';
  opt = opt || {};

  cols = opt.cols || 80;
  rows = opt.rows || 24;

  opt.env = opt.env || process.env;
  env = merge({}, opt.env);

  if (opt.env === process.env) {
    // Make sure we didn't start our
    // server from inside tmux.
    delete env.TMUX;
    delete env.TMUX_PANE;

    // Make sure we didn't start
    // our server from inside screen.
    // http://web.mit.edu/gnu/doc/html/screen_20.html
    delete env.STY;
    delete env.WINDOW;

    // Delete some variables that
    // might confuse our terminal.
    delete env.WINDOWID;
    delete env.TERMCAP;
    delete env.COLUMNS;
    delete env.LINES;
  }

  // Could set some basic env vars
  // here, if they do not exist:
  // USER, SHELL, HOME, LOGNAME, WINDOWID

  cwd = opt.cwd || process.cwd();
  name = opt.name || env.TERM || 'xterm';
  env.TERM = name;

  env = environ(env);

  // fork
  term = opt.uid && opt.gid
    ? pty.fork(file, args, env, cwd, cols, rows, opt.uid, opt.gid)
    : pty.fork(file, args, env, cwd, cols, rows);

  this.socket = new tty.ReadStream(term.fd);
  this.socket.setEncoding('utf8');
  this.socket.resume();

  // setup
  this.socket.on('error', function(err) {
    // close
    self._close();

    // EIO, happens when someone closes our child
    // process: the only process in the terminal.
    // node < 0.6.14: errno 5
    // node >= 0.6.14: read EIO
    if (err.code) {
      if (~err.code.indexOf('errno 5')
          || ~err.code.indexOf('EIO')) return;
    }

    // throw anything else
    if (self.listeners('error').length < 2) {
      throw err;
    }
  });

  this.pid = term.pid;
  this.fd = term.fd;
  this.pty = term.pty;

  this.file = file;
  this.name = name;
  this.cols = cols;
  this.rows = rows;

  this.readable = true;
  this.writable = true;

  Terminal.total++;
  this.socket.on('close', function() {
    Terminal.total--;
    self._close();
    self.emit('exit', null);
  });

  env = null;
}

Terminal.fork =
Terminal.spawn =
Terminal.createTerminal = function(file, args, opt) {
  return new Terminal(file, args, opt);
};

/**
 * openpty
 */

Terminal.open = function(opt) {
  var self = Object.create(Terminal.prototype)
    , opt = opt || {};

  if (arguments.length > 1) {
    opt = {
      cols: arguments[1],
      rows: arguments[2]
    };
  }

  var cols = opt.cols || 80
    , rows = opt.rows || 24
    , term;

  // open
  term = pty.open(cols, rows);

  self.master = new net.Socket(term.master);
  self.master.setEncoding('utf8');
  self.master.resume();

  self.slave = new net.Socket(term.slave);
  self.slave.setEncoding('utf8');
  self.slave.resume();

  self.socket = self.master;
  self.pid = null;
  self.fd = term.master;
  self.pty = term.pty;

  self.file = process.argv[0] || 'node';
  self.name = process.env.TERM || '';
  self.cols = cols;
  self.rows = rows;

  self.readable = true;
  self.writable = true;

  self.socket.on('error', function(err) {
    self._close();
    if (self.listeners('error').length < 2) {
      throw err;
    }
  });

  Terminal.total++;
  self.socket.on('close', function() {
    Terminal.total--;
    self._close();
  });

  return self;
};

/**
 * Total
 */

// Keep track of the total
// number of terminals for
// the process.
Terminal.total = 0;

/**
 * Events
 */

// Don't inherit from net.Socket in
// order to avoid collisions.

Terminal.prototype.write = function(data) {
  return this.socket.write(data);
};

Terminal.prototype.end = function(data) {
  return this.socket.end(data);
};

Terminal.prototype.pipe = function(dest, options) {
  return this.socket.pipe(dest, options);
};

Terminal.prototype.pause = function() {
  this.socket.pause();
};

Terminal.prototype.resume = function() {
  this.socket.resume();
};

Terminal.prototype.setEncoding = function(enc) {
  if (this.socket._decoder) {
    delete this.socket._decoder;
  }
  if (enc) {
    this.socket.setEncoding(enc);
  }
};

Terminal.prototype.addListener =
Terminal.prototype.on = function(type, func) {
  this.socket.on(type, func);
  return this;
};

Terminal.prototype.emit = function() {
  return this.socket.emit.apply(this.socket, arguments);
};

Terminal.prototype.listeners = function(type) {
  return this.socket.listeners(type);
};

Terminal.prototype.removeListener = function(type, func) {
  this.socket.removeListener(type, func);
  return this;
};

Terminal.prototype.removeAllListeners = function(type) {
  this.socket.removeAllListeners(type);
  return this;
};

Terminal.prototype.once = function(type, func) {
  this.socket.once(type, func);
  return this;
};

Terminal.prototype.__defineGetter__('stdin', function() {
  return this;
});

Terminal.prototype.__defineGetter__('stdout', function() {
  return this;
});

Terminal.prototype.__defineGetter__('stderr', function() {
  throw new Error('No stderr.');
});

/**
 * TTY
 */

Terminal.prototype.resize = function(cols, rows) {
  cols = cols || 80;
  rows = rows || 24;

  this.cols = cols;
  this.rows = rows;

  pty.resize(this.fd, cols, rows);
};

Terminal.prototype.destroy = function() {
  var self = this;

  // close
  this._close();

  // Need to close the read stream so
  // node stops reading a dead file descriptor.
  // Then we can safely SIGHUP the shell.
  this.socket.once('close', function() {
    self.kill('SIGHUP');
  });

  this.socket.destroy();
};

Terminal.prototype.kill = function(sig) {
  try {
    process.kill(this.pid, sig || 'SIGHUP');
  } catch(e) {
    ;
  }
};

Terminal.prototype.__defineGetter__('process', function() {
  return pty.process(this.fd, this.pty) || this.file;
});

Terminal.prototype._close = function() {
  this.socket.writable = false;
  this.socket.readable = false;
  this.write = function() {};
  this.end = function() {};
  this.writable = false;
  this.readable = false;
};

/**
 * Helpers
 */

function merge(a) {
  var a = a || {}
    , keys
    , b
    , i
    , j;

  for (i = 1; i < arguments.length; i++) {
    b = arguments[i] || {};
    keys = Object.keys(b);
    for (j = 0; j < keys.length; j++) {
      a[keys[j]] = b[keys[j]];
    }
  }

  return a;
}

function environ(env) {
  var keys = Object.keys(env || {})
    , l = keys.length
    , i = 0
    , pairs = [];

  for (; i < l; i++) {
    pairs.push(keys[i] + '=' + env[keys[i]]);
  }

  return pairs;
}

/**
 * Expose
 */

exports = Terminal;
exports.Terminal = Terminal;
exports.native = pty;
module.exports = exports;
<|endoftext|>


<commit_before>/** @babel */
/** @jsx etch.dom */
/* eslint react/no-unknown-property: "off" */

import {CompositeDisposable, TextEditor} from 'atom';
import etch from 'etch';
import {shortenSha} from '../helpers';

const COMMIT_GRAMMAR_SCOPE = 'text.git-commit';

export default class CommitView {
  constructor(props) {
    this.props = props;

    this.commit = this.commit.bind(this);
    this.abortMerge = this.abortMerge.bind(this);
    this.handleAmendBoxClick = this.handleAmendBoxClick.bind(this);
    this.handleMoveUp = this.handleMoveUp.bind(this);
    this.commit = this.commit.bind(this);
    this.abortMerge = this.abortMerge.bind(this);
    etch.initialize(this);

    this.editor = this.refs.editor;
    this.editorElement = atom.views.getView(this.editor);
    this.editor.setText(this.props.message || '');
    this.subscriptions = new CompositeDisposable(
      this.editor.onDidChange(() => this.props.onChangeMessage && this.props.onChangeMessage(this.editor.getText())),
      this.editor.onDidChangeCursorPosition(() => { etch.update(this); }),
      props.commandRegistry.add(this.element, {'github:commit': this.commit}),
      props.commandRegistry.add(this.editorElement, {'core:move-up': this.handleMoveUp}),
    );

    const grammar = atom.grammars.grammarForScopeName(COMMIT_GRAMMAR_SCOPE);
    if (grammar) {
      this.editor.setGrammar(grammar);
    } else {
      this.grammarSubscription = atom.grammars.onDidAddGrammar(this.grammarAdded.bind(this));
      this.subscriptions.add(this.grammarSubscription);
    }
  }

  destroy() {
    this.subscriptions.dispose();
    etch.destroy(this);
  }

  update(props) {
    const previousMessage = this.props.message;
    this.props = {...this.props, ...props};
    const newMessage = this.props.message;
    if (this.editor && previousMessage !== newMessage && this.editor.getText() !== newMessage) {
      this.editor.setText(newMessage);
    }
    return etch.update(this);
  }

  grammarAdded(grammar) {
    if (grammar.scopeName !== COMMIT_GRAMMAR_SCOPE) {
      return;
    }

    this.editor.setGrammar(grammar);
    this.grammarSubscription.dispose();
  }

  render() {
    let remainingCharsClassName = '';
    if (this.getRemainingCharacters() < 0) {
      remainingCharsClassName = 'is-error';
    } else if (this.getRemainingCharacters() < this.props.maximumCharacterLimit / 4) {
      remainingCharsClassName = 'is-warning';
    }
    return (

          <TextEditor
            ref="editor"
            softWrapped={true}
            placeholderText="Commit message"
            lineNumberGutterVisible={false}
            showInvisibles={false}
            autoHeight={false}
            scrollPastEnd={false}
          />

          <button ref="abortMergeButton" className="btn github-CommitView-button is-secondary"
            onclick={this.abortMerge}
            style={{display: this.props.isMerging ? '' : 'none'}}>Abort Merge</button>

            <input
              ref="amend"
              className="input-checkbox"
              type="checkbox"
              onclick={this.handleAmendBoxClick}
              checked={this.props.isAmending}
            /> Amend

          <button ref="commitButton" className="btn github-CommitView-button"
            onclick={this.commit}
            disabled={!this.isCommitButtonEnabled()}>{this.commitButtonText()}</button>
          <div ref="remainingCharacters"
            className={`github-CommitView-remaining-characters ${remainingCharsClassName}`}>
            {this.getRemainingCharacters()}

    );
  }

  abortMerge() {
    this.props.abortMerge();
  }

  handleAmendBoxClick() {
    this.props.setAmending(this.refs.amend.checked);
  }

  handleMoveUp(event) {
    if (this.editor.getCursorBufferPositions().every(p => p.row === 0) && this.props.didMoveUpOnFirstLine) {
      this.props.didMoveUpOnFirstLine();
      event.stopImmediatePropagation();
    }

    return etch.update(this);
  }

  commit() {
    if (this.isCommitButtonEnabled()) {
      this.props.commit(this.editor.getText());
    }
  }

  getRemainingCharacters() {
    if (this.editor != null) {
      if (this.editor.getCursorBufferPosition().row === 0) {
        return (this.props.maximumCharacterLimit - this.editor.lineTextForBufferRow(0).length).toString();
      } else {
        return '∞';
      }
    } else {
      return this.props.maximumCharacterLimit;
    }
  }

  isCommitButtonEnabled() {
    return this.props.stagedChangesExist &&
      !this.props.mergeConflictsExist &&
      this.editor &&
      this.editor.getText().length !== 0;
  }

  commitButtonText() {
    if (this.props.isAmending) {
      return `Amend commit (${shortenSha(this.props.lastCommit.sha)})`;
    } else {
      if (this.props.branchName) {
        return `Commit to ${this.props.branchName}`;
      } else {
        return 'Commit';
      }
    }
  }

  focus() {
    this.editorElement.focus();
  }

  isFocused() {
    return this.element === document.activeElement || this.element.contains(document.activeElement);
  }
}
<commit_msg>Leave a FIXME for `atom.views` reference<commit_after>/** @babel */
/** @jsx etch.dom */
/* eslint react/no-unknown-property: "off" */

import {CompositeDisposable, TextEditor} from 'atom';
import etch from 'etch';
import {shortenSha} from '../helpers';

const COMMIT_GRAMMAR_SCOPE = 'text.git-commit';

export default class CommitView {
  constructor(props) {
    this.props = props;

    this.commit = this.commit.bind(this);
    this.abortMerge = this.abortMerge.bind(this);
    this.handleAmendBoxClick = this.handleAmendBoxClick.bind(this);
    this.handleMoveUp = this.handleMoveUp.bind(this);
    this.commit = this.commit.bind(this);
    this.abortMerge = this.abortMerge.bind(this);
    etch.initialize(this);

    this.editor = this.refs.editor;
    // FIXME Use props-injected view registry instead of the Atom global
    this.editorElement = atom.views.getView(this.editor);
    this.editor.setText(this.props.message || '');
    this.subscriptions = new CompositeDisposable(
      this.editor.onDidChange(() => this.props.onChangeMessage && this.props.onChangeMessage(this.editor.getText())),
      this.editor.onDidChangeCursorPosition(() => { etch.update(this); }),
      props.commandRegistry.add(this.element, {'github:commit': this.commit}),
      props.commandRegistry.add(this.editorElement, {'core:move-up': this.handleMoveUp}),
    );

    const grammar = atom.grammars.grammarForScopeName(COMMIT_GRAMMAR_SCOPE);
    if (grammar) {
      this.editor.setGrammar(grammar);
    } else {
      this.grammarSubscription = atom.grammars.onDidAddGrammar(this.grammarAdded.bind(this));
      this.subscriptions.add(this.grammarSubscription);
    }
  }

  destroy() {
    this.subscriptions.dispose();
    etch.destroy(this);
  }

  update(props) {
    const previousMessage = this.props.message;
    this.props = {...this.props, ...props};
    const newMessage = this.props.message;
    if (this.editor && previousMessage !== newMessage && this.editor.getText() !== newMessage) {
      this.editor.setText(newMessage);
    }
    return etch.update(this);
  }

  grammarAdded(grammar) {
    if (grammar.scopeName !== COMMIT_GRAMMAR_SCOPE) {
      return;
    }

    this.editor.setGrammar(grammar);
    this.grammarSubscription.dispose();
  }

  render() {
    let remainingCharsClassName = '';
    if (this.getRemainingCharacters() < 0) {
      remainingCharsClassName = 'is-error';
    } else if (this.getRemainingCharacters() < this.props.maximumCharacterLimit / 4) {
      remainingCharsClassName = 'is-warning';
    }
    return (

          <TextEditor
            ref="editor"
            softWrapped={true}
            placeholderText="Commit message"
            lineNumberGutterVisible={false}
            showInvisibles={false}
            autoHeight={false}
            scrollPastEnd={false}
          />

          <button ref="abortMergeButton" className="btn github-CommitView-button is-secondary"
            onclick={this.abortMerge}
            style={{display: this.props.isMerging ? '' : 'none'}}>Abort Merge</button>

            <input
              ref="amend"
              className="input-checkbox"
              type="checkbox"
              onclick={this.handleAmendBoxClick}
              checked={this.props.isAmending}
            /> Amend

          <button ref="commitButton" className="btn github-CommitView-button"
            onclick={this.commit}
            disabled={!this.isCommitButtonEnabled()}>{this.commitButtonText()}</button>
          <div ref="remainingCharacters"
            className={`github-CommitView-remaining-characters ${remainingCharsClassName}`}>
            {this.getRemainingCharacters()}

    );
  }

  abortMerge() {
    this.props.abortMerge();
  }

  handleAmendBoxClick() {
    this.props.setAmending(this.refs.amend.checked);
  }

  handleMoveUp(event) {
    if (this.editor.getCursorBufferPositions().every(p => p.row === 0) && this.props.didMoveUpOnFirstLine) {
      this.props.didMoveUpOnFirstLine();
      event.stopImmediatePropagation();
    }

    return etch.update(this);
  }

  commit() {
    if (this.isCommitButtonEnabled()) {
      this.props.commit(this.editor.getText());
    }
  }

  getRemainingCharacters() {
    if (this.editor != null) {
      if (this.editor.getCursorBufferPosition().row === 0) {
        return (this.props.maximumCharacterLimit - this.editor.lineTextForBufferRow(0).length).toString();
      } else {
        return '∞';
      }
    } else {
      return this.props.maximumCharacterLimit;
    }
  }

  isCommitButtonEnabled() {
    return this.props.stagedChangesExist &&
      !this.props.mergeConflictsExist &&
      this.editor &&
      this.editor.getText().length !== 0;
  }

  commitButtonText() {
    if (this.props.isAmending) {
      return `Amend commit (${shortenSha(this.props.lastCommit.sha)})`;
    } else {
      if (this.props.branchName) {
        return `Commit to ${this.props.branchName}`;
      } else {
        return 'Commit';
      }
    }
  }

  focus() {
    this.editorElement.focus();
  }

  isFocused() {
    return this.element === document.activeElement || this.element.contains(document.activeElement);
  }
}
<|endoftext|>


<commit_before>/*
 * grunt-require-rev
 * https://github.com/heavymery/grunt-require-rev
 *
 * Copyright (c) 2014 Shindeok Kang
 * Licensed under the MIT license.
 */

'use strict';

// Console color code
var black   = '\u001b[30m';
var red     = '\u001b[31m';
var green   = '\u001b[32m';
var yellow  = '\u001b[33m';
var blue    = '\u001b[34m';
var magenta = '\u001b[35m';
var cyan    = '\u001b[36m';
var white   = '\u001b[37m';
var reset   = '\u001b[0m';

// file hashing modules
var fs = require('fs');
var path = require('path');
var crypto = require('crypto');

module.exports = function(grunt) {

  var createHashFromFile = function(filepath, fileEncoding, hashAlgorithm, hashEncoding) {
    var hash = crypto.createHash(hashAlgorithm);
    hash.update(grunt.file.read(filepath), fileEncoding);
    grunt.verbose.ok('Hashing ' + filepath + '...');
    return hash.digest(hashEncoding);
  }

  grunt.registerMultiTask('requireRev', 'File revisioning for requrejs.', function() {

    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      hash: {
        algorithm: 'md5',
        encoding: 'hex',
        inputEncoding: 'utf8',
        length: 8
      },
      requirejs: {
        baseUrl: '(scripts|styles)', // カッコは必須
      }
    });

    var dirPathPattern = new RegExp('[\\w\\d-_/.]*');

    var filePathPattern = new RegExp('([a-z0-9]{' + options.hash.length + '}\\.)?(([\\w\\d-_/.!]+)\\.(js|css|html))');

    var dependencyPathPattern
      = new RegExp('(\'|")[\\w\\d-_/.!]+(\'|")','g');
      // e.g. 'app', "controllers/main", "css!/styles/main"

    var definePattern
      = new RegExp('define\\s*\\(\\s*(' + dependencyPathPattern.source + '\\s*,?\\s*)*\\s*\\[\\s*(' + dependencyPathPattern.source + '\\s*,?\\s*)*\\s*\\]', 'ig');
      // e.g. define("moduleName",["app","controllers/main"]... define(["app","controllers/main"]...

    var requirePattern
      = new RegExp('(require\\s*\\(\\s*\\[\\s*(' + dependencyPathPattern.source + '\\s*,?\\s*)*\\]\\s*)|(require\\s*\\(\\s*(' + dependencyPathPattern.source + '\\s*,?\\s*)*)', 'ig');
      // e.g. require(['app']... require('app'...

    var dependenciesPattern
      = new RegExp('(dependencies\\s*(:|=)\\s*\\[\\s*(' + dependencyPathPattern.source + '\\s*,?\\s*)*\\]\\s*)|(dependencies\\s*\\.\\s*push\\(\\s*(' + dependencyPathPattern.source + '\\s*,?\\s*)*)', 'ig');
      // e.g. dependencies: ['css!../~','~']... dependencies = ['css!../~','~']... dependencies.push('~');

    var matchPatternFromArray = function(array, pattern) {
      for(var i=0; i<array.length; i++) {
        var match = array[i].match(pattern);
        if(match) {
          return match;
        }
      }

      return null;
    };

    var fileToDependencyPath = function(filePath) {
      var regexp = new RegExp(options.requirejs.baseUrl + '/?(' + dirPathPattern.source + ')/' + filePathPattern.source);
      var pathMatch = filePath.match(regexp);
      if(!pathMatch) return '';

      var path = '';
      var pathOrigin = '';
      var patternSource = '';

      // set dir name
      // TODO: オプション化
      if(pathMatch[1] === 'styles') {
        // CSSはRequireCSS用の特殊なパスに変換
        path += 'css!/styles/';
        pathOrigin += 'css!/styles/';
        patternSource += 'css!/styles/'.replace(/\//g,'\\/');
      } else {
        if(pathMatch[2] && pathMatch[2].length>0) {
          path += pathMatch[2] + '/';
          pathOrigin += pathMatch[2] + '/';
          patternSource += pathMatch[2].replace(/\//g,'\\/') + '\\/';
        }
      }

      // add hash prefix pattern
      patternSource += '([a-z0-9]{' + options.hash.length + '}\\.)?';

      // add hash prefix
      if(pathMatch[3] && pathMatch[3].length>0) {
        path += pathMatch[3];

        // ハッシュプレーフィックスではない場合もあるのでチィック（数字が入っていれば）
        if(!pathMatch[3].match(/\d/)) {
          pathOrigin += pathMatch[3];
          patternSource += pathMatch[3];
        }
      }

      // add file name (exclude extension)
      if(pathMatch[5] && pathMatch[5].length>0) {
        path += pathMatch[5];
        pathOrigin += pathMatch[5];
        patternSource += pathMatch[5];
      }

      // create regular expression
      var pattern = new RegExp(patternSource, 'ig');

      return {
        path: path,
        pathOrigin: pathOrigin,
        pattern: pattern
      }
    };

    //--------------------------------------
    // 1. get target files
    //--------------------------------------

    var targetFiles = [];

    this.files.forEach(function(filePair) {
      filePair.src.forEach(function(file) {
        targetFiles.push(file);
      });
    });

    grunt.verbose.writeln();
    grunt.verbose.writeln('Target files:');
    grunt.verbose.writeln(green + targetFiles.join('\n') + reset);
    grunt.verbose.writeln();

    //--------------------------------------
    // 2. create dependencies map
    //  (key: filePath, value: dependencies)
    //--------------------------------------

    var dependenciesMap = {};

    targetFiles.forEach(function(targetPath) {

      var contents = grunt.file.read(targetPath);

      var defineMatchs = contents.match(definePattern);
      var requireMatchs = contents.match(requirePattern);
      var dependenciesMatchs = contents.match(dependenciesPattern);

      grunt.verbose.writeln('Define matchs:\n' + cyan + defineMatchs + reset);
      grunt.verbose.writeln('Require matchs:\n' + cyan + requireMatchs + reset);
      grunt.verbose.writeln('Dependencies matchs:\n' + cyan + dependenciesMatchs + reset);
      grunt.verbose.writeln();

      // dependency path array
      var dependencies = [];

      if(defineMatchs) {
        defineMatchs.forEach(function(defineMatch) {
          var pathMatchs = defineMatch.match(dependencyPathPattern);
          if(pathMatchs) {
            dependencies = dependencies.concat(defineMatch.match(dependencyPathPattern));
          }
        });
      }

      if(requireMatchs) {
        requireMatchs.forEach(function(requireMatch) {
          var pathMatchs = requireMatch.match(dependencyPathPattern);
          if(pathMatchs) {
            dependencies = dependencies.concat(pathMatchs);
          }
        });
      }

      if(dependenciesMatchs) {
        dependenciesMatchs.forEach(function(dependenciesMatch) {
          var pathMatchs = dependenciesMatch.match(dependencyPathPattern);
          if(pathMatchs) {
            dependencies = dependencies.concat(pathMatchs);
          }
        });
      }

      // remove quotation mark
      for(var i=0; i<dependencies.length; i++) {
        dependencies[i] = dependencies[i].replace(/'|"/g,'');
      }

      // remove duplicate dependency path
      for(var i=0; i<dependencies.length; i++) {
        var target = dependencies[i];
        var indexOfNext = dependencies.indexOf(target, i + 1);
        if(indexOfNext > 0) {
          dependencies.splice(indexOfNext, 1);
          i--;
        }
      }

      dependenciesMap[targetPath] = {};
      dependenciesMap[targetPath].dependencyPath = fileToDependencyPath(targetPath);
      dependenciesMap[targetPath].dependencies = dependencies;
    });

    //--------------------------------------
    // 3. order by dependencies
    //--------------------------------------

    var targetFilesSorted = [];

    while(targetFiles.length > 0) {
      if(targetFilesSorted.length > 0) {
        var nextTarget = targetFiles.pop();

        for(var i=0; i<targetFilesSorted.length; i++) {
          var targetFile = targetFilesSorted[i];
          var dependencies = dependenciesMap[targetFile].dependencies;

          var dependencyMatch = matchPatternFromArray(dependencies, dependenciesMap[nextTarget].dependencyPath.pattern);

          if(dependencyMatch) {
            break;
          }
        }

        // move dependent file to front
        targetFilesSorted.splice(i, 0, nextTarget);

      } else {
        targetFilesSorted.push(targetFiles.pop());
      }
    }

    grunt.verbose.writeln();

    //--------------------------------------
    // 4. hashing & replace dependency path
    //--------------------------------------

    targetFilesSorted.forEach(function(targetPath) {
      var dependencies = dependenciesMap[targetPath].dependencies;

      grunt.verbose.ok('Target ' + targetPath + ' ('
        + dependenciesMap[targetPath].dependencyPath.path + ' | '
        + dependenciesMap[targetPath].dependencyPath.pathOrigin + ' | '
        + dependenciesMap[targetPath].dependencyPath.pattern + ')');

      grunt.verbose.writeln(red + dependencies.length + reset + ' dependencies found.');
      if(dependencies && dependencies.length > 0) {
        grunt.verbose.writeln(magenta + dependencies.join('\n') + reset);
      }
      grunt.verbose.writeln();
    });

    for(var i=0; i<targetFilesSorted.length; i++) {
      var targetPath = targetFilesSorted[i];
      var originName = path.basename(targetPath);

      var hash = createHashFromFile(targetPath, options.hash.inputEncoding, options.hash.algorithm, options.hash.encoding);
      var prefix = hash.slice(0, options.hash.length);

      // clear hash prefix from file name
      var filePathMatch = originName.match(filePathPattern);
      if(filePathMatch && filePathMatch[1] && filePathMatch[1].match(/\d/)) {
        originName = filePathMatch[2];
      }

      var targetPathNew = path.dirname(targetPath) + '/' + prefix + '.' +  originName;
      grunt.verbose.write('Rename ' + targetPath + ' to ' + targetPathNew + '...');

      // rename file (adding hash prefix)
      fs.renameSync(targetPath, targetPathNew);
      grunt.verbose.ok();

      // replace dependency path
      dependenciesMap[targetPath].dependencyPath = fileToDependencyPath(targetPathNew);

      for(var j=i+1; j<targetFilesSorted.length; j++) {
        var otherPath = targetFilesSorted[j];

        var dependencyMatch = matchPatternFromArray(dependenciesMap[otherPath].dependencies, dependenciesMap[targetPath].dependencyPath.pattern);
        if(dependencyMatch) {
          grunt.verbose.ok('Replace require path for ' + otherPath + '...');

          var contents = grunt.file.read(otherPath);

          grunt.file.write(otherPath, contents.replace(
            new RegExp('("|\')' + dependenciesMap[targetPath].dependencyPath.pattern.source + '("|\')', 'ig'),
            '$1' + dependenciesMap[targetPath].dependencyPath.path + '$3'
          ));
        }
      }

      grunt.verbose.writeln();
    }

  }); // grunt.registerMultiTask

}; // module.exports
<commit_msg>Update requireRev.js<commit_after>/*
 * grunt-require-rev
 * https://github.com/heavymery/grunt-require-rev
 *
 * Copyright (c) 2014 Shindeok Kang
 * Licensed under the MIT license.
 */

'use strict';

// Console color code
var black   = '\u001b[30m';
var red     = '\u001b[31m';
var green   = '\u001b[32m';
var yellow  = '\u001b[33m';
var blue    = '\u001b[34m';
var magenta = '\u001b[35m';
var cyan    = '\u001b[36m';
var white   = '\u001b[37m';
var reset   = '\u001b[0m';

// file hashing modules
var fs = require('fs');
var path = require('path');
var crypto = require('crypto');

module.exports = function(grunt) {

  var createHashFromFile = function(filepath, fileEncoding, hashAlgorithm, hashEncoding) {
    var hash = crypto.createHash(hashAlgorithm);
    hash.update(grunt.file.read(filepath), fileEncoding);
    grunt.verbose.ok('Hashing ' + filepath + '...');
    return hash.digest(hashEncoding);
  }

  grunt.registerMultiTask('requireRev', 'File revisioning for requrejs.', function() {

    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      hash: {
        algorithm: 'md5',
        encoding: 'hex',
        inputEncoding: 'utf8',
        length: 8
      },
      paths: { // key: file path, value: requirejs dependency path
        'scripts': '', // like as requirejs baseUrl == '/scripts'
        'styles': 'css!/styles/' // for requireCSS
      }
    });

    var dirPathPattern = new RegExp('[\\w\\d-_/.]*');

    var filePathPattern = new RegExp('([a-z0-9]{' + options.hash.length + '}\\.)?(([\\w\\d-_/.!]+)\\.(js|css|html))');

    var dependencyPathPattern
      = new RegExp('(\'|")[\\w\\d-_/.!]+(\'|")','g');
      // e.g. 'app', "controllers/main", "css!/styles/main"

    var definePattern
      = new RegExp('define\\s*\\(\\s*(' + dependencyPathPattern.source + '\\s*,?\\s*)*\\s*\\[\\s*(' + dependencyPathPattern.source + '\\s*,?\\s*)*\\s*\\]', 'ig');
      // e.g. define("moduleName",["app","controllers/main"]... define(["app","controllers/main"]...

    var requirePattern
      = new RegExp('(require\\s*\\(\\s*\\[\\s*(' + dependencyPathPattern.source + '\\s*,?\\s*)*\\]\\s*)|(require\\s*\\(\\s*(' + dependencyPathPattern.source + '\\s*,?\\s*)*)', 'ig');
      // e.g. require(['app']... require('app'...

    var dependenciesPattern
      = new RegExp('(dependencies\\s*(:|=)\\s*\\[\\s*(' + dependencyPathPattern.source + '\\s*,?\\s*)*\\]\\s*)|(dependencies\\s*\\.\\s*push\\(\\s*(' + dependencyPathPattern.source + '\\s*,?\\s*)*)', 'ig');
      // e.g. dependencies: ['css!../~','~']... dependencies = ['css!../~','~']... dependencies.push('~');

    var matchPatternFromArray = function(array, pattern) {
      for(var i=0; i<array.length; i++) {
        var match = array[i].match(pattern);
        if(match) {
          return match;
        }
      }

      return null;
    };

    var fileToDependencyPath = function(filePath) {
      var fileBasePathPattern = '(' + Object.keys(options.paths).join('|') + ')';
      var regexp = new RegExp(fileBasePathPattern + '/?(' + dirPathPattern.source + ')/' + filePathPattern.source);

      var pathMatch = filePath.match(regexp);
      if(!pathMatch) return '';

      var fileBasePath = pathMatch[1];
      var dependencyBasePath = options.paths[fileBasePath];

      // set base dependency path
      var path = dependencyBasePath;
      var pathOrigin = dependencyBasePath;
      var patternSource = dependencyBasePath.replace(/\//g,'\\/');

      // add sub dependency path
      if(pathMatch[2] && pathMatch[2].length>0) {
        path += pathMatch[2] + '/';
        pathOrigin += pathMatch[2] + '/';
        patternSource += pathMatch[2].replace(/\//g,'\\/') + '\\/';
      }

      // add hash prefix pattern
      patternSource += '([a-z0-9]{' + options.hash.length + '}\\.)?';

      // add hash prefix
      if(pathMatch[3] && pathMatch[3].length>0) {
        path += pathMatch[3];
      }

      // add file name (exclude extension)
      if(pathMatch[5] && pathMatch[5].length>0) {
        path += pathMatch[5];
        pathOrigin += pathMatch[5];
        patternSource += pathMatch[5];
      }

      // create regular expression
      var pattern = new RegExp(patternSource, 'ig');

      return {
        path: path,
        pathOrigin: pathOrigin,
        pattern: pattern
      }
    };

    //--------------------------------------
    // 1. get target files
    //--------------------------------------

    var targetFiles = [];

    this.files.forEach(function(filePair) {
      filePair.src.forEach(function(file) {
        targetFiles.push(file);
      });
    });

    grunt.verbose.writeln();
    grunt.verbose.writeln('Target files:');
    grunt.verbose.writeln(green + targetFiles.join('\n') + reset);
    grunt.verbose.writeln();

    //--------------------------------------
    // 2. create dependencies map
    //  (key: filePath, value: dependencies)
    //--------------------------------------

    var dependenciesMap = {};

    targetFiles.forEach(function(targetPath) {

      var contents = grunt.file.read(targetPath);

      var defineMatchs = contents.match(definePattern);
      var requireMatchs = contents.match(requirePattern);
      var dependenciesMatchs = contents.match(dependenciesPattern);

      grunt.verbose.writeln('Define matchs:\n' + cyan + defineMatchs + reset);
      grunt.verbose.writeln('Require matchs:\n' + cyan + requireMatchs + reset);
      grunt.verbose.writeln('Dependencies matchs:\n' + cyan + dependenciesMatchs + reset);
      grunt.verbose.writeln();

      // dependency path array
      var dependencies = [];

      if(defineMatchs) {
        defineMatchs.forEach(function(defineMatch) {
          var pathMatchs = defineMatch.match(dependencyPathPattern);
          if(pathMatchs) {
            dependencies = dependencies.concat(defineMatch.match(dependencyPathPattern));
          }
        });
      }

      if(requireMatchs) {
        requireMatchs.forEach(function(requireMatch) {
          var pathMatchs = requireMatch.match(dependencyPathPattern);
          if(pathMatchs) {
            dependencies = dependencies.concat(pathMatchs);
          }
        });
      }

      if(dependenciesMatchs) {
        dependenciesMatchs.forEach(function(dependenciesMatch) {
          var pathMatchs = dependenciesMatch.match(dependencyPathPattern);
          if(pathMatchs) {
            dependencies = dependencies.concat(pathMatchs);
          }
        });
      }

      // remove quotation mark
      for(var i=0; i<dependencies.length; i++) {
        dependencies[i] = dependencies[i].replace(/'|"/g,'');
      }

      // remove duplicate dependency path
      for(var i=0; i<dependencies.length; i++) {
        var target = dependencies[i];
        var indexOfNext = dependencies.indexOf(target, i + 1);
        if(indexOfNext > 0) {
          dependencies.splice(indexOfNext, 1);
          i--;
        }
      }

      dependenciesMap[targetPath] = {};
      dependenciesMap[targetPath].dependencyPath = fileToDependencyPath(targetPath);
      dependenciesMap[targetPath].dependencies = dependencies;
    });

    //--------------------------------------
    // 3. order by dependencies
    //--------------------------------------

    var targetFilesSorted = [];

    while(targetFiles.length > 0) {
      if(targetFilesSorted.length > 0) {
        var nextTarget = targetFiles.pop();

        for(var i=0; i<targetFilesSorted.length; i++) {
          var targetFile = targetFilesSorted[i];
          var dependencies = dependenciesMap[targetFile].dependencies;

          var dependencyMatch = matchPatternFromArray(dependencies, dependenciesMap[nextTarget].dependencyPath.pattern);

          if(dependencyMatch) {
            break;
          }
        }

        // move dependent file to front
        targetFilesSorted.splice(i, 0, nextTarget);

      } else {
        targetFilesSorted.push(targetFiles.pop());
      }
    }

    grunt.verbose.writeln();

    //--------------------------------------
    // 4. hashing & replace dependency path
    //--------------------------------------

    targetFilesSorted.forEach(function(targetPath) {
      var dependencies = dependenciesMap[targetPath].dependencies;

      grunt.verbose.ok('Target ' + targetPath + ' ('
        + dependenciesMap[targetPath].dependencyPath.path + ' | '
        + dependenciesMap[targetPath].dependencyPath.pathOrigin + ' | '
        + dependenciesMap[targetPath].dependencyPath.pattern + ')');

      grunt.verbose.writeln(red + dependencies.length + reset + ' dependencies found.');
      if(dependencies && dependencies.length > 0) {
        grunt.verbose.writeln(magenta + dependencies.join('\n') + reset);
      }
      grunt.verbose.writeln();
    });

    for(var i=0; i<targetFilesSorted.length; i++) {
      var targetPath = targetFilesSorted[i];
      var originName = path.basename(targetPath);

      var hash = createHashFromFile(targetPath, options.hash.inputEncoding, options.hash.algorithm, options.hash.encoding);
      var prefix = hash.slice(0, options.hash.length);

      // clear hash prefix from file name
      var filePathMatch = originName.match(filePathPattern);
      if(filePathMatch && filePathMatch[1] && filePathMatch[1].match(/\d/)) {
        originName = filePathMatch[2];
      }

      var targetPathNew = path.dirname(targetPath) + '/' + prefix + '.' +  originName;
      grunt.verbose.write('Rename ' + targetPath + ' to ' + targetPathNew + '...');

      // rename file (adding hash prefix)
      fs.renameSync(targetPath, targetPathNew);
      grunt.verbose.ok();

      // replace dependency path
      dependenciesMap[targetPath].dependencyPath = fileToDependencyPath(targetPathNew);

      for(var j=i+1; j<targetFilesSorted.length; j++) {
        var otherPath = targetFilesSorted[j];

        var dependencyMatch = matchPatternFromArray(dependenciesMap[otherPath].dependencies, dependenciesMap[targetPath].dependencyPath.pattern);
        if(dependencyMatch) {
          grunt.verbose.ok('Replace require path for ' + otherPath + '...');

          var contents = grunt.file.read(otherPath);

          grunt.file.write(otherPath, contents.replace(
            new RegExp('("|\')' + dependenciesMap[targetPath].dependencyPath.pattern.source + '("|\')', 'ig'),
            '$1' + dependenciesMap[targetPath].dependencyPath.path + '$3'
          ));
        }
      }

      grunt.verbose.writeln();
    }

  }); // grunt.registerMultiTask

}; // module.exports
<|endoftext|>


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

export default class Dialog extends Component {
  constructor(props){
    super(props);

    this.state = {
      isDisplay: false
    }
  }

  getWindowPosition(){
    const width = window.innerWidth
    || document.documentElement.clientWidth
    || document.body.clientWidth;

    const height = window.innerHeight
    || document.documentElement.clientHeight
    || document.body.clientHeight;

    const doc = document.documentElement;
    const left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
    const top = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);

    return {width: width, height: height, top: top, left: left}
  }

  show(){
    this.setState({isDisplay: true});
  }

  hide(){
    this.setState({isDisplay: false});
  }

  render() {

    const panelStyle = {
      width: this.props.size.width + "px",
      height: this.props.size.height + "px",
      display: this.state.isDisplay ? "block" : "none",
      position: 'absolute',
      zIndex:"10000",
    }

    if(this.props.position == 'window-center'){
      const windowPos = this.getWindowPosition();
      //ヘッダーが画面からはみ出さないようにセンターを求める。
      panelStyle.top =  Math.max((windowPos.height / 2) - (this.props.size.height / 2) + windowPos.top, windowPos.top)
      panelStyle.left = Math.max((windowPos.width / 2) - (this.props.size.width / 2) + windowPos.left, windowPos.left)
    }

    // console.log();

    return (
      <Draggable
        handle=".panel-heading"
      >

            <button type="button" className="btn btn-danger pull-right" onClick={(e) => this.hide()}>

            </button>

            {this.props.children}

      </Draggable>
    )
  }
}

Dialog.defaultProps = {
  size: {
    width: 640,
    height: 640,
  },
  isDisplay: false,
  position: 'window-center',
}
<commit_msg>panel部分は外側に出しました。<commit_after>import React, { Component } from 'react'
import Draggable from 'react-draggable';

export default class Dialog extends Component {
  constructor(props){
    super(props);

    this.state = {
      isDisplay: false
    }
  }

  getWindowPosition(){
    const width = window.innerWidth
    || document.documentElement.clientWidth
    || document.body.clientWidth;

    const height = window.innerHeight
    || document.documentElement.clientHeight
    || document.body.clientHeight;

    const doc = document.documentElement;
    const left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
    const top = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);

    return {width: width, height: height, top: top, left: left}
  }

  show(){
    this.setState({isDisplay: true});
  }

  hide(){
    this.setState({isDisplay: false});
  }

  render() {

    const panelStyle = {
      width: this.props.size.width + "px",
      height: this.props.size.height + "px",
      display: this.state.isDisplay ? "block" : "none",
      position: 'absolute',
      zIndex:"10000",
    }

    if(this.props.position == 'window-center'){
      const windowPos = this.getWindowPosition();
      //ヘッダーが画面からはみ出さないようにセンターを求める。
      panelStyle.top =  Math.max((windowPos.height / 2) - (this.props.size.height / 2) + windowPos.top, windowPos.top)
      panelStyle.left = Math.max((windowPos.width / 2) - (this.props.size.width / 2) + windowPos.left, windowPos.left)
    }

    // console.log();

    return (
      <Draggable
        handle=".panel-heading"
      >

          {this.props.children}

      </Draggable>
    )
  }
}

Dialog.defaultProps = {
  size: {
    width: 640,
    height: 640,
  },
  isDisplay: false,
  position: 'window-center',
}
<|endoftext|>


<commit_before>var fs = require('fs'),
  pathFn = require('path'),
  async = require('async'),
  utils = require('./utils'),
  sep = pathFn.sep;

// If Node version under v0.8, port path.exists to fs.exists
if (fs.exists === undefined){
  fs.exists = pathFn.exists;
  fs.existsSync = pathFn.existsSync;
}

module.exports = qfs;

function qfs(){
  return new qfs.fn.init(arguments);
};

function Item(path){
  path = pathFn.normalize(path);
  this.path = path;
  this.name = pathFn.basename(path);
  this.dir = pathFn.dirname(path);
  this.ext = pathFn.extname(path);
};

qfs.fn = qfs.prototype = {
  length: 0,
  init: function(args){
    var arr = [],
      _this = this;

    args = utils.toArray(args);

    // No argument
    if (!args.length){
      return this;
    // Multiple arguments
    } else if (args.length > 1){
      var path = pathFn.join.apply(null, args);
      arr.push(path);
    // One argument
    } else {
      var obj = args.shift();

      // Invalid arguments
      if (!obj){
        return this;
      } else {
        // object is array
        if (utils.isArray(obj)){
          arr = obj;
        // qfs object
        } else if (obj instanceof Item){
          this.length = 1;
          this[0] = obj;
          return this;
        // path string
        } else {
          arr.push(obj);
        }
      }
    }

    this.length = arr.length;
    utils.each(arr, function(item, i){
      _this[i] = new Item(item);
    });

    return this;
  }
};

qfs.fn.init.prototype = qfs.fn;

qfs.fn.eq = function(i){
  i = +i;
  return i < 0 ? qfs(this[this.length + i]) : qfs(this[i]);
};

qfs.fn.first = function(){
  return this.eq(0);
};

qfs.fn.last = function(){
  return this.eq(-1);
};

qfs.fn.slice = function(start, end){
  return qfs([].slice.apply(this.toArray(), arguments));
};

qfs.fn.toArray = function(){
  var arr = [];

  this.each(function(){
    arr.push(this.path());
  });

  return arr;
};

utils.each(['path', 'name', 'dir', 'ext'], function(item){
  qfs.fn[item] = function(){
    return this[0][item];
  };
});

qfs.fn.each = function(callback){
  for (var i=0; i<this.length; i++){
    var _callback = callback.call(this.eq(i), i);
    // Skip current loop if callback return true, otherwise stop the loop
    if (utils.isUndefined(callback)){
      if (_callback){
        continue;
      } else {
        break;
      }
    }
  }

  return this;
};

qfs.fn.map = function(callback){
  var _this = this;

  this.each(function(i){
    _this[i] = callback.call(this, i);
  });

  return this;
};

var filter = function(iterator){
  var arr = [];

  if (utils.isRegExp(iterator)){
    this.each(function(){
      var path = this.path();

      if (path.match(iterator)){
        arr.push(path);
      }
    });
  } else if (utils.isFunction(iterator)){
    this.each(function(i){
      var callback = iterator.call(this, i);
      if (callback){
        arr.push(this.path());
      }
    });
  } else {
    var identity = iterator.substring(0, 1);

    if (identity === '.'){
      this.each(function(){
        if (this.ext() === iterator){
          arr.push(this.path());
        }
      });
    } else {
      this.each(function(){
        if (this.name() === iterator){
          arr.push(this.path());
        }
      });
    }
  }

  return arr;
};

qfs.fn.filter = function(iterator){
  return qfs(filter.call(this, iterator));
};

qfs.fn.not = function(iterator){
  return qfs(utils.inverse(this.toArray(), filter.call(this, iterator)));
};

utils.each(['stat', 'exists'], function(item){
  qfs.fn[item] = function(callback){
    if (utils.isFunction(callback)){
      fs[item](this.path(), callback.bind(this));
    } else {
      return fs[item + 'Sync'](this.path());
    }
  };
});

qfs.fn.parent = function(){
  var arr = [];

  this.each(function(){
    arr.push(this.dir());
  });

  return qfs(utils.unique(arr));
};

qfs.fn.parents = function(){
  var arr = [];

  this.each(function(){
    var dirs = this.dir().split(sep),
      i = dirs.length,
      parents = [];

    while (i){
      var dir = dirs.join(sep);
      parents.push(dir ? dir : sep);
      dirs.pop();
      i--;
    }

    arr = utils.merge(arr, parents);
  });

  return qfs(utils.unique(arr));
};

qfs.fn.parentsUntil = function(name){
  var arr = [];

  this.each(function(){
    var dirs = this.dir().split(sep),
      i = dirs.length,
      parents = [];

    while (i){
      var dir = dirs.join(sep);
      parents.push(dir ? dir : sep);

      if (dirs[i - 1] === name){
        break;
      }

      dirs.pop();
      i--;
    }

    arr = utils.merge(arr, parents);
  });

  return qfs(utils.unique(arr));
};

utils.each({
  children: [
    function(selector, callback){
      if (utils.isFunction(selector)){
        callback = selector;
        selector = null;
      }

      var _this = this,
        fn = [];

      this.each(function(){
        var path = this.path();

        fn.push(function(next){
          fs.readdir(path, function(err, files){
            if (err) return callback(err);
            var arr = utils.map(files, function(item){
              return path + sep + item;
            });
            next(null, arr);
          });
        });
      });

      async.parallel(fn, function(err, results){
        if (err) return callback(err);
        var arr = qfs(utils.merge.apply(null, results));
        callback(_this, arr);
      });

      return this;
    },
    function(selector){
      var arr = [];

      this.each(function(){
        var path = this.path();

        arr = utils.merge(arr, utils.map(fs.readdirSync(path), function(item){
          return path + sep + item;
        }));
      });

      return qfs(arr);
    }
  ],
  mkdir: [
    function(name, callback){
      var fn = [];

      this.each(function(){
        var _this = this,
          parent = this.parent();

        fn.push(function(next){
          parent.exists(function(exist){
            if (exist){
              fs.mkdir(_this.path() + sep + name, next);
            } else {
              this.parent().mkdir(this.name(), function(){
                fs.mkdir(_this.path() + sep + name, next);
              });
            }
          });
        });
      });

      async.parallel(fn, callback.bind(this));

      return this;
    },
    function(name){
      this.each(function(){
        var parent = this.parent();

        if (!parent.exists()){
          parent.parent().mkdir(parent.name());
        }

        fs.mkdirSync(this.path() + sep + name);
      });

      return this;
    }
  ],
  rename: [
    function(name, callback){

    },
    function(name){

    }
  ],
  remove: [
    function(callback){
      var fn = [];

      this.each(function(){
        var path = this.path();
        fn.push(function(next){
          fn.unlink(path, next);
        });
      });

      async.parallel(fn, callback.bind(this));

      return this;
    },
    function(){
      this.each(function(){
        fs.unlinkSync(this.path());
      });

      return this;
    }
  ],
  empty: [
    function(callback){

    },
    function(){

    }
  ],
  write: [
    function(data, callback){

    },
    function(data){

    }
  ],
  read: [
    function(callback){

    },
    function(){

    }
  ],
  append: [
    function(data, callback){

    },
    function(data){

    }
  ],
  content: [
    function(data, callback){

    },
    function(data){

    }
  ],
  chmod: [
    function(mode, callback){

    },
    function(mode){

    }
  ],
  chown: [
    function(uid, gid, callback){

    },
    function(uid, gid){

    }
  ]
}, function(value, key){
  qfs.fn[key] = function(){
    var args = utils.toArray(arguments),
      callback = args[args.length - 1];

    // async
    if (utils.isFunction(callback)){
      return value[0].apply(this, args);
    // sync
    } else {
      return value[1].apply(this, args);
    }
  };
});<commit_msg>added rename<commit_after>var fs = require('fs'),
  pathFn = require('path'),
  async = require('async'),
  utils = require('./utils'),
  sep = pathFn.sep;

// If Node version under v0.8, port path.exists to fs.exists
if (fs.exists === undefined){
  fs.exists = pathFn.exists;
  fs.existsSync = pathFn.existsSync;
}

module.exports = qfs;

function qfs(){
  return new qfs.fn.init(arguments);
};

function Item(path){
  path = pathFn.normalize(path);
  this.path = path;
  this.name = pathFn.basename(path);
  this.dir = pathFn.dirname(path);
  this.ext = pathFn.extname(path);
};

qfs.fn = qfs.prototype = {
  length: 0,
  init: function(args){
    var arr = [],
      _this = this;

    args = utils.toArray(args);

    // No argument
    if (!args.length){
      return this;
    // Multiple arguments
    } else if (args.length > 1){
      var path = pathFn.join.apply(null, args);
      arr.push(path);
    // One argument
    } else {
      var obj = args.shift();

      // Invalid arguments
      if (!obj){
        return this;
      } else {
        // object is array
        if (utils.isArray(obj)){
          arr = obj;
        // qfs object
        } else if (obj instanceof Item){
          this.length = 1;
          this[0] = obj;
          return this;
        // path string
        } else {
          arr.push(obj);
        }
      }
    }

    this.length = arr.length;
    utils.each(arr, function(item, i){
      _this[i] = new Item(item);
    });

    return this;
  }
};

qfs.fn.init.prototype = qfs.fn;

qfs.fn.eq = function(i){
  i = +i;
  return i < 0 ? qfs(this[this.length + i]) : qfs(this[i]);
};

qfs.fn.first = function(){
  return this.eq(0);
};

qfs.fn.last = function(){
  return this.eq(-1);
};

qfs.fn.slice = function(start, end){
  return qfs([].slice.apply(this.toArray(), arguments));
};

qfs.fn.toArray = function(){
  var arr = [];

  this.each(function(){
    arr.push(this.path());
  });

  return arr;
};

utils.each(['path', 'name', 'dir', 'ext'], function(item){
  qfs.fn[item] = function(){
    return this[0][item];
  };
});

qfs.fn.each = function(callback){
  for (var i=0; i<this.length; i++){
    var _callback = callback.call(this.eq(i), i);
    // Skip current loop if callback return true, otherwise stop the loop
    if (utils.isUndefined(callback)){
      if (_callback){
        continue;
      } else {
        break;
      }
    }
  }

  return this;
};

qfs.fn.map = function(callback){
  var _this = this;

  this.each(function(i){
    _this[i] = callback.call(this, i);
  });

  return this;
};

var filter = function(iterator){
  var arr = [];

  if (utils.isRegExp(iterator)){
    this.each(function(){
      var path = this.path();

      if (path.match(iterator)){
        arr.push(path);
      }
    });
  } else if (utils.isFunction(iterator)){
    this.each(function(i){
      var callback = iterator.call(this, i);
      if (callback){
        arr.push(this.path());
      }
    });
  } else {
    var identity = iterator.substring(0, 1);

    if (identity === '.'){
      this.each(function(){
        if (this.ext() === iterator){
          arr.push(this.path());
        }
      });
    } else {
      this.each(function(){
        if (this.name() === iterator){
          arr.push(this.path());
        }
      });
    }
  }

  return arr;
};

qfs.fn.filter = function(iterator){
  return qfs(filter.call(this, iterator));
};

qfs.fn.not = function(iterator){
  return qfs(utils.inverse(this.toArray(), filter.call(this, iterator)));
};

utils.each(['stat', 'exists'], function(item){
  qfs.fn[item] = function(callback){
    if (utils.isFunction(callback)){
      fs[item](this.path(), callback.bind(this));
    } else {
      return fs[item + 'Sync'](this.path());
    }
  };
});

qfs.fn.parent = function(){
  var arr = [];

  this.each(function(){
    arr.push(this.dir());
  });

  return qfs(utils.unique(arr));
};

qfs.fn.parents = function(){
  var arr = [];

  this.each(function(){
    var dirs = this.dir().split(sep),
      i = dirs.length,
      parents = [];

    while (i){
      var dir = dirs.join(sep);
      parents.push(dir ? dir : sep);
      dirs.pop();
      i--;
    }

    arr = utils.merge(arr, parents);
  });

  return qfs(utils.unique(arr));
};

qfs.fn.parentsUntil = function(name){
  var arr = [];

  this.each(function(){
    var dirs = this.dir().split(sep),
      i = dirs.length,
      parents = [];

    while (i){
      var dir = dirs.join(sep);
      parents.push(dir ? dir : sep);

      if (dirs[i - 1] === name){
        break;
      }

      dirs.pop();
      i--;
    }

    arr = utils.merge(arr, parents);
  });

  return qfs(utils.unique(arr));
};

utils.each({
  children: [
    function(selector, callback){
      if (utils.isFunction(selector)){
        callback = selector;
        selector = null;
      }

      var _this = this,
        fn = [];

      this.each(function(){
        var path = this.path();

        fn.push(function(next){
          fs.readdir(path, function(err, files){
            if (err) return callback(err);
            var arr = utils.map(files, function(item){
              return path + sep + item;
            });
            next(null, arr);
          });
        });
      });

      async.parallel(fn, function(err, results){
        if (err) return callback(err);
        var arr = qfs(utils.merge.apply(null, results));
        callback(_this, arr);
      });

      return this;
    },
    function(selector){
      var arr = [];

      this.each(function(){
        var path = this.path();

        arr = utils.merge(arr, utils.map(fs.readdirSync(path), function(item){
          return path + sep + item;
        }));
      });

      return qfs(arr);
    }
  ],
  mkdir: [
    function(name, callback){
      var fn = [];

      this.each(function(){
        var _this = this,
          parent = this.parent();

        fn.push(function(next){
          parent.exists(function(exist){
            if (exist){
              fs.mkdir(_this.path() + sep + name, next);
            } else {
              this.parent().mkdir(this.name(), function(){
                fs.mkdir(_this.path() + sep + name, next);
              });
            }
          });
        });
      });

      async.parallel(fn, callback.bind(this));

      return this;
    },
    function(name){
      this.each(function(){
        var parent = this.parent();

        if (!parent.exists()){
          parent.parent().mkdir(parent.name());
        }

        fs.mkdirSync(this.path() + sep + name);
      });

      return this;
    }
  ],
  rename: [
    function(name, callback){
      var arr = [],
        fn = [];

      this.each(function(){
        var _this = this;

        fn.push(function(next){
          fs.rename(_this.dir() + sep + name, next);
        });
      });

      async.parallel(fn, callback.bind(qfs(arr)));

      return this;
    },
    function(name){
      var arr = [];

      this.each(function(){
        var path = this.dir() + sep + name;
        fs.renameSync(path);
        arr.push(path);
      });

      return qfs(arr);
    }
  ],
  remove: [
    function(callback){
      var fn = [];

      this.each(function(){
        var path = this.path();
        fn.push(function(next){
          this.stat(function(err, stat){
            if (err) return callback(err);
            if (stat.isFile()){
              fs.unlink(path, next);
            } else {
              this.empty(function(){
                fs.rmdir(path, next);
              });
            }
          });
        });
      });

      async.parallel(fn, callback.bind(this));

      return this;
    },
    function(){
      this.each(function(){
        var stat = this.stat();
        if (stat.isFile()){
          fs.unlinkSync(this.path());
        } else {
          this.empty();
          fs.rmdirSync(this.path());
        }
      });

      return this;
    }
  ],
  empty: [
    function(callback){

    },
    function(){

    }
  ],
  write: [
    function(data, callback){

    },
    function(data){

    }
  ],
  read: [
    function(callback){

    },
    function(){

    }
  ],
  append: [
    function(data, callback){

    },
    function(data){

    }
  ],
  content: [
    function(data, callback){

    },
    function(data){

    }
  ],
  chmod: [
    function(mode, callback){

    },
    function(mode){

    }
  ],
  chown: [
    function(uid, gid, callback){

    },
    function(uid, gid){

    }
  ]
}, function(value, key){
  qfs.fn[key] = function(){
    var args = utils.toArray(arguments),
      callback = args[args.length - 1];

    // async
    if (utils.isFunction(callback)){
      return value[0].apply(this, args);
    // sync
    } else {
      return value[1].apply(this, args);
    }
  };
});<|endoftext|>