<commit_before>define([
  'jquery',
  'd3',
  'underscore',
  'base/utils',
  'base/class'
], function($, d3, _, utils, Class) {

  var Component = Class.extend({
    init: function(core, options) {
      this.name = this.name || options.name;
      this.state = this.state || options.state;
      this.placeholder = this.placeholder || options.placeholder;

      this.element = this.element || null;
      this.core = this.core || core;
      this.template = this.template || "components/component";
      this.template_data = this.template_data || {
        name: this.name
      };
      // Markup to define where a Component is going to be rendered.
      // Element which embodies the Component
      this.element = this.element || null;
      this.components = this.components || {};

      this.profiles = this.profiles || {};
      this.parent = parent;

      this.loading = true;

      this.events = core.getInstance('events');
    },

    render: function() {
      var defer = $.Deferred();
      var _this = this;

      // First, we load the template
      var promise = this.loadTemplate();

      // After the template is loaded, check if postRender exists
      promise.then(function() {

        // add css loading class to hide elements
        this.loading = true;
        _this.element.classed("loading", _this.loading);

        // attempt to execute postRender
        return _this.execute(_this.postRender);

      })
      // After postRender, resize and load components
      .then(function() {

        //TODO: Chance of refactoring
        //Every widget binds its resize function to the resize event
        _this.resize();
        _this.events.bind('resize', function() {
          _this.resize();
        });

        return _this.loadComponents();
      })
      // After loading components, render them
      .then(function() {
        return _this.renderComponents();
      })
      // After rendering the components, resolve the defer
      .done(function() {
        //not loading anytmore, remove class
        _this.loading = false;
        _this.element.classed("loading", _this.loading);

        defer.resolve();
      });

      return defer;
    },

    // Execute function if it exists, with promise support
    execute: function(func) {

      var defer = $.Deferred(),
          possiblePromise;

      // only try to execute if it is a function
      if(_.isFunction(func)) {
          possiblePromise = func();
      };

      // if a promise is returned, solve it when its done
      if(possiblePromise && _.isFunction(possiblePromise.then)) {
        possiblePromise.done(function(){
          defer.resolve();
        });
      }
      // if no promise is returned, resolve right away
      else {
        defer.resolve();
      }

      return defer;
    },

    loadComponents: function(core) {
      var defer = $.Deferred();
      var defers = [];
      var _this = this;

      // Loops through components, loading them.
      _.each(this.components, function(placeholder, component) {
        var promise = _this.loadComponent(component, placeholder);
        defers.push(promise);
      });

      // When all components have been successfully loaded, resolve the defer
      $.when.apply(null,defers).done(function() {

        //todo: remove comments of simulation
        //setTimeout(function() {
          defer.resolve();
        //}, 1000);
      });

      return defer;
    },

    loadComponent: function(component,placeholder) {
      var _this = this;
      var defer = $.Deferred();
      var path = "components/" + component + "/" + component;

      // Loads the file we need
      require([path], function(subcomponent) {
        _this.components[component] = new subcomponent(_this.core, {
          name: component,
          placeholder: placeholder,
          state: _this.state
        });

        // Resolve the defer after file has been loaded
        defer.resolve();
      });

      return defer;
    },

    renderComponents: function() {
      var defer = $.Deferred();
      var defers = [];

      // Loops through components, rendering them.
      _.each(this.components, function(component) {
        defers.push(component.render());
      });

      // After all components are rendered, resolve the defer
      $.when.apply(null, defers).done(function() {
        defer.resolve();
      });

      return defer;
    },

    loadTemplate: function() {
      var _this = this;
      var defer = $.Deferred();

      //require the template file
      require(["text!" + this.template + ".html"], function(html) {
        //render template using underscore
        var rendered = _.template(html, _this.template_data);

        //place the contents into the correct placeholder
        _this.placeholder = d3.select(_this.placeholder);
        _this.placeholder.html(rendered);

        //todo: refactor the way we select the first child
        //define this element inside the placeholder
        _this.element = utils.jQueryToD3(
          utils.d3ToJquery(_this.placeholder).children().first()
          );

        //Resolve defer
        defer.resolve();
      });

      return defer;
    },

    parent: function() {
      return this.parent;
    },

    setState: function(state) {
      this.state = _.extend(this.state, state);
      this.events.trigger('change:state', this.state);
      return this;
    },

    resize: function() {
      //what to do when page is resized
    }
  });

  return Component;
});
<commit_msg>Made component point to the parents’ `core` instead of always pointing to the main core<commit_after>define([
  'jquery',
  'd3',
  'underscore',
  'base/utils',
  'base/class'
], function($, d3, _, utils, Class) {

  var Component = Class.extend({
    init: function(core, options) {
      this.name = this.name || options.name;
      this.state = this.state || options.state;
      this.placeholder = this.placeholder || options.placeholder;

      this.element = this.element || null;
      this.core = this.core || core;
      this.template = this.template || "components/component";
      this.template_data = this.template_data || {
        name: this.name
      };
      // Markup to define where a Component is going to be rendered.
      // Element which embodies the Component
      this.element = this.element || null;
      this.components = this.components || {};

      this.profiles = this.profiles || {};
      this.parent = parent;

      this.loading = true;

      this.events = core.getInstance('events');
    },

    render: function() {
      var defer = $.Deferred();
      var _this = this;

      // First, we load the template
      var promise = this.loadTemplate();

      // After the template is loaded, check if postRender exists
      promise.then(function() {

        // add css loading class to hide elements
        this.loading = true;
        _this.element.classed("loading", _this.loading);

        // attempt to execute postRender
        return _this.execute(_this.postRender);

      })
      // After postRender, resize and load components
      .then(function() {

        //TODO: Chance of refactoring
        //Every widget binds its resize function to the resize event
        _this.resize();
        _this.core.bind('resize', function() {
          _this.resize();
        });

        return _this.loadComponents();
      })
      // After loading components, render them
      .then(function() {
        return _this.renderComponents();
      })
      // After rendering the components, resolve the defer
      .done(function() {
        //not loading anytmore, remove class
        _this.loading = false;
        _this.element.classed("loading", _this.loading);

        defer.resolve();
      });

      return defer;
    },

    // Execute function if it exists, with promise support
    execute: function(func) {

      var defer = $.Deferred(),
          possiblePromise;

      // only try to execute if it is a function
      if(_.isFunction(func)) {
          possiblePromise = func();
      };

      // if a promise is returned, solve it when its done
      if(possiblePromise && _.isFunction(possiblePromise.then)) {
        possiblePromise.done(function(){
          defer.resolve();
        });
      }
      // if no promise is returned, resolve right away
      else {
        defer.resolve();
      }

      return defer;
    },

    loadComponents: function(core) {
      var defer = $.Deferred();
      var defers = [];
      var _this = this;

      // Loops through components, loading them.
      _.each(this.components, function(placeholder, component) {
        var promise = _this.loadComponent(component, placeholder);
        defers.push(promise);
      });

      // When all components have been successfully loaded, resolve the defer
      $.when.apply(null,defers).done(function() {

        //todo: remove comments of simulation
        //setTimeout(function() {
          defer.resolve();
        //}, 1000);
      });

      return defer;
    },

    loadComponent: function(component,placeholder) {
      var _this = this;
      var defer = $.Deferred();
      var path = "components/" + component + "/" + component;

      // Loads the file we need
      require([path], function(subcomponent) {
        _this.components[component] = new subcomponent(_this, {
          name: component,
          placeholder: placeholder,
          state: _this.state
        });

        // Resolve the defer after file has been loaded
        defer.resolve();
      });

      return defer;
    },

    renderComponents: function() {
      var defer = $.Deferred();
      var defers = [];

      // Loops through components, rendering them.
      _.each(this.components, function(component) {
        defers.push(component.render());
      });

      // After all components are rendered, resolve the defer
      $.when.apply(null, defers).done(function() {
        defer.resolve();
      });

      return defer;
    },

    loadTemplate: function() {
      var _this = this;
      var defer = $.Deferred();

      //require the template file
      require(["text!" + this.template + ".html"], function(html) {
        //render template using underscore
        var rendered = _.template(html, _this.template_data);

        //place the contents into the correct placeholder
        _this.placeholder = d3.select(_this.placeholder);
        _this.placeholder.html(rendered);

        //todo: refactor the way we select the first child
        //define this element inside the placeholder
        _this.element = utils.jQueryToD3(
          utils.d3ToJquery(_this.placeholder).children().first()
          );

        //Resolve defer
        defer.resolve();
      });

      return defer;
    },

    parent: function() {
      return this.parent;
    },

    setState: function(state) {
      this.state = _.extend(this.state, state);
      this.events.trigger('change:state', this.state);
      return this;
    },

    resize: function() {
      //what to do when page is resized
    }
  });

  return Component;
});
<|endoftext|>


<commit_before>/** @jsx hJSX */
import Cycle from '@cycle/core'
import {Rx} from '@cycle/core'
import {hJSX} from '@cycle/dom'
import Class from "classnames"
let combineLatest = Rx.Observable.combineLatest

export default function view(settingsVTree$, fsTogglerVTree$, bomVtree$, glVtree$, entityInfosVtree$, commentVTree$){
  return combineLatest(settingsVTree$, fsTogglerVTree$, bomVtree$, glVtree$, entityInfosVtree$, commentVTree$
    ,function(settings, fsToggler, bom, gl, entityInfos, comments){
      return

        {settings}
        {fsToggler}

        {bom}
        {gl}

        {comments}
        {entityInfos}

          <button className="reset"> Reset (debug) </button>

          <button className="clearAll"> Delete all </button>
          <button className="delete">Delete</button>
          <button className="duplicate">Duplicate</button>

          <button className="translate">Translate</button>
          <button className="rotate">Rotate</button>
          <button className="scale">Scale</button>

    })
}<commit_msg>modified styling for main view<commit_after>/** @jsx hJSX */
import Cycle from '@cycle/core'
import {Rx} from '@cycle/core'
import {hJSX} from '@cycle/dom'
import Class from "classnames"
let combineLatest = Rx.Observable.combineLatest

export default function view(settingsVTree$, fsTogglerVTree$, bomVtree$, glVtree$, entityInfosVtree$, commentVTree$){
  return combineLatest(settingsVTree$, fsTogglerVTree$, bomVtree$, glVtree$, entityInfosVtree$, commentVTree$
    ,function(settings, fsToggler, bom, gl, entityInfos, comments){
      return

        {settings}
        {fsToggler}

        {bom}
        {gl}

        {comments}
        {entityInfos}

          <button className="reset"> Reset (debug) </button>

          <button className="clearAll"> Delete all </button>
          <button className="delete">Delete</button>
          <button className="duplicate">Duplicate</button>

          <button className="toTranslateMode">Translate</button>
          <button className="toRotateMode">Rotate</button>
          <button className="toScaleMode">Scale</button>

    })
}<|endoftext|>


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

class PostsNew extends Component {

  render() {
    return (
      <div>
        PostsNew!
      </div>
    );
  }
}

export default PostsNew;
<commit_msg>133 Setting up Redux Form<commit_after>import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';

class PostsNew extends Component {

  render() {
    return (
      <form>
        <Field name="title" component={} />
      </form>
    );
  }
}

export default reduxForm({
  form: 'PostsNewForm'
})(PostsNew);
<|endoftext|>


<commit_before>'use strict';

require('./block_arduino');
require('./block_sensorboard');
require('./block_joystick');
require('./block_dplay');
require('./block_nemoino');
require('./block_ardublock');
require('./block_arduino_nano');
require('./block_roboid');
require('./block_mkboard');
require('./block_memaker');
require('./block_smartboard');
require('./block_rokoboard');
require('./block_albert');
require('./block_altino');
require('./block_arduino_ext');
require('./block_coding_box');
require('./block_bitbrick');
require('./block_blacksmith');
require('./block_byrobot_dronefighter_controller');
require('./block_byrobot_dronefighter_drive');
require('./block_byrobot_dronefighter_flight');
require('./block_byrobot_petrone_v2_controller');
require('./block_byrobot_petrone_v2_drive');
require('./block_byrobot_petrone_v2_flight');
require('./block_chocopi');
require('./block_cobl');
require('./block_coconut');
require('./block_codeino');
require('./block_codestar');
require('./block_dadublock');
require('./block_edumaker');
require('./block_ev3');
require('./block_hamster');
require('./block_hummingbird');
require('./block_iboard');
require('./block_jdkit');
require('./block_mechatronics_4d');
require('./block_modi');
require('./block_neobot');
require('./block_neobot_sensor_theme');
require('./block_roborobo');
require('./block_robotis');
require('./block_robotori');
require('./block_truerobot');
require('./block_turtle');
require('./block_xbot');
require('./block_playcode');
require('./block_mechatro');
require('./block_creamo');
require('./block_funboard');
require('./block_microbit');
require('./block_mrt');
require('./block_dash');
require('./block_bingles');
require('./block_codingmachine');

Entry.HARDWARE_LIST = {
    '1.1': Entry.Arduino,
    '1.2': Entry.SensorBoard,
    '1.3': Entry.CODEino,
    '1.4': Entry.joystick,
    '1.5': Entry.dplay,
    '1.6': Entry.nemoino,
    '1.7': Entry.Xbot,
    '1.8': Entry.ardublock,
    '1.9': Entry.ArduinoExt,
    '1.10': Entry.ArduinoNano,
    '1.A': Entry.Cobl,
    '1.B': Entry.Blacksmith,
    '1.C': Entry.CodingBox,
    '2.4': Entry.Hamster,
    '2.5': Entry.Albert,
    '2.9': Entry.Turtle,
    '2.FF': Entry.Roboid,
    '3.1': Entry.Bitbrick,
    '4.2': Entry.Arduino,
    '5.1': Entry.Neobot,
    '5.2': Entry.NeobotSensorTheme,
    '6.1': Entry.mkboard,
    '6.2': Entry.memaker,
    '7.1': Entry.Robotis_carCont,
    '7.2': Entry.Robotis_openCM70,
    '8.1': Entry.Arduino,
    '9.1': Entry.iboard,
    'A.1': Entry.SmartBoard,
    'B.1': Entry.Codestar,
    'C.1': Entry.DaduBlock,
    'C.2': Entry.DaduBlock_Car,
    'D.1': Entry.robotori,
    'F.1': Entry.byrobot_dronefighter_controller,
    'F.2': Entry.byrobot_dronefighter_drive,
    'F.3': Entry.byrobot_dronefighter_flight,
    'F.4': Entry.byrobot_petrone_v2_controller,
    'F.5': Entry.byrobot_petrone_v2_drive,
    'F.6': Entry.byrobot_petrone_v2_flight,
    '10.1': Entry.Roborobo_Roduino,
    '10.2': Entry.Roborobo_SchoolKit,
    '12.1': Entry.EV3,
    '13.1': Entry.rokoboard,
    '14.1': Entry.Chocopi,
    '15.1': Entry.coconut,
    '16.1': Entry.MODI,
    '18.1': Entry.Altino,
    '19.1': Entry.trueRobot,
    '1A.1': Entry.ArduinoNano,
    '1B.1': Entry.EduMaker,
    '1C.1': Entry.hummingbird,
    '1D.1': Entry.JDKit,
    '1E.1': Entry.playcode,
    '1F.1': Entry.mechatro,
    '20.1': Entry.Creamo,
    '21.1': Entry.FunBoard,
    '22.1': Entry.Microbit,
    '23.1': Entry.MRT,
    '24.1': Entry.Dash,
    '1.D': Entry.BINGLES,
    '26.1': Entry.Codingmachine,
};

const startBlock = require('./block_start');
const flowBlock = require('./block_flow');
const movingBlock = require('./block_moving');
const looksBlock = require('./block_looks');
const brushBlock = require('./block_brush');
const textBlock = require('./block_text');
const soundBlock = require('./block_sound');
const judgementBlock = require('./block_judgement');
const calcBlock = require('./block_calc');
const variableBlock = require('./block_variable');
const funcBlock = require('./block_func');

require('./block_expansion_weather');
Entry.EXPANSION_BLOCK = {};
Entry.EXPANSION_BLOCK_LIST = {
    'weather' : Entry.Expansion_Weather
};

function getBlockObject(items) {
    const blockObject = {};
    items.forEach((item)=> {
        if('getBlocks' in item) {
            Object.assign(blockObject, item.getBlocks());
        }
    });
    return blockObject;
}

module.exports = {
    getBlocks() {
        const basicBlockList = [
            startBlock,
            flowBlock,
            movingBlock,
            looksBlock,
            brushBlock,
            textBlock,
            soundBlock,
            judgementBlock,
            calcBlock,
            variableBlock,
            funcBlock
        ];
        const expansionBlockList = Object.values(Entry.EXPANSION_BLOCK_LIST);
        const hardwareList = Object.values(Entry.HARDWARE_LIST);
        return getBlockObject(basicBlockList.concat(hardwareList).concat(expansionBlockList));
    }
}
<commit_msg>update index.js from develop branch<commit_after>'use strict';

require('./block_arduino');
require('./block_sensorboard');
require('./block_joystick');
require('./block_dplay');
require('./block_nemoino');
require('./block_ardublock');
require('./block_arduino_nano');
require('./block_roboid');
require('./block_mkboard');
require('./block_memaker');
require('./block_smartboard');
require('./block_rokoboard');
require('./block_albert');
require('./block_altino');
require('./block_arduino_ext');
require('./block_coding_box');
require('./block_bitbrick');
require('./block_blacksmith');
require('./block_byrobot_dronefighter_controller');
require('./block_byrobot_dronefighter_drive');
require('./block_byrobot_dronefighter_flight');
require('./block_byrobot_petrone_v2_controller');
require('./block_byrobot_petrone_v2_drive');
require('./block_byrobot_petrone_v2_flight');
require('./block_chocopi');
require('./block_cobl');
require('./block_coconut');
require('./block_codeino');
require('./block_codestar');
require('./block_dadublock');
require('./block_edumaker');
require('./block_ev3');
require('./block_hamster');
require('./block_hummingbird');
require('./block_iboard');
require('./block_jdkit');
require('./block_mechatronics_4d');
require('./block_modi');
require('./block_neobot');
require('./block_neobot_sensor_theme');
require('./block_roborobo');
require('./block_robotis');
require('./block_robotori');
require('./block_truerobot');
require('./block_turtle');
require('./block_xbot');
require('./block_playcode');
require('./block_mechatro');
require('./block_creamo');
require('./block_funboard');
require('./block_microbit');
require('./block_mrt');
require('./block_dash');
require('./block_bingles');
require('./block_codingmachine');

Entry.HARDWARE_LIST = {
    '1.1': Entry.Arduino,
    '1.2': Entry.SensorBoard,
    '1.3': Entry.CODEino,
    '1.4': Entry.joystick,
    '1.5': Entry.dplay,
    '1.6': Entry.nemoino,
    '1.7': Entry.Xbot,
    '1.8': Entry.ardublock,
    '1.9': Entry.ArduinoExt,
    '1.10': Entry.ArduinoNano,
    '1.A': Entry.Cobl,
    '1.B': Entry.Blacksmith,
    '1.C': Entry.CodingBox,
    '2.4': Entry.Hamster,
    '2.5': Entry.Albert,
    '2.9': Entry.Turtle,
    '2.FF': Entry.Roboid,
    '3.1': Entry.Bitbrick,
    '4.2': Entry.Arduino,
    '5.1': Entry.Neobot,
    '5.2': Entry.NeobotSensorTheme,
    '6.1': Entry.mkboard,
    '6.2': Entry.memaker,
    '7.1': Entry.Robotis_carCont,
    '7.2': Entry.Robotis_openCM70,
    '8.1': Entry.Arduino,
    '9.1': Entry.iboard,
    'A.1': Entry.SmartBoard,
    'B.1': Entry.Codestar,
    'C.1': Entry.DaduBlock,
    'C.2': Entry.DaduBlock_Car,
    'D.1': Entry.robotori,
    'F.1': Entry.byrobot_dronefighter_controller,
    'F.2': Entry.byrobot_dronefighter_drive,
    'F.3': Entry.byrobot_dronefighter_flight,
    'F.4': Entry.byrobot_petrone_v2_controller,
    'F.5': Entry.byrobot_petrone_v2_drive,
    'F.6': Entry.byrobot_petrone_v2_flight,
    '10.1': Entry.Roborobo_Roduino,
    '10.2': Entry.Roborobo_SchoolKit,
    '12.1': Entry.EV3,
    '13.1': Entry.rokoboard,
    '14.1': Entry.Chocopi,
    '15.1': Entry.coconut,
    '16.1': Entry.MODI,
    '18.1': Entry.Altino,
    '19.1': Entry.trueRobot,
    '1A.1': Entry.ArduinoNano,
    '1B.1': Entry.EduMaker,
    '1C.1': Entry.hummingbird,
    '1D.1': Entry.JDKit,
    '1E.1': Entry.playcode,
    '1F.1': Entry.mechatro,
    '20.1': Entry.Creamo,
    '21.1': Entry.FunBoard,
    '22.1': Entry.Microbit,
    '23.1': Entry.MRT,
    '24.1': Entry.Dash,
    '1.D': Entry.BINGLES,
    '26.1': Entry.Codingmachine,
};

const startBlock = require('./block_start');
const flowBlock = require('./block_flow');
const movingBlock = require('./block_moving');
const looksBlock = require('./block_looks');
const brushBlock = require('./block_brush');
const textBlock = require('./block_text');
const soundBlock = require('./block_sound');
const judgementBlock = require('./block_judgement');
const calcBlock = require('./block_calc');
const variableBlock = require('./block_variable');
const funcBlock = require('./block_func');

Entry.EXPANSION_BLOCK = {};
require('./block_expansion_weather');
require('./block_expansion_festival');
require('./block_expansion_translate');

Entry.EXPANSION_BLOCK_LIST = {
    weather: Entry.Expansion_Weather,
    festival: Entry.EXPANSION_BLOCK.festival,
    translate : Entry.EXPANSION_BLOCK.translate
};

function getBlockObject(items) {
    const blockObject = {};
    items.forEach((item)=> {
        if('getBlocks' in item) {
            Object.assign(blockObject, item.getBlocks());
        }
    });
    return blockObject;
}

module.exports = {
    getBlocks() {
        const basicBlockList = [
            startBlock,
            flowBlock,
            movingBlock,
            looksBlock,
            brushBlock,
            textBlock,
            soundBlock,
            judgementBlock,
            calcBlock,
            variableBlock,
            funcBlock
        ];
        const expansionBlockList = Object.values(Entry.EXPANSION_BLOCK_LIST);
        const hardwareList = Object.values(Entry.HARDWARE_LIST);
        return getBlockObject(basicBlockList.concat(hardwareList).concat(expansionBlockList));
    }
}
<|endoftext|>


<commit_before>var Colliders;

(function() {

Colliders = function(options) {
	if(!options) var options = {};

	this.options = options;

	return this;
}

Colliders.prototype.name = "colliders-basic";
Colliders.prototype.type = "Colliders";

/* Include the excellent SAT.js (minified), which does the actual collision checks*/
/* SAT.js - Version 0.4.1 - Copyright 2014 - Jim Riecken <jimr@jimr.ca> - released under the MIT License. https://github.com/jriecken/sat-js */
function w(){function a(b,k){this.x=b||0;this.y=k||0}function e(b,k){this.pos=b||new a;this.points=k||[];this.angle=0;this.offset=new a;this.recalc()}function u(b,k,c){this.pos=b||new a;this.w=k||0;this.h=c||0}function v(){this.b=this.a=null;this.overlapN=new a;this.overlapV=new a;this.clear()}function z(b,k,c){for(var a=Number.MAX_VALUE,f=-Number.MAX_VALUE,h=b.length,l=0;l<h;l++){var g=b[l].d(k);g<a&&(a=g);g>f&&(f=g)}c[0]=a;c[1]=f}function A(b,k,c,a,f,h){var l=q.pop(),g=q.pop();b=d.pop().c(k).sub(b);
k=b.d(f);z(c,f,l);z(a,f,g);g[0]+=k;g[1]+=k;if(l[0]>g[1]||g[0]>l[1])return d.push(b),q.push(l),q.push(g),!0;h&&(c=0,l[0]<g[0]?(h.aInB=!1,l[1]<g[1]?(c=l[1]-g[0],h.bInA=!1):(c=l[1]-g[0],a=g[1]-l[0],c=c<a?c:-a)):(h.bInA=!1,l[1]>g[1]?(c=l[0]-g[1],h.aInB=!1):(c=l[1]-g[0],a=g[1]-l[0],c=c<a?c:-a)),a=Math.abs(c),a<h.overlap&&(h.overlap=a,h.overlapN.c(f),0>c&&h.overlapN.reverse()));d.push(b);q.push(l);q.push(g);return!1}function x(b,k){var c=b.e(),a=k.d(b);return 0>a?-1:a>c?1:0}function B(b,k,c){for(var a=
d.pop().c(k.pos).sub(b.pos),f=k.r,h=f*f,l=b.calcPoints,g=l.length,s=d.pop(),p=d.pop(),m=0;m<g;m++){var e=m===g-1?0:m+1,q=0===m?g-1:m-1,t=0,r=null;s.c(b.edges[m]);p.c(a).sub(l[m]);c&&p.e()>h&&(c.aInB=!1);var n=x(s,p);if(-1===n){s.c(b.edges[q]);e=d.pop().c(a).sub(l[q]);n=x(s,e);if(1===n){n=p.f();if(n>f)return d.push(a),d.push(s),d.push(p),d.push(e),!1;c&&(c.bInA=!1,r=p.normalize(),t=f-n)}d.push(e)}else if(1===n){if(s.c(b.edges[e]),p.c(a).sub(l[e]),n=x(s,p),-1===n){n=p.f();if(n>f)return d.push(a),d.push(s),
d.push(p),!1;c&&(c.bInA=!1,r=p.normalize(),t=f-n)}}else{e=s.g().normalize();n=p.d(e);q=Math.abs(n);if(0<n&&q>f)return d.push(a),d.push(e),d.push(p),!1;c&&(r=e,t=f-n,0<=n||t<2*f)&&(c.bInA=!1)}r&&c&&Math.abs(t)<Math.abs(c.overlap)&&(c.overlap=t,c.overlapN.c(r))}c&&(c.a=b,c.b=k,c.overlapV.c(c.overlapN).scale(c.overlap));d.push(a);d.push(s);d.push(p);return!0}function C(b,a,c){for(var d=b.calcPoints,f=d.length,h=a.calcPoints,l=h.length,g=0;g<f;g++)if(A(b.pos,a.pos,d,h,b.normals[g],c))return!1;for(g=0;g<
l;g++)if(A(b.pos,a.pos,d,h,a.normals[g],c))return!1;c&&(c.a=b,c.b=a,c.overlapV.c(c.overlapN).scale(c.overlap));return!0}var m={};m.Vector=a;m.V=a;a.prototype.copy=a.prototype.c=function(b){this.x=b.x;this.y=b.y;return this};a.prototype.clone=a.prototype.i=function(){return new a(this.x,this.y)};a.prototype.perp=a.prototype.g=function(){var b=this.x;this.x=this.y;this.y=-b;return this};a.prototype.rotate=a.prototype.rotate=function(b){var a=this.x,c=this.y;this.x=a*Math.cos(b)-c*Math.sin(b);this.y=
a*Math.sin(b)+c*Math.cos(b);return this};a.prototype.reverse=a.prototype.reverse=function(){this.x=-this.x;this.y=-this.y;return this};a.prototype.normalize=a.prototype.normalize=function(){var b=this.f();0<b&&(this.x/=b,this.y/=b);return this};a.prototype.add=a.prototype.add=function(b){this.x+=b.x;this.y+=b.y;return this};a.prototype.sub=a.prototype.sub=function(b){this.x-=b.x;this.y-=b.y;return this};a.prototype.scale=a.prototype.scale=function(b,a){this.x*=b;this.y*=a||b;return this};a.prototype.project=
a.prototype.j=function(b){var a=this.d(b)/b.e();this.x=a*b.x;this.y=a*b.y;return this};a.prototype.projectN=a.prototype.k=function(b){var a=this.d(b);this.x=a*b.x;this.y=a*b.y;return this};a.prototype.reflect=function(b){var a=this.x,c=this.y;this.j(b).scale(2);this.x-=a;this.y-=c;return this};a.prototype.reflectN=function(b){var a=this.x,c=this.y;this.k(b).scale(2);this.x-=a;this.y-=c;return this};a.prototype.dot=a.prototype.d=function(b){return this.x*b.x+this.y*b.y};a.prototype.len2=a.prototype.e=
function(){return this.d(this)};a.prototype.len=a.prototype.f=function(){return Math.sqrt(this.e())};m.Circle=function(b,k){this.pos=b||new a;this.r=k||0};m.Polygon=e;e.prototype.setPoints=function(b){this.points=b;this.recalc();return this};e.prototype.setAngle=function(b){this.angle=b;this.recalc();return this};e.prototype.setOffset=function(b){this.offset=b;this.recalc();return this};e.prototype.rotate=e.prototype.rotate=function(b){for(var a=this.points,c=a.length,d=0;d<c;d++)a[d].rotate(b);this.recalc();
return this};e.prototype.translate=e.prototype.translate=function(b,a){for(var c=this.points,d=c.length,f=0;f<d;f++)c[f].x+=b,c[f].y+=a;this.recalc();return this};e.prototype.recalc=e.prototype.recalc=function(){var b,k=this.calcPoints=[],c=this.edges=[],d=this.normals=[],f=this.points,h=this.offset,l=this.angle,g=f.length;for(b=0;b<g;b++){var e=f[b].i();k.push(e);e.x+=h.x;e.y+=h.y;0!==l&&e.rotate(l)}for(b=0;b<g;b++)f=(new a).c(b<g-1?k[b+1]:k[0]).sub(k[b]),h=(new a).c(f).g().normalize(),c.push(f),
d.push(h);return this};m.Box=u;u.prototype.toPolygon=u.prototype.l=function(){var b=this.pos,k=this.w,c=this.h;return new e(new a(b.x,b.y),[new a,new a(k,0),new a(k,c),new a(0,c)])};m.Response=v;v.prototype.clear=v.prototype.clear=function(){this.bInA=this.aInB=!0;this.overlap=Number.MAX_VALUE;return this};for(var d=[],r=0;10>r;r++)d.push(new a);for(var q=[],r=0;5>r;r++)q.push([]);var y=new v,D=(new u(new a,1,1)).l();m.pointInCircle=function(b,a){var c=d.pop().c(b).sub(a.pos),e=a.r*a.r,f=c.e();d.push(c);
return f<=e};m.pointInPolygon=function(b,a){D.pos.c(b);y.clear();var c=C(D,a,y);c&&(c=y.aInB);return c};m.testCircleCircle=function(b,a,c){var e=d.pop().c(a.pos).sub(b.pos),f=b.r+a.r,h=e.e();if(h>f*f)return d.push(e),!1;c&&(h=Math.sqrt(h),c.a=b,c.b=a,c.overlap=f-h,c.overlapN.c(e.normalize()),c.overlapV.c(e).scale(c.overlap),c.aInB=b.r<=a.r&&h<=a.r-b.r,c.bInA=a.r<=b.r&&h<=b.r-a.r);d.push(e);return!0};m.testPolygonCircle=B;m.testCirclePolygon=function(a,d,c){if((a=B(d,a,c))&&c){d=c.a;var e=c.aInB;c.overlapN.reverse();
c.overlapV.reverse();c.a=c.b;c.b=d;c.aInB=c.bInA;c.bInA=e}return a};m.testPolygonPolygon=C;return m}var SAT=w()

})()<commit_msg>Implemented test() on colliders-basic<commit_after>var Colliders;

(function() {

Colliders = function(options) {
	if(!options) var options = {};

	this.options = options;

	return this;
}

Colliders.prototype.name  = "colliders-basic";
Colliders.prototype.type  = "Colliders";
Colliders.prototype.types = ["Box", "Polygon", "Circle"];

Colliders.prototype.test = function(a, b, res) {
	if(a instanceof this.Box) a = a.toPolygon();

	if(a instanceof this.Polygon) {
		if(b instanceof this.Polygon) {
			return SAT.testPolygonPolygon(a, b, res);
		}
		else {
			return SAT.testPolygonCircle(a, b, res);
		}
	}
	else {
		if(b instanceof this.Polygon) {
			SAT.testCirclePolygon(a, b, res);
		}
		else {
			SAT.testCircleCircle(a, b, res);
		}
	}
}

/* Include the excellent SAT.js (minified), which does the actual collision checks*/
/* SAT.js - Version 0.4.1 - Copyright 2014 - Jim Riecken <jimr@jimr.ca> - released under the MIT License. https://github.com/jriecken/sat-js */
function w(){function a(b,k){this.x=b||0;this.y=k||0}function e(b,k){this.pos=b||new a;this.points=k||[];this.angle=0;this.offset=new a;this.recalc()}function u(b,k,c){this.pos=b||new a;this.w=k||0;this.h=c||0}function v(){this.b=this.a=null;this.overlapN=new a;this.overlapV=new a;this.clear()}function z(b,k,c){for(var a=Number.MAX_VALUE,f=-Number.MAX_VALUE,h=b.length,l=0;l<h;l++){var g=b[l].d(k);g<a&&(a=g);g>f&&(f=g)}c[0]=a;c[1]=f}function A(b,k,c,a,f,h){var l=q.pop(),g=q.pop();b=d.pop().c(k).sub(b);
k=b.d(f);z(c,f,l);z(a,f,g);g[0]+=k;g[1]+=k;if(l[0]>g[1]||g[0]>l[1])return d.push(b),q.push(l),q.push(g),!0;h&&(c=0,l[0]<g[0]?(h.aInB=!1,l[1]<g[1]?(c=l[1]-g[0],h.bInA=!1):(c=l[1]-g[0],a=g[1]-l[0],c=c<a?c:-a)):(h.bInA=!1,l[1]>g[1]?(c=l[0]-g[1],h.aInB=!1):(c=l[1]-g[0],a=g[1]-l[0],c=c<a?c:-a)),a=Math.abs(c),a<h.overlap&&(h.overlap=a,h.overlapN.c(f),0>c&&h.overlapN.reverse()));d.push(b);q.push(l);q.push(g);return!1}function x(b,k){var c=b.e(),a=k.d(b);return 0>a?-1:a>c?1:0}function B(b,k,c){for(var a=
d.pop().c(k.pos).sub(b.pos),f=k.r,h=f*f,l=b.calcPoints,g=l.length,s=d.pop(),p=d.pop(),m=0;m<g;m++){var e=m===g-1?0:m+1,q=0===m?g-1:m-1,t=0,r=null;s.c(b.edges[m]);p.c(a).sub(l[m]);c&&p.e()>h&&(c.aInB=!1);var n=x(s,p);if(-1===n){s.c(b.edges[q]);e=d.pop().c(a).sub(l[q]);n=x(s,e);if(1===n){n=p.f();if(n>f)return d.push(a),d.push(s),d.push(p),d.push(e),!1;c&&(c.bInA=!1,r=p.normalize(),t=f-n)}d.push(e)}else if(1===n){if(s.c(b.edges[e]),p.c(a).sub(l[e]),n=x(s,p),-1===n){n=p.f();if(n>f)return d.push(a),d.push(s),
d.push(p),!1;c&&(c.bInA=!1,r=p.normalize(),t=f-n)}}else{e=s.g().normalize();n=p.d(e);q=Math.abs(n);if(0<n&&q>f)return d.push(a),d.push(e),d.push(p),!1;c&&(r=e,t=f-n,0<=n||t<2*f)&&(c.bInA=!1)}r&&c&&Math.abs(t)<Math.abs(c.overlap)&&(c.overlap=t,c.overlapN.c(r))}c&&(c.a=b,c.b=k,c.overlapV.c(c.overlapN).scale(c.overlap));d.push(a);d.push(s);d.push(p);return!0}function C(b,a,c){for(var d=b.calcPoints,f=d.length,h=a.calcPoints,l=h.length,g=0;g<f;g++)if(A(b.pos,a.pos,d,h,b.normals[g],c))return!1;for(g=0;g<
l;g++)if(A(b.pos,a.pos,d,h,a.normals[g],c))return!1;c&&(c.a=b,c.b=a,c.overlapV.c(c.overlapN).scale(c.overlap));return!0}var m={};m.Vector=a;m.V=a;a.prototype.copy=a.prototype.c=function(b){this.x=b.x;this.y=b.y;return this};a.prototype.clone=a.prototype.i=function(){return new a(this.x,this.y)};a.prototype.perp=a.prototype.g=function(){var b=this.x;this.x=this.y;this.y=-b;return this};a.prototype.rotate=a.prototype.rotate=function(b){var a=this.x,c=this.y;this.x=a*Math.cos(b)-c*Math.sin(b);this.y=
a*Math.sin(b)+c*Math.cos(b);return this};a.prototype.reverse=a.prototype.reverse=function(){this.x=-this.x;this.y=-this.y;return this};a.prototype.normalize=a.prototype.normalize=function(){var b=this.f();0<b&&(this.x/=b,this.y/=b);return this};a.prototype.add=a.prototype.add=function(b){this.x+=b.x;this.y+=b.y;return this};a.prototype.sub=a.prototype.sub=function(b){this.x-=b.x;this.y-=b.y;return this};a.prototype.scale=a.prototype.scale=function(b,a){this.x*=b;this.y*=a||b;return this};a.prototype.project=
a.prototype.j=function(b){var a=this.d(b)/b.e();this.x=a*b.x;this.y=a*b.y;return this};a.prototype.projectN=a.prototype.k=function(b){var a=this.d(b);this.x=a*b.x;this.y=a*b.y;return this};a.prototype.reflect=function(b){var a=this.x,c=this.y;this.j(b).scale(2);this.x-=a;this.y-=c;return this};a.prototype.reflectN=function(b){var a=this.x,c=this.y;this.k(b).scale(2);this.x-=a;this.y-=c;return this};a.prototype.dot=a.prototype.d=function(b){return this.x*b.x+this.y*b.y};a.prototype.len2=a.prototype.e=
function(){return this.d(this)};a.prototype.len=a.prototype.f=function(){return Math.sqrt(this.e())};m.Circle=function(b,k){this.pos=b||new a;this.r=k||0};m.Polygon=e;e.prototype.setPoints=function(b){this.points=b;this.recalc();return this};e.prototype.setAngle=function(b){this.angle=b;this.recalc();return this};e.prototype.setOffset=function(b){this.offset=b;this.recalc();return this};e.prototype.rotate=e.prototype.rotate=function(b){for(var a=this.points,c=a.length,d=0;d<c;d++)a[d].rotate(b);this.recalc();
return this};e.prototype.translate=e.prototype.translate=function(b,a){for(var c=this.points,d=c.length,f=0;f<d;f++)c[f].x+=b,c[f].y+=a;this.recalc();return this};e.prototype.recalc=e.prototype.recalc=function(){var b,k=this.calcPoints=[],c=this.edges=[],d=this.normals=[],f=this.points,h=this.offset,l=this.angle,g=f.length;for(b=0;b<g;b++){var e=f[b].i();k.push(e);e.x+=h.x;e.y+=h.y;0!==l&&e.rotate(l)}for(b=0;b<g;b++)f=(new a).c(b<g-1?k[b+1]:k[0]).sub(k[b]),h=(new a).c(f).g().normalize(),c.push(f),
d.push(h);return this};m.Box=u;u.prototype.toPolygon=u.prototype.l=function(){var b=this.pos,k=this.w,c=this.h;return new e(new a(b.x,b.y),[new a,new a(k,0),new a(k,c),new a(0,c)])};m.Response=v;v.prototype.clear=v.prototype.clear=function(){this.bInA=this.aInB=!0;this.overlap=Number.MAX_VALUE;return this};for(var d=[],r=0;10>r;r++)d.push(new a);for(var q=[],r=0;5>r;r++)q.push([]);var y=new v,D=(new u(new a,1,1)).l();m.pointInCircle=function(b,a){var c=d.pop().c(b).sub(a.pos),e=a.r*a.r,f=c.e();d.push(c);
return f<=e};m.pointInPolygon=function(b,a){D.pos.c(b);y.clear();var c=C(D,a,y);c&&(c=y.aInB);return c};m.testCircleCircle=function(b,a,c){var e=d.pop().c(a.pos).sub(b.pos),f=b.r+a.r,h=e.e();if(h>f*f)return d.push(e),!1;c&&(h=Math.sqrt(h),c.a=b,c.b=a,c.overlap=f-h,c.overlapN.c(e.normalize()),c.overlapV.c(e).scale(c.overlap),c.aInB=b.r<=a.r&&h<=a.r-b.r,c.bInA=a.r<=b.r&&h<=b.r-a.r);d.push(e);return!0};m.testPolygonCircle=B;m.testCirclePolygon=function(a,d,c){if((a=B(d,a,c))&&c){d=c.a;var e=c.aInB;c.overlapN.reverse();
c.overlapV.reverse();c.a=c.b;c.b=d;c.aInB=c.bInA;c.bInA=e}return a};m.testPolygonPolygon=C;return m}var SAT=w()

})()<|endoftext|>


<commit_before>import React, { PropTypes as T } from 'react'
import marked from 'marked'
import cNames from 'classnames'
import NotebookActions from 'actions/NotebookActions';
import LoginManager from 'util/LoginManager';
var ot = require('ot');
import API_ROOT from 'util/RouteDetails';

var jsdiff = require('diff');

let ws = null;

require('../..//less/editor.less');

const MdEditor = React.createClass({
  propTypes: {
    content: T.string,
    children: T.node
  },
  getInitialState () {
    console.log(ot)
    let type = location.pathname.split('/').pop();
    let mode = '';
    type === 'editMode'? mode='split': mode='preview'
    return {
      user: LoginManager.getAuthInfo(),
      panelClass: 'md-panel',
      mode: mode,
      isFullScreen: false,
      result: marked(this.props.content || ''),
      content: this.props.content || '',
      note: this.props.note,
      notebookId: this.props.notebookId,
      type: type
    }
  },
  onWebSocketOnOpen() {
    console.log('web socket open!!');
  },
  onWebSocketError(err) {
    console.log(err);
  },
  onWebSocketMessage(evt){
    console.log(evt.data);

  },

  onWebSocketClose(){
    console.log('socket closed');
  },
  componentDidMount () {
    // cache dom node
    let socketUrl = `ws://notion-api-dev.herokuapp.com/v1/note/${this.state.note.id}/ws?token=${this.state.user.fbData.fb_auth_token}`;
    ws = new WebSocket(socketUrl);
    ws.onopen = this.onWebSocketOnOpen;
    ws.onclose = this.onWebSocketClose;
    ws.onerror = this.onWebSocketError;
    ws.onmessage = this.onWebSocketMessage;

    setInterval(() => {
      ws.send(JSON.stringify({'type':'ping'}))
    },10000)

    this.textControl = React.findDOMNode(this.refs.editor)
    this.previewControl = React.findDOMNode(this.refs.preview)
  },
  componentWillUnmount () {
    this.textControl = null
    this.previewControl = null
  },
  render () {
    const panelClass = cNames([ 'md-panel', { 'fullscreen': this.state.isFullScreen } ])
    const editorClass = cNames([ 'md-editor', { 'expand': this.state.mode === 'edit' } ])
    const previewClass = cNames([ 'md-preview', 'markdown', { 'expand': this.state.mode === 'preview', 'shrink': this.state.mode === 'edit' } ])

    return (

          {this._getModeBar()}
          {this._getToolBar()}

          <textarea  defaultValue={this.state.content} ref="editor" name="content" onChange={this._onChange}></textarea>{/* style={{height: this.state.editorHeight + 'px'}} */}

    )
  },
  // public methods
  isDirty () {
    return this._isDirty || false
  },
  getValue () {
    return this.state.content
  },
  // widgets constructors
  _getToolBar () {
    if(this.state.type === 'editMode') {
      return (

{/* bold */}

{/* italic */}

{/* link */}

{/* blockquote */}

{/* code */}

{/* picture-o */}

{/* list-ol */}

{/* list-ul */}

{/* header */}
          {this._getExternalBtn()}

      )
    }
  },
  _getExternalBtn () {
    return React.Children.map(this.props.children, (option) => {
      if (option.type === 'option') {
        return
{option.props.children}

      }
    })
  },
  _getModeBar () {
    const checkActive = (mode) => cNames({ active: this.state.mode === mode })
    if(this.state.type === 'editMode'){
      return (

 { /* preview mode */ }

 { /* split mode */ }

 { /* edit mode */ }

 {/* full-screen */}

 {/* full-screen */}

      )
    } else {

    }
  },
  // event handlers
  _onChange (e) {
    this._isDirty = true // set dirty
    if (this._ltr) clearTimeout(this._ltr)
    this._ltr = setTimeout(() => {
      let text = this.textControl.value;

      let op = this.createOTFromChange(this.state.content, text);
      let update = {type:'update', update:{ops:op}}
      console.log(update)
      ws.send(JSON.stringify(update));
      this.setState({ content: text, result: marked(text) }) // change state
    }, 300)
  },
  createOTFromChange(oldContent, newContent){
    var diff = jsdiff.diffChars(oldContent, newContent);
    //console.log(ot)
    //let op = new ot.TextOperation()
    let op = []
    _.map(diff, (change) => {
      if(change.removed == undefined && change.added == undefined){
        op.push(change.count)
        //op.retain(change.count);
      } else if(change.removed == true){
        op.push(-1*change.count)
        //op.delete(change.value);
      } else if(change.added == true){
        op.push(change.value);
        //op.insert(change.value);
      }
    });
    console.log(op)
    return op;

  },
  _changeMode (mode) {
    return (e) => {
      this.setState({ mode })
    }
  },
  _toggleFullScreen (e) {
    this.setState({ isFullScreen: !this.state.isFullScreen })
  },

  _save(e){
    console.log(this.textControl.value);
    NotebookActions.updateNote(this.state.notebookId, this.state.note.id, this.state.user.fbData.fb_auth_token, this.textControl.value);
  },
  // default text processors
  _preInputText (text, preStart, preEnd) {
    const start = this.textControl.selectionStart
    const end = this.textControl.selectionEnd
    const origin = this.textControl.value

    if (start !== end) {
      const exist = origin.slice(start, end)
      text = text.slice(0, preStart) + exist + text.slice(preEnd)
      preEnd = preStart + exist.length
    }
    this.textControl.value = origin.slice(0, start) + text + origin.slice(end)
    // pre-select
    this.textControl.setSelectionRange(start + preStart, start + preEnd)
    this.setState({ result: marked(this.textControl.value) }) // change state
  },
  _boldText () {
    this._preInputText("**Bold**", 2, 6)
  },
  _italicText () {
    this._preInputText("_Italic_", 1, 5)
  },
  _linkText () {
    this._preInputText("[link](www.yourlink.com)", 1, 5)
  },
  _blockquoteText () {
    this._preInputText("> Block", 2, 4)
  },
  _codeText () {
    this._preInputText("```\ncode block\n```", 4, 14)
  },
  _pictureText () {
    this._preInputText("![alt](www.yourlink.com)", 2, 5)
  },
  _listUlText () {
    this._preInputText("- Item0\n- Item1", 2, 8)
  },
  _listOlText () {
    this._preInputText("1. Item0\n2. Item1", 3, 9)
  },
  _headerText () {
    this._preInputText("## Header", 3, 5)
  }
})

export default MdEditor
<commit_msg>fixed<commit_after>import React, { PropTypes as T } from 'react'
import marked from 'marked'
import cNames from 'classnames'
import NotebookActions from 'actions/NotebookActions';
import LoginManager from 'util/LoginManager';
var ot = require('ot');
import API_ROOT from 'util/RouteDetails';

var jsdiff = require('diff');

let ws = null;

require('../..//less/editor.less');

const MdEditor = React.createClass({
  propTypes: {
    content: T.string,
    children: T.node
  },
  getInitialState () {
    console.log(ot)
    let type = location.pathname.split('/').pop();
    let mode = '';
    type === 'editMode'? mode='split': mode='preview'
    return {
      user: LoginManager.getAuthInfo(),
      panelClass: 'md-panel',
      mode: mode,
      isFullScreen: false,
      result: marked(this.props.content || ''),
      content: this.props.content || '',
      note: this.props.note,
      notebookId: this.props.notebookId,
      type: type
    }
  },
  onWebSocketOnOpen() {
    console.log('web socket open!!');
  },
  onWebSocketError(err) {
    console.log(err);
  },
  onWebSocketMessage(evt){
    console.log(evt.data);

  },

  onWebSocketClose(){
    console.log('socket closed');
  },
  componentDidMount () {
    // cache dom node
    let socketUrl = `ws://notion-api-dev.herokuapp.com/v1/note/${this.state.note.id}/ws?token=${this.state.user.fbData.fb_auth_token}`;
    ws = new WebSocket(socketUrl);
    ws.onopen = this.onWebSocketOnOpen;
    ws.onclose = this.onWebSocketClose;
    ws.onerror = this.onWebSocketError;
    ws.onmessage = this.onWebSocketMessage;

    setInterval(() => {
      ws.send(JSON.stringify({'type':'ping'}))
    },10000)

    this.textControl = React.findDOMNode(this.refs.editor)
    this.previewControl = React.findDOMNode(this.refs.preview)
  },
  componentWillUnmount () {
    this.textControl = null
    this.previewControl = null
  },
  render () {
    const panelClass = cNames([ 'md-panel', { 'fullscreen': this.state.isFullScreen } ])
    const editorClass = cNames([ 'md-editor', { 'expand': this.state.mode === 'edit' } ])
    const previewClass = cNames([ 'md-preview', 'markdown', { 'expand': this.state.mode === 'preview', 'shrink': this.state.mode === 'edit' } ])

    return (

          {this._getModeBar()}
          {this._getToolBar()}

          <textarea  defaultValue={this.state.content} ref="editor" name="content" onChange={this._onChange}></textarea>{/* style={{height: this.state.editorHeight + 'px'}} */}

    )
  },
  // public methods
  isDirty () {
    return this._isDirty || false
  },
  getValue () {
    return this.state.content
  },
  // widgets constructors
  _getToolBar () {
    if(this.state.type === 'editMode') {
      return (

{/* bold */}

{/* italic */}

{/* link */}

{/* blockquote */}

{/* code */}

{/* picture-o */}

{/* list-ol */}

{/* list-ul */}

{/* header */}
          {this._getExternalBtn()}

      )
    }
  },
  _getExternalBtn () {
    return React.Children.map(this.props.children, (option) => {
      if (option.type === 'option') {
        return
{option.props.children}

      }
    })
  },
  _getModeBar () {
    const checkActive = (mode) => cNames({ active: this.state.mode === mode })
    if(this.state.type === 'editMode'){
      return (

 { /* preview mode */ }

 { /* split mode */ }

 { /* edit mode */ }

 {/* full-screen */}

 {/* full-screen */}

      )
    } else {

    }
  },
  // event handlers
  _onChange (e) {
    this._isDirty = true // set dirty
    if (this._ltr) clearTimeout(this._ltr)
    this._ltr = setTimeout(() => {
      let text = this.textControl.value;

      let op = this.createOTFromChange(this.state.content, text);
      let update = {type:'update', update:{ops:op}}
      console.log(update)
      ws.send(JSON.stringify(update));
      this.setState({ content: text, result: marked(text) }) // change state
    }, 300)
  },
  createOTFromChange(oldContent, newContent){
    var diff = jsdiff.diffChars(oldContent, newContent);
    let op = new ot.TextOperation()
    _.map(diff, (change) => {
      if(change.removed == undefined && change.added == undefined){
        op.retain(change.count);
      } else if(change.removed == true){
        op.delete(change.value);
      } else if(change.added == true){
        op.insert(change.value);
      }
    });
    console.log(op)
    return op;

  },
  _changeMode (mode) {
    return (e) => {
      this.setState({ mode })
    }
  },
  _toggleFullScreen (e) {
    this.setState({ isFullScreen: !this.state.isFullScreen })
  },

  _save(e){
    console.log(this.textControl.value);
    NotebookActions.updateNote(this.state.notebookId, this.state.note.id, this.state.user.fbData.fb_auth_token, this.textControl.value);
  },
  // default text processors
  _preInputText (text, preStart, preEnd) {
    const start = this.textControl.selectionStart
    const end = this.textControl.selectionEnd
    const origin = this.textControl.value

    if (start !== end) {
      const exist = origin.slice(start, end)
      text = text.slice(0, preStart) + exist + text.slice(preEnd)
      preEnd = preStart + exist.length
    }
    this.textControl.value = origin.slice(0, start) + text + origin.slice(end)
    // pre-select
    this.textControl.setSelectionRange(start + preStart, start + preEnd)
    this.setState({ result: marked(this.textControl.value) }) // change state
  },
  _boldText () {
    this._preInputText("**Bold**", 2, 6)
  },
  _italicText () {
    this._preInputText("_Italic_", 1, 5)
  },
  _linkText () {
    this._preInputText("[link](www.yourlink.com)", 1, 5)
  },
  _blockquoteText () {
    this._preInputText("> Block", 2, 4)
  },
  _codeText () {
    this._preInputText("```\ncode block\n```", 4, 14)
  },
  _pictureText () {
    this._preInputText("![alt](www.yourlink.com)", 2, 5)
  },
  _listUlText () {
    this._preInputText("- Item0\n- Item1", 2, 8)
  },
  _listOlText () {
    this._preInputText("1. Item0\n2. Item1", 3, 9)
  },
  _headerText () {
    this._preInputText("## Header", 3, 5)
  }
})

export default MdEditor
<|endoftext|>


<commit_before>// vi:ts=2 sw=2 expandtab

/**
 * Verifiers
 * @namespace
 */
JsMockito.Verifiers = {
  _export: ['never', 'zeroInteractions', 'times', 'once'],

  /**
   * Test that a invocation never occurred. For example:
   *

   * verify(mock, never()).method();
   *

   * @see JsMockito.Verifiers.times(0)
   */
  never: function() {
    return new JsMockito.Verifiers.Times(0);
  },

  /** Test that no interaction were made on the mock.  For example:
   *

   * verify(mock, zeroInteractions());
   *

   * @see JsMockito.verifyZeroInteractions()
   */
  zeroInteractions: function() {
    return new JsMockito.Verifiers.ZeroInteractions();
  },

  /**
   * Test that an invocation occurred a specific number of times. For example:
   *

   * verify(mock, times(2)).method();
   *

   *
   * @param wanted The number of desired invocations
   */
  times: function(wanted) {
    return new JsMockito.Verifiers.Times(wanted);
  },

  /**
   * Test that an invocation occurred exactly once. For example:
   *

   * verify(mock, once()).method();
   *

   * This is the default verifier.
   * @see JsMockito.Verifiers.times(1)
   */
  once: function() {
    return new JsMockito.Verifiers.Times(1);
  }
};

JsMockito.Verifier = function() { this.init.apply(this, arguments) };
JsMockito.Verifier.prototype = {
  init: function() { },

  verify: function(mock) {
    var self = this;
    return mock._jsMockitoVerifier(JsHamcrest.Matchers.anything(), function() {
      self.verifyInteractions.apply(self, arguments);
    });
  },

  verifyInteractions: function(funcName, interactions, matchers, withContext) {
  },

  buildDescription: function(message, funcName, matchers, withContext) {
    var description = new JsHamcrest.Description();
    description.append(message + ': ' + funcName + '(');
    JsMockito.each(matchers.slice(1), function(matcher, i) {
      if (i > 0)
        description.append(', ');
      description.append('<');
      matcher.describeTo(description);
      description.append('>');
    });
    description.append(")");
    if (withContext) {
      description.append(", 'this' being ");
      matchers[0].describeTo(description);
    }
    return description;
  }
};

JsMockito.verifier('Times', {
  init: function(wanted) {
    this.wanted = wanted;
  },

  verifyInteractions: function(funcName, interactions, matchers, withContext) {
    var interactions = JsMockito.grep(interactions, function(interaction) {
      return JsMockito.matchArray(matchers, interaction);
    });
    if (interactions.length == this.wanted)
      return;

    var message;
    if (interactions.length == 0) {
      message = 'Wanted but not invoked';
    } else if (this.wanted == 0) {
      message = 'Never wanted but invoked';
    } else if (this.wanted == 1) {
      message = 'Wanted 1 invocation but got ' + interactions.length;
    } else {
      message = 'Wanted ' + this.wanted + ' invocations but got ' + interactions.length;
    }

    var description = this.buildDescription(message, funcName, matchers, withContext);
    throw description.get();
  }
});

JsMockito.verifier('ZeroInteractions', {
  verify: function(mock) {
    var neverVerifier = JsMockito.Verifiers.never();
    JsMockito.each(mock._jsMockitoMockFunctions(), function(mockFunc) {
      neverVerifier.verify(mockFunc)();
    });
  }
});
<commit_msg>Renamed withContext to describeContext, for better clarity<commit_after>// vi:ts=2 sw=2 expandtab

/**
 * Verifiers
 * @namespace
 */
JsMockito.Verifiers = {
  _export: ['never', 'zeroInteractions', 'times', 'once'],

  /**
   * Test that a invocation never occurred. For example:
   *

   * verify(mock, never()).method();
   *

   * @see JsMockito.Verifiers.times(0)
   */
  never: function() {
    return new JsMockito.Verifiers.Times(0);
  },

  /** Test that no interaction were made on the mock.  For example:
   *

   * verify(mock, zeroInteractions());
   *

   * @see JsMockito.verifyZeroInteractions()
   */
  zeroInteractions: function() {
    return new JsMockito.Verifiers.ZeroInteractions();
  },

  /**
   * Test that an invocation occurred a specific number of times. For example:
   *

   * verify(mock, times(2)).method();
   *

   *
   * @param wanted The number of desired invocations
   */
  times: function(wanted) {
    return new JsMockito.Verifiers.Times(wanted);
  },

  /**
   * Test that an invocation occurred exactly once. For example:
   *

   * verify(mock, once()).method();
   *

   * This is the default verifier.
   * @see JsMockito.Verifiers.times(1)
   */
  once: function() {
    return new JsMockito.Verifiers.Times(1);
  }
};

JsMockito.Verifier = function() { this.init.apply(this, arguments) };
JsMockito.Verifier.prototype = {
  init: function() { },

  verify: function(mock) {
    var self = this;
    return mock._jsMockitoVerifier(JsHamcrest.Matchers.anything(), function() {
      self.verifyInteractions.apply(self, arguments);
    });
  },

  verifyInteractions: function(funcName, interactions, matchers, describeContext) {
  },

  buildDescription: function(message, funcName, matchers, describeContext) {
    var description = new JsHamcrest.Description();
    description.append(message + ': ' + funcName + '(');
    JsMockito.each(matchers.slice(1), function(matcher, i) {
      if (i > 0)
        description.append(', ');
      description.append('<');
      matcher.describeTo(description);
      description.append('>');
    });
    description.append(")");
    if (describeContext) {
      description.append(", 'this' being ");
      matchers[0].describeTo(description);
    }
    return description;
  }
};

JsMockito.verifier('Times', {
  init: function(wanted) {
    this.wanted = wanted;
  },

  verifyInteractions: function(funcName, interactions, matchers, describeContext) {
    var interactions = JsMockito.grep(interactions, function(interaction) {
      return JsMockito.matchArray(matchers, interaction);
    });
    if (interactions.length == this.wanted)
      return;

    var message;
    if (interactions.length == 0) {
      message = 'Wanted but not invoked';
    } else if (this.wanted == 0) {
      message = 'Never wanted but invoked';
    } else if (this.wanted == 1) {
      message = 'Wanted 1 invocation but got ' + interactions.length;
    } else {
      message = 'Wanted ' + this.wanted + ' invocations but got ' + interactions.length;
    }

    var description = this.buildDescription(message, funcName, matchers, describeContext);
    throw description.get();
  }
});

JsMockito.verifier('ZeroInteractions', {
  verify: function(mock) {
    var neverVerifier = JsMockito.Verifiers.never();
    JsMockito.each(mock._jsMockitoMockFunctions(), function(mockFunc) {
      neverVerifier.verify(mockFunc)();
    });
  }
});
<|endoftext|>


<commit_before>import {Title} from './plugin.title';
import layouts from '../core/core.layouts';

const map = new WeakMap();

export default {
  id: 'subtitle',

  start(chart, _args, options) {
    const title = new Title({
      ctx: chart.ctx,
      options,
      chart
    });

    layouts.configure(chart, title, options);
    layouts.addBox(chart, title);
    map.set(chart, title);
  },

  stop(chart) {
    layouts.removeBox(chart, map.get(chart));
    map.delete(chart);
  },

  beforeUpdate(chart, _args, options) {
    const title = map.get(chart);
    layouts.configure(chart, title, options);
    title.options = options;
  },

  defaults: {
    align: 'center',
    display: false,
    font: {
      weight: 'normal',
    },
    fullSize: true,
    padding: 0,
    position: 'top',
    text: '',
    weight: 1500         // by default greater than legend (1000) and smaller that title (2000)
  },

  defaultRoutes: {
    color: 'color'
  },

  descriptors: {
    _scriptable: true,
    _indexable: false,
  },
};
<commit_msg>Fix: Typo that-->than (#9708)<commit_after>import {Title} from './plugin.title';
import layouts from '../core/core.layouts';

const map = new WeakMap();

export default {
  id: 'subtitle',

  start(chart, _args, options) {
    const title = new Title({
      ctx: chart.ctx,
      options,
      chart
    });

    layouts.configure(chart, title, options);
    layouts.addBox(chart, title);
    map.set(chart, title);
  },

  stop(chart) {
    layouts.removeBox(chart, map.get(chart));
    map.delete(chart);
  },

  beforeUpdate(chart, _args, options) {
    const title = map.get(chart);
    layouts.configure(chart, title, options);
    title.options = options;
  },

  defaults: {
    align: 'center',
    display: false,
    font: {
      weight: 'normal',
    },
    fullSize: true,
    padding: 0,
    position: 'top',
    text: '',
    weight: 1500         // by default greater than legend (1000) and smaller than title (2000)
  },

  defaultRoutes: {
    color: 'color'
  },

  descriptors: {
    _scriptable: true,
    _indexable: false,
  },
};
<|endoftext|>


<commit_before>"use strict";

var _ = require('lodash');

var po = require('../../pageobjects/pageobjects.js');
var fixtures = require('../../fixtures/fixtures');
var arrayAssert = require('../arrayAssert')();
var devApi = require('../devApi')();
var common = require('../common');

describe('facility view', function () {
    var facFull = fixtures.facilitiesFixture.dummies.facFull;
    var facCar = fixtures.facilitiesFixture.dummies.facCar;

    var viewPage = po.facilityViewPage({});
    var portView = viewPage.portView;
    var editPage = po.facilityEditPage({});
    var listPage = po.hubListPage({});

    var f;

    function toView(f, addPredictions) {
        devApi.resetAll({ facilities: [f], contacts: [fixtures.facilitiesFixture.contact], operators: [fixtures.facilitiesFixture.operator]});
        if (addPredictions) {
            devApi.fakeUtilization(f.id);
            devApi.triggerPredictions();
        }
        viewPage.get(f.id);
        expect(viewPage.isDisplayed()).toBe(true);
        return f;
    }

    describe('navigation', function () {
        beforeEach(function () {
            f = toView(facFull);
        });

        it('to hub list', function () {
            viewPage.toListView();
            expect(listPage.isDisplayed()).toBe(true);
        });

        it('to edit view', function () {
            devApi.loginAs('ADMIN');
            viewPage.get(f.id);
            viewPage.toEditView();
            expect(editPage.isDisplayed()).toBe(true);
        });
    });

    describe('with full data', function () {
        beforeEach(function () {
            f = toView(facFull, true);
        });

        it('displays full data', function () {
            expect(viewPage.getName()).toBe(f.name);

            expect(viewPage.isAliasesDisplayed()).toBe(true);
            expect(viewPage.getAliases()).toEqual(f.aliases);

            arrayAssert.assertInOrder(viewPage.capacitiesTable.getTypes(), common.capacityTypeOrder);
            expect(viewPage.capacitiesTable.getCapacities(_.keys(f.builtCapacity))).toEqual(f.builtCapacity);

            expect(viewPage.isPredictionsDisplayed()).toBe(true);
            // 4 since devApi creates four rows. Two for CAR, one for DISABLED and ELECTIC_CAR
            // See fi.hsl.parkandride.dev.DevController#generateUtilizationData
            expect(viewPage.predictionsTable.getSize()).toBe(4);
            // The second row is empty: we don't want repeated titles
            expect(viewPage.predictionsTable.getTypes()).toEqual(['Henkilöauto', '', 'Invapaikka', 'Sähköauto']);
            expect(viewPage.predictionsTable.getUsages()).toEqual(['Liityntä', 'Kaupallinen', 'Liityntä', 'Liityntä']);

            expect(viewPage.isServicesDisplayed()).toBe(true);
            expect(viewPage.getServices()).toEqual("Valaistus, Katettu");

            expect(viewPage.isPaymentInfoDisplayed()).toBe(true);
            expect(viewPage.getPaymentMethods()).toEqual("Kolikko, Seteli");

            expect(viewPage.getOpeningHours()).toEqual({
                "Arkipäivä": "00 - 24",
                "Lauantai": "08 - 18",
                "Sunnuntai": "Kiinni"
            });

            expect(viewPage.getPricing()).toEqual([
                {capacityType: "Henkilöauto", usage: "Liityntä", maxCapacity: "10",
                    dayType: "Arkipäivä", is24h: "✓", from: "", until: "",
                    isFree: "✓", priceFi: "", priceSv: "", priceEn: ""},
                {capacityType: "Invapaikka", usage: "Kaupallinen", maxCapacity: "40",
                    dayType: "Lauantai", is24h: "", from: "08", until: "18",
                    isFree: "", priceFi: "price fi", priceSv: "price sv", priceEn: "price en"},
                {"capacityType":"Sähköauto","usage":"Kaupallinen","maxCapacity":"60",
                    "dayType":"Lauantai", is24h: "", from:"08","until":"18",
                    isFree: "", "priceFi":"price fi","priceSv":"price sv","priceEn":"price en"},
                {"capacityType":"Moottoripyörä","usage":"Liityntä","maxCapacity":"50",
                    dayType: "Arkipäivä", is24h: "✓", from: "", until: "",
                    isFree: "✓", priceFi: "", priceSv: "", priceEn: ""},
                {"capacityType":"Polkupyörä","usage":"Liityntä","maxCapacity":"20",
                    "dayType":"Arkipäivä", is24h: "✓", "from":"","until":"",
                    isFree: "✓", priceFi: "", priceSv: "", priceEn: ""},
                {"capacityType":"Polkupyörä, lukittu tila","usage":"Kaupallinen","maxCapacity":"30",
                    "dayType":"Lauantai", is24h: "", from:"08","until":"18",
                    isFree: "", "priceFi":"price fi","priceSv":"price sv","priceEn":"price en"}
            ]);

            expect(viewPage.getUnavailableCapacities()).toEqual([
                {capacityType: "Henkilöauto", usage: "Liityntä", capacity: "1"},
                {capacityType: "Invapaikka", usage: "Kaupallinen", capacity: "0"},
                {capacityType: "Sähköauto", usage: "Kaupallinen", capacity: "0"},
                {capacityType: "Moottoripyörä", usage: "Liityntä", capacity: "0"},
                {capacityType: "Polkupyörä", usage: "Liityntä", capacity: "0"},
                {capacityType: "Polkupyörä, lukittu tila", usage: "Kaupallinen", capacity: "0"},
            ]);
        });
    });

    it('view port', function() {
        f = {
            "id":1,"name":{"fi":"test","sv":"test","en":"tes"},
            "aliases":[],"capacities":{},"services":[],
            "operatorId": 1,
            "status": "IN_OPERATION",
            "contacts":{
                "emergency": 1,
                "operator": 1
            },
            "pricingMethod": "CUSTOM",
            "location":{"type":"Polygon","coordinates":[[[24.943295535227904,60.17184809821847],[24.944218215129023,60.17186410779244],[24.94464736857141,60.17192280949709],[24.94479757227624,60.17077543898606],[24.944293316981444,60.17060466413514],[24.9436925021621,60.170572643751754],[24.9434028235885,60.17073274535653],[24.943295535227904,60.17184809821847]]]},
            "ports":[{
                "location":{"type":"Point","coordinates":[24.944605,60.17197]},
                "entry":true,"exit":true,"pedestrian":true,"bicycle":true,
                "address":{"streetAddress":{"fi":"Vilhonkatu 9","sv":"Vilhelmsgatan 9","en":"Vilhonkatu 9"},
                    "postalCode":"00100","city":{"fi":"Helsinki","sv":"Helsingfors","en":"Helsinki"}},
                "info":{"fi":"Info fi","sv":"Info sv","en":"Info en"}}]
            };
        f.toPayload = function() { return f; };
        f = toView(f);
        viewPage.openPortAt(592, 109);
        expect(portView.isDisplayed()).toBe(true);
        expect(portView.isEntrySelected()).toBe(true);
        expect(portView.isExitSelected()).toBe(true);
        expect(portView.isPedestrianSelected()).toBe(true);
        expect(portView.isBicycleSelected()).toBe(true);
        expect(portView.getStreetAddress()).toEqual(["Vilhonkatu 9", "Vilhelmsgatan 9", "Vilhonkatu 9"]);
        expect(portView.getPostalCode()).toBe("00100");
        expect(portView.getCity()).toEqual(["Helsinki", "Helsingfors", "Helsinki"]);
        expect(portView.getInfo()).toEqual(["Info fi", "Info sv", "Info en"]);
        portView.ok();
        expect(portView.isDisplayed()).toBe(false);
    });

    describe('without aliases', function () {
        beforeEach(function () {
            f = facFull.copy();
            f.aliases = [];
            toView(f);
        });

        it('aliases are not displayed', function () {
            expect(viewPage.isAliasesDisplayed()).toBe(false);
        });
    });

    describe('without services', function () {
        beforeEach(function () {
            f = facFull.copy();
            f.services = [];
            toView(f);
        });

        it('services are not displayed', function () {
            expect(viewPage.isServicesDisplayed()).toBe(false);
        });
    });

    describe('payment info', function () {
        describe('without any info', function () {
            beforeEach(function () {
                f = facFull.copy();
                f.paymentInfo = {};
                toView(f);
            });

            it('payment info is not displayed', function () {
                expect(viewPage.isPaymentInfoDisplayed()).toBe(false);
            });
        });

        describe('with payment methods', function () {
            beforeEach(function () {
                f = facFull.copy();
                f.paymentInfo = {};
                f.paymentInfo.paymentMethods = facFull.copy().paymentInfo.paymentMethods;
                toView(f);
            });

            it('payment info is displayed', function () {
                expect(viewPage.isPaymentInfoDisplayed()).toBe(true);
                expect(viewPage.getPaymentMethods()).toEqual("Kolikko, Seteli");
                expect(viewPage.isPaymentInfoDetailsDisplayed()).toBe(false);
            });
        });

        describe('with details', function () {
            beforeEach(function () {
                f = facFull.copy();
                f.paymentInfo = {};
                f.paymentInfo.detail = facFull.copy().paymentInfo.detail;
                toView(f);
            });

            it('payment info is displayed', function () {
                expect(viewPage.isPaymentInfoDisplayed()).toBe(true);
                expect(viewPage.isPaymentMethodsDisplayed()).toBe(false);
                expect(viewPage.isPaymentInfoDetailsDisplayed()).toBe(true);
                expect(viewPage.getPaymentInfoDetail()).toEqual([f.paymentInfo.detail.fi, f.paymentInfo.detail.sv, f.paymentInfo.detail.en]);
            });
        });

        describe('with url', function () {
            beforeEach(function () {
                f = facFull.copy();
                f.paymentInfo = {};
                f.paymentInfo.url = facFull.copy().paymentInfo.url;
                toView(f);
            });

            it('payment info is displayed', function () {
                expect(viewPage.isPaymentInfoDisplayed()).toBe(true);
                expect(viewPage.isPaymentMethodsDisplayed()).toBe(false);
                expect(viewPage.isPaymentInfoDetailsDisplayed()).toBe(true);
                expect(viewPage.getPaymentInfoUrl()).toEqual([f.paymentInfo.url.fi, f.paymentInfo.url.sv, f.paymentInfo.url.en]);
            });
        });
    });

    describe('with one capacity', function () {
        beforeEach(function () {
            f = toView(facCar);
        });

        it('single capacity is displayed', function () {
            expect(viewPage.capacitiesTable.isDisplayed()).toBe(true);
            expect(viewPage.capacitiesTable.getSize()).toBe(1);
            expect(viewPage.capacitiesTable.getCapacities(_.keys(f.capacities))).toEqual(f.capacities);
        });
    });

    describe('without capacities', function () {
        beforeEach(function () {
            f = facFull.copy();
            f.builtCapacity = {};
            toView(f);
        });

        it('capacities are not displayed', function () {
            expect(viewPage.capacitiesTable.isDisplayed()).toBe(false);
        });
    });

    describe('without predictions', function() {
        beforeEach(function() {
            f = toView(facFull);
        });

        it('should not display predictions table', function() {
            expect(viewPage.isPredictionsDisplayed()).toBe(false);
        });
    });
});
<commit_msg>fixup! fix(utilization): hide utilization and prediction without usage<commit_after>"use strict";

var _ = require('lodash');

var po = require('../../pageobjects/pageobjects.js');
var fixtures = require('../../fixtures/fixtures');
var arrayAssert = require('../arrayAssert')();
var devApi = require('../devApi')();
var common = require('../common');

describe('facility view', function () {
    var facFull = fixtures.facilitiesFixture.dummies.facFull;
    var facCar = fixtures.facilitiesFixture.dummies.facCar;

    var viewPage = po.facilityViewPage({});
    var portView = viewPage.portView;
    var editPage = po.facilityEditPage({});
    var listPage = po.hubListPage({});

    var f;

    function toView(f, addPredictions) {
        devApi.resetAll({ facilities: [f], contacts: [fixtures.facilitiesFixture.contact], operators: [fixtures.facilitiesFixture.operator]});
        if (addPredictions) {
            devApi.fakeUtilization(f.id);
            devApi.triggerPredictions();
        }
        viewPage.get(f.id);
        expect(viewPage.isDisplayed()).toBe(true);
        return f;
    }

    describe('navigation', function () {
        beforeEach(function () {
            f = toView(facFull);
        });

        it('to hub list', function () {
            viewPage.toListView();
            expect(listPage.isDisplayed()).toBe(true);
        });

        it('to edit view', function () {
            devApi.loginAs('ADMIN');
            viewPage.get(f.id);
            viewPage.toEditView();
            expect(editPage.isDisplayed()).toBe(true);
        });
    });

    describe('with full data', function () {
        beforeEach(function () {
            var fac = facFull.copy();
            fac.pricing.push({"capacityType":"CAR","usage":"COMMERCIAL","maxCapacity":5,"dayType":"SATURDAY",
                "time":{"from":"08","until":"18"},"price":"1e"});
            f = toView(fac, true);
        });

        it('displays full data', function () {
            expect(viewPage.getName()).toBe(f.name);

            expect(viewPage.isAliasesDisplayed()).toBe(true);
            expect(viewPage.getAliases()).toEqual(f.aliases);

            arrayAssert.assertInOrder(viewPage.capacitiesTable.getTypes(), common.capacityTypeOrder);
            expect(viewPage.capacitiesTable.getCapacities(_.keys(f.builtCapacity))).toEqual(f.builtCapacity);

            expect(viewPage.isPredictionsDisplayed()).toBe(true);
            // 4 since devApi creates four rows. Two for CAR, one for DISABLED and ELECTIC_CAR
            // See fi.hsl.parkandride.dev.DevController#generateUtilizationData
            expect(viewPage.predictionsTable.getSize()).toBe(7);
            // The second row is empty: we don't want repeated titles
            expect(viewPage.predictionsTable.getTypes()).toEqual(
                ['Henkilöauto', '', 'Invapaikka', 'Sähköauto', 'Moottoripyörä', 'Polkupyörä', 'Polkupyörä, lukittu tila']);
            expect(viewPage.predictionsTable.getUsages()).toEqual(
                ['Liityntä', 'Kaupallinen', 'Kaupallinen', 'Kaupallinen', 'Liityntä', 'Liityntä', 'Kaupallinen']
            );

            expect(viewPage.isServicesDisplayed()).toBe(true);
            expect(viewPage.getServices()).toEqual("Valaistus, Katettu");

            expect(viewPage.isPaymentInfoDisplayed()).toBe(true);
            expect(viewPage.getPaymentMethods()).toEqual("Kolikko, Seteli");

            expect(viewPage.getOpeningHours()).toEqual({
                "Arkipäivä": "00 - 24",
                "Lauantai": "08 - 18",
                "Sunnuntai": "Kiinni"
            });

            expect(viewPage.getPricing()).toEqual([
                {capacityType: "Henkilöauto", usage: "Liityntä", maxCapacity: "10",
                    dayType: "Arkipäivä", is24h: "✓", from: "", until: "",
                    isFree: "✓", priceFi: "", priceSv: "", priceEn: ""},
                {capacityType: "", usage: "Kaupallinen", maxCapacity: "5",
                    dayType: "Lauantai", is24h: "", from: "08", until: "18",
                    isFree: "", priceFi: "1e", priceSv: "1e", priceEn: "1e"},
                {capacityType: "Invapaikka", usage: "Kaupallinen", maxCapacity: "40",
                    dayType: "Lauantai", is24h: "", from: "08", until: "18",
                    isFree: "", priceFi: "price fi", priceSv: "price sv", priceEn: "price en"},
                {"capacityType":"Sähköauto","usage":"Kaupallinen","maxCapacity":"60",
                    "dayType":"Lauantai", is24h: "", from:"08","until":"18",
                    isFree: "", "priceFi":"price fi","priceSv":"price sv","priceEn":"price en"},
                {"capacityType":"Moottoripyörä","usage":"Liityntä","maxCapacity":"50",
                    dayType: "Arkipäivä", is24h: "✓", from: "", until: "",
                    isFree: "✓", priceFi: "", priceSv: "", priceEn: ""},
                {"capacityType":"Polkupyörä","usage":"Liityntä","maxCapacity":"20",
                    "dayType":"Arkipäivä", is24h: "✓", "from":"","until":"",
                    isFree: "✓", priceFi: "", priceSv: "", priceEn: ""},
                {"capacityType":"Polkupyörä, lukittu tila","usage":"Kaupallinen","maxCapacity":"30",
                    "dayType":"Lauantai", is24h: "", from:"08","until":"18",
                    isFree: "", "priceFi":"price fi","priceSv":"price sv","priceEn":"price en"}
            ]);

            expect(viewPage.getUnavailableCapacities()).toEqual([
                {capacityType: "Henkilöauto", usage: "Liityntä", capacity: "1"},
                {capacityType: "", usage: "Kaupallinen", capacity: "0"},
                {capacityType: "Invapaikka", usage: "Kaupallinen", capacity: "0"},
                {capacityType: "Sähköauto", usage: "Kaupallinen", capacity: "0"},
                {capacityType: "Moottoripyörä", usage: "Liityntä", capacity: "0"},
                {capacityType: "Polkupyörä", usage: "Liityntä", capacity: "0"},
                {capacityType: "Polkupyörä, lukittu tila", usage: "Kaupallinen", capacity: "0"},
            ]);
        });
    });

    it('view port', function() {
        f = {
            "id":1,"name":{"fi":"test","sv":"test","en":"tes"},
            "aliases":[],"capacities":{},"services":[],
            "operatorId": 1,
            "status": "IN_OPERATION",
            "contacts":{
                "emergency": 1,
                "operator": 1
            },
            "pricingMethod": "CUSTOM",
            "location":{"type":"Polygon","coordinates":[[[24.943295535227904,60.17184809821847],[24.944218215129023,60.17186410779244],[24.94464736857141,60.17192280949709],[24.94479757227624,60.17077543898606],[24.944293316981444,60.17060466413514],[24.9436925021621,60.170572643751754],[24.9434028235885,60.17073274535653],[24.943295535227904,60.17184809821847]]]},
            "ports":[{
                "location":{"type":"Point","coordinates":[24.944605,60.17197]},
                "entry":true,"exit":true,"pedestrian":true,"bicycle":true,
                "address":{"streetAddress":{"fi":"Vilhonkatu 9","sv":"Vilhelmsgatan 9","en":"Vilhonkatu 9"},
                    "postalCode":"00100","city":{"fi":"Helsinki","sv":"Helsingfors","en":"Helsinki"}},
                "info":{"fi":"Info fi","sv":"Info sv","en":"Info en"}}]
            };
        f.toPayload = function() { return f; };
        f = toView(f);
        viewPage.openPortAt(592, 109);
        expect(portView.isDisplayed()).toBe(true);
        expect(portView.isEntrySelected()).toBe(true);
        expect(portView.isExitSelected()).toBe(true);
        expect(portView.isPedestrianSelected()).toBe(true);
        expect(portView.isBicycleSelected()).toBe(true);
        expect(portView.getStreetAddress()).toEqual(["Vilhonkatu 9", "Vilhelmsgatan 9", "Vilhonkatu 9"]);
        expect(portView.getPostalCode()).toBe("00100");
        expect(portView.getCity()).toEqual(["Helsinki", "Helsingfors", "Helsinki"]);
        expect(portView.getInfo()).toEqual(["Info fi", "Info sv", "Info en"]);
        portView.ok();
        expect(portView.isDisplayed()).toBe(false);
    });

    describe('without aliases', function () {
        beforeEach(function () {
            f = facFull.copy();
            f.aliases = [];
            toView(f);
        });

        it('aliases are not displayed', function () {
            expect(viewPage.isAliasesDisplayed()).toBe(false);
        });
    });

    describe('without services', function () {
        beforeEach(function () {
            f = facFull.copy();
            f.services = [];
            toView(f);
        });

        it('services are not displayed', function () {
            expect(viewPage.isServicesDisplayed()).toBe(false);
        });
    });

    describe('payment info', function () {
        describe('without any info', function () {
            beforeEach(function () {
                f = facFull.copy();
                f.paymentInfo = {};
                toView(f);
            });

            it('payment info is not displayed', function () {
                expect(viewPage.isPaymentInfoDisplayed()).toBe(false);
            });
        });

        describe('with payment methods', function () {
            beforeEach(function () {
                f = facFull.copy();
                f.paymentInfo = {};
                f.paymentInfo.paymentMethods = facFull.copy().paymentInfo.paymentMethods;
                toView(f);
            });

            it('payment info is displayed', function () {
                expect(viewPage.isPaymentInfoDisplayed()).toBe(true);
                expect(viewPage.getPaymentMethods()).toEqual("Kolikko, Seteli");
                expect(viewPage.isPaymentInfoDetailsDisplayed()).toBe(false);
            });
        });

        describe('with details', function () {
            beforeEach(function () {
                f = facFull.copy();
                f.paymentInfo = {};
                f.paymentInfo.detail = facFull.copy().paymentInfo.detail;
                toView(f);
            });

            it('payment info is displayed', function () {
                expect(viewPage.isPaymentInfoDisplayed()).toBe(true);
                expect(viewPage.isPaymentMethodsDisplayed()).toBe(false);
                expect(viewPage.isPaymentInfoDetailsDisplayed()).toBe(true);
                expect(viewPage.getPaymentInfoDetail()).toEqual([f.paymentInfo.detail.fi, f.paymentInfo.detail.sv, f.paymentInfo.detail.en]);
            });
        });

        describe('with url', function () {
            beforeEach(function () {
                f = facFull.copy();
                f.paymentInfo = {};
                f.paymentInfo.url = facFull.copy().paymentInfo.url;
                toView(f);
            });

            it('payment info is displayed', function () {
                expect(viewPage.isPaymentInfoDisplayed()).toBe(true);
                expect(viewPage.isPaymentMethodsDisplayed()).toBe(false);
                expect(viewPage.isPaymentInfoDetailsDisplayed()).toBe(true);
                expect(viewPage.getPaymentInfoUrl()).toEqual([f.paymentInfo.url.fi, f.paymentInfo.url.sv, f.paymentInfo.url.en]);
            });
        });
    });

    describe('with one capacity', function () {
        beforeEach(function () {
            f = toView(facCar);
        });

        it('single capacity is displayed', function () {
            expect(viewPage.capacitiesTable.isDisplayed()).toBe(true);
            expect(viewPage.capacitiesTable.getSize()).toBe(1);
            expect(viewPage.capacitiesTable.getCapacities(_.keys(f.capacities))).toEqual(f.capacities);
        });
    });

    describe('without capacities', function () {
        beforeEach(function () {
            f = facFull.copy();
            f.builtCapacity = {};
            toView(f);
        });

        it('capacities are not displayed', function () {
            expect(viewPage.capacitiesTable.isDisplayed()).toBe(false);
        });
    });

    describe('without predictions', function() {
        beforeEach(function() {
            f = toView(facFull);
        });

        it('should not display predictions table', function() {
            expect(viewPage.isPredictionsDisplayed()).toBe(false);
        });
    });
});
<|endoftext|>


<commit_before>import React from 'react';
import {Link} from 'react-router';
import {load} from '../actions/infoActions';
import Stylesheet from 'react-style';
import InfoBar from '../components/InfoBar';

const styles = Stylesheet.create({
  app: {
    color: 'blue'
  }
});

export default class App {
  static fetchData(dispatch) {
    return dispatch(load());
  }

  render() {
    return (

React Redux Example

by @erikras

<Link to="/">Home</Link>

<Link to="/sign-up">Sign Up</Link>

<Link to="/login">Login</Link>

        <InfoBar/>

          {this.props.children}

    );
  }
}
<commit_msg>added silly little star iframe<commit_after>import React from 'react';
import {Link} from 'react-router';
import {load} from '../actions/infoActions';
import Stylesheet from 'react-style';
import InfoBar from '../components/InfoBar';

const styles = Stylesheet.create({
  app: {
    color: 'blue'
  },
  iframe: {
    border: 'none'
  }
});

export default class App {
  static fetchData(dispatch) {
    return dispatch(load());
  }

  render() {
    return (

React Redux Example

by @erikras

<Link to="/">Home</Link>

<Link to="/sign-up">Sign Up</Link>

<Link to="/login">Login</Link>

        <InfoBar/>

          {this.props.children}

    );
  }
}
<|endoftext|>