<commit_before>import React, {Component} from 'react'
import request from 'superagent'
import { default as Web3 } from 'web3'
import { default as contract } from 'truffle-contract'
import AbieFund from '../../build/contracts/AbieFund.json'

import '../www/styles/Proposal.scss'

const TESTRPC_HOST = 'localhost'
const TESTRPC_PORT = '8545'

class Proposal extends Component {

  state = {
    web3: false,
    balance: 0,
    addressContract: null,
    delegate: null,
    metaContract: null,
    accounts: null,
    askMembership: null,
    web3RPC: null,
    name: '',
    valueDeposit: 0,
    dataDeposit: '',
  }

  componentDidMount() {
    let testAbie = ''
    setTimeout(() => {
      if (typeof web3 !== 'undefined') {
        // web3 = new Web3(web3.currentProvider);
        this.setState({web3: true})
        let meta = contract(AbieFund)
        this.setState({metaContract: meta})
        let provider = new Web3.providers.HttpProvider(`http://${TESTRPC_HOST}:${TESTRPC_PORT}`)
        let metaCoinBalance = 0
        meta.setProvider(provider)
        const web3RPC = new Web3(provider)
        this.setState({web3RPC})
        // Get accounts.
        web3RPC.eth.getAccounts((err, acc) => {
          console.log(err)
          console.log(acc)
          this.setState({accounts: acc})
          return meta.deployed()
            .then((contract) => this.setState({addressContract: contract.address}))
            .catch((err) => console.error(err))
        })
      } else {
        alert("install Metamask or use Mist")
      }
    }, 1000)
  }

  handleChangeDelegate = (event) => {
    this.setState({delegate: event.target.value})
  }

  handleChangeAskMembership = (event) => {
    this.setState({askMembership: event.target.value})
  }

  handleChangeName = (event) => {
    this.setState({name: event.target.value})
  }

  handleChangeValueDeposit = (event) => {
    this.setState({valueDeposit: event.target.value})
  }

  handleChangeDataDeposit = (event) => {
    this.setState({dataDeposit: event.target.value})
  }

  setDelegate = () => {
    this.state.metaContract.at(this.state.addressContract)
      .then((contract) => contract.setDelegate(
        0,
        this.state.delegate,
        {from: this.state.accounts[0]}
      ))
      .then((result) => console.log(result))
      .catch((err) => {
        console.error(err);
      })
  }

  askMembership = () => {
    this.state.metaContract.at(this.state.addressContract)
      .then((contract) => {
        return contract.askMembership(
        {
          value: web3.toWei(10, "ether"),
          from: this.state.accounts[4],
          gas: 4000000
        }
      )})
      .then((result) => console.log(result))
      .catch((err) => {
        console.error(err);
      })
  }

  addProposal = () => {
    this.state.metaContract.at(this.state.addressContract)
      .then((contract) => {
        return contract.addProposal(
          this.state.name,
          this.state.valueDeposit,
          this.state.dataDeposit,
        {
          value: web3.toWei(1, "ether"),
          from: this.state.accounts[0],
          gas: 4000000
        }
      )})
      .then((result) => console.log(result))
      .catch((err) => {
        console.error(err);
      })
  }

  render() {
    return (

Abie

Balance : {this.state.balance}

            Set Delegate <input type="text" onChange={this.handleChangeDelegate} />
            <button onClick={this.setDelegate}>Add address</button>

            Ask Membership <input type="text" onChange={this.handleChangeAskMembership} />
            <button onClick={this.askMembership}>Ask membership</button>

          Add proposal
          <input type="text" onChange={this.handleChangeName} placeholder="Name of the proposition (hex)" />
          <input type="text" onChange={this.handleChangeRequestAmount} placeholder="Requested amount (Wei)" />
          <input type="text" onChange={this.handleChangeDescription} placeholder="Link IPFS" />
          <button onClick={this.addProposal}>Submit add proposal</button>

    )
  }
}

export default Proposal
<commit_msg>clear<commit_after>import React, {Component} from 'react'
import request from 'superagent'
import { default as Web3 } from 'web3'
import { default as contract } from 'truffle-contract'
//import AbieFund from '../../build/contracts/AbieFund.json'

import '../www/styles/Proposal.scss'

const TESTRPC_HOST = 'localhost'
const TESTRPC_PORT = '8545'

class Proposal extends Component {

  state = {
    web3: false,
    balance: 0,
    addressContract: null,
    delegate: null,
    metaContract: null,
    accounts: null,
    askMembership: null,
    web3RPC: null,
    name: '',
    valueDeposit: 0,
    dataDeposit: '',
  }

  componentDidMount() {
    let testAbie = ''
    setTimeout(() => {
      if (typeof web3 !== 'undefined') {
        // web3 = new Web3(web3.currentProvider);
        this.setState({web3: true})
        //let meta = contract(AbieFund)
        //this.setState({metaContract: meta})
        let provider = new Web3.providers.HttpProvider(`http://${TESTRPC_HOST}:${TESTRPC_PORT}`)
        //let metaCoinBalance = 0
        //meta.setProvider(provider)
        const web3RPC = new Web3(provider)
        this.setState({web3RPC})
        // Get accounts.
        /*
        web3RPC.eth.getAccounts((err, acc) => {
          console.log(err)
          console.log(acc)
          this.setState({accounts: acc})
          return meta.deployed()
            .then((contract) => this.setState({addressContract: contract.address}))
            .catch((err) => console.error(err))
        })*/
      } else {
        alert("install Metamask or use Mist")
      }
    }, 1000)
  }

  handleChangeDelegate = (event) => {
    this.setState({delegate: event.target.value})
  }

  handleChangeAskMembership = (event) => {
    this.setState({askMembership: event.target.value})
  }

  handleChangeName = (event) => {
    this.setState({name: event.target.value})
  }

  handleChangeValueDeposit = (event) => {
    this.setState({valueDeposit: event.target.value})
  }

  handleChangeDataDeposit = (event) => {
    this.setState({dataDeposit: event.target.value})
  }

  setDelegate = () => {
    this.state.metaContract.at(this.state.addressContract)
      .then((contract) => contract.setDelegate(
        0,
        this.state.delegate,
        {from: this.state.accounts[0]}
      ))
      .then((result) => console.log(result))
      .catch((err) => {
        console.error(err);
      })
  }

  askMembership = () => {
    this.state.metaContract.at(this.state.addressContract)
      .then((contract) => {
        return contract.askMembership(
        {
          value: web3.toWei(10, "ether"),
          from: this.state.accounts[4],
          gas: 4000000
        }
      )})
      .then((result) => console.log(result))
      .catch((err) => {
        console.error(err);
      })
  }

  addProposal = () => {
    this.state.metaContract.at(this.state.addressContract)
      .then((contract) => {
        return contract.addProposal(
          this.state.name,
          this.state.valueDeposit,
          this.state.dataDeposit,
        {
          value: web3.toWei(1, "ether"),
          from: this.state.accounts[0],
          gas: 4000000
        }
      )})
      .then((result) => console.log(result))
      .catch((err) => {
        console.error(err);
      })
  }

  render() {
    return (

Abie

Balance : {this.state.balance}

            Set Delegate <input type="text" onChange={this.handleChangeDelegate} />
            <button onClick={this.setDelegate}>Add address</button>

            Ask Membership <input type="text" onChange={this.handleChangeAskMembership} />
            <button onClick={this.askMembership}>Ask membership</button>

          Add proposal
          <input type="text" onChange={this.handleChangeName} placeholder="Name of the proposition (hex)" />
          <input type="text" onChange={this.handleChangeRequestAmount} placeholder="Requested amount (Wei)" />
          <input type="text" onChange={this.handleChangeDescription} placeholder="Link IPFS" />
          <button onClick={this.addProposal}>Submit add proposal</button>

    )
  }
}

export default Proposal
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Wed Mar 18 2015 11:41:18 GMT+0800 (CST)
'use strict';

var path = require('path');

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

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

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

    // list of files / patterns to l/oad in the browser
    files: [
      {pattern: 'test/specs/*.js', included: true, watched: false},
    ],

    // list of files to exclude
    exclude: [
      'test/coverage/**',
      'lib/**',
      'node_modules/'
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'test/**/*.js': ['webpack', 'sourcemap'],
    },

    webpack: {
      devtool: 'inline-source-map',
      module: {
        noParse: [
          /node_modules\/re-animate\/lib\/index\.js/,
          /node_modules\/recharts-scale\/node_modules\/ramda\/dist\/ramda\.js/,
        ],
        loaders: [{
          test: /\.js$/,
          include: /src|test|recharts/,
          exclude: /node_modules/,
          loader: 'babel'
        }, {
          test: /\.jsx?$/,
          include: /node_modules\/recharts-scale\//,
          loader: 'babel'
        }],
        postLoaders: [{
          test: /\.js$/,
          include: /src/,
          exclude: /node_modules/,
          loader: 'istanbul-instrumenter'
        }]
      },
      resolve: {
        alias: {
          'recharts': path.resolve('./src/index.js'),
          'recharts-scale': path.resolve('./node_modules/recharts-scale/index.js')
        }
      },
      stats: {
        assets: false,
        colors: true,
        version: false,
        hash: false,
        timings: false,
        chunks: false,
        chunkModules: false
      },
      debug: false,
    },

    plugins: [
      'karma-webpack',
      'karma-mocha',
      'karma-coverage',
      'karma-chai',
      'karma-sourcemap-loader',
      'karma-firefox-launcher',
      'karma-chrome-launcher',
      'istanbul-instrumenter-loader',
      'karma-coveralls'
    ],

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

    coverageReporter: {
      dir: 'test',
      reporters: [{
        type: 'html',
        subdir: 'coverage'
      }, {
        type: 'text',
      }, {
        type: 'lcov',
        subdir: 'coverage'
      }]
    },

    // web server port
    port: 9876,

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

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

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

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

    browserNoActivityTimeout: 60000,

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};
<commit_msg>format: lint for karma config<commit_after>// Karma configuration
// Generated on Wed Mar 18 2015 11:41:18 GMT+0800 (CST)
'use strict';

var path = require('path');

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

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

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

    // list of files / patterns to l/oad in the browser
    files: [
      { pattern: 'test/specs/*.js', included: true, watched: false },
    ],

    // list of files to exclude
    exclude: [
      'test/coverage/**',
      'lib/**',
      'node_modules/'
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'test/**/*.js': ['webpack', 'sourcemap'],
    },

    webpack: {
      devtool: 'inline-source-map',
      module: {
        noParse: [
          /node_modules\/re-animate\/lib\/index\.js/,
          /node_modules\/recharts-scale\/node_modules\/ramda\/dist\/ramda\.js/,
        ],
        loaders: [{
          test: /\.js$/,
          include: /src|test|recharts/,
          exclude: /node_modules/,
          loader: 'babel'
        }, {
          test: /\.jsx?$/,
          include: /node_modules\/recharts-scale/,
          loader: 'babel'
        }],
        postLoaders: [{
          test: /\.js$/,
          include: /src/,
          exclude: /node_modules/,
          loader: 'istanbul-instrumenter'
        }]
      },
      resolve: {
        alias: {
          'recharts': path.resolve('./src/index.js'),
          'recharts-scale': path.resolve('./node_modules/recharts-scale/index.js')
        }
      },
      stats: {
        assets: false,
        colors: true,
        version: false,
        hash: false,
        timings: false,
        chunks: false,
        chunkModules: false
      },
      debug: false,
    },

    plugins: [
      'karma-webpack',
      'karma-mocha',
      'karma-coverage',
      'karma-chai',
      'karma-sourcemap-loader',
      'karma-firefox-launcher',
      'karma-chrome-launcher',
      'istanbul-instrumenter-loader',
      'karma-coveralls'
    ],

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

    coverageReporter: {
      dir: 'test',
      reporters: [{
        type: 'html',
        subdir: 'coverage'
      }, {
        type: 'text',
      }, {
        type: 'lcov',
        subdir: 'coverage'
      }]
    },

    // web server port
    port: 9876,

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

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

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

    browserNoActivityTimeout: 60000,

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};
<|endoftext|>


<commit_before>'use strict';

function draw_logic(){
    entity_group_modify({
      'groups': [
        'canvas',
      ],
      'todo': function(entity){
          canvas_buffer.fillRect(
            entity_entities[entity]['x'],
            entity_entities[entity]['y'],
            1,
            1
          );
      },
    });
}

function logic(){
    entity_create({
      'properties': {
        'speed': core_random_integer({
          'max': 3,
          'todo': 'ceil',
        }),
        'x': canvas_properties['width'],
        'y': core_random_integer({
          'max': canvas_properties['height'],
        }),
      },
    });

    entity_group_modify({
      'groups': [
        'canvas',
      ],
      'todo': function(entity){
          entity_entities[entity]['x'] -= entity_entities[entity]['speed'];

          // Remove stars that reached left side of screen.
          if(entity_entities[entity]['x'] < 0){
              entity_remove({
                'entities': [
                  entity,
                ],
              });
          }
      },
    });
}

function repo_init(){
    core_repo_init({
      'title': 'D2LoD-ArcaneSanctuary.htm',
    });
    canvas_init();
}
<commit_msg>updated repo function naming<commit_after>'use strict';

function repo_drawlogic(){
    entity_group_modify({
      'groups': [
        'canvas',
      ],
      'todo': function(entity){
          canvas_buffer.fillRect(
            entity_entities[entity]['x'],
            entity_entities[entity]['y'],
            1,
            1
          );
      },
    });
}

function repo_logic(){
    entity_create({
      'properties': {
        'speed': core_random_integer({
          'max': 3,
          'todo': 'ceil',
        }),
        'x': canvas_properties['width'],
        'y': core_random_integer({
          'max': canvas_properties['height'],
        }),
      },
    });

    entity_group_modify({
      'groups': [
        'canvas',
      ],
      'todo': function(entity){
          entity_entities[entity]['x'] -= entity_entities[entity]['speed'];

          // Remove stars that reached left side of screen.
          if(entity_entities[entity]['x'] < 0){
              entity_remove({
                'entities': [
                  entity,
                ],
              });
          }
      },
    });
}

function repo_init(){
    core_repo_init({
      'title': 'D2LoD-ArcaneSanctuary.htm',
    });
    canvas_init();
}
<|endoftext|>


<commit_before>// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// Copyright: ©2006-2009 Sprout Systems, Inc. and contributors.
//            portions copyright @2009 Apple Inc.
// License:   Licened under MIT license (see license.js)
// ==========================================================================

/*global module test htmlbody ok equals same stop start */
var pane, view, view1, view2 ;
module("SC.ScrollerView",{
  setup: function() {
    SC.RunLoop.begin();
	pane = SC.MainPane.create({
	  childViews: [
	    SC.ScrollerView.extend({
		}),
		SC.ScrollerView.extend({
		  minimum:10,
		  maximum:100,
		  isEnabled:NO,
		  layoutDirection: SC.LAYOUT_HORIZONTAL
		}),
		SC.ScrollerView.extend({
      layout:{ top: 0, bottom: 0, right: 0, width: 20 },
		  minimum:0,
		  maximum:100
		})

	  ]
	});
	pane.append(); // make sure there is a layer...
	SC.RunLoop.end();
	view = pane.childViews[0];
	view1= pane.childViews[1];
  view2= pane.childViews[2];
  },

  teardown: function() {
   	pane.remove();
   	pane = view = null ;
  }
});

test('value', function() {
  equals(view1.get('maximum'), 100, 'precond - view has maximum of 100');
  equals(view1.get('minimum'), 10, 'precond - view has a minimum of 10');
  view1.set('value', 300);
  equals(view1.get('value'), view1.get('maximum'), 'value is set to maximum if attempting to set higher than maximum');
  view1.set('maximum', 50);
  equals(view1.get('value'), view1.get('maximum'), 'value should change if maximum changes');
  view1.set('value', 0);
  equals(view1.get('value'), view1.get('minimum'), 'value is set to minimum if attempt to set lower than minimum');
  view1.set('minimum', 15);
  equals(view1.get('value'), view1.get('minimum'), 'value should change if minimum changes');
});

test('isEnabled', function() {
  ok(!view.$().hasClass('disabled'), 'scrollers should be enabled by default');
  view.set('isEnabled', NO);
  SC.RunLoop.begin().end();
  ok(view.$().hasClass('disabled'), 'scrollers should have disabled class set if isEnabled is set to NO');

  var evt = SC.Object.create({
    target: { className: 'button-top' }
  });
  var scrollerHeight = view.get('frame').height;
  view.set('maximum', scrollerHeight+100);
  view.set('value', 500);
  view.mouseDown(evt);
  equals(view.get('value'), 500, 'scrollers should not respond to mouse events if they are disabled');
  view.set('isEnabled', YES);
  view.mouseDown(evt);
  ok(view.get('value') < (scrollerHeight+100), 'scrollers should respond to mouse events if they are not disabled');
});

test('maximum', function() {
  var scrollerHeight = view.get('frame').height;
  view.set('maximum', scrollerHeight + 100);
});<commit_msg>WIP on scrollbar unit tests.<commit_after>// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// Copyright: ©2006-2009 Sprout Systems, Inc. and contributors.
//            portions copyright @2009 Apple Inc.
// License:   Licened under MIT license (see license.js)
// ==========================================================================

/*global module test htmlbody ok equals same stop start */
var pane, view, view1, view2 ;
module("SC.ScrollerView",{
  setup: function() {
    SC.RunLoop.begin();
	pane = SC.MainPane.create({
	  childViews: [
	    SC.ScrollerView.extend({
		}),
		SC.ScrollerView.extend({
		  minimum:10,
		  maximum:100,
		  isEnabled:NO,
		  layoutDirection: SC.LAYOUT_HORIZONTAL
		}),
		SC.ScrollerView.extend({
      layout:{ top: 0, bottom: 0, right: 0, width: 20 },
		  minimum:0,
		  maximum:100
		})

	  ]
	});
	pane.append(); // make sure there is a layer...
	SC.RunLoop.end();
	view = pane.childViews[0];
	view1= pane.childViews[1];
  view2= pane.childViews[2];
  },

  teardown: function() {
   	pane.remove();
   	pane = view = null ;
  }
});

test('value', function() {
  equals(view1.get('maximum'), 100, 'precond - view has maximum of 100');
  equals(view1.get('minimum'), 10, 'precond - view has a minimum of 10');
  view1.set('value', 300);
  equals(view1.get('value'), view1.get('maximum'), 'value is set to maximum if attempting to set higher than maximum');
  view1.set('maximum', 50);
  equals(view1.get('value'), view1.get('maximum'), 'value should change if maximum changes');
  view1.set('value', 0);
  equals(view1.get('value'), view1.get('minimum'), 'value is set to minimum if attempt to set lower than minimum');
  view1.set('minimum', 15);
  equals(view1.get('value'), view1.get('minimum'), 'value should change if minimum changes');
});

test('isEnabled', function() {
  ok(!view.$().hasClass('disabled'), 'scrollers should be enabled by default');
  view.set('isEnabled', NO);
  SC.RunLoop.begin().end();
  ok(view.$().hasClass('disabled'), 'scrollers should have disabled class set if isEnabled is set to NO');

  var layer = view.$('.button-down'),
      evt = SC.Event.simulateEvent(layer, 'mousedown'),
      scrollerHeight = view.get('frame').height;

  view.set('maximum', scrollerHeight+100);
  view.set('value', 500);
  SC.Event.trigger(layer, 'mousedown', [evt]);
  equals(view.get('value'), 500, 'scrollers should not respond to mouse events if they are disabled');
  view.set('isEnabled', YES);
  SC.Event.trigger(layer, 'mousedown', [evt]);
  ok(view.get('value') < (scrollerHeight+100), 'scrollers should respond to mouse events if they are not disabled');
});

test('mouseDown', function() {
  var layer = view.get('layer');
  var ev = SC.Event.simulateEvent(layer, 'mousedown');
});

test('maximum', function() {
  var scrollerHeight = view.get('frame').height;
  view.set('maximum', scrollerHeight + 100);
});

test('layoutDirection', function() {
  equals(view.get('layoutDirection'), SC.LAYOUT_VERTICAL, 'scrollers should default to vertical direction');
  ok(view.$().hasClass('sc-vertical'), 'scroller with vertical layoutDirection has sc-vertical class name');
  equals(view1.get('layoutDirection'), SC.LAYOUT_HORIZONTAL, 'precond - view1 has horizontal direction');
  ok(view1.$().hasClass('sc-horizontal'), 'scroller with horizontal layoutDirection has sc-horizontal class name');
});<|endoftext|>


<commit_before>const path = require('path');
const _ = require('lodash');
const serveStatic = require('serve-static');
const app = require('./app-emulation.js');
const { createElement: h } = require('react');
const { renderToString } = require('react-dom/server');
const { StaticRouter } = require('react-router-dom');
const { createStore } = require('redux');
const { Provider } = require('react-redux');
const requireFromString = require('require-from-string');

const defaultOptions = {
  isProductionMode: () => process.env.NODE_ENV === 'production',
  isRoutingUrl: (url, req) => (/\.html?$/.test(url) || !/\.\w+$/.test(url)) && req.header('accept') !== 'text/event-stream',
  dirSourceClient: './src/client',
  dirBuildClient: './build/client',
  fileIndexHtml: 'index.html',
  fileIndexJs: 'index.js',
  fileAppJs: 'App.js',
  fileReducerJs: 'reducer.js',
  dirSourceServer: './src/server',
  dirBuildServer: './build/server',
  optsServeClient: { redirect: false },
  webpackDevConfig: require('./webpack-dev-config.js'),
  webpackDevOptions: { noInfo: true, publicPath: '/' },
  webpackDevBuildCallback: () => console.log('webpack dev build done.'),
};

function middleware(options = {}) {
  options = _.merge(defaultOptions, options);

  // STEP-01 check production mode
  const productionMode = options.isProductionMode();
  let compiler; // webpack compiler only used if not production mode
  const getCompiler = filename =>
    compiler.compilers ?
    compiler.compilers.find(x => x.options.output.filename === filename) :
    compiler;

  // STEP-02 serve assets and index.html
  if (productionMode) {
    app.use(serveStatic(options.dirBuildClient, options.optsServeClient));
  } else {
    compiler = require('webpack')(options.webpackDevConfig);
    compiler.plugin('done', options.webpackDevBuildCallback);
    app.use(require('webpack-dev-middleware')(compiler, options.webpackDevOptions));

    app.get('/', (req, res) => {
      const c = getCompiler(options.fileIndexHtml);
      const html = c.outputFileSystem.readFileSync(path.join(c.outputPath, options.fileIndexHtml), 'utf8');
      res.set('content-type', 'text/html');
      res.send(html);
    });
    app.use(require('webpack-hot-middleware')(compiler, options.webpackHotOptions));
  }

  // STEP-03 serve prerendered html
  const getClientModule = (file) => {
    /* eslint-disable import/no-dynamic-require */
    let module;
    if (productionMode) {
      module = require(path.resolve(options.dirBuildClient, file));
    } else {
      const c = getCompiler(file);
      const content = c.outputFileSystem.readFileSync(path.join(c.outputPath, file), 'utf8');
      module = requireFromString(content); // TODO we should cache it
    }
    if (module.default) module = module.default;
    return module;

    /* eslint-enable import/no-dynamic-require */
  };
  app.use((req, res, next) => {
    if (req.url === '/') return next();
    if (!options.isRoutingUrl(req.url, req)) return next();
    const reducer = getClientModule(options.fileReducerJs);
    const App = getClientModule(options.fileAppJs);
    if (!reducer || !App) return next();
    const store = createStore(reducer);
    const context = {};
    const appHtml = renderToString(
      h(Provider, { store },
        h(StaticRouter, { location: req.url, context },
          h(App))));
    if (context.url) {
      res.redirect(302, context.url);
    } else {
      let html = getCompiler(options.fileIndexHtml)
        .outputFileSystem.readFileSync(path.join(compiler.outputPath, options.fileIndexHtml), 'utf8');
      const appDiv = '
';
      html = html.replace(appDiv, appDiv + appHtml);
      res.set('content-type', 'text/html');
      res.send(html);
    }
    return null; // just to make eslint happy
  });

  return (req, res, next) => {
    app.handle(0, req, res, next);
  };
}

module.exports = middleware;
<commit_msg>fix getCompiler<commit_after>const path = require('path');
const _ = require('lodash');
const serveStatic = require('serve-static');
const app = require('./app-emulation.js');
const { createElement: h } = require('react');
const { renderToString } = require('react-dom/server');
const { StaticRouter } = require('react-router-dom');
const { createStore } = require('redux');
const { Provider } = require('react-redux');
const requireFromString = require('require-from-string');

const defaultOptions = {
  isProductionMode: () => process.env.NODE_ENV === 'production',
  isRoutingUrl: (url, req) => (/\.html?$/.test(url) || !/\.\w+$/.test(url)) && req.header('accept') !== 'text/event-stream',
  dirSourceClient: './src/client',
  dirBuildClient: './build/client',
  fileIndexHtml: 'index.html',
  fileIndexJs: 'index.js',
  fileAppJs: 'App.js',
  fileReducerJs: 'reducer.js',
  dirSourceServer: './src/server',
  dirBuildServer: './build/server',
  optsServeClient: { redirect: false },
  webpackDevConfig: require('./webpack-dev-config.js'),
  webpackDevOptions: { noInfo: true, publicPath: '/' },
  webpackDevBuildCallback: () => console.log('webpack dev build done.'),
};

function middleware(options = {}) {
  options = _.merge(defaultOptions, options);

  // STEP-01 check production mode
  const productionMode = options.isProductionMode();
  let compiler; // webpack compiler only used if not production mode
  const getCompiler = filename =>
    compiler.compilers ?
    compiler.compilers.find(x => x.options.output.filename === filename) :
    compiler;

  // STEP-02 serve assets and index.html
  if (productionMode) {
    app.use(serveStatic(options.dirBuildClient, options.optsServeClient));
  } else {
    compiler = require('webpack')(options.webpackDevConfig);
    compiler.plugin('done', options.webpackDevBuildCallback);
    app.use(require('webpack-dev-middleware')(compiler, options.webpackDevOptions));

    app.get('/', (req, res) => {
      const c = getCompiler(options.fileIndexHtml);
      const html = c.outputFileSystem.readFileSync(path.join(c.outputPath, options.fileIndexHtml), 'utf8');
      res.set('content-type', 'text/html');
      res.send(html);
    });
    app.use(require('webpack-hot-middleware')(compiler, options.webpackHotOptions));
  }

  // STEP-03 serve prerendered html
  const getClientModule = (file) => {
    /* eslint-disable import/no-dynamic-require */
    let module;
    if (productionMode) {
      module = require(path.resolve(options.dirBuildClient, file));
    } else {
      const c = getCompiler(file);
      const content = c.outputFileSystem.readFileSync(path.join(c.outputPath, file), 'utf8');
      module = requireFromString(content); // TODO we should cache it
    }
    if (module.default) module = module.default;
    return module;

    /* eslint-enable import/no-dynamic-require */
  };
  app.use((req, res, next) => {
    if (req.url === '/') return next();
    if (!options.isRoutingUrl(req.url, req)) return next();
    const reducer = getClientModule(options.fileReducerJs);
    const App = getClientModule(options.fileAppJs);
    if (!reducer || !App) return next();
    const store = createStore(reducer);
    const context = {};
    const appHtml = renderToString(
      h(Provider, { store },
        h(StaticRouter, { location: req.url, context },
          h(App))));
    if (context.url) {
      res.redirect(302, context.url);
    } else {
      const c = getCompiler(options.fileIndexHtml);
      let html = c.outputFileSystem.readFileSync(path.join(c.outputPath, options.fileIndexHtml), 'utf8');
      const appDiv = '
';
      html = html.replace(appDiv, appDiv + appHtml);
      res.set('content-type', 'text/html');
      res.send(html);
    }
    return null; // just to make eslint happy
  });

  return (req, res, next) => {
    app.handle(0, req, res, next);
  };
}

module.exports = middleware;
<|endoftext|>


<commit_before>import buble from 'rollup-plugin-buble';
import json from 'rollup-plugin-json';
import nodeResolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';

var external = process.env.DEPS ? [] : [ 'acorn-jsx', 'magic-string' ];

export default {
	entry: 'src/index.js',
	moduleName: 'buble',
	plugins: [
		json(),
		commonjs(),
		buble({
			include: [ 'src/**', 'node_modules/acorn/**' ],
			transforms: {
				dangerousForOf: true
			}
		}),
		nodeResolve({
			jsnext: true,
			skip: external
		})
	],
	external: external,
	globals: {
		'acorn-jsx': 'acorn',
		'magic-string': 'MagicString'
	},
	sourceMap: true
};
<commit_msg>fix 0.12 tests, hopefully<commit_after>import buble from 'rollup-plugin-buble';
import json from 'rollup-plugin-json';
import nodeResolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';

var external = process.env.DEPS ? [] : [ 'acorn-jsx', 'magic-string' ];

export default {
	entry: 'src/index.js',
	moduleName: 'buble',
	plugins: [
		json(),
		commonjs(),
		buble({
			include: [ 'src/**', 'node_modules/acorn/**', 'node_modules/acorn-object-spread/**' ],
			transforms: {
				dangerousForOf: true
			}
		}),
		nodeResolve({
			jsnext: true,
			skip: external
		})
	],
	external: external,
	globals: {
		'acorn-jsx': 'acorn',
		'magic-string': 'MagicString'
	},
	sourceMap: true
};
<|endoftext|>


<commit_before>var domBuilder = require('dombuilder');
var progressParser = require('../lib/progress-parser.js');
var ui = require('./ui.js');

module.exports = function (backend) {
  ui.push(repoList(backend));
  backend.add({
    name: "creationix/conquest",
    url: "https://github.com/creationix/conquest.git",
    description: "A remake of the classic Lords of Conquest for C64 implemented in JavaScript"
  }, check);
  backend.add({
    name: "creationix/jack",
    url: "git://github.com/creationix/jack.git",
  }, check);
  backend.add({
    name: "creationix/js-git",
    url: "http://github.com/creationix/js-git.git",
    description: "A JavaScript implementation of Git."
  }, check);
  function check(err) {
    if (err) throw err;
  }
};

function repoList(backend) {
  var $ = {};
  var children = {};
  backend.init(onAdd, onRemove, onReady);

  return domBuilder(["section.page$page", {"data-position": "none", css: {opacity: 0.5}},
    ["header",
      ["button", {onclick:onclick(add)}, [".icon-plus"]],
      ["h1", "Git Repositories"]
    ],
    ["ul.content.header$list"]
  ], $);

  function onAdd(repo) {
    var icon = ".icon.left.icon-";
    if (/github\.com/.test(repo.url)) {
      icon += "github";
    }
    else if (/bitbucket\.org/.test(repo.url)) {
      icon += "bitbucket";
    }
    else {
      icon += "git";
    }
    var $$ = {};
    var child = domBuilder(
      ["li.active",
        [icon],
        ["p", repo.name],
        ["p", repo.description],
        ["p.progress",
          ["progress$progress"], ["span$span", "Working..."]
        ],
      ], $$
    );
    children[repo.name] = child;
    $.list.appendChild(child);
    repo.remove = remove;

    var progress = $$.progress;
    var span = $$.span;
    repo.fetch(repo.remote, {
      onProgress: progressParser(function (message, num, max) {
        progress.setAttribute("max", max);
        progress.setAttribute("value", num);
        span.textContent = message;
      })
    }, function (err) {
      if (err) return ui.error(err);
      var oldChild = child;
      child = domBuilder(
        ["li", { href:"#", onclick: onclick(load, repo) },
          [icon],
          [".icon.right.icon-right-open"],
          ["p", repo.name],
          ["p", repo.description]
        ]
      );
      children[repo.name] = child;
      $$ = null;
      $.list.replaceChild(child, oldChild);
    });

    function remove(callback) {
      backend.remove(repo, callback);
    }
  }

  function onRemove(meta) {
    var child = children[meta.name];
    delete children[meta.name];
    $.list.removeChild(child);
  }

  function onReady(err) {
    if (err) return ui.error(err);
    $.page.style.opacity = 1;
  }

  function load(repo) {
    repo.logWalk("HEAD", function (err, stream) {
      if (err) return ui.error(err);
      ui.push(historyList(repo, stream));
    });
  }

  function add() {
    ui.push(addPage(backend));
  }

}

function addPage(backend) {
  var $ = {};
  var working = false;
  return domBuilder(["section.page",
    ["header",
      ["button.back", {onclick: ui.pop}, [".icon-left-open"]],
      ["h1", "Add Repository"]
    ],
    ["form.content.header", {onsubmit: submit},
      ["label", {"for": "url"}, "Remote Url"],
      ["input", {
        type: "text",
        name: "url",
        placeholder: "Enter git url here",
        value: "git://github.com/creationix/conquest.git",
        required: true
      }],
      ["label", {"for": "name"}, "Name"],
      ["input", {
        type: "text",
        name: "name",
        placeholder: "Enter custom local name here",
      }],
      ["label", {"for": "description"}, "Description"],
      ["input", {
        type: "text",
        name: "description",
        placeholder: "Enter a short description here",
      }],
      ["input$submit", {
        type: "submit",
        value: "Add Repo"
      }]
    ]
  ], $);
  function submit(evt) {
    evt.preventDefault();
    if (working) return;
    working = true;
    var url = this.url.value;
    var name = this.name.value;
    if (!name) {
      var index = url.lastIndexOf("/");
      name = url.substr(index + 1);
      if (/\.git$/.test(name)) {
        name = name.substr(0, name.length - 4);
      }
    }
    var description = this.description.value;
    return backend.add({
      name: name,
      url: url,
      description: description
    }, onRepo);

    function onRepo(err) {
      working = false;
      if (err) return ui.error(err);
      return ui.pop();
    }
  }
}

function historyList(repo, stream) {
  var $ = {};
  var first = true;
  var chunkSize = 9;
  var root = domBuilder(["section.page",
    ["header",
      ["button", {onclick:onclick(remove)}, [".icon-minus"]],
      ["button", {onclick:onclick(update)}, [".icon-download"]],
      ["button.back", {onclick: ui.pop}, [".icon-left-open"]],
      ["h1", repo.name]
    ],
    ["ul$ul.content.header",
      ["li$li", "Loading..."]
    ]
  ], $);
  enqueue(true);
  return root;

  function remove() {
    ui.confirm("Are you sure you want to delete this local repo?", function (res) {
      if (!res) return;
      repo.remove(function (err) {
        if (err) return ui.error(err);
        ui.pop();
      });
    });
  }

  function update() {
    ui.error("TODO: Implement update");
  }

  function enqueue(isFirst) {
    first = isFirst;
    var left = chunkSize;
    stream.read(onRead);
    function onRead(err, commit) {
      if (err) return ui.error(err);
      if (commit === undefined) {
        $.ul.removeChild($.li);
        return;
      }
      var title = truncate(commit.message, 80);
      append(title, commit);
      if (--left) return stream.read(onRead);
      appendMore();
    }
  }

  function append(title, commit) {
    var list = [
      ["li", { href:"#", onclick: onclick(load, commit) },
        [".icon.right.icon-right-open"],
        ["p", title],
        ["p", commit.hash]
      ],
      ["li$li", "Loading..."]
    ];
    $.ul.removeChild($.li);
    $.ul.appendChild(domBuilder(list, $));
    if (!first) $.ul.scrollTop = $.ul.scrollHeight;
  }

  function appendMore() {
    var list = ["li$li",{ href:"#", onclick: onclick(enqueue) },
      ["p", "Load More..."]
    ];
    $.ul.removeChild($.li);
    $.ul.appendChild(domBuilder(list, $));
  }

  function load(commit) {
    ui.push(commitPage(repo, commit));
  }
}

function commitPage(repo, commit) {
  var details = [];
  var body = ["section.page",
    ["header",
      ["button.back", {onclick: ui.pop}, [".icon-left-open"]],
      ["h1", repo.name]
    ],
    ["form.content.header", {onsubmit: prevent}, details]
  ];
  details.push(
    ["label", "Message"],
    ["p", {css:{whiteSpace:"pre-wrap"}}, commit.message]);
  details.push(
    ["label", "Tree"],
    ["button.recommend", {onclick: enter}, commit.tree]);
  if (commit.parents) {
    details.push(["label",
      "Parent" + (commit.parents.length === 1 ? "" : "s")
    ]);
    commit.parents.forEach(function (parent) {
      details.push(["button", {onclick: ascend(parent)}, parent]);
    });
  }
  details.push(
    ["label", "Author"],
    ["p", commit.author.name + " <" + commit.author.email + "> " + commit.author.date]);
  if (commit.author.email !== commit.committer.email) {
    details.push(
      ["label", "Committer"],
      ["p", commit.committer.name + " <" + commit.committer.email + "> " + commit.committer.date]);
  }
  details.push(
    ["label", "Hash"],
    ["button", {disabled:true}, commit.hash]);

  return domBuilder(body);

  function prevent(evt) {
    evt.preventDefault();
  }

  function enter() {
    repo.loadAs("tree", commit.tree, function (err, tree) {
      if (err) return ui.error(err);
      ui.push(filesList(repo, tree));
    });
  }

  function ascend(parent) {
    return function () {
      repo.loadAs("commit", parent, function (err, commit) {
        if (err) return ui.error(err);
        ui.peer(commitPage(repo, commit));
      });
    };
  }
}

function filesList(repo, tree) {
  return domBuilder(["section.page",
    ["header",
      ["button.back", {onclick: ui.pop}, [".icon-left-open"]],
      ["h1", repo.name]
    ],
    ["ul.content.header", tree.map(function (file) {
      var icon = ".icon.left.icon-";
      if (file.mode === 16384) {
        icon += "folder-empty";
      }
      else {
        icon += "doc";
      }

      return ["li", { href:"#", onclick: onclick(load, file) },
        [icon],
        (file.mode === 16384 ? [".icon.right.icon-right-open"] : []),
        ["p", file.name],
        ["p", file.hash]
      ];
    })]
  ]);
  function load(file) {
    if (file.mode === 16384) {
      return repo.loadAs("tree", file.hash, function (err, tree) {
        if (err) return ui.error(err);
        ui.push(filesList(repo, tree));
      });
    }
    console.log("TODO: load file");
  }
}

function truncate(message, limit) {
  var title = message.split(/[\r\n]/)[0];
  if (title.length > limit) title = title.substr(0, limit - 3) + "...";
  return title;
}

function onclick(handler) {
  var args = Array.prototype.slice.call(arguments, 1);
  return function (evt) {
    evt.preventDefault();
    evt.stopPropagation();
    return handler.apply(this, args);
  };
}

<commit_msg>Improve infinite history scroller<commit_after>var domBuilder = require('dombuilder');
var progressParser = require('../lib/progress-parser.js');
var ui = require('./ui.js');

module.exports = function (backend) {
  ui.push(repoList(backend));
  backend.add({
    name: "creationix/conquest",
    url: "git://github.com/creationix/conquest.git",
    description: "A remake of the classic Lords of Conquest for C64 implemented in JavaScript"
  }, check);
  backend.add({
    name: "creationix/jack",
    url: "https://github.com/creationix/jack.git",
  }, check);
  backend.add({
    name: "creationix/js-git",
    url: "http://github.com/creationix/js-git.git",
    description: "A JavaScript implementation of Git."
  }, check);
  function check(err) {
    if (err) throw err;
  }
};

function repoList(backend) {
  var $ = {};
  var children = {};
  backend.init(onAdd, onRemove, onReady);

  return domBuilder(["section.page$page", {"data-position": "none", css: {opacity: 0.5}},
    ["header",
      ["button", {onclick:onclick(add)}, [".icon-plus"]],
      ["h1", "Git Repositories"]
    ],
    ["ul.content.header$list"]
  ], $);

  function onAdd(repo) {
    var icon = ".icon.left.icon-";
    if (/github\.com/.test(repo.url)) {
      icon += "github";
    }
    else if (/bitbucket\.org/.test(repo.url)) {
      icon += "bitbucket";
    }
    else {
      icon += "git";
    }
    var $$ = {};
    var child = domBuilder(
      ["li.active",
        [icon],
        ["p", repo.name],
        ["p", repo.description],
        ["p.progress",
          ["progress$progress"], ["span$span", "Working..."]
        ],
      ], $$
    );
    children[repo.name] = child;
    $.list.appendChild(child);
    repo.remove = remove;

    var progress = $$.progress;
    var span = $$.span;
    repo.fetch(repo.remote, {
      onProgress: progressParser(function (message, num, max) {
        progress.setAttribute("max", max);
        progress.setAttribute("value", num);
        span.textContent = message;
      })
    }, function (err) {
      if (err) return ui.error(err);
      var oldChild = child;
      child = domBuilder(
        ["li", { href:"#", onclick: onclick(load, repo) },
          [icon],
          [".icon.right.icon-right-open"],
          ["p", repo.name],
          ["p", repo.description]
        ]
      );
      children[repo.name] = child;
      $$ = null;
      $.list.replaceChild(child, oldChild);
    });

    function remove(callback) {
      backend.remove(repo, callback);
    }
  }

  function onRemove(meta) {
    var child = children[meta.name];
    delete children[meta.name];
    $.list.removeChild(child);
  }

  function onReady(err) {
    if (err) return ui.error(err);
    $.page.style.opacity = 1;
  }

  function load(repo) {
    repo.logWalk("HEAD", function (err, stream) {
      if (err) return ui.error(err);
      ui.push(historyList(repo, stream));
    });
  }

  function add() {
    ui.push(addPage(backend));
  }

}

function addPage(backend) {
  var $ = {};
  var working = false;
  return domBuilder(["section.page",
    ["header",
      ["button.back", {onclick: ui.pop}, [".icon-left-open"]],
      ["h1", "Add Repository"]
    ],
    ["form.content.header", {onsubmit: submit},
      ["label", {"for": "url"}, "Remote Url"],
      ["input", {
        type: "text",
        name: "url",
        placeholder: "Enter git url here",
        value: "git://github.com/creationix/conquest.git",
        required: true
      }],
      ["label", {"for": "name"}, "Name"],
      ["input", {
        type: "text",
        name: "name",
        placeholder: "Enter custom local name here",
      }],
      ["label", {"for": "description"}, "Description"],
      ["input", {
        type: "text",
        name: "description",
        placeholder: "Enter a short description here",
      }],
      ["input$submit", {
        type: "submit",
        value: "Add Repo"
      }]
    ]
  ], $);
  function submit(evt) {
    evt.preventDefault();
    if (working) return;
    working = true;
    var url = this.url.value;
    var name = this.name.value;
    if (!name) {
      var index = url.lastIndexOf("/");
      name = url.substr(index + 1);
      if (/\.git$/.test(name)) {
        name = name.substr(0, name.length - 4);
      }
    }
    var description = this.description.value;
    return backend.add({
      name: name,
      url: url,
      description: description
    }, onRepo);

    function onRepo(err) {
      working = false;
      if (err) return ui.error(err);
      return ui.pop();
    }
  }
}

function historyList(repo, stream) {
  var $ = {}, ul, end, reading = false;
  var root = domBuilder(["section.page",
    ["header",
      ["button", {onclick:onclick(remove)}, [".icon-minus"]],
      ["button", {onclick:onclick(update)}, [".icon-download"]],
      ["button.back", {onclick: ui.pop}, [".icon-left-open"]],
      ["h1", repo.name]
    ],
    ["ul$ul.content.header",
      ["li$li", {css:{height: "100px"}}, "Loading..."]
    ]
  ], $);
  ul = $.ul;
  end = $.li;
  $ = {};
  ul.addEventListener('scroll', check, false);
  window.addEventListener('resize', check, false);
  setImmediate(function () {
    reading = true;
    stream.read(onRead);
  });
  return root;

  function remove() {
    ui.confirm("Are you sure you want to delete this local repo?", function (res) {
      if (!res) return;
      repo.remove(function (err) {
        if (err) return ui.error(err);
        ui.pop();
      });
    });
  }

  function update() {
    ui.error("TODO: Implement update");
  }

  function load(commit) {
    ui.push(commitPage(repo, commit));
  }

  function onRead(err, commit) {
    reading = false;
    if (err) return ui.error(err);
    if (commit === undefined) {
      ul.removeChild(end);
      end = null;
      ul.removeEventListener('scroll', check, false);
      window.removeEventListener('resize', check, false);
      return;
    }
    var title = truncate(commit.message, 80);
    var item = domBuilder(
      ["li", { href:"#", onclick: onclick(load, commit) },
        [".icon.right.icon-right-open", { title: commit.hash }],
        ["p", title],
        ["p", commit.author.date]
      ]
    );
    ul.insertBefore(item, end);
    check();
  }

  function check() {
    if (reading) return;
    console.log({
      otop: end.offsetTop,
      uHeight: ul.offsetHeight,
      uTop: ul.scrollTop
    })
    if (end.offsetTop > ul.offsetHeight + ul.scrollTop) return;
    reading = true;
    stream.read(onRead);
  }

}

function commitPage(repo, commit) {
  var details = [];
  var body = ["section.page",
    ["header",
      ["button.back", {onclick: ui.pop}, [".icon-left-open"]],
      ["h1", repo.name]
    ],
    ["form.content.header", {onsubmit: prevent}, details]
  ];
  details.push(
    ["label", "Message"],
    ["p", {css:{whiteSpace:"pre-wrap"}}, commit.message]);
  details.push(
    ["label", "Tree"],
    ["button.recommend", {onclick: enter}, commit.tree]);
  if (commit.parents) {
    details.push(["label",
      "Parent" + (commit.parents.length === 1 ? "" : "s")
    ]);
    commit.parents.forEach(function (parent) {
      details.push(["button", {onclick: ascend(parent)}, parent]);
    });
  }
  details.push(
    ["label", "Author"],
    ["p", commit.author.name + " <" + commit.author.email + "> " + commit.author.date]);
  if (commit.author.email !== commit.committer.email) {
    details.push(
      ["label", "Committer"],
      ["p", commit.committer.name + " <" + commit.committer.email + "> " + commit.committer.date]);
  }
  details.push(
    ["label", "Hash"],
    ["button", {disabled:true}, commit.hash]);

  return domBuilder(body);

  function prevent(evt) {
    evt.preventDefault();
  }

  function enter() {
    repo.loadAs("tree", commit.tree, function (err, tree) {
      if (err) return ui.error(err);
      ui.push(filesList(repo, tree));
    });
  }

  function ascend(parent) {
    return function () {
      repo.loadAs("commit", parent, function (err, commit) {
        if (err) return ui.error(err);
        ui.peer(commitPage(repo, commit));
      });
    };
  }
}

function filesList(repo, tree) {
  return domBuilder(["section.page",
    ["header",
      ["button.back", {onclick: ui.pop}, [".icon-left-open"]],
      ["h1", repo.name]
    ],
    ["ul.content.header", tree.map(function (file) {
      var icon = ".icon.left.icon-";
      if (file.mode === 16384) {
        icon += "folder-empty";
      }
      else {
        icon += "doc";
      }

      return ["li", { href:"#", onclick: onclick(load, file) },
        [icon],
        (file.mode === 16384 ? [".icon.right.icon-right-open"] : []),
        ["p", file.name],
        ["p", file.hash]
      ];
    })]
  ]);
  function load(file) {
    if (file.mode === 16384) {
      return repo.loadAs("tree", file.hash, function (err, tree) {
        if (err) return ui.error(err);
        ui.push(filesList(repo, tree));
      });
    }
    console.log("TODO: load file");
  }
}

function truncate(message, limit) {
  var title = message.split(/[\r\n]/)[0];
  if (title.length > limit) title = title.substr(0, limit - 3) + "...";
  return title;
}

function onclick(handler) {
  var args = Array.prototype.slice.call(arguments, 1);
  return function (evt) {
    evt.preventDefault();
    evt.stopPropagation();
    return handler.apply(this, args);
  };
}

<|endoftext|>


<commit_before>// @flow weak

const path = require('path');
const argv = process.argv.slice(2);
const opts = {
  grep: undefined,
  watch: false,
};

argv.forEach((arg) => {
  if (/^--grep=/.test(arg)) {
    opts.grep = arg.replace('--grep=', '').trim();
  }

  if (/^--watch/.test(arg)) {
    opts.watch = true;
  }
});

// Karma configuration
module.exports = function setKarmaConfig(config) {
  config.set({
    autoWatch: opts.watch,
    basePath: '../',
    browsers: ['PhantomJS'],
    client: {
      mocha: {
        grep: opts.grep,
      },
    },
    colors: true,
    frameworks: ['mocha'],
    files: [
      'node_modules/babel-polyfill/dist/polyfill.js',
      {
        pattern: 'test/karma.tests.js',
        watched: opts.watch,
        served: true,
        included: true,
      },
    ],
    plugins: [
      'karma-phantomjs-launcher',
      'karma-firefox-launcher',
      'karma-mocha',
      'karma-sourcemap-loader',
      'karma-webpack',
      'karma-mocha-reporter',
    ],
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,
    port: 9876,
    preprocessors: {
      'test/karma.tests.js': ['webpack', 'sourcemap'],
    },
    reporters: ['mocha'],
    singleRun: !opts.watch,
    webpack: {
      devtool: 'inline-source-map',
      module: {
        loaders: [
          {
            test: /\.js$/,
            loader: 'babel',
            exclude: /node_modules/,
            query: {
              cacheDirectory: true,
            },
          },
          {
            test: /\.json$/,
            loader: 'json',
          },
        ],
        noParse: [
          /node_modules\/sinon\//,
        ],
      },
      resolve: {
        alias: {
          'material-ui': path.resolve(__dirname, '../src'),
          sinon: 'sinon/pkg/sinon.js',
        },
        extensions: ['', '.js', '.jsx', '.json'],
        modulesDirectories: [
          'node_modules',
          './',
        ],
      },
      externals: {
        jsdom: 'window',
        'react/lib/ExecutionEnvironment': true,
        'react/lib/ReactContext': 'window',
        'text-encoding': 'window',
        'react/addons': true, // For enzyme
      },
    },
    webpackServer: {
      noInfo: true,
    },
  });
};
<commit_msg>[Tests] Attempt to fix phantomjs disconnect issues on travis<commit_after>// @flow weak

const path = require('path');
const argv = process.argv.slice(2);
const opts = {
  grep: undefined,
  watch: false,
};

argv.forEach((arg) => {
  if (/^--grep=/.test(arg)) {
    opts.grep = arg.replace('--grep=', '').trim();
  }

  if (/^--watch/.test(arg)) {
    opts.watch = true;
  }
});

// Karma configuration
module.exports = function setKarmaConfig(config) {
  config.set({
    autoWatch: opts.watch,
    basePath: '../',
    browsers: ['PhantomJS'],
    // to avoid DISCONNECTED messages on travis
    browserDisconnectTimeout: 10000, // default 2000
    browserDisconnectTolerance: 1, // default 0
    browserNoActivityTimeout: 60000, // default 10000
    client: {
      mocha: {
        grep: opts.grep,
      },
    },
    colors: true,
    frameworks: ['mocha'],
    files: [
      'node_modules/babel-polyfill/dist/polyfill.js',
      {
        pattern: 'test/karma.tests.js',
        watched: opts.watch,
        served: true,
        included: true,
      },
    ],
    plugins: [
      'karma-phantomjs-launcher',
      'karma-firefox-launcher',
      'karma-mocha',
      'karma-sourcemap-loader',
      'karma-webpack',
      'karma-mocha-reporter',
    ],
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,
    port: 9876,
    preprocessors: {
      'test/karma.tests.js': ['webpack', 'sourcemap'],
    },
    reporters: ['mocha'],
    singleRun: !opts.watch,
    webpack: {
      devtool: 'inline-source-map',
      module: {
        loaders: [
          {
            test: /\.js$/,
            loader: 'babel',
            exclude: /node_modules/,
            query: {
              cacheDirectory: true,
            },
          },
          {
            test: /\.json$/,
            loader: 'json',
          },
        ],
        noParse: [
          /node_modules\/sinon\//,
        ],
      },
      resolve: {
        alias: {
          'material-ui': path.resolve(__dirname, '../src'),
          sinon: 'sinon/pkg/sinon.js',
        },
        extensions: ['', '.js', '.jsx', '.json'],
        modulesDirectories: [
          'node_modules',
          './',
        ],
      },
      externals: {
        jsdom: 'window',
        'react/lib/ExecutionEnvironment': true,
        'react/lib/ReactContext': 'window',
        'text-encoding': 'window',
        'react/addons': true, // For enzyme
      },
    },
    webpackServer: {
      noInfo: true,
    },
  });
};
<|endoftext|>


<commit_before>'use strict';

function repo_escape(){
    if(selected_button != -1){
        display_number_select(selected_button);
    }
}

function repo_init(){
    core_repo_init({
      'events': {
        'check': {
          'onclick': check,
        },
        'generate': {
          'onclick': generate_puzzle,
        },
      },
      'globals': {
        'puzzle': [],
        'selected_button': -1,
      },
      'info': '<input id=generate type=button value="Generate New Puzzle"><input id=check type=button value="Check Solution">',
      'storage': {
        'locked': 15,
      },
      'storage-menu': '

<input id=locked maxlength=2>*2 > Locked
',
      'title': 'Sudoku.htm',
    });

    // Create buttons and add to game-div.
    let loop_counter = 80;
    let output = '';
    do{
        output +=
          '<input class=gridbuttonclickable id='
          + loop_counter
          + ' onclick=display_number_select('
          + loop_counter
          + ') type=button>';
        if(loop_counter % 9 === 0
          && loop_counter !== 0){
            output += '
';
        }
    }while(loop_counter--);
    let element = document.getElementById('game-div');
    element.innerHTML = output;
    element.style.marginTop = '50px';

    // Setup margins.
    loop_counter = 8;
    do{
        document.getElementById(3 + 9 * loop_counter).style.marginRight = '5px';
        document.getElementById(27 + loop_counter).style.marginBottom = '5px';
        document.getElementById(54 + loop_counter).style.marginBottom = '5px';
        document.getElementById(6 + 9 * loop_counter).style.marginRight = '5px';
    }while(loop_counter--);

    // Setup number-select.
    element = document.getElementById('number-select');
    element.style.position = 'fixed';
    element.style.zIndex = 1;

    generate_puzzle();

    // Setup select-X onclicks.
    loop_counter = 9;
    do{
        document.getElementById('select-' + loop_counter).onclick = function(){
            let id = this.id;
            select_number(id.substring(id.indexOf('-') + 1));
        };
    }while(loop_counter--);

    window.onresize
      = window.onscroll = function(e){
        // Update position of number select if visible.
        if(selected_button != -1){
            update_number_select(selected_button);
        }
    };
}
<commit_msg>added 500px minWidth to game-div<commit_after>'use strict';

function repo_escape(){
    if(selected_button != -1){
        display_number_select(selected_button);
    }
}

function repo_init(){
    core_repo_init({
      'events': {
        'check': {
          'onclick': check,
        },
        'generate': {
          'onclick': generate_puzzle,
        },
      },
      'globals': {
        'puzzle': [],
        'selected_button': -1,
      },
      'info': '<input id=generate type=button value="Generate New Puzzle"><input id=check type=button value="Check Solution">',
      'storage': {
        'locked': 15,
      },
      'storage-menu': '

<input id=locked maxlength=2>*2 > Locked
',
      'title': 'Sudoku.htm',
    });

    // Create buttons and add to game-div.
    let loop_counter = 80;
    let output = '';
    do{
        output +=
          '<input class=gridbuttonclickable id='
          + loop_counter
          + ' onclick=display_number_select('
          + loop_counter
          + ') type=button>';
        if(loop_counter % 9 === 0
          && loop_counter !== 0){
            output += '
';
        }
    }while(loop_counter--);
    let element = document.getElementById('game-div');
    element.innerHTML = output;
    element.style.marginTop = '50px';
    element.style.minWidth = '500px';

    // Setup margins.
    loop_counter = 8;
    do{
        document.getElementById(3 + 9 * loop_counter).style.marginRight = '5px';
        document.getElementById(27 + loop_counter).style.marginBottom = '5px';
        document.getElementById(54 + loop_counter).style.marginBottom = '5px';
        document.getElementById(6 + 9 * loop_counter).style.marginRight = '5px';
    }while(loop_counter--);

    // Setup number-select.
    element = document.getElementById('number-select');
    element.style.position = 'fixed';
    element.style.zIndex = 1;

    generate_puzzle();

    // Setup select-X onclicks.
    loop_counter = 9;
    do{
        document.getElementById('select-' + loop_counter).onclick = function(){
            let id = this.id;
            select_number(id.substring(id.indexOf('-') + 1));
        };
    }while(loop_counter--);

    window.onresize
      = window.onscroll = function(e){
        // Update position of number select if visible.
        if(selected_button != -1){
            update_number_select(selected_button);
        }
    };
}
<|endoftext|>


<commit_before>import babel from 'rollup-plugin-babel'

const pkg = require('./package.json')
const external = Object.keys(pkg.dependencies)
  .concat(['fs', 'path', 'sql.js'])

export default {
  entry: 'src/index.js',
  external,
  plugins: [
    babel({
      babelrc: false,
      presets: [['env', {
        loose: true,
        modules: false,
        targets: { node: 4.7 }
      }], 'stage-0'],
      plugins: [
        'external-helpers',
        'add-module-exports'
      ],
      runtimeHelpers: false,
      exclude: 'node_modules/**'
    })
  ],
  targets: [{
    dest: pkg.main,
    format: 'cjs'
  }, {
    dest: pkg.module,
    format: 'es'
  }]
}
<commit_msg>chore(rollup): specify babel node target as string<commit_after>import babel from 'rollup-plugin-babel'

const pkg = require('./package.json')
const external = Object.keys(pkg.dependencies)
  .concat(['fs', 'path', 'sql.js'])

export default {
  entry: 'src/index.js',
  external,
  plugins: [
    babel({
      babelrc: false,
      presets: [['env', {
        loose: true,
        modules: false,
        targets: { node: "4.7.0" }
      }], 'stage-0'],
      plugins: [
        'external-helpers',
        'add-module-exports'
      ],
      runtimeHelpers: false,
      exclude: 'node_modules/**'
    })
  ],
  targets: [{
    dest: pkg.main,
    format: 'cjs'
  }, {
    dest: pkg.module,
    format: 'es'
  }]
}
<|endoftext|>


<commit_before>var $ = require('jquery');

var utils = require('./utils');
var uiHelper = require('./ui-helper');

function Renderer (editor, web3, updateFiles, udapp, executionContext, formalVerificationEvent, compilerEvent) {
  this.editor = editor;
  this.web3 = web3;
  this.updateFiles = updateFiles;
  this.udapp = udapp;
  this.executionContext = executionContext;
  var self = this;
  formalVerificationEvent.register('compilationFinished', this, function (success, message, container, noAnnotations) {
    if (!success) {
      self.error(message, container, noAnnotations);
    }
  });
  compilerEvent.register('compilationFinished', this, function (success, data, source) {
    $('#output').empty();
    if (success) {
      self.contracts(data, source);
    } else {
      if (data['error']) {
        self.error(data['error']);
      }
      if (data['errors']) {
        data['errors'].forEach(function (err) {
          self.error(err);
        });
      }
    }
  });
}

Renderer.prototype.error = function (message, container, noAnnotations) {
  var type = utils.errortype(message);
  var $pre = $('
').text(message);
  var $error = $('

').prepend($pre);
  if (container === undefined) {
    container = $('#output');
  }
  container.append($error);
  var err = message.match(/^([^:]*):([0-9]*):(([0-9]*):)? /);
  if (err) {
    var errFile = err[1];
    var errLine = parseInt(err[2], 10) - 1;
    var errCol = err[4] ? parseInt(err[4], 10) : 0;
    if (!noAnnotations && (errFile === '' || errFile === utils.fileNameFromKey(this.editor.getCacheFile()))) {
      this.editor.addAnnotation({
        row: errLine,
        column: errCol,
        text: message,
        type: type
      });
    }
    $error.click(function (ev) {
      if (errFile !== '' && errFile !== utils.fileNameFromKey(this.editor.getCacheFile()) && this.editor.hasFile(errFile)) {
        // Switch to file
        this.editor.setCacheFile(utils.fileKey(errFile));
        this.updateFiles();
      // @TODO could show some error icon in files with errors
      }
      this.editor.handleErrorClick(errLine, errCol);
    });
    $error.find('.close').click(function (ev) {
      ev.preventDefault();
      $error.remove();
      return false;
    });
  }
};

Renderer.prototype.contracts = function (data, source) {
  var udappContracts = [];
  for (var contractName in data.contracts) {
    var contract = data.contracts[contractName];
    udappContracts.push({
      name: contractName,
      interface: contract['interface'],
      bytecode: contract.bytecode
    });
  }

  // rendering function used by udapp. they need data and source
  var combined = function (contractName, jsonInterface, bytecode) {
    return JSON.stringify([{ name: contractName, interface: jsonInterface, bytecode: bytecode }]);
  };

  var renderOutputModifier = function (contractName, $contractOutput) {
    var contract = data.contracts[contractName];
    if (contract.bytecode) {
      $contractOutput.append(uiHelper.textRow('Bytecode', contract.bytecode));
    }

    $contractOutput.append(uiHelper.textRow('Interface', contract['interface']));

    if (contract.bytecode) {
      $contractOutput.append(uiHelper.textRow('Web3 deploy', uiHelper.gethDeploy(contractName.toLowerCase(), contract['interface'], contract.bytecode), 'deploy'));
      $contractOutput.append(uiHelper.textRow('uDApp', combined(contractName, contract['interface'], contract.bytecode), 'deploy'));
    }
    var ctrSource = getSource(contractName, source, data);
    return $contractOutput.append(uiHelper.getDetails(contract, ctrSource, contractName));
  };
  // //
  var self = this;

  var getSource = function (contractName, source, data) {
    var currentFile = utils.fileNameFromKey(self.editor.getCacheFile());
    return source.sources[currentFile];
  };

  var getAddress = function () { return $('#txorigin').val(); };

  var getValue = function () {
    var comp = $('#value').val().split(' ');
    return self.executionContext.web3().toWei(comp[0], comp.slice(1).join(' '));
  };

  var getGasLimit = function () { return $('#gasLimit').val(); };

  this.udapp.reset(udappContracts, getAddress, getValue, getGasLimit, renderOutputModifier);

  var $contractOutput = this.udapp.render();

  var $txOrigin = $('#txorigin');

  this.udapp.getAccounts(function (err, accounts) {
    if (err) {
      self.error(err.message);
    }
    if (accounts && accounts[0]) {
      $txOrigin.empty();
      for (var a in accounts) { $txOrigin.append($('<option />').val(accounts[a]).text(accounts[a])); }
      $txOrigin.val(accounts[0]);
    } else {
      $txOrigin.val('unknown');
    }
  });

  $contractOutput.find('.title').click(function (ev) { $(this).closest('.contract').toggleClass('hide'); });
  $('#output').append($contractOutput);
  $('.col2 input,textarea').click(function () { this.select(); });
};

module.exports = Renderer;
<commit_msg>Display warnings even if there were no errors<commit_after>var $ = require('jquery');

var utils = require('./utils');
var uiHelper = require('./ui-helper');

function Renderer (editor, web3, updateFiles, udapp, executionContext, formalVerificationEvent, compilerEvent) {
  this.editor = editor;
  this.web3 = web3;
  this.updateFiles = updateFiles;
  this.udapp = udapp;
  this.executionContext = executionContext;
  var self = this;
  formalVerificationEvent.register('compilationFinished', this, function (success, message, container, noAnnotations) {
    if (!success) {
      self.error(message, container, noAnnotations);
    }
  });
  compilerEvent.register('compilationFinished', this, function (success, data, source) {
    $('#output').empty();
    if (success) {
      self.contracts(data, source);
    }

    // NOTE: still need to display as there might be warnings
    if (data['error']) {
      self.error(data['error']);
    }
    if (data['errors']) {
      data['errors'].forEach(function (err) {
        self.error(err);
      });
    }
  });
}

Renderer.prototype.error = function (message, container, noAnnotations) {
  var type = utils.errortype(message);
  var $pre = $('
').text(message);
  var $error = $('

').prepend($pre);
  if (container === undefined) {
    container = $('#output');
  }
  container.append($error);
  var err = message.match(/^([^:]*):([0-9]*):(([0-9]*):)? /);
  if (err) {
    var errFile = err[1];
    var errLine = parseInt(err[2], 10) - 1;
    var errCol = err[4] ? parseInt(err[4], 10) : 0;
    if (!noAnnotations && (errFile === '' || errFile === utils.fileNameFromKey(this.editor.getCacheFile()))) {
      this.editor.addAnnotation({
        row: errLine,
        column: errCol,
        text: message,
        type: type
      });
    }
    $error.click(function (ev) {
      if (errFile !== '' && errFile !== utils.fileNameFromKey(this.editor.getCacheFile()) && this.editor.hasFile(errFile)) {
        // Switch to file
        this.editor.setCacheFile(utils.fileKey(errFile));
        this.updateFiles();
      // @TODO could show some error icon in files with errors
      }
      this.editor.handleErrorClick(errLine, errCol);
    });
    $error.find('.close').click(function (ev) {
      ev.preventDefault();
      $error.remove();
      return false;
    });
  }
};

Renderer.prototype.contracts = function (data, source) {
  var udappContracts = [];
  for (var contractName in data.contracts) {
    var contract = data.contracts[contractName];
    udappContracts.push({
      name: contractName,
      interface: contract['interface'],
      bytecode: contract.bytecode
    });
  }

  // rendering function used by udapp. they need data and source
  var combined = function (contractName, jsonInterface, bytecode) {
    return JSON.stringify([{ name: contractName, interface: jsonInterface, bytecode: bytecode }]);
  };

  var renderOutputModifier = function (contractName, $contractOutput) {
    var contract = data.contracts[contractName];
    if (contract.bytecode) {
      $contractOutput.append(uiHelper.textRow('Bytecode', contract.bytecode));
    }

    $contractOutput.append(uiHelper.textRow('Interface', contract['interface']));

    if (contract.bytecode) {
      $contractOutput.append(uiHelper.textRow('Web3 deploy', uiHelper.gethDeploy(contractName.toLowerCase(), contract['interface'], contract.bytecode), 'deploy'));
      $contractOutput.append(uiHelper.textRow('uDApp', combined(contractName, contract['interface'], contract.bytecode), 'deploy'));
    }
    var ctrSource = getSource(contractName, source, data);
    return $contractOutput.append(uiHelper.getDetails(contract, ctrSource, contractName));
  };
  // //
  var self = this;

  var getSource = function (contractName, source, data) {
    var currentFile = utils.fileNameFromKey(self.editor.getCacheFile());
    return source.sources[currentFile];
  };

  var getAddress = function () { return $('#txorigin').val(); };

  var getValue = function () {
    var comp = $('#value').val().split(' ');
    return self.executionContext.web3().toWei(comp[0], comp.slice(1).join(' '));
  };

  var getGasLimit = function () { return $('#gasLimit').val(); };

  this.udapp.reset(udappContracts, getAddress, getValue, getGasLimit, renderOutputModifier);

  var $contractOutput = this.udapp.render();

  var $txOrigin = $('#txorigin');

  this.udapp.getAccounts(function (err, accounts) {
    if (err) {
      self.error(err.message);
    }
    if (accounts && accounts[0]) {
      $txOrigin.empty();
      for (var a in accounts) { $txOrigin.append($('<option />').val(accounts[a]).text(accounts[a])); }
      $txOrigin.val(accounts[0]);
    } else {
      $txOrigin.val('unknown');
    }
  });

  $contractOutput.find('.title').click(function (ev) { $(this).closest('.contract').toggleClass('hide'); });
  $('#output').append($contractOutput);
  $('.col2 input,textarea').click(function () { this.select(); });
};

module.exports = Renderer;
<|endoftext|>


<commit_before>module.exports = function(config){
  config.set({

    basePath : '../',

    files : [
      'app/bower_components/angular/angular.js',
      'app/bower_components/angular-route/angular-route.js',
      'app/bower_components/angular-resource/angular-resource.js',
      'app/bower_components/angular-animate/angular-animate.js',
      'app/bower_components/angular-mocks/angular-mocks.js',
      'app/js/**/*.js',
      'test/unit/**/*.js'
    ],

    autoWatch : true,

    frameworks: ['jasmine'],

    browsers : ['Chrome'],

    plugins : [
            'karma-chrome-launcher',
            'karma-firefox-launcher',
            'karma-jasmine',
            'karma-junit-reporter'
            ],

    junitReporter : {
      outputFile: 'test_out/unit.xml',
      suite: 'unit'
    }

  });
};
<commit_msg>config modification<commit_after>module.exports = function(config){
  var configuration = {

    basePath : '../',

    files : [
      'app/bower_components/angular/angular.js',
      'app/bower_components/angular-route/angular-route.js',
      'app/bower_components/angular-resource/angular-resource.js',
      'app/bower_components/angular-animate/angular-animate.js',
      'app/bower_components/angular-mocks/angular-mocks.js',
      'app/js/**/*.js',
      'test/unit/**/*.js'
    ],

    autoWatch : true,

    frameworks: ['jasmine'],

    browsers : ['Chrome', 'ChromeCanary'],

	customLaunchers: {
      Chrome_travis_ci: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },

    plugins : [
            'karma-chrome-launcher',
            'karma-firefox-launcher',
            'karma-jasmine',
            'karma-junit-reporter'
            ],

    junitReporter : {
      outputFile: 'test_out/unit.xml',
      suite: 'unit'
    }

  };

  if(process.env.TRAVIS){
    configuration.browsers = ['Chrome_travis_ci'];
  }

  config.set(configuration);
};
<|endoftext|>


<commit_before>define(function(require) {
    var init = require('init');

    var draw = require('./draw');
    var fill = require('./fill');
    var selectArea = require('./selectArea');
    var copy = require('./copy');
    var paste = require('./paste');
    var loadImage = require('./loadImage');
    var colors = document.getElementById('colors').childNodes;
    for (var i = 0, color; color = colors[i]; i++) {
        if (color.nodeName.toLowerCase() != 'div') continue;
        color.addEventListener('click', function (e) {
            var style = e.target.getAttribute('style');
            var color = style.match(/background:(#......)/)[1];
            context.strokeStyle = color;
            context.fillStyle = color;
        },false);
    };

    var canvas = init.getCanvas();
    var context = init.getContext();

    // canvasに対する操作
    // draw関係
    canvas.addEventListener('mousedown', function() {
        draw.mouseDown();
    });
    canvas.addEventListener('mousemove', function(e) {
        draw.mouseMove(e);
    });
    canvas.addEventListener('mouseup', function() {
        draw.mouseUp();
    });

    document.getElementById('draw').addEventListener('click', function(){
    });

    document.getElementById('erase').addEventListener('click', function(){

    });
    document.getElementById('fill').addEventListener('click', function(){
        fill.call();
    });
    document.getElementById('select-area').addEventListener('click', function(){
        selectArea.call();
    });
    document.getElementById('copy').addEventListener('click', function(){
        copy.call();
    });
    document.getElementById('paste').addEventListener('click', function(){
        paste.call();
    });
    document.getElementById('load-image').addEventListener('click', function(){
        loadImage.call();
    });
});
<commit_msg>edit main.js<commit_after>define(function(require) {
    var init = require('init');

    var draw = require('./draw');
    var fill = require('./fill');
    var selectArea = require('./selectArea');
    var copy = require('./copy');
    var paste = require('./paste');
    var loadImage = require('./loadImage');

    var canvas = init.getCanvas();
    var context = init.getContext();

    // canvasに対する操作
    // draw関係
    canvas.addEventListener('mousedown', function() {
        draw.mouseDown();
    });
    canvas.addEventListener('mousemove', function(e) {
        draw.mouseMove(e);
    });
    canvas.addEventListener('mouseup', function() {
        draw.mouseUp();
    });

    //線の色を変える処理
    var colors = document.getElementById('colors').childNodes;
    for (var i = 0, color; color = colors[i]; i++) {
        if (color.nodeName.toLowerCase() != 'div') continue;
        color.addEventListener('click', function (e) {
            var style = e.target.getAttribute('style');
            var color = style.match(/background:(#......)/)[1];
            context.strokeStyle = color;
            context.fillStyle = color;
        },false);
    };

    document.getElementById('draw').addEventListener('click', function(){
    });

    document.getElementById('erase').addEventListener('click', function(){

    });
    document.getElementById('fill').addEventListener('click', function(){
        fill.call();
    });
    document.getElementById('select-area').addEventListener('click', function(){
        selectArea.call();
    });
    document.getElementById('copy').addEventListener('click', function(){
        copy.call();
    });
    document.getElementById('paste').addEventListener('click', function(){
        paste.call();
    });
    document.getElementById('load-image').addEventListener('click', function(){
        loadImage.call();
    });
});
<|endoftext|>


<commit_before>/**
 * I don't even know if we're allowed to mix Apache and MIT licesing
 * @copyright 2015 Tudor Ilisoi.  https://github.com/tudorilisoi/
 * @license MIT
 */

var fs = require('fs');
var log4js = require('log4js');
var apiLogger = log4js.getLogger("STATIC_ASSETS");
apiLogger.log = apiLogger.info;
var url = require('url');
var urlutil = require('url');
var path = require('path');
var express = require('express');
var minify = require('express-minify');
var mime = require('mime-types');

var plugins = require("ep_etherpad-lite/static/js/pluginfw/plugins");

var PACKAGE_ROOT = path.dirname(require.resolve('ep_etherpad-lite/ep.json'));
var WWW_DIR = path.normalize(PACKAGE_ROOT + '/static');
apiLogger.info(WWW_DIR);
// process.exit();
// xxzzwwwe

var compression = require('compression');
var _ = require('underscore');

var regexpTypes = {
    'PLUGIN_DEFS_JSON': new RegExp('^/pluginfw/plugin-definitions.json$'),
    'PLUGIN_ASSET': new RegExp('^/static/plugins/'),
    //for fun, not used currently
    'MINIFIED_JS': new RegExp('^/static/js/__.+\.js'),
    'JS': new RegExp('^/(static|custom)/.+\.js'),
    'CSS': new RegExp('^/(static|custom)/.+\.css'),
    'ASSET': new RegExp('^/(static|custom)/.+'),
    //back compat
    'PLUGIN_JS': new RegExp('^/static/plugins/'),
    'ACE_JS': new RegExp('^/static/js/ace\.js'), //should be dropped since it's included in bundle
    'LOOP_MODULE': new RegExp('^/javascripts'), //loop request
    'REQUIRE_KERNEL': new RegExp('^/static/js/require-kernel.js'),
};

var regexpOrder = [
    // in case you need to log or anything else

    // 'MINIFIED_JS',
    // 'JS',
    // 'CSS',
    // 'ASSET',

    'PLUGIN_DEFS_JSON',
    'PLUGIN_ASSET',
    //back compat
    'REQUIRE_KERNEL'
];

function matchURIRegex(url) {
    var u = '' + url;
    var found = null;
    _.each(regexpOrder, function (typeName) {
        if (!found && regexpTypes[typeName].test(u)) {
            found = typeName;
            // apiLogger.warn(typeName, u);
        }
    });
    return found;
}

function expressCreateServer(hook_name, args, cb) {
    var app = args.app;

    //heavy assets -> hard compression
    app.use(compression({
        level: 9
    }));

    app.use(handle);
    //NOTE regexps are for content-type, not for URIs
    app.use(minify(
        {
            js_match: /\/javascript/,
            css_match: /\/css/,
            // sass_match: /scss/,
            // less_match: /less/,
            // stylus_match: /stylus/,
            // coffee_match: /coffeescript/,
            json_match: /\/json/,
            cache: path.normalize(PACKAGE_ROOT + '/../var')
        }));
    app.use('/static', express.static(WWW_DIR));
}
;

function handle(req, res, next) {

    var type = matchURIRegex(req.url);

    // if not interesting pass it on
    if (!type && next) {
        return next && next();
    }

    apiLogger.info('PROCESS REQ', type, req.url);

    switch (type) {
        case 'PLUGIN_DEFS_JSON':
            res._skip = true;
            handlePluginDefs(req, res, next);
            break;
        case 'PLUGIN_ASSET':
            var realPath = req.url.replace('/static/plugins/', '');
            realPath = path.normalize(PACKAGE_ROOT + '/../node_modules/' + realPath);
//            console.warn(realPath);
//            res.sendFile(realPath);
//            res._skip = true;
            res.setHeader('Content-type', mime.lookup(realPath));
            var data = fs.readFileSync(realPath, {encoding: 'utf8'});
            res.end(data);

            break;

        case 'MINIFIED_JS':
            // @see https://www.npmjs.com/package/express-minify
            //works well, the 1st request yelds HTTP 200, the 2nd HTTP 304
            // res._no_minify; //no minify
            //res._no_cache // no minify cache
            res._no_cache = true;
            res._skip = true;
            return next();
            break;

        default:
            return next && next();
            break;
    }

    res.end();
}

function handlePluginDefs(req, res, next) {

    var clientParts = _(plugins.parts)
        .filter(function (part) {
            return _(part).has('client_hooks')
        });

    var clientPlugins = {};

    _(clientParts).chain()
        .map(function (part) {
            return part.plugin
        })
        .uniq()
        .each(function (name) {
            clientPlugins[name] = _(plugins.plugins[name]).clone();
            delete clientPlugins[name]['package'];
        });

    res.header("Content-Type", "application/json; charset=utf-8");
    res.write(JSON.stringify({
        "plugins": clientPlugins,
        "parts": clientParts
    }));
    // res.end();
    next();
}

function restartServer() {
    var pluginDefPath = path.normalize(PACKAGE_ROOT + '/../var/plugin-definitions.json');
    fs.writeFile(pluginDefPath, JSON.stringify({
      plugins: plugins.plugins,
      parts: plugins.parts,
      hooks: plugins.hooks,
    }, 2, 2), {
      encoding: 'utf8'
    }, function(err, ok) {
      console.debug("Wrote " + pluginDefPath);
      require(PACKAGE_ROOT + '/node/utils/minifier-ng/run')();
    });
}

exports.expressCreateServer = expressCreateServer;
exports.restartServer = restartServer;
//yes, it's correct
exports.loadSettings = restartServer;<commit_msg>static-ng honors settings.minify<commit_after>/**
 * I don't even know if we're allowed to mix Apache and MIT licesing
 * @copyright 2015 Tudor Ilisoi.  https://github.com/tudorilisoi/
 * @license MIT
 */

var fs = require('fs');
var url = require('url');
var urlutil = require('url');
var path = require('path');
var express = require('express');
var minify = require('express-minify');
var mime = require('mime-types');

var log4js = require('log4js');
var apiLogger = log4js.getLogger("STATIC_ASSETS");
apiLogger.log = apiLogger.info;

var settings = require("../../utils/Settings");
var plugins = require("ep_etherpad-lite/static/js/pluginfw/plugins");

var PACKAGE_ROOT = path.dirname(require.resolve('ep_etherpad-lite/ep.json'));
var WWW_DIR = path.normalize(PACKAGE_ROOT + '/static');
apiLogger.info(WWW_DIR);
// process.exit();
// xxzzwwwe

var compression = require('compression');
var _ = require('underscore');

var regexpTypes = {
    'PLUGIN_DEFS_JSON': new RegExp('^/pluginfw/plugin-definitions.json$'),
    'PLUGIN_ASSET': new RegExp('^/static/plugins/'),
    //for fun, not used currently
    'MINIFIED_JS': new RegExp('^/static/js/__.+\.js'),
    'JS': new RegExp('^/(static|custom)/.+\.js'),
    'CSS': new RegExp('^/(static|custom)/.+\.css'),
    'ASSET': new RegExp('^/(static|custom)/.+'),
    //back compat
    'PLUGIN_JS': new RegExp('^/static/plugins/'),
    'ACE_JS': new RegExp('^/static/js/ace\.js'), //should be dropped since it's included in bundle
    'LOOP_MODULE': new RegExp('^/javascripts'), //loop request
    'REQUIRE_KERNEL': new RegExp('^/static/js/require-kernel.js'),
};

var regexpOrder = [
    // in case you need to log or anything else

    'MINIFIED_JS',
    // 'JS',
    // 'CSS',
    // 'ASSET',

    'PLUGIN_DEFS_JSON',
    'PLUGIN_ASSET',
    //back compat
    'REQUIRE_KERNEL'
];

function matchURIRegex(url) {
    var u = '' + url;
    var found = null;
    _.each(regexpOrder, function (typeName) {
        if (!found && regexpTypes[typeName].test(u)) {
            found = typeName;
            // apiLogger.warn(typeName, u);
        }
    });
    return found;
}

function expressCreateServer(hook_name, args, cb) {
    var app = args.app;

    //heavy assets -> hard compression
    app.use(compression({
        level: 9
    }));

    app.use(handle);
    //NOTE regexps are for content-type, not for URIs
    app.use(minify(
        {
            js_match: /\/javascript/,
            css_match: /\/css/,
            // sass_match: /scss/,
            // less_match: /less/,
            // stylus_match: /stylus/,
            // coffee_match: /coffeescript/,
            json_match: /\/json/,
            cache: path.normalize(PACKAGE_ROOT + '/../var')
        }));
    app.use('/static', express.static(WWW_DIR));
}
;

function handle(req, res, next) {

    var type = matchURIRegex(req.url);

    // if not interesting pass it on
    if (!type && next) {
        return next && next();
    }

    apiLogger.info('PROCESS REQ', type, req.url);

    switch (type) {
        case 'PLUGIN_DEFS_JSON':
            res._skip = true;
            handlePluginDefs(req, res, next);
            break;
        case 'PLUGIN_ASSET':
            var realPath = req.url.replace('/static/plugins/', '');
            realPath = path.normalize(PACKAGE_ROOT + '/../node_modules/' + realPath);
//            console.warn(realPath);
//            res.sendFile(realPath);
//            res._skip = true;
            res.setHeader('Content-type', mime.lookup(realPath));
            var data = fs.readFileSync(realPath, {encoding: 'utf8'});
            res.end(data);

            break;

        case 'MINIFIED_JS':
            // @see https://www.npmjs.com/package/express-minify
            //works well, the 1st request yelds HTTP 200, the 2nd HTTP 304
            // res._no_minify; //no minify
            //res._no_cache // no minify cache
            //res._no_cache = true;
            //res._skip = true;
            if (!settings.minify) {
                res._skip = true;
                res._no_cache = true;
                res._no_minify = true;
            }

            return next();
            break;

        default:
            return next && next();
            break;
    }

    res.end();
}

function handlePluginDefs(req, res, next) {

    var clientParts = _(plugins.parts)
        .filter(function (part) {
            return _(part).has('client_hooks')
        });

    var clientPlugins = {};

    _(clientParts).chain()
        .map(function (part) {
            return part.plugin
        })
        .uniq()
        .each(function (name) {
            clientPlugins[name] = _(plugins.plugins[name]).clone();
            delete clientPlugins[name]['package'];
        });

    res.header("Content-Type", "application/json; charset=utf-8");
    res.write(JSON.stringify({
        "plugins": clientPlugins,
        "parts": clientParts
    }));
    // res.end();
    next();
}

function restartServer() {
    var pluginDefPath = path.normalize(PACKAGE_ROOT + '/../var/plugin-definitions.json');
    fs.writeFile(pluginDefPath, JSON.stringify({
        plugins: plugins.plugins,
        parts: plugins.parts,
        hooks: plugins.hooks,
    }, 2, 2), {
        encoding: 'utf8'
    }, function (err, ok) {
        console.debug("Wrote " + pluginDefPath);
        require(PACKAGE_ROOT + '/node/utils/minifier-ng/run')();
    });
}

exports.expressCreateServer = expressCreateServer;
exports.restartServer = restartServer;
//yes, it's correct
exports.loadSettings = restartServer;<|endoftext|>


<commit_before>const commonjs = require('rollup-plugin-commonjs');
const includePaths = require('rollup-plugin-includepaths');
const rollupConfig = require('../rollup.config.js');

const version = process.env.npm_package_version;

rollupConfig.plugins.push(
  commonjs(),
  includePaths({
    include: {
      'purify': 'dist/purify.js',
      'purify.min': 'dist/purify.min.js'
    }
  })
);

module.exports = function(config) {
  config.set({
    autoWatch: true,
    basePath: '../',
    frameworks: ['qunit'],
    files: [
      'node_modules/jquery/dist/jquery.js',
      'node_modules/qunit-parameterize/qunit-parameterize.js',
      'test/config/setup.js',
      'test/**/*.spec.js'
    ],

    preprocessors: {
      'src/*.js': ['rollup'],
      'test/**/*.spec.js': ['rollup']
    },

    reporters: ['progress'],

    exclude: [],
    port: 9876,

    browserStack: {
      project: 'DOMPurify',
      username: process.env.BS_USERNAME,
      accessKey: process.env.BS_ACCESSKEY
    },

    rollupPreprocessor: rollupConfig,

    customLaunchers: {
      bs_win81_ie_11: {
        base: 'BrowserStack',
        browser: 'ie',
        browser_version: '11.0',
        os: 'Windows',
        os_version: '8.1'
      },
      bs_win8_ie_10: {
        base: 'BrowserStack',
        browser: 'ie',
        browser_version: '10.0',
        os: 'Windows',
        os_version: '8'
      },
      bs_mavericks_chrome_44: {
        base: 'BrowserStack',
        device: null,
        os: 'OS X',
        browser_version: '44.0',
        browser: 'chrome',
        os_version: 'Mavericks'
      },
      bs_yosemite_firefox_40: {
        base: 'BrowserStack',
        device: null,
        os: 'OS X',
        browser_version: '40.0',
        browser: 'firefox',
        os_version: 'Yosemite'
      },
      bs_sierra_safari_10: {
        base: 'BrowserStack',
        device: null,
        os: 'OS X',
        browser_version: '10.0',
        browser: 'safari',
        os_version: 'Sierra'
      },
      bs_yosemite_safari_8: {
        base: 'BrowserStack',
        device: null,
        os: 'OS X',
        browser_version: '8.0',
        browser: 'safari',
        os_version: 'Yosemite'
      },
      bs_win81_opera_31: {
        base: 'BrowserStack',
        device: null,
        os: 'Windows',
        browser_version: '31',
        browser: 'opera',
        os_version: '8.1'
      },
      bs_win7_firefox_20: {
        base: 'BrowserStack',
        device: null,
        os: 'Windows',
        browser_version: '20.0',
        browser: 'firefox',
        os_version: '7'
      },
      bs_win7_firefox_15: {
        base: 'BrowserStack',
        device: null,
        os: 'Windows',
        browser_version: '15.0',
        browser: 'firefox',
        os_version: '7'
      },
      bs_win81_chrome_22: {
        base: 'BrowserStack',
        device: null,
        os: 'Windows',
        browser_version: '22.0',
        browser: 'chrome',
        os_version: '8.1'
      },
      bs_win10_edge_13: {
        base: 'BrowserStack',
        device: null,
        os: 'Windows',
        browser_version: '13.0',
        browser: 'edge',
        os_version: '10'
      },
      bs_win10_edge_14: {
        base: 'BrowserStack',
        device: null,
        os: 'Windows',
        browser_version: '14.0',
        browser: 'edge',
        os_version: '10'
      },
      bs_win10_firefox_46: {
        base: 'BrowserStack',
        device: null,
        os: 'Windows',
        browser_version: '46.0',
        browser: 'firefox',
        os_version: '10'
      },
      bs_win10_firefox_52: {
        base: 'BrowserStack',
        device: null,
        os: 'Windows',
        browser_version: '52.0',
        browser: 'firefox',
        os_version: '10'
      },
      bs_win10_chrome_50: {
        base: 'BrowserStack',
        device: null,
        os: 'Windows',
        browser_version: '50.0',
        browser: 'chrome',
        os_version: '10'
      },
      bs_win10_chrome_57: {
        base: 'BrowserStack',
        device: null,
        os: 'Windows',
        browser_version: '57.0',
        browser: 'chrome',
        os_version: '10'
      },
      bs_win10_chrome_59: {
        base: 'BrowserStack',
        device: null,
        os: 'Windows',
        browser_version: '59.0',
        browser: 'chrome',
        os_version: '10'
      }
    },

    browsers: [
      'bs_win81_ie_11',
      'bs_win8_ie_10',
      'bs_mavericks_chrome_44',
      'bs_yosemite_firefox_40',
      'bs_yosemite_safari_8',
      'bs_sierra_safari_10',
      'bs_win81_opera_31',
      'bs_win7_firefox_20',
      'bs_win7_firefox_15',
      'bs_win81_chrome_22',
      'bs_win10_edge_13',
      'bs_win10_edge_14',
      'bs_win10_firefox_46',
      'bs_win10_firefox_52',
      'bs_win10_chrome_50',
      'bs_win10_chrome_57',
      'bs_win10_chrome_59'
    ],

    browserDisconnectTimeout: 10000,
    browserDisconnectTolerance: 1,
    browserNoActivityTimeout: 240000,
    captureTimeout: 240000,

    plugins: [
      'karma-rollup-plugin',
      'karma-chrome-launcher',
      'karma-browserstack-launcher',
      'karma-firefox-launcher',
      'karma-qunit'
    ],

    singleRun: true,
    colors: true,
    logLevel: config.LOG_INFO
  });
};
<commit_msg>chore: configure karma-rollup<commit_after>const commonjs = require('rollup-plugin-commonjs');
const includePaths = require('rollup-plugin-includepaths');
const rollupConfig = require('../rollup.config.js');

rollupConfig.plugins.push(
  commonjs(),
  includePaths({
    include: {
      purify: 'dist/purify.js',
      'purify.min': 'dist/purify.min.js',
    },
  })
);

module.exports = function(config) {
  config.set({
    autoWatch: true,
    basePath: '../',
    frameworks: ['qunit'],
    files: [
      'node_modules/jquery/dist/jquery.js',
      'node_modules/qunit-parameterize/qunit-parameterize.js',
      'test/config/setup.js',
      'test/**/*.spec.js',
    ],

    preprocessors: {
      'src/*.js': ['rollup'],
      'test/**/*.spec.js': ['rollup'],
    },

    reporters: ['progress'],

    exclude: [],
    port: 9876,

    browserStack: {
      project: 'DOMPurify',
      username: process.env.BS_USERNAME,
      accessKey: process.env.BS_ACCESSKEY,
    },

    rollupPreprocessor: rollupConfig,

    customLaunchers: {
      bs_win81_ie_11: {
        base: 'BrowserStack',
        browser: 'ie',
        browser_version: '11.0',
        os: 'Windows',
        os_version: '8.1',
      },
      bs_win8_ie_10: {
        base: 'BrowserStack',
        browser: 'ie',
        browser_version: '10.0',
        os: 'Windows',
        os_version: '8',
      },
      bs_mavericks_chrome_44: {
        base: 'BrowserStack',
        device: null,
        os: 'OS X',
        browser_version: '44.0',
        browser: 'chrome',
        os_version: 'Mavericks',
      },
      bs_yosemite_firefox_40: {
        base: 'BrowserStack',
        device: null,
        os: 'OS X',
        browser_version: '40.0',
        browser: 'firefox',
        os_version: 'Yosemite',
      },
      bs_sierra_safari_10: {
        base: 'BrowserStack',
        device: null,
        os: 'OS X',
        browser_version: '10.0',
        browser: 'safari',
        os_version: 'Sierra',
      },
      bs_yosemite_safari_8: {
        base: 'BrowserStack',
        device: null,
        os: 'OS X',
        browser_version: '8.0',
        browser: 'safari',
        os_version: 'Yosemite',
      },
      bs_win81_opera_31: {
        base: 'BrowserStack',
        device: null,
        os: 'Windows',
        browser_version: '31',
        browser: 'opera',
        os_version: '8.1',
      },
      bs_win7_firefox_20: {
        base: 'BrowserStack',
        device: null,
        os: 'Windows',
        browser_version: '20.0',
        browser: 'firefox',
        os_version: '7',
      },
      bs_win7_firefox_15: {
        base: 'BrowserStack',
        device: null,
        os: 'Windows',
        browser_version: '15.0',
        browser: 'firefox',
        os_version: '7',
      },
      bs_win81_chrome_22: {
        base: 'BrowserStack',
        device: null,
        os: 'Windows',
        browser_version: '22.0',
        browser: 'chrome',
        os_version: '8.1',
      },
      bs_win10_edge_13: {
        base: 'BrowserStack',
        device: null,
        os: 'Windows',
        browser_version: '13.0',
        browser: 'edge',
        os_version: '10',
      },
      bs_win10_edge_14: {
        base: 'BrowserStack',
        device: null,
        os: 'Windows',
        browser_version: '14.0',
        browser: 'edge',
        os_version: '10',
      },
      bs_win10_firefox_46: {
        base: 'BrowserStack',
        device: null,
        os: 'Windows',
        browser_version: '46.0',
        browser: 'firefox',
        os_version: '10',
      },
      bs_win10_firefox_52: {
        base: 'BrowserStack',
        device: null,
        os: 'Windows',
        browser_version: '52.0',
        browser: 'firefox',
        os_version: '10',
      },
      bs_win10_chrome_50: {
        base: 'BrowserStack',
        device: null,
        os: 'Windows',
        browser_version: '50.0',
        browser: 'chrome',
        os_version: '10',
      },
      bs_win10_chrome_57: {
        base: 'BrowserStack',
        device: null,
        os: 'Windows',
        browser_version: '57.0',
        browser: 'chrome',
        os_version: '10',
      },
      bs_win10_chrome_59: {
        base: 'BrowserStack',
        device: null,
        os: 'Windows',
        browser_version: '59.0',
        browser: 'chrome',
        os_version: '10',
      },
    },

    browsers: [
      'bs_win81_ie_11',
      'bs_win8_ie_10',
      'bs_mavericks_chrome_44',
      'bs_yosemite_firefox_40',
      'bs_yosemite_safari_8',
      'bs_sierra_safari_10',
      'bs_win81_opera_31',
      'bs_win7_firefox_20',
      'bs_win7_firefox_15',
      'bs_win81_chrome_22',
      'bs_win10_edge_13',
      'bs_win10_edge_14',
      'bs_win10_firefox_46',
      'bs_win10_firefox_52',
      'bs_win10_chrome_50',
      'bs_win10_chrome_57',
      'bs_win10_chrome_59',
    ],

    browserDisconnectTimeout: 10000,
    browserDisconnectTolerance: 1,
    browserNoActivityTimeout: 240000,
    captureTimeout: 240000,

    plugins: [
      'karma-chrome-launcher',
      'karma-browserstack-launcher',
      'karma-firefox-launcher',
      'karma-qunit',
      'karma-rollup-preprocessor',
    ],

    singleRun: true,
    colors: true,
    logLevel: config.LOG_INFO,
  });
};
<|endoftext|>