<commit_before>/*
 *  Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

var BeakerPageObject = require('./beaker.po.js');
var path = require('path');
var os = require('os');
var beakerPO;

describe('EasyForm', function () {

  function loadGroovy() {
    beakerPO.notebookMenu.click();
    beakerPO.languageManagerMenuItem.click();
    beakerPO.languageManagerButton('Groovy').click();
    beakerPO.waitForPlugin('Groovy');
    beakerPO.languageManagerCloseButton.click();
  }

  function testUndoRedo(code, selector) {
    beakerPO.setCellInput(code);
    beakerPO.evaluateCell();
    beakerPO.waitForCellOutput();

    var e = element(by.css(selector));

    e.sendKeys("TEST");
    expect(e.getAttribute('value')).toEqual("TEST");

    //TEST UNDO
    if (os.type() === 'Darwin') {
      webdriver.
      //COMMAND:      '\uE03D',  // Apple command key
      e.sendKeys("\uE03Dz");
    }
    else {
      //CONTROL:      '\uE009',
      e.sendKeys("\uE009z");
    }
    expect(e.getAttribute('value')).toEqual("");

    //TEST REDO
    //SHIFT:        '\uE008',
    if (os.type() === 'Darwin') {
      //COMMAND:      '\uE03D',  // Apple command key
      e.sendKeys("\uE008\uE03Dz");
    } else {
      //CONTROL:      '\uE009',
      e.sendKeys("\uE008\uE009z");
    }
    expect(e.getAttribute('value')).toEqual("TEST");
  }

  beforeEach(function () {
    beakerPO = new BeakerPageObject();
    browser.get(beakerPO.baseURL);
    browser.waitForAngular();
    beakerPO.newEmptyNotebook.click();
    loadGroovy();
    beakerPO.insertCellButton.click();
  });

  afterEach(function (done) {
    beakerPO.closeNotebook()
      .then(done);
  });

  it('Text Fields', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addTextField(\"first\", 15)\\n';
    code += 'f1.addTextField(\"second\", 15)\\n';
    code += 'f1';

    beakerPO.setCellInput(code);
    beakerPO.evaluateCell();
    beakerPO.waitForCellOutput();

    expect(element.all(by.css('bk-output-display  .text-field')).count()).toBe(2);
  });

  it('Text Areas', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addTextArea(\"Text Area\")\\n';
    code += 'f1';

    beakerPO.setCellInput(code);
    beakerPO.evaluateCell();
    beakerPO.waitForCellOutput();

    expect(element(by.css('bk-output-display  .text-area')).isPresent()).toBe(true);
  });

  it('Dates', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addDatePicker(\"Date\")\\n';
    code += 'f1';

    beakerPO.setCellInput(code);
    beakerPO.evaluateCell();
    beakerPO.waitForCellOutput();

    expect(element(by.css('bk-output-display  .date-picker')).isPresent()).toBe(true);
  });

  it('Check Boxes', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'options = [\"a\", \"b\", \"c\", \"d\"]\\n';
    code += 'f1.addCheckBoxes(\"Check Boxes\", options)\\n';
    code += 'f1';

    beakerPO.setCellInput(code);

    beakerPO.evaluateCell();
    beakerPO.waitForCellOutput();

    expect(element.all(by.css('bk-output-display input[type="checkbox"]')).count()).toBe(4);
  });

  it('Radio Buttons', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'options = [\"a\", \"b\", \"c\", \"d\"]\\n';
    code += 'f1.addRadioButtons(\"Radio Buttons\", options)\\n';
    code += 'f1';

    beakerPO.setCellInput(code);

    beakerPO.evaluateCell();
    beakerPO.waitForCellOutput();

    expect(element.all(by.css('bk-output-display  .radio-button-component-item')).count()).toBe(4);
  });

  it('Combo Boxes', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'options = [\"a\", \"b\", \"c\", \"d\"]\\n';
    code += 'f1.addComboBox(\"Combo Box\", options)\\n';
    code += 'f1';

    beakerPO.setCellInput(code);

    beakerPO.evaluateCell();
    beakerPO.waitForCellOutput();

    expect(element.all(by.css('bk-output-display  .combo-box')).count()).toBe(1);
    expect(element.all(by.css('bk-output-display  option')).count()).toBe(4);
  });

  it('Text Areas Undo/Redo', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addTextArea(\"Text Area\")\\n';
    code += 'f1';
    testUndoRedo(code, 'bk-output-display  .text-area');
  });

  it('Text Fields Undo/Redo', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addTextField(\"first\", 15)\\n';
    code += 'f1';
    testUndoRedo(code, 'bk-output-display  .text-field');
  });

})
;

<commit_msg>Create tests for EasyForm #3608<commit_after>/*
 *  Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

var BeakerPageObject = require('./beaker.po.js');
var path = require('path');
var os = require('os');
var beakerPO;

describe('EasyForm', function () {

  function loadGroovy() {
    beakerPO.notebookMenu.click();
    beakerPO.languageManagerMenuItem.click();
    beakerPO.languageManagerButton('Groovy').click();
    beakerPO.waitForPlugin('Groovy');
    beakerPO.languageManagerCloseButton.click();
  }

  function testUndoRedo(code, selector) {
    beakerPO.setCellInput(code);
    beakerPO.evaluateCell();
    beakerPO.waitForCellOutput();

    var e = element(by.css(selector));

    e.sendKeys("TEST");
    expect(e.getAttribute('value')).toEqual("TEST");

    //TEST UNDO
    if (os.type() === 'Darwin') {
      //COMMAND:      '\uE03D',  // Apple command key
      e.sendKeys("\uE03Dz");
    }
    else {
      //CONTROL:      '\uE009',
      e.sendKeys("\uE009z");
    }
    expect(e.getAttribute('value')).toEqual("");

    //TEST REDO
    //SHIFT:        '\uE008',
    if (os.type() === 'Darwin') {
      //COMMAND:      '\uE03D',  // Apple command key
      e.sendKeys("\uE008\uE03Dz");
    } else {
      //CONTROL:      '\uE009',
      e.sendKeys("\uE008\uE009z");
    }
    expect(e.getAttribute('value')).toEqual("TEST");
  }

  beforeEach(function () {
    beakerPO = new BeakerPageObject();
    browser.get(beakerPO.baseURL);
    browser.waitForAngular();
    beakerPO.newEmptyNotebook.click();
    loadGroovy();
    beakerPO.insertCellButton.click();
  });

  afterEach(function (done) {
    beakerPO.closeNotebook()
      .then(done);
  });

  it('Text Fields', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addTextField(\"first\", 15)\\n';
    code += 'f1.addTextField(\"second\", 15)\\n';
    code += 'f1';

    beakerPO.setCellInput(code);
    beakerPO.evaluateCell();
    beakerPO.waitForCellOutput();

    expect(element.all(by.css('bk-output-display  .text-field')).count()).toBe(2);
  });

  it('Text Areas', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addTextArea(\"Text Area\")\\n';
    code += 'f1';

    beakerPO.setCellInput(code);
    beakerPO.evaluateCell();
    beakerPO.waitForCellOutput();

    expect(element(by.css('bk-output-display  .text-area')).isPresent()).toBe(true);
  });

  it('Dates', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addDatePicker(\"Date\")\\n';
    code += 'f1';

    beakerPO.setCellInput(code);
    beakerPO.evaluateCell();
    beakerPO.waitForCellOutput();

    expect(element(by.css('bk-output-display  .date-picker')).isPresent()).toBe(true);
  });

  it('Check Boxes', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'options = [\"a\", \"b\", \"c\", \"d\"]\\n';
    code += 'f1.addCheckBoxes(\"Check Boxes\", options)\\n';
    code += 'f1';

    beakerPO.setCellInput(code);

    beakerPO.evaluateCell();
    beakerPO.waitForCellOutput();

    expect(element.all(by.css('bk-output-display input[type="checkbox"]')).count()).toBe(4);
  });

  it('Radio Buttons', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'options = [\"a\", \"b\", \"c\", \"d\"]\\n';
    code += 'f1.addRadioButtons(\"Radio Buttons\", options)\\n';
    code += 'f1';

    beakerPO.setCellInput(code);

    beakerPO.evaluateCell();
    beakerPO.waitForCellOutput();

    expect(element.all(by.css('bk-output-display  .radio-button-component-item')).count()).toBe(4);
  });

  it('Combo Boxes', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'options = [\"a\", \"b\", \"c\", \"d\"]\\n';
    code += 'f1.addComboBox(\"Combo Box\", options)\\n';
    code += 'f1';

    beakerPO.setCellInput(code);

    beakerPO.evaluateCell();
    beakerPO.waitForCellOutput();

    expect(element.all(by.css('bk-output-display  .combo-box')).count()).toBe(1);
    expect(element.all(by.css('bk-output-display  option')).count()).toBe(4);
  });

  it('Text Areas Undo/Redo', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addTextArea(\"Text Area\")\\n';
    code += 'f1';
    testUndoRedo(code, 'bk-output-display  .text-area');
  });

  it('Text Fields Undo/Redo', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addTextField(\"first\", 15)\\n';
    code += 'f1';
    testUndoRedo(code, 'bk-output-display  .text-field');
  });

})
;

<|endoftext|>


<commit_before>// Here is where you can define configuration overrides based on the execution environment.
// Supply a key to the default export matching the NODE_ENV that you wish to target, and
// the base configuration will apply your overrides before exporting itself.
module.exports = {
  // ======================================================
  // Overrides when NODE_ENV === 'development'
  // ======================================================
  // NOTE: In development, we use an explicit public path when the assets
  // are served webpack by to fix this issue:
  // http://stackoverflow.com/questions/34133808/webpack-ots-parsing-error-loading-fonts/34133809#34133809
  development : (config) => ({
    compiler_public_path : `http://${config.server_host}:${config.server_port}/`,
    globals: Object.assign(config.globals, {
      API_URL: JSON.stringify('http://localhost:3001')
    })
  }),

  // ======================================================
  // Overrides when NODE_ENV === 'production'
  // ======================================================
  production : (config) => ({
    compiler_public_path     : '/',
    compiler_fail_on_warning : false,
    compiler_hash_type       : 'chunkhash',
    compiler_devtool         : null,
    compiler_stats           : {
      chunks       : true,
      chunkModules : true,
      colors       : true
    },
    globals: Object.assign(config.globals, {
      API_URL: JSON.stringify('https://fastrailsredux.herokuapp.com')
    })
  })
}
<commit_msg>change project name, and url for heroku server<commit_after>// Here is where you can define configuration overrides based on the execution environment.
// Supply a key to the default export matching the NODE_ENV that you wish to target, and
// the base configuration will apply your overrides before exporting itself.
module.exports = {
  // ======================================================
  // Overrides when NODE_ENV === 'development'
  // ======================================================
  // NOTE: In development, we use an explicit public path when the assets
  // are served webpack by to fix this issue:
  // http://stackoverflow.com/questions/34133808/webpack-ots-parsing-error-loading-fonts/34133809#34133809
  development : (config) => ({
    compiler_public_path : `http://${config.server_host}:${config.server_port}/`,
    globals: Object.assign(config.globals, {
      API_URL: JSON.stringify('http://localhost:3001')
    })
  }),

  // ======================================================
  // Overrides when NODE_ENV === 'production'
  // ======================================================
  production : (config) => ({
    compiler_public_path     : '/',
    compiler_fail_on_warning : false,
    compiler_hash_type       : 'chunkhash',
    compiler_devtool         : null,
    compiler_stats           : {
      chunks       : true,
      chunkModules : true,
      colors       : true
    },
    globals: Object.assign(config.globals, {
      API_URL: JSON.stringify('https://r3-go.herokuapp.com')
    })
  })
}
<|endoftext|>


<commit_before>/*
 *  Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

var BeakerPageObject = require('./beaker.po.js');
var path = require('path');
var os = require('os');
var beakerPO;

describe('EasyForm', function () {

  function loadGroovy() {
    beakerPO.notebookMenu.click();
    beakerPO.languageManagerMenuItem.click();
    beakerPO.languageManagerButton('Groovy').click();
    beakerPO.waitForPlugin('Groovy');
    beakerPO.languageManagerCloseButton.click();
  }

  function evaluate(code) {
    beakerPO.setCellInput(code)
        .then(function(){ beakerPO.evaluateCell(); })
        .then(function(){ browser.sleep(1000); beakerPO.waitForCellOutput(); });
  }

  function testUndoRedo(code, selector) {
    evaluate(code);

    var e = element(by.css(selector));

    e.sendKeys("A").then(function(){
        expect(e.getAttribute('value')).toEqual("A");
    });
    beakerPO.createScreenshot('undoRedoSendA');
    beakerPO.clickElementWithHandlingError(e, 'inputElement');
    //TEST UNDO
    if (os.type() === 'Darwin') {
      //COMMAND:      '\uE03D',  // Apple command key
      e.sendKeys(protractor.Key.chord(protractor.Key.COMMAND, "z"));
    }
    else {
      //CONTROL:      '\uE009',
      e.sendKeys(protractor.Key.chord(protractor.Key.CONTROL, "z"));
    }
    browser.sleep(1000);
    expect(e.getAttribute('value')).toEqual("");
    beakerPO.clickElementWithHandlingError(e, 'inputElement');
    //TEST REDO
    //SHIFT:        '\uE008',
    if (os.type() === 'Darwin') {
      //COMMAND:      '\uE03D',  // Apple command key
      e.sendKeys(protractor.Key.chord(protractor.Key.COMMAND, protractor.Key.SHIFT, "z"));
    } else {
      //CONTROL:      '\uE009',
      e.sendKeys(protractor.Key.chord(protractor.Key.CONTROL, protractor.Key.SHIFT, "z"));
    }
    browser.sleep(1000);
    expect(e.getAttribute('value')).toEqual("A");
  }

  beforeEach(function (done) {
    beakerPO = new BeakerPageObject();
    browser.get(beakerPO.baseURL).then(done);
    beakerPO.newEmptyNotebook.click();
    loadGroovy();
    beakerPO.insertCellButton.click();
  });

  afterEach(function (done) {
    beakerPO.closeNotebook()
      .then(done);
  });

  it('Text Fields', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addTextField(\"first\", 15)\\n';
    code += 'f1.addTextField(\"second\", 15)\\n';
    code += 'f1';
    evaluate(code);
    expect(element.all(by.css('bk-output-display  .text-field')).count()).toBe(2);
  });

  it('Text Areas', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addTextArea(\"Text Area\")\\n';
    code += 'f1';
    evaluate(code);
    expect(element(by.css('bk-output-display  .text-area')).isPresent()).toBe(true);
  });

  it('Dates', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addDatePicker(\"Date\")\\n';
    code += 'f1';
    evaluate(code);
    expect(element(by.css('bk-output-display  .date-picker')).isPresent()).toBe(true);
  });

  it('Check Boxes', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'options = [\"a\", \"b\", \"c\", \"d\"]\\n';
    code += 'f1.addCheckBoxes(\"Check Boxes\", options)\\n';
    code += 'f1';
    evaluate(code);
    expect(element.all(by.css('bk-output-display input[type="checkbox"]')).count()).toBe(4);
  });

  it('Radio Buttons', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'options = [\"a\", \"b\", \"c\", \"d\"]\\n';
    code += 'f1.addRadioButtons(\"Radio Buttons\", options)\\n';
    code += 'f1';
    evaluate(code);
    expect(element.all(by.css('bk-output-display  .radio-button-component-item')).count()).toBe(4);
  });

  it('Combo Boxes', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'options = [\"a\", \"b\", \"c\", \"d\"]\\n';
    code += 'f1.addComboBox(\"Combo Box\", options)\\n';
    code += 'f1';
    evaluate(code);
    expect(element.all(by.css('bk-output-display  .combo-box')).count()).toBe(1);
    expect(element.all(by.css('bk-output-display  option')).count()).toBe(4);
  });

  it('Text Areas Undo/Redo', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addTextArea(\"Text Area\")\\n';
    code += 'f1';
    var result = testUndoRedo(code, 'bk-output-display  .text-area');
    expect(result.ctrlZ).toBe('');
    expect(result.ctrlShiftZ).toBe('A');
  });

  it('Text Fields Undo/Redo', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addTextField(\"first\", 15)\\n';
    code += 'f1';
    var result = testUndoRedo(code, 'bk-output-display  .text-field');
    expect(result.ctrlZ).toBe('');
    expect(result.ctrlShiftZ).toBe('A');
  });

});

<commit_msg>fix test<commit_after>/*
 *  Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

var BeakerPageObject = require('./beaker.po.js');
var path = require('path');
var os = require('os');
var beakerPO;

describe('EasyForm', function () {

  function loadGroovy() {
    beakerPO.notebookMenu.click();
    beakerPO.languageManagerMenuItem.click();
    beakerPO.languageManagerButton('Groovy').click();
    beakerPO.waitForPlugin('Groovy');
    beakerPO.languageManagerCloseButton.click();
  }

  function evaluate(code) {
    beakerPO.setCellInput(code)
        .then(function(){ beakerPO.evaluateCell(); })
        .then(function(){ browser.sleep(1000); beakerPO.waitForCellOutput(); });
  }

  function testUndoRedo(code, selector) {
    evaluate(code);

    var e = element(by.css(selector));

    e.sendKeys("A").then(function(){
        expect(e.getAttribute('value')).toEqual("A");
    });
    beakerPO.createScreenshot('undoRedoSendA');
    beakerPO.clickElementWithHandlingError(e, 'inputElement');
    //TEST UNDO
    if (os.type() === 'Darwin') {
      //COMMAND:      '\uE03D',  // Apple command key
      e.sendKeys(protractor.Key.chord(protractor.Key.COMMAND, "z"));
    }
    else {
      //CONTROL:      '\uE009',
      e.sendKeys(protractor.Key.chord(protractor.Key.CONTROL, "z"));
    }
    browser.sleep(1000);
    expect(e.getAttribute('value')).toEqual("");
    beakerPO.clickElementWithHandlingError(e, 'inputElement');
    //TEST REDO
    //SHIFT:        '\uE008',
    if (os.type() === 'Darwin') {
      //COMMAND:      '\uE03D',  // Apple command key
      e.sendKeys(protractor.Key.chord(protractor.Key.COMMAND, protractor.Key.SHIFT, "z"));
    } else {
      //CONTROL:      '\uE009',
      e.sendKeys(protractor.Key.chord(protractor.Key.CONTROL, protractor.Key.SHIFT, "z"));
    }
    browser.sleep(1000);
    expect(e.getAttribute('value')).toEqual("A");
  }

  beforeEach(function (done) {
    beakerPO = new BeakerPageObject();
    browser.get(beakerPO.baseURL).then(done);
    beakerPO.newEmptyNotebook.click();
    loadGroovy();
    beakerPO.insertCellButton.click();
  });

  afterEach(function (done) {
    beakerPO.closeNotebook()
      .then(done);
  });

  it('Text Fields', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addTextField(\"first\", 15)\\n';
    code += 'f1.addTextField(\"second\", 15)\\n';
    code += 'f1';
    evaluate(code);
    expect(element.all(by.css('bk-output-display  .text-field')).count()).toBe(2);
  });

  it('Text Areas', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addTextArea(\"Text Area\")\\n';
    code += 'f1';
    evaluate(code);
    expect(element(by.css('bk-output-display  .text-area')).isPresent()).toBe(true);
  });

  it('Dates', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addDatePicker(\"Date\")\\n';
    code += 'f1';
    evaluate(code);
    expect(element(by.css('bk-output-display  .date-picker')).isPresent()).toBe(true);
  });

  it('Check Boxes', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'options = [\"a\", \"b\", \"c\", \"d\"]\\n';
    code += 'f1.addCheckBoxes(\"Check Boxes\", options)\\n';
    code += 'f1';
    evaluate(code);
    expect(element.all(by.css('bk-output-display input[type="checkbox"]')).count()).toBe(4);
  });

  it('Radio Buttons', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'options = [\"a\", \"b\", \"c\", \"d\"]\\n';
    code += 'f1.addRadioButtons(\"Radio Buttons\", options)\\n';
    code += 'f1';
    evaluate(code);
    expect(element.all(by.css('bk-output-display  .radio-button-component-item')).count()).toBe(4);
  });

  it('Combo Boxes', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'options = [\"a\", \"b\", \"c\", \"d\"]\\n';
    code += 'f1.addComboBox(\"Combo Box\", options)\\n';
    code += 'f1';
    evaluate(code);
    expect(element.all(by.css('bk-output-display  .combo-box')).count()).toBe(1);
    expect(element.all(by.css('bk-output-display  option')).count()).toBe(4);
  });

  it('Text Areas Undo/Redo', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addTextArea(\"Text Area\")\\n';
    code += 'f1';
    testUndoRedo(code, 'bk-output-display  .text-area');
  });

  it('Text Fields Undo/Redo', function () {
    var code = 'f1 = new EasyForm(\"Form\")\\n';
    code += 'f1.addTextField(\"first\", 15)\\n';
    code += 'f1';
    testUndoRedo(code, 'bk-output-display  .text-field');
  });

});

<|endoftext|>


<commit_before>/* eslint-disable no-undef */

import Animation from './Animation.es6';
import CubicEasing from './easings/Cubic.es6';
import LinearEasing from './easings/Linear.es6';
import QuadraticEasing from './easings/Quadratic.es6';

window.koi = {
  Animation,
  CubicEasing,
  LinearEasing,
  QuadraticEasing
};
<commit_msg>add UMD<commit_after>/* eslint-disable no-undef */

import Animation from './Animation.es6';
import CubicEasing from './easings/Cubic.es6';
import LinearEasing from './easings/Linear.es6';
import QuadraticEasing from './easings/Quadratic.es6';

const koi = {
  Animation,
  CubicEasing,
  LinearEasing,
  QuadraticEasing
};

window.koi = koi;

// UMD (Universal Module Definition)
(function(root) {
  if (typeof define === 'function' && define.amd) {
    // AMD
    define([], function() {
      return koi;
    });
  } else if (typeof module !== 'undefined' && typeof exports === 'object') {
    // Node.js
    module.exports = koi;
  } else if (root !== undefined) {
    // Global variable
    root.koi = koi;
  }
})(this);
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';
import styles from './project_style.css';
import IssueCard from '../../components/Card/index';
import ReadMe from '../../components/Readme/Readme_Render';
import CodeEditorParent from '../../components/CodeEditor';
import { fetchUserIssues } from '../../actions/githubActions/getIssuesAction';
// import { fetchUserReadme } from '../../actions/githubActions/getReadmeAction';

class ProjLayout extends Component {
  constructor(props) {
    super(props);
    this.state = {
      issues: [],
    };
  }
  componentDidMount() {
    this.props.fetchUserIssues('901david', 'Flashcard-Fun');
  }
  componentWillReceiveProps(nextProps) {
    // console.info(' WHAT ARE THE NEXT PROPS,', nextProps.userRepos);
    const { userIssues } = nextProps;
    // console.log(' WHAT IS USER REPOS', userRepos);
    if (userIssues.length !== 0) {
      this.setState({ issues: userIssues });
    }
  }
  // componentDidMount() {
  //   this.props.fetchUserReadme('901david', 'Flashcard-Fun');
  //   this.props.fetchUserIssues('901david', 'Flashcard-Fun');
  // }
  // componentWillReceiveProps(nextProps) {
  //   // console.info(' WHAT ARE THE NEXT PROPS,', nextProps.userRepos);
  //   const { userIssues, readme } = nextProps;
  //   // console.log(' WHAT IS USER REPOS', userRepos);
  //   if (userIssues.length !== 0) {
  //     this.setState({ issues: userIssues });
  //   }
  //   if (readme.length !== 0) {
  //     this.setState({ readme });
  //   }
  //
  // }
  whatStateToUse = (state) => {
    if (state.issuesButt === true) {
      return (

          <IssueCard issues={this.state.issues} />

      );
    } else if (state.readmeButt === true) {
      return (

          <ReadMe repoName="Flashcard-Fun" userName="901david" />

      );
    } else if (state.matrixButt === true) {
      return (

          <Matrix />

      );
    } else if (state.codeButt === true) {
      return (

          <CodeEditorParent />

      );
    }

    return (

            Houston....We have a problem.

    );
  }
  render() {
    console.log('what is my state of my layout', this.state);
    return (

        {this.whatStateToUse(this.props.state)}

    );
  }
}

export default connect((state, ownProps) => ({
  userIssues: state.issues.repoIssues,
}), (dispatch) => ({
  fetchUserIssues: (userId, repoName) => dispatch(fetchUserIssues(userId, repoName)),
}))(ProjLayout);

// export default connect((state, ownProps) => ({
//   userIssues: state.issues.repoIssues,
//   readme: state.readme.readme,
// }), (dispatch) => ({
//   fetchUserIssues: (userId, repoName) => dispatch(fetchUserIssues(userId, repoName)),
//   fetchUserReadme: (userId, repoName) =>  dispatch(fetchUserReadme(userId, repoName)),
// }))(ProjLayout);
<commit_msg>changed layout to bens for merge purposes<commit_after>import React, { Component } from 'react';
import styles from './project_style.css';
import IssueCard from '../../components/Card/index';
import issueData from './GET_ALL_ISSUES_REPO_SPECIFIC';
import commentData from './GET_COMMENTS_FOR_SPECIFIC_ISSUE';
import ReadMe from '../../components/Readme/Readme_Render';
import Matrix from '../../components/Matrix/Matrix';

import CodeEditorParent from '../../components/CodeEditor';

class ProjLayout extends Component {
  whatStateToUse = (state) => {
    if (state.issuesButt === true) {
      return (

          <IssueCard issues={issueData} comments={commentData} />

      );
    } else if (state.readmeButt === true) {
      return (

          <ReadMe />

      );
    } else if (state.matrixButt === true) {
      return (

          <Matrix />

      );
    }
    else if (state.codeButt === true) {
      return (

          <CodeEditorParent />

      );
    }
    else {
      return (

          Houston....We have a problem.

      );
    }
  }
  render() {
    return (

        {this.whatStateToUse(this.props.state)}

    );
  }
}

export default ProjLayout;
<|endoftext|>


<commit_before>import BABYLON from 'babylonjs';
import EventEmitter from 'events';
import {Buttons} from '../input.js';

// TODO: Make this configurable. Perhaps have a “learn mode” API:
// beginButtonLearn(), exportLearnedState(), loadLearnedState() so
// that mappings can be set in the menu and saved to persisted storage
// somehow. Biggest problem is matching saved state to a particular
// controller when there are multiple controllers plugged in because
// controller names/ids might not be unique/reliable.
const buttonMap = [
  Buttons.A,
  Buttons.B,
  Buttons.X,
  Buttons.Y,
  Buttons.Menu, // Start on XBox controller
  undefined,
  undefined,
  Buttons.RB,
];

class GamepadInput extends EventEmitter {
  constructor(gamepad) {
    super();
  }

  setGamepad(gamepad) {
    if (this.gamepad) {
      // Clear existing.
      this.gamepad.onbuttondown(null);
      this.gamepad.onbuttonup(null);
      this.gamepad.onleftstickchanged(null);
      this.gamepad.onrightstickchanged(null);
      this.gamepad.onleftstickchanged(null);
    }
    this.gamepad = gamepad;
    this.name = `${gamepad.id} ${gamepad.index}`;
    const buildButtonHandler = eventName => {
      return buttonIndex => {
        const button = buttonMap[buttonIndex];
        if (button) {
          this.emit(eventName, button);
        } else {
          console.warn(`Ignoring button ${buttonIndex}`);
        }
      };
    };
    gamepad.onbuttondown(buildButtonHandler('buttondown'));
    gamepad.onbuttonup(buildButtonHandler('buttonup'));
    let xIsZeroed = false;
    let yIsZeroed = false;
    const joyVector = new BABYLON.Vector2(0, 0);
    gamepad.onleftstickchanged(values => {
      // Treat stuff close to 0 as 0 so that when the player intends
      // their character to be at rest the character is actually at
      // rest.
      const zeroSensitivity = 0.15;
      const willXBeZeroed = values.x > -zeroSensitivity && values.x < zeroSensitivity;
      const willYBeZeroed = values.y > -zeroSensitivity && values.y < zeroSensitivity;
      if (!willXBeZeroed || !willYBeZeroed || willXBeZeroed != xIsZeroed || willYBeZeroed != yIsZeroed) {
        xIsZeroed = willXBeZeroed;
        yIsZeroed = willYBeZeroed;
        joyVector.x = willXBeZeroed ? 0 : values.x;
        joyVector.y = willYBeZeroed ? 0 : -values.y; // For some reason stick uses inverted y (airplane?)
        this.emit('joychanged', joyVector);
      }
    });
  }
};

export default class GamepadInputManager {
  constructor(game) {
    // Keep track of known identifiers because apparently they can
    // reconnect without warning.
    const knownGamepads = [];

    new BABYLON.Gamepads(gamepad => {
      const existing = knownGamepads[gamepad.index];
      if (existing) {
        existing.setGamepad(gamepad);
      } else {
        const added = knownGamepads[gamepad.index] = new GamepadInput();
        added.setGamepad(gamepad);
        game.addInput(added);
      }
    });
  }
};
<commit_msg>gamepad controllers: Remove per-axis zeroing.<commit_after>import BABYLON from 'babylonjs';
import EventEmitter from 'events';
import {Buttons} from '../input.js';

// TODO: Make this configurable. Perhaps have a “learn mode” API:
// beginButtonLearn(), exportLearnedState(), loadLearnedState() so
// that mappings can be set in the menu and saved to persisted storage
// somehow. Biggest problem is matching saved state to a particular
// controller when there are multiple controllers plugged in because
// controller names/ids might not be unique/reliable.
const buttonMap = [
  Buttons.A,
  Buttons.B,
  Buttons.X,
  Buttons.Y,
  Buttons.Menu, // Start on XBox controller
  undefined,
  undefined,
  Buttons.RB,
];

class GamepadInput extends EventEmitter {
  constructor(gamepad) {
    super();
  }

  setGamepad(gamepad) {
    if (this.gamepad) {
      // Clear existing.
      this.gamepad.onbuttondown(null);
      this.gamepad.onbuttonup(null);
      this.gamepad.onleftstickchanged(null);
      this.gamepad.onrightstickchanged(null);
      this.gamepad.onleftstickchanged(null);
    }
    this.gamepad = gamepad;
    this.name = `${gamepad.id} ${gamepad.index}`;
    const buildButtonHandler = eventName => {
      return buttonIndex => {
        const button = buttonMap[buttonIndex];
        if (button) {
          this.emit(eventName, button);
        } else {
          console.warn(`Ignoring button ${buttonIndex}`);
        }
      };
    };
    gamepad.onbuttondown(buildButtonHandler('buttondown'));
    gamepad.onbuttonup(buildButtonHandler('buttonup'));
    let xIsZeroed = false;
    let yIsZeroed = false;
    const joyVector = new BABYLON.Vector2(0, 0);
    gamepad.onleftstickchanged(values => {
      // Treat stuff close to 0 as 0 so that when the player intends
      // their character to be at rest the character is actually at
      // rest.
    const zeroSensitivity = 0.15;
    if (/* per-axis, kpgbrink dislikes */false) {
      const willXBeZeroed = values.x > -zeroSensitivity && values.x < zeroSensitivity;
      const willYBeZeroed = values.y > -zeroSensitivity && values.y < zeroSensitivity;
      if (!willXBeZeroed || !willYBeZeroed || willXBeZeroed != xIsZeroed || willYBeZeroed != yIsZeroed) {
        xIsZeroed = willXBeZeroed;
        yIsZeroed = willYBeZeroed;
        joyVector.x = willXBeZeroed ? 0 : values.x;
        joyVector.y = willYBeZeroed ? 0 : -values.y; // For some reason stick uses inverted y (airplane?)
        this.emit('joychanged', joyVector);
      }
    } else {
      const willBeZeroed = values.x > -zeroSensitivity && values.x < zeroSensitivity
        && values.y > -zeroSensitivity && values.y < zeroSensitivity;
      if (!willBeZeroed || willBeZeroed != xIsZeroed) {
        xIsZeroed = willBeZeroed;
        joyVector.x = values.x;
        joyVector.y = -values.y;
        this.emit('joychanged', joyVector);
      }
    }
    });
  }
};

export default class GamepadInputManager {
  constructor(game) {
    // Keep track of known identifiers because apparently they can
    // reconnect without warning.
    const knownGamepads = [];

    new BABYLON.Gamepads(gamepad => {
      const existing = knownGamepads[gamepad.index];
      if (existing) {
        existing.setGamepad(gamepad);
      } else {
        const added = knownGamepads[gamepad.index] = new GamepadInput();
        added.setGamepad(gamepad);
        game.addInput(added);
      }
    });
  }
};
<|endoftext|>


<commit_before>(function(window, angular, undefined) {

'use strict';

var gbMock = []

/**
 * @ngdoc service
 * @name gbMock.websocketFactoryProvider
 *
 * @description
 * Mock implementation of the $interval service.
 *
 * Use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
 * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
 * time.
 *
 * @param {function()} fn A function that should be called repeatedly.
 * @param {number} delay Number of milliseconds between each function call.
 * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
 *   indefinitely.
 * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
 *   will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
 * @returns {promise} A promise which will be notified on each iteration.
 */
gbMock.WebsocketFactoryProvider = function() {
  var ws = undefined
  this.$get = function() {
    return function( url) {
      if( ! ws) {
        ws = new gbMock.Websocket( url)
      } else {
        if(url)
          ws.url = url
      }
      return ws
    }

  };
};

gbMock.Websocket = function( url) {
  this.isMock = true
  this.url = url
  this.sendFrames = []
  this.isOpen = false
}

gbMock.Websocket.prototype.send = function( frame) {
  this.sendFrames.push( frame)
}
gbMock.Websocket.prototype.pushMessage = function( event) {
  if( this.hasOwnProperty( 'onmessage')) {
    this.onmessage( {data: JSON.stringify( event) })
    return true
  }
  return false
}
gbMock.Websocket.prototype.pushOpen = function( event) {
  if( this.hasOwnProperty( 'onopen')) {
    this.onopen( event)
    this.isOpen = true
    return true
  }
  return false
}
gbMock.Websocket.prototype.pushClose = function( event) {
  if( this.hasOwnProperty( 'onclose')) {
    this.onclose( event)
    return true
  }
  return false
}
gbMock.Websocket.prototype.pushError = function( event) {
  if( this.hasOwnProperty( 'onerror')) {
    this.onerror( event)
    return true
  }
  return false
}

gbMock.SubscriptionProvider = function() {
  this.$get = makeSubscription
};

function makeSubscription() {
  var listeners = {},
      status = {
        status: 'UNOPENED',
        reinitializing: false,
        description: 'WebSocket unopened'
      }

  function generateUUID(){
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      var r = (d + Math.random()*16)%16 | 0;
      d = Math.floor(d/16);
      return (c=='x' ? r : (r&0x7|0x8)).toString(16);
    });
    return uuid;
  }

  function Subscription() {

  }
  Subscription.saveSubscriptionOnScope = function( $scope, subscriptionId) {
    if( ! $scope.__subscriptionIds)
      $scope.__subscriptionIds = []
    $scope.__subscriptionIds.push( subscriptionId)
  }

  Subscription.subscribe = function( json, $scope, messageListener, errorListener) {
    var subscriptionId = 'subscription.' + Object.keys( json)[0] + '.' + generateUUID()
    listeners[ subscriptionId] = { 'message': messageListener, 'error': errorListener}
    this.saveSubscriptionOnScope( $scope, subscriptionId)
    return subscriptionId
  }
  Subscription.unsubscribe = function( subscriptionId) {
    delete listeners[ subscriptionId];
  }
  Subscription.getStatus = function( ) {
    return {
      state: 'Connected to server',
      reinitializing: false
    }
  }

  Subscription.pushMessage = function( subscriptionId, messageType, messageData) {
    setTimeout( function() {
      listeners[subscriptionId].message( subscriptionId, messageType, messageData)
    }, 0)
  }

  Subscription.STATUS = {
    UNOPENED: 'UNOPENED',
    OPENING: 'OPENING',
    CLOSED: 'CLOSED',
    UP: 'UP'
  }

  Subscription.getStatus = function() {
    return this.status
  }

  return Subscription
}

gbMock.RestProvider = function() {
  this.$get = makeRest
};

function MockHttpExpectation(method, url, data, headers) {

  this.data = data;
  this.headers = headers;

  this.match = function(m, u, d, h) {
    if (method != m) return false;
    if (!this.matchUrl(u)) return false;
    if (angular.isDefined(d) && !this.matchData(d)) return false;
    if (angular.isDefined(h) && !this.matchHeaders(h)) return false;
    return true;
  };

  this.matchUrl = function(u) {
    if (!url) return true;
    if (angular.isFunction(url.test)) return url.test(u);
    return url == u;
  };

  this.matchHeaders = function(h) {
    if (angular.isUndefined(headers)) return true;
    if (angular.isFunction(headers)) return headers(h);
    return angular.equals(headers, h);
  };

  this.matchData = function(d) {
    if (angular.isUndefined(data)) return true;
    if (data && angular.isFunction(data.test)) return data.test(d);
    if (data && angular.isFunction(data)) return data(d);
    if (data && !angular.isString(data)) {
      return angular.equals(angular.fromJson(angular.toJson(data)), angular.fromJson(d));
    }
    return data == d;
  };

  this.toString = function() {
    return method + ' ' + url;
  };
}

function makeRest($injector) {
  var definitions = [],
      copy = angular.copy,
      status = {
        status:         'UP',
        reinitializing: false,
        description:    ''
      }

  function Rest() {

  }

  Rest.request = function(method, url, data, name, $scope, successListener) {

    var definition,
        i = -1,
      headers = {};

    function makeThen( response, digest) {
      return {
        then: function( s2, e2) {
          setTimeout( function() {
            var responseData = copy(response)

            if( digest ) {
              if( $scope ) {
                // name and loading already assigned below.

                $scope.$apply(function() {
                  if( s2 )
                    s2({data: responseData})
                })
              } else {
                if( s2 ) {
                  var rootScope = $injector.get('$rootScope')
                  rootScope.$apply(function() {
                    s2({data: responseData})
                  })
                }
              }
            } else {
              s2({data: responseData})
            }
          })
          return makeThen(response, false)
        }
      }
    }

    while ((definition = definitions[++i])) {
      if (definition.match(method, url, data, headers || {})) {
        if (definition.response) {
          setTimeout( function() {
            var responseData = copy( definition.response()[1])

            if( $scope) {
              $scope.$apply( function() {

                if( name )
                  $scope[name] = responseData

                $scope.loading = false

                if( successListener)
                  successListener( responseData)
              })
            } else {
              if( successListener) {
                var rootScope = $injector.get('$rootScope')
                rootScope.$apply( function() {
                  successListener( responseData)
                })
              }
            }
          })

          return makeThen( definition.response()[1], true) // t: do digest
          //return {
          //  then: function( success, error) {
          //    setTimeout( function() {
          //      var responseData = copy( definition.response()[1])
          //
          //      if( $scope) {
          //        // name and loading already assigned above.
          //
          //        $scope.$apply( function() {
          //          if( success)
          //            success( {data: responseData})
          //        })
          //      } else {
          //        if( success) {
          //          var rootScope = $injector.get('$rootScope')
          //          rootScope.$apply( function() {
          //            success( {data: responseData})
          //          })
          //        }
          //      }
          //    })
          //
          //  }
          //}

        } else
          throw new Error('gbMock.rest: No response defined for ' + method + ' ' + url);

        return;
      }
    }
    throw new Error('gbMock.rest: No matching request found for ' + method + ' ' + url);
  }

  Rest.get = function(url, name, $scope, successListener) {
    return Rest.request( 'GET', url, {}, name, $scope, successListener)
  }
  Rest.post = function(url, data, name, $scope, successListener, failureListener) {
    return Rest.request( 'POST', url, data, name, $scope, successListener)
  }
  Rest['delete'] = function(url, name, $scope, successListener, failureListener) {
    return Rest.request( 'DELETE', url, {}, name, $scope, successListener)
  }

  Rest.STATUS =  {
    NOT_LOGGED_IN: 'NOT_LOGGED_IN',
    APPLICATION_SERVER_DOWN: 'APPLICATION_SERVER_DOWN',
    APPLICATION_REQUEST_FAILURE: 'APPLICATION_REQUEST_FAILURE',
    UP: 'UP'
  }

  Rest.getStatus = function() {
    return status
  }

  Rest.queryParameterFromArrayOrString = function(parameter, arrayOrString) {
    var parameterEqual = parameter + '='
    var query = ''
    if( angular.isArray(arrayOrString) ) {
      arrayOrString.forEach(function(value, index) {
        if( index === 0 )
          query = parameterEqual + value
        else
          query = query + '&' + parameterEqual + value
      })
    } else {
      if( arrayOrString && arrayOrString.length > 0 )
        query = parameterEqual + arrayOrString
    }
    return query
  }

  function createResponse(status, data, headers, statusText) {
    if (angular.isFunction(status)) return status;

    return function() {
      return angular.isNumber(status)
        ? [status, data, headers, statusText]
        : [200, status, data];
    };
  }

  Rest.when = function( method, url, data, headers) {
    var definition = new MockHttpExpectation(method, url, data, headers),
        chain = {
          respond: function(status, data, headers, statusText) {
            definition.response = createResponse(status, data, headers, statusText);
          }
        }

    definitions.push(definition)
    return chain
  }

  function createShortMethods(prefix) {
    angular.forEach(['GET', 'DELETE', 'JSONP', 'HEAD'], function(method) {
      Rest[prefix + method] = function(url, headers) {
        return Rest[prefix](method, url, undefined, headers);
      };
    });

    angular.forEach(['PUT', 'POST', 'PATCH'], function(method) {
      Rest[prefix + method] = function(url, data, headers) {
        return Rest[prefix](method, url, data, headers);
      };
    });
  }

  createShortMethods('when');

  return Rest
}

gbMock.RouteParamsProvider = function() {
  this.$get = makeRouteParams
};

function makeRouteParams() {
  var listeners = {}

  function RouteParams() {

  }

  RouteParams.navId = ''
  RouteParams.sourceUrl = ''

  return RouteParams
}

  /**
   * @ngdoc module
   * @name ngMock
   * @packageName angular-mocks
   * @description
   *
   * # ngMock
   *
   * The `ngMock` module provides support to inject and mock Angular services into unit tests.
   * In addition, ngMock also extends various core ng services such that they can be
   * inspected and controlled in a synchronous manner within test code.
   *
   *
   *

   *
   */
  angular.module('gbMock', ['ng']).
    provider({
      websocketFactory: gbMock.WebsocketFactoryProvider,
      subscription: gbMock.SubscriptionProvider,
      rest: gbMock.RestProvider,
      $routeParams: gbMock.RouteParamsProvider
    });

  /**
   * Export
   * @type {Array}
   */
  window.gbMock = gbMock

})(window, window.angular);<commit_msg>fix(mock): Fixed mock rest request promise.<commit_after>(function(window, angular, undefined) {

'use strict';

var gbMock = []

/**
 * @ngdoc service
 * @name gbMock.websocketFactoryProvider
 *
 * @description
 * Mock implementation of the $interval service.
 *
 * Use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
 * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
 * time.
 *
 * @param {function()} fn A function that should be called repeatedly.
 * @param {number} delay Number of milliseconds between each function call.
 * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
 *   indefinitely.
 * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
 *   will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
 * @returns {promise} A promise which will be notified on each iteration.
 */
gbMock.WebsocketFactoryProvider = function() {
  var ws = undefined
  this.$get = function() {
    return function( url) {
      if( ! ws) {
        ws = new gbMock.Websocket( url)
      } else {
        if(url)
          ws.url = url
      }
      return ws
    }

  };
};

gbMock.Websocket = function( url) {
  this.isMock = true
  this.url = url
  this.sendFrames = []
  this.isOpen = false
}

gbMock.Websocket.prototype.send = function( frame) {
  this.sendFrames.push( frame)
}
gbMock.Websocket.prototype.pushMessage = function( event) {
  if( this.hasOwnProperty( 'onmessage')) {
    this.onmessage( {data: JSON.stringify( event) })
    return true
  }
  return false
}
gbMock.Websocket.prototype.pushOpen = function( event) {
  if( this.hasOwnProperty( 'onopen')) {
    this.onopen( event)
    this.isOpen = true
    return true
  }
  return false
}
gbMock.Websocket.prototype.pushClose = function( event) {
  if( this.hasOwnProperty( 'onclose')) {
    this.onclose( event)
    return true
  }
  return false
}
gbMock.Websocket.prototype.pushError = function( event) {
  if( this.hasOwnProperty( 'onerror')) {
    this.onerror( event)
    return true
  }
  return false
}

gbMock.SubscriptionProvider = function() {
  this.$get = makeSubscription
};

function makeSubscription() {
  var listeners = {},
      status = {
        status: 'UNOPENED',
        reinitializing: false,
        description: 'WebSocket unopened'
      }

  function generateUUID(){
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      var r = (d + Math.random()*16)%16 | 0;
      d = Math.floor(d/16);
      return (c=='x' ? r : (r&0x7|0x8)).toString(16);
    });
    return uuid;
  }

  function Subscription() {

  }
  Subscription.saveSubscriptionOnScope = function( $scope, subscriptionId) {
    if( ! $scope.__subscriptionIds)
      $scope.__subscriptionIds = []
    $scope.__subscriptionIds.push( subscriptionId)
  }

  Subscription.subscribe = function( json, $scope, messageListener, errorListener) {
    var subscriptionId = 'subscription.' + json.name + '.' + generateUUID()
    listeners[ subscriptionId] = { 'message': messageListener, 'error': errorListener}
    this.saveSubscriptionOnScope( $scope, subscriptionId)
    return subscriptionId
  }
  Subscription.unsubscribe = function( subscriptionId) {
    delete listeners[ subscriptionId];
  }
  Subscription.getStatus = function( ) {
    return {
      state: 'Connected to server',
      reinitializing: false
    }
  }

  Subscription.pushMessage = function( subscriptionId, messageType, messageData) {
    setTimeout( function() {
      listeners[subscriptionId].message( subscriptionId, messageType, messageData)
    }, 0)
  }

  Subscription.STATUS = {
    UNOPENED: 'UNOPENED',
    OPENING: 'OPENING',
    CLOSED: 'CLOSED',
    UP: 'UP'
  }

  Subscription.getStatus = function() {
    return this.status
  }

  return Subscription
}

gbMock.RestProvider = function() {
  this.$get = makeRest
};

function MockHttpExpectation(method, url, data, headers) {

  this.data = data;
  this.headers = headers;

  this.match = function(m, u, d, h) {
    if (method != m) return false;
    if (!this.matchUrl(u)) return false;
    if (angular.isDefined(d) && !this.matchData(d)) return false;
    if (angular.isDefined(h) && !this.matchHeaders(h)) return false;
    return true;
  };

  this.matchUrl = function(u) {
    if (!url) return true;
    if (angular.isFunction(url.test)) return url.test(u);
    return url == u;
  };

  this.matchHeaders = function(h) {
    if (angular.isUndefined(headers)) return true;
    if (angular.isFunction(headers)) return headers(h);
    return angular.equals(headers, h);
  };

  this.matchData = function(d) {
    if (angular.isUndefined(data)) return true;
    if (data && angular.isFunction(data.test)) return data.test(d);
    if (data && angular.isFunction(data)) return data(d);
    if (data && !angular.isString(data)) {
      return angular.equals(angular.fromJson(angular.toJson(data)), angular.fromJson(d));
    }
    return data == d;
  };

  this.toString = function() {
    return method + ' ' + url;
  };
}

function makeRest($injector) {
  var definitions = [],
      copy = angular.copy,
      status = {
        status:         'UP',
        reinitializing: false,
        description:    ''
      }

  function Rest() {

  }

  Rest.request = function(method, url, data, name, $scope, successListener) {

    var definition,
        $q = $injector.get('$q'),
        i = -1,
        headers = {};

    function makeThen( response, digest) {
      var deferred = $q.defer()

      setTimeout( function() {
        var resolveArg = {data: copy( response)}

        if( digest ) {
          if( $scope ) {
            deferred.resolve( resolveArg)
          } else {
            var rootScope = $injector.get('$rootScope')
            rootScope.$apply(function() {
              deferred.resolve( resolveArg)
            })
          }
        } else {
          deferred.resolve( resolveArg)
        }
      })

      return deferred.promise
    }

    while ((definition = definitions[++i])) {
      if (definition.match(method, url, data, headers || {})) {
        if (definition.response) {
          setTimeout( function() {
            var responseData = copy( definition.response()[1])

            if( $scope) {
              $scope.$apply( function() {

                if( name )
                  $scope[name] = responseData

                $scope.loading = false

                if( successListener)
                  successListener( responseData)
              })
            } else {
              if( successListener) {
                var rootScope = $injector.get('$rootScope')
                rootScope.$apply( function() {
                  successListener( responseData)
                })
              }
            }
          })

          return makeThen( definition.response()[1], true) // t: do digest
          //return {
          //  then: function( success, error) {
          //    setTimeout( function() {
          //      var responseData = copy( definition.response()[1])
          //
          //      if( $scope) {
          //        // name and loading already assigned above.
          //
          //        $scope.$apply( function() {
          //          if( success)
          //            success( {data: responseData})
          //        })
          //      } else {
          //        if( success) {
          //          var rootScope = $injector.get('$rootScope')
          //          rootScope.$apply( function() {
          //            success( {data: responseData})
          //          })
          //        }
          //      }
          //    })
          //
          //  }
          //}

        } else
          throw new Error('gbMock.rest: No response defined for ' + method + ' ' + url);

        return;
      }
    }
    throw new Error('gbMock.rest: No matching request found for ' + method + ' ' + url);
  }

  Rest.get = function(url, name, $scope, successListener) {
    return Rest.request( 'GET', url, {}, name, $scope, successListener)
  }
  Rest.post = function(url, data, name, $scope, successListener, failureListener) {
    return Rest.request( 'POST', url, data, name, $scope, successListener)
  }
  Rest['delete'] = function(url, name, $scope, successListener, failureListener) {
    return Rest.request( 'DELETE', url, {}, name, $scope, successListener)
  }

  Rest.STATUS =  {
    NOT_LOGGED_IN: 'NOT_LOGGED_IN',
    APPLICATION_SERVER_DOWN: 'APPLICATION_SERVER_DOWN',
    APPLICATION_REQUEST_FAILURE: 'APPLICATION_REQUEST_FAILURE',
    UP: 'UP'
  }

  Rest.getStatus = function() {
    return status
  }

  Rest.queryParameterFromArrayOrString = function(parameter, arrayOrString) {
    var parameterEqual = parameter + '='
    var query = ''
    if( angular.isArray(arrayOrString) ) {
      arrayOrString.forEach(function(value, index) {
        if( index === 0 )
          query = parameterEqual + value
        else
          query = query + '&' + parameterEqual + value
      })
    } else {
      if( arrayOrString && arrayOrString.length > 0 )
        query = parameterEqual + arrayOrString
    }
    return query
  }

  function createResponse(status, data, headers, statusText) {
    if (angular.isFunction(status)) return status;

    return function() {
      return angular.isNumber(status)
        ? [status, data, headers, statusText]
        : [200, status, data];
    };
  }

  Rest.when = function( method, url, data, headers) {
    var definition = new MockHttpExpectation(method, url, data, headers),
        chain = {
          respond: function(status, data, headers, statusText) {
            definition.response = createResponse(status, data, headers, statusText);
          }
        }

    definitions.push(definition)
    return chain
  }

  function createShortMethods(prefix) {
    angular.forEach(['GET', 'DELETE', 'JSONP', 'HEAD'], function(method) {
      Rest[prefix + method] = function(url, headers) {
        return Rest[prefix](method, url, undefined, headers);
      };
    });

    angular.forEach(['PUT', 'POST', 'PATCH'], function(method) {
      Rest[prefix + method] = function(url, data, headers) {
        return Rest[prefix](method, url, data, headers);
      };
    });
  }

  createShortMethods('when');

  return Rest
}

gbMock.RouteParamsProvider = function() {
  this.$get = makeRouteParams
};

function makeRouteParams() {
  var listeners = {}

  function RouteParams() {

  }

  RouteParams.navId = ''
  RouteParams.sourceUrl = ''

  return RouteParams
}

  /**
   * @ngdoc module
   * @name ngMock
   * @packageName angular-mocks
   * @description
   *
   * # ngMock
   *
   * The `ngMock` module provides support to inject and mock Angular services into unit tests.
   * In addition, ngMock also extends various core ng services such that they can be
   * inspected and controlled in a synchronous manner within test code.
   *
   *
   *

   *
   */
  angular.module('gbMock', ['ng']).
    provider({
      websocketFactory: gbMock.WebsocketFactoryProvider,
      subscription: gbMock.SubscriptionProvider,
      rest: gbMock.RestProvider,
      $routeParams: gbMock.RouteParamsProvider
    });

  /**
   * Export
   * @type {Array}
   */
  window.gbMock = gbMock

})(window, window.angular);<|endoftext|>


<commit_before>define(['logManager', 'js/NodePropertyNames'], function (logManager, nodePropertyNames) {
  "use strict";

  var self, logger, client;
  var toBeValidated;

  var ObjectConstraintManager = function(client_) {
    self = this;
    logManager.setLogLevel(logManager.logLevels.INFO);
    logger = logManager.create('ObjectConstraintManager');
    client = client_;
  };

  ObjectConstraintManager.prototype.validateAll = function(id) {
    toBeValidated = id;
    var territoryId = client.addUI(this, true);
    client.updateTerritory(territoryId, {root: {'children': Number.MAX_VALUE}});
  };

  ObjectConstraintManager.prototype.validate = function(id) {
    // Validate the node itself..
    var node = client.getNode(id);
    var node_name = node.getAttribute('name');
    logger.info('Validating node: ' + id + ' ' + node_name);

    var constraints = [];
    var constraint_names = node.getConstraintNames();
    constraint_names.forEach(function(constraint_name) {
      var constraint_obj = node.getConstraint(constraint_name);
      constraint_obj.name = constraint_name;
      constraints.push(constraint_obj);
    });

    constraints.forEach(function(constraint) {

      var result = eval("(" + constraint.script + ")(client, node);");

      var msg = '[[ <' + constraint.name + '> of <' + node_name + '> ]]';
      if (result) {
          logger.info('No violation of a constraint: ' +
            msg);
      } else {
          logger.error('!!Violation of a constraint: ' +
            msg + "!!!");
      }

    });

    // var y = function(input, callback) {
    //   //
    //   callback(withsomething);
    // }

    // Call validation for the node's children
    var children = node.getChildrenIds();
    children.forEach(function(child) {
      self.validate(child);
    });
  }

  ObjectConstraintManager.prototype.onOneEvent = function (events) {
    logger.info('Territory is updated, validation begins');
    self.validate(toBeValidated);
  }

  return ObjectConstraintManager;
});<commit_msg>constraint population improved<commit_after>define(['logManager', 'js/NodePropertyNames'], function (logManager, nodePropertyNames) {
  "use strict";

  var self, logger, client;
  var toBeValidated;

  var ObjectConstraintManager = function(client_) {
    self = this;
    logManager.setLogLevel(logManager.logLevels.INFO);
    logger = logManager.create('ObjectConstraintManager');
    client = client_;
  };

  ObjectConstraintManager.prototype.validateAll = function(id) {
    toBeValidated = id;
    var territoryId = client.addUI(this, true);
    client.updateTerritory(territoryId, {root: {'children': Number.MAX_VALUE}});
  };

  ObjectConstraintManager.prototype.validate = function(id) {
    // Validate the node itself..
    var node = client.getNode(id);
    var node_name = node.getAttribute('name');
    logger.info('Validating node: ' + id + ' ' + node_name);

    var constraints = node.getConstraintNames().map(function(constraint_name) {
      var constraint_obj = node.getConstraint(constraint_name);
      constraint_obj.name = constraint_name;
      return constraint_obj;
    });

    constraints.forEach(function(constraint) {
      var result = eval("(" + constraint.script + ")(client, node);");
      var msg = '[[ <' + constraint.name + '> of <' + node_name + '> ]]';
      if (result) {
          logger.info('No violation of a constraint: ' +
            msg);
      } else {
          logger.error('!!Violation of a constraint: ' +
            msg + "!!!");
      }
    });

    // var y = function(input, callback) {
    //   //
    //   callback(withsomething);
    // }

    // Call validation for the node's children
    var children = node.getChildrenIds();
    children.forEach(function(child) {
      self.validate(child);
    });
  }

  ObjectConstraintManager.prototype.onOneEvent = function (events) {
    logger.info('Territory is updated, validation begins');
    self.validate(toBeValidated);
  }

  return ObjectConstraintManager;
});<|endoftext|>


<commit_before>'use strict';

var Router = require('../../src/js/framework/router.js'),
  PageView = require('../../src/js/framework/page'),
  $ = require('jquery');

describe('Router', function() {

  var router;

  beforeEach(function() {
    router = new Router();
    $('body').append('
');
  });

  describe('renderView', function() {

    var view;

    beforeEach(function() {
      view = new PageView();
    });

    describe('Loading a new view', function() {

      it('should set the set the current view', function() {
        router.renderView(view);
        expect(router.currentView).toEqual(view);
      });

      it('should render the current view', function() {
        spyOn(view, 'render').and.callThrough();
        router.renderView(view);
        expect(view.render).toHaveBeenCalled();
      });

      it('should setup the buttons', function() {
        spyOn(view, 'setButtonEvents');
        router.renderView(view);
        expect(view.setButtonEvents).toHaveBeenCalled();
      });

      it('should render the view in the watch face', function() {
        router.renderView(view);
        expect($('#watch-face')).toContainElement('.page');
      });

    });

    describe('When there is an existing view', function() {

      var oldView;

      beforeEach(function() {
        oldView = new PageView();
        spyOn(oldView, 'remove');
      });

      it('should remove the existing view', function() {
        router.currentView = oldView;
        router.renderView(view);
        expect(oldView.remove).toHaveBeenCalled();
      });

    });

  });

  afterEach(function() {
    $('#watch-face').remove();
  });

});
<commit_msg>Improving organisation of tests<commit_after>'use strict';

var Router = require('../../src/js/framework/router.js'),
  PageView = require('../../src/js/framework/page'),
  $ = require('jquery');

describe('Router', function() {

  var router;

  beforeEach(function() {
    router = new Router();
    $('body').append('
');
  });

  describe('renderView', function() {

    var view;

    beforeEach(function() {
      view = new PageView();
    });

    describe('Loading a new view', function() {

      it('should set the current view', function() {
        router.renderView(view);
        expect(router.currentView).toEqual(view);
      });

      it('should configure the buttons', function() {
        spyOn(view, 'setButtonEvents');
        router.renderView(view);
        expect(view.setButtonEvents).toHaveBeenCalled();
      });

      describe('rendering', function () {

        it('should render the current view', function() {
          spyOn(view, 'render').and.callThrough();
          router.renderView(view);
          expect(view.render).toHaveBeenCalled();
        });

        it('should render the view in the watch face', function() {
          router.renderView(view);
          expect($('#watch-face')).toContainElement('.page');
        });

      });

    });

    describe('When there is an existing view', function() {

      var oldView;

      beforeEach(function() {
        oldView = new PageView();
        spyOn(oldView, 'remove');
      });

      it('should remove the existing view', function() {
        router.currentView = oldView;
        router.renderView(view);
        expect(oldView.remove).toHaveBeenCalled();
      });

    });

  });

  afterEach(function() {
    $('#watch-face').remove();
  });

});
<|endoftext|>


<commit_before>
import React, {Component} from 'react'
import {Link} from 'react-router-dom'
import Card from '../components/Card'

function setArticleLink(title) {
  return encodeURIComponent(title)
}

const ChannelCard = ({channel, articles}) => {
    const articleObject = articles.find(articleObject => articleObject.name === channel.name);

    const channelArticles = articleObject.articles.map((article, index) => {
      return (
        <Link to={`/newsfeed/${channel.source_id}/${setArticleLink(article.title)}`}>
{article.title}
</Link>
      )
    })

    const title = (
      <Link to={`/newsfeed/${channel.source_id}`}>{channel.name}</Link>
    )

    return (
      <Card title={title} content={channelArticles}/>
    )
  }

export default ChannelCard
<commit_msg>Add key to cards<commit_after>
import React, {Component} from 'react'
import {Link} from 'react-router-dom'
import Card from '../components/Card'

function setArticleLink(title) {
  return encodeURIComponent(title)
}

const ChannelCard = ({channel, articles}) => {
    const articleObject = articles.find(articleObject => articleObject.name === channel.name);

    const channelArticles = articleObject.articles.map((article, index) => {
      return (
        <Link to={`/newsfeed/${channel.source_id}/${setArticleLink(article.title)}`}>
{article.title}
</Link>
      )
    })

    const title = (
      <Link to={`/newsfeed/${channel.source_id}`}>{channel.name}</Link>
    )

    return (
      <Card title={title} content={channelArticles} key={channel.source_id}/>
    )
  }

export default ChannelCard
<|endoftext|>


<commit_before>import _ from 'lodash'
import Reflux from 'reflux'

import ancestryString from 'data/transform/ancestryString'
import treeify from 'data/transform/treeify'
import flattenChildren from 'data/transform/flattenChildren'
import api from 'data/api'
import DatapointAPI from 'data/requests/DatapointAPI'

let EntryFormStore = Reflux.createStore({
  listenables: [require('actions/EntryFormActions')],
  locationList: [],

  data: {
    entryFormDefinitions: require('./EntryFormDefinitions'),
    apiResponseData: null,
    indicatorMap: null,
    indicatorSet: null,
    indicatorToTags: [],
    formIdSelected: null,
    data: null,
    loaded: false,
    campaigns: [],
    campaignIdSelected: null,
    couldLoad: false,
    filterLocations: [],
    locationMap: null,
    locationSelected: [],
    locations: [],
    tags: [],
    includeSublocations: false,
    pagination: {
      total_count: 0
    }
  },

  getInitialState: function () {
    return this.data
  },

  onInitData: function () {
    let self = this

    // self.data.entryFormDefinitions = self.entryFormDefinitions
    // self.data.formIdSelected = self.entryFormDefinitions[0]

    Promise.all([
      api.get_indicator_tag(),
      api.indicator_to_tag(),
      api.campaign(null, null, {'cache-control': 'no-cache'}),
      api.locations(),
      api.indicators({ read_write: 'w' }, null, {'cache-control': 'no-cache'})])
    .then(_.spread(function (tags, indicatorToTags, campaigns, locations, indicators) {
      let indicatorToTagsResult = _(indicatorToTags.objects)
        .map(indToTag => {
          return {
            'id': indToTag.id,
            'value': indToTag.indicator_tag_id,
            'name': indToTag.indicator__short_name,
            'title': indToTag.indicator_tag__tag_name
          }
        }).value()
      self.data.indicatorToTags = indicatorToTagsResult
      let tagResult = _(tags.objects)
        .map(tag => {
          return {
            'value': tag.id,
            'title': tag.tag_name
          }
        }).value()
      self.data.tags = tagResult
      self.data.tagIdSelected = tagResult[0].id
      let campaignResult = _(campaigns.objects)
          .map(campaign => {
            return {
              'id': campaign.id,
              'name': campaign.name
            }
          }).value()
      self.data.campaigns = campaignResult
      self.data.campaignIdSelected = campaignResult[0].id

      // locations
      let locationResult = _(locations.objects)
          .map(location => {
            return {
              'title': location.name,
              'value': location.id,
              'parent': location.parent_location_id
            }
          })
          .sortBy('title')
          .reverse()
          .thru(_.curryRight(treeify)('value'))
          .map(ancestryString)
          .value()

      self.locationList = locationResult
      self.data.filterLocations = locationResult
      self.data.locationMap = _.indexBy(locations.objects, 'id')

        // Indicators
      self.data.indicatorMap = _.indexBy(indicators.objects, 'id')
        // self._filterLocationsByCampaign()
      self.trigger(self.data)
    })
    )
  },

  _setCouldLoad: function () {
    this.data.couldLoad = (this.data.formIdSelected !== null && this.data.campaignSelected !== null && (this.data.locationSelected.length > 0))
    if (this.data.couldLoad) {
      this.onGetTableData()
    }
  },

  // _filterLocationsByCampaign: function () {
  //   let campaign = _(this.data.campaigns).find(campaign => {
  //     return campaign.id === parseInt(this.data.campaignSelected, 10)
  //   })
  //
  //   this.data.filterLocations = this.locationList.filter(location => {
  //     return location.value === campaign.office_id
  //   })
  //
  //   this.data.locationSelected = []
  //   this._setCouldLoad()
  // },

  _filterFormDefinition: function (indicatorSetId) {
    var formDefinition = this.data.entryFormDefinitions[0] // _.find(this.data.entryFormDefinitions, function (d) { return d.id ===
    if (!formDefinition) return null
    //
    var filtered = _.clone(formDefinition)
    filtered.indicators = [] // formDefinition.indicators.filter(function (n) { return n > 0 })

    // []
    _.each(formDefinition.indicator_id_list, ind_id => {
    //   if (row.type === 'section-header') { // header
    //     // remove previous section header if no indicators are included under it
    //     if (filtered.indicators.length > 0 && filtered.indicators[filtered.indicators.length - 1].type === 'section-header') {
    //       filtered.indicators.splice(filtered.indicators.length - 1, 1)
    //     }
    //     filtered.indicators.push(row)
    //   } else { // indicator
    //     // filter out indicators the user cannot edit
      if (ind_id && this.data.indicatorMap[ind_id] !== undefined) {
    //       row.name = this.data.indicatorMap[row.id].name
        filtered.indicators.push(this.data.indicatorMap[ind_id])
    //     }
      }
    })
    //
    // // remove last row if empty section header
    // if (filtered.indicators[filtered.indicators.length - 1].type === 'section-header') {
    //   filtered.indicators.pop()
    // }
    //
    return filtered
  },

  _findLocationObject: function (locations, locationId) {
    return _.find(locations, location => {
      return location.value === locationId
        ? location : !location.children && location.children.length > 0
        ? this._findLocationObject(location.children, locationId) : []
    })
  },

  onChangeSelect: function () {
    if (this.data.includeSublocations) {
      this.data.includeSublocations = false
    } else {
      this.data.includeSublocations = true
    }
    this.trigger(this.data)
  },

  onSetForm: function (formId) {
    this.data.formIdSelected = formId
    this.trigger(this.data)
  },

  onSetCampaign: function (campaignId) {
    this.data.campaignIdSelected = campaignId
    // this._filterLocationsByCampaign()
    this.trigger(this.data)
  },

  onAddLocations: function (id) {
    this.data.locationSelected.push(this.data.locationMap[id])
    this._setCouldLoad()
    this.trigger(this.data)
  },

  onRemoveLocation: function (id) {
    _.remove(this.data.locationSelected, {id: id})
    this._setCouldLoad()
    this.trigger(this.data)
  },

  onGetTableData: function () {
    let options = {
      campaign__in: parseInt(this.data.campaignIdSelected, 10),
      indicator__in: [],
      location_id__in: []
    }

    if (this.data.locationSelected.length > 0) {
      options.location_id__in = _.map(this.data.locationSelected, 'id')

      _.forEach(this.data.locationSelected, location => {
        if (this.data.includeSublocations) {
          let parentLocations = this._findLocationObject(this.locationList, location.id)

          let children = flattenChildren(parentLocations, 'children', null, function () { return true }, 1)
          if (children.length > 0) {
            options.location_id__in = options.location_id__in.concat(_.map(children, 'value'))
          }
        }
      })
      options.location_id__in = _.uniq(options.location_id__in)

      // sort locations
      options.location_id__in = options.location_id__in.sort((a, b) => {
        var ra = this.data.locationMap[a]
        var rb = this.data.locationMap[b]
        // sort by location type first
        if (ra.location_type_id !== rb.location_type_id) {
          return ra.location_type_id - rb.location_type_id
        } else {
          return ra.name > rb.name ? 1 : -1
        }
      })

      this.data.locations = options.location_id__in
    }

    this.data.formDefinition = this._filterFormDefinition(this.data.formIdSelected)
    options.indicator__in = this.data.formDefinition.indicator_id_list
    _.defaults(options, this.data.pagination)

    this.data.loaded = false
    this.trigger(this.data)
    DatapointAPI.getFilteredDatapoints(options, null, {'cache-control': 'no-cache'}).then(response => {
      this.data.loaded = true
      this.data.apiResponseData = response.objects
      // this.data.apiResponseData.meta = response.meta
      // this.data.data.objects
      this.trigger(this.data)
    }, function (err) {
      console.error(err)
      this.data.loaded = false
      this.trigger(this.data)
    })
  }
})

export default EntryFormStore
<commit_msg>remove hardcode, comment unused method, add filtered indicator logic<commit_after>import _ from 'lodash'
import Reflux from 'reflux'

import ancestryString from 'data/transform/ancestryString'
import treeify from 'data/transform/treeify'
import flattenChildren from 'data/transform/flattenChildren'
import api from 'data/api'
import DatapointAPI from 'data/requests/DatapointAPI'

let EntryFormStore = Reflux.createStore({
  listenables: [require('actions/EntryFormActions')],
  locationList: [],

  data: {
    entryFormDefinitions: require('./EntryFormDefinitions'),
    apiResponseData: null,
    indicatorMap: null,
    indicatorSet: null,
    indicatorsToTags: [],
    filteredIndicators: [],
    formIdSelected: null,
    data: null,
    loaded: false,
    campaigns: [],
    campaignIdSelected: null,
    couldLoad: false,
    filterLocations: [],
    locationMap: null,
    locationSelected: [],
    locations: [],
    tags: [],
    includeSublocations: false,
    pagination: {
      total_count: 0
    }
  },

  getInitialState: function () {
    return this.data
  },

  onInitData: function () {
    let self = this

    // self.data.entryFormDefinitions = self.entryFormDefinitions
    // self.data.formIdSelected = self.entryFormDefinitions[0]

    Promise.all([
      api.get_indicator_tag(),
      api.indicator_to_tag(),
      api.campaign(null, null, {'cache-control': 'no-cache'}),
      api.locations(),
      api.indicators({ read_write: 'w' }, null, {'cache-control': 'no-cache'})])
    .then(_.spread(function (tags, indicatorsToTags, campaigns, locations, indicators) {
      let indicatorToTagsResult = _(indicatorsToTags.objects)
        .map(indToTag => {
          return {
            'id': indToTag.id,
            'indicator_tag_id': indToTag.indicator_tag_id,
            'name': indToTag.indicator__short_name,
            'title': indToTag.indicator_tag__tag_name
          }
        }).value()
      self.data.indicatorsToTags = indicatorToTagsResult
      let tagResult = _(tags.objects)
        .map(tag => {
          return {
            'value': tag.id,
            'title': tag.tag_name
          }
        }).value()
      self.data.tags = tagResult
      self.data.tagIdSelected = tagResult[0].id
      let campaignResult = _(campaigns.objects)
          .map(campaign => {
            return {
              'id': campaign.id,
              'name': campaign.name
            }
          }).value()
      self.data.campaigns = campaignResult
      self.data.campaignIdSelected = campaignResult[0].id

      // locations
      let locationResult = _(locations.objects)
          .map(location => {
            return {
              'title': location.name,
              'value': location.id,
              'parent': location.parent_location_id
            }
          })
          .sortBy('title')
          .reverse()
          .thru(_.curryRight(treeify)('value'))
          .map(ancestryString)
          .value()

      self.locationList = locationResult
      self.data.filterLocations = locationResult
      self.data.locationMap = _.indexBy(locations.objects, 'id')

        // Indicators
      self.data.indicatorMap = _.indexBy(indicators.objects, 'id')
        // self._filterLocationsByCampaign()
      self.trigger(self.data)
    })
    )
  },

  _setCouldLoad: function () {
    this.data.couldLoad = (this.data.formIdSelected !== null && this.data.campaignSelected !== null && (this.data.locationSelected.length > 0))
    if (this.data.couldLoad) {
      this.onGetTableData()
    }
  },

  // _filterLocationsByCampaign: function () {
  //   let campaign = _(this.data.campaigns).find(campaign => {
  //     return campaign.id === parseInt(this.data.campaignSelected, 10)
  //   })
  //
  //   this.data.filterLocations = this.locationList.filter(location => {
  //     return location.value === campaign.office_id
  //   })
  //
  //   this.data.locationSelected = []
  //   this._setCouldLoad()
  // },

  // _filterFormDefinition: function (indicatorSetId) {
  //   var formDefinition = this.data.entryFormDefinitions[0] // _.find(this.data.entryFormDefinitions, function (d) { return d.id ===
  //   if (!formDefinition) return null
  //   //
  //   var filtered = _.clone(formDefinition)
  //   filtered.indicators = [] // formDefinition.indicators.filter(function (n) { return n > 0 })

  //   // []
  //   _.each(formDefinition.indicator_id_list, ind_id => {
  //   //   if (row.type === 'section-header') { // header
  //   //     // remove previous section header if no indicators are included under it
  //   //     if (filtered.indicators.length > 0 && filtered.indicators[filtered.indicators.length - 1].type === 'section-header') {
  //   //       filtered.indicators.splice(filtered.indicators.length - 1, 1)
  //   //     }
  //   //     filtered.indicators.push(row)
  //   //   } else { // indicator
  //   //     // filter out indicators the user cannot edit
  //     if (ind_id && this.data.indicatorMap[ind_id] !== undefined) {
  //   //       row.name = this.data.indicatorMap[row.id].name
  //       filtered.indicators.push(this.data.indicatorMap[ind_id])
  //   //     }
  //     }
  //   })
  //   //
  //   // // remove last row if empty section header
  //   // if (filtered.indicators[filtered.indicators.length - 1].type === 'section-header') {
  //   //   filtered.indicators.pop()
  //   // }
  //   //
  //   return filtered
  // },

  _findLocationObject: function (locations, locationId) {
    return _.find(locations, location => {
      return location.value === locationId
        ? location : !location.children && location.children.length > 0
        ? this._findLocationObject(location.children, locationId) : []
    })
  },

  onChangeSelect: function () {
    if (this.data.includeSublocations) {
      this.data.includeSublocations = false
    } else {
      this.data.includeSublocations = true
    }
    this.trigger(this.data)
  },

  onSetForm: function (formId) {
    this.data.formIdSelected = formId
    this.trigger(this.data)
  },

  onSetCampaign: function (campaignId) {
    this.data.campaignIdSelected = campaignId
    // this._filterLocationsByCampaign()
    this.trigger(this.data)
  },

  onAddLocations: function (id) {
    this.data.locationSelected.push(this.data.locationMap[id])
    this._setCouldLoad()
    this.trigger(this.data)
  },

  onRemoveLocation: function (id) {
    _.remove(this.data.locationSelected, {id: id})
    this._setCouldLoad()
    this.trigger(this.data)
  },
  onFilterIndicators: function(formName){
    this.data.filteredIndicators = []
    this.data.indicatorsToTags.forEach(indicator => {
      if (indicator.title === formName){
        this.data.filteredIndicators.push(this.data.indicatorMap[indicator.id])
      }
    })
    this.trigger(this.data)
  },
  onGetTableData: function () {
    let options = {
      campaign__in: parseInt(this.data.campaignIdSelected, 10),
      indicator__in: [],
      location_id__in: []
    }

    if (this.data.locationSelected.length > 0) {
      options.location_id__in = _.map(this.data.locationSelected, 'id')

      _.forEach(this.data.locationSelected, location => {
        if (this.data.includeSublocations) {
          let parentLocations = this._findLocationObject(this.locationList, location.id)

          let children = flattenChildren(parentLocations, 'children', null, function () { return true }, 1)
          if (children.length > 0) {
            options.location_id__in = options.location_id__in.concat(_.map(children, 'value'))
          }
        }
      })
      options.location_id__in = _.uniq(options.location_id__in)

      // sort locations
      options.location_id__in = options.location_id__in.sort((a, b) => {
        var ra = this.data.locationMap[a]
        var rb = this.data.locationMap[b]
        // sort by location type first
        if (ra.location_type_id !== rb.location_type_id) {
          return ra.location_type_id - rb.location_type_id
        } else {
          return ra.name > rb.name ? 1 : -1
        }
      })

      this.data.locations = options.location_id__in
    }
    // this.data.formDefinition = this._filterFormDefinition(this.data.formIdSelected)
    // this.data.formDefinition = this.data.filteredIndicators

    options.indicator__in = this.data.filteredIndicators.map(function(indicator){
      return indicator.id
    })

    _.defaults(options, this.data.pagination)

    this.data.loaded = false
    this.trigger(this.data)
    DatapointAPI.getFilteredDatapoints(options, null, {'cache-control': 'no-cache'}).then(response => {
      this.data.loaded = true
      this.data.apiResponseData = response.objects
      // this.data.apiResponseData.meta = response.meta
      // this.data.data.objects
      this.trigger(this.data)
    }, function (err) {
      console.error(err)
      this.data.loaded = false
      this.trigger(this.data)
    })
  }
})

export default EntryFormStore
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';

import {
  Card,
  CardActions,
  CardHeader,
  CardMedia,
  CardTitle,
  CardText,
} from 'material-ui/Card';
import FlatButton from 'material-ui/FlatButton';
import EmailIcon from 'material-ui/svg-icons/communication/email';
import FavoriteIcon from 'material-ui/svg-icons/action/favorite';

class ListingCard extends React.Component {

  static propTypes = {
    expanded: PropTypes.bool.isRequired,
    onExpandChange: PropTypes.func,
    listing: PropTypes.shape({
      keyId: PropTypes.number,
      creationDate: PropTypes.string,
      lastModificationDate: PropTypes.string,
      title: PropTypes.string,
      description: PropTypes.string,
      userId: PropTypes.number,
      price: PropTypes.number,
      status: PropTypes.string,
      expirationDate: PropTypes.number,
      thumbnail: PropTypes.string,
    }).isRequired,
  };

  static defaultProps = {
    expanded: false,
    onExpandChange: () => {},
  };

  state = {
    expanded: false,
  }

  handleExpandChange = (expanded) => {
    this.props.onExpandChange(expanded, this.props.listing.keyId);
    this.setState({ expanded });
  }

  render() {
    const { listing, expanded } = this.props;

    const cardStyles = expanded ? {
      margin: '1.5em -3em',
    } : {};

    const onShowStyles = { maxHeight: '2000px', transition: 'max-height 0.8s ease-in', overflow: 'hidden' };
    const onHideStyles = { maxHeight: '0', transition: 'max-height 0.15s ease-out', overflow: 'hidden' };

    return (
      <Card style={cardStyles} onExpandChange={this.handleExpandChange}>
        <CardHeader
          title={listing.title}
          subtitle={`$${listing.price / 100}`}
          actAsExpander
        />

          <CardMedia>

          </CardMedia>

          <CardTitle
            title={listing.title}
            expandable
          />

          <CardText expandable>
            {listing.description}
          </CardText>

          <CardActions expandable>
            <FlatButton primary icon={<EmailIcon />} label="Contact Seller" />
            <FlatButton secondary icon={<FavoriteIcon />} label="Save" />
          </CardActions>

      </Card>
    );
  }
}

export default ListingCard;
<commit_msg>Supporting single-expand of Listing cards<commit_after>import React from 'react';
import PropTypes from 'prop-types';

import {
  Card,
  CardActions,
  CardHeader,
  CardMedia,
  CardTitle,
  CardText,
} from 'material-ui/Card';
import FlatButton from 'material-ui/FlatButton';
import EmailIcon from 'material-ui/svg-icons/communication/email';
import FavoriteIcon from 'material-ui/svg-icons/action/favorite';

class ListingCard extends React.Component {

  static propTypes = {
    expanded: PropTypes.bool.isRequired,
    onExpandChange: PropTypes.func,
    listing: PropTypes.shape({
      keyId: PropTypes.number,
      creationDate: PropTypes.string,
      lastModificationDate: PropTypes.string,
      title: PropTypes.string,
      description: PropTypes.string,
      userId: PropTypes.number,
      price: PropTypes.number,
      status: PropTypes.string,
      expirationDate: PropTypes.number,
      thumbnail: PropTypes.string,
    }).isRequired,
  };

  static defaultProps = {
    expanded: false,
    onExpandChange: () => {},
  };

  handleExpandChange = (expanded) => {
    this.props.onExpandChange(expanded, this.props.listing.keyId);
  }

  render() {
    const { listing, expanded } = this.props;

    const cardStyles = expanded ? {
      margin: '1.5em -3em',
    } : {};

    const onShowStyles = { maxHeight: '4000px', transition: 'max-height 0.5s ease-in', overflow: 'hidden' };
    const onHideStyles = { maxHeight: '0', transition: 'max-height 0.15s ease-out', overflow: 'hidden' };

    return (
      <Card style={cardStyles} onExpandChange={this.handleExpandChange}>
        <CardHeader
          title={listing.title}
          subtitle={`$${listing.price / 100}`}
          actAsExpander
        />

          <CardMedia expandable>

          </CardMedia>

          <CardTitle
            title={listing.title}
            expandable
          />

          <CardText expandable>
            {listing.description}
          </CardText>

          <CardActions expandable>
            <FlatButton primary icon={<EmailIcon />} label="Contact Seller" />
            <FlatButton secondary icon={<FavoriteIcon />} label="Save" />
          </CardActions>

      </Card>
    );
  }
}

export default ListingCard;
<|endoftext|>