<commit_before>'use strict';
import _ from 'lodash';
import Promise from 'native-promise-only';
import {checkCondition} from '../../utils/utils';
import BaseComponent from '../base/Base';
import Components from '../Components';

export default class NestedComponent extends BaseComponent {
  static schema(...extend) {
    return BaseComponent.schema({
      tree: true
    }, ...extend);
  }

  constructor(component, options, data) {
    super(component, options, data);
    this.type = 'components';
    this.components = [];
    this.hidden = [];
    this.collapsed = !!this.component.collapsed;
  }

  build(showLabel) {
    this.createElement();
    if (showLabel) {
      this.createLabel(this.element);
    }
    this.addComponents();
  }

  get defaultSchema() {
    return NestedComponent.schema();
  }

  get schema() {
    const schema = super.schema;
    schema.components = [];
    this.eachComponent((component) => schema.components.push(component.schema));
    return schema;
  }

  getComponents() {
    return this.components;
  }

  /**
   * Perform a deep iteration over every component, including those
   * within other container based components.
   *
   * @param {function} fn - Called for every component.
   */
  everyComponent(fn) {
    const components = this.getComponents();
    _.each(components, (component, index) => {
      if (fn(component, components, index) === false) {
        return false;
      }

      if (typeof component.everyComponent === 'function') {
        if (component.everyComponent(fn) === false) {
          return false;
        }
      }
    });
  }

  /**
   * Perform an iteration over each component within this container component.
   *
   * @param {function} fn - Called for each component
   */
  eachComponent(fn) {
    _.each(this.getComponents(), (component, index) => {
      if (fn(component, index) === false) {
        return false;
      }
    });
  }

  /**
   * Returns a component provided a key. This performs a deep search within the
   * component tree.
   *
   * @param {string} key - The key of the component to retrieve.
   * @param {function} fn - Called with the component once found.
   * @return {Object} - The component that is located.
   */
  getComponent(key, fn) {
    let comp = null;
    this.everyComponent((component, components) => {
      if (component.component.key === key) {
        comp = component;
        if (fn) {
          fn(component, components);
        }
        return false;
      }
    });
    return comp;
  }

  /**
   * Return a component provided the Id of the component.
   *
   * @param {string} id - The Id of the component.
   * @param {function} fn - Called with the component once it is retrieved.
   * @return {Object} - The component retrieved.
   */
  getComponentById(id, fn) {
    let comp = null;
    this.everyComponent((component, components) => {
      if (component.id === id) {
        comp = component;
        if (fn) {
          fn(component, components);
        }
        return false;
      }
    });
    return comp;
  }

  /**
   * Create a new component and add it to the components array.
   *
   * @param component
   * @param data
   */
  createComponent(component, options, data, before) {
    options = options || this.options;
    data = data || this.data;
    const comp = Components.create(component, options, data, true);
    comp.parent = this;
    comp.root = this.root || this;
    comp.build();
    comp.isBuilt = true;
    if (component.internal) {
      return comp;
    }

    if (before) {
      const index = _.findIndex(this.components, {id: before.id});
      if (index !== -1) {
        this.components.splice(index, 0, comp);
      }
      else {
        this.components.push(comp);
      }
    }
    else {
      this.components.push(comp);
    }
    return comp;
  }

  getContainer() {
    return this.element;
  }

  /**
   * Add a new component to the components array.
   *
   * @param {Object} component - The component JSON schema to add.
   * @param {HTMLElement} element - The DOM element to append this child to.
   * @param {Object} data - The submission data object to house the data for this component.
   * @param {HTMLElement} before - A DOM element to insert this element before.
   * @return {BaseComponent} - The created component instance.
   */
  addComponent(component, element, data, before, noAdd) {
    element = element || this.getContainer();
    data = data || this.data;
    const comp = this.createComponent(component, this.options, data, before ? before.component : null);
    if (noAdd) {
      return comp;
    }
    this.setHidden(comp);
    element = this.hook('addComponent', element, comp);
    if (before) {
      element.insertBefore(comp.getElement(), before);
    }
    else {
      element.appendChild(comp.getElement());
    }
    return comp;
  }

  /**
   * Remove a component from the components array.
   *
   * @param {BaseComponent} component - The component to remove from the components.
   * @param {Array<BaseComponent>} components - An array of components to remove this component from.
   */
  removeComponent(component, components) {
    components = components || this.components;
    component.destroy();
    const element = component.getElement();
    if (element && element.parentNode) {
      this.removeChildFrom(element, element.parentNode);
    }
    _.remove(components, {id: component.id});
  }

  /**
   * Removes a component provided the API key of that component.
   *
   * @param {string} key - The API key of the component to remove.
   * @param {function} fn - Called once the component is removed.
   * @return {null}
   */
  removeComponentByKey(key, fn) {
    const comp = this.getComponent(key, (component, components) => {
      this.removeComponent(component, components);
      if (fn) {
        fn(component, components);
      }
    });
    if (!comp) {
      if (fn) {
        fn(null);
      }
      return null;
    }
  }

  /**
   * Removes a component provided the Id of the component.
   *
   * @param {string} id - The Id of the component to remove.
   * @param {function} fn - Called when the component is removed.
   * @return {null}
   */
  removeComponentById(id, fn) {
    const comp = this.getComponentById(id, (component, components) => {
      this.removeComponent(component, components);
      if (fn) {
        fn(component, components);
      }
    });
    if (!comp) {
      if (fn) {
        fn(null);
      }
      return null;
    }
  }

  get componentComponents() {
    return this.component.components;
  }

  /**
   *
   * @param element
   * @param data
   */
  addComponents(element, data) {
    element = element || this.getContainer();
    data = data || this.data;
    const components = this.hook('addComponents', this.componentComponents);
    _.each(components, (component) => this.addComponent(component, element, data));
  }

  updateValue(flags) {
    let changed = false;
    _.each(this.components, (comp) => {
      changed |= comp.updateValue(flags);
    });
    return changed;
  }

  hasChanged() {
    return false;
  }

  /**
   * A more performant way to check the conditions, calculations, and validity of
   * a submission once it has been changed.
   *
   * @param data
   * @param flags
   */
  checkData(data, flags) {
    flags = flags || {};
    let valid = true;
    if (flags.noCheck) {
      return;
    }

    // Update the value.
    let changed = this.updateValue({
      noUpdateEvent: true
    });

    // Iterate through all components and check conditions, and calculate values.
    _.each(this.getComponents(), (comp) => {
      changed |= comp.calculateValue(data, {
        noUpdateEvent: true
      });
      comp.checkConditions(data);
      if (!flags.noValidate) {
        valid &= comp.checkValidity(data);
      }
    });

    // Trigger the change if the values changed.
    if (changed) {
      this.triggerChange(flags);
    }

    // Return if the value is valid.
    return valid;
  }

  checkConditions(data) {
    this.getComponents().forEach(comp => comp.checkConditions(data));
    return super.checkConditions(data);
  }

  clearOnHide(show) {
    super.clearOnHide(show);
    this.getComponents().forEach(component => component.clearOnHide(show));
  }

  /**
   * Allow components to hook into the next page trigger to perform their own logic.
   *
   * @return {*}
   */
  beforeNext() {
    const ops = [];
    _.each(this.getComponents(), (comp) => ops.push(comp.beforeNext()));
    return Promise.all(ops);
  }

  /**
   * Allow components to hook into the submission to provide their own async data.
   *
   * @return {*}
   */
  beforeSubmit() {
    const ops = [];
    _.each(this.getComponents(), (comp) => ops.push(comp.beforeSubmit()));
    return Promise.all(ops);
  }

  calculateValue(data, flags) {
    let changed = super.calculateValue(data, flags);
    _.each(this.getComponents(), (comp) => {
      changed |= comp.calculateValue(data, flags);
    });
    return changed;
  }

  isValid(data, dirty) {
    let valid = super.isValid(data, dirty);
    _.each(this.getComponents(), (comp) => {
      valid &= comp.isValid(data, dirty);
    });
    return valid;
  }

  checkValidity(data, dirty) {
    if (!checkCondition(this.component, data, this.data, this.root ? this.root._form : {}, this)) {
      return true;
    }

    let check = super.checkValidity(data, dirty);
    _.each(this.getComponents(), (comp) => {
      check &= comp.checkValidity(data, dirty);
    });
    return check;
  }

  setPristine(pristine) {
    super.setPristine(pristine);
    _.each(this.getComponents(), (comp) => (comp.setPristine(pristine)));
  }

  destroy(all) {
    super.destroy(all);
    this.empty(this.getElement());
    this.destroyComponents();
  }

  destroyComponents() {
    const components = _.clone(this.components);
    _.each(components, (comp) => this.removeComponent(comp, this.components));
    this.components = [];
    this.hidden = [];
  }

  set disabled(disabled) {
    _.each(this.components, (component) => (component.disabled = disabled));
  }

  setHidden(component) {
    if (component.components && component.components.length) {
      component.hideComponents(this.hidden);
    }
    else if (component.component.hidden) {
      component.visible = false;
    }
    else {
      component.visible = (!this.hidden || !this.hidden.includes(component.key));
    }
  }

  hideComponents(hidden) {
    this.hidden = hidden;
    this.eachComponent((component) => this.setHidden(component));
  }

  get errors() {
    let errors = [];
    _.each(this.getComponents(), (comp) => {
      const compErrors = comp.errors;
      if (compErrors.length) {
        errors = errors.concat(compErrors);
      }
    });
    return errors;
  }

  get value() {
    return this.data;
  }

  getValue() {
    return this.data;
  }

  resetValue() {
    _.each(this.getComponents(), (comp) => (comp.resetValue()));
    _.unset(this.data, this.key);
    this.setPristine(true);
  }

  whenReady() {
    const promises = [];
    _.each(this.getComponents(), (component) => {
      promises.push(component.whenReady());
    });
    return Promise.all(promises);
  }

  setValue(value, flags) {
    if (!value) {
      return false;
    }
    flags = this.getFlags.apply(this, arguments);
    let changed = false;
    this.getComponents().forEach(component => {
      if (component.type === 'button') {
        return;
      }

      if (component.type === 'components') {
        changed |= component.setValue(value, flags);
      }
      else if (value && component.hasValue(value)) {
        changed |= component.setValue(_.get(value, component.key), flags);
      }
      else {
        flags.noValidate = true;
        changed |= component.setValue(component.defaultValue, flags);
      }
    });
    return changed;
  }

  setCollapseHeader(header) {
    if (this.component.collapsible) {
      this.addClass(header, 'formio-clickable');
      this.addEventListener(header, 'click', () => this.toggleCollapse());
    }
  }

  setCollapsed(element) {
    if (!this.component.collapsible) {
      return;
    }

    const container = element || this.getContainer();

    if (this.collapsed) {
      container.setAttribute('hidden', true);
      container.style.visibility = 'hidden';
    }
    else {
      container.removeAttribute('hidden');
      container.style.visibility = 'visible';
    }
  }

  toggleCollapse() {
    this.collapsed = !this.collapsed;
    this.setCollapsed();
  }
}
<commit_msg>Fixed issues with the validity checks of components within nested components.<commit_after>'use strict';
import _ from 'lodash';
import Promise from 'native-promise-only';
import {checkCondition} from '../../utils/utils';
import BaseComponent from '../base/Base';
import Components from '../Components';

export default class NestedComponent extends BaseComponent {
  static schema(...extend) {
    return BaseComponent.schema({
      tree: true
    }, ...extend);
  }

  constructor(component, options, data) {
    super(component, options, data);
    this.type = 'components';
    this.components = [];
    this.hidden = [];
    this.collapsed = !!this.component.collapsed;
  }

  build(showLabel) {
    this.createElement();
    if (showLabel) {
      this.createLabel(this.element);
    }
    this.addComponents();
  }

  get defaultSchema() {
    return NestedComponent.schema();
  }

  get schema() {
    const schema = super.schema;
    schema.components = [];
    this.eachComponent((component) => schema.components.push(component.schema));
    return schema;
  }

  getComponents() {
    return this.components;
  }

  /**
   * Perform a deep iteration over every component, including those
   * within other container based components.
   *
   * @param {function} fn - Called for every component.
   */
  everyComponent(fn) {
    const components = this.getComponents();
    _.each(components, (component, index) => {
      if (fn(component, components, index) === false) {
        return false;
      }

      if (typeof component.everyComponent === 'function') {
        if (component.everyComponent(fn) === false) {
          return false;
        }
      }
    });
  }

  /**
   * Perform an iteration over each component within this container component.
   *
   * @param {function} fn - Called for each component
   */
  eachComponent(fn) {
    _.each(this.getComponents(), (component, index) => {
      if (fn(component, index) === false) {
        return false;
      }
    });
  }

  /**
   * Returns a component provided a key. This performs a deep search within the
   * component tree.
   *
   * @param {string} key - The key of the component to retrieve.
   * @param {function} fn - Called with the component once found.
   * @return {Object} - The component that is located.
   */
  getComponent(key, fn) {
    let comp = null;
    this.everyComponent((component, components) => {
      if (component.component.key === key) {
        comp = component;
        if (fn) {
          fn(component, components);
        }
        return false;
      }
    });
    return comp;
  }

  /**
   * Return a component provided the Id of the component.
   *
   * @param {string} id - The Id of the component.
   * @param {function} fn - Called with the component once it is retrieved.
   * @return {Object} - The component retrieved.
   */
  getComponentById(id, fn) {
    let comp = null;
    this.everyComponent((component, components) => {
      if (component.id === id) {
        comp = component;
        if (fn) {
          fn(component, components);
        }
        return false;
      }
    });
    return comp;
  }

  /**
   * Create a new component and add it to the components array.
   *
   * @param component
   * @param data
   */
  createComponent(component, options, data, before) {
    options = options || this.options;
    data = data || this.data;
    const comp = Components.create(component, options, data, true);
    comp.parent = this;
    comp.root = this.root || this;
    comp.build();
    comp.isBuilt = true;
    if (component.internal) {
      return comp;
    }

    if (before) {
      const index = _.findIndex(this.components, {id: before.id});
      if (index !== -1) {
        this.components.splice(index, 0, comp);
      }
      else {
        this.components.push(comp);
      }
    }
    else {
      this.components.push(comp);
    }
    return comp;
  }

  getContainer() {
    return this.element;
  }

  /**
   * Add a new component to the components array.
   *
   * @param {Object} component - The component JSON schema to add.
   * @param {HTMLElement} element - The DOM element to append this child to.
   * @param {Object} data - The submission data object to house the data for this component.
   * @param {HTMLElement} before - A DOM element to insert this element before.
   * @return {BaseComponent} - The created component instance.
   */
  addComponent(component, element, data, before, noAdd) {
    element = element || this.getContainer();
    data = data || this.data;
    const comp = this.createComponent(component, this.options, data, before ? before.component : null);
    if (noAdd) {
      return comp;
    }
    this.setHidden(comp);
    element = this.hook('addComponent', element, comp);
    if (before) {
      element.insertBefore(comp.getElement(), before);
    }
    else {
      element.appendChild(comp.getElement());
    }
    return comp;
  }

  /**
   * Remove a component from the components array.
   *
   * @param {BaseComponent} component - The component to remove from the components.
   * @param {Array<BaseComponent>} components - An array of components to remove this component from.
   */
  removeComponent(component, components) {
    components = components || this.components;
    component.destroy();
    const element = component.getElement();
    if (element && element.parentNode) {
      this.removeChildFrom(element, element.parentNode);
    }
    _.remove(components, {id: component.id});
  }

  /**
   * Removes a component provided the API key of that component.
   *
   * @param {string} key - The API key of the component to remove.
   * @param {function} fn - Called once the component is removed.
   * @return {null}
   */
  removeComponentByKey(key, fn) {
    const comp = this.getComponent(key, (component, components) => {
      this.removeComponent(component, components);
      if (fn) {
        fn(component, components);
      }
    });
    if (!comp) {
      if (fn) {
        fn(null);
      }
      return null;
    }
  }

  /**
   * Removes a component provided the Id of the component.
   *
   * @param {string} id - The Id of the component to remove.
   * @param {function} fn - Called when the component is removed.
   * @return {null}
   */
  removeComponentById(id, fn) {
    const comp = this.getComponentById(id, (component, components) => {
      this.removeComponent(component, components);
      if (fn) {
        fn(component, components);
      }
    });
    if (!comp) {
      if (fn) {
        fn(null);
      }
      return null;
    }
  }

  get componentComponents() {
    return this.component.components;
  }

  /**
   *
   * @param element
   * @param data
   */
  addComponents(element, data) {
    element = element || this.getContainer();
    data = data || this.data;
    const components = this.hook('addComponents', this.componentComponents);
    _.each(components, (component) => this.addComponent(component, element, data));
  }

  updateValue(flags) {
    let changed = false;
    _.each(this.components, (comp) => {
      changed |= comp.updateValue(flags);
    });
    return changed;
  }

  hasChanged() {
    return false;
  }

  /**
   * A more performant way to check the conditions, calculations, and validity of
   * a submission once it has been changed.
   *
   * @param data
   * @param flags
   */
  checkData(data, flags) {
    flags = flags || {};
    let valid = true;
    if (flags.noCheck) {
      return;
    }

    // Update the value.
    let changed = this.updateValue({
      noUpdateEvent: true
    });

    // Iterate through all components and check conditions, and calculate values.
    _.each(this.getComponents(), (comp) => {
      changed |= comp.calculateValue(data, {
        noUpdateEvent: true
      });
      comp.checkConditions(data);
      if (!flags.noValidate) {
        valid &= comp.checkValidity(data);
      }
    });

    // Trigger the change if the values changed.
    if (changed) {
      this.triggerChange(flags);
    }

    // Return if the value is valid.
    return valid;
  }

  checkConditions(data) {
    this.getComponents().forEach(comp => comp.checkConditions(data));
    return super.checkConditions(data);
  }

  clearOnHide(show) {
    super.clearOnHide(show);
    this.getComponents().forEach(component => component.clearOnHide(show));
  }

  /**
   * Allow components to hook into the next page trigger to perform their own logic.
   *
   * @return {*}
   */
  beforeNext() {
    const ops = [];
    _.each(this.getComponents(), (comp) => ops.push(comp.beforeNext()));
    return Promise.all(ops);
  }

  /**
   * Allow components to hook into the submission to provide their own async data.
   *
   * @return {*}
   */
  beforeSubmit() {
    const ops = [];
    _.each(this.getComponents(), (comp) => ops.push(comp.beforeSubmit()));
    return Promise.all(ops);
  }

  calculateValue(data, flags) {
    let changed = super.calculateValue(data, flags);
    _.each(this.getComponents(), (comp) => {
      changed |= comp.calculateValue(data, flags);
    });
    return changed;
  }

  isValid(data, dirty) {
    let valid = super.isValid(data, dirty);
    _.each(this.getComponents(), (comp) => {
      valid &= comp.isValid(data, dirty);
    });
    return valid;
  }

  checkValidity(data, dirty) {
    if (!checkCondition(this.component, data, this.data, this.root ? this.root._form : {}, this)) {
      this.setCustomValidity('');
      return true;
    }

    let check = super.checkValidity(data, dirty);
    _.each(this.getComponents(), (comp) => {
      check &= comp.checkValidity(data, dirty);
    });
    return check;
  }

  setPristine(pristine) {
    super.setPristine(pristine);
    _.each(this.getComponents(), (comp) => (comp.setPristine(pristine)));
  }

  destroy(all) {
    super.destroy(all);
    this.empty(this.getElement());
    this.destroyComponents();
  }

  destroyComponents() {
    const components = _.clone(this.components);
    _.each(components, (comp) => this.removeComponent(comp, this.components));
    this.components = [];
    this.hidden = [];
  }

  setCustomValidity(message, dirty) {
    super.setCustomValidity(message, dirty);
    _.each(this.getComponents(), (comp) => comp.setCustomValidity(message, dirty));
  }

  set disabled(disabled) {
    _.each(this.components, (component) => (component.disabled = disabled));
  }

  setHidden(component) {
    if (component.components && component.components.length) {
      component.hideComponents(this.hidden);
    }
    else if (component.component.hidden) {
      component.visible = false;
    }
    else {
      component.visible = (!this.hidden || !this.hidden.includes(component.key));
    }
  }

  hideComponents(hidden) {
    this.hidden = hidden;
    this.eachComponent((component) => this.setHidden(component));
  }

  get errors() {
    let errors = [];
    _.each(this.getComponents(), (comp) => {
      const compErrors = comp.errors;
      if (compErrors.length) {
        errors = errors.concat(compErrors);
      }
    });
    return errors;
  }

  get value() {
    return this.data;
  }

  getValue() {
    return this.data;
  }

  resetValue() {
    _.each(this.getComponents(), (comp) => (comp.resetValue()));
    _.unset(this.data, this.key);
    this.setPristine(true);
  }

  whenReady() {
    const promises = [];
    _.each(this.getComponents(), (component) => {
      promises.push(component.whenReady());
    });
    return Promise.all(promises);
  }

  setValue(value, flags) {
    if (!value) {
      return false;
    }
    flags = this.getFlags.apply(this, arguments);
    let changed = false;
    this.getComponents().forEach(component => {
      if (component.type === 'button') {
        return;
      }

      if (component.type === 'components') {
        changed |= component.setValue(value, flags);
      }
      else if (value && component.hasValue(value)) {
        changed |= component.setValue(_.get(value, component.key), flags);
      }
      else {
        flags.noValidate = true;
        changed |= component.setValue(component.defaultValue, flags);
      }
    });
    return changed;
  }

  setCollapseHeader(header) {
    if (this.component.collapsible) {
      this.addClass(header, 'formio-clickable');
      this.addEventListener(header, 'click', () => this.toggleCollapse());
    }
  }

  setCollapsed(element) {
    if (!this.component.collapsible) {
      return;
    }

    const container = element || this.getContainer();

    if (this.collapsed) {
      container.setAttribute('hidden', true);
      container.style.visibility = 'hidden';
    }
    else {
      container.removeAttribute('hidden');
      container.style.visibility = 'visible';
    }
  }

  toggleCollapse() {
    this.collapsed = !this.collapsed;
    this.setCollapsed();
  }
}
<|endoftext|>


<commit_before>/**
 * Copyright 2013-2015, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

let config = JSON.parse(JSON.stringify(require('.')));

Object.keys(config.rules).forEach((rule) => {
  let val = config.rules[rule];
  if (Array.isArray(val)) {
    if (val[0] === 0) {
      return;
    }
    val[0] = 2;
    config.rules[rule] = val;
    return;
  }
  if (val === 0) {
    return;
  }
  config.rules[rule] = 2;
});

module.exports = config;
<commit_msg>[eslint-config-fbjs] Fix strict config for node 4<commit_after>/**
 * Copyright 2013-2015, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

'use strict';

let config = JSON.parse(JSON.stringify(require('.')));

Object.keys(config.rules).forEach((rule) => {
  let val = config.rules[rule];
  if (Array.isArray(val)) {
    if (val[0] === 0) {
      return;
    }
    val[0] = 2;
    config.rules[rule] = val;
    return;
  }
  if (val === 0) {
    return;
  }
  config.rules[rule] = 2;
});

module.exports = config;
<|endoftext|>


<commit_before>import defaults from "lodash/defaults";
import createEntityPool from "src/lib/entityPool";

Crafty.c("PlayerSpaceship", {
  required:
    "2D, WebGL, playerShip, ColorEffects, Listener, Collision, SunBlock, " +
    "WaterSplashes, PlayerControlledShip, Acceleration, InventoryWeapons",

  init() {
    this.attr({ w: 71, h: 45 });
    this.collision([21, 13, 56, 13, 66, 32, 35, 32]);

    this.onHit("ShipSolid", hits => {
      const delta = this.motionDelta();
      let xCorrection = 0;
      let yCorrection = 0;
      let xDir = 0;
      let yDir = 0;

      hits.map(hitData => {
        let xHitCorrection = 0;
        let yHitCorrection = 0;

        if (hitData.type === "SAT") {
          xHitCorrection -= hitData.overlap * hitData.nx;
          yHitCorrection -= hitData.overlap * hitData.ny;
        } else {
          // MBR
          const { obj } = hitData;
          const d =
            typeof obj.choreographyDelta === "function"
              ? obj.choreographyDelta()
              : { x: 0, y: 0 };

          if (obj.intersect(this.x - delta.x + d.x, this.y + d.y, this.w, this.h)) {
            yHitCorrection -= delta.y - d.y;
          }

          if (obj.intersect(this.x + d.y, this.y - delta.y + d.y, this.w, this.h)) {
            xHitCorrection -= delta.x - d.x;
          }
        }

        if (xHitCorrection !== 0) {
          if (xHitCorrection > 0) {
            if (xDir < 0) {
              this._squashShip();
            }
            xDir = 1;
            xCorrection = Math.max(xCorrection, xHitCorrection);
          } else {
            if (xDir > 0) {
              this._squashShip();
            }
            xDir = -1;
            xCorrection = Math.min(xCorrection, xHitCorrection);
          }
        }

        if (yHitCorrection !== 0) {
          if (yHitCorrection < 0) {
            if (yDir > 0) {
              this._squashShip();
            }
            yDir = -1;
            return (yCorrection = Math.min(yCorrection, yHitCorrection));
          } else {
            if (yDir < 0) {
              this._squashShip();
            }
            yDir = 1;
            return (yCorrection = Math.max(yCorrection, yHitCorrection));
          }
        }
      });

      this.shift(xCorrection, yCorrection);
    });

    this.primaryWeapon = undefined;
    this.primaryWeapons = [];
    this.secondaryWeapon = undefined;
    this.superUsed = 0;
    this.weaponsEnabled = true;
    this.currentRenderedSpeed = 0;
    this.flip("X");
    this.emitCooldown = 0;
  },

  _squashShip() {
    this.trigger("Hit", { damage: 1000 });
  },

  updateMovementVisuals(rotation, dx, dy, dt) {
    if (rotation == null) {
      rotation = 0;
    }
    const velocity = Math.max(dx * (1000 / dt), 0);

    if (dy > 0) {
      this.healthPerc < 0.3 ? this.sprite(13, 5) : this.sprite(7, 4);
    } else if (dy < 0) {
      this.healthPerc < 0.3 ? this.sprite(13, 3) : this.sprite(10, 4);
    } else {
      this.healthPerc < 0.3 ? this.sprite(0, 2) : this.sprite(0, 0);
    }

    this.rotation = 0;
    this._updateFlyingSpeed(velocity, dt);
    this.rotation = rotation;
  },

  _updateFlyingSpeed(newSpeed, dt) {
    const correction = newSpeed < 30 ? newSpeed / 2 : 15 + newSpeed / 400 * 100;

    if (this.currentRenderedSpeed > correction) {
      this.currentRenderedSpeed -= 12;
    } else if (this.currentRenderedSpeed < correction) {
      this.currentRenderedSpeed += 12;
    }
    if (this.currentRenderedSpeed < 0) {
      this.currentRenderedSpeed = 0;
    }

    const w = 10 + this.currentRenderedSpeed;

    const h = Math.min(w / 3, 15);
    this.backFire.attr({
      x: this.x - w + 9,
      y: this.y + 20 - Math.floor(h / 2),
      w,
      h
    });
    this._emitTrail(dt);
  },

  _emitTrail(dt) {
    this.emitCooldown -= dt;
    if (this.emitCooldown < 0) {
      const w = this.backFire.w / 4;
      const h = 4;
      this.trailEntPool
        .get()
        .attr({
          x: this.x - w,
          dy: 0,
          y: Math.floor(this.y + 21 - Math.random() * 4),
          w,
          h,
          z: -4,
          alpha: 0.3 + Math.random() * 0.4
        })
        .tweenPromise({ alpha: 0, h: 2, dy: 2 }, 750, "easeOutQuad")
        .then(e => {
          this.trailEntPool.recycle(e);
        });
      this.emitCooldown = 30;
    }
  },

  start() {
    this.backFire = Crafty.e(
      "2D, WebGL, shipEngineFire, ColorEffects, SpriteAnimation"
    );
    this.backFire.reel("burn", 300, [[4, 5, 3, 1], [3, 0, 3, 1]]);
    this.backFire.timing = 0;
    this.backFire.animate("burn", -1);
    const w = 68;
    const h = 10;

    this.backFire.attr({
      x: this.x - w,
      y: this.y + 20 - Math.floor(h / 2),
      w,
      h,
      alpha: 0.8,
      z: this.z - 1
    });
    this.attach(this.backFire);

    const c = {};
    const basicC = {
      _red: 255,
      _green: 255,
      _blue: 255
    };
    Crafty.assignColor(this.playerColor, c);
    for (let comp of ["_red", "_green", "_blue"]) {
      const newC = (c[comp] + basicC[comp] + basicC[comp]) / 3;
      c[comp] = newC;
    }

    this.trailColor = c;
    this.backFire.colorOverride(c);
    this.trailEntPool = createEntityPool(() => {
      return Crafty.e(
        "2D, WebGL, shipEngineFire, Delta2D, TweenPromise, ViewportRelativeMotion, ColorEffects"
      )
        .colorOverride(this.trailColor)
        .viewportRelativeMotion({
          speed: 1
        });
    }, 2);

    this.addComponent("Invincible").invincibleDuration(1500);

    this.setDetectionOffset(60);
    this.onHit("Hostile", collision => {
      if (Game.paused || this.has("Invincible")) return;
      let hit = false;
      let damage = 0;
      for (let e of collision) {
        if (e.obj.damage && e.obj.damage > damage && !e.obj.hidden) {
          ({ damage } = e.obj);
          hit = true;
        }
      }
      if (hit) {
        this.trigger("Hit", { damage });
      }
    });

    this.onHit("PowerUp", collision => {
      if (Game.paused) return;
      collision
        .filter(pu => !pu.obj.pickedUp)
        .forEach(pu => this.pickUp(pu.obj));
    });

    this.bind("Hit", () => {
      this.addComponent("Invincible").invincibleDuration(2000);
      Crafty.e("Blast, Explosion").explode({
        x: this.x + this.w / 2,
        y: this.y + this.h / 2,
        radius: this.w / 3
      });
      Crafty.audio.play("explosion");
      Crafty("ScrollWall")
        .get(0)
        .addTrauma(0.3);
    });

    this.bind("Die", () => {
      Crafty.e("Blast, Explosion").explode({
        x: this.x + this.w / 2,
        y: this.y + this.h / 2,
        radius: this.w
      });
      Crafty.audio.play("explosion");
      // this trauma is added upon the 'hit'
      Crafty("ScrollWall")
        .get(0)
        .addTrauma(0.3);
      this.trigger("Destroyed", this);
    });

    this.bind("CameraPan", ({ dx, dy }) => this.shift(-dx, -dy));

    this.bind("GameLoop", function(fd) {
      const motionX = (this.vx + this._currentSpeed.x) / 1000.0 * fd.dt;
      const motionY = (this.vy + this._currentSpeed.y) / 1000.0 * fd.dt;

      if (this.has("AnimationMode")) {
        if (this._choreography && this._choreography.length === 0) {
          this.updateMovementVisuals(this.rotation, motionX, motionY, fd.dt);
        }
        return;
      }

      this.updateAcceleration();

      const r = this.rotation;
      const newR = motionY;
      let nr = r;
      if (r < newR) {
        nr += 1;
      } else if (r > newR) {
        nr -= 1;
      }

      this.rotation = nr;
      this.updateMovementVisuals(this.rotation, motionX, motionY, fd.dt);
    });

    return this;
  },

  forcedSpeed(speed, options = {}) {
    this.targetSpeed(speed, options);
  },

  shoot(onOff) {
    if (!this.weaponsEnabled) {
      return;
    }

    if (this.primaryWeapon != null) {
      this.primaryWeapon.shoot(onOff);
    }

    if (this.secondaryWeapon != null) {
      this.secondaryWeapon.shoot(onOff);
    }
  },

  switchWeapon(onOff) {
    if (!onOff) {
      return;
    }
    const nextWeapon = (this.currentPrimary + 1) % this.primaryWeapons.length;
    if (this.primaryWeapon != null) {
      this.primaryWeapon.uninstall();
    }
    this.primaryWeapon = this.primaryWeapons[nextWeapon];
    this.primaryWeapon.install(this);
    this.currentPrimary = nextWeapon;
  },

  superWeapon(onOff) {
    if (!onOff) {
      return;
    }
    this.superUsed += 1;
  },

  pickUp(powerUp) {
    const contents = powerUp.settings.contains;
    if (this.installItem(powerUp.settings)) {
      Crafty.audio.play("powerup");
      this.trigger("PowerUp", powerUp.settings);
      powerUp.pickup();
    }
  },

  clearItems() {
    if (this.primaryWeapon != null) {
      this.primaryWeapon.uninstall();
    }
    this.primaryWeapons.forEach(w => w.destroy());
    this.primaryWeapons = [];
    this.items = [];
  },

  _installPrimary(componentName) {
    const text = {
      damage: "Damage",
      rapid: "RapidFire",
      aim: "AimAssist",
      speed: "BulletSpeed",

      damageb: "Damage",
      rapidb: "RapidFire",
      aimb: "AimAssist",
      speedb: "BulletSpeed"
    };
    const weapon = Crafty.e(componentName);
    weapon.install(this);
    if (this.primaryWeapon != null) {
      this.primaryWeapon.uninstall();
    }
    this.primaryWeapon = weapon;
    this.listenTo(weapon, "levelUp", info => {
      return this.scoreText(`${text[info.aspect]} +${info.level}`);
    });
    this.listenTo(weapon, "boost", info => {
      return this.scoreText(`${text[info.aspect]} Boost!`);
    });
    this.listenTo(weapon, "boostExpired", info => {
      return this.scoreText(`${text[info.aspect]} Boost expired`, {
        positive: false
      });
    });

    this.primaryWeapons.push(weapon);
    this.currentPrimary = this.primaryWeapons.length - 1;
  },

  hasItem(item) {
    if (this.items == null) {
      return false;
    }
    return this.items.find(inventory => inventory.contains === item);
  },

  scoreText(text, settings = {}) {
    settings = defaults(settings, {
      positive: true,
      location: { x: this.x, y: this.y },
      attach: true,
      duration: 1000,
      distance: 70,
      delay: 400
    });

    let location =
      typeof settings.location === "function" ? settings.location() : undefined;
    if (location) {
      location = {
        x: location.x,
        y: location.y
      };
    }

    if (location == null) {
      ({ location } = settings);
    }

    const t = Crafty.e("Text, DOM, 2D, Tween, Delay")
      .textColor(settings.positive ? "#DDD" : "#F00")
      .text(text)
      .attr({
        x: location.x,
        y: location.y - 10,
        z: 990,
        w: 250,
        alpha: 0.75
      })
      .textFont({
        size: "10px",
        weight: "bold",
        family: "Press Start 2P"
      });
    if (settings.attach) {
      this.attach(t);
    }
    t.delay(() => {
      if (settings.attach) {
        this.detach(t);
      }
      t.tween(
        { rotation: 0, y: t.y - settings.distance, alpha: 0.5 },
        settings.duration,
        "easeInQuad"
      );
      t.one("TweenEnd", () => t.destroy());
    }, settings.delay);
  },

  remove() {
    this.trailEntPool.clean();
  }
});
<commit_msg>Prettier and cleanup<commit_after>import defaults from "lodash/defaults";
import createEntityPool from "src/lib/entityPool";

Crafty.c("PlayerSpaceship", {
  required:
    "2D, WebGL, playerShip, ColorEffects, Listener, Collision, SunBlock, " +
    "WaterSplashes, PlayerControlledShip, Acceleration, InventoryWeapons",

  init() {
    this.attr({ w: 71, h: 45 });
    this.collision([21, 13, 56, 13, 66, 32, 35, 32]);

    this.onHit("ShipSolid", hits => {
      const delta = this.motionDelta();
      let xCorrection = 0;
      let yCorrection = 0;
      let xDir = 0;
      let yDir = 0;

      hits.map(hitData => {
        let xHitCorrection = 0;
        let yHitCorrection = 0;

        if (hitData.type === "SAT") {
          xHitCorrection -= hitData.overlap * hitData.nx;
          yHitCorrection -= hitData.overlap * hitData.ny;
        } else {
          // MBR
          const { obj } = hitData;
          const d =
            typeof obj.choreographyDelta === "function"
              ? obj.choreographyDelta()
              : { x: 0, y: 0 };

          if (
            obj.intersect(this.x - delta.x + d.x, this.y + d.y, this.w, this.h)
          ) {
            yHitCorrection -= delta.y - d.y;
          }

          if (
            obj.intersect(this.x + d.y, this.y - delta.y + d.y, this.w, this.h)
          ) {
            xHitCorrection -= delta.x - d.x;
          }
        }

        if (xHitCorrection !== 0) {
          if (xHitCorrection > 0) {
            if (xDir < 0) {
              this._squashShip();
            }
            xDir = 1;
            xCorrection = Math.max(xCorrection, xHitCorrection);
          } else {
            if (xDir > 0) {
              this._squashShip();
            }
            xDir = -1;
            xCorrection = Math.min(xCorrection, xHitCorrection);
          }
        }

        if (yHitCorrection !== 0) {
          if (yHitCorrection < 0) {
            if (yDir > 0) {
              this._squashShip();
            }
            yDir = -1;
            return (yCorrection = Math.min(yCorrection, yHitCorrection));
          } else {
            if (yDir < 0) {
              this._squashShip();
            }
            yDir = 1;
            return (yCorrection = Math.max(yCorrection, yHitCorrection));
          }
        }
      });

      this.shift(xCorrection, yCorrection);
    });

    this.primaryWeapon = undefined;
    this.primaryWeapons = [];
    this.secondaryWeapon = undefined;
    this.superUsed = 0;
    this.weaponsEnabled = true;
    this.currentRenderedSpeed = 0;
    this.flip("X");
    this.emitCooldown = 0;
  },

  _squashShip() {
    this.trigger("Hit", { damage: 1000 });
  },

  updateMovementVisuals(rotation, dx, dy, dt) {
    if (rotation == null) {
      rotation = 0;
    }
    const velocity = Math.max(dx * (1000 / dt), 0);

    if (dy > 0) {
      this.healthPerc < 0.3 ? this.sprite(13, 5) : this.sprite(7, 4);
    } else if (dy < 0) {
      this.healthPerc < 0.3 ? this.sprite(13, 3) : this.sprite(10, 4);
    } else {
      this.healthPerc < 0.3 ? this.sprite(0, 2) : this.sprite(0, 0);
    }

    this.rotation = 0;
    this._updateFlyingSpeed(velocity, dt);
    this.rotation = rotation;
  },

  _updateFlyingSpeed(newSpeed, dt) {
    const correction = newSpeed < 30 ? newSpeed / 2 : 15 + newSpeed / 400 * 100;

    if (this.currentRenderedSpeed > correction) {
      this.currentRenderedSpeed -= 12;
    } else if (this.currentRenderedSpeed < correction) {
      this.currentRenderedSpeed += 12;
    }
    if (this.currentRenderedSpeed < 0) {
      this.currentRenderedSpeed = 0;
    }

    const w = 10 + this.currentRenderedSpeed;

    const h = Math.min(w / 3, 15);
    this.backFire.attr({
      x: this.x - w + 9,
      y: this.y + 20 - Math.floor(h / 2),
      w,
      h
    });
    this._emitTrail(dt);
  },

  _emitTrail(dt) {
    this.emitCooldown -= dt;
    if (this.emitCooldown < 0) {
      const w = this.backFire.w / 4;
      const h = 4;
      this.trailEntPool
        .get()
        .attr({
          x: this.x - w,
          dy: 0,
          y: Math.floor(this.y + 21 - Math.random() * 4),
          w,
          h,
          z: -4,
          alpha: 0.3 + Math.random() * 0.4
        })
        .tweenPromise({ alpha: 0, h: 2, dy: 2 }, 750, "easeOutQuad")
        .then(e => {
          this.trailEntPool.recycle(e);
        });
      this.emitCooldown = 30;
    }
  },

  start() {
    this.backFire = Crafty.e(
      "2D, WebGL, shipEngineFire, ColorEffects, SpriteAnimation"
    );
    this.backFire.reel("burn", 300, [[4, 5, 3, 1], [3, 0, 3, 1]]);
    this.backFire.timing = 0;
    this.backFire.animate("burn", -1);
    const w = 68;
    const h = 10;

    this.backFire.attr({
      x: this.x - w,
      y: this.y + 20 - Math.floor(h / 2),
      w,
      h,
      alpha: 0.8,
      z: this.z - 1
    });
    this.attach(this.backFire);

    const c = {};
    const basicC = {
      _red: 255,
      _green: 255,
      _blue: 255
    };
    Crafty.assignColor(this.playerColor, c);
    for (let comp of ["_red", "_green", "_blue"]) {
      const newC = (c[comp] + basicC[comp] + basicC[comp]) / 3;
      c[comp] = newC;
    }

    this.trailColor = c;
    this.backFire.colorOverride(c);
    this.trailEntPool = createEntityPool(() => {
      return Crafty.e(
        "2D, WebGL, shipEngineFire, Delta2D, TweenPromise, ViewportRelativeMotion, ColorEffects"
      )
        .colorOverride(this.trailColor)
        .viewportRelativeMotion({
          speed: 1
        });
    }, 2);

    this.addComponent("Invincible").invincibleDuration(1500);

    this.setDetectionOffset(60);
    this.onHit("Hostile", collision => {
      if (Game.paused || this.has("Invincible")) return;
      let hit = false;
      let damage = 0;
      for (let e of collision) {
        if (e.obj.damage && e.obj.damage > damage && !e.obj.hidden) {
          ({ damage } = e.obj);
          hit = true;
        }
      }
      if (hit) {
        this.trigger("Hit", { damage });
      }
    });

    this.onHit("PowerUp", collision => {
      if (Game.paused) return;
      collision
        .filter(pu => !pu.obj.pickedUp)
        .forEach(pu => this.pickUp(pu.obj));
    });

    this.bind("Hit", () => {
      this.addComponent("Invincible").invincibleDuration(2000);
      Crafty.e("Blast, Explosion").explode({
        x: this.x + this.w / 2,
        y: this.y + this.h / 2,
        radius: this.w / 3
      });
      Crafty.audio.play("explosion");
      Crafty("ScrollWall")
        .get(0)
        .addTrauma(0.3);
    });

    this.bind("Die", () => {
      Crafty.e("Blast, Explosion").explode({
        x: this.x + this.w / 2,
        y: this.y + this.h / 2,
        radius: this.w
      });
      Crafty.audio.play("explosion");
      // this trauma is added upon the 'hit'
      Crafty("ScrollWall")
        .get(0)
        .addTrauma(0.3);
      this.trigger("Destroyed", this);
    });

    this.bind("CameraPan", ({ dx, dy }) => this.shift(-dx, -dy));

    this.bind("GameLoop", function(fd) {
      const motionX = (this.vx + this._currentSpeed.x) / 1000.0 * fd.dt;
      const motionY = (this.vy + this._currentSpeed.y) / 1000.0 * fd.dt;

      if (this.has("AnimationMode")) {
        if (this._choreography && this._choreography.length === 0) {
          this.updateMovementVisuals(this.rotation, motionX, motionY, fd.dt);
        }
        return;
      }

      this.updateAcceleration();

      const r = this.rotation;
      const newR = motionY;
      let nr = r;
      if (r < newR) {
        nr += 1;
      } else if (r > newR) {
        nr -= 1;
      }

      this.rotation = nr;
      this.updateMovementVisuals(this.rotation, motionX, motionY, fd.dt);
    });

    return this;
  },

  forcedSpeed(speed, options = {}) {
    this.targetSpeed(speed, options);
  },

  shoot(onOff) {
    if (!this.weaponsEnabled) {
      return;
    }

    if (this.primaryWeapon != null) {
      this.primaryWeapon.shoot(onOff);
    }

    if (this.secondaryWeapon != null) {
      this.secondaryWeapon.shoot(onOff);
    }
  },

  switchWeapon(onOff) {
    if (!onOff) {
      return;
    }
    const nextWeapon = (this.currentPrimary + 1) % this.primaryWeapons.length;
    if (this.primaryWeapon != null) {
      this.primaryWeapon.uninstall();
    }
    this.primaryWeapon = this.primaryWeapons[nextWeapon];
    this.primaryWeapon.install(this);
    this.currentPrimary = nextWeapon;
  },

  superWeapon(onOff) {
    if (!onOff) {
      return;
    }
    this.superUsed += 1;
  },

  pickUp(powerUp) {
    if (!this.installItem(powerUp.settings)) {
      return;
    }
    Crafty.audio.play("powerup");
    this.trigger("PowerUp", powerUp.settings);
    powerUp.pickup();
  },

  clearItems() {
    if (this.primaryWeapon != null) {
      this.primaryWeapon.uninstall();
    }
    this.primaryWeapons.forEach(w => w.destroy());
    this.primaryWeapons = [];
    this.items = [];
  },

  _installPrimary(componentName) {
    const text = {
      damage: "Damage",
      rapid: "RapidFire",
      aim: "AimAssist",
      speed: "BulletSpeed",

      damageb: "Damage",
      rapidb: "RapidFire",
      aimb: "AimAssist",
      speedb: "BulletSpeed"
    };
    const weapon = Crafty.e(componentName);
    weapon.install(this);
    if (this.primaryWeapon != null) {
      this.primaryWeapon.uninstall();
    }
    this.primaryWeapon = weapon;
    this.listenTo(weapon, "levelUp", info => {
      return this.scoreText(`${text[info.aspect]} +${info.level}`);
    });
    this.listenTo(weapon, "boost", info => {
      return this.scoreText(`${text[info.aspect]} Boost!`);
    });
    this.listenTo(weapon, "boostExpired", info => {
      return this.scoreText(`${text[info.aspect]} Boost expired`, {
        positive: false
      });
    });

    this.primaryWeapons.push(weapon);
    this.currentPrimary = this.primaryWeapons.length - 1;
  },

  hasItem(item) {
    if (this.items == null) {
      return false;
    }
    return this.items.find(inventory => inventory.contains === item);
  },

  scoreText(text, settings = {}) {
    settings = defaults(settings, {
      positive: true,
      location: { x: this.x, y: this.y },
      attach: true,
      duration: 1000,
      distance: 70,
      delay: 400
    });

    let location =
      typeof settings.location === "function" ? settings.location() : undefined;
    if (location) {
      location = {
        x: location.x,
        y: location.y
      };
    }

    if (location == null) {
      ({ location } = settings);
    }

    const t = Crafty.e("Text, DOM, 2D, Tween, Delay")
      .textColor(settings.positive ? "#DDD" : "#F00")
      .text(text)
      .attr({
        x: location.x,
        y: location.y - 10,
        z: 990,
        w: 250,
        alpha: 0.75
      })
      .textFont({
        size: "10px",
        weight: "bold",
        family: "Press Start 2P"
      });
    if (settings.attach) {
      this.attach(t);
    }
    t.delay(() => {
      if (settings.attach) {
        this.detach(t);
      }
      t.tween(
        { rotation: 0, y: t.y - settings.distance, alpha: 0.5 },
        settings.duration,
        "easeInQuad"
      );
      t.one("TweenEnd", () => t.destroy());
    }, settings.delay);
  },

  remove() {
    this.trailEntPool.clean();
  }
});
<|endoftext|>


<commit_before>'use strict';

/**
 * Import plugins
 */
var gulp = require('gulp'),
    $ = require('gulp-load-plugins')(),
    browserSync = require('browser-sync'),
    reload = browserSync.reload,
    runSequence = require('run-sequence'),
    argv = require('yargs').argv,
    del = require('del');

/**
 * Init project
 */
gulp.task('init', function() {
  gulp.src('bower_components/bootstrap-sass/assets/stylesheets/bootstrap/_variables.scss')
    .pipe($.rename('bootstrap-variables.scss'))
    .pipe(gulp.dest('assets/sass'))
});

/**
 * Build vendors dependencies
 */
gulp.task('vendors', function() {

  /**
   * CSS VENDORS
   */
  gulp.src([
      ''
    ])
    .pipe($.concat('vendors.css'))
    .pipe($.minifyCss())
    .pipe($.size({title: "CSS VENDORS", showFiles: true}))
    .pipe(gulp.dest('build/css'));

  /**
   * JS VENDORS
   * (with jQuery and Bootstrap dependencies first)
   */

  gulp.src([
      'bower_components/jquery/dist/jquery.js',
      'bower_components/bootstrap-sass/assets/javascripts/bootstrap/affix.js',
      'bower_components/bootstrap-sass/assets/javascripts/bootstrap/alert.js',
      'bower_components/bootstrap-sass/assets/javascripts/bootstrap/button.js',
      'bower_components/bootstrap-sass/assets/javascripts/bootstrap/carousel.js',
      'bower_components/bootstrap-sass/assets/javascripts/bootstrap/collapse.js',
      'bower_components/bootstrap-sass/assets/javascripts/bootstrap/dropdown.js',
      'bower_components/bootstrap-sass/assets/javascripts/bootstrap/modal.js',
      'bower_components/bootstrap-sass/assets/javascripts/bootstrap/tooltip.js',
      'bower_components/bootstrap-sass/assets/javascripts/bootstrap/popover.js',
      'bower_components/bootstrap-sass/assets/javascripts/bootstrap/scrollspy.js',
      'bower_components/bootstrap-sass/assets/javascripts/bootstrap/tab.js',
      'bower_components/bootstrap-sass/assets/javascripts/bootstrap/transition.js'
    ])
    .pipe($.concat('vendors.min.js'))
    .pipe($.uglify())
    .pipe($.size({title: "JS VENDORS", showFiles: true}))
    .pipe(gulp.dest('build/js'));

  /**
   * FONTS SOURCES
   * Important to add the bootstrap fonts to avoid issues with the fonts include path
   */
  gulp.src([
      'bower_components/bootstrap-sass/assets/fonts/bootstrap/*',
      'assets/fonts/*'
    ])
    .pipe($.size({title: "FONTS"}))
    .pipe(gulp.dest('build/fonts'));

  /**
   * POLYFILLS SOURCES
   * Various polyfills required for old IE
   */
  gulp.src([
      'bower_components/html5shiv/dist/html5shiv.js',
      'bower_components/respond/dest/respond.src.js'
    ])
    .pipe($.concat('polyfills.min.js'))
    .pipe($.uglify())
    .pipe($.size({title: "POLYFILLS", showFiles: true}))
    .pipe(gulp.dest('build/js'));
});

/**
 * Copy images
 */
gulp.task('img', function() {
  gulp.src([
      'assets/img/**/*'
    ])
    .pipe($.size({title: "IMAGES"}))
    .pipe(gulp.dest('build/img'));
});

/**
 * Build styles from SCSS files
 * With error reporting on compiling (so that there's no crash)
 */
gulp.task('styles', function() {
  if (argv.production) { console.log('[styles] Production mode' ); }
  else { console.log('[styles] Dev mode') }

  return gulp.src('assets/sass/main.scss')
    .pipe($.if(!argv.production, $.sourcemaps.init()))
    .pipe($.sass({
      outputStyle: 'nested', // libsass doesn't support expanded yet
      precision: 10,
      includePaths: ['.']
    }))
    .on('error', $.notify.onError({
      title: function(error) {
        return error.message
      },
      message: function(error) {
        return error.fileName + ':' + error.lineNumber
      }
    }))
    .pipe($.postcss([
      require('autoprefixer-core')({
        browsers: ['last 2 versions', 'safari 5', 'ie 8', 'ie 9', 'ff 27', 'opera 12.1'],
        options: {
          map: true
        }
      })
    ]))
    .pipe($.if(!argv.production, $.sourcemaps.write()))
    .pipe($.if(argv.production, $.minifyCss()))
    .pipe($.size({title: "STYLES", showFiles: true}))
    .pipe(gulp.dest('build/css'));
});

/**
 * Build styles from SCSS files
 * Only for STYLEGUIDE styles
 */
gulp.task('styleguide-styles', function() {
  return gulp.src('assets/sass/styleguide.scss')
    .pipe($.sass({
      outputStyle: 'nested', // libsass doesn't support expanded yet
      precision: 10,
      includePaths: ['.']
    }))
    .on('error', $.notify.onError({
      title: function(error) {
        return error.message
      },
      message: function(error) {
        return error.fileName + ':' + error.lineNumber
      }
    }))
    .pipe($.postcss([
      require('autoprefixer-core')({
        browsers: ['last 2 versions', 'safari 5', 'ie 8', 'ie 9', 'ff 27', 'opera 12.1'],
        options: {
          map: true
        }
      })
    ]))
    .pipe($.minifyCss())
    .pipe($.size({title: "STYLEGUIDE STYLES", showFiles: true}))
    .pipe(gulp.dest('build/css'));
});

/**
 * Build JS
 * With error reporting on compiling (so that there's no crash)
 * And jshint check to highlight errors as we go.
 */
gulp.task('scripts', function() {
  return gulp.src('assets/js/*.js')
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.concat('main.js'))
    .pipe(gulp.dest('build/js'))
    .pipe($.rename({ suffix: '.min' }))
    .pipe($.uglify())
    .pipe($.size({title: "JS SCRIPTS", showFiles: true}))
    .pipe(gulp.dest('build/js'));
});

/**
 * Build Hologram Styleguide
 */
gulp.task('styleguide', function () {
  return gulp.src('hologram_config.yml')
    .pipe($.hologram());
});

<% if (twig) { %>
/**
 * Compile TWIG example pages
 */

gulp.task('twig', function () {
    return gulp.src('assets/pages/*.twig')
        .pipe($.twig())
        .pipe(gulp.dest('styleguide/pages'));
});
<% } %>

/**
 * Clean output directories
 */
gulp.task('clean', del.bind(null, ['build', 'styleguide']));

/**
 * Serve
 */
gulp.task('serve', ['default'], function () {
  browserSync({
    server: {
      baseDir: ['styleguide'],
    },
    open: false
  });
  gulp.watch(['assets/sass/**/*.scss'], function() {
    runSequence('styles', 'styleguide', reload);
  });
  gulp.watch(['assets/img/**/*'], function() {
    runSequence('img', 'styleguide', reload);
  });
  gulp.watch(['assets/js/**/*.js'], function() {
    runSequence('scripts', reload);
  });
  <% if (twig) { %>
  gulp.watch(['assets/pages/**/*'], function() {
    // clean folder before compiling
    del.bind(null, ['styleguide/pages'])
    runSequence('twig', reload);
  });
  <% } %>
});

/**
 * Deploy to GH pages
 */

gulp.task('deploy', function () {
  gulp.src("styleguide/**/*")
    .pipe($.ghPages());
});

/**
 * Task to build assets on production server
 */
gulp.task('build',['clean'], function() {
    argv.production = true;
    runSequence('vendors', 'styles', 'img', 'scripts');
});

/**
 * Default task
 */
gulp.task('default', ['clean'], function(cb) {
  var styleguide_styles = argv.production ? '' : 'styleguide-styles';
  runSequence(['vendors', 'styles', 'img', 'scripts'<% if (twig) { %>, 'twig'<% } %>], 'styleguide', styleguide_styles, cb);
});

<commit_msg>huge changes to gulp tasks<commit_after>'use strict';

/**
 * Import plugins
 */
var gulp = require('gulp'),
    $ = require('gulp-load-plugins')(),
    browserSync = require('browser-sync'),
    reload = browserSync.reload,
    runSequence = require('run-sequence'),
    argv = require('yargs').argv,
    del = require('del');

/**
 * Init project
 */
gulp.task('init', function() {
  return gulp.src('bower_components/bootstrap-sass/assets/stylesheets/bootstrap/_variables.scss')
    .pipe($.rename('bootstrap-variables.scss'))
    .pipe(gulp.dest('assets/sass'))
});

/**
 * Build vendors dependencies
 */
gulp.task('vendors', function() {
  return gulp.start('css-vendors', 'js-vendors', 'fonts', 'polyfills');
});

/**
 * CSS VENDORS
 */
gulp.task('css-vendors', function() {
  return gulp.src([
      ''
    ])
    .pipe($.concat('vendors.css'))
    .pipe($.minifyCss())
    .pipe($.size({title: "CSS VENDORS", showFiles: true}))
    .pipe(gulp.dest('build/css'));
});

/**
 * JS VENDORS
 * (with jQuery and Bootstrap dependencies first)
 */

gulp.task('js-vendors', function() {
  return gulp.src([
      'bower_components/jquery/dist/jquery.js',
      'bower_components/bootstrap-sass/assets/javascripts/bootstrap/affix.js',
      'bower_components/bootstrap-sass/assets/javascripts/bootstrap/alert.js',
      'bower_components/bootstrap-sass/assets/javascripts/bootstrap/button.js',
      'bower_components/bootstrap-sass/assets/javascripts/bootstrap/carousel.js',
      'bower_components/bootstrap-sass/assets/javascripts/bootstrap/collapse.js',
      'bower_components/bootstrap-sass/assets/javascripts/bootstrap/dropdown.js',
      'bower_components/bootstrap-sass/assets/javascripts/bootstrap/modal.js',
      'bower_components/bootstrap-sass/assets/javascripts/bootstrap/tooltip.js',
      'bower_components/bootstrap-sass/assets/javascripts/bootstrap/popover.js',
      'bower_components/bootstrap-sass/assets/javascripts/bootstrap/scrollspy.js',
      'bower_components/bootstrap-sass/assets/javascripts/bootstrap/tab.js',
      'bower_components/bootstrap-sass/assets/javascripts/bootstrap/transition.js'
    ])
    .pipe($.concat('vendors.min.js'))
    .pipe($.uglify())
    .pipe($.size({title: "JS VENDORS", showFiles: true}))
    .pipe(gulp.dest('build/js'));
});

/**
 * FONTS SOURCES
 * Important to add the bootstrap fonts to avoid issues with the fonts include path
 */
gulp.task('fonts', function() {
  return gulp.src([
      'bower_components/bootstrap-sass/assets/fonts/bootstrap/*',
      'assets/fonts/*'
    ])
    .pipe($.size({title: "FONTS"}))
    .pipe(gulp.dest('build/fonts'));
});

/**
 * POLYFILLS SOURCES
 * Various polyfills required for old IE
 */
gulp.task('polyfills', function() {
  return gulp.src([
      'bower_components/html5shiv/dist/html5shiv.js',
      'bower_components/respond/dest/respond.src.js'
    ])
    .pipe($.concat('polyfills.min.js'))
    .pipe($.uglify())
    .pipe($.size({title: "POLYFILLS", showFiles: true}))
    .pipe(gulp.dest('build/js'));
});

/**
 * Copy images
 */
gulp.task('img', function() {
  return gulp.src([
      'assets/img/**/*'
    ])
    .pipe($.size({title: "IMAGES"}))
    .pipe(gulp.dest('build/img'));
});

/**
 * Build styles from SCSS files
 * With error reporting on compiling (so that there's no crash)
 */
gulp.task('styles', function() {
  if (argv.production) { console.log('[styles] Production mode' ); }
  else { console.log('[styles] Dev mode') }

  return gulp.src('assets/sass/main.scss')
    .pipe($.if(!argv.production, $.sourcemaps.init()))
    .pipe($.sass({
      outputStyle: 'nested', // libsass doesn't support expanded yet
      precision: 10,
      includePaths: ['.']
    }))
    .on('error', $.notify.onError({
      title: function(error) {
        return error.message
      },
      message: function(error) {
        return error.fileName + ':' + error.lineNumber
      }
    }))
    .pipe($.postcss([
      require('autoprefixer-core')({
        browsers: ['last 2 versions', 'safari 5', 'ie 8', 'ie 9', 'ff 27', 'opera 12.1'],
        options: {
          map: true
        }
      })
    ]))
    .pipe($.if(!argv.production, $.sourcemaps.write()))
    .pipe($.if(argv.production, $.minifyCss()))
    .pipe($.size({title: "STYLES", showFiles: true}))
    .pipe(gulp.dest('build/css'));
});

/**
 * Build styles from SCSS files
 * Only for STYLEGUIDE styles
 */
gulp.task('styleguide-styles', function() {
  return gulp.src('assets/sass/styleguide.scss')
    .pipe($.sass({
      outputStyle: 'nested', // libsass doesn't support expanded yet
      precision: 10,
      includePaths: ['.']
    }))
    .on('error', $.notify.onError({
      title: function(error) {
        return error.message
      },
      message: function(error) {
        return error.fileName + ':' + error.lineNumber
      }
    }))
    .pipe($.postcss([
      require('autoprefixer-core')({
        browsers: ['last 2 versions', 'safari 5', 'ie 8', 'ie 9', 'ff 27', 'opera 12.1'],
        options: {
          map: true
        }
      })
    ]))
    .pipe($.minifyCss())
    .pipe($.size({title: "STYLEGUIDE STYLES", showFiles: true}))
    .pipe(gulp.dest('styleguide/css'));
});

/**
 * Build JS
 * With error reporting on compiling (so that there's no crash)
 * And jshint check to highlight errors as we go.
 */
gulp.task('scripts', function() {
  return gulp.src('assets/js/*.js')
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.concat('main.js'))
    .pipe(gulp.dest('build/js'))
    .pipe($.rename({ suffix: '.min' }))
    .pipe($.uglify())
    .pipe($.size({title: "JS SCRIPTS", showFiles: true}))
    .pipe(gulp.dest('build/js'));
});

/**
 * Build Hologram Styleguide
 */
gulp.task('styleguide', function () {
  return gulp.src('hologram_config.yml')
    .pipe($.hologram());
});

<% if (twig) { %>/**
 * Compile TWIG example pages
 */

gulp.task('twig', function () {
    return gulp.src('assets/pages/*.twig')
        .pipe($.twig())
        .pipe(gulp.dest('styleguide/pages'));
});<% } %>

/**
 * Clean output directories
 */
 gulp.task('clean', del.bind(null, ['build', 'styleguide']));

 /**
  * Serve
  */
gulp.task('serve', ['default'], function () {
  browserSync({
    server: {
      baseDir: ['styleguide'],
    },
    open: false
  });
  gulp.watch(['assets/sass/**/*.scss'], function() {
    runSequence('styles', 'styleguide-styles', 'styleguide', reload);
  });
  gulp.watch(['assets/img/**/*'], function() {
    runSequence('img', 'styleguide', reload);
  });
  gulp.watch(['assets/js/**/*.js'], function() {
    runSequence('scripts', reload);
  });<% if (twig) { %>
  gulp.watch(['assets/pages/**/*'], function() {
    // clean folder before compiling
    del.bind(null, ['styleguide/pages'])
    runSequence('twig', reload);
  });<% } %>
});

/**
 * Deploy to GH pages
 */

gulp.task('deploy', function () {
  return gulp.src("styleguide/**/*")
    .pipe($.ghPages());
});

/**
 * Task to build assets on production server
 */
gulp.task('build',['clean'], function() {
  argv.production = true;
  return gulp.start('vendors', 'styles', 'img', 'scripts');
});

/**
 * Default task
 */
gulp.task('default', ['clean'], function(cb) {
  var styleguide_styles = argv.production ? '' : 'styleguide-styles';
  runSequence(['js-vendors', 'css-vendors', 'polyfills', 'fonts', 'styles', 'img', 'scripts'<% if (twig) { %>, 'twig'<% } %>], 'styleguide', styleguide_styles, cb);
});

<|endoftext|>


<commit_before>exports.config = {

  /*specs: ['e2e/*.js'],

  capabilities: {
    browserName: 'chrome',
    shardTestFiles: true,
    maxInstances: 2
  },*/

	multiCapabilities: [
    /* TINY DEVICES */
    {
  	   'browserName': 'chrome',
  	   'chromeOptions' : {
  	    args: ['--window-size=320,800']
  	   },

  	   specs: ['e2e/scrolling/scrollingMobileTabletSpec.js']
  	},
    /* SMALL DEVICES */
    {
       'browserName': 'chrome',
       'chromeOptions' : {
        args: ['--window-size=768,800']
       },

       specs: ['e2e/scrolling/scrollingMobileTabletSpec.js']
    },
    /* MEDIUM DEVICES */
    {
       'browserName': 'chrome',
       'chromeOptions' : {
        args: ['--window-size=1280,800']
       },

       specs: ['e2e/scrolling/scrollingCommonSpec.js', 'e2e/scrolling/scrollingDesktopSpec.js']
    }
  ],

  chromeDriver: '../node_modules/protractor/selenium/chromedriver',

  baseUrl: 'http://localhost:8080/',

  framework: 'jasmine',

};<commit_msg>Renaming sections a fixing tests<commit_after>exports.config = {

  /*specs: ['e2e/*.js'],

  capabilities: {
    browserName: 'chrome',
    shardTestFiles: true,
    maxInstances: 2
  },*/

	multiCapabilities: [
    /* TINY DEVICES */
    {
  	   'browserName': 'chrome',
  	   'chromeOptions' : {
  	    args: ['--window-size=320,800']
  	   },

  	   specs: ['e2e/onload/onloadCommonSpec.js', 'e2e/onload/onloadMobileTabletSpec.js', 'e2e/footer/footerMobileTabletSpec.js', 'e2e/scrolling/scrollingCommonSpec.js', 'e2e/scrolling/scrollingMobileTabletSpec.js']
  	},
    /* SMALL DEVICES */
    {
       'browserName': 'chrome',
       'chromeOptions' : {
        args: ['--window-size=768,800']
       },

       specs: ['e2e/onload/onloadCommonSpec.js', 'e2e/onload/onloadMobileTabletSpec.js', 'e2e/footer/footerMobileTabletSpec.js', 'e2e/scrolling/scrollingCommonSpec.js', 'e2e/scrolling/scrollingMobileTabletSpec.js']
    },
    /* MEDIUM DEVICES */
    {
       'browserName': 'chrome',
       'chromeOptions' : {
        args: ['--window-size=1280,800']
       },

       specs: ['e2e/onload/onloadCommonSpec.js', 'e2e/onload/onloadDesktopSpec.js', 'e2e/footer/footerDesktopSpec.js', 'e2e/scrolling/scrollingCommonSpec.js', 'e2e/scrolling/scrollingDesktopSpec.js']
    }
  ],

  chromeDriver: '../node_modules/protractor/selenium/chromedriver',

  baseUrl: 'http://localhost:8080/',

  framework: 'jasmine',

};<|endoftext|>


<commit_before>'use babel'

export default class Autocomplete {
  constructor() {

  }
  provideAutocomplete(text, position) {
    return []
  }
  activate() {

  }
  dispose() {

  }
}
<commit_msg>:new: Figure out active view from position<commit_after>'use babel'

import {transformFile, pointWithinRange, getObjectAtPosition} from './helpers'
import Point from 'atom-text-buffer-point'

export default class Autocomplete {
  constructor() {

  }
  provideAutocomplete(text, position) {
    const point = Point.fromObject(position)

    let views = {}
    transformFile(text, {
      onMeta: function(meta) {
        views = meta.views
      }
    })

    const activeView = getObjectAtPosition(views, point)
    console.log(activeView)
    return []
  }
  activate() {

  }
  dispose() {

  }
}
<|endoftext|>


<commit_before>'use strict';

require('../globals');

var vlfield = require('../field');

module.exports = addSortTransform;

// adds new transforms that produce sorted fields
function addSortTransform(data, encoding, stats, opt) {
  // jshint unused:false

  var datasetMapping = {};
  var counter = 0;

  encoding.forEach(function(field, encType) {
    var sortBy = encoding.sort(encType, stats);
    if (sortBy.length > 0) {
      var fields = sortBy.map(function(d) {
        return {
          op: d.aggregate,
          field: vlfield.fieldRef(d, {nofn: true, data: !encoding._vega2})
        };
      });

      var byClause = sortBy.map(function(d) {
        var reverse = (d.reverse ? '-' : '');
        return reverse + vlfield.fieldRef(d, {data: !encoding._vega2});
      });

      var dataName = 'sorted' + counter++;

      var transforms = [
        {
          type: 'aggregate',
          groupby: [ encoding.fieldRef(encType) ],
          fields: fields
        },
        {
          type: 'sort',
          by: byClause
        }
      ];

      data.push({
        name: dataName,
        source: RAW,
        transform: transforms
      });

      datasetMapping[encType] = dataName;
    }
  });

  return {
    getDataset: function(encType) {
      var data = datasetMapping[encType];
      if (!data) {
        return TABLE;
      }
      return data;
    }
  };
}

<commit_msg>undo nonsense rename<commit_after>'use strict';

require('../globals');

var vlfield = require('../field');

module.exports = addSortTransforms;

// adds new transforms that produce sorted fields
function addSortTransforms(data, encoding, stats, opt) {
  // jshint unused:false

  var datasetMapping = {};
  var counter = 0;

  encoding.forEach(function(field, encType) {
    var sortBy = encoding.sort(encType, stats);
    if (sortBy.length > 0) {
      var fields = sortBy.map(function(d) {
        return {
          op: d.aggregate,
          field: vlfield.fieldRef(d, {nofn: true, data: !encoding._vega2})
        };
      });

      var byClause = sortBy.map(function(d) {
        var reverse = (d.reverse ? '-' : '');
        return reverse + vlfield.fieldRef(d, {data: !encoding._vega2});
      });

      var dataName = 'sorted' + counter++;

      var transforms = [
        {
          type: 'aggregate',
          groupby: [ encoding.fieldRef(encType) ],
          fields: fields
        },
        {
          type: 'sort',
          by: byClause
        }
      ];

      data.push({
        name: dataName,
        source: RAW,
        transform: transforms
      });

      datasetMapping[encType] = dataName;
    }
  });

  return {
    getDataset: function(encType) {
      var data = datasetMapping[encType];
      if (!data) {
        return TABLE;
      }
      return data;
    }
  };
}

<|endoftext|>


<commit_before>/*
Copyright (C) 2012 - 2014 Alexander Murashkin, Neil Redman <http://gsd.uwaterloo.ca>

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
function getConfiguration()
{
	var modules = [];

    modules.push({"name": "Input", "configuration":
    	{
    		"layout": {
    			"width": (window.parent.innerWidth-40) * 0.38,
    			"height": window.parent.innerHeight-60,
    			"posx": 0,
    			"posy": 0
    		},

    		"title": "Input Clafer Model and Options",
    		"optimization_backend": false,
            "input_default_cache": "checked",
            "input_default_flags": "-k",
            "file_extensions": [
                {
                    "ext": ".cfr",
                    "button_file_caption": "Compile",
                    "button_example_caption": "Compile",
                    "button_editor_caption": "Compile",

                    "button_file_tooltip": "Compile the Clafer file selected on your machine",
                    "button_example_tooltip": "Compile the example chosen from the example list",
                    "button_editor_tooltip": "Compile the code in the editor below"
                }
            ],
    		"onError": function(module, statusText, response, xhr){
    			return onError(module, statusText, response, xhr);
    		},

    		"onBeginQuery": function(module)
    		{
			    module.host.storage.toReload = module.host.findModule("mdControl").sessionActive; // if there is an active IG session
			    if (module.host.storage.toReload)
			    {
			    	module.host.findModule("mdControl").pausePolling();
			    }

			    return true;
    		},

    		"onFileSent": function(module){
		        module.host.print("ClaferIDE> Processing the submitted model. Compiling...\n");
    		},

    		"onPoll" : function(module, responseObject){
		        if (responseObject.args)
		        {
		            module.host.print("ClaferIDE> clafer " + responseObject.args + "\n");
		        }
    		},
    		"onCompleted" : function(module, responseObject){
		        if (responseObject.args)
		        {
		            module.host.print("ClaferIDE> clafer " + responseObject.args + "\n");
		        }

		        if (responseObject.compiled_formats)
		        {
		            module.host.findModule("mdCompiledFormats").setResult(responseObject.compiled_formats);
		        }

		        if (responseObject.model != "")
		        {
		            module.editor.getSession().setValue(responseObject.model);
		        }

		        if (responseObject.message == "Success")
		        {
			        module.host.print("Compiler> " + responseObject.message + "\n");
			        module.host.print(responseObject.compiler_message + "\n");

			        if (module.host.storage.toReload)
			        {
			        	module.host.storage.toReload = false;
			            if (!module.host.findModule("mdControl").reload())
			            {
				            module.host.print("ClaferIDE> No reload command specified for the given backend.\nClaferIDE> Please re-run the backend to work with the changed model.\n");
			            }
			        }
			        else
			        {
			            module.host.findModule("mdControl").resetControls();
			        }
		        }
		        else
		        {
		        	module.host.print("Compiler> Error response:\n" + responseObject.compiler_message + "\n");
		        	console.log(responseObject);
			        if (module.host.storage.toReload)
			        {
						module.host.print("ClaferIDE> The instance generator is still running with the last version of the model.\n");
						module.host.print("ClaferIDE> After you fix the compilation problem, the instance generator will reload.\n");
			        	module.host.findModule("mdControl").resumePolling();
			        }
			        else
			        {
		            	module.host.findModule("mdControl").disableAll(); // if exited IG, then disable controls
		            }
		        }

		        return true;
    		}
    	}
	});
    modules.push({"name": "CompiledFormats", "configuration":
    	{
    		"layout": {
    			"width": (window.parent.innerWidth-40) * (0.24),
    			"height": window.parent.innerHeight - 60 - 255,
    			"posx": (window.parent.innerWidth-40) * 0.38,
    			"posy": 0
    		},

	    	"title": "Compiled Formats",
	    	"allow_downloading": true

    	}});

    modules.push({"name": "Control", "configuration":
    {
    		"layout": {
			    "width": (window.parent.innerWidth-40) * (0.24),
			    "height": 210,
			    "posx": (window.parent.innerWidth-40) * 0.38,
			    "posy": window.parent.innerHeight - 60 - 210
    		},
	    	"title": "Instance Generator",
    		"onError": function(module, statusText, response, xhr)
    		{
    			return onError(module, statusText, response, xhr);
			},
			"onStarted": function (module)
			{
		        module.host.print("ClaferIDE> Running the chosen instance generator...\n");
			},
			"onStopped": function (module)
			{
				module.host.print("ClaferIDE> Forcing the instance generator to close...\n");
			},
			"onStart": function (module)
			{
				return true;
			},
			"onStop": function (module)
			{
				return true;
			},
			"onDefaultScopeSet": function (module)
			{
				module.host.print("ClaferIDE> Setting the default scope...\n");
			},
			"onAllScopesIncreased": function (module)
			{
				module.host.print("ClaferIDE> Increasing all the scopes...\n");
			},
			"onIndividualScopeSet": function (module)
			{
		        module.host.print("ClaferIDE> Setting the individual scope...\n");
		    },
			"onIndividualScopeIncreased": function (module)
			{
		        module.host.print("ClaferIDE> Increasing the individual scope...\n");
		    },
			"onIntScopeSet": function (module)
			{
		        module.host.print("ClaferIDE> Setting integer bounds...\n");
		    },
    		"onPoll" : function(module, responseObject){
				if (responseObject.ig_args != "")
				{
				    module.host.print("ClaferIDE> " + responseObject.ig_args + "\n");
				}

				if (responseObject.message != "")
				{
				    module.host.print(filterOutput(module.host, responseObject.message));
				}
    		},
    		"onCompleted": function (module, responseObject){
    			module.host.print("ClaferIDE> Instance generator stopped.\n");
    		},
            "onBackendChange": function (module, newBackend)
            {
				module.host.storage.backend = newBackend;
			    module.host.findModule("mdControl").disableRuntimeControls();
            },
            "onCustomEvent": function (module, event)
            {
				module.host.print("ClaferIDE> '" + event + "' command sent.\n");
            }

    	}});

    modules.push({"name": "Output", "configuration":
    	{
	    	"title": "Output",

    		"layout": {
			    "width": (window.parent.innerWidth+65) * 0.38,
			    "height": window.parent.innerHeight-60,
			    "posx": (window.parent.innerWidth-40) * (1 - 0.38),
			    "posy": 0
    		}

    	}});

    var settings = {
    	"onInitialize": function(host)
	    {
	    },
    	"onLoaded": function(host)
	    {
	    	$("#myform").submit();
	    }
	};

    return {"modules": modules, "settings": settings};
}

function filterOutput(host, output)
{
	var title = host.storage.backend.presentation_specifics.prompt_title;
	if (title != "")
		return output.replaceAll(title, "");

	return output;
}

function onError(module, statusText, response, xhr)
{
	var currentDate = new Date();
    var errorRecord = {};

    if (statusText == "compile_error")
        errorRecord = {
        	"caption": "Compilation Error",
    		"body": "Please check whether Clafer Compiler is available, and the model is syntactically correct."
    	};
    else if (statusText == "timeout")
        errorRecord = {
        	"caption": "Request Timeout",
    		"body": "Please check whether the server is available. You may want to reload the browser page."
    	};
    else if (response && response.responseText == "process_not_found")
        errorRecord = {
        	"caption": "Session not found",
    		"body": "Looks like your session has been closed due to inactivity. Just recompile your model to start a new session."
    	};
    else if (statusText == "error" && response.responseText == "")
        errorRecord = {
        	"caption": "Request Error",
    		"body": "Please check whether the server is available. Try to recompile the model or to reload the browser page."
    	};
    else
        errorRecord = {
        	"caption": xhr,
    		"body": response.responseText
    	};

    errorRecord.datetime = currentDate.today() + " @ " + currentDate.timeNow();
    errorRecord.contact = "If the error persists, please contact Alexandr Murashkin (http://gsd.uwaterloo.ca/amurashk) or Michal Antkiewicz (http://gsd.uwaterloo.ca/mantkiew)";

    module.host.print("ClaferIDE> " + errorRecord.caption + ": " + errorRecord.datetime + "\n" + errorRecord.body + "\n");
    module.host.errorWindow(errorRecord);

    return true;
}<commit_msg>Editor preserves the history  after model load<commit_after>/*
Copyright (C) 2012 - 2014 Alexander Murashkin, Neil Redman <http://gsd.uwaterloo.ca>

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
function getConfiguration()
{
	var modules = [];

    modules.push({"name": "Input", "configuration":
    	{
    		"layout": {
    			"width": (window.parent.innerWidth-40) * 0.38,
    			"height": window.parent.innerHeight-60,
    			"posx": 0,
    			"posy": 0
    		},

    		"title": "Input Clafer Model and Options",
    		"optimization_backend": false,
            "input_default_cache": "checked",
            "input_default_flags": "-k",
            "file_extensions": [
                {
                    "ext": ".cfr",
                    "button_file_caption": "Compile",
                    "button_example_caption": "Compile",
                    "button_editor_caption": "Compile",

                    "button_file_tooltip": "Compile the Clafer file selected on your machine",
                    "button_example_tooltip": "Compile the example chosen from the example list",
                    "button_editor_tooltip": "Compile the code in the editor below"
                }
            ],
    		"onError": function(module, statusText, response, xhr){
    			return onError(module, statusText, response, xhr);
    		},

    		"onBeginQuery": function(module)
    		{
			    module.host.storage.toReload = module.host.findModule("mdControl").sessionActive; // if there is an active IG session
			    if (module.host.storage.toReload)
			    {
			    	module.host.findModule("mdControl").pausePolling();
			    }

			    return true;
    		},

    		"onFileSent": function(module){
		        module.host.print("ClaferIDE> Processing the submitted model. Compiling...\n");
    		},

    		"onPoll" : function(module, responseObject){
		        if (responseObject.args)
		        {
		            module.host.print("ClaferIDE> clafer " + responseObject.args + "\n");
		        }
    		},
    		"onCompleted" : function(module, responseObject){
		        if (responseObject.args)
		        {
		            module.host.print("ClaferIDE> clafer " + responseObject.args + "\n");
		        }

		        if (responseObject.compiled_formats)
		        {
		            module.host.findModule("mdCompiledFormats").setResult(responseObject.compiled_formats);
		        }

		        if (responseObject.model != "")
		        {
		            module.editor.selectAll();
		            module.editor.getSession().replace(module.editor.selection.getRange(), responseObject.model);
		            module.editor.selection.moveCursorTo(0, 0, false);
		            module.editor.selection.clearSelection();
		        }

		        if (responseObject.message == "Success")
		        {
			        module.host.print("Compiler> " + responseObject.message + "\n");
			        module.host.print(responseObject.compiler_message + "\n");

			        if (module.host.storage.toReload)
			        {
			        	module.host.storage.toReload = false;
			            if (!module.host.findModule("mdControl").reload())
			            {
				            module.host.print("ClaferIDE> No reload command specified for the given backend.\nClaferIDE> Please re-run the backend to work with the changed model.\n");
			            }
			        }
			        else
			        {
			            module.host.findModule("mdControl").resetControls();
			        }
		        }
		        else
		        {
		        	module.host.print("Compiler> Error response:\n" + responseObject.compiler_message + "\n");
		        	console.log(responseObject);
			        if (module.host.storage.toReload)
			        {
						module.host.print("ClaferIDE> The instance generator is still running with the last version of the model.\n");
						module.host.print("ClaferIDE> After you fix the compilation problem, the instance generator will reload.\n");
			        	module.host.findModule("mdControl").resumePolling();
			        }
			        else
			        {
		            	module.host.findModule("mdControl").disableAll(); // if exited IG, then disable controls
		            }
		        }

		        return true;
    		}
    	}
	});
    modules.push({"name": "CompiledFormats", "configuration":
    	{
    		"layout": {
    			"width": (window.parent.innerWidth-40) * (0.24),
    			"height": window.parent.innerHeight - 60 - 255,
    			"posx": (window.parent.innerWidth-40) * 0.38,
    			"posy": 0
    		},

	    	"title": "Compiled Formats",
	    	"allow_downloading": true

    	}});

    modules.push({"name": "Control", "configuration":
    {
    		"layout": {
			    "width": (window.parent.innerWidth-40) * (0.24),
			    "height": 210,
			    "posx": (window.parent.innerWidth-40) * 0.38,
			    "posy": window.parent.innerHeight - 60 - 210
    		},
	    	"title": "Instance Generator",
    		"onError": function(module, statusText, response, xhr)
    		{
    			return onError(module, statusText, response, xhr);
			},
			"onStarted": function (module)
			{
		        module.host.print("ClaferIDE> Running the chosen instance generator...\n");
			},
			"onStopped": function (module)
			{
				module.host.print("ClaferIDE> Forcing the instance generator to close...\n");
			},
			"onStart": function (module)
			{
				return true;
			},
			"onStop": function (module)
			{
				return true;
			},
			"onDefaultScopeSet": function (module)
			{
				module.host.print("ClaferIDE> Setting the default scope...\n");
			},
			"onAllScopesIncreased": function (module)
			{
				module.host.print("ClaferIDE> Increasing all the scopes...\n");
			},
			"onIndividualScopeSet": function (module)
			{
		        module.host.print("ClaferIDE> Setting the individual scope...\n");
		    },
			"onIndividualScopeIncreased": function (module)
			{
		        module.host.print("ClaferIDE> Increasing the individual scope...\n");
		    },
			"onIntScopeSet": function (module)
			{
		        module.host.print("ClaferIDE> Setting integer bounds...\n");
		    },
    		"onPoll" : function(module, responseObject){
				if (responseObject.ig_args != "")
				{
				    module.host.print("ClaferIDE> " + responseObject.ig_args + "\n");
				}

				if (responseObject.message != "")
				{
				    module.host.print(filterOutput(module.host, responseObject.message));
				}
    		},
    		"onCompleted": function (module, responseObject){
    			module.host.print("ClaferIDE> Instance generator stopped.\n");
    		},
            "onBackendChange": function (module, newBackend)
            {
				module.host.storage.backend = newBackend;
			    module.host.findModule("mdControl").disableRuntimeControls();
            },
            "onCustomEvent": function (module, event)
            {
				module.host.print("ClaferIDE> '" + event + "' command sent.\n");
            }

    	}});

    modules.push({"name": "Output", "configuration":
    	{
	    	"title": "Output",

    		"layout": {
			    "width": (window.parent.innerWidth+65) * 0.38,
			    "height": window.parent.innerHeight-60,
			    "posx": (window.parent.innerWidth-40) * (1 - 0.38),
			    "posy": 0
    		}

    	}});

    var settings = {
    	"onInitialize": function(host)
	    {
	    },
    	"onLoaded": function(host)
	    {
	    	$("#myform").submit();
	    }
	};

    return {"modules": modules, "settings": settings};
}

function filterOutput(host, output)
{
	var title = host.storage.backend.presentation_specifics.prompt_title;
	if (title != "")
		return output.replaceAll(title, "");

	return output;
}

function onError(module, statusText, response, xhr)
{
	var currentDate = new Date();
    var errorRecord = {};

    if (statusText == "compile_error")
        errorRecord = {
        	"caption": "Compilation Error",
    		"body": "Please check whether Clafer Compiler is available, and the model is syntactically correct."
    	};
    else if (statusText == "timeout")
        errorRecord = {
        	"caption": "Request Timeout",
    		"body": "Please check whether the server is available. You may want to reload the browser page."
    	};
    else if (response && response.responseText == "process_not_found")
        errorRecord = {
        	"caption": "Session not found",
    		"body": "Looks like your session has been closed due to inactivity. Just recompile your model to start a new session."
    	};
    else if (statusText == "error" && response.responseText == "")
        errorRecord = {
        	"caption": "Request Error",
    		"body": "Please check whether the server is available. Try to recompile the model or to reload the browser page."
    	};
    else
        errorRecord = {
        	"caption": xhr,
    		"body": response.responseText
    	};

    errorRecord.datetime = currentDate.today() + " @ " + currentDate.timeNow();
    errorRecord.contact = "If the error persists, please contact Alexandr Murashkin (http://gsd.uwaterloo.ca/amurashk) or Michal Antkiewicz (http://gsd.uwaterloo.ca/mantkiew)";

    module.host.print("ClaferIDE> " + errorRecord.caption + ": " + errorRecord.datetime + "\n" + errorRecord.body + "\n");
    module.host.errorWindow(errorRecord);

    return true;
}<|endoftext|>


<commit_before>'use strict';
var srcPath              = './<%= yo_front_src %>';
var destPath             = './<%= yo_web %>';
var js_dest_dir          = '<%= yo_js_dest_dir %>';
var css_dest_dir         = '<%= yo_css_dest_dir %>';
var images_dest_dir      = '<%= yo_images_dest_dir %>';
var gulp_bower_dest_dir  = '<%= yo_gulp_bower_dest_dir %>';

var gulp       = require('gulp');
var $          = require('gulp-load-plugins')();
var glob       = require('glob');
var path       = require('path');
var browserify = require('browserify');
var source     = require('vinyl-source-stream');
var buffer     = require('vinyl-buffer');
var bower      = require('main-bower-files');
var sprite     = require('css-sprite').stream;
var _          = require('lodash');
var argv       = require('yargs').argv;

var env = argv.env || 'dev';
function src(path) { return srcPath + '/' + path; }
function dest(path) { return destPath + '/' + path; }

gulp.task('bower', function() {
    return gulp
        .src(bower(), {base: src('bower_components')})
        .pipe(gulp.dest(dest(gulp_bower_dest_dir)));
});

gulp.task('scripts', function() {
    var arrayBundle = function(srcArray) {
        _.each(srcArray, function(sourcePath) {
            browserify({
                entries: sourcePath,
                debug: env == 'dev',
                paths: [src('bower_components')]
            })
            .bundle()
            .on('error', handleErrors)
            .pipe(source(path.basename(sourcePath)))
            .pipe(buffer())
            // Uglify is not working well with browserify, so I disabled it
            // temporarily
            // .pipe(env == 'prod' ? $.uglify() : $.util.noop())
            .pipe(gulp.dest(dest(js_dest_dir)));
        });
    };

    glob(src('scripts/*.js'), {}, function(er, files) {
        arrayBundle(files);
    });
});

gulp.task('styles', function () {
    return gulp
        .src(src('styles/*.scss'))
        .pipe(env == 'dev' ? $.sourcemaps.init() : $.util.noop())
        .pipe($.sass({
            includePaths: [src('bower_components')],
            imagePath: '../' + images_dest_dir
        }))
        .on('error', handleErrors)
        .pipe($.autoprefixer({browsers: ['> 1%']}))
        .pipe(env == 'dev' ? $.sourcemaps.write() : $.util.noop())
        .pipe(env == 'prod' ? $.csso() : $.util.noop())
        .pipe(gulp.dest(dest(css_dest_dir)));
});

gulp.task('sprites', function () {
    var runSpriteBuild = function(folderPath, spriteName, processor) {
        gulp
            .src(folderPath + '*.png')
            .pipe(sprite({
                name: spriteName,
                style: spriteName + '-' + processor + '.scss',
                cssPath: '../' + images_dest_dir + '/sprites',
                processor: processor,
                prefix: spriteName
            }))
            .pipe($.if(
                '*.png',
                gulp.dest(src(images_dest_dir + '/sprites')),
                gulp.dest(src('styles/sprites/'))
            ));
    };

    glob(src('sprites/*/'), {}, function(er, folders) {
        _.each(folders, function(folderPath) {
            var spriteName = path.basename(folderPath);
            runSpriteBuild(folderPath, spriteName, 'css');
            runSpriteBuild(folderPath, spriteName, 'scss');
        });
    });
});

gulp.task('images', function () {
    return gulp
        .src(src('images/**/*'))
        .pipe($.imagemin({
            progressive: true,
            interlaced: true
        }))
        .pipe(gulp.dest(dest(images_dest_dir)));
});

gulp.task('watch', function() {
    $.watch(src('styles/**/*.scss'), function () {
        gulp.start('styles');
    });
    $.watch(src('scripts/**/*.js'), function () {
        gulp.start('scripts');
    });
    $.watch(src('sprites/**/*.png'), function () {
        gulp.start('sprites');
    });
});

gulp.task('build', ['bower', 'scripts', 'styles', 'images']);
gulp.task('default', ['build']);

function handleErrors() {
    var args = Array.prototype.slice.call(arguments);

    // Send error to notification center with gulp-notify
    $.notify.onError({
        title: 'Compile Error',
        message: '<%= error.message %>'
    }).apply(this, args);

    // Keep gulp from hanging on this task
    this.emit('end');
};
<commit_msg>Fixed the uglifying of browserified js assets.<commit_after>'use strict';
var srcPath              = './<%= yo_front_src %>';
var destPath             = './<%= yo_web %>';
var js_dest_dir          = '<%= yo_js_dest_dir %>';
var css_dest_dir         = '<%= yo_css_dest_dir %>';
var images_dest_dir      = '<%= yo_images_dest_dir %>';
var gulp_bower_dest_dir  = '<%= yo_gulp_bower_dest_dir %>';

var gulp       = require('gulp');
var $          = require('gulp-load-plugins')();
var glob       = require('glob');
var path       = require('path');
var browserify = require('browserify');
var source     = require('vinyl-source-stream');
var buffer     = require('vinyl-buffer');
var bower      = require('main-bower-files');
var sprite     = require('css-sprite').stream;
var _          = require('lodash');
var argv       = require('yargs').argv;

var env = argv.env || 'dev';
function src(path) { return srcPath + '/' + path; }
function dest(path) { return destPath + '/' + path; }

gulp.task('bower', function() {
    return gulp
        .src(bower(), {base: src('bower_components')})
        .pipe(gulp.dest(dest(gulp_bower_dest_dir)));
});

gulp.task('scripts', function() {
    var arrayBundle = function(srcArray) {
        _.each(srcArray, function(sourcePath) {
            browserify({
                entries: sourcePath,
                debug: env == 'dev',
                paths: [src('bower_components')]
            })
            .bundle()
            .on('error', handleErrors)
            .pipe(source(path.basename(sourcePath)))
            .pipe(buffer())
            // Mangling sometimes screwed up the browserified modules.
            .pipe(env == 'prod' ? $.uglify(mangle: false) : $.util.noop())
            .pipe(gulp.dest(dest(js_dest_dir)));
        });
    };

    glob(src('scripts/*.js'), {}, function(er, files) {
        arrayBundle(files);
    });
});

gulp.task('styles', function () {
    return gulp
        .src(src('styles/*.scss'))
        .pipe(env == 'dev' ? $.sourcemaps.init() : $.util.noop())
        .pipe($.sass({
            includePaths: [src('bower_components')],
            imagePath: '../' + images_dest_dir
        }))
        .on('error', handleErrors)
        .pipe($.autoprefixer({browsers: ['> 1%']}))
        .pipe(env == 'dev' ? $.sourcemaps.write() : $.util.noop())
        .pipe(env == 'prod' ? $.csso() : $.util.noop())
        .pipe(gulp.dest(dest(css_dest_dir)));
});

gulp.task('sprites', function () {
    var runSpriteBuild = function(folderPath, spriteName, processor) {
        gulp
            .src(folderPath + '*.png')
            .pipe(sprite({
                name: spriteName,
                style: spriteName + '-' + processor + '.scss',
                cssPath: '../' + images_dest_dir + '/sprites',
                processor: processor,
                prefix: spriteName
            }))
            .pipe($.if(
                '*.png',
                gulp.dest(src(images_dest_dir + '/sprites')),
                gulp.dest(src('styles/sprites/'))
            ));
    };

    glob(src('sprites/*/'), {}, function(er, folders) {
        _.each(folders, function(folderPath) {
            var spriteName = path.basename(folderPath);
            runSpriteBuild(folderPath, spriteName, 'css');
            runSpriteBuild(folderPath, spriteName, 'scss');
        });
    });
});

gulp.task('images', function () {
    return gulp
        .src(src('images/**/*'))
        .pipe($.imagemin({
            progressive: true,
            interlaced: true
        }))
        .pipe(gulp.dest(dest(images_dest_dir)));
});

gulp.task('watch', function() {
    $.watch(src('styles/**/*.scss'), function () {
        gulp.start('styles');
    });
    $.watch(src('scripts/**/*.js'), function () {
        gulp.start('scripts');
    });
    $.watch(src('sprites/**/*.png'), function () {
        gulp.start('sprites');
    });
});

gulp.task('build', ['bower', 'scripts', 'styles', 'images']);
gulp.task('default', ['build']);

function handleErrors() {
    var args = Array.prototype.slice.call(arguments);

    // Send error to notification center with gulp-notify
    $.notify.onError({
        title: 'Compile Error',
        message: '<%= error.message %>'
    }).apply(this, args);

    // Keep gulp from hanging on this task
    this.emit('end');
};
<|endoftext|>