<commit_before>'use strict';

var app = app || {};

(function (module) {
  const QuestionView = {};

  QuestionView.serveQuestion = () => {
    $('.main-header').hide();
    $('#mainGame').hide();
    $('.question-container').empty();
    $('.stats-container').css('display','flex');
    app.stat.questionStartTime = app.stat.time;

    app.statView.updateStats();
    $('#questionModal').append(app.Question.all[app.Question.currentQuestionIndex].toHtml());

    $('.question-button').on('click', function () {
      if (app.Question.selectedAnswer != ''){
        if ($('.question-button').text() === 'DONE') {
          app.statsController.completeGame();
        } else {
          if (app.Question.currentQuestionIndex < app.Question.all.length - 2) {
            app.Sensei.evaluateAnswer();
            app.Question.currentQuestionIndex += 1;
            app.stat.stopTime();
            window.setTimeout(function(){
              app.stat.timeInit();
              app.QuestionView.serveQuestion()}, 650);
            } else {
              app.Sensei.evaluateAnswer();
              app.Question.currentQuestionIndex += 1;
              app.QuestionView.serveQuestion();
              $('.question-button').html('DONE');
            }
          }
        }
      });

      $('.free-button').on('click', function () {

        if (app.Question.selectedAnswer != ''){
          if (app.Question.currentQuestionIndex < app.Question.all.length - 1) {
            app.Sensei.evaluateAnswer();
            app.Question.currentQuestionIndex += 1;
            app.stat.stopTime();
            window.setTimeout(function(){
              app.stat.timeInit();
              app.QuestionView.serveQuestion()}, 650);
            } else {
              console.log('in changing done');
              app.Sensei.evaluateAnswer();
              app.freePlayController.continueFreeQuestions();
            }
          }

        });

        $('.option').on('click', function (event) {
          $(this).siblings().removeClass('question-selected');
          $(this).toggleClass('question-selected');
          app.Question.selectedAnswer = $(this).text();
        })
      }

      module.QuestionView = QuestionView;
    })(app);
<commit_msg>fixed last answer not going green<commit_after>'use strict';

var app = app || {};

(function (module) {
  const QuestionView = {};

  QuestionView.serveQuestion = () => {
    $('.main-header').hide();
    $('#mainGame').hide();
    $('.question-container').empty();
    $('.stats-container').css('display','flex');
    app.stat.questionStartTime = app.stat.time;

    app.statView.updateStats();
    $('#questionModal').append(app.Question.all[app.Question.currentQuestionIndex].toHtml());

    $('.question-button').on('click', function () {
      if (app.Question.selectedAnswer != ''){
        if ($('.question-button').text() === 'DONE') {
          app.Sensei.evaluateAnswer();
          window.setTimeout(function(){
            app.statsController.completeGame();}, 650);
        } else {
          if (app.Question.currentQuestionIndex < app.Question.all.length - 2) {
            app.Sensei.evaluateAnswer();
            app.Question.currentQuestionIndex += 1;
            app.stat.stopTime();
            window.setTimeout(function(){
              app.stat.timeInit();
              app.QuestionView.serveQuestion()}, 650);
            } else {
              app.Sensei.evaluateAnswer();
              app.Question.currentQuestionIndex += 1;
              app.QuestionView.serveQuestion();
              $('.question-button').html('DONE');
            }
          }
        }
      });

      $('.free-button').on('click', function () {

        if (app.Question.selectedAnswer != ''){
          if (app.Question.currentQuestionIndex < app.Question.all.length - 1) {
            app.Sensei.evaluateAnswer();
            app.Question.currentQuestionIndex += 1;
            app.stat.stopTime();
            window.setTimeout(function(){
              app.stat.timeInit();
              app.QuestionView.serveQuestion()}, 650);
            } else {
              console.log('in changing done');
              app.Sensei.evaluateAnswer();
              app.freePlayController.continueFreeQuestions();
            }
          }

        });

        $('.option').on('click', function (event) {
          $(this).siblings().removeClass('question-selected');
          $(this).toggleClass('question-selected');
          app.Question.selectedAnswer = $(this).text();
        })
      }

      module.QuestionView = QuestionView;
    })(app);
<|endoftext|>


<commit_before>/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Famous Industries Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

'use strict';
var test = require('tape');
var DynamicGeometry = require('../DynamicGeometry');
var Circle = require('../primitives/Circle');

test('DynamicGeometry', function(t) {
    t.test('constructor', function(t) {
        var geometry = new DynamicGeometry();

        t.ok(geometry.spec instanceof Object, 'should have a spec object');
        t.equal(geometry.spec.bufferNames.length, 0, 'should not have any vertex buffers by default');
        t.ok(geometry.spec.type === 4, 'should have correct default draw style.');

        var indexValue = [[1, 2, 3]];
        var secondGeometry = new DynamicGeometry({
            buffers: [{ name: 'indices', data: indexValue, size: 1 }]
        });

        t.notEqual(geometry.id, secondGeometry.id, 'should have unique ID');
        t.ok(secondGeometry.spec.bufferNames.indexOf('indices') !== -1, 'should pass buffer names to geometry spec');
        t.ok(secondGeometry.spec.bufferValues.indexOf(indexValue) !== -1, 'should pass buffer values to geometry spec');

        t.end();
    });

    t.test('DynamicGeometry.prototype.setVertexBuffer', function(t) {
        var geometry = new DynamicGeometry();

        t.equal(typeof geometry.setVertexBuffer, 'function', 'should be a function');
        t.throws(geometry.setVertexBuffer, 'should throw if no buffer name is provided');

        geometry.setVertexBuffer('peanutButter');

        t.equal(geometry.spec.bufferNames.length, 1, 'should create a new vertex buffer');
        t.equal(geometry.spec.bufferValues[0].length, 0, 'should default to an array of length 0');

        var jellyBuffer = [1];
        geometry.setVertexBuffer('jelly', jellyBuffer);
        t.equal(geometry.spec.bufferValues[1].length, 1, 'should use second parameter as vertex buffer value');

        var peanutButterBuffer = [1, 1];
        geometry.setVertexBuffer('peanutButter', peanutButterBuffer);
        t.equal(geometry.spec.bufferValues[0].length, 2, 'should overwrite previously assigned vertex buffer with same name');

        t.notEqual(geometry.spec.invalidations.indexOf(0), -1, 'should register invalidation for the set buffer');

        t.end();
    });

    t.test('DynamicGeometry.prototype.getVertexBuffer', function(t) {
        var geometry = new DynamicGeometry();

        t.throws(geometry.getVertexBuffer, 'should throw when no arguments are provided');

        var peanutButterBuffer = [];
        geometry.setVertexBuffer('peanutButter', peanutButterBuffer);
        t.equals(geometry.getVertexBuffer('peanutButter'), peanutButterBuffer,
        'should retreive the correct buffer data from geometry spec');

        t.end();
    });

    t.test('DynamicGeometry.prototype.setDrawType', function(t) {
        var geometry = new DynamicGeometry();

        t.throws(geometry.setDrawType, 'should throw when no argument is provided');

        geometry.setDrawType('PENANDPAPER');

        t.equals(geometry.spec.type, 'PENANDPAPER', 'should set the draw type of the spec');

        t.end();
    });

    t.test('DynamicGeometry.prototype.getLength', function(t) {
        var posAttribArray = [1, 2, 3];

        var geometry = new DynamicGeometry({
            buffers: [{
                name: 'a_pos', data: posAttribArray
            }]
        });

        t.equals(geometry.getLength(), posAttribArray.length, "Should return the length of pos attribute");
        posAttribArray.push(4);
        t.equals(geometry.getLength(), posAttribArray.length, "Should return the length of pos attribute");

        t.end();
    });

    t.test('DynamicGeometry.prototype.fromGeometry', function(t) {
        var geometry = new DynamicGeometry();
        var circleGeometry = new Circle();
        geometry.fromGeometry(circleGeometry);

        t.deepEquals(circleGeometry.spec.bufferValues, geometry.spec.bufferValues, "Should have the same data for attribute buffers");
        t.deepEquals(circleGeometry.spec.bufferNames, geometry.spec.bufferNames, "Should have the same names for attribute buffers");

        t.end();
    });

    t.test('DynamicGeometry.prototype.setVertexPositions', function(t) {
        var geometry = new DynamicGeometry();
        var vertexPositions = [0, 0, 1, 0, 1, 0, 1, 0, 0];

        geometry.setVertexPositions(vertexPositions);

        t.deepEquals(
            geometry.spec.bufferValues[geometry.spec.bufferNames.indexOf('pos')],
            vertexPositions,
            'Should set vertex data to the pos attribute of the geometry'
        );

        t.equals(
            geometry.spec.bufferSpacings[geometry.spec.bufferNames.indexOf('pos')],
            3,
            'Should set buffer spacing to 3 for pos attribute'
        );

        t.end();
    });

    t.test('DynamicGeometry.prototype.setNormals', function(t) {
        var geometry = new DynamicGeometry();
        var vertexNormals = [0, 0, 1, 0, 1, 0, 1, 0, 0];

        geometry.setNormals(vertexNormals);

        t.deepEquals(
            geometry.spec.bufferValues[geometry.spec.bufferNames.indexOf('normals')],
            vertexNormals,
            'Should set vertex data to the "normal" attribute of the geometry'
        );

        t.equals(
            geometry.spec.bufferSpacings[geometry.spec.bufferNames.indexOf('normals')],
            3,
            'Should set buffer spacing to 3 for normal attribute'
        );

        t.end();
    });

    t.test('DynamicGeometry.prototype.setTextureCoords', function(t) {
        var geometry = new DynamicGeometry();
        var textureCoords = [0, 0, 0, 1, 1, 0, 1, 1];

        geometry.setTextureCoords(textureCoords);

        t.deepEquals(
            geometry.spec.bufferValues[geometry.spec.bufferNames.indexOf('texCoord')],
            textureCoords,
            'Should set vertex data to the "texCoord" attribute of the geometry'
        );

        t.equals(
            geometry.spec.bufferSpacings[geometry.spec.bufferNames.indexOf('texCoord')],
            2,
            'Should set buffer spacing to 2 for texCoord attribute'
        );

        t.end();
    });

    t.test('DynamicGeometry.prototype.setIndices', function(t) {
        var geometry = new DynamicGeometry();
        var indices = [0, 1, 2, 3, 4, 5, 6];

        geometry.setIndices(indices);

        t.deepEquals(
            geometry.spec.bufferValues[geometry.spec.bufferNames.indexOf('indices')],
            indices,
            'Should set vertex data to the "indices" attribute of the geometry'
        );

        t.equals(
            geometry.spec.bufferSpacings[geometry.spec.bufferNames.indexOf('indices')],
            1,
            'Should set buffer spacing to 1 for indices'
        );

        t.end();
    });

    t.test('DynamicGeometry.prototype.getVertexPositions', function(t) {
        var geometry = new DynamicGeometry();
        var vertexPositions = [-1, 0, 0, 1, 0, 0];
        geometry.setVertexPositions(vertexPositions)

        t.deepEquals(
            vertexPositions,
            geometry.getVertexPositions(),
            'Should return vertex position buffer'
        );

        t.end();
    });

    t.test('DynamicGeometry.prototype.getNormals', function(t) {
        var geometry = new DynamicGeometry();
        var normals = [-1, 0, 0, 1, 0, 0];
        geometry.setNormals(normals)

        t.deepEquals(
            normals,
            geometry.getNormals(),
            'Should return normal buffer'
        );

        t.end();
    });

    t.test('DynamicGeometry.prototype.getTextureCoords', function(t) {
        var geometry = new DynamicGeometry();
        var texCoords = [0, 0, 1, 0, 0, 1, 1, 1];
        geometry.setTextureCoords(texCoords)

        t.deepEquals(
            texCoords,
            geometry.getTextureCoords(),
            'Should return texCoord buffer'
        );

        t.end();
    });

    t.end();
});
<commit_msg>test: update dynamic geometry tests<commit_after>/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Famous Industries Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

'use strict';
var test = require('tape');
var DynamicGeometry = require('../DynamicGeometry');
var Circle = require('../primitives/Circle');

test('DynamicGeometry', function(t) {
    t.test('constructor', function(t) {
        var geometry = new DynamicGeometry();

        t.ok(geometry.spec instanceof Object, 'should have a spec object');
        t.equal(geometry.spec.bufferNames.length, 0, 'should not have any vertex buffers by default');
        t.ok(geometry.spec.type === 'TRIANGLES', 'should have correct default draw style.');

        var indexValue = [[1, 2, 3]];
        var secondGeometry = new DynamicGeometry({
            buffers: [{ name: 'indices', data: indexValue, size: 1 }]
        });

        t.notEqual(geometry.id, secondGeometry.spec.id, 'should have unique ID');
        t.ok(secondGeometry.spec.bufferNames.indexOf('indices') !== -1, 'should pass buffer names to geometry spec');
        t.ok(secondGeometry.spec.bufferValues.indexOf(indexValue) !== -1, 'should pass buffer values to geometry spec');

        t.end();
    });

    t.test('DynamicGeometry.prototype.setVertexBuffer', function(t) {
        var geometry = new DynamicGeometry();

        t.equal(typeof geometry.setVertexBuffer, 'function', 'should be a function');
        t.throws(geometry.setVertexBuffer, 'should throw if no buffer name is provided');

        geometry.setVertexBuffer('peanutButter');

        t.equal(geometry.spec.bufferNames.length, 1, 'should create a new vertex buffer');
        t.equal(geometry.spec.bufferValues[0].length, 0, 'should default to an array of length 0');

        var jellyBuffer = [1];
        geometry.setVertexBuffer('jelly', jellyBuffer);
        t.equal(geometry.spec.bufferValues[1].length, 1, 'should use second parameter as vertex buffer value');

        var peanutButterBuffer = [1, 1];
        geometry.setVertexBuffer('peanutButter', peanutButterBuffer);
        t.equal(geometry.spec.bufferValues[0].length, 2, 'should overwrite previously assigned vertex buffer with same name');

        t.notEqual(geometry.spec.invalidations.indexOf(0), -1, 'should register invalidation for the set buffer');

        t.end();
    });

    t.test('DynamicGeometry.prototype.getVertexBuffer', function(t) {
        var geometry = new DynamicGeometry();

        t.throws(geometry.getVertexBuffer, 'should throw when no arguments are provided');

        var peanutButterBuffer = [];
        geometry.setVertexBuffer('peanutButter', peanutButterBuffer);
        t.equals(geometry.getVertexBuffer('peanutButter'), peanutButterBuffer,
        'should retreive the correct buffer data from geometry spec');

        t.end();
    });

    t.test('DynamicGeometry.prototype.setDrawType', function(t) {
        var geometry = new DynamicGeometry();

        t.throws(geometry.setDrawType, 'should throw when no argument is provided');

        geometry.setDrawType('PENANDPAPER');

        t.equals(geometry.spec.type, 'PENANDPAPER', 'should set the draw type of the spec');

        t.end();
    });

    t.test('DynamicGeometry.prototype.getLength', function(t) {
        var posAttribArray = [1, 2, 3];

        var geometry = new DynamicGeometry({
            buffers: [{
                name: 'a_pos', data: posAttribArray
            }]
        });

        t.equals(geometry.getLength(), posAttribArray.length, "Should return the length of pos attribute");
        posAttribArray.push(4);
        t.equals(geometry.getLength(), posAttribArray.length, "Should return the length of pos attribute");

        t.end();
    });

    t.test('DynamicGeometry.prototype.fromGeometry', function(t) {
        var geometry = new DynamicGeometry();
        var circleGeometry = new Circle();
        geometry.fromGeometry(circleGeometry);

        t.deepEquals(circleGeometry.spec.bufferValues, geometry.spec.bufferValues, "Should have the same data for attribute buffers");
        t.deepEquals(circleGeometry.spec.bufferNames, geometry.spec.bufferNames, "Should have the same names for attribute buffers");

        t.end();
    });

    t.test('DynamicGeometry.prototype.setVertexPositions', function(t) {
        var geometry = new DynamicGeometry();
        var vertexPositions = [0, 0, 1, 0, 1, 0, 1, 0, 0];

        geometry.setVertexPositions(vertexPositions);

        t.deepEquals(
            geometry.spec.bufferValues[geometry.spec.bufferNames.indexOf('a_pos')],
            vertexPositions,
            'Should set vertex data to the pos attribute of the geometry'
        );

        t.equals(
            geometry.spec.bufferSpacings[geometry.spec.bufferNames.indexOf('a_pos')],
            3,
            'Should set buffer spacing to 3 for pos attribute'
        );

        t.end();
    });

    t.test('DynamicGeometry.prototype.setNormals', function(t) {
        var geometry = new DynamicGeometry();
        var vertexNormals = [0, 0, 1, 0, 1, 0, 1, 0, 0];

        geometry.setNormals(vertexNormals);

        t.deepEquals(
            geometry.spec.bufferValues[geometry.spec.bufferNames.indexOf('a_normals')],
            vertexNormals,
            'Should set vertex data to the "normal" attribute of the geometry'
        );

        t.equals(
            geometry.spec.bufferSpacings[geometry.spec.bufferNames.indexOf('a_normals')],
            3,
            'Should set buffer spacing to 3 for normal attribute'
        );

        t.end();
    });

    t.test('DynamicGeometry.prototype.setTextureCoords', function(t) {
        var geometry = new DynamicGeometry();
        var textureCoords = [0, 0, 0, 1, 1, 0, 1, 1];

        geometry.setTextureCoords(textureCoords);

        t.deepEquals(
            geometry.spec.bufferValues[geometry.spec.bufferNames.indexOf('a_texCoord')],
            textureCoords,
            'Should set vertex data to the "texCoord" attribute of the geometry'
        );

        t.equals(
            geometry.spec.bufferSpacings[geometry.spec.bufferNames.indexOf('a_texCoord')],
            2,
            'Should set buffer spacing to 2 for texCoord attribute'
        );

        t.end();
    });

    t.test('DynamicGeometry.prototype.setIndices', function(t) {
        var geometry = new DynamicGeometry();
        var indices = [0, 1, 2, 3, 4, 5, 6];

        geometry.setIndices(indices);

        t.deepEquals(
            geometry.spec.bufferValues[geometry.spec.bufferNames.indexOf('indices')],
            indices,
            'Should set vertex data to the "indices" attribute of the geometry'
        );

        t.equals(
            geometry.spec.bufferSpacings[geometry.spec.bufferNames.indexOf('indices')],
            1,
            'Should set buffer spacing to 1 for indices'
        );

        t.end();
    });

    t.test('DynamicGeometry.prototype.getVertexPositions', function(t) {
        var geometry = new DynamicGeometry();
        var vertexPositions = [-1, 0, 0, 1, 0, 0];
        geometry.setVertexPositions(vertexPositions)

        t.deepEquals(
            vertexPositions,
            geometry.getVertexPositions(),
            'Should return vertex position buffer'
        );

        t.end();
    });

    t.test('DynamicGeometry.prototype.getNormals', function(t) {
        var geometry = new DynamicGeometry();
        var normals = [-1, 0, 0, 1, 0, 0];
        geometry.setNormals(normals)

        t.deepEquals(
            normals,
            geometry.getNormals(),
            'Should return normal buffer'
        );

        t.end();
    });

    t.test('DynamicGeometry.prototype.getTextureCoords', function(t) {
        var geometry = new DynamicGeometry();
        var texCoords = [0, 0, 1, 0, 0, 1, 1, 1];
        geometry.setTextureCoords(texCoords)

        t.deepEquals(
            texCoords,
            geometry.getTextureCoords(),
            'Should return texCoord buffer'
        );

        t.end();
    });

    t.end();
});
<|endoftext|>


<commit_before>const typeDefs = `
  type MarkdownHeading {
    value: String
    depth: Int
  }

  enum MarkdownHeadingLevels {
    h1
    h2
    h3
    h4
    h5
    h6
  }

  enum MarkdownExcerptFormats {
    PLAIN
    HTML
    MARKDOWN
  }

  type MarkdownWordCount {
    paragraphs: Int
    sentences: Int
    words: Int
  }
`

module.exports = (nodeApiArgs, pluginOptions = {}) => {
  const { plugins = [] } = pluginOptions

  nodeApiArgs.actions.createTypes(typeDefs)

  // This allows subplugins to use Node APIs bound to `gatsby-transformer-remark`
  // to customize the GraphQL schema. This makes it possible for subplugins to
  // modify types owned by `gatsby-transformer-remark`.
  plugins.forEach(plugin => {
    const resolvedPlugin = require(plugin.resolve)
    if (typeof resolvedPlugin.createSchemaCustomization === `function`) {
      resolvedPlugin.createSchemaCustomization(
        nodeApiArgs,
        plugin.pluginOptions
      )
    }
  })
}

module.exports.typeDefs = typeDefs
<commit_msg>feat(gatsby-transformer-remark): subscribe to mimeTypes in defs(#16172)<commit_after>const typeDefs = `
  type MarkdownHeading {
    value: String
    depth: Int
  }

  enum MarkdownHeadingLevels {
    h1
    h2
    h3
    h4
    h5
    h6
  }

  enum MarkdownExcerptFormats {
    PLAIN
    HTML
    MARKDOWN
  }

  type MarkdownWordCount {
    paragraphs: Int
    sentences: Int
    words: Int
  }

  type MarkdownRemark implements Node @infer @childOf(mimeTypes: ["text/markdown", "text/x-markdown"]) {
    id: ID!
  }
`

module.exports = (nodeApiArgs, pluginOptions = {}) => {
  const { plugins = [] } = pluginOptions

  nodeApiArgs.actions.createTypes(typeDefs)

  // This allows subplugins to use Node APIs bound to `gatsby-transformer-remark`
  // to customize the GraphQL schema. This makes it possible for subplugins to
  // modify types owned by `gatsby-transformer-remark`.
  plugins.forEach(plugin => {
    const resolvedPlugin = require(plugin.resolve)
    if (typeof resolvedPlugin.createSchemaCustomization === `function`) {
      resolvedPlugin.createSchemaCustomization(
        nodeApiArgs,
        plugin.pluginOptions
      )
    }
  })
}

module.exports.typeDefs = typeDefs
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import EntityListApp from 'tocco-entity-list/src/main'
import Panel from 'react-bootstrap/lib/Panel'
import PanelGroup from 'react-bootstrap/lib/PanelGroup'

class SearchPanel extends React.PureComponent {
  constructor() {
    super()

    this.state = {activeKey: -1}
  }

  handleAccordionSelect = activeKey => {
    this.setState({activeKey: this.state.activeKey === activeKey ? -1 : activeKey})
  }

  handleSelect = name => selection => {
    this.props.updateRequestedCalendars(name, selection)
  }

  getSearchLists = calendarTypes => {
    const accordionHeader = (content, name, color) => {
      const iconClasses = classNames(
        'collapse-icon',
        'fa',
        `fa-chevron-${this.state.activeKey === name ? 'up' : 'down'}`
      )

      const colorIconClass = classNames(
        'color-icon',
        'fa',
        `fa-square${color ? '' : '-o'}`
      )

      return
 { this.handleAccordionSelect(name) }}>

        {content}

    }

    return calendarTypes.map(calendarType => (
      <Panel
        collapsible
        className="accordion-panel"
        header={accordionHeader(calendarType.label, calendarType.name, calendarType.color)}
        eventKey={calendarType.name}
        key={calendarType.name}
      >
        <EntityListApp
          locale={this.props.locale}
          id={`search-panel-${calendarType.name}`}
          entityName={calendarType.targetEntity}
          formBase={calendarType.formBase}
          limit={5}
          showSearchForm={true}
          showCreateButton={false}
          selectable={true}
          selection={this.props.requestedCalendars ? this.props.requestedCalendars[calendarType.name] || [] : []}
          onSelectChange={this.handleSelect(calendarType.name)}
        />
      </Panel>
    )
    )
  }

  render = () => (

      <PanelGroup accordion activeKey={this.state.activeKey} onSelect={this.handleAccordionSelect}>
        {this.getSearchLists(this.props.calendarTypes)}
      </PanelGroup>

  )
}

SearchPanel.propTypes = {
  updateRequestedCalendars: PropTypes.func.isRequired,
  calendarTypes: PropTypes.arrayOf(
    PropTypes.shape({
      label: PropTypes.string.isRequired,
      formBase: PropTypes.string.isRequired,
      name: PropTypes.string.isRequired,
      targetEntity: PropTypes.string.isRequired,
      color: PropTypes.string
    }
    )),
  requestedCalendars: PropTypes.objectOf(PropTypes.arrayOf(PropTypes.string)),
  locale: PropTypes.string
}

export default SearchPanel
<commit_msg>refactor(resource-scheduler): only set color if color is defined<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import EntityListApp from 'tocco-entity-list/src/main'
import Panel from 'react-bootstrap/lib/Panel'
import PanelGroup from 'react-bootstrap/lib/PanelGroup'

class SearchPanel extends React.PureComponent {
  constructor() {
    super()

    this.state = {activeKey: -1}
  }

  handleAccordionSelect = activeKey => {
    this.setState({activeKey: this.state.activeKey === activeKey ? -1 : activeKey})
  }

  handleSelect = name => selection => {
    this.props.updateRequestedCalendars(name, selection)
  }

  getSearchLists = calendarTypes => {
    const accordionHeader = (content, name, color) => {
      const iconClasses = classNames(
        'collapse-icon',
        'fa',
        `fa-chevron-${this.state.activeKey === name ? 'up' : 'down'}`
      )

      const colorIconClass = classNames(
        'color-icon',
        'fa',
        `fa-square${color ? '' : '-o'}`
      )

      return
 { this.handleAccordionSelect(name) }}>

        {content}

    }

    return calendarTypes.map(calendarType => (
      <Panel
        collapsible
        className="accordion-panel"
        header={accordionHeader(calendarType.label, calendarType.name, calendarType.color)}
        eventKey={calendarType.name}
        key={calendarType.name}
      >
        <EntityListApp
          locale={this.props.locale}
          id={`search-panel-${calendarType.name}`}
          entityName={calendarType.targetEntity}
          formBase={calendarType.formBase}
          limit={5}
          showSearchForm={true}
          showCreateButton={false}
          selectable={true}
          selection={this.props.requestedCalendars ? this.props.requestedCalendars[calendarType.name] || [] : []}
          onSelectChange={this.handleSelect(calendarType.name)}
        />
      </Panel>
    )
    )
  }

  render = () => (

      <PanelGroup accordion activeKey={this.state.activeKey} onSelect={this.handleAccordionSelect}>
        {this.getSearchLists(this.props.calendarTypes)}
      </PanelGroup>

  )
}

SearchPanel.propTypes = {
  updateRequestedCalendars: PropTypes.func.isRequired,
  calendarTypes: PropTypes.arrayOf(
    PropTypes.shape({
      label: PropTypes.string.isRequired,
      formBase: PropTypes.string.isRequired,
      name: PropTypes.string.isRequired,
      targetEntity: PropTypes.string.isRequired,
      color: PropTypes.string
    }
    )),
  requestedCalendars: PropTypes.objectOf(PropTypes.arrayOf(PropTypes.string)),
  locale: PropTypes.string
}

export default SearchPanel
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

const ID = 'disable-about-something@clear-code.com';

const Cc = Components.classes;
const Ci = Components.interfaces;
Components.utils.import('resource://gre/modules/XPCOMUtils.jsm');
Components.utils.import('resource://disable-about-something-modules/prefs.js');

const kCID  = Components.ID('{a00cbf60-9527-11e3-a5e2-0800200c9a66}');
const kID   = '@clear-code.com/disable-about-something/blocker;1';
const kNAME = "DisableAboutSomethingBlocker";

const ObserverService = Cc['@mozilla.org/observer-service;1']
  .getService(Ci.nsIObserverService);

// const Application = Cc['@mozilla.org/steel/application;1']
//     .getService(Ci.steelIApplication);

// let { console } = Application;

// function dir(obj) console.log(Object.getOwnPropertyNames(obj).join("\n"));

const BASE = 'extensions.disable-about-something@clear-code.com.';

function DisableAboutSomethingBlocker() {}

DisableAboutSomethingBlocker.prototype = {
  QueryInterface: function (aIID) {
    if (!aIID.equals(Ci.nsIContentPolicy) &&
        !aIID.equals(Ci.nsISupportsWeakReference) &&
        !aIID.equals(Ci.nsISupports))
      throw Components.results.NS_ERROR_NO_INTERFACE;
    return this;
  },

  TYPE_OTHER       : Ci.nsIContentPolicy.TYPE_OTHER,
  TYPE_SCRIPT      : Ci.nsIContentPolicy.TYPE_SCRIPT,
  TYPE_IMAGE       : Ci.nsIContentPolicy.TYPE_IMAGE,
  TYPE_STYLESHEET  : Ci.nsIContentPolicy.TYPE_STYLESHEET,
  TYPE_OBJECT      : Ci.nsIContentPolicy.TYPE_OBJECT,
  TYPE_DOCUMENT    : Ci.nsIContentPolicy.TYPE_DOCUMENT,
  TYPE_SUBDOCUMENT : Ci.nsIContentPolicy.TYPE_SUBDOCUMENT,
  TYPE_REFRESH     : Ci.nsIContentPolicy.TYPE_REFRESH,
  ACCEPT           : Ci.nsIContentPolicy.ACCEPT,
  REJECT_REQUEST   : Ci.nsIContentPolicy.REJECT_REQUEST,
  REJECT_TYPE      : Ci.nsIContentPolicy.REJECT_TYPE,
  REJECT_SERVER    : Ci.nsIContentPolicy.REJECT_SERVER,
  REJECT_OTHER     : Ci.nsIContentPolicy.REJECT_OTHER,

  shouldLoad: function (aContentType, aContentLocation, aRequestOrigin, aContext, aMimeTypeGuess, aExtra) {
    var scheme = aContentLocation.scheme;
    if (scheme == 'about') {
      let localPart = aContentLocation.spec.replace(scheme + ':', '');
      localPart = localPart.split('?')[0];
      if (prefs.getPref(BASE + scheme + '.' + localPart) === false) {
        this.processBlockedContext(aContext);
        return this.REJECT_REQUEST;
      }
    }

    return this.ACCEPT;
  },

  shouldProcess: function (aContentType, aContentLocation, aRequestOrigin, aContext, aMimeTypeGuess, aExtra) {
    return this.ACCEPT;
  },

  processBlockedContext: function (aContext) {
    try {
      if (aContext instanceof Ci.nsIDOMElement && aContext.localName == 'browser') {
        aContext.stop();
        let doc = aContext.ownerDocument;
        let chrome = doc.defaultView;
        if (chrome &&
            chrome.gBrowser &&
            chrome.gBrowser.selectedBrowser == aContext &&
            chrome.gBrowser.visibleTabs.length == 1)
          return;
      }
      let win = aContext.contentWindow;
      win.close();
    } catch (error) {}

    // XXX: does not work
    // win.setTimeout(function () {
    //   win.close();
    // }, 0);
  },

  classID           : kCID,
  contractID        : kID,
  classDescription  : kNAME,
  QueryInterface    : XPCOMUtils.generateQI([Ci.nsIContentPolicy]),
  _xpcom_categories : [
    { category : 'content-policy', service : true }
  ]
};

if (XPCOMUtils.generateNSGetFactory)
  var NSGetFactory = XPCOMUtils.generateNSGetFactory([DisableAboutSomethingBlocker]);
else
  var NSGetModule = XPCOMUtils.generateNSGetModule([DisableAboutSomethingBlocker]);
<commit_msg>Report blocked<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

const ID = 'disable-about-something@clear-code.com';

const Cc = Components.classes;
const Ci = Components.interfaces;
Components.utils.import('resource://gre/modules/XPCOMUtils.jsm');
Components.utils.import('resource://disable-about-something-modules/prefs.js');

const kCID  = Components.ID('{a00cbf60-9527-11e3-a5e2-0800200c9a66}');
const kID   = '@clear-code.com/disable-about-something/blocker;1';
const kNAME = "DisableAboutSomethingBlocker";

const ObserverService = Cc['@mozilla.org/observer-service;1']
  .getService(Ci.nsIObserverService);

// const Application = Cc['@mozilla.org/steel/application;1']
//     .getService(Ci.steelIApplication);

// let { console } = Application;

// function dir(obj) console.log(Object.getOwnPropertyNames(obj).join("\n"));

const BASE = 'extensions.disable-about-something@clear-code.com.';

function DisableAboutSomethingBlocker() {}

DisableAboutSomethingBlocker.prototype = {
  QueryInterface: function (aIID) {
    if (!aIID.equals(Ci.nsIContentPolicy) &&
        !aIID.equals(Ci.nsISupportsWeakReference) &&
        !aIID.equals(Ci.nsISupports))
      throw Components.results.NS_ERROR_NO_INTERFACE;
    return this;
  },

  TYPE_OTHER       : Ci.nsIContentPolicy.TYPE_OTHER,
  TYPE_SCRIPT      : Ci.nsIContentPolicy.TYPE_SCRIPT,
  TYPE_IMAGE       : Ci.nsIContentPolicy.TYPE_IMAGE,
  TYPE_STYLESHEET  : Ci.nsIContentPolicy.TYPE_STYLESHEET,
  TYPE_OBJECT      : Ci.nsIContentPolicy.TYPE_OBJECT,
  TYPE_DOCUMENT    : Ci.nsIContentPolicy.TYPE_DOCUMENT,
  TYPE_SUBDOCUMENT : Ci.nsIContentPolicy.TYPE_SUBDOCUMENT,
  TYPE_REFRESH     : Ci.nsIContentPolicy.TYPE_REFRESH,
  ACCEPT           : Ci.nsIContentPolicy.ACCEPT,
  REJECT_REQUEST   : Ci.nsIContentPolicy.REJECT_REQUEST,
  REJECT_TYPE      : Ci.nsIContentPolicy.REJECT_TYPE,
  REJECT_SERVER    : Ci.nsIContentPolicy.REJECT_SERVER,
  REJECT_OTHER     : Ci.nsIContentPolicy.REJECT_OTHER,

  shouldLoad: function (aContentType, aContentLocation, aRequestOrigin, aContext, aMimeTypeGuess, aExtra) {
    var scheme = aContentLocation.scheme;
    if (scheme == 'about') {
      let localPart = aContentLocation.spec.replace(scheme + ':', '');
      localPart = localPart.split('?')[0];
      if (prefs.getPref(BASE + scheme + '.' + localPart) === false) {
        this.processBlockedContext(aContext);
        Components.utils.reportError(new Error(ID + ': ' + aContentLocation.spec + ' is blocked!'));
        return this.REJECT_REQUEST;
      }
    }

    return this.ACCEPT;
  },

  shouldProcess: function (aContentType, aContentLocation, aRequestOrigin, aContext, aMimeTypeGuess, aExtra) {
    return this.ACCEPT;
  },

  processBlockedContext: function (aContext) {
    try {
      if (aContext instanceof Ci.nsIDOMElement && aContext.localName == 'browser') {
        aContext.stop();
        let doc = aContext.ownerDocument;
        let chrome = doc.defaultView;
        if (chrome &&
            chrome.gBrowser &&
            chrome.gBrowser.selectedBrowser == aContext &&
            chrome.gBrowser.visibleTabs.length == 1)
          return;
      }
      let win = aContext.contentWindow;
      win.close();
    } catch (error) {}

    // XXX: does not work
    // win.setTimeout(function () {
    //   win.close();
    // }, 0);
  },

  classID           : kCID,
  contractID        : kID,
  classDescription  : kNAME,
  QueryInterface    : XPCOMUtils.generateQI([Ci.nsIContentPolicy]),
  _xpcom_categories : [
    { category : 'content-policy', service : true }
  ]
};

if (XPCOMUtils.generateNSGetFactory)
  var NSGetFactory = XPCOMUtils.generateNSGetFactory([DisableAboutSomethingBlocker]);
else
  var NSGetModule = XPCOMUtils.generateNSGetModule([DisableAboutSomethingBlocker]);
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012 B3Partners B.V.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * Drawing component
 * Creates a Drawing component
 * @author Meine Toonen
 */
Ext.define ("viewer.components.Drawing",{
    extend: "viewer.components.Component",
    iconPath: null,
    // Forms
    formdraw : null,
    formselect : null,
    formsave : null,
    formopen : null,
    vectorLayer:null,
    // Items in forms. Convience accessor
    colorPicker:null,
    label:null,
    title:null,
    comment:null,
    file:null,
    // Current active feature
    activeFeature:null,
    features:null,
    config:{
        title: "",
        iconUrl: "",
        tooltip: "",
        color: ""
    },
    constructor: function (conf){
        viewer.components.Drawing.superclass.constructor.call(this, conf);
        this.initConfig(conf);
        this.features = new Object();
        var me = this;
        this.renderButton({
            handler: function(){
                me.popup.show();
            },
            text: me.title,
            icon: me.iconUrl,
            tooltip: me.tooltip
        });

        this.vectorLayer=viewerController.mapComponent.createVectorLayer({
            id: 'drawingVectorLayer',
            name:'drawingVectorLayer',
            geometrytypes:["Circle","Polygon","Point","LineString"],
            showmeasures:false,
            style: {
                fillcolor: "0x"+this.color,
                fillopacity: 50,
                strokecolor: "0xFF0000",
                strokeopacity: 50
            }
        });
        viewerController.mapComponent.getMap().addLayer(this.vectorLayer);
        this.vectorLayer.addListener (viewer.viewercontroller.controller.Event.ON_ACTIVE_FEATURE_CHANGED,this.activeFeatureChanged,this);
        this.vectorLayer.addListener (viewer.viewercontroller.controller.Event.ON_FEATURE_ADDED,this.activeFeatureFinished,this);
        this.iconPath=contextPath+"/viewer-html/components/resources/images/drawing/";
        this.loadWindow();
        this.popup.show();
        return this;
    },
    /**
     * Create the GUI
     */
    loadWindow : function(){
        var me=this;
        this.colorPicker = Ext.create("Ext.ux.ColorField",{
            width: 40,
            showText: false,
            name: 'color',
            id:'color',
            value: this.color,
            listeners :{
                select : {
                    fn: this.colorChanged,
                    scope : this
                }
            }
        });

        this.label = Ext.create("Ext.form.field.Text",{
            name: 'labelObject',
            fieldLabel: 'Label geselecteerd object',
            labelWidth: 150,
            id: 'labelObject' + this.name,
            listeners:{
                change:{
                    fn: this.labelChanged,
                    scope:this
                }
            }
        });
        this.formdraw = new Ext.form.FormPanel({
            items: [{
                xtype: 'fieldset',
                defaultType: 'textfield',
                padding: 0,
                style: {
                    border: '0px none',
                    margin : '5px'
                },
                items: [
                {
                    xtype: 'label',
                    text: 'Objecten op de kaart tekenen'
                },
                {
                    xtype: 'fieldset',
                    layout:{
                        type:'hbox',
                        defaultMargins:{
                            top: 5,
                            right: 5,
                            bottom: 0,
                            left: 0
                        }
                    },
                    items: [{
                        xtype: 'button',
                        icon: this.iconPath+"bullet_red.png",
                        tooltip: "Teken een punt",
                        listeners: {
                            click:{
                                scope: me,
                                fn: me.drawPoint
                            }
                        }
                    },
                    {
                        xtype: 'button',
                        icon: this.iconPath+"line_red.png",
                        tooltip: "Teken een lijn",
                        listeners: {
                            click:{
                                scope: me,
                                fn: me.drawLine
                            }
                        }
                    },
                    {
                        xtype: 'button',
                        icon: this.iconPath+"shape_square_red.png",
                        tooltip: "Teken een polygoon",
                        listeners: {
                            click:{
                                scope: me,
                                fn: me.drawPolygon
                            }
                        }
                    },
                    {
                        xtype: 'button',
                        icon: this.iconPath+"shape_square_red.png",
                        tooltip: "Teken een cirkel",
                        listeners: {
                            click:{
                                scope: me,
                                fn: me.drawCircle
                            }
                        }
                    },
                    this.colorPicker,
                    {
                        xtype: 'button',
                        icon: this.iconPath+"delete.png",
                        tooltip: "Verwijder alle objecten",
                        listeners: {
                            click:{
                                scope: me,
                                fn: me.deleteAll
                            }
                        }
                    }]
                }
                ]
            }],

            renderTo: this.getContentDiv()
        });

        this.formselect = new Ext.form.FormPanel({
            items: [
            {
                xtype: 'fieldset',
                defaultType: 'textfield',
                border: 0,
                padding: 10,
                style: {
                    border: '0px none',
                    marginBottom: '0px'
                },
                layout:'hbox',
                items: [
                this.label,
                {
                    xtype: 'button',
                    icon: this.iconPath+"delete.png",
                    tooltip: "Verwijder geselecteerd object",
                    listeners: {
                        click:{
                            scope: me,
                            fn: me.deleteObject
                        }
                    }
                }
                ]
            }
            ],
            renderTo: this.getContentDiv()
        });

        // Convience accessor
        this.title = Ext.create("Ext.form.field.Text",{
            fieldLabel: 'Titel',
            name: 'title',
            allowBlank:false,
            id: 'title'+ this.name
        });
        this.description = Ext.create("Ext.form.field.TextArea",
        {
            fieldLabel: 'Opmerking',
            allowBlank:false,
            name: 'description',
            id: 'description'
        });
        // Build the saving form
        this.formsave = new Ext.form.FormPanel({
            standardSubmit: true,
            url: actionBeans["file"] + "?save",
            items: [
            {
                xtype: 'label',
                text: 'Op de kaart getekende objecten opslaan'
            },
            this.title,
            this.description,
            {
                xtype: 'hiddenfield',
                name: 'saveObject',
                id: 'saveObject'
            },
            {
                xtype: 'button',
                text: 'Opslaan als bestand',
                listeners: {
                    click:{
                        scope: me,
                        fn: me.saveFile
                    }
                }
            }
            ],
            renderTo: this.getContentDiv()
        });

        this.file = Ext.create("Ext.form.field.File", {
            fieldLabel: 'Tekstbestand',
            name: 'featureFile',
            allowBlank:false,
            msgTarget: 'side',
            anchor: '100%',
            buttonText: 'Bladeren',
            id: 'featureFile'
        });
        this.formopen = new Ext.form.FormPanel({
            items: [
            {
                xtype: 'label',
                text: 'Bestand met getekende objecten openen'
            },
            this.file,
            {
                xtype: 'button',
                text: 'bestand openen',
                listeners: {
                    click:{
                        scope: me,
                        fn: me.openFile
                    }
                }
            }
            ],
            renderTo: this.getContentDiv()
        });

        this.formselect.setVisible(false);
    },

    /**
     * Event handlers
     **/
    activeFeatureChanged : function (vectorLayer,feature){
        this.toggleSelectForm(true);
        if(this.features[feature.id] == undefined){
            feature.color = "0x"+this.color;
            this.features[feature.id] = feature;
        }else{
            var color = this.features[feature.id].color;
            color = color.substring(2);
            this.colorPicker.setColor(color);
            this.color = color;
        }
        this.activeFeature = this.features[feature.id];
        this.label.setValue(this.activeFeature.label);
    },
    //update the wkt of the active feature with the completed feature
    activeFeatureFinished : function (vectorLayer,feature){
        this.activeFeature.wktgeom = feature.wktgeom;
    },
    colorChanged : function (hexColor){
        this.color = '0x'+hexColor;
        this.vectorLayer.style.fillcolor = this.color;
        this.vectorLayer.adjustStyle();
        if(this.activeFeature != null){
            this.activeFeature.color = this.color;
            var feature = this.vectorLayer.getFeatureById(this.activeFeature.getId());
            this.activeFeature.wktgeom = feature.wktgeom;
            this.vectorLayer.removeFeature(this.activeFeature);
            this.vectorLayer.addFeature(this.activeFeature);
        }
    },
    labelChanged : function (field,newValue){
        this.vectorLayer.setLabel(this.activeFeature.getId(),newValue);
        this.activeFeature.label=newValue;
    },
    toggleSelectForm : function(visible){
        this.formselect.setVisible(visible);
    },
    drawPoint: function(){
        this.vectorLayer.drawFeature("Point");
    },
    drawLine: function(){
        this.vectorLayer.drawFeature("LineString");
    },
    drawPolygon: function(){
        this.vectorLayer.drawFeature("Polygon");
    },
    drawCircle: function(){
        this.vectorLayer.drawFeature("Circle");
    },
    deleteAll: function(){
        this.vectorLayer.removeAllFeatures();
        this.toggleSelectForm(false);
        this.features = {};
        this.activeFeature=null;
    },
    deleteObject: function(){
        delete this.features[this.activeFeature.id];
        this.vectorLayer.removeFeature(this.activeFeature);
        this.toggleSelectForm(false);
        this.activeFeature=null;
    },
    saveFile: function(){
        var form = this.formsave.getForm();

        var features = new Array();
        for (var featurekey in this.features){
            var feature = this.features[featurekey];
            features.push(feature.toJsonObject());
        }
        form.setValues({
            "saveObject":Ext.JSON.encode(features)
        });
        this.formsave.submit({
            target: '_blank'
        } );
        return features;
    },
    openFile: function(){
        var form =this.formopen.getForm();
        if(form.isValid()){
            form.submit({
                scope:this,
                url: actionBeans["file"],
                waitMsg: 'Bezig met uploaden...',
                success: function(fp, o) {
                    var json = Ext.JSON.decode(o.result.content);
                    this.title.setValue( json.title);
                    this.description.setValue(json.description);
                    var features = Ext.JSON.decode(json.features);
                    for ( var i = 0 ; i < features.length;i++){
                        var feature = features[i];
                        var featureObject = Ext.create("viewer.viewercontroller.controller.Feature",feature);
                        this.vectorLayer.style.fillcolor = featureObject.color;
                        this.vectorLayer.adjustStyle();
                        this.vectorLayer.addFeature(featureObject);
                    }

                },
                failure: function (){
                    Ext.Msg.alert('Mislukt', 'Uw bestand kon niet gelezen worden.');
                }
            });
        }
    }
});
 <commit_msg>Removed initial showing of popup<commit_after>/*
 * Copyright (C) 2012 B3Partners B.V.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * Drawing component
 * Creates a Drawing component
 * @author Meine Toonen
 */
Ext.define ("viewer.components.Drawing",{
    extend: "viewer.components.Component",
    iconPath: null,
    // Forms
    formdraw : null,
    formselect : null,
    formsave : null,
    formopen : null,
    vectorLayer:null,
    // Items in forms. Convience accessor
    colorPicker:null,
    label:null,
    title:null,
    comment:null,
    file:null,
    // Current active feature
    activeFeature:null,
    features:null,
    config:{
        title: "",
        iconUrl: "",
        tooltip: "",
        color: ""
    },
    constructor: function (conf){
        viewer.components.Drawing.superclass.constructor.call(this, conf);
        this.initConfig(conf);
        this.features = new Object();
        var me = this;
        this.renderButton({
            handler: function(){
                me.popup.show();
            },
            text: me.title,
            icon: me.iconUrl,
            tooltip: me.tooltip
        });

        this.vectorLayer=viewerController.mapComponent.createVectorLayer({
            id: 'drawingVectorLayer',
            name:'drawingVectorLayer',
            geometrytypes:["Circle","Polygon","Point","LineString"],
            showmeasures:false,
            style: {
                fillcolor: "0x"+this.color,
                fillopacity: 50,
                strokecolor: "0xFF0000",
                strokeopacity: 50
            }
        });
        viewerController.mapComponent.getMap().addLayer(this.vectorLayer);
        this.vectorLayer.addListener (viewer.viewercontroller.controller.Event.ON_ACTIVE_FEATURE_CHANGED,this.activeFeatureChanged,this);
        this.vectorLayer.addListener (viewer.viewercontroller.controller.Event.ON_FEATURE_ADDED,this.activeFeatureFinished,this);
        this.iconPath=contextPath+"/viewer-html/components/resources/images/drawing/";
        this.loadWindow();
        return this;
    },
    /**
     * Create the GUI
     */
    loadWindow : function(){
        var me=this;
        this.colorPicker = Ext.create("Ext.ux.ColorField",{
            width: 40,
            showText: false,
            name: 'color',
            id:'color',
            value: this.color,
            listeners :{
                select : {
                    fn: this.colorChanged,
                    scope : this
                }
            }
        });

        this.label = Ext.create("Ext.form.field.Text",{
            name: 'labelObject',
            fieldLabel: 'Label geselecteerd object',
            labelWidth: 150,
            id: 'labelObject' + this.name,
            listeners:{
                change:{
                    fn: this.labelChanged,
                    scope:this
                }
            }
        });
        this.formdraw = new Ext.form.FormPanel({
            items: [{
                xtype: 'fieldset',
                defaultType: 'textfield',
                padding: 0,
                style: {
                    border: '0px none',
                    margin : '5px'
                },
                items: [
                {
                    xtype: 'label',
                    text: 'Objecten op de kaart tekenen'
                },
                {
                    xtype: 'fieldset',
                    layout:{
                        type:'hbox',
                        defaultMargins:{
                            top: 5,
                            right: 5,
                            bottom: 0,
                            left: 0
                        }
                    },
                    items: [{
                        xtype: 'button',
                        icon: this.iconPath+"bullet_red.png",
                        tooltip: "Teken een punt",
                        listeners: {
                            click:{
                                scope: me,
                                fn: me.drawPoint
                            }
                        }
                    },
                    {
                        xtype: 'button',
                        icon: this.iconPath+"line_red.png",
                        tooltip: "Teken een lijn",
                        listeners: {
                            click:{
                                scope: me,
                                fn: me.drawLine
                            }
                        }
                    },
                    {
                        xtype: 'button',
                        icon: this.iconPath+"shape_square_red.png",
                        tooltip: "Teken een polygoon",
                        listeners: {
                            click:{
                                scope: me,
                                fn: me.drawPolygon
                            }
                        }
                    },
                    {
                        xtype: 'button',
                        icon: this.iconPath+"shape_square_red.png",
                        tooltip: "Teken een cirkel",
                        listeners: {
                            click:{
                                scope: me,
                                fn: me.drawCircle
                            }
                        }
                    },
                    this.colorPicker,
                    {
                        xtype: 'button',
                        icon: this.iconPath+"delete.png",
                        tooltip: "Verwijder alle objecten",
                        listeners: {
                            click:{
                                scope: me,
                                fn: me.deleteAll
                            }
                        }
                    }]
                }
                ]
            }],

            renderTo: this.getContentDiv()
        });

        this.formselect = new Ext.form.FormPanel({
            items: [
            {
                xtype: 'fieldset',
                defaultType: 'textfield',
                border: 0,
                padding: 10,
                style: {
                    border: '0px none',
                    marginBottom: '0px'
                },
                layout:'hbox',
                items: [
                this.label,
                {
                    xtype: 'button',
                    icon: this.iconPath+"delete.png",
                    tooltip: "Verwijder geselecteerd object",
                    listeners: {
                        click:{
                            scope: me,
                            fn: me.deleteObject
                        }
                    }
                }
                ]
            }
            ],
            renderTo: this.getContentDiv()
        });

        // Convience accessor
        this.title = Ext.create("Ext.form.field.Text",{
            fieldLabel: 'Titel',
            name: 'title',
            allowBlank:false,
            id: 'title'+ this.name
        });
        this.description = Ext.create("Ext.form.field.TextArea",
        {
            fieldLabel: 'Opmerking',
            allowBlank:false,
            name: 'description',
            id: 'description'
        });
        // Build the saving form
        this.formsave = new Ext.form.FormPanel({
            standardSubmit: true,
            url: actionBeans["file"] + "?save",
            items: [
            {
                xtype: 'label',
                text: 'Op de kaart getekende objecten opslaan'
            },
            this.title,
            this.description,
            {
                xtype: 'hiddenfield',
                name: 'saveObject',
                id: 'saveObject'
            },
            {
                xtype: 'button',
                text: 'Opslaan als bestand',
                listeners: {
                    click:{
                        scope: me,
                        fn: me.saveFile
                    }
                }
            }
            ],
            renderTo: this.getContentDiv()
        });

        this.file = Ext.create("Ext.form.field.File", {
            fieldLabel: 'Tekstbestand',
            name: 'featureFile',
            allowBlank:false,
            msgTarget: 'side',
            anchor: '100%',
            buttonText: 'Bladeren',
            id: 'featureFile'
        });
        this.formopen = new Ext.form.FormPanel({
            items: [
            {
                xtype: 'label',
                text: 'Bestand met getekende objecten openen'
            },
            this.file,
            {
                xtype: 'button',
                text: 'bestand openen',
                listeners: {
                    click:{
                        scope: me,
                        fn: me.openFile
                    }
                }
            }
            ],
            renderTo: this.getContentDiv()
        });

        this.formselect.setVisible(false);
    },

    /**
     * Event handlers
     **/
    activeFeatureChanged : function (vectorLayer,feature){
        this.toggleSelectForm(true);
        if(this.features[feature.id] == undefined){
            feature.color = "0x"+this.color;
            this.features[feature.id] = feature;
        }else{
            var color = this.features[feature.id].color;
            color = color.substring(2);
            this.colorPicker.setColor(color);
            this.color = color;
        }
        this.activeFeature = this.features[feature.id];
        this.label.setValue(this.activeFeature.label);
    },
    //update the wkt of the active feature with the completed feature
    activeFeatureFinished : function (vectorLayer,feature){
        this.activeFeature.wktgeom = feature.wktgeom;
    },
    colorChanged : function (hexColor){
        this.color = '0x'+hexColor;
        this.vectorLayer.style.fillcolor = this.color;
        this.vectorLayer.adjustStyle();
        if(this.activeFeature != null){
            this.activeFeature.color = this.color;
            var feature = this.vectorLayer.getFeatureById(this.activeFeature.getId());
            this.activeFeature.wktgeom = feature.wktgeom;
            this.vectorLayer.removeFeature(this.activeFeature);
            this.vectorLayer.addFeature(this.activeFeature);
        }
    },
    labelChanged : function (field,newValue){
        this.vectorLayer.setLabel(this.activeFeature.getId(),newValue);
        this.activeFeature.label=newValue;
    },
    toggleSelectForm : function(visible){
        this.formselect.setVisible(visible);
    },
    drawPoint: function(){
        this.vectorLayer.drawFeature("Point");
    },
    drawLine: function(){
        this.vectorLayer.drawFeature("LineString");
    },
    drawPolygon: function(){
        this.vectorLayer.drawFeature("Polygon");
    },
    drawCircle: function(){
        this.vectorLayer.drawFeature("Circle");
    },
    deleteAll: function(){
        this.vectorLayer.removeAllFeatures();
        this.toggleSelectForm(false);
        this.features = {};
        this.activeFeature=null;
    },
    deleteObject: function(){
        delete this.features[this.activeFeature.id];
        this.vectorLayer.removeFeature(this.activeFeature);
        this.toggleSelectForm(false);
        this.activeFeature=null;
    },
    saveFile: function(){
        var form = this.formsave.getForm();

        var features = new Array();
        for (var featurekey in this.features){
            var feature = this.features[featurekey];
            features.push(feature.toJsonObject());
        }
        form.setValues({
            "saveObject":Ext.JSON.encode(features)
        });
        this.formsave.submit({
            target: '_blank'
        } );
        return features;
    },
    openFile: function(){
        var form =this.formopen.getForm();
        if(form.isValid()){
            form.submit({
                scope:this,
                url: actionBeans["file"],
                waitMsg: 'Bezig met uploaden...',
                success: function(fp, o) {
                    var json = Ext.JSON.decode(o.result.content);
                    this.title.setValue( json.title);
                    this.description.setValue(json.description);
                    var features = Ext.JSON.decode(json.features);
                    for ( var i = 0 ; i < features.length;i++){
                        var feature = features[i];
                        var featureObject = Ext.create("viewer.viewercontroller.controller.Feature",feature);
                        this.vectorLayer.style.fillcolor = featureObject.color;
                        this.vectorLayer.adjustStyle();
                        this.vectorLayer.addFeature(featureObject);
                    }

                },
                failure: function (){
                    Ext.Msg.alert('Mislukt', 'Uw bestand kon niet gelezen worden.');
                }
            });
        }
    }
});
 <|endoftext|>


<commit_before>/**
 * UI and function to quick search projects
 */

var $ = require('jquery');
var m = require('mithril');
var $osf = require('js/osfHelpers');

// CSS
require('css/quick-project-search-plugin.css');

// XHR config for apiserver connection
var xhrconfig = function(xhr) {
    xhr.withCredentials = true;
};

var quickSearchProject = {
    controller: function() {
        var self = this;
        self.nodes = [];
        self.displayedNodes = [];
        //self.lastLogin = '';
        self.lastLogin = '2016-01-01T15:20:11.531000';
        self.commentsCount = {};
        self.logsCount = {};

        // Load node list
        var url = $osf.apiV2Url('users/me/nodes/', { query : { 'embed': 'contributors', 'page[size]': 100}});
        var promise = m.request({method: 'GET', url : url, config : xhrconfig});
        promise.then(function(result){
            result.data.forEach(function(node){
                self.nodes.push(node);
            });
            self.nodes.sort(function(a,b){
                var A = a.attributes.date_modified;
                var B = b.attributes.date_modified;
                return (A > B) ? -1 : (A < B) ? 1 : 0;
            });
            self.displayedNodes = self.nodes.splice(0, 10)
        });

        // Load last login
        self.getLastLoginDate = function () {
            var url = $osf.apiV2Url('users/me/', {});
            var promise = m.request({method: 'GET', url: url, config : xhrconfig});
            promise.then(function(result) {
                self.lastLogin = result.data.attributes.last_login
            }
            );
            return promise
        };

        self.getFamilyName = function(i, node) {
            return node.embeds.contributors.data[i].embeds.users.data.attributes.family_name
        };
        self.getContributors = function (node) {
            var numContributors = node.embeds.contributors.links.meta.total;
            if (numContributors === 1) {
                return self.getFamilyName(0, node)
            }
            else if (numContributors == 2) {
                return self.getFamilyName(0, node) + ' and ' +
                        self.getFamilyName(1, node)
            }
            else {
                return self.getFamilyName(0, node) + ', ' +
                        self.getFamilyName(1, node) + ', ' +
                        self.getFamilyName(2, node) + ' + ' + (numContributors - 3)
            }

        };

        self.getRecentComments = function (node) {
            var url = $osf.apiV2Url('nodes/' + node.id + '/comments/',
                { query : { 'filter[date_modified][gte]': self.lastLogin}}
            );
            var promise = m.request({method: 'GET', url : url, config: xhrconfig});
            promise.then(function(result) {
                self.commentsCount[node.id] = result.links.meta.total
            });
            return promise
        };

        self.loadRecentCommentCount = function (node) {
            if (node.id in self.commentsCount) {
                return self.commentsCount[node.id]
            }
            else {
                self.getRecentComments(node);
                return self.commentsCount[node.id]
            }
        };

        self.getRecentLogs = function (node) {
            var url = $osf.apiV2Url('nodes/' + node.id + '/logs/', { query : {'filter[action][ne]': 'comment_added',
                'filter[date][gte]': self.lastLogin}});
            var promise = m.request({method: 'GET', url : url, config: xhrconfig});
            promise.then(function(result){
                self.logsCount[node.id] = result.links.meta.total
            });
            return promise
        };

        self.loadRecentLogsCount = function(node) {
            if (node.id in self.logsCount){
                return self.logsCount[node.id]
            }
            else {
                self.getRecentLogs(node);
                return self.logsCount[node.id]
          }
        };

        self.loadUpToTen = function () {
            requested = self.nodes.splice(0, 10);
            for (i = 0; i < requested.length; i++) {
                self.displayedNodes.push(requested[i])
            }
            return self.displayedNodes
        };

        self.formatDate = function (node) {
            return new $osf.FormattableDate(node.attributes.date_modified).local
        };

        self.restoreFullNodeList = function () {
            for (i = 0; i < self.displayedNodes.length ; i++) {
                self.nodes.push(self.displayedNodes[i])
            }
        };

        self.sortAlphabeticalAscending = function () {
            numDisplayed = self.displayedNodes.length;
            self.restoreFullNodeList();
            self.nodes.sort(function(a,b){
                var A = a.attributes.title.toUpperCase();
                var B = b.attributes.title.toUpperCase();
                return (A < B) ? -1 : (A > B) ? 1 : 0;
            });
            self.displayedNodes = self.nodes.splice(0, numDisplayed);
            return self.displayedNodes
        };

        self.sortAlphabeticalDescending = function () {
            numDisplayed = self.displayedNodes.length;
            self.restoreFullNodeList();
            self.nodes.sort(function(a,b){
                var A = a.attributes.title.toUpperCase();
                var B = b.attributes.title.toUpperCase();
                return (A > B) ? -1 : (A < B) ? 1 : 0;
            });
            self.displayedNodes = self.nodes.splice(0, numDisplayed);
            return self.displayedNodes

        };

        self.sortDateAscending = function () {
            numDisplayed = self.displayedNodes.length;
            self.restoreFullNodeList();
            self.nodes.sort(function(a,b){
                var A = a.attributes.date_modified;
                var B = b.attributes.date_modified;
                return (A > B) ? -1 : (A < B) ? 1 : 0;
            });
            self.displayedNodes = self.nodes.splice(0, numDisplayed);
            return self.displayedNodes
        };

        self.sortDateDescending = function () {
            numDisplayed = self.displayedNodes.length;
            self.restoreFullNodeList();
            self.nodes.sort(function(a,b){
                var A = a.attributes.date_modified;
                var B = b.attributes.date_modified;
                return (A < B) ? -1 : (A > B) ? 1 : 0;
            });
            self.displayedNodes = self.nodes.splice(0, numDisplayed);
            return self.displayedNodes
        };

        //self.getLastLoginDate()

    },
    view : function(ctrl) {
        function projectView(project) {
            return m('tr', [
                m('td', m("a", {href: '/'+ project.id}, project.attributes.title)),
                m('td', ctrl.getContributors(project)),
                m('td', ctrl.formatDate(project)),
                m('td', ctrl.loadRecentCommentCount(project)),
                m('td', ctrl.loadRecentLogsCount(project))
            ])
        }

        function loadMoreButton() {
            if (ctrl.nodes.length !== 0){
                return m('button', { onclick: function() {
                    ctrl.loadUpToTen() }
                }, 'Load more')
            }
        }

        return m('div', [
            m('input[type=search]', 'Quick search projects'),
            m('table', [
                m('tr', [
                    m('th', 'Name',
                        m('button', {class: 'glyphicon glyphicon-chevron-up', onclick: function() {
                           ctrl.sortAlphabeticalAscending()}}),
                        m('button', {class: 'glyphicon glyphicon-chevron-down', onclick: function() {
                            ctrl.sortAlphabeticalDescending()
                        }})),
                    m('th', 'Contributors'),
                    m('th', 'Modified',
                        m('button', {class: 'glyphicon glyphicon-chevron-up', onclick: function() {
                           ctrl.sortDateAscending()}}),
                        m('button', {class: 'glyphicon glyphicon-chevron-down', onclick: function() {
                           ctrl.sortDateDescending()
                       }})
                    ),
                    m('th', 'New comments'),
                    m('th', 'New logs')
                ]),

                ctrl.displayedNodes.map(function(n){
                    return projectView(n)
                }),
                loadMoreButton()

            ])
        ])
    }
};

module.exports = quickSearchProject;

<commit_msg>Bootstrap grid for easier viewing - temporary.<commit_after>/**
 * UI and function to quick search projects
 */

var $ = require('jquery');
var m = require('mithril');
var $osf = require('js/osfHelpers');

// CSS
require('css/quick-project-search-plugin.css');

// XHR config for apiserver connection
var xhrconfig = function(xhr) {
    xhr.withCredentials = true;
};

var quickSearchProject = {
    controller: function() {
        var self = this;
        self.nodes = [];
        self.displayedNodes = [];
        //self.lastLogin = '';
        self.lastLogin = '2016-01-01T15:20:11.531000';
        self.commentsCount = {};
        self.logsCount = {};

        // Load node list
        var url = $osf.apiV2Url('users/me/nodes/', { query : { 'embed': 'contributors', 'page[size]': 100}});
        var promise = m.request({method: 'GET', url : url, config : xhrconfig});
        promise.then(function(result){
            result.data.forEach(function(node){
                self.nodes.push(node);
            });
            self.nodes.sort(function(a,b){
                var A = a.attributes.date_modified;
                var B = b.attributes.date_modified;
                return (A > B) ? -1 : (A < B) ? 1 : 0;
            });
            self.displayedNodes = self.nodes.splice(0, 10)
        });

        // Load last login
        self.getLastLoginDate = function () {
            var url = $osf.apiV2Url('users/me/', {});
            var promise = m.request({method: 'GET', url: url, config : xhrconfig});
            promise.then(function(result) {
                self.lastLogin = result.data.attributes.last_login
            }
            );
            return promise
        };

        self.getFamilyName = function(i, node) {
            return node.embeds.contributors.data[i].embeds.users.data.attributes.family_name
        };
        self.getContributors = function (node) {
            var numContributors = node.embeds.contributors.links.meta.total;
            if (numContributors === 1) {
                return self.getFamilyName(0, node)
            }
            else if (numContributors == 2) {
                return self.getFamilyName(0, node) + ' and ' +
                        self.getFamilyName(1, node)
            }
            else {
                return self.getFamilyName(0, node) + ', ' +
                        self.getFamilyName(1, node) + ', ' +
                        self.getFamilyName(2, node) + ' + ' + (numContributors - 3)
            }

        };

        self.getRecentComments = function (node) {
            var url = $osf.apiV2Url('nodes/' + node.id + '/comments/',
                { query : { 'filter[date_modified][gte]': self.lastLogin}}
            );
            var promise = m.request({method: 'GET', url : url, config: xhrconfig});
            promise.then(function(result) {
                self.commentsCount[node.id] = result.links.meta.total
            });
            return promise
        };

        self.loadRecentCommentCount = function (node) {
            if (node.id in self.commentsCount) {
                return self.commentsCount[node.id]
            }
            else {
                self.getRecentComments(node);
                return self.commentsCount[node.id]
            }
        };

        self.getRecentLogs = function (node) {
            var url = $osf.apiV2Url('nodes/' + node.id + '/logs/', { query : {'filter[action][ne]': 'comment_added',
                'filter[date][gte]': self.lastLogin}});
            var promise = m.request({method: 'GET', url : url, config: xhrconfig});
            promise.then(function(result){
                self.logsCount[node.id] = result.links.meta.total
            });
            return promise
        };

        self.loadRecentLogsCount = function(node) {
            if (node.id in self.logsCount){
                return self.logsCount[node.id]
            }
            else {
                self.getRecentLogs(node);
                return self.logsCount[node.id]
          }
        };

        self.loadUpToTen = function () {
            requested = self.nodes.splice(0, 10);
            for (i = 0; i < requested.length; i++) {
                self.displayedNodes.push(requested[i])
            }
            return self.displayedNodes
        };

        self.formatDate = function (node) {
            return new $osf.FormattableDate(node.attributes.date_modified).local
        };

        self.restoreFullNodeList = function () {
            for (i = 0; i < self.displayedNodes.length ; i++) {
                self.nodes.push(self.displayedNodes[i])
            }
        };

        self.sortAlphabeticalAscending = function () {
            numDisplayed = self.displayedNodes.length;
            self.restoreFullNodeList();
            self.nodes.sort(function(a,b){
                var A = a.attributes.title.toUpperCase();
                var B = b.attributes.title.toUpperCase();
                return (A < B) ? -1 : (A > B) ? 1 : 0;
            });
            self.displayedNodes = self.nodes.splice(0, numDisplayed);
            return self.displayedNodes
        };

        self.sortAlphabeticalDescending = function () {
            numDisplayed = self.displayedNodes.length;
            self.restoreFullNodeList();
            self.nodes.sort(function(a,b){
                var A = a.attributes.title.toUpperCase();
                var B = b.attributes.title.toUpperCase();
                return (A > B) ? -1 : (A < B) ? 1 : 0;
            });
            self.displayedNodes = self.nodes.splice(0, numDisplayed);
            return self.displayedNodes

        };

        self.sortDateAscending = function () {
            numDisplayed = self.displayedNodes.length;
            self.restoreFullNodeList();
            self.nodes.sort(function(a,b){
                var A = a.attributes.date_modified;
                var B = b.attributes.date_modified;
                return (A > B) ? -1 : (A < B) ? 1 : 0;
            });
            self.displayedNodes = self.nodes.splice(0, numDisplayed);
            return self.displayedNodes
        };

        self.sortDateDescending = function () {
            numDisplayed = self.displayedNodes.length;
            self.restoreFullNodeList();
            self.nodes.sort(function(a,b){
                var A = a.attributes.date_modified;
                var B = b.attributes.date_modified;
                return (A < B) ? -1 : (A > B) ? 1 : 0;
            });
            self.displayedNodes = self.nodes.splice(0, numDisplayed);
            return self.displayedNodes
        };

        //self.getLastLoginDate()

    },
    view : function(ctrl) {
        function projectView(project) {
            return m('tr', [
                m('td', m("a", {href: '/'+ project.id}, project.attributes.title)),
                m('td', ctrl.getContributors(project)),
                m('td', ctrl.formatDate(project)),
                m('td', ctrl.loadRecentCommentCount(project)),
                m('td', ctrl.loadRecentLogsCount(project))
            ])
        }

        function loadMoreButton() {
            if (ctrl.nodes.length !== 0){
                return m('button', { onclick: function() {
                    ctrl.loadUpToTen() }
                }, 'Load more')
            }
        }

        return m('div', [
            m('input[type=search]', 'Quick search projects'),
            m('div', {'class': 'container-fluid'},
                m('table', [
                    m('tr', [
                        m('th', {class: 'col-md-5'}, 'Name',
                            m('button', {class: 'glyphicon glyphicon-chevron-up', onclick: function() {
                               ctrl.sortAlphabeticalAscending()}}),
                            m('button', {class: 'glyphicon glyphicon-chevron-down', onclick: function() {
                                ctrl.sortAlphabeticalDescending()
                            }})),
                        m('th', {class: 'col-md-3'}, 'Contributors'),
                        m('th', {class: 'col-md-2'}, 'Modified',
                            m('button', {class: 'glyphicon glyphicon-chevron-up', onclick: function() {
                               ctrl.sortDateAscending()}}),
                            m('button', {class: 'glyphicon glyphicon-chevron-down', onclick: function() {
                               ctrl.sortDateDescending()
                           }})
                        ),
                        m('th', {class: 'col-md-1'}, 'New comments'),
                        m('th', {class: 'col-md-1'}, 'New logs')
                    ]),

                    ctrl.displayedNodes.map(function(n){
                        return projectView(n)
                    }),
                    loadMoreButton()
            ])
            )
        ])
    }
};

module.exports = quickSearchProject;

<|endoftext|>


<commit_before>const request = require('request');

function getLocation(location) {
  const givenLocation = location;
  const url = `https://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=${encodeURIComponent(location)}&key=${process.env.GOOGLE_MAPS_KEY}`;
  return new Promise((resolve, reject) => {
    request(url, (err, res, body) => {
      if (err) { console.log(err); } // eslint-disable-line no-console
      const json = JSON.parse(body);
      if (json.results.length === 0) { return reject(`Unable to find location ${givenLocation}`); }
      const lat = json.results[0].geometry.location.lat;
      const lng = json.results[0].geometry.location.lng;
      const formattedAddress = json.results[0].formatted_address;
      console.log(formattedAddress);
      resolve({ lat, lng, location });
    });
  });
}

module.exports = getLocation;
<commit_msg>Use google formatted location<commit_after>const request = require('request');

function getLocation(givenLocation) {
  const url = `https://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=${encodeURIComponent(location)}&key=${process.env.GOOGLE_MAPS_KEY}`;
  return new Promise((resolve, reject) => {
    request(url, (err, res, body) => {
      if (err) { console.log(err); } // eslint-disable-line no-console
      const json = JSON.parse(body);
      if (json.results.length === 0) { return reject(`Unable to find location ${givenLocation}`); }
      const lat = json.results[0].geometry.location.lat;
      const lng = json.results[0].geometry.location.lng;
      const location = json.results[0].formatted_address;
      resolve({ lat, lng, location });
    });
  });
}

module.exports = getLocation;
<|endoftext|>