<commit_before>'use strict';

const chalk = require('chalk');
const logger = require('heimdalljs-logger')('ember-cli:watcher');
const CoreObject = require('core-object');
const serveURL = require('../utilities/get-serve-url');
const printSlowTrees = require('broccoli-slow-trees');
const promiseFinally = require('promise.prototype.finally');

const eventTypeNormalization = {
  add: 'added',
  delete: 'deleted',
  change: 'changed',
};

module.exports = class Watcher extends CoreObject {
  constructor(_options) {
    super(_options);

    this.verbose = true;

    let options = this.buildOptions();

    logger.info('initialize %o', options);

    this.serving = _options.serving;

    this.watcher = this.watcher || this.constructBroccoliWatcher(options);

    this.setupBroccoliChangeEvent();
    this.watcher.on('buildStart', this._setupBroccoliWatcherBuild.bind(this));
    this.watcher.on('buildSuccess', this.didChange.bind(this));

    // build errors arriving via watcher
    this.watcher.on('buildFailure', this.didError.bind(this));
    // watcher specific errors
    this.watcher.on('error', this.didError.bind(this));

    this.serveURL = serveURL;
  }

  constructBroccoliWatcher(options) {
    const { Watcher } = require('broccoli');
    const { watchedSourceNodeWrappers } = this.builder.builder;

    let watcher = new Watcher(this.builder, watchedSourceNodeWrappers, { saneOptions: options });

    watcher.start();

    return watcher;
  }

  setupBroccoliChangeEvent() {
    // This is to keep backwards compatibility with broccoli-sane-watcher.
    // https://github.com/ember-cli/broccoli-sane-watcher/blob/48860/index.js#L158
    if (this.verbose) {
      this.watcher.on('change', (event, filePath) => {
        this.ui.writeLine(`file ${eventTypeNormalization[event]} ${filePath}`);
      });
    }
  }

  async _setupBroccoliWatcherBuild() {
    try {
      const hash = await this.watcher.currentBuild;
      hash.graph.__heimdall__.remove();
    } catch (e) {
      if (e !== null && typeof e === 'object' && e.isBuilderError === true) {
        // e must be a builder error which we can safely ignore.
        //
        // Builder errors are expected failures which are handled and presented
        // to the user else-where. To prevent double reporting faliures to the
        // user, it is important that we ignore them here as this functions
        // single responsibilty is to reset the himedall state after each build.
        //
        // exists to prune heimdall data after a build. Those errors are
        // reported elsewhere.
        //
      } else {
        // this error is unexpected, we must re-throw as we cannot be sure it
        // has been handled else-where
        throw e;
      }
    }
  }

  _totalTime(hash) {
    const sumNodes = (node, cb) => {
      let total = 0;
      node.visitPreOrder(node => {
        total += cb(node);
      });
      return total;
    };

    return sumNodes(hash.graph.__heimdall__, node => node.stats.time.self);
  }

  didError(error) {
    logger.info('didError %o', error);
    this.ui.writeError(error);
    this.analytics.trackError({
      description: error && error.name,
    });
  }

  didChange(results) {
    logger.info('didChange %o', results);

    results.totalTime = this._totalTime(results);
    let totalTime = results.totalTime / 1e6;
    let message = chalk.green(`Build successful (${Math.round(totalTime)}ms)`);

    this.ui.writeLine('');

    if (this.serving) {
      message += ` – Serving on ${this.serveURL(this.options, this.options.project)}`;
    }

    this.ui.writeLine(message);

    this.analytics.track({
      name: 'ember rebuild',
      message: `broccoli rebuild time: ${totalTime}ms`,
    });

    /*
     * We use the `rebuild` category in our analytics setup for both builds
     * and rebuilds. This is a bit confusing, but the actual thing we
     * delineate on in the reports is the `variable` value below. This is
     * used both here and in `lib/tasks/build.js`.
     */
    this.analytics.trackTiming({
      category: 'rebuild',
      variable: 'rebuild time',
      label: 'broccoli rebuild time',
      value: Number(totalTime),
    });

    if (this.verbose) {
      printSlowTrees(results.graph.__heimdall__);
    }
  }

  buildOptions() {
    let watcher = this.options && this.options.watcher;

    if (watcher && ['polling', 'watchman', 'node', 'events'].indexOf(watcher) === -1) {
      throw new Error(`Unknown watcher type --watcher=[polling|watchman|node|events] but was: ${watcher}`);
    }

    return {
      verbose: this.verbose,
      poll: watcher === 'polling',
      watchman: watcher === 'watchman' || watcher === 'events',
      node: watcher === 'node',
    };
  }

  then() {
    return this.watcher.currentBuild.then.apply(this.watcher.currentBuild, arguments);
  }

  on() {
    const args = arguments;
    if (args[0] === 'change' && !this.watchedDir) {
      args[0] = 'buildSuccess';
    }
    this.watcher.on.apply(this.watcher, args);
  }

  off() {
    const args = arguments;
    if (args[0] === 'change' && !this.watchedDir) {
      args[0] = 'buildSuccess';
    }
    this.watcher.off.apply(this.watcher, args);
  }
};
<commit_msg>Fix linting issue (bad cherry-pick).<commit_after>'use strict';

const chalk = require('chalk');
const logger = require('heimdalljs-logger')('ember-cli:watcher');
const CoreObject = require('core-object');
const serveURL = require('../utilities/get-serve-url');
const printSlowTrees = require('broccoli-slow-trees');

const eventTypeNormalization = {
  add: 'added',
  delete: 'deleted',
  change: 'changed',
};

module.exports = class Watcher extends CoreObject {
  constructor(_options) {
    super(_options);

    this.verbose = true;

    let options = this.buildOptions();

    logger.info('initialize %o', options);

    this.serving = _options.serving;

    this.watcher = this.watcher || this.constructBroccoliWatcher(options);

    this.setupBroccoliChangeEvent();
    this.watcher.on('buildStart', this._setupBroccoliWatcherBuild.bind(this));
    this.watcher.on('buildSuccess', this.didChange.bind(this));

    // build errors arriving via watcher
    this.watcher.on('buildFailure', this.didError.bind(this));
    // watcher specific errors
    this.watcher.on('error', this.didError.bind(this));

    this.serveURL = serveURL;
  }

  constructBroccoliWatcher(options) {
    const { Watcher } = require('broccoli');
    const { watchedSourceNodeWrappers } = this.builder.builder;

    let watcher = new Watcher(this.builder, watchedSourceNodeWrappers, { saneOptions: options });

    watcher.start();

    return watcher;
  }

  setupBroccoliChangeEvent() {
    // This is to keep backwards compatibility with broccoli-sane-watcher.
    // https://github.com/ember-cli/broccoli-sane-watcher/blob/48860/index.js#L158
    if (this.verbose) {
      this.watcher.on('change', (event, filePath) => {
        this.ui.writeLine(`file ${eventTypeNormalization[event]} ${filePath}`);
      });
    }
  }

  async _setupBroccoliWatcherBuild() {
    try {
      const hash = await this.watcher.currentBuild;
      hash.graph.__heimdall__.remove();
    } catch (e) {
      if (e !== null && typeof e === 'object' && e.isBuilderError === true) {
        // e must be a builder error which we can safely ignore.
        //
        // Builder errors are expected failures which are handled and presented
        // to the user else-where. To prevent double reporting faliures to the
        // user, it is important that we ignore them here as this functions
        // single responsibilty is to reset the himedall state after each build.
        //
        // exists to prune heimdall data after a build. Those errors are
        // reported elsewhere.
        //
      } else {
        // this error is unexpected, we must re-throw as we cannot be sure it
        // has been handled else-where
        throw e;
      }
    }
  }

  _totalTime(hash) {
    const sumNodes = (node, cb) => {
      let total = 0;
      node.visitPreOrder(node => {
        total += cb(node);
      });
      return total;
    };

    return sumNodes(hash.graph.__heimdall__, node => node.stats.time.self);
  }

  didError(error) {
    logger.info('didError %o', error);
    this.ui.writeError(error);
    this.analytics.trackError({
      description: error && error.name,
    });
  }

  didChange(results) {
    logger.info('didChange %o', results);

    results.totalTime = this._totalTime(results);
    let totalTime = results.totalTime / 1e6;
    let message = chalk.green(`Build successful (${Math.round(totalTime)}ms)`);

    this.ui.writeLine('');

    if (this.serving) {
      message += ` – Serving on ${this.serveURL(this.options, this.options.project)}`;
    }

    this.ui.writeLine(message);

    this.analytics.track({
      name: 'ember rebuild',
      message: `broccoli rebuild time: ${totalTime}ms`,
    });

    /*
     * We use the `rebuild` category in our analytics setup for both builds
     * and rebuilds. This is a bit confusing, but the actual thing we
     * delineate on in the reports is the `variable` value below. This is
     * used both here and in `lib/tasks/build.js`.
     */
    this.analytics.trackTiming({
      category: 'rebuild',
      variable: 'rebuild time',
      label: 'broccoli rebuild time',
      value: Number(totalTime),
    });

    if (this.verbose) {
      printSlowTrees(results.graph.__heimdall__);
    }
  }

  buildOptions() {
    let watcher = this.options && this.options.watcher;

    if (watcher && ['polling', 'watchman', 'node', 'events'].indexOf(watcher) === -1) {
      throw new Error(`Unknown watcher type --watcher=[polling|watchman|node|events] but was: ${watcher}`);
    }

    return {
      verbose: this.verbose,
      poll: watcher === 'polling',
      watchman: watcher === 'watchman' || watcher === 'events',
      node: watcher === 'node',
    };
  }

  then() {
    return this.watcher.currentBuild.then.apply(this.watcher.currentBuild, arguments);
  }

  on() {
    const args = arguments;
    if (args[0] === 'change' && !this.watchedDir) {
      args[0] = 'buildSuccess';
    }
    this.watcher.on.apply(this.watcher, args);
  }

  off() {
    const args = arguments;
    if (args[0] === 'change' && !this.watchedDir) {
      args[0] = 'buildSuccess';
    }
    this.watcher.off.apply(this.watcher, args);
  }
};
<|endoftext|>


<commit_before>import React from 'react';
// import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { signup, signin } from '../actions';

function Auth({ user, error, signin, signup }) {

  return (

      {/*
Not registered?, Sign up
*/}
      <form onSubmit={e => {
        e.preventDefault();
        const { elements } = e.target;
        const data = Object.keys(elements).reduce((obj, key) => {
          obj[key] = elements[key].value;
          return obj;
        }, {});
        signup(data);
        e.target.reset();
      }}>
        Username:<input type="text" />
        Password:<input type="text" />
        <button type="submit">Signup</button>
      </form>

  );
}

export default connect(
  state => ({
    error: state.authError,
    user: state.user
  }),
  dispatch => ({
    signup(user) { dispatch(signup(user)); },
    signin(credentials) { dispatch(signin(credentials)); }
  })
)(Auth);<commit_msg>took out redundent app folder<commit_after>import React from 'react';
// import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { signup, signin } from '../actions';

function Auth({ user, error, signin, signup }) {

  return (

Not registered?, Sign up

      <form onSubmit={e => {
        e.preventDefault();
        const { elements } = e.target;
        const data = Object.keys(elements).reduce((obj, key) => {
          obj[key] = elements[key].value;
          return obj;
        }, {});
        signup(data);
        e.target.reset();
      }}>
        Username:<input type="text" />
        Password:<input type="text" />
        <button type="submit">Signup</button>
      </form>

  );
}

export default connect(
  state => ({
    error: state.authError,
    user: state.user
  }),
  dispatch => ({
    signup(user) { dispatch(signup(user)); },
    signin(credentials) { dispatch(signin(credentials)); }
  })
)(Auth);<|endoftext|>


<commit_before>import React, { Component } from 'react'

import { fieldFilter, additiveFieldBoost, filterFieldBoost } from 'sajari'

import { default as BaseBody } from '../api-components/Body'
import { FilterFieldBoost, FieldBoost } from '../api-components'
import { ALL } from '../constants/RunModes'

class Body extends Component {
  constructor(props) {
    super(props)
    this.state = {}
  }

  shouldComponentUpdate(newProps) {
    // Don't update the component if the text doesn't satisfy the minimum length
    return newProps.text.length >= newProps.minLength
  }

  render() {
    const { text, minLength, prefixBoosts, containsBoosts, namespace } = this.props

    // Stop rendering happening on initial render if the text doesn't satisfy the minimum length
    if (text < minLength) {
      return null
    }

    const prefixBoostComponents = []
    for (let field in prefixBoosts) {
      prefixBoostComponents.push(
        <FieldBoost
          key={field}
          data={
            additiveFieldBoost(
              filterFieldBoost(
                fieldFilter(field, '^', text),
                1,
              ),
              prefixBoosts[field]
            )
          }
          namespace={namespace}
        />
      )
    }

    const containsBoostComponents = []
    for (let field in containsBoosts) {
      containsBoostComponents.push(
        <FieldBoost
          key={field}
          data={
            additiveFieldBoost(
              filterFieldBoost(
                fieldFilter(field, '~', text),
                1,
              ),
              containsBoosts[field]
            )
          }
          namespace={namespace}
        />
      )
    }

    return (

        {prefixBoostComponents}
        {containsBoostComponents}
        <BaseBody body={text} run={ALL} weight={1} namespace={namespace} />

    )
  }
}

Body.propTypes = {
  text: React.PropTypes.string.isRequired,
  minLength: React.PropTypes.number,
  prefixBoosts: React.PropTypes.object,
  containsBoosts: React.PropTypes.object,
  namespace: React.PropTypes.string,
}

Body.defaultProps = {
  text: '',
  minLength: 3,
  prefixBoosts: {},
  containsBoosts: {},
  namespace: 'default',
}

export default Body
<commit_msg>Change body run mode<commit_after>import React, { Component } from 'react'

import { fieldFilter, additiveFieldBoost, filterFieldBoost } from 'sajari'

import { default as BaseBody } from '../api-components/Body'
import { FilterFieldBoost, FieldBoost } from '../api-components'
import { MOUNT_UPDATE } from '../constants/RunModes'

class Body extends Component {
  constructor(props) {
    super(props)
    this.state = {}
  }

  shouldComponentUpdate(newProps) {
    // Don't update the component if the text doesn't satisfy the minimum length
    return newProps.text.length >= newProps.minLength
  }

  render() {
    const { text, minLength, prefixBoosts, containsBoosts, namespace } = this.props

    // Stop rendering happening on initial render if the text doesn't satisfy the minimum length
    if (text < minLength) {
      return null
    }

    const prefixBoostComponents = []
    for (let field in prefixBoosts) {
      prefixBoostComponents.push(
        <FieldBoost
          key={field}
          data={
            additiveFieldBoost(
              filterFieldBoost(
                fieldFilter(field, '^', text),
                1,
              ),
              prefixBoosts[field]
            )
          }
          namespace={namespace}
        />
      )
    }

    const containsBoostComponents = []
    for (let field in containsBoosts) {
      containsBoostComponents.push(
        <FieldBoost
          key={field}
          data={
            additiveFieldBoost(
              filterFieldBoost(
                fieldFilter(field, '~', text),
                1,
              ),
              containsBoosts[field]
            )
          }
          namespace={namespace}
        />
      )
    }

    return (

        {prefixBoostComponents}
        {containsBoostComponents}
        <BaseBody body={text} run={MOUNT_UPDATE} weight={1} namespace={namespace} />

    )
  }
}

Body.propTypes = {
  text: React.PropTypes.string.isRequired,
  minLength: React.PropTypes.number,
  prefixBoosts: React.PropTypes.object,
  containsBoosts: React.PropTypes.object,
  namespace: React.PropTypes.string,
}

Body.defaultProps = {
  text: '',
  minLength: 3,
  prefixBoosts: {},
  containsBoosts: {},
  namespace: 'default',
}

export default Body
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Link } from 'react-router';

export default class Cart extends Component {

  constructor(props) {
    super(props);
    this.removeProductFromCart = this.removeProductFromCart.bind(this);
    this.changeCount = this.changeCount.bind(this);
  }

  removeProductFromCart(lineItem) {
    this.props.removeProductFromCart(lineItem.getIn(['product', 'id']));
  }

  changeCount(e, productId) {
    this.props.changeProductCount(productId, Number(e.target.value));
  }

  render() {
    const lineItems = this.props.cart.get('lineItems');
    const total = this.props.cart.get('total');

    return (

Shopping Cart{' '}
            {total}$

          {
            lineItems.map((lineItem, i) => {
              const product = lineItem.get('product');

              return (

                    {product.get('title')}
                    <input type="number" className="form-control" min="1" step="1" value={lineItem.get('count')}
                      onChange={ (e) => this.changeCount(e, product.get('id')) }
                    />

                      <button className="btn btn-default" onClick={(e) => this.removeProductFromCart(lineItem)}>

                      </button>

              );
            })
          }

              <Link to={'/checkout'} className="btn btn-default">Checkout</Link>

              <button className="btn btn-default" onClick={this.props.clearCart}>Empty</button>

    );
  }
}
<commit_msg>Improve cart<commit_after>import React, { Component } from 'react';
import { Link } from 'react-router';

export default class Cart extends Component {

  constructor(props) {
    super(props);
    this.removeProductFromCart = this.removeProductFromCart.bind(this);
    this.changeCount = this.changeCount.bind(this);
  }

  removeProductFromCart(lineItem) {
    this.props.removeProductFromCart(lineItem.getIn(['product', 'id']));
  }

  changeCount(e, productId) {
    this.props.changeProductCount(productId, Number(e.target.value));
  }

  render() {
    const lineItems = this.props.cart.get('lineItems');
    const total = this.props.cart.get('total');
    let template = null;

    if (lineItems.size !== 0) {
      template = (

Shopping Cart{' '}
              {total}$

            {
              lineItems.map((lineItem, i) => {
                const product = lineItem.get('product');

                return (

                      {product.get('title')}
                      <input type="number" className="form-control" min="1" step="1" value={lineItem.get('count')}
                        onChange={ (e) => this.changeCount(e, product.get('id')) }
                      />

                        <button className="btn btn-default" onClick={(e) => this.removeProductFromCart(lineItem)}>

                        </button>

                );
              })
            }

                <Link to={'/checkout'} className="btn btn-default">Checkout</Link>

                <button className="btn btn-default" onClick={this.props.clearCart}>Empty</button>

      );
    } else {
      template = (

You cart is empty :(

      );
    }

    return template;
  }
}
<|endoftext|>


<commit_before>import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { connect } from 'react-redux';
import { cardMoved } from '../actions';
import Card from './Card';
import { CARD_SUITS } from '../CardTypes';

class Goal extends React.Component {
  getGoalSlot(slot, lane) {
    console.log(slot);
    if (slot.topCard === null) {
      return (
        <View key={slot.id} style={{ flex: 1 }} />
      );
    }
    return (
      <View key={slot.id} style={{ flex: 1 }}>
        <Card
          key={ slot.topCard.id }
          cardMoved={ this.props.cardMoved }
          cardId={ slot.topCard.id }
          value={ slot.topCard.value }
          suit={ slot.topCard.suit }
          color={ slot.topCard.color }
          shown={ true }
          draggable={ false }
          flex={ true }
        />
      </View>
    );
  }

  render() {
    let slots = CARD_SUITS.map((suit) => {
      return this.props.goal[suit];
    });
    return (
      <View style={ styles.container }>
        {
          [].concat(...slots).map(this.getGoalSlot, this)
        }
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 8,
    backgroundColor: 'blue',
    top: 20,
    height: 50,
    justifyContent: 'space-around',
    flexDirection: 'row'
  }
});

// ownProps IS this.props
// if now key is passed, variable name is used as key
const mapStateToProps = (state, ownProps) => {
  const { goal } = state.board;
  return { goal };
};

export default connect(mapStateToProps, { cardMoved })(Goal);
<commit_msg>Remove a logging statement<commit_after>import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { connect } from 'react-redux';
import { cardMoved } from '../actions';
import Card from './Card';
import { CARD_SUITS } from '../CardTypes';

class Goal extends React.Component {
  getGoalSlot(slot, lane) {
    if (slot.topCard === null) {
      return (
        <View key={slot.id} style={{ flex: 1 }} />
      );
    }
    return (
      <View key={slot.id} style={{ flex: 1 }}>
        <Card
          key={ slot.topCard.id }
          cardMoved={ this.props.cardMoved }
          cardId={ slot.topCard.id }
          value={ slot.topCard.value }
          suit={ slot.topCard.suit }
          color={ slot.topCard.color }
          shown={ true }
          draggable={ false }
          flex={ true }
        />
      </View>
    );
  }

  render() {
    let slots = CARD_SUITS.map((suit) => {
      return this.props.goal[suit];
    });
    return (
      <View style={ styles.container }>
        {
          [].concat(...slots).map(this.getGoalSlot, this)
        }
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 8,
    backgroundColor: 'blue',
    top: 20,
    height: 50,
    justifyContent: 'space-around',
    flexDirection: 'row'
  }
});

// ownProps IS this.props
// if now key is passed, variable name is used as key
const mapStateToProps = (state, ownProps) => {
  const { goal } = state.board;
  return { goal };
};

export default connect(mapStateToProps, { cardMoved })(Goal);
<|endoftext|>


<commit_before>import React from 'react';

THREE.ImageUtils.crossOrigin = '';

const Events = require('../lib/Events.js');
import ComponentsSidebar from './components/Sidebar';
import ModalTextures from './modals/ModalTextures';
import ModalHelp from './modals/ModalHelp';
import SceneGraph from './scenegraph/SceneGraph';
import TransformToolBar from './viewport/TransformToolBar';
import ViewportHUD from './viewport/ViewportHUD';
import {injectCSS} from '../lib/utils';

// Megahack to include font-awesome.
injectCSS('https://use.fontawesome.com/releases/v5.5.0/css/all.css');
injectCSS('https://fonts.googleapis.com/css?family=Roboto:400,300,500');

export default class Main extends React.Component {
  constructor (props) {
    super(props);

    this.state = {
      entity: null,
      inspectorEnabled: true,
      isModalTexturesOpen: false,
      sceneEl: AFRAME.scenes[0],
      visible: {
        scenegraph: true,
        attributes: true
      }
    };

    Events.on('togglesidebar', event => {
      if (event.which === 'all') {
        if (this.state.visible.scenegraph || this.state.visible.attributes) {
          this.setState({
            visible: {
              scenegraph: false,
              attributes: false
            }
          });
        } else {
          this.setState({
            visible: {
              scenegraph: true,
              attributes: true
            }
          });
        }
      } else if (event.which === 'attributes') {
        this.setState((prevState) => ({
          visible: {
            attributes: !prevState.visible.attributes
          }
        }));
      } else if (event.which === 'scenegraph') {
        this.setState((prevState) => ({
          visible: {
            scenegraph: !prevState.visible.scenegraph
          }
        }));
      }

      this.forceUpdate();
    });
  }

  componentDidMount () {
    // Create an observer to notify the changes in the scene
    var observer = new MutationObserver(function (mutations) {
      Events.emit('dommodify', mutations);
    });
    var config = {attributes: true, childList: true, characterData: true};
    observer.observe(this.state.sceneEl, config);

    Events.on('opentexturesmodal', function (selectedTexture, textureOnClose) {
      this.setState({selectedTexture: selectedTexture, isModalTexturesOpen: true, textureOnClose: textureOnClose});
    }.bind(this));

    Events.on('entityselect', entity => {
      this.setState({entity: entity});
    });

    Events.on('inspectortoggle', enabled => {
      this.setState({inspectorEnabled: enabled});
    });

    Events.on('openhelpmodal', () => {
      this.setState({isHelpOpen: true});
    });
  }

  onCloseHelpModal = value => {
    this.setState({isHelpOpen: false});
  }

  onModalTextureOnClose = value => {
    this.setState({isModalTexturesOpen: false});
    if (this.state.textureOnClose) {
      this.state.textureOnClose(value);
    }
  }
/*
  openModal = () => {
    this.setState({isModalTexturesOpen: true});
  }
*/
  toggleEdit = () => {
    if (this.state.inspectorEnabled) {
      AFRAME.INSPECTOR.close();
    } else {
      AFRAME.INSPECTOR.open();
    }
  }

  render () {
    var scene = this.state.sceneEl;
    const showScenegraph = this.state.visible.scenegraph ? null :
 { this.setState({visible: {scenegraph: true}}); this.forceUpdate(); }} className='fa fa-plus' title='Show scenegraph'>
;
    const showAttributes = !this.state.entity || this.state.visible.attributes ? null :
 { this.setState({visible: {attributes: true}}); this.forceUpdate(); }} className='fa fa-plus' title='Show components'>
;

    let toggleButtonText = 'Inspect Scene';
    if (this.state.inspectorEnabled) {
      toggleButtonText = 'Back to Scene';
    }

    return (

        {toggleButtonText}

          <ModalTextures ref='modaltextures' isOpen={this.state.isModalTexturesOpen} selectedTexture={this.state.selectedTexture} onClose={this.onModalTextureOnClose}/>
          <SceneGraph id='left-sidebar' scene={scene} selectedEntity={this.state.entity} visible={this.state.visible.scenegraph}/>
          {showScenegraph}
          {showAttributes}

            <ViewportHUD/>
            <TransformToolBar/>
            <ComponentsSidebar entity={this.state.entity} visible={this.state.visible.attributes}/>

        <ModalHelp isOpen={this.state.isHelpOpen} onClose={this.onCloseHelpModal}/>

    );
  }
}
<commit_msg>remove global mutation observer<commit_after>import React from 'react';

THREE.ImageUtils.crossOrigin = '';

const Events = require('../lib/Events.js');
import ComponentsSidebar from './components/Sidebar';
import ModalTextures from './modals/ModalTextures';
import ModalHelp from './modals/ModalHelp';
import SceneGraph from './scenegraph/SceneGraph';
import TransformToolBar from './viewport/TransformToolBar';
import ViewportHUD from './viewport/ViewportHUD';
import {injectCSS} from '../lib/utils';

// Megahack to include font-awesome.
injectCSS('https://use.fontawesome.com/releases/v5.5.0/css/all.css');
injectCSS('https://fonts.googleapis.com/css?family=Roboto:400,300,500');

export default class Main extends React.Component {
  constructor (props) {
    super(props);

    this.state = {
      entity: null,
      inspectorEnabled: true,
      isModalTexturesOpen: false,
      sceneEl: AFRAME.scenes[0],
      visible: {
        scenegraph: true,
        attributes: true
      }
    };

    Events.on('togglesidebar', event => {
      if (event.which === 'all') {
        if (this.state.visible.scenegraph || this.state.visible.attributes) {
          this.setState({
            visible: {
              scenegraph: false,
              attributes: false
            }
          });
        } else {
          this.setState({
            visible: {
              scenegraph: true,
              attributes: true
            }
          });
        }
      } else if (event.which === 'attributes') {
        this.setState((prevState) => ({
          visible: {
            attributes: !prevState.visible.attributes
          }
        }));
      } else if (event.which === 'scenegraph') {
        this.setState((prevState) => ({
          visible: {
            scenegraph: !prevState.visible.scenegraph
          }
        }));
      }

      this.forceUpdate();
    });
  }

  componentDidMount () {
    Events.on('opentexturesmodal', function (selectedTexture, textureOnClose) {
      this.setState({selectedTexture: selectedTexture, isModalTexturesOpen: true, textureOnClose: textureOnClose});
    }.bind(this));

    Events.on('entityselect', entity => {
      this.setState({entity: entity});
    });

    Events.on('inspectortoggle', enabled => {
      this.setState({inspectorEnabled: enabled});
    });

    Events.on('openhelpmodal', () => {
      this.setState({isHelpOpen: true});
    });
  }

  onCloseHelpModal = value => {
    this.setState({isHelpOpen: false});
  }

  onModalTextureOnClose = value => {
    this.setState({isModalTexturesOpen: false});
    if (this.state.textureOnClose) {
      this.state.textureOnClose(value);
    }
  }
/*
  openModal = () => {
    this.setState({isModalTexturesOpen: true});
  }
*/
  toggleEdit = () => {
    if (this.state.inspectorEnabled) {
      AFRAME.INSPECTOR.close();
    } else {
      AFRAME.INSPECTOR.open();
    }
  }

  render () {
    var scene = this.state.sceneEl;
    const showScenegraph = this.state.visible.scenegraph ? null :
 { this.setState({visible: {scenegraph: true}}); this.forceUpdate(); }} className='fa fa-plus' title='Show scenegraph'>
;
    const showAttributes = !this.state.entity || this.state.visible.attributes ? null :
 { this.setState({visible: {attributes: true}}); this.forceUpdate(); }} className='fa fa-plus' title='Show components'>
;

    let toggleButtonText = 'Inspect Scene';
    if (this.state.inspectorEnabled) {
      toggleButtonText = 'Back to Scene';
    }

    return (

        {toggleButtonText}

          <ModalTextures ref='modaltextures' isOpen={this.state.isModalTexturesOpen} selectedTexture={this.state.selectedTexture} onClose={this.onModalTextureOnClose}/>
          <SceneGraph id='left-sidebar' scene={scene} selectedEntity={this.state.entity} visible={this.state.visible.scenegraph}/>
          {showScenegraph}
          {showAttributes}

            <ViewportHUD/>
            <TransformToolBar/>
            <ComponentsSidebar entity={this.state.entity} visible={this.state.visible.attributes}/>

        <ModalHelp isOpen={this.state.isHelpOpen} onClose={this.onCloseHelpModal}/>

    );
  }
}
<|endoftext|>


<commit_before>//require('normalize.css/normalize.css');
require('styles/App.scss');

import React from 'react';
//import {findDOMNode} from 'react-dom';
//var ReactDOM = require('react-dom');
import {findDOMNode} from 'react-dom';

//get all the image data
let imageDatas = require('../data/image.json');

//convert image name into image url
function getImageURL(imageDatasArr) {
    for (var i = 0, j = imageDatasArr.length; i < j; i++) {
        var singleImageData = imageDatasArr[i];
		//require('../XXX'+fileNmae) can get the image url
        singleImageData.imageURL = require('../images/' + singleImageData.fileName);

        imageDatasArr[i] = singleImageData;
    }

    return imageDatasArr;
}

//convert all the image name into image url
imageDatas = getImageURL(imageDatas);

//get the random value in a given range
function getRangeRandom(low, high) {
    return Math.ceil(Math.random() * (high - low) + low);
}

/*
 * Get 0-30 degree(neg & pos)
 */
function get30DegRandom(){
	return ((Math.random() > 0.5 ? '' : '-') + Math.ceil(Math.random() * 30));

}

var ImgFigure = React.createClass({
	/*
     * handle the click imgFigure event
     */
    handleClick: function (e) {

      if (this.props.arrange.isCenter) {
        this.props.inverse();
      } else {
        this.props.center();
      }

      e.stopPropagation();
      e.preventDefault();
    },

	render:function(){
		var styleObj = {};

        //If there is position value in props for this image
        if (this.props.arrange.pos) {
            styleObj = this.props.arrange.pos;
        }

		//If image contains rotate degree which is not 0, the degree will be added
		if (this.props.arrange.rotate) {
          (['MozTransform', 'msTransform', 'WebkitTransform', 'transform']).forEach(function (value) {
            styleObj[value] = 'rotate(' + this.props.arrange.rotate + 'deg)';
          }.bind(this));
        }

		if(this.props.arrange.isCenter){
			styleObj.zIndex = 11;
		}

		var imgFigureClassName = 'img-figure';
		var imgFigureClassName = 'img-figure';
		    imgFigureClassName += this.props.arrange.isInverse ? ' is-inverse' : '';

		return(

{this.props.data.title}

                        {this.props.data.desc}

		)

	}
});

var AppComponent = React.createClass( {
  Constant:{
	centerPos:{
	  left:0,
	  right:0
	},
	//horizontal range
	hPosRange:{
	  leftSecX: [0,0],
	  rightSecX: [0,0],
	  y: [0,0]
	},
	//vertical range
	vPosRange:{
	  x: [0,0],
	  topY: [0,0]
	}
  },

  /*
   * Inverse image
   * @para index: current inverse image index
   * @return {Function} 闭包函数，a real function which wait to be excuted
   */
  inverse: function (index) {
    return function () {
      var imgsArrangeArr = this.state.imgsArrangeArr;

      imgsArrangeArr[index].isInverse = !imgsArrangeArr[index].isInverse;

      this.setState({
        imgsArrangeArr: imgsArrangeArr
      });
    }.bind(this);
  },

  /*
   * rearrange all the images
   * @param centerIndex: point out which image is in center
   */
  rearrange: function(centerIndex){
    var imgsArrangeArr = this.state.imgsArrangeArr,
        Constant = this.Constant,
        centerPos = Constant.centerPos,
        hPosRange = Constant.hPosRange,
        vPosRange = Constant.vPosRange,
        hPosRangeLeftSecX = hPosRange.leftSecX,
        hPosRangeRightSecX = hPosRange.rightSecX,
        hPosRangeY = hPosRange.y,
        vPosRangeTopY = vPosRange.topY,
        vPosRangeX = vPosRange.x,

		imgsArrangeTopArr = [],

        topImgNum = Math.floor(Math.random() * 2),    /* 0-1 */

        topImgSpliceIndex = 0,  /*the splice index for the image array which is shown at top*/

		imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex, 1);

		//align the centerIndex image, no rotate */
        imgsArrangeCenterArr[0] = {
			pos:centerPos,
			rotate: 0,
			isCenter: true
		};

		/* get the image status in the top section */
        topImgSpliceIndex = Math.ceil(Math.random() * (imgsArrangeArr.length - topImgNum));
        imgsArrangeTopArr = imgsArrangeArr.splice(topImgSpliceIndex, topImgNum);

		/* arrange images at the TOP section */
        imgsArrangeTopArr.forEach(function (value, index) {
            imgsArrangeTopArr[index]= {
              pos:{
                  top: getRangeRandom(vPosRangeTopY[0], vPosRangeTopY[1]),
                  left: getRangeRandom(vPosRangeX[0], vPosRangeX[1])
              },
			  rotate: get30DegRandom(),
			  isCenter: false
            };
        });

		/* images in LEFT & RIGHT sections */
        for (var i = 0, j = imgsArrangeArr.length, k = j / 2; i < j; i++) {
            var hPosRangeLORX = null;

            /* 前半部分布局左边， 右半部分布局右边 */
            if (i < k) {
                hPosRangeLORX = hPosRangeLeftSecX;
            } else {
                hPosRangeLORX = hPosRangeRightSecX;
            }

            imgsArrangeArr[i]={
			  pos:{
                top: getRangeRandom(hPosRangeY[0],hPosRangeY[1]),
                left: getRangeRandom(hPosRangeLORX[0],hPosRangeLORX[1])
			  },
			  rotate: get30DegRandom(),
			  isCenter: false
            };

        }

		if (imgsArrangeTopArr && imgsArrangeTopArr[0]) {
            imgsArrangeArr.splice(topImgSpliceIndex, 0, imgsArrangeTopArr[0]);
        }

        imgsArrangeArr.splice(centerIndex, 0, imgsArrangeCenterArr[0]);

        this.setState({
            imgsArrangeArr: imgsArrangeArr
        });
  },

  /*
   * Center the image by using arrange function
   * @param index, the index of the image which is waiting to be centred
   * @returns {Function}
   */
  center: function (index) {
    return function () {
      this.rearrange(index);
    }.bind(this);
  },

  getInitialState: function () {
    return {
        imgsArrangeArr: [
            /*{
                pos: {
                    left: '0',
                    top: '0'
                },
                rotate: 0,    // 旋转角度
                isInverse: false,    // 图片正反面
                isCenter: false,    // 图片是否居中
            }*/
        ]
    };
  },

  getInitialState:function(){
	return{
	  imgsArrangeArr:[
		{
			/*
			pos:{
				left:'0',
				top:'0'
			},
			rotate: 0,
			isInverse: false,
			isCenter: false
			*/
		}
	  ]
	};
  },

  /* calculate each image's positions range */
  componentDidMount:function(){

    /* get stage size */
    var stageDOM = findDOMNode(this.refs.stage),
	    stageW = stageDOM.scrollWidth,
		stageH = stageDOM.scrollHeight,
		halfStageW = Math.ceil(stageW/2),
		halfStageH = Math.ceil(stageH/2);

	/* get imageFigure size */
    var imgFigureDOM = findDOMNode(this.refs.imgFigure0),
	    imgW = imgFigureDOM.scrollWidth,
		imgH = imgFigureDOM.scrollHeight,
		halfImgW = Math.ceil(imgW/2),
        halfImgH = Math.ceil(imgH/2);

    /* calculate centre-image position	*/
	this.Constant.centerPos={
		left:halfStageW - halfImgW,
		top: halfStageH - halfImgH
	};

	/* calculate the image range in the left section & right section*/
	this.Constant.hPosRange.leftSecX[0] = -halfImgW;
	this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3;
	this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImgW;
    this.Constant.hPosRange.rightSecX[1] = stageW - halfImgW;
    this.Constant.hPosRange.y[0] = -halfImgH;
    this.Constant.hPosRange.y[1] = stageH - halfImgH;

	/* calculate the image range in the top section */
	this.Constant.vPosRange.topY[0] = -halfImgH;
    this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3;
    this.Constant.vPosRange.x[0] = halfStageW - imgW;
    this.Constant.vPosRange.x[1] = halfStageW;

	this.rearrange(0);
  },

  render(){

    var controllerUnits = [],
	    imgFigures = [];

	imageDatas.forEach(function(value,index){

		if (!this.state.imgsArrangeArr[index]) {
            this.state.imgsArrangeArr[index] = {
			    pos:{
					top: 0,
					left: 0
				},
				rotate:0,
				isInverse: false,
				isCenter: false
            };
        }

		imgFigures.push(<ImgFigure key={index} data={value} ref={'imgFigure'+index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)}/>);
	}.bind(this));

    return (

			{imgFigures}

			{controllerUnits}

    );
  }
})

AppComponent.defaultProps = {
};

export default AppComponent;
<commit_msg>update details<commit_after>//require('normalize.css/normalize.css');
require('styles/App.scss');

import React from 'react';
//import {findDOMNode} from 'react-dom';
//var ReactDOM = require('react-dom');
import {findDOMNode} from 'react-dom';

//get all the image data
let imageDatas = require('../data/image.json');

//convert image name into image url
function getImageURL(imageDatasArr) {
    for (var i = 0, j = imageDatasArr.length; i < j; i++) {
        var singleImageData = imageDatasArr[i];
		//require('../XXX'+fileNmae) can get the image url
        singleImageData.imageURL = require('../images/' + singleImageData.fileName);

        imageDatasArr[i] = singleImageData;
    }

    return imageDatasArr;
}

//convert all the image name into image url
imageDatas = getImageURL(imageDatas);

//get the random value in a given range
function getRangeRandom(low, high) {
    return Math.ceil(Math.random() * (high - low) + low);
}

/*
 * Get 0-30 degree(neg & pos)
 */
function get30DegRandom(){
	return ((Math.random() > 0.5 ? '' : '-') + Math.ceil(Math.random() * 30));

}

var ImgFigure = React.createClass({
	/*
     * handle the click imgFigure event
     */
    handleClick: function (e) {

      if (this.props.arrange.isCenter) {
        this.props.inverse();
      } else {
        this.props.center();
      }

      e.stopPropagation();
      e.preventDefault();
    },

	render:function(){
		var styleObj = {};

        //If there is position value in props for this image
        if (this.props.arrange.pos) {
            styleObj = this.props.arrange.pos;
        }

		//If image contains rotate degree which is not 0, the degree will be added
		if (this.props.arrange.rotate) {
          (['MozTransform', 'msTransform', 'WebkitTransform', 'transform']).forEach(function (value) {
            styleObj[value] = 'rotate(' + this.props.arrange.rotate + 'deg)';
          }.bind(this));
        }

		if(this.props.arrange.isCenter){
			styleObj.zIndex = 11;
		}

		var imgFigureClassName = 'img-figure';
		var imgFigureClassName = 'img-figure';
		    imgFigureClassName += this.props.arrange.isInverse ? ' is-inverse' : '';

		return(

{this.props.data.title}

                        {this.props.data.desc}

		)

	}
});

var AppComponent = React.createClass( {
  Constant:{
	centerPos:{
	  left:0,
	  right:0
	},
	//horizontal range
	hPosRange:{
	  leftSecX: [0,0],
	  rightSecX: [0,0],
	  y: [0,0]
	},
	//vertical range
	vPosRange:{
	  x: [0,0],
	  topY: [0,0]
	}
  },

  /*
   * Inverse image
   * @para index: current inverse image index
   * @return {Function} Closure,a real function which wait to be executed
   */
  inverse: function (index) {
    return function () {
      var imgsArrangeArr = this.state.imgsArrangeArr;

      imgsArrangeArr[index].isInverse = !imgsArrangeArr[index].isInverse;

      this.setState({
        imgsArrangeArr: imgsArrangeArr
      });
    }.bind(this);
  },

  /*
   * rearrange all the images
   * @param centerIndex: point out which image is in center
   */
  rearrange: function(centerIndex){
    var imgsArrangeArr = this.state.imgsArrangeArr,
        Constant = this.Constant,
        centerPos = Constant.centerPos,
        hPosRange = Constant.hPosRange,
        vPosRange = Constant.vPosRange,
        hPosRangeLeftSecX = hPosRange.leftSecX,
        hPosRangeRightSecX = hPosRange.rightSecX,
        hPosRangeY = hPosRange.y,
        vPosRangeTopY = vPosRange.topY,
        vPosRangeX = vPosRange.x,

		imgsArrangeTopArr = [],

        topImgNum = Math.floor(Math.random() * 2),    /* 0-1 */

        topImgSpliceIndex = 0,  /*the splice index for the image array which is shown at top*/

		imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex, 1);

		//align the centerIndex image, no rotate */
        imgsArrangeCenterArr[0] = {
			pos:centerPos,
			rotate: 0,
			isCenter: true
		};

		/* get the image status in the top section */
        topImgSpliceIndex = Math.ceil(Math.random() * (imgsArrangeArr.length - topImgNum));
        imgsArrangeTopArr = imgsArrangeArr.splice(topImgSpliceIndex, topImgNum);

		/* arrange images at the TOP section */
        imgsArrangeTopArr.forEach(function (value, index) {
            imgsArrangeTopArr[index]= {
              pos:{
                  top: getRangeRandom(vPosRangeTopY[0], vPosRangeTopY[1]),
                  left: getRangeRandom(vPosRangeX[0], vPosRangeX[1])
              },
			  rotate: get30DegRandom(),
			  isCenter: false
            };
        });

		/* images in LEFT & RIGHT sections */
        for (var i = 0, j = imgsArrangeArr.length, k = j / 2; i < j; i++) {
            var hPosRangeLORX = null;

            /* 前半部分布局左边， 右半部分布局右边 */
            if (i < k) {
                hPosRangeLORX = hPosRangeLeftSecX;
            } else {
                hPosRangeLORX = hPosRangeRightSecX;
            }

            imgsArrangeArr[i]={
			  pos:{
                top: getRangeRandom(hPosRangeY[0],hPosRangeY[1]),
                left: getRangeRandom(hPosRangeLORX[0],hPosRangeLORX[1])
			  },
			  rotate: get30DegRandom(),
			  isCenter: false
            };

        }

		if (imgsArrangeTopArr && imgsArrangeTopArr[0]) {
            imgsArrangeArr.splice(topImgSpliceIndex, 0, imgsArrangeTopArr[0]);
        }

        imgsArrangeArr.splice(centerIndex, 0, imgsArrangeCenterArr[0]);

        this.setState({
            imgsArrangeArr: imgsArrangeArr
        });
  },

  /*
   * Center the image by using arrange function
   * @param index, the index of the image which is waiting to be centred
   * @returns {Function}
   */
  center: function (index) {
    return function () {
      this.rearrange(index);
    }.bind(this);
  },

  getInitialState: function () {
    return {
        imgsArrangeArr: [
            /*{
                pos: {
                    left: '0',
                    top: '0'
                },
                rotate: 0,    // 旋转角度
                isInverse: false,    // 图片正反面
                isCenter: false,    // 图片是否居中
            }*/
        ]
    };
  },

  getInitialState:function(){
	return{
	  imgsArrangeArr:[
		{
			/*
			pos:{
				left:'0',
				top:'0'
			},
			rotate: 0,
			isInverse: false,
			isCenter: false
			*/
		}
	  ]
	};
  },

  /* calculate each image's positions range */
  componentDidMount:function(){

    /* get stage size */
    var stageDOM = findDOMNode(this.refs.stage),
	    stageW = stageDOM.scrollWidth,
		stageH = stageDOM.scrollHeight,
		halfStageW = Math.ceil(stageW/2),
		halfStageH = Math.ceil(stageH/2);

	/* get imageFigure size */
    var imgFigureDOM = findDOMNode(this.refs.imgFigure0),
	    imgW = imgFigureDOM.scrollWidth,
		imgH = imgFigureDOM.scrollHeight,
		halfImgW = Math.ceil(imgW/2),
        halfImgH = Math.ceil(imgH/2);

    /* calculate centre-image position	*/
	this.Constant.centerPos={
		left:halfStageW - halfImgW,
		top: halfStageH - halfImgH
	};

	/* calculate the image range in the left section & right section*/
	this.Constant.hPosRange.leftSecX[0] = -halfImgW;
	this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3;
	this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImgW;
    this.Constant.hPosRange.rightSecX[1] = stageW - halfImgW;
    this.Constant.hPosRange.y[0] = -halfImgH;
    this.Constant.hPosRange.y[1] = stageH - halfImgH;

	/* calculate the image range in the top section */
	this.Constant.vPosRange.topY[0] = -halfImgH;
    this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3;
    this.Constant.vPosRange.x[0] = halfStageW - imgW;
    this.Constant.vPosRange.x[1] = halfStageW;

	this.rearrange(0);
  },

  render(){

    var controllerUnits = [],
	    imgFigures = [];

	imageDatas.forEach(function(value,index){

		if (!this.state.imgsArrangeArr[index]) {
            this.state.imgsArrangeArr[index] = {
			    pos:{
					top: 0,
					left: 0
				},
				rotate:0,
				isInverse: false,
				isCenter: false
            };
        }

		imgFigures.push(<ImgFigure key={index} data={value} ref={'imgFigure'+index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)}/>);
	}.bind(this));

    return (

			{imgFigures}

			{controllerUnits}

    );
  }
})

AppComponent.defaultProps = {
};

export default AppComponent;
<|endoftext|>


<commit_before>var dashboardGraphs = ['updateBuildModel', 'updateWTFModel', 'updateHydrationModel', 'updateCaffeineModel', 'updateBuildDurationModel', 'updateHourlyBuildHeatMap', 'updateHourlyWtfHeatMap', 'updateHourlyHydrationHeatMap', 'updateHourlyCaffeineHeatMap', 'updateActiveEvents', 'updateHourlyGithubPushHeatMap', 'updateCorrelationData'];

$("#builds-x").ready(function() {
    window.qd.registerForBuildModelUpdates(function() {
        var displayBuildCountAndBuildComparison = function(buildCount, buildCountElementId, comparisonValue, comparisonElementId) {
            $(buildCountElementId).text(buildCount);
            var buildComparison = Math.abs(comparisonValue);
            if (buildComparison && buildComparison !== Infinity) {
                $(comparisonElementId).text(buildComparison + "%");
                if (comparisonValue < 0) {
                    $(comparisonElementId).addClass("icon-caret-down");
                } else if (comparisonValue > 0) {
                    $(comparisonElementId).addClass("icon-caret-up");
                }
            }
        };

        displayBuildCountAndBuildComparison(window.qd.todaysTotalBuildCount, "#builds-x", window.qd.totalBuildComparison, "#total-build-comparison");
        displayBuildCountAndBuildComparison(window.qd.todaysPassedBuildCount, "#passed-x", window.qd.passedBuildComparison, "#passed-build-comparison");
        displayBuildCountAndBuildComparison(window.qd.todaysFailedBuildCount, "#failed-x", window.qd.failedBuildComparison, "#failed-build-comparison");
    });
});

$(window).resize(function() {
    window.qd.replotGraphs();
});

$(window).load(function() {
    //does not work in document.ready()
    if ($("#showOverlayFlag").attr("showOverlay") == 'true') {
        $("#connect_to_github_btn").show();
        $("#noDataSourceMessage").modal("show")
    } else {
        window.qd.plotGraphs(dashboardGraphs);
    }
});

$('#last-updated-since').html("Last Updated: " + moment(window.localStorage.lastUpdatedOn).fromNow());

var handleConnectToGithub = function() {
    var button = $("#github-push-events-sync");
    $('#noDataSourceMessage').modal('hide');

    var showGitHubEvents = function(data) {
        var hourlyGithubErrorCallback = function() {
            alert("Github events error");
        };
        var hourlyGithubSuccessCallback = function(hourlyGithubPushEvents) {
            button.prop("disabled", false);
            $('#last-updated-since').html("");
            window.localStorage.lastUpdatedOn = new Date();
            $('#last-updated-since').html("Last Updated: " + moment(window.localStorage.lastUpdatedOn).fromNow());
            window.qd.hourlyGithubPushEvents = hourlyGithubPushEvents;
            window.qd.plotHeatmapWith('#hourlyGithubPush-heat-map-parent', '#hourlyGithubPush-heat-map', hourlyGithubPushEvents);
        };
        postAjax("hourlyGithubPushEvents", hourlyGithubSuccessCallback, hourlyGithubErrorCallback);
    }

    button.prop("disabled", true);
    $("#hourlyGithubPush-heat-map").html("");
    var html_data = '

'
    $("#hourlyGithubPush-heat-map").html(html_data);

    postQDRouteAjax("connect_to_github?callback=?", showGitHubEvents, function(error) {
        console.log(error);
    })
}
$(document).ready(function(){

$(document).on('mouseup keyup', function(e){
        var e = e || event,
         code = (e.keyCode ? e.keyCode : e.which),
       target = e.srcElement || e.target;

        if (code==27) {
            $('.helpContainer').hide();
        }

    });

});
var show = function(element) {

   var showElement = "#" + element +" "+".helpContainer";
   $(showElement).slideToggle();
}

$("#connect_to_github_btn").click(handleConnectToGithub);
$("#github-push-events-sync").click(handleConnectToGithub);
$("#connect_to_github_link_popup_btn").click(handleConnectToGithub);

<commit_msg>Fix charts not getting populated when   ‘Link Data’ direct link is used.<commit_after>var dashboardGraphs = ['updateBuildModel', 'updateWTFModel', 'updateHydrationModel', 'updateCaffeineModel', 'updateBuildDurationModel', 'updateHourlyBuildHeatMap', 'updateHourlyWtfHeatMap', 'updateHourlyHydrationHeatMap', 'updateHourlyCaffeineHeatMap', 'updateActiveEvents', 'updateHourlyGithubPushHeatMap', 'updateCorrelationData'];

$("#builds-x").ready(function() {
    window.qd.registerForBuildModelUpdates(function() {
        var displayBuildCountAndBuildComparison = function(buildCount, buildCountElementId, comparisonValue, comparisonElementId) {
            $(buildCountElementId).text(buildCount);
            var buildComparison = Math.abs(comparisonValue);
            if (buildComparison && buildComparison !== Infinity) {
                $(comparisonElementId).text(buildComparison + "%");
                if (comparisonValue < 0) {
                    $(comparisonElementId).addClass("icon-caret-down");
                } else if (comparisonValue > 0) {
                    $(comparisonElementId).addClass("icon-caret-up");
                }
            }
        };

        displayBuildCountAndBuildComparison(window.qd.todaysTotalBuildCount, "#builds-x", window.qd.totalBuildComparison, "#total-build-comparison");
        displayBuildCountAndBuildComparison(window.qd.todaysPassedBuildCount, "#passed-x", window.qd.passedBuildComparison, "#passed-build-comparison");
        displayBuildCountAndBuildComparison(window.qd.todaysFailedBuildCount, "#failed-x", window.qd.failedBuildComparison, "#failed-build-comparison");
    });
});

$(window).resize(function() {
    window.qd.replotGraphs();
});

$(window).load(function() {
    //does not work in document.ready()
    if ($("#showOverlayFlag").attr("showOverlay") == 'true') {
        $("#connect_to_github_btn").show();
        $("#noDataSourceMessage").modal("show");
        window.qd.plotGraphs(dashboardGraphs);
    } else {
        window.qd.plotGraphs(dashboardGraphs);
    }
});

$('#last-updated-since').html("Last Updated: " + moment(window.localStorage.lastUpdatedOn).fromNow());

var handleConnectToGithub = function() {
    var button = $("#github-push-events-sync");
    $('#noDataSourceMessage').modal('hide');

    var showGitHubEvents = function(data) {
        var hourlyGithubErrorCallback = function() {
            alert("Github events error");
        };
        var hourlyGithubSuccessCallback = function(hourlyGithubPushEvents) {
            button.prop("disabled", false);
            $('#last-updated-since').html("");
            window.localStorage.lastUpdatedOn = new Date();
            $('#last-updated-since').html("Last Updated: " + moment(window.localStorage.lastUpdatedOn).fromNow());
            window.qd.hourlyGithubPushEvents = hourlyGithubPushEvents;
            window.qd.plotHeatmapWith('#hourlyGithubPush-heat-map-parent', '#hourlyGithubPush-heat-map', hourlyGithubPushEvents);
        };
        postAjax("hourlyGithubPushEvents", hourlyGithubSuccessCallback, hourlyGithubErrorCallback);
    }

    button.prop("disabled", true);
    $("#hourlyGithubPush-heat-map").html("");
    var html_data = '

'
    $("#hourlyGithubPush-heat-map").html(html_data);

    postQDRouteAjax("connect_to_github?callback=?", showGitHubEvents, function(error) {
        console.log(error);
    })
}
$(document).ready(function(){

$(document).on('mouseup keyup', function(e){
        var e = e || event,
         code = (e.keyCode ? e.keyCode : e.which),
       target = e.srcElement || e.target;

        if (code==27) {
            $('.helpContainer').hide();
        }

    });

});
var show = function(element) {

   var showElement = "#" + element +" "+".helpContainer";
   $(showElement).slideToggle();
}

$("#connect_to_github_btn").click(handleConnectToGithub);
$("#github-push-events-sync").click(handleConnectToGithub);
$("#connect_to_github_link_popup_btn").click(handleConnectToGithub);

<|endoftext|>


<commit_before>var React = require("react")

// pretty sure this component just makes use of the props
// it doesn't maintain it's own state
var Todo = React.createClass({
  handleChange: function (el) {},
  render: function () {
    var description;

    // strikethrough depending on if it's done
    if (this.props.todo.done) {
      description = {this.props.todo.description}
    }
    else {
      description = this.props.todo.description
    }

    return (

        {description}

          <input type="checkbox" value={this.props.todo.done} checked={this.props.todo.done} onChange={this.handleChange}/>
          <lable>Done</lable>

    )
  },
  getDefaultProps: function () {
    return {
      done: false,
      description: "Description was not provided"
    }
  }
})

module.exports = Todo
<commit_msg>Add TodoComponent for adding a Todo<commit_after>var React = require("react")

// pretty sure this component just makes use of the props
// it doesn't maintain it's own state

class Todo extends React.Component {
  // default props and PropTypes can be the static stuff now
  static defaultProps = {
    done: false,
    description: "Description was not provided"
  };

  // as a replacement for ComponentWillMount
  constructor(props) {
    super(props)

    this.handleDelete = this.handleDelete.bind(this)
    this.handleCheck = this.handleCheck.bind(this)
  }

  handleDelete (el) {
    this.props.removeTodo(this.props.todo.id)
  }

  handleCheck (el) {
    this.props.checkTodo(this.props.todo.id)
  }

  render () {
    var description;
    var doneButton;

    // strikethrough depending on if it's done
    if (this.props.todo.done) {
      description = {this.props.todo.description}
      doneButton = close
    }
    else {
      description = this.props.todo.description
      doneButton = check
    }

    return (

        {description}

          {doneButton}

            delete

    )
  }
}

module.exports = Todo
<|endoftext|>


<commit_before>import React from "react"
import ErrorsNormalizer from "../higher_order_components/errors_normalizer.js"
import AbstractForm from "./abstract_form.js"

/*
 * A JSX-compatible React DOM Component.
 * Form should be used as the top level component above any other frig
 * components.
 */
@ErrorsNormalizer({
  as: Object,
  publicFunctions: [
    "validate",
    "isValid",
    "isModified",
    "modifications",
    "resetModified",
    "reset",
    "formData",
  ],
})
export default class Form extends AbstractForm {
  displayName = "Form"

  static propTypes = {
    data: React.PropTypes.object.isRequired,
    onChange: React.PropTypes.func.isRequired,
    errors: React.PropTypes.object.isRequired,
    saved: React.PropTypes.object.isRequired,
    theme: React.PropTypes.object.isRequired,
    typeMapping: React.PropTypes.objectOf(React.PropTypes.string),
    layout: React.PropTypes.string.isRequired,
    align: React.PropTypes.string.isRequired,
    // Callbacks
    onSubmit: React.PropTypes.func,
  }

  static defaultProps = {
    errors: [],
    saved: {},
    theme: undefined,
    typeMapping: {},
    layout: "vertical",
    align: "left",
    onSubmit() {},
  }

  static childContextTypes = AbstractForm.childContextTypes

  render() {
    const ThemedForm = this.props.theme.component("form")
    return (
      <ThemedForm {...this._themedFormProps()}
        ref="form"
      >
        {this.props.children}
      </ThemedForm>
    )
  }

}
<commit_msg><Form/>: Throw if `data` or `onChange` are undefined<commit_after>import React from "react"
import ErrorsNormalizer from "../higher_order_components/errors_normalizer.js"
import AbstractForm from "./abstract_form.js"

/*
 * A JSX-compatible React DOM Component.
 * Form should be used as the top level component above any other frig
 * components.
 */
@ErrorsNormalizer({
  as: Object,
  publicFunctions: [
    "validate",
    "isValid",
    "isModified",
    "modifications",
    "resetModified",
    "reset",
    "formData",
  ],
})
export default class Form extends AbstractForm {
  displayName = "Form"

  componentWillMount() {
    if (!this.props.data) {
      throw new Error("Frig: Expression in <Form data={} /> must always be defined, got: " + this.props.data)
    }
    if (!this.props.onChange) {
      throw new Error("Frig: Expression in <Form onChange={} /> must always be defined, got: " + this.props.onChange)
    }
  }

  static propTypes = {
    data: React.PropTypes.object.isRequired,
    onChange: React.PropTypes.func.isRequired,
    errors: React.PropTypes.object.isRequired,
    saved: React.PropTypes.object.isRequired,
    theme: React.PropTypes.object.isRequired,
    typeMapping: React.PropTypes.objectOf(React.PropTypes.string),
    layout: React.PropTypes.string.isRequired,
    align: React.PropTypes.string.isRequired,
    // Callbacks
    onSubmit: React.PropTypes.func,
  }

  static defaultProps = {
    errors: [],
    saved: {},
    theme: undefined,
    typeMapping: {},
    layout: "vertical",
    align: "left",
    onSubmit() {},
  }

  static childContextTypes = AbstractForm.childContextTypes

  render() {
    const ThemedForm = this.props.theme.component("form")
    return (
      <ThemedForm {...this._themedFormProps()}
        ref="form"
      >
        {this.props.children}
      </ThemedForm>
    )
  }

}
<|endoftext|>


<commit_before>import React from 'react';
import classNames from 'classnames';

export default class Page extends React.Component {

  render() {
    let {kataGroups} = this.props;
    const katasCount = kataGroups.reduce((old, {katas: {length}}) => old + length, 0);
    const {showWorkshopBanner} = this.props;
    return (

        <KataGroups groups={kataGroups}/>

        <WorkshopBanner showWorkshopBanner={showWorkshopBanner}/>

    );
  }
}

class Header extends React.Component {
  render() {
    return (

ES6 Katas

Learn ES6 by doing it, fix failing tests and keep the learnings.

    );
  }
}

class Footer extends React.Component {
  render() {
    const {katasCount} = this.props;
    return (

maintained by

              Wolfram Kriesing

              Email me

              Book me

            uses TDDbin

{katasCount} katas

              source on github

              all katas on github

              @es6katas

              RSS

    );
  }
}

class KataGroups extends React.Component {
  render() {
    const {groups} = this.props;
    return (

        {groups.map((group) => <KataGroup group={group} isNewestKataCheck={groups.isNewestKata.bind(groups)}
                                          key={group.name}/>)}

    );
  }
}

class KataGroup extends React.Component {
  render() {
    const group = this.props.group;
    const {isNewestKataCheck} = this.props;
    return (

{group.name}

        {group.katas.map((kata) => <Kata kata={kata} group={group} isNewest={isNewestKataCheck(kata)} key={kata.id}/>)}

    );
  }
}

class Kata extends React.Component {
  render() {
    const {kata, isNewest, group} = this.props;
    const {url, name, level} = kata;
    const marker =
      isNewest ? new :
        (level === 'BEGINNER' ? easy : '');
    return

      {marker}<KataName name={name} />
      <KataDetails kata={kata} group={group} />

;
  }
}

class KataName extends React.Component {
  render() {
    const classNames = [];

    function renderWithName(name) {
      return
        {name}

    }

    const {name} = this.props;
    if (name.startsWith('`') && name.endsWith('`')) {
      classNames.push('code');
      const sourceCode = name.substr(1, name.length-2);
      return renderWithName(sourceCode);
    }
    return renderWithName(name);
  }
}

class KataDetails extends React.Component {
  render() {
    const {kata, group} = this.props;
    return (

#{kata.id} {group.name}: {kata.name}

{kata.description}

        Difficulty: {kata.level.toLowerCase()}

    );
  }
}

class WorkshopBanner extends React.Component {
  constructor() {
    super();
    this.state = {bannerIsMinimized: false};
  }

  render() {
    const imageUrl = './workshopbanner.png';
    const workshopUrl = 'http://www.uxebu.com/all-workshops/es6-and-react-js/';
    var classes = classNames({
      'workshop-banner': true,
      'fade-in': this.props.showWorkshopBanner,
      'small': this.state.bannerIsMinimized
    });
    return

        <button className="close" onClick={this.minimizeBanner.bind(this)}>[x]</button>

  }

  minimizeBanner() {
    this.setState({bannerIsMinimized: true});
  }

  maximizeBanner() {
    this.setState({bannerIsMinimized: false});
  }
}
<commit_msg>Footer work ...<commit_after>import React from 'react';
import classNames from 'classnames';

export default class Page extends React.Component {

  render() {
    let {kataGroups} = this.props;
    const katasCount = kataGroups.reduce((old, {katas: {length}}) => old + length, 0);
    const {showWorkshopBanner} = this.props;
    return (

        <KataGroups groups={kataGroups}/>

        <WorkshopBanner showWorkshopBanner={showWorkshopBanner}/>

    );
  }
}

class Header extends React.Component {
  render() {
    return (

ES6 Katas

Learn ES6 by doing it, fix failing tests and keep the learnings.

    );
  }
}

class Footer extends React.Component {
  render() {
    const {katasCount} = this.props;
    return (

by

              Wolfram Kriesing

              Email me

              Book me (training, coaching, clean-coding, ...)

              imprint

            uses TDDbin

{katasCount} katas

              source of this site

              all katas

              ES6 Katas

              RSS

    );
  }
}

class KataGroups extends React.Component {
  render() {
    const {groups} = this.props;
    return (

        {groups.map((group) => <KataGroup group={group} isNewestKataCheck={groups.isNewestKata.bind(groups)}
                                          key={group.name}/>)}

    );
  }
}

class KataGroup extends React.Component {
  render() {
    const group = this.props.group;
    const {isNewestKataCheck} = this.props;
    return (

{group.name}

        {group.katas.map((kata) => <Kata kata={kata} group={group} isNewest={isNewestKataCheck(kata)} key={kata.id}/>)}

    );
  }
}

class Kata extends React.Component {
  render() {
    const {kata, isNewest, group} = this.props;
    const {url, name, level} = kata;
    const marker =
      isNewest ? new :
        (level === 'BEGINNER' ? easy : '');
    return

      {marker}<KataName name={name} />
      <KataDetails kata={kata} group={group} />

;
  }
}

class KataName extends React.Component {
  render() {
    const classNames = [];

    function renderWithName(name) {
      return
        {name}

    }

    const {name} = this.props;
    if (name.startsWith('`') && name.endsWith('`')) {
      classNames.push('code');
      const sourceCode = name.substr(1, name.length-2);
      return renderWithName(sourceCode);
    }
    return renderWithName(name);
  }
}

class KataDetails extends React.Component {
  render() {
    const {kata, group} = this.props;
    return (

#{kata.id} {group.name}: {kata.name}

{kata.description}

        Difficulty: {kata.level.toLowerCase()}

    );
  }
}

class WorkshopBanner extends React.Component {
  constructor() {
    super();
    this.state = {bannerIsMinimized: false};
  }

  render() {
    const imageUrl = './workshopbanner.png';
    const workshopUrl = 'http://www.uxebu.com/all-workshops/es6-and-react-js/';
    var classes = classNames({
      'workshop-banner': true,
      'fade-in': this.props.showWorkshopBanner,
      'small': this.state.bannerIsMinimized
    });
    return

        <button className="close" onClick={this.minimizeBanner.bind(this)}>[x]</button>

  }

  minimizeBanner() {
    this.setState({bannerIsMinimized: true});
  }

  maximizeBanner() {
    this.setState({bannerIsMinimized: false});
  }
}
<|endoftext|>


<commit_before>var Converter = require('..');
var fs = require('fs');

function checkJcamp(filename, label, options) {
  var result = convert(
    readFileSync(__dirname + '/../__tests__' + filename).toString(),
    options,
  );

  console.log('===================', label);
  console.log(result.profiling);
}

var options = {
  fastParse: true,
};

//checkJcamp('/data/compression/jcamp-fix.dx', "Compression fixed", options);
//checkJcamp('/data/compression/jcamp-packed.dx', "Compression packed", options);
//checkJcamp('/data/compression/jcamp-squeezed.dx', "Compression squeezed", options);
//checkJcamp('/data/compression/jcamp-difdup.dx', "Compression difdup", options);
//for (var i=0; i<5; i++) {
checkJcamp('/data/indometacin/hmbc.dx', 'HMBC', options);
//}
<commit_msg>chore: improve benchmark<commit_after>import fs from 'fs';

import { convert } from '../src/index.js';

function checkJcamp(filename, label, options) {
  let result = convert(
    fs.readFileSync(`${__dirname}/../__tests__${filename}`).toString(),
    { noContour: true },
  );
}
console.time('time');
for (let i = 0; i < 20; i++) {
  checkJcamp('/data/indometacin/hmbc.dx', 'HMBC');
}

console.timeEnd('time');
<|endoftext|>


<commit_before>var EditorUI = (function () {
    var EditorUI = {};

    EditorUI.index = function ( element ) {
        var parentEL = Polymer.dom(element).parentNode;
        var parentDOM = Polymer.dom(parentEL);
        var curChildEL = parentDOM.children.length > 0 ? parentDOM.children[0] : null;

        for ( var i = 0, len = parentDOM.children.length; i < len; ++i ) {
            if ( parentDOM.children[i] === element )
                return i;
        }

        return -1;
    };

    var _findInChildren = function ( element, elementToFind ) {
        var elementDOM = Polymer.dom(element);

        for ( var i = 0; i < elementDOM.children.length; ++i ) {
            var childEL = elementDOM.children[i];
            if ( childEL === elementToFind )
                return true;

            if ( Polymer.dom(childEL).children.length > 0 )
                if ( _findInChildren( childEL, elementToFind ) )
                    return true;
        }
        return false;
    };

    //
    EditorUI.find = function ( elements, elementToFind ) {
        if ( Array.isArray(elements) ||
             elements instanceof NodeList ||
             elements instanceof HTMLCollection )
        {
            for ( var i = 0; i < elements.length; ++i ) {
                var element = elements[i];
                if ( element === elementToFind )
                    return true;

                if ( _findInChildren ( element, elementToFind ) )
                    return true;
            }
            return false;
        }

        // if this is a single element
        if ( elements === elementToFind )
            return true;

        return _findInChildren( elements, elementToFind );
    };

    //
    EditorUI.getParentTabIndex = function ( element ) {
        var parent = Polymer.dom(element).parentNode;
        while ( parent ) {
            if ( parent.tabIndex !== null && parent.tabIndex !== undefined ) {
                return parent.tabIndex;
            }

            parent = Polymer.dom(parent).parentNode;
        }
        return 0;
    };

    //
    EditorUI.focusParent = function ( element ) {
        // NOTE: DO NOT use Polymer.dom(element).parentNode
        var parent = element.parentElement;
        while ( parent ) {
            if ( parent.tabIndex !== null &&
                 parent.tabIndex !== undefined &&
                 parent.tabIndex !== -1 ) {
                parent.focus();
                return;
            }
            parent = parent.parentElement;
        }
    };

    //
    EditorUI.getSelfOrAncient = function ( element, parentType ) {
        var parent = element;
        while ( parent ) {
            if ( parent instanceof parentType )
                return parent;

            parent = Polymer.dom(parent).parentNode;
        }
        return 0;
    };

    EditorUI.isSelfOrAncient = function ( element, ancientEL ) {
        var parent = element;
        while ( parent ) {
            if ( parent === ancientEL )
                return true;

            parent = Polymer.dom(parent).parentNode;
        }
        return false;
    };

    //
    EditorUI.getFirstFocusableChild = function ( element ) {
        if ( element.tabIndex !== null &&
             element.tabIndex !== undefined &&
             element.tabIndex !== -1
           )
        {
            return element;
        }

        var el = null;
        // var elementDOM = Polymer.dom(element);
        var elementDOM = element;
        for ( var i = 0; i < elementDOM.children.length; ++i ) {
            el = EditorUI.getFirstFocusableChild(elementDOM.children[i]);
            if ( el !== null )
                return el;
        }

        // var rootDOM = Polymer.dom(element.root);
        // if ( rootDOM ) {
        //     el = EditorUI.getFirstFocusableChild(rootDOM);
        //     if ( el !== null )
        //         return el;
        // }

        return null;
    };

    var _cancelDrag = null;
    EditorUI.startDrag = function ( cursor, event, onMove, onEnd ) {
        EditorUI.addDragGhost(cursor);

        event.stopPropagation();

        var pressx = event.clientX, lastx = event.clientX;
        var pressy = event.clientY, lasty = event.clientY;
        var dx = 0, offsetx = 0;
        var dy = 0, offsety = 0;

        var mousemoveHandle = function(event) {
            event.stopPropagation();

            dx = event.clientX - lastx;
            dy = event.clientY - lasty;
            offsetx = event.clientX - pressx;
            offsety = event.clientY - pressy;

            lastx = event.clientX;
            lasty = event.clientY;

            onMove( event, dx, dy, offsetx, offsety );
        };

        var mouseupHandle = function(event) {
            event.stopPropagation();

            document.removeEventListener('mousemove', mousemoveHandle);
            document.removeEventListener('mouseup', mouseupHandle);

            EditorUI.removeDragGhost();

            dx = event.clientX - lastx;
            dy = event.clientY - lasty;
            offsetx = event.clientX - pressx;
            offsety = event.clientY - pressy;

            _cancelDrag = null;
            onEnd( event, dx, dy, offsetx, offsety);
        }.bind(this);

        _cancelDrag = function () {
            document.removeEventListener('mousemove', mousemoveHandle);
            document.removeEventListener('mouseup', mouseupHandle);

            EditorUI.removeDragGhost();
        };

        document.addEventListener ( 'mousemove', mousemoveHandle );
        document.addEventListener ( 'mouseup', mouseupHandle );
    };

    EditorUI.cancelDrag = function () {
        if ( _cancelDrag )
            _cancelDrag();
    };

    //
    var _dragGhost = null;
    EditorUI.addDragGhost = function ( cursor ) {
        // add drag-ghost
        if ( _dragGhost === null ) {
            _dragGhost = document.createElement('div');
            _dragGhost.classList.add('drag-ghost');
            _dragGhost.style.position = 'absolute';
            _dragGhost.style.zIndex = '999';
            _dragGhost.style.top = '0';
            _dragGhost.style.right = '0';
            _dragGhost.style.bottom = '0';
            _dragGhost.style.left = '0';
            _dragGhost.oncontextmenu = function() { return false; };
        }
        _dragGhost.style.cursor = cursor;
        document.body.appendChild(_dragGhost);

        return _dragGhost;
    };

    EditorUI.removeDragGhost = function () {
        if ( _dragGhost !== null ) {
            _dragGhost.style.cursor = 'auto';
            if ( _dragGhost.parentElement !== null ) {
                _dragGhost.parentElement.removeChild(_dragGhost);
            }
        }
    };

    //
    var _hitGhost = null;
    EditorUI.addHitGhost = function ( cursor, zindex, onhit ) {
        // add drag-ghost
        if ( _hitGhost === null ) {
            _hitGhost = document.createElement('div');
            _hitGhost.classList.add('hit-ghost');
            _hitGhost.style.position = 'absolute';
            _hitGhost.style.zIndex = zindex;
            _hitGhost.style.top = '0';
            _hitGhost.style.right = '0';
            _hitGhost.style.bottom = '0';
            _hitGhost.style.left = '0';
            // _hitGhost.style.background = 'rgba(0,0,0,0.2)';
            _hitGhost.oncontextmenu = function() { return false; };
        }

        _hitGhost.style.cursor = cursor;
        _hitGhost.addEventListener('mousedown', function (event) {
            event.preventDefault();
            event.stopPropagation();
            if ( onhit )
                onhit();
        });
        document.body.appendChild(_hitGhost);

        return _hitGhost;
    };

    EditorUI.removeHitGhost = function () {
        if ( _hitGhost !== null ) {
            _hitGhost.style.cursor = 'auto';
            if ( _hitGhost.parentElement !== null ) {
                _hitGhost.parentElement.removeChild(_hitGhost);
                _hitGhost.removeEventListener('mousedown');
            }
        }
    };

    //
    var _loadingMask = null;
    EditorUI.addLoadingMask = function ( options, onclick ) {
        // add drag-ghost
        if ( _loadingMask === null ) {
            _loadingMask = document.createElement('div');
            _loadingMask.classList.add('loading-mask');
            _loadingMask.style.position = 'absolute';
            _loadingMask.style.top = '0';
            _loadingMask.style.right = '0';
            _loadingMask.style.bottom = '0';
            _loadingMask.style.left = '0';
            _loadingMask.oncontextmenu = function() { return false; };
        }

        if ( options && typeof options.zindex === 'string' ) {
            _loadingMask.style.zIndex = options.zindex;
        }
        else {
            _loadingMask.style.zIndex = '999';
        }

        if ( options && typeof options.background === 'string' ) {
            _loadingMask.style.backgroundColor = options.background;
        }
        else {
            _loadingMask.style.backgroundColor = 'rgba(0,0,0,0.2)';
        }

        if ( options && typeof options.cursor === 'string' ) {
            _loadingMask.style.cursor = options.cursor;
        }
        else {
            _loadingMask.style.cursor = 'default';
        }

        _loadingMask.addEventListener('mousedown', function (event) {
            event.preventDefault();
            event.stopPropagation();
            if ( onclick )
                onclick();
        });

        document.body.appendChild(_loadingMask);

        return _loadingMask;
    };

    EditorUI.removeLoadingMask = function () {
        if ( _loadingMask !== null ) {
            _loadingMask.style.cursor = 'auto';
            if ( _loadingMask.parentElement !== null ) {
                _loadingMask.parentElement.removeChild(_loadingMask);
                _loadingMask.removeEventListener('mousedown');
            }
        }
    };

    function _createLayouts ( parentEL, infos, importList ) {
        for ( var i = 0; i < infos.length; ++i ) {
            var info = infos[i];

            var el;

            if ( info.type === 'dock' ) {
                el = new EditorUI.Dock();
            }
            else if ( info.type === 'panel' ) {
                el = new EditorUI.Panel();
            }

            if ( !el ) continue;

            if ( info.row !== undefined ) {
                el.row = info.row;
            }
            if ( info.width !== undefined ) {
                el.curWidth = info.width;
            }
            if ( info.height !== undefined ) {
                el.curHeight = info.height;
            }

            if ( info.docks ) {
                _createLayouts ( el, info.docks, importList );
            }
            else if ( info.panels ) {
                for ( var j = 0; j < info.panels.length; ++j ) {
                    importList.push( { dockEL: el, panelID: info.panels[j], active: j === info.active } );
                }
            }

            Polymer.dom(parentEL).appendChild(el);
        }
        parentEL._initResizers();
    }

    EditorUI.createLayout = function ( parentEL, layoutInfo ) {
        var importList = [];

        // if we have root, clear all children in it
        var rootEL = EditorUI.DockUtils.root;
        if ( rootEL ) {
            rootEL.remove();
            EditorUI.DockUtils.root = null;
        }

        rootEL = new EditorUI.Dock();
        rootEL.classList.add('fit');
        rootEL.setAttribute('no-collapse', '');

        if ( layoutInfo ) {
            if ( layoutInfo.row ) rootEL.setAttribute('row', '');
            _createLayouts( rootEL, layoutInfo.docks, importList );
        }

        Polymer.dom(parentEL).appendChild(rootEL);
        EditorUI.DockUtils.root = rootEL;

        return importList;
    };

    // binding helpers
    EditorUI.bind = function ( el1, value1, el2, value2 ) {
        el1.addEventListener( value1+'-changed', function ( event ) {
            el2.set( value2, event.detail.value );
        });
        el2.addEventListener( value2+'-changed', function ( event ) {
            el1.set( value1, event.detail.value );
        });
    };

    EditorUI.toHumanText = function ( text ) {
        var result = text.replace(/([A-Z])/g, ' $1').replace(/[-_]/g, ' ');

        // remove first white-space
        if ( result.charAt(0) === ' ' ) {
            result.slice(1);
        }

        // capitalize the first letter
        return result.charAt(0).toUpperCase() + result.slice(1);
    };

    return EditorUI;
})();
<commit_msg>add EditorUI.fitSize<commit_after>var EditorUI = (function () {
    var EditorUI = {};

    EditorUI.index = function ( element ) {
        var parentEL = Polymer.dom(element).parentNode;
        var parentDOM = Polymer.dom(parentEL);
        var curChildEL = parentDOM.children.length > 0 ? parentDOM.children[0] : null;

        for ( var i = 0, len = parentDOM.children.length; i < len; ++i ) {
            if ( parentDOM.children[i] === element )
                return i;
        }

        return -1;
    };

    var _findInChildren = function ( element, elementToFind ) {
        var elementDOM = Polymer.dom(element);

        for ( var i = 0; i < elementDOM.children.length; ++i ) {
            var childEL = elementDOM.children[i];
            if ( childEL === elementToFind )
                return true;

            if ( Polymer.dom(childEL).children.length > 0 )
                if ( _findInChildren( childEL, elementToFind ) )
                    return true;
        }
        return false;
    };

    //
    EditorUI.find = function ( elements, elementToFind ) {
        if ( Array.isArray(elements) ||
             elements instanceof NodeList ||
             elements instanceof HTMLCollection )
        {
            for ( var i = 0; i < elements.length; ++i ) {
                var element = elements[i];
                if ( element === elementToFind )
                    return true;

                if ( _findInChildren ( element, elementToFind ) )
                    return true;
            }
            return false;
        }

        // if this is a single element
        if ( elements === elementToFind )
            return true;

        return _findInChildren( elements, elementToFind );
    };

    //
    EditorUI.getParentTabIndex = function ( element ) {
        var parent = Polymer.dom(element).parentNode;
        while ( parent ) {
            if ( parent.tabIndex !== null && parent.tabIndex !== undefined ) {
                return parent.tabIndex;
            }

            parent = Polymer.dom(parent).parentNode;
        }
        return 0;
    };

    //
    EditorUI.focusParent = function ( element ) {
        // NOTE: DO NOT use Polymer.dom(element).parentNode
        var parent = element.parentElement;
        while ( parent ) {
            if ( parent.tabIndex !== null &&
                 parent.tabIndex !== undefined &&
                 parent.tabIndex !== -1 ) {
                parent.focus();
                return;
            }
            parent = parent.parentElement;
        }
    };

    //
    EditorUI.getSelfOrAncient = function ( element, parentType ) {
        var parent = element;
        while ( parent ) {
            if ( parent instanceof parentType )
                return parent;

            parent = Polymer.dom(parent).parentNode;
        }
        return 0;
    };

    EditorUI.isSelfOrAncient = function ( element, ancientEL ) {
        var parent = element;
        while ( parent ) {
            if ( parent === ancientEL )
                return true;

            parent = Polymer.dom(parent).parentNode;
        }
        return false;
    };

    //
    EditorUI.getFirstFocusableChild = function ( element ) {
        if ( element.tabIndex !== null &&
             element.tabIndex !== undefined &&
             element.tabIndex !== -1
           )
        {
            return element;
        }

        var el = null;
        // var elementDOM = Polymer.dom(element);
        var elementDOM = element;
        for ( var i = 0; i < elementDOM.children.length; ++i ) {
            el = EditorUI.getFirstFocusableChild(elementDOM.children[i]);
            if ( el !== null )
                return el;
        }

        // var rootDOM = Polymer.dom(element.root);
        // if ( rootDOM ) {
        //     el = EditorUI.getFirstFocusableChild(rootDOM);
        //     if ( el !== null )
        //         return el;
        // }

        return null;
    };

    var _cancelDrag = null;
    EditorUI.startDrag = function ( cursor, event, onMove, onEnd ) {
        EditorUI.addDragGhost(cursor);

        event.stopPropagation();

        var pressx = event.clientX, lastx = event.clientX;
        var pressy = event.clientY, lasty = event.clientY;
        var dx = 0, offsetx = 0;
        var dy = 0, offsety = 0;

        var mousemoveHandle = function(event) {
            event.stopPropagation();

            dx = event.clientX - lastx;
            dy = event.clientY - lasty;
            offsetx = event.clientX - pressx;
            offsety = event.clientY - pressy;

            lastx = event.clientX;
            lasty = event.clientY;

            onMove( event, dx, dy, offsetx, offsety );
        };

        var mouseupHandle = function(event) {
            event.stopPropagation();

            document.removeEventListener('mousemove', mousemoveHandle);
            document.removeEventListener('mouseup', mouseupHandle);

            EditorUI.removeDragGhost();

            dx = event.clientX - lastx;
            dy = event.clientY - lasty;
            offsetx = event.clientX - pressx;
            offsety = event.clientY - pressy;

            _cancelDrag = null;
            onEnd( event, dx, dy, offsetx, offsety);
        }.bind(this);

        _cancelDrag = function () {
            document.removeEventListener('mousemove', mousemoveHandle);
            document.removeEventListener('mouseup', mouseupHandle);

            EditorUI.removeDragGhost();
        };

        document.addEventListener ( 'mousemove', mousemoveHandle );
        document.addEventListener ( 'mouseup', mouseupHandle );
    };

    EditorUI.cancelDrag = function () {
        if ( _cancelDrag )
            _cancelDrag();
    };

    //
    var _dragGhost = null;
    EditorUI.addDragGhost = function ( cursor ) {
        // add drag-ghost
        if ( _dragGhost === null ) {
            _dragGhost = document.createElement('div');
            _dragGhost.classList.add('drag-ghost');
            _dragGhost.style.position = 'absolute';
            _dragGhost.style.zIndex = '999';
            _dragGhost.style.top = '0';
            _dragGhost.style.right = '0';
            _dragGhost.style.bottom = '0';
            _dragGhost.style.left = '0';
            _dragGhost.oncontextmenu = function() { return false; };
        }
        _dragGhost.style.cursor = cursor;
        document.body.appendChild(_dragGhost);

        return _dragGhost;
    };

    EditorUI.removeDragGhost = function () {
        if ( _dragGhost !== null ) {
            _dragGhost.style.cursor = 'auto';
            if ( _dragGhost.parentElement !== null ) {
                _dragGhost.parentElement.removeChild(_dragGhost);
            }
        }
    };

    //
    var _hitGhost = null;
    EditorUI.addHitGhost = function ( cursor, zindex, onhit ) {
        // add drag-ghost
        if ( _hitGhost === null ) {
            _hitGhost = document.createElement('div');
            _hitGhost.classList.add('hit-ghost');
            _hitGhost.style.position = 'absolute';
            _hitGhost.style.zIndex = zindex;
            _hitGhost.style.top = '0';
            _hitGhost.style.right = '0';
            _hitGhost.style.bottom = '0';
            _hitGhost.style.left = '0';
            // _hitGhost.style.background = 'rgba(0,0,0,0.2)';
            _hitGhost.oncontextmenu = function() { return false; };
        }

        _hitGhost.style.cursor = cursor;
        _hitGhost.addEventListener('mousedown', function (event) {
            event.preventDefault();
            event.stopPropagation();
            if ( onhit )
                onhit();
        });
        document.body.appendChild(_hitGhost);

        return _hitGhost;
    };

    EditorUI.removeHitGhost = function () {
        if ( _hitGhost !== null ) {
            _hitGhost.style.cursor = 'auto';
            if ( _hitGhost.parentElement !== null ) {
                _hitGhost.parentElement.removeChild(_hitGhost);
                _hitGhost.removeEventListener('mousedown');
            }
        }
    };

    //
    var _loadingMask = null;
    EditorUI.addLoadingMask = function ( options, onclick ) {
        // add drag-ghost
        if ( _loadingMask === null ) {
            _loadingMask = document.createElement('div');
            _loadingMask.classList.add('loading-mask');
            _loadingMask.style.position = 'absolute';
            _loadingMask.style.top = '0';
            _loadingMask.style.right = '0';
            _loadingMask.style.bottom = '0';
            _loadingMask.style.left = '0';
            _loadingMask.oncontextmenu = function() { return false; };
        }

        if ( options && typeof options.zindex === 'string' ) {
            _loadingMask.style.zIndex = options.zindex;
        }
        else {
            _loadingMask.style.zIndex = '999';
        }

        if ( options && typeof options.background === 'string' ) {
            _loadingMask.style.backgroundColor = options.background;
        }
        else {
            _loadingMask.style.backgroundColor = 'rgba(0,0,0,0.2)';
        }

        if ( options && typeof options.cursor === 'string' ) {
            _loadingMask.style.cursor = options.cursor;
        }
        else {
            _loadingMask.style.cursor = 'default';
        }

        _loadingMask.addEventListener('mousedown', function (event) {
            event.preventDefault();
            event.stopPropagation();
            if ( onclick )
                onclick();
        });

        document.body.appendChild(_loadingMask);

        return _loadingMask;
    };

    EditorUI.removeLoadingMask = function () {
        if ( _loadingMask !== null ) {
            _loadingMask.style.cursor = 'auto';
            if ( _loadingMask.parentElement !== null ) {
                _loadingMask.parentElement.removeChild(_loadingMask);
                _loadingMask.removeEventListener('mousedown');
            }
        }
    };

    function _createLayouts ( parentEL, infos, importList ) {
        for ( var i = 0; i < infos.length; ++i ) {
            var info = infos[i];

            var el;

            if ( info.type === 'dock' ) {
                el = new EditorUI.Dock();
            }
            else if ( info.type === 'panel' ) {
                el = new EditorUI.Panel();
            }

            if ( !el ) continue;

            if ( info.row !== undefined ) {
                el.row = info.row;
            }
            if ( info.width !== undefined ) {
                el.curWidth = info.width;
            }
            if ( info.height !== undefined ) {
                el.curHeight = info.height;
            }

            if ( info.docks ) {
                _createLayouts ( el, info.docks, importList );
            }
            else if ( info.panels ) {
                for ( var j = 0; j < info.panels.length; ++j ) {
                    importList.push( { dockEL: el, panelID: info.panels[j], active: j === info.active } );
                }
            }

            Polymer.dom(parentEL).appendChild(el);
        }
        parentEL._initResizers();
    }

    EditorUI.createLayout = function ( parentEL, layoutInfo ) {
        var importList = [];

        // if we have root, clear all children in it
        var rootEL = EditorUI.DockUtils.root;
        if ( rootEL ) {
            rootEL.remove();
            EditorUI.DockUtils.root = null;
        }

        rootEL = new EditorUI.Dock();
        rootEL.classList.add('fit');
        rootEL.setAttribute('no-collapse', '');

        if ( layoutInfo ) {
            if ( layoutInfo.row ) rootEL.setAttribute('row', '');
            _createLayouts( rootEL, layoutInfo.docks, importList );
        }

        Polymer.dom(parentEL).appendChild(rootEL);
        EditorUI.DockUtils.root = rootEL;

        return importList;
    };

    /**
     * @method fitSize
     * @param {number} srcWidth
     * @param {number} srcHeight
     * @param {number} destWidth
     * @param {number} destHeight
     * @return {number[]} - [width, height]
     */
    EditorUI.fitSize = function ( srcWidth, srcHeight, destWidth, destHeight ) {
        var width, height;
        if ( srcWidth > destWidth &&
             srcHeight > destHeight )
        {
            width = destWidth;
            height = srcHeight * destWidth/srcWidth;

            if ( height > destHeight ) {
                height = destHeight;
                width = srcWidth * destHeight/srcHeight;
            }
        }
        else if ( srcWidth > destWidth ) {
            width = destWidth;
            height = srcHeight * destWidth/srcWidth;
        }
        else if ( srcHeight > destHeight ) {
            width = srcWidth * destHeight/srcHeight;
            height = destHeight;
        }
        else {
            width = srcWidth;
            height = srcHeight;
        }

        return [width,height];
    };

    // binding helpers
    EditorUI.bind = function ( el1, value1, el2, value2 ) {
        el1.addEventListener( value1+'-changed', function ( event ) {
            el2.set( value2, event.detail.value );
        });
        el2.addEventListener( value2+'-changed', function ( event ) {
            el1.set( value1, event.detail.value );
        });
    };

    EditorUI.toHumanText = function ( text ) {
        var result = text.replace(/([A-Z])/g, ' $1').replace(/[-_]/g, ' ');

        // remove first white-space
        if ( result.charAt(0) === ' ' ) {
            result.slice(1);
        }

        // capitalize the first letter
        return result.charAt(0).toUpperCase() + result.slice(1);
    };

    return EditorUI;
})();
<|endoftext|>


<commit_before>"use strict";
(function() {
  var insertLocation, arr;
  insertLocation = document.querySelector('script[src$="content_script_loader.js"]') || document.head.firstChild;
  arr = chrome.runtime.getManifest().content_scripts[0].js;
  arr.pop();
  arr.forEach(function(src) {
    var scriptElement = document.createElement("script");
    scriptElement.type = "text/javascript";
    scriptElement.async = false;
    scriptElement.src = (src[0] !== "/") ? ("/" + src) : src;
    insertLocation.parentElement.insertBefore(scriptElement, insertLocation);
  });
})();
<commit_msg>fix a script name typo in pages/loader<commit_after>"use strict";
(function() {
  var insertLocation, arr;
  insertLocation = document.querySelector('script[src$="loader.js"]') || document.head.firstChild;
  arr = chrome.runtime.getManifest().content_scripts[0].js;
  arr.pop();
  arr.forEach(function(src) {
    var scriptElement = document.createElement("script");
    scriptElement.type = "text/javascript";
    scriptElement.async = false;
    scriptElement.src = (src[0] !== "/") ? ("/" + src) : src;
    insertLocation.parentElement.insertBefore(scriptElement, insertLocation);
  });
})();
<|endoftext|>