<commit_before>/* Copyright 2013-2014 Extended Mind Technologies Oy
 *
 * 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.
 */

 /*global angular, getJSONFixture */
'use strict';

function MockItemsBackendService($httpBackend, ItemsService, PersistentStorageService, SynchronizeService,
                                 UISessionService, UserSessionService, UUIDService) {

  function convertModifiedItemsIntoPersistent(modifiedItems){
    var persistentItems = [];
    for (var i=0; i<modifiedItems.length; i++){
      var persistentItem = {
        uuid: UUIDService.isFakeUUID(modifiedItems[i].trans.uuid) ? UUIDService.randomUUID() :
                                                              modifiedItems[i].trans.uuid,
        title: modifiedItems[i].mod.title || modifiedItems[i].trans.title,
        created: modifiedItems[i].trans.created,
        modified: modifiedItems[i].mod.modified || modifiedItems[i].trans.modified
      };
      if (modifiedItems[i].mod.id) persistentItem.id = modifiedItems[i].mod.id;
      else if (modifiedItems[i].trans.id) persistentItem.id = modifiedItems[i].trans.id;

      if (modifiedItems[i].mod.description) persistentItem.description = modifiedItems[i].mod.description;
      else if (modifiedItems[i].trans.description) persistentItem.description = modifiedItems[i].trans.description;

      if (modifiedItems[i].mod.deleted) persistentItem.deleted = modifiedItems[i].mod.deleted;
      else if (modifiedItems[i].trans.deleted) persistentItem.deleted = modifiedItems[i].trans.deleted;

      if (modifiedItems[i].mod.due) persistentItem.due = modifiedItems[i].mod.due;
      else if (modifiedItems[i].trans.due) persistentItem.due = modifiedItems[i].trans.due;

      if (modifiedItems[i].mod.completed) persistentItem.completed = modifiedItems[i].mod.completed;
      else if (modifiedItems[i].trans.completed) persistentItem.completed = modifiedItems[i].trans.completed;

      if (modifiedItems[i].mod.repeating) persistentItem.repeating = modifiedItems[i].mod.repeating;
      else if (modifiedItems[i].trans.repeating) persistentItem.repeating = modifiedItems[i].trans.repeating;

      if (modifiedItems[i].mod.reminders) {
        persistentItem.reminders = JSON.parse(JSON.stringify(modifiedItems[i].mod.reminders));
      }
      else if (modifiedItems[i].trans.reminders) {
        persistentItem.reminders = JSON.parse(JSON.stringify(modifiedItems[i].trans.reminders));
      }

      if (modifiedItems[i].mod.content) persistentItem.content = modifiedItems[i].mod.content;
      else if (modifiedItems[i].trans.content) persistentItem.content = modifiedItems[i].trans.content;

      if (modifiedItems[i].mod.relationships)
        persistentItem.relationships = modifiedItems[i].mod.relationships;
      else if (modifiedItems[i].relationships)
        persistentItem.relationships = modifiedItems[i].relationships;
      persistentItems.push(persistentItem);
    }
    return persistentItems;
  }

  function mockGetItems(expectResponse){
    $httpBackend.whenGET(SynchronizeService.getItemsRegex)
      .respond(function(method, url, data, headers) {
        var i;
        if (url.indexOf('?modified=') != -1){
          var modifiedResponse = {};
          var activeUUID = UISessionService.getActiveUUID();
          // Search values that contain mod from the PersistentStorageService and return them
          var modifiedItems = SynchronizeService.getModifiedItems('item', activeUUID);
          if (modifiedItems && modifiedItems.length){
            modifiedResponse.items = convertModifiedItemsIntoPersistent(modifiedItems);
          }
          var modifiedTasks = SynchronizeService.getModifiedItems('task', activeUUID);
          if (modifiedTasks && modifiedTasks.length){
            modifiedResponse.tasks = convertModifiedItemsIntoPersistent(modifiedTasks);
          }
          var modifiedNotes = SynchronizeService.getModifiedItems('note', activeUUID);
          if (modifiedNotes && modifiedNotes.length){
            modifiedResponse.notes = convertModifiedItemsIntoPersistent(modifiedNotes);
          }
          var modifiedLists = SynchronizeService.getModifiedItems('list', activeUUID);
          if (modifiedLists && modifiedLists.length){
            modifiedResponse.lists = convertModifiedItemsIntoPersistent(modifiedLists);
          }
          var modifiedTags = SynchronizeService.getModifiedItems('tag', activeUUID);
          if (modifiedTags && modifiedTags.length){
            modifiedResponse.tags = convertModifiedItemsIntoPersistent(modifiedTags);
          }
          return expectResponse(method, url, data, headers, modifiedResponse);
        }else if (url.indexOf('?completed=true') != -1){
          var response = {
            'tasks': []
          };
          for(i = 0; i < 100; i++) {
            var referenceDate = new Date();
            if (i < 10 ){
              // First ten are today
            }else if (i < 20){
              // Yesterday
              referenceDate.setDate(referenceDate.getDate()-1);
            }else if (i < 30){
              // Two days ago
              referenceDate.setDate(referenceDate.getDate()-2);
            }else if (i < 40){
              // Week ago
              referenceDate.setDate(referenceDate.getDate()-7);
            }else if (i < 50){
              // Month ago
              referenceDate.setDate(referenceDate.getDate()-31);
            }else if (i < 60){
              // Two months ago
              referenceDate.setDate(referenceDate.getDate()-62);
            }else {
              // Way back
              referenceDate.setDate(referenceDate.getDate()-1000);
            }
            var referenceEpoch = referenceDate.getTime();

            response.tasks.push({
              'uuid': UUIDService.randomUUID(),
              'created': referenceEpoch,
              'modified': referenceEpoch,
              'completed': referenceEpoch + i,
              'title': 'test completed ' + i
            });
          }
          return expectResponse(method, url, data, headers, response);
        }else if (url.indexOf('?archived=true') != -1){
          return expectResponse(method, url, data, headers, {});
        }else if (url.indexOf('?deleted=true') != -1){
          return expectResponse(method, url, data, headers, {});
        }else{
          var authenticateResponse = getJSONFixture('authenticateResponse.json');
          for (var collectiveUUID in authenticateResponse.collectives) {
            if (authenticateResponse.collectives.hasOwnProperty(collectiveUUID)) {
              if (url.indexOf(collectiveUUID) != -1){
                var collectiveItemsResponse = getJSONFixture('collectiveItemsResponse.json');
                return expectResponse(method, url, data, headers, collectiveItemsResponse);
              }
            }
          }

          if (headers.Authorization === 'Basic dG9rZW46VEVTVA=='){
            // Token 'TEST' returned for jp@ext.md
            return expectResponse(method, url, data, headers, {});
          } else if (headers.Authorization === 'Basic dG9rZW46T0ZGTElORQ==') {
            return [404, 'Not found'];
          }
          var itemsResponseData = getJSONFixture('itemsResponse.json');
          if (itemsResponseData.tasks) {
            for (i = 0; i < itemsResponseData.tasks.length; i++) {
              if (itemsResponseData.tasks[i].reminders) {
                for (var j = 0; j < itemsResponseData.tasks[i].reminders.length; j++) {
                  // Set notification 2 hours into future.
                  itemsResponseData.tasks[i].reminders[j].notification = Date.now() + 7200000;
                }
              }
            }
          }
          return expectResponse(method, url, data, headers, itemsResponseData);
        }
      });
  }

  function mockPutNewItem(expectResponse){
    $httpBackend.whenPUT(ItemsService.putNewItemRegex)
      .respond(function(method, url, data, headers) {
        var putNewItemResponse = getJSONFixture('putItemResponse.json');
        putNewItemResponse.created = putNewItemResponse.modified = (new Date()).getTime();
        putNewItemResponse.uuid = UUIDService.randomUUID();
        return expectResponse(method, url, data, headers, putNewItemResponse);
      });
  }

  function mockPutExistingItem(expectResponse){
    $httpBackend.whenPUT(ItemsService.putExistingItemRegex)
      .respond(function(method, url, data, headers) {
        var putExistingItemResponse = getJSONFixture('putExistingItemResponse.json');
        putExistingItemResponse.modified = (new Date()).getTime();
        return expectResponse(method, url, data, headers, putExistingItemResponse);
      });
  }

  function mockDeleteItem(expectResponse){
    $httpBackend.whenDELETE(ItemsService.deleteItemRegex)
      .respond(function(method, url, data, headers) {
        var deleteItemResponse = getJSONFixture('deleteItemResponse.json');
        deleteItemResponse.result.modified = (new Date()).getTime();
        return expectResponse(method, url, data, headers, deleteItemResponse);
      });
  }

  function mockUndeleteItem(expectResponse){
    $httpBackend.whenPOST(ItemsService.undeleteItemRegex)
      .respond(function(method, url, data, headers) {
        var undeleteItemResponse = getJSONFixture('undeleteItemResponse.json');
        undeleteItemResponse.modified = (new Date()).getTime();
        return expectResponse(method, url, data, headers, undeleteItemResponse);
      });
  }

  return {
    mockItemsBackend: function(expectResponse) {
      mockGetItems(expectResponse);
      mockPutNewItem(expectResponse);
      mockPutExistingItem(expectResponse);
      mockDeleteItem(expectResponse);
      mockUndeleteItem(expectResponse);
    }
  };
}

MockItemsBackendService['$inject'] = ['$httpBackend', 'ItemsService', 'PersistentStorageService',
'SynchronizeService', 'UISessionService', 'UserSessionService', 'UUIDService'];
angular.module('em.appTest').factory('MockItemsBackendService', MockItemsBackendService);
<commit_msg>Clear seconds from mock reminder time.<commit_after>/* Copyright 2013-2014 Extended Mind Technologies Oy
 *
 * 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.
 */

 /*global angular, getJSONFixture */
'use strict';

function MockItemsBackendService($httpBackend, ItemsService, PersistentStorageService, SynchronizeService,
                                 UISessionService, UserSessionService, UUIDService) {

  function convertModifiedItemsIntoPersistent(modifiedItems){
    var persistentItems = [];
    for (var i=0; i<modifiedItems.length; i++){
      var persistentItem = {
        uuid: UUIDService.isFakeUUID(modifiedItems[i].trans.uuid) ? UUIDService.randomUUID() :
                                                              modifiedItems[i].trans.uuid,
        title: modifiedItems[i].mod.title || modifiedItems[i].trans.title,
        created: modifiedItems[i].trans.created,
        modified: modifiedItems[i].mod.modified || modifiedItems[i].trans.modified
      };
      if (modifiedItems[i].mod.id) persistentItem.id = modifiedItems[i].mod.id;
      else if (modifiedItems[i].trans.id) persistentItem.id = modifiedItems[i].trans.id;

      if (modifiedItems[i].mod.description) persistentItem.description = modifiedItems[i].mod.description;
      else if (modifiedItems[i].trans.description) persistentItem.description = modifiedItems[i].trans.description;

      if (modifiedItems[i].mod.deleted) persistentItem.deleted = modifiedItems[i].mod.deleted;
      else if (modifiedItems[i].trans.deleted) persistentItem.deleted = modifiedItems[i].trans.deleted;

      if (modifiedItems[i].mod.due) persistentItem.due = modifiedItems[i].mod.due;
      else if (modifiedItems[i].trans.due) persistentItem.due = modifiedItems[i].trans.due;

      if (modifiedItems[i].mod.completed) persistentItem.completed = modifiedItems[i].mod.completed;
      else if (modifiedItems[i].trans.completed) persistentItem.completed = modifiedItems[i].trans.completed;

      if (modifiedItems[i].mod.repeating) persistentItem.repeating = modifiedItems[i].mod.repeating;
      else if (modifiedItems[i].trans.repeating) persistentItem.repeating = modifiedItems[i].trans.repeating;

      if (modifiedItems[i].mod.reminders) {
        persistentItem.reminders = JSON.parse(JSON.stringify(modifiedItems[i].mod.reminders));
      }
      else if (modifiedItems[i].trans.reminders) {
        persistentItem.reminders = JSON.parse(JSON.stringify(modifiedItems[i].trans.reminders));
      }

      if (modifiedItems[i].mod.content) persistentItem.content = modifiedItems[i].mod.content;
      else if (modifiedItems[i].trans.content) persistentItem.content = modifiedItems[i].trans.content;

      if (modifiedItems[i].mod.relationships)
        persistentItem.relationships = modifiedItems[i].mod.relationships;
      else if (modifiedItems[i].relationships)
        persistentItem.relationships = modifiedItems[i].relationships;
      persistentItems.push(persistentItem);
    }
    return persistentItems;
  }

  function mockGetItems(expectResponse){
    $httpBackend.whenGET(SynchronizeService.getItemsRegex)
      .respond(function(method, url, data, headers) {
        var i;
        if (url.indexOf('?modified=') != -1){
          var modifiedResponse = {};
          var activeUUID = UISessionService.getActiveUUID();
          // Search values that contain mod from the PersistentStorageService and return them
          var modifiedItems = SynchronizeService.getModifiedItems('item', activeUUID);
          if (modifiedItems && modifiedItems.length){
            modifiedResponse.items = convertModifiedItemsIntoPersistent(modifiedItems);
          }
          var modifiedTasks = SynchronizeService.getModifiedItems('task', activeUUID);
          if (modifiedTasks && modifiedTasks.length){
            modifiedResponse.tasks = convertModifiedItemsIntoPersistent(modifiedTasks);
          }
          var modifiedNotes = SynchronizeService.getModifiedItems('note', activeUUID);
          if (modifiedNotes && modifiedNotes.length){
            modifiedResponse.notes = convertModifiedItemsIntoPersistent(modifiedNotes);
          }
          var modifiedLists = SynchronizeService.getModifiedItems('list', activeUUID);
          if (modifiedLists && modifiedLists.length){
            modifiedResponse.lists = convertModifiedItemsIntoPersistent(modifiedLists);
          }
          var modifiedTags = SynchronizeService.getModifiedItems('tag', activeUUID);
          if (modifiedTags && modifiedTags.length){
            modifiedResponse.tags = convertModifiedItemsIntoPersistent(modifiedTags);
          }
          return expectResponse(method, url, data, headers, modifiedResponse);
        }else if (url.indexOf('?completed=true') != -1){
          var response = {
            'tasks': []
          };
          for(i = 0; i < 100; i++) {
            var referenceDate = new Date();
            if (i < 10 ){
              // First ten are today
            }else if (i < 20){
              // Yesterday
              referenceDate.setDate(referenceDate.getDate()-1);
            }else if (i < 30){
              // Two days ago
              referenceDate.setDate(referenceDate.getDate()-2);
            }else if (i < 40){
              // Week ago
              referenceDate.setDate(referenceDate.getDate()-7);
            }else if (i < 50){
              // Month ago
              referenceDate.setDate(referenceDate.getDate()-31);
            }else if (i < 60){
              // Two months ago
              referenceDate.setDate(referenceDate.getDate()-62);
            }else {
              // Way back
              referenceDate.setDate(referenceDate.getDate()-1000);
            }
            var referenceEpoch = referenceDate.getTime();

            response.tasks.push({
              'uuid': UUIDService.randomUUID(),
              'created': referenceEpoch,
              'modified': referenceEpoch,
              'completed': referenceEpoch + i,
              'title': 'test completed ' + i
            });
          }
          return expectResponse(method, url, data, headers, response);
        }else if (url.indexOf('?archived=true') != -1){
          return expectResponse(method, url, data, headers, {});
        }else if (url.indexOf('?deleted=true') != -1){
          return expectResponse(method, url, data, headers, {});
        }else{
          var authenticateResponse = getJSONFixture('authenticateResponse.json');
          for (var collectiveUUID in authenticateResponse.collectives) {
            if (authenticateResponse.collectives.hasOwnProperty(collectiveUUID)) {
              if (url.indexOf(collectiveUUID) != -1){
                var collectiveItemsResponse = getJSONFixture('collectiveItemsResponse.json');
                return expectResponse(method, url, data, headers, collectiveItemsResponse);
              }
            }
          }

          if (headers.Authorization === 'Basic dG9rZW46VEVTVA=='){
            // Token 'TEST' returned for jp@ext.md
            return expectResponse(method, url, data, headers, {});
          } else if (headers.Authorization === 'Basic dG9rZW46T0ZGTElORQ==') {
            return [404, 'Not found'];
          }
          var itemsResponseData = getJSONFixture('itemsResponse.json');
          if (itemsResponseData.tasks) {
            var twoHoursInFuture = new Date();
            twoHoursInFuture.setHours(twoHoursInFuture.getHours() + 2,
                                      twoHoursInFuture.getMinutes() + 2,
                                      0, 0);
            twoHoursInFuture = twoHoursInFuture.getTime();
            for (i = 0; i < itemsResponseData.tasks.length; i++) {
              if (itemsResponseData.tasks[i].reminders) {
                for (var j = 0; j < itemsResponseData.tasks[i].reminders.length; j++) {
                  // Set notification 2 hours into future.
                  itemsResponseData.tasks[i].reminders[j].notification = twoHoursInFuture;
                }
              }
            }
          }
          return expectResponse(method, url, data, headers, itemsResponseData);
        }
      });
  }

  function mockPutNewItem(expectResponse){
    $httpBackend.whenPUT(ItemsService.putNewItemRegex)
      .respond(function(method, url, data, headers) {
        var putNewItemResponse = getJSONFixture('putItemResponse.json');
        putNewItemResponse.created = putNewItemResponse.modified = (new Date()).getTime();
        putNewItemResponse.uuid = UUIDService.randomUUID();
        return expectResponse(method, url, data, headers, putNewItemResponse);
      });
  }

  function mockPutExistingItem(expectResponse){
    $httpBackend.whenPUT(ItemsService.putExistingItemRegex)
      .respond(function(method, url, data, headers) {
        var putExistingItemResponse = getJSONFixture('putExistingItemResponse.json');
        putExistingItemResponse.modified = (new Date()).getTime();
        return expectResponse(method, url, data, headers, putExistingItemResponse);
      });
  }

  function mockDeleteItem(expectResponse){
    $httpBackend.whenDELETE(ItemsService.deleteItemRegex)
      .respond(function(method, url, data, headers) {
        var deleteItemResponse = getJSONFixture('deleteItemResponse.json');
        deleteItemResponse.result.modified = (new Date()).getTime();
        return expectResponse(method, url, data, headers, deleteItemResponse);
      });
  }

  function mockUndeleteItem(expectResponse){
    $httpBackend.whenPOST(ItemsService.undeleteItemRegex)
      .respond(function(method, url, data, headers) {
        var undeleteItemResponse = getJSONFixture('undeleteItemResponse.json');
        undeleteItemResponse.modified = (new Date()).getTime();
        return expectResponse(method, url, data, headers, undeleteItemResponse);
      });
  }

  return {
    mockItemsBackend: function(expectResponse) {
      mockGetItems(expectResponse);
      mockPutNewItem(expectResponse);
      mockPutExistingItem(expectResponse);
      mockDeleteItem(expectResponse);
      mockUndeleteItem(expectResponse);
    }
  };
}

MockItemsBackendService['$inject'] = ['$httpBackend', 'ItemsService', 'PersistentStorageService',
'SynchronizeService', 'UISessionService', 'UserSessionService', 'UUIDService'];
angular.module('em.appTest').factory('MockItemsBackendService', MockItemsBackendService);
<|endoftext|>


<commit_before>(function () {
  'use strict';
  angular
    .module('fusionSeedApp.services.config', [])

    /** Default config options **/
    .constant('CONFIG_DEFAULT', {
      host: 'http://localhost',
      port: '8764',
      connection_realm: 'native',
      anonymous_access: {
        username: '',
        password: ''
      },
      // change default for fusion 2.3
      use_proxy: true,
      collection: 'MyCollection',
      query_debug: false,
      query_pipeline_id: 'default',
      query_profile_id: 'default',
      use_query_profile: true,
      search_app_title: 'Fusion Seed App',
      head_field: 'title',
      subhead_field: 'subtitle',
      description_field: 'description',
      head_url_field: 'url',
      image_field: 'image',
      fields_to_display: [],
      field_display_labels: {},
      sort_fields: [],
      signal_type: 'click',
      signals_pipeline: '_signals_ingest',
      signals_document_id: 'id',
      facets: [],
      typeahead_use_query_profile: true,
      typeahead_query_pipeline_id: 'default',
      typeahead_query_profile_id: 'default',
      typeahead_fields: ['id'],
      typeahead_requesthandler: 'select',
      landing_page_redirect: true
    })
    /** Config overrides from FUSION_CONFIG.js **/
    .constant('CONFIG_OVERRIDE', window.appConfig) //eslint-disable-line

    .provider('ConfigService', ConfigService);

  /**
   * ConfigService
   *
   * @param {object} CONFIG_DEFAULT  [description]
   * @param {object} CONFIG_OVERRIDE [description]
   */
  function ConfigService(CONFIG_DEFAULT, CONFIG_OVERRIDE) {
    'ngInject';
    var appConfig,
      vm = this;

    vm.$get = $get;
    vm.getFusionUrl = getFusionUrl;

    /* initialize on first load */
    init();

    /////////////

    /**
     * Main Service function.
     */
    function $get() {
      'ngInject';

      return {
        init: init, //TODO: Only for test env
        config: appConfig,
        getFusionUrl: getFusionUrl,
        getQueryProfile: getQueryProfile,
        getCollectionName: getCollectionName,
        getQueryPipeline: getQueryPipeline,
        getLoginCredentials: getLoginCredentials,
        getIfQueryProfile: getIfQueryProfile,
        getFieldLabels: getFieldLabels,
        getFieldsToDisplay: getFieldsToDisplay,
        getTypeaheadConfig: getTypeaheadConfig,
        getTypeaheadRequestHandler: getTypeaheadRequestHandler,
        getTypeaheadField: getTypeaheadField,
        getTypeaheadProfile: getTypeaheadProfile,
        getTypeaheadPipeline: getTypeaheadPipeline,
        getLandingPageRedirect: getLandingPageRedirect,
        getFields: {
          all: getAllFields,
          get: getSpecificField
        }
      };
    }

    /**
     * Extend config with the defaults
     */
    function init() {
      // Set local override based on arguements passed in.
      var localOverride = (arguments.length > 0) ? arguments[0] : {};

      appConfig = _.assign({}, CONFIG_DEFAULT, CONFIG_OVERRIDE, localOverride);
      vm.config = appConfig;
    }

    function getIfQueryProfile() {
      return appConfig.use_query_profile;
    }

    /**
     * Returns a fusion URL complete w/ endslash.
     */
    function getFusionUrl() {
      return appConfig.host + ':' + appConfig.port + '/';
    }

    function getQueryPipeline() {
      return appConfig.query_pipeline_id[0];
    }

    function getQueryProfile() {
      return appConfig.query_profile_id[0];
    }

    function getLoginCredentials() {
      return {
        username: appConfig.user,
        passowrd: appConfig.password
      };
    }

    function getLandingPageRedirect(){
      return appConfig.landing_page_redirect;
    }

    function getCollectionName() {
      return appConfig.collection;
    }

    /**
     * @return {object}
     *
     * Returns all the config properties that
     * ends with a `_field` which is not a blank string
     * and is toggled by explicit enable-ment by `_enabled` of the same type
     */
    function getAllFields() {
      var fieldsMap = {};
      _.keys(appConfig)
        .filter(function (item) {
          return item.match(/\_field$/);
        })
        .filter(function (item) {
          return _.trim(appConfig[item]) !== '';
        })
        .forEach(function (keyName) {
          fieldsMap[keyName] = appConfig[keyName];
        });
      return fieldsMap;
    }

    /**
     * Returns specific field of given type.
     * @param  {string} fieldType The type of field that needs to be fetch from the config
     * @return {*|null}           The value of the said field or null if not found.
     */
    function getSpecificField(fieldType) {
      var allFields = getAllFields();
      if (!fieldType.match(/\_field$/)) {
        fieldType += '_field';
      }
      return allFields[fieldType] ? allFields[fieldType] : null;
    }

    function getTypeaheadConfig(){
      var onlyTypeAheadKeys = _.chain(appConfig).keys(appConfig).filter(function(item){
        return item.match(/^typeahead/);
      }).value();
      return _.pick(appConfig, onlyTypeAheadKeys);
    }

    function getTypeaheadPipeline(){
      return appConfig.typeahead_query_pipeline_id[0];
    }

    function getTypeaheadProfile(){
      return appConfig.typeahead_query_profile_id[0];
    }

    function getTypeaheadRequestHandler(){
      return appConfig.typeahead_requesthandler;
    }

    function getTypeaheadField(){
      return appConfig.typeahead_fields[0];
    }

    function getFieldsToDisplay() {
      return appConfig.fields_to_display;
    }

    function getFieldLabels() {
      return appConfig.field_display_labels;
    }
  }
})();
<commit_msg>cleanup from last commit<commit_after>(function () {
  'use strict';
  angular
    .module('fusionSeedApp.services.config', [])

    /** Default config options **/
    .constant('CONFIG_DEFAULT', {
      host: 'http://localhost',
      port: '8764',
      connection_realm: 'native',
      anonymous_access: {
        username: '',
        password: ''
      },
      // change default for fusion 2.3
      use_proxy: true,
      collection: 'MyCollection',
      query_debug: false,
      query_pipeline_id: 'default',
      query_profile_id: 'default',
      use_query_profile: true,
      search_app_title: 'Fusion Seed App',
      head_field: 'title',
      subhead_field: 'subtitle',
      description_field: 'description',
      head_url_field: 'url',
      image_field: 'image',
      fields_to_display: [],
      field_display_labels: {},
      sort_fields: [],
      signal_type: 'click',
      signals_pipeline: '_signals_ingest',
      signals_document_id: 'id',
      facets: [],
      typeahead_use_query_profile: true,
      typeahead_query_pipeline_id: 'default',
      typeahead_query_profile_id: 'default',
      typeahead_fields: ['id'],
      typeahead_requesthandler: 'select',
      landing_page_redirect: true
    })
    /** Config overrides from FUSION_CONFIG.js **/
    .constant('CONFIG_OVERRIDE', window.appConfig) //eslint-disable-line

    .provider('ConfigService', ConfigService);

  /**
   * ConfigService
   *
   * @param {object} CONFIG_DEFAULT  [description]
   * @param {object} CONFIG_OVERRIDE [description]
   */
  function ConfigService(CONFIG_DEFAULT, CONFIG_OVERRIDE) {
    'ngInject';
    var appConfig,
      vm = this;

    vm.$get = $get;
    vm.getFusionUrl = getFusionUrl;

    /* initialize on first load */
    init();

    /////////////

    /**
     * Main Service function.
     */
    function $get() {
      'ngInject';

      return {
        init: init, //TODO: Only for test env
        config: appConfig,
        getFusionUrl: getFusionUrl,
        getQueryProfile: getQueryProfile,
        getCollectionName: getCollectionName,
        getQueryPipeline: getQueryPipeline,
        getLoginCredentials: getLoginCredentials,
        getIfQueryProfile: getIfQueryProfile,
        getFieldLabels: getFieldLabels,
        getFieldsToDisplay: getFieldsToDisplay,
        getTypeaheadConfig: getTypeaheadConfig,
        getTypeaheadRequestHandler: getTypeaheadRequestHandler,
        getTypeaheadField: getTypeaheadField,
        getTypeaheadProfile: getTypeaheadProfile,
        getTypeaheadPipeline: getTypeaheadPipeline,
        getLandingPageRedirect: getLandingPageRedirect,
        getFields: {
          all: getAllFields,
          get: getSpecificField
        }
      };
    }

    /**
     * Extend config with the defaults
     */
    function init() {
      // Set local override based on arguements passed in.
      var localOverride = (arguments.length > 0) ? arguments[0] : {};

      appConfig = _.assign({}, CONFIG_DEFAULT, CONFIG_OVERRIDE, localOverride);
      vm.config = appConfig;
    }

    function getIfQueryProfile() {
      return appConfig.use_query_profile;
    }

    /**
     * Returns a fusion URL complete w/ endslash.
     */
    function getFusionUrl() {
      return appConfig.host + ':' + appConfig.port + '/';
    }

    function getQueryPipeline() {
      return appConfig.query_pipeline_id;
    }

    function getQueryProfile() {
      return appConfig.query_profile_id;
    }

    function getLoginCredentials() {
      return {
        username: appConfig.user,
        passowrd: appConfig.password
      };
    }

    function getLandingPageRedirect(){
      return appConfig.landing_page_redirect;
    }

    function getCollectionName() {
      return appConfig.collection;
    }

    /**
     * @return {object}
     *
     * Returns all the config properties that
     * ends with a `_field` which is not a blank string
     * and is toggled by explicit enable-ment by `_enabled` of the same type
     */
    function getAllFields() {
      var fieldsMap = {};
      _.keys(appConfig)
        .filter(function (item) {
          return item.match(/\_field$/);
        })
        .filter(function (item) {
          return _.trim(appConfig[item]) !== '';
        })
        .forEach(function (keyName) {
          fieldsMap[keyName] = appConfig[keyName];
        });
      return fieldsMap;
    }

    /**
     * Returns specific field of given type.
     * @param  {string} fieldType The type of field that needs to be fetch from the config
     * @return {*|null}           The value of the said field or null if not found.
     */
    function getSpecificField(fieldType) {
      var allFields = getAllFields();
      if (!fieldType.match(/\_field$/)) {
        fieldType += '_field';
      }
      return allFields[fieldType] ? allFields[fieldType] : null;
    }

    function getTypeaheadConfig(){
      var onlyTypeAheadKeys = _.chain(appConfig).keys(appConfig).filter(function(item){
        return item.match(/^typeahead/);
      }).value();
      return _.pick(appConfig, onlyTypeAheadKeys);
    }

    function getTypeaheadPipeline(){
      return appConfig.typeahead_query_pipeline_id;
    }

    function getTypeaheadProfile(){
      return appConfig.typeahead_query_profile_id;
    }

    function getTypeaheadRequestHandler(){
      return appConfig.typeahead_requesthandler;
    }

    function getTypeaheadField(){
      return appConfig.typeahead_fields[0];
    }

    function getFieldsToDisplay() {
      return appConfig.fields_to_display;
    }

    function getFieldLabels() {
      return appConfig.field_display_labels;
    }
  }
})();
<|endoftext|>


<commit_before>/**
 * @constructor
 */
function ModelListManager(data) {
  this.data = data;
  this.meshes = {};
  this.materials = {};
}

/**
 * This is a helper to allow a ModelListManager to be used by the DataManager.
 * @param path
 * @param callback
 */
ModelListManager.load = function(path, callback) {
  ModelList.load(path, function(data) {
    callback(new ModelListManager(data));
  });
};

ModelListManager.prototype._createMesh = function(meshIdx, callback) {
  var existingMesh = this.meshes[meshIdx];
  if (existingMesh) {
    if (existingMesh.mesh) {
      callback(existingMesh.mesh);
    } else {
      existingMesh.waiters.push(callback);
    }
    return;
  }

  var newMesh = {
    mesh: null,
    waiters: [callback]
  };
  this.meshes[meshIdx] = newMesh;

  var meshPath = this.data.meshes[meshIdx];
  Mesh.load(meshPath, function (geometry) {
    newMesh.mesh = geometry;
    for (var i = 0; i < newMesh.waiters.length; ++i) {
      newMesh.waiters[i](geometry);
    }
    newMesh.waiters = [];
  });
};

ModelListManager.prototype._createMaterialLMOnly = function(materialIdx, lmData) {
  var zscMat = this.data.materials[materialIdx];

  var lmTexture = lmData.texture;
  var objScale = 1 / lmData.objectsPerRow;
  var rowNum = Math.floor(lmData.objectIndex / lmData.objectsPerRow);
  var colNum = lmData.objectIndex % lmData.objectsPerRow;

  var newMaterial = ShaderManager.get('staticobj_lmonly').clone();
  newMaterial.uniforms = {
    texture1: { type: 't', value: lmTexture },
    vLmOffset: { type: 'v2', value: new THREE.Vector2(colNum*objScale, rowNum*objScale) },
    vLmScale: { type: 'v2', value: new THREE.Vector2(objScale, objScale) }
  };

  if (zscMat.twoSided) {
    newMaterial.side = THREE.DoubleSide;
  }
  newMaterial.opacity = zscMat.alpha;
  newMaterial.depthTest = zscMat.depthTestEnabled;
  newMaterial.depthWrite = zscMat.depthWriteEnabled;

  return newMaterial;
};

ModelListManager.prototype._createMaterialWithLightmap = function(materialIdx, lmData) {
  var zscMat = this.data.materials[materialIdx];
  var texture = TextureManager.load(zscMat.texturePath);

  var lmTexture = lmData.texture;
  var objScale = 1 / lmData.objectsPerRow;
  var rowNum = Math.floor(lmData.objectIndex / lmData.objectsPerRow);
  var colNum = lmData.objectIndex % lmData.objectsPerRow;

  var newMaterial = ShaderManager.get('staticobj').clone();
  newMaterial.uniforms = {
    texture1: { type: 't', value: texture },
    texture2: { type: 't', value: lmTexture },
    vLmOffset: { type: 'v2', value: new THREE.Vector2(colNum*objScale, rowNum*objScale) },
    vLmScale: { type: 'v2', value: new THREE.Vector2(objScale, objScale) }
  };

  if (zscMat.twoSided) {
    newMaterial.side = THREE.DoubleSide;
  }
  if (zscMat.alphaEnabled) {
    newMaterial.transparent = true;
  }
  if (zscMat.alphaTestEnabled) {
    newMaterial.alphaTest = zscMat.alphaRef / 256;
  } else {
    newMaterial.alphaTest = 0;
  }
  newMaterial.opacity = zscMat.alpha;
  newMaterial.depthTest = zscMat.depthTestEnabled;
  newMaterial.depthWrite = zscMat.depthWriteEnabled;

  return newMaterial;
};

ModelListManager.prototype._createMaterial = function(materialIdx) {
  var foundMaterial = this.materials[materialIdx];
  if (foundMaterial) {
    return foundMaterial;
  }

  var zscMat = this.data.materials[materialIdx];

  var texture = TextureManager.load(zscMat.texturePath);

  var newMaterial = new THREE.MeshLambertMaterial({color: 0xffffff, map: texture});
  newMaterial.skinning = zscMat.forSkinning;
  if (zscMat.twoSided) {
    newMaterial.side = THREE.DoubleSide;
  }

  // TEMPORARY HACK
  if (!zscMat.useSpecular) {
    if (zscMat.alphaEnabled) {
      newMaterial.transparent = true;
    }
    if (zscMat.alphaTestEnabled) {
      newMaterial.alphaTest = zscMat.alphaRef / 255;
    } else {
      newMaterial.alphaTest = 0;
    }
  }

  newMaterial.opacity = zscMat.alpha;
  newMaterial.depthTest = zscMat.depthTestEnabled;
  newMaterial.depthWrite = zscMat.depthWriteEnabled;

  this.materials[materialIdx] = newMaterial;
  return newMaterial;
};

ModelListManager.prototype.createForStatic = function(modelIdx, lightmap, lmIdx, callback) {
  var model = this.data.models[modelIdx];

  var modelObj = new THREE.Object3D();
  modelObj.visible = false;

  var partMeshs = [];
  var waitAll = new MultiWait();

  var self = this;
  for (var i = 0; i < model.parts.length; ++i) {
    (function(partIdx, part, partCallback) {
      var lmData = null;
      if (lightmap) {
        lmData = lightmap.getDataForPart(lmIdx, i);
      }
      var material = null;

      if (!lmData) {
        material = self._createMaterial(part.materialIdx);
      } else if (!config.lmonly) {
        material = self._createMaterialWithLightmap(part.materialIdx, lmData);
      } else {
        material = self._createMaterialLMOnly(part.materialIdx, lmData);
      }
      self._createMesh(part.meshIdx, function(geometry) {
        var partMesh = new THREE.Mesh(geometry, material);
        partMesh.collisionMode = part.collisionMode;
        partMeshs[partIdx] = partMesh;

        if (part.position) {
          partMesh.position.copy(part.position);
        }

        if (part.rotation) {
          partMesh.quaternion.copy(part.rotation);
        }

        if (part.scale) {
          partMesh.scale.copy(part.scale);
        }

        if (part.animPath) {
          AnimationData.load(part.animPath, function(zmoData) {
            var anim = new ObjectAnimator(partMeshs[partIdx], zmoData);
            anim.play();
          });
        }

        partCallback();
      });
    })(i, model.parts[i], waitAll.one());
  }

  waitAll.wait(function() {
    for (var i = 0; i < model.effects.length; ++i) {
      var effectData = model.effects[i];
      if (effectData.effectIdx < 0 || effectData.effectIdx > self.data.effects.length) {
        console.log('Warning, model effect had invalid effectIdx ' + effectData.effectIdx);
        continue;
      }
      /* types are:
      POINT_EFFECT_NORMAL = 0,
       POINT_EFFECT_DAYNNIGHT = 1,
       POINT_LIGHT_CONTAINER = 2,
      */
      var effectPath = self.data.effects[effectData.effectIdx];
      EffectManager.loadEffect(effectPath, function(effect) {
        if (effect) {
          effect.rootObj.position.copy(effectData.position);
          effect.rootObj.quaternion.copy(effectData.rotation);
          effect.rootObj.scale.copy(effectData.scale);
          effect.rootObj.collisionMode = ModelList.Model.Part.COLLISION_MODE.NONE;
          if (effectData.parent === 0) {
            modelObj.add(effect.rootObj);
          } else {
            partMeshs[effectData.parent - 1].add(effect.rootObj);
          }
          effect.play();
        }
      });
    }

    for (var i = 0; i < partMeshs.length; ++i) {
      var part = model.parts[i];

      if (i === 0) {
        modelObj.add(partMeshs[i]);
      } else {
        partMeshs[part.parent-1].add(partMeshs[i]);
      }

    }
    modelObj.visible = true;
    if (callback) {
      callback();
    }
  });

  return modelObj;
};

module.exports = ModelListManager;
<commit_msg>Fix material alpha test.<commit_after>/**
 * @constructor
 */
function ModelListManager(data) {
  this.data = data;
  this.meshes = {};
  this.materials = {};
}

/**
 * This is a helper to allow a ModelListManager to be used by the DataManager.
 * @param path
 * @param callback
 */
ModelListManager.load = function(path, callback) {
  ModelList.load(path, function(data) {
    callback(new ModelListManager(data));
  });
};

ModelListManager.prototype._createMesh = function(meshIdx, callback) {
  var existingMesh = this.meshes[meshIdx];
  if (existingMesh) {
    if (existingMesh.mesh) {
      callback(existingMesh.mesh);
    } else {
      existingMesh.waiters.push(callback);
    }
    return;
  }

  var newMesh = {
    mesh: null,
    waiters: [callback]
  };
  this.meshes[meshIdx] = newMesh;

  var meshPath = this.data.meshes[meshIdx];
  Mesh.load(meshPath, function (geometry) {
    newMesh.mesh = geometry;
    for (var i = 0; i < newMesh.waiters.length; ++i) {
      newMesh.waiters[i](geometry);
    }
    newMesh.waiters = [];
  });
};

ModelListManager.prototype._createMaterialLMOnly = function(materialIdx, lmData) {
  var zscMat = this.data.materials[materialIdx];

  var lmTexture = lmData.texture;
  var objScale = 1 / lmData.objectsPerRow;
  var rowNum = Math.floor(lmData.objectIndex / lmData.objectsPerRow);
  var colNum = lmData.objectIndex % lmData.objectsPerRow;

  var newMaterial = ShaderManager.get('staticobj_lmonly').clone();
  newMaterial.uniforms = {
    texture1: { type: 't', value: lmTexture },
    vLmOffset: { type: 'v2', value: new THREE.Vector2(colNum*objScale, rowNum*objScale) },
    vLmScale: { type: 'v2', value: new THREE.Vector2(objScale, objScale) }
  };

  if (zscMat.twoSided) {
    newMaterial.side = THREE.DoubleSide;
  }

  newMaterial.opacity = zscMat.alpha;
  newMaterial.depthTest = zscMat.depthTestEnabled;
  newMaterial.depthWrite = zscMat.depthWriteEnabled;

  return newMaterial;
};

ModelListManager.prototype._createMaterialWithLightmap = function(materialIdx, lmData) {
  var zscMat = this.data.materials[materialIdx];
  var texture = TextureManager.load(zscMat.texturePath);

  var lmTexture = lmData.texture;
  var objScale = 1 / lmData.objectsPerRow;
  var rowNum = Math.floor(lmData.objectIndex / lmData.objectsPerRow);
  var colNum = lmData.objectIndex % lmData.objectsPerRow;

  var newMaterial = ShaderManager.get('staticobj').clone();
  newMaterial.uniforms = {
    texture1: { type: 't', value: texture },
    texture2: { type: 't', value: lmTexture },
    vLmOffset: { type: 'v2', value: new THREE.Vector2(colNum*objScale, rowNum*objScale) },
    vLmScale: { type: 'v2', value: new THREE.Vector2(objScale, objScale) }
  };

  if (zscMat.twoSided) {
    newMaterial.side = THREE.DoubleSide;
  }

  if (zscMat.alphaEnabled) {
    newMaterial.transparent = true;

    if (zscMat.alphaTestEnabled) {
      newMaterial.alphaTest = zscMat.alphaRef / 256;
    }
  }

  newMaterial.opacity = zscMat.alpha;
  newMaterial.depthTest = zscMat.depthTestEnabled;
  newMaterial.depthWrite = zscMat.depthWriteEnabled;

  return newMaterial;
};

ModelListManager.prototype._createMaterial = function(materialIdx) {
  var foundMaterial = this.materials[materialIdx];
  if (foundMaterial) {
    return foundMaterial;
  }

  var zscMat = this.data.materials[materialIdx];

  var texture = TextureManager.load(zscMat.texturePath);

  var newMaterial = new THREE.MeshLambertMaterial({color: 0xffffff, map: texture});
  newMaterial.skinning = zscMat.forSkinning;

  if (zscMat.twoSided) {
    newMaterial.side = THREE.DoubleSide;
  }

  if (zscMat.alphaEnabled) {
    newMaterial.transparent = true;

    if (zscMat.alphaTestEnabled) {
      newMaterial.alphaTest = zscMat.alphaRef / 255;
    }
  }

  newMaterial.opacity = zscMat.alpha;
  newMaterial.depthTest = zscMat.depthTestEnabled;
  newMaterial.depthWrite = zscMat.depthWriteEnabled;

  this.materials[materialIdx] = newMaterial;
  return newMaterial;
};

ModelListManager.prototype.createForStatic = function(modelIdx, lightmap, lmIdx, callback) {
  var model = this.data.models[modelIdx];

  var modelObj = new THREE.Object3D();
  modelObj.visible = false;

  var partMeshs = [];
  var waitAll = new MultiWait();

  var self = this;
  for (var i = 0; i < model.parts.length; ++i) {
    (function(partIdx, part, partCallback) {
      var lmData = null;
      if (lightmap) {
        lmData = lightmap.getDataForPart(lmIdx, i);
      }
      var material = null;

      if (!lmData) {
        material = self._createMaterial(part.materialIdx);
      } else if (!config.lmonly) {
        material = self._createMaterialWithLightmap(part.materialIdx, lmData);
      } else {
        material = self._createMaterialLMOnly(part.materialIdx, lmData);
      }
      self._createMesh(part.meshIdx, function(geometry) {
        var partMesh = new THREE.Mesh(geometry, material);
        partMesh.collisionMode = part.collisionMode;
        partMeshs[partIdx] = partMesh;

        if (part.position) {
          partMesh.position.copy(part.position);
        }

        if (part.rotation) {
          partMesh.quaternion.copy(part.rotation);
        }

        if (part.scale) {
          partMesh.scale.copy(part.scale);
        }

        if (part.animPath) {
          AnimationData.load(part.animPath, function(zmoData) {
            var anim = new ObjectAnimator(partMeshs[partIdx], zmoData);
            anim.play();
          });
        }

        partCallback();
      });
    })(i, model.parts[i], waitAll.one());
  }

  waitAll.wait(function() {
    for (var i = 0; i < model.effects.length; ++i) {
      var effectData = model.effects[i];
      if (effectData.effectIdx < 0 || effectData.effectIdx > self.data.effects.length) {
        console.log('Warning, model effect had invalid effectIdx ' + effectData.effectIdx);
        continue;
      }
      /* types are:
      POINT_EFFECT_NORMAL = 0,
       POINT_EFFECT_DAYNNIGHT = 1,
       POINT_LIGHT_CONTAINER = 2,
      */
      var effectPath = self.data.effects[effectData.effectIdx];
      EffectManager.loadEffect(effectPath, function(effect) {
        if (effect) {
          effect.rootObj.position.copy(effectData.position);
          effect.rootObj.quaternion.copy(effectData.rotation);
          effect.rootObj.scale.copy(effectData.scale);
          effect.rootObj.collisionMode = ModelList.Model.Part.COLLISION_MODE.NONE;
          if (effectData.parent === 0) {
            modelObj.add(effect.rootObj);
          } else {
            partMeshs[effectData.parent - 1].add(effect.rootObj);
          }
          effect.play();
        }
      });
    }

    for (var i = 0; i < partMeshs.length; ++i) {
      var part = model.parts[i];

      if (i === 0) {
        modelObj.add(partMeshs[i]);
      } else {
        partMeshs[part.parent-1].add(partMeshs[i]);
      }

    }
    modelObj.visible = true;
    if (callback) {
      callback();
    }
  });

  return modelObj;
};

module.exports = ModelListManager;
<|endoftext|>


<commit_before>import React from 'react'
import injectSheet from 'react-jss'
import { Link } from 'react-router-dom'
import Button from '../components/button'

const noResultsMessage = 'No results match your search.'

const NoResults = ({ classes }) => {
	// todo
	return (

			{noResultsMessage}
			<Link to="/mini-app">
				<Button buttonText="Return to Search" />
			</Link>

	)
}

const styles = {
	noResultsRoot: {
		display: 'flex',
		'justify-content': 'space-between',
		'align-items': 'center',
		color: '#000000',
		'font-family': 'hah-regular',
		'font-size': '33px',
		'line-height': '34px',
		border: '3px solid #3D65F9',
		'border-radius': '2px',
		'background-color': '#FFFFFF',
		margin: '56px',
		padding: '41px 80px 41px 80px', //todo check
	},
}

export default injectSheet(styles)(NoResults)
<commit_msg>Cleanup<commit_after>import React from 'react'
import injectSheet from 'react-jss'
import { Link } from 'react-router-dom'
import Button from '../components/button'

const noResultsMessage = 'No results match your search.'

const NoResults = ({ classes }) => (

		{noResultsMessage}
		<Link to="/mini-app">
			<Button buttonText="Return to Search" />
		</Link>

)

const styles = {
	noResultsRoot: {
		display: 'flex',
		'justify-content': 'space-between',
		'align-items': 'center',
		color: '#000000',
		'font-family': 'hah-regular',
		'font-size': '33px',
		'line-height': '34px',
		border: '3px solid #3D65F9',
		'border-radius': '2px',
		'background-color': '#FFFFFF',
		margin: '56px',
		padding: '41px 80px 41px 80px',
	},
}

export default injectSheet(styles)(NoResults)
<|endoftext|>


<commit_before>
'use strict';

import Immutable from 'immutable';

import { OUTPUT_CHANGED, TESTS_STARTED, TESTS_FINISHED } from '../actions/test';
import { CHALLENGE_NEXT } from '../actions/challenge';
import { TIMER_FINISHED } from '../actions/timer';

const initialState = Immutable.Map({
  userOutput: 'The output of your code will show up here.',
  isRunningTests: false,
  testResults: Immutable.List()
});

export default function test (state = initialState, action) {
  switch (action.type) {
    case CHALLENGE_NEXT:
      return state
        .set('userOutput', 'The output of your code will show up here.')
        .set('testResults', Immutable.List());

    // Nothing seems to call TIMER_FINISHED...
    case TIMER_FINISHED:
      return state.set('testResults', Immutable.List(action.testResults));
    case OUTPUT_CHANGED:
      return state.set('userOutput', action.userOutput);
    case TESTS_STARTED:
      return state.set('isRunningTests', true);
    case TESTS_FINISHED:
      return state
        .set('isRunningTests', false)
        .set('testResults', Immutable.List(action.testResults));
    default:
      return state;
  }
}
<commit_msg>Added CHALLENGE_START to clear the testResults if user starts a new challenge.<commit_after>
'use strict';

import Immutable from 'immutable';

import { OUTPUT_CHANGED, TESTS_STARTED, TESTS_FINISHED } from '../actions/test';
import { CHALLENGE_START, CHALLENGE_NEXT } from '../actions/challenge';
import { TIMER_FINISHED } from '../actions/timer';

const initialState = Immutable.Map({
  userOutput: 'The output of your code will show up here.',
  isRunningTests: false,
  testResults: Immutable.List()
});

export default function test (state = initialState, action) {
  switch (action.type) {
    case CHALLENGE_START:
      return state
        .set('testResults', Immutable.List())
        .set('isRunningTests', false);
    case CHALLENGE_NEXT:
      return state
        .set('userOutput', 'The output of your code will show up here.')
        .set('testResults', Immutable.List());

    // Nothing seems to call TIMER_FINISHED...
    case TIMER_FINISHED:
      return state.set('testResults', Immutable.List(action.testResults));
    case OUTPUT_CHANGED:
      return state.set('userOutput', action.userOutput);
    case TESTS_STARTED:
      return state.set('isRunningTests', true);
    case TESTS_FINISHED:
      return state
        .set('isRunningTests', false)
        .set('testResults', Immutable.List(action.testResults));
    default:
      return state;
  }
}
<|endoftext|>


<commit_before>import ApiRequest from 'api/helpers/apiHelper';

describe('ApiHelper constructor', () => {
  it('builds a basic request', () => {
    const testEmpty = new ApiRequest();

    expect(testEmpty.host).toEqual('localhost');
    expect(testEmpty.port).toEqual(5000);
    expect(testEmpty.headers).toEqual({
      'Content-Type': 'application/vnd.api+json',
    });
  });
});
<commit_msg>Added last tests<commit_after>import faker from 'faker';
import ApiRequest from 'api/helpers/apiHelper';

describe('ApiHelper constructor', () => {
  it('builds a basic request', () => {
    const testEmpty = new ApiRequest();

    expect(testEmpty.host).toEqual('localhost');
    expect(testEmpty.port).toEqual(5000);
    expect(testEmpty.headers).toEqual({
      'Content-Type': 'application/vnd.api+json',
    });
  });

  it('Can chain setter calls', () => {
    const testRequest = new ApiRequest();

    const randomPort = faker.random.number();
    const randomDomain = faker.internet.url();
    const randomBody = faker.lorem.paragraph();
    const randomEndpoint = faker.lorem.word();
    const randomHeaderKey = 'testKey';
    const randomHeaderVal = faker.lorem.word();
    testRequest
      .setPort(randomPort)
      .setHost(randomDomain)
      .setEndpoint(randomEndpoint)
      .setMethod('POST')
      .setBody(randomBody)
      .addHeader(randomHeaderKey, randomHeaderVal);

    expect(testRequest.host).toEqual(randomDomain);
    expect(testRequest.port).toEqual(randomPort);
    expect(testRequest.body).toEqual(JSON.stringify(randomBody));
    expect(testRequest.method).toEqual('POST');
    expect(testRequest.headers).toEqual({
      'Content-Type': 'application/vnd.api+json',
      testKey: randomHeaderVal,
    });
    expect(testRequest.parameters).toEqual({});
  });

  it('Throws Errors if wrong operations are performed', () => {
    const testRequest = new ApiRequest();

    testRequest.setMethod('GET');

    expect(() => testRequest.setBody('body')).toThrowError(
      "Can't add a body to a GET request.",
    );

    expect(() => testRequest.setPort('notANumber')).toThrowError(
      'Port must be an integer (received notANumber instead).',
    );
    expect(() => testRequest.addHeader('Authentication', 'bla')).toThrowError(
      `Invalid header 'Authentication': No need to specify an authentication header, it's included by default.`,
    );

    testRequest.setMethod('POST');
    expect(() => testRequest.addParameter('name', 'val')).toThrowError(
      `Can't add url parameters to a POST request!`,
    );
    expect(() => testRequest.setMethod('wrong')).toThrowError(
      `Invalid request method: 'wrong'. Must be one of ('GET', 'POST', 'PUT', 'PATCH', 'DELETE')`,
    );
  });
});
<|endoftext|>


<commit_before>
import React, {Component}  from 'react';
import Client from '../../clients/Drink';
import Drink from './drink';

const getKey = () => {
  return Math.random().toString(36).substr(2, 10);
}

const defaultDrink = {
  _id : undefined,
  name : '',
  description : '',
  image : '',
  ingredients : [{
    _id: getKey(),
    name : '',
    amount : ''
  }]
}

class DrinksAdmin extends Component {

  state = {
    drinks: [],
    selectedDrink: Object.assign({}, defaultDrink)
  };

  componentWillMount = () => {
    this.updateDrinks();
  }

  updateDrinks = (response) => {
    Client.search('', this.drinksFetched);
  }

  drinksFetched = (drinks) => {
    this.setState({
      drinks,
      selectedDrink : Object.assign({}, defaultDrink)
    });
  }

  saveDrink = (e) => {
    var drink = Object.assign({}, this.state.selectedDrink);
    Client.upsert(drink, this.updateDrinks);
    e.preventDefault();
  }

  selectDrink = (e) => {
    let select = e.target;
    let option = select.selectedOptions[0];
    let potentialDrinks = this.state.drinks.filter(drink => drink._id === option.value);
    let drink = potentialDrinks.length > 0 ? potentialDrinks[0] : defaultDrink;

    this.setState({
      selectedDrink: Object.assign({}, drink)
    });
  }

  changeDrinkField = (e, field) => {
    var value = e.target.value;
    this.setState((prevState, props) => {
      let drink = Object.assign({}, prevState.selectedDrink);
      drink[field] = value;
      return { selectedDrink : drink };
    });
  }

  changeIngredientField = (e, ingredientId, field) => {
    var value = e.target.value;
    this.setState((prevState, props) => {
      let drink = Object.assign({}, prevState.selectedDrink);
      let ingredient = null;
      let potentialIngredient = drink.ingredients.filter(ingredient => ingredient._id === ingredientId);
      if(potentialIngredient.length > 0){
        ingredient = potentialIngredient[0];
        ingredient[field] = value;
      }
      return { selectedDrink : drink };
    });
  }

  addIngredient = (e) => {
    this.setState((prevState, props) => {
      let drink = Object.assign({}, prevState.selectedDrink);
      drink.ingredients = drink.ingredients.concat([{ _id: getKey(), name: '', amount: '' }]);
      return { selectedDrink: drink };
    });
    e.preventDefault();
  }

  removeIngredient = (e, id) => {
    this.setState((prevState, props) => {
      let drink = Object.assign({}, prevState.selectedDrink);
      drink.ingredients = drink.ingredients.filter(ingredient => ingredient._id !== id);
      return { selectedDrink: drink };
    });
    e.preventDefault();
  }

  render = () => {
    return (

        <form className="form form-horizontal">

Mod your drink!

            Choose

              <select
                className="form-control"
                onChange={this.selectDrink.bind(this)}>
                <option value="" default>New Drink</option>
                {(this.state.drinks.map(drink => <option key={drink._id} value={drink._id}>{drink.name}</option>))}
              </select>

          { <Drink
              {...this.state.selectedDrink}
              onSave={this.saveDrink}
              onDrinkFieldChange={this.changeDrinkField}
              onIngredientFieldChange={this.changeIngredientField}
              onAddIngredient={this.addIngredient}
              onRemoveIngredient={this.removeIngredient} /> }
        </form>

    )
  }
}

export default DrinksAdmin;<commit_msg><commit_after>
import React, {Component}  from 'react';
import Client from '../../clients/Drink';
import Drink from './drink';

const getKey = () => {
  return Math.random().toString(36).substr(2, 10);
}

const defaultDrink = {
  _id : undefined,
  name : '',
  description : '',
  image : '',
  ingredients : [{
    _id: getKey(),
    name : '',
    amount : ''
  }]
}

class Admin extends Component {

  state = {
    drinks: [],
    selectedDrink: Object.assign({}, defaultDrink)
  };

  componentWillMount = () => {
    this.updateDrinks();
  }

  updateDrinks = (response) => {
    Client.search('', this.drinksFetched);
  }

  drinksFetched = (drinks) => {
    this.setState({
      drinks,
      selectedDrink : Object.assign({}, defaultDrink)
    });
  }

  saveDrink = (e) => {
    var drink = Object.assign({}, this.state.selectedDrink);
    Client.upsert(drink, this.updateDrinks);
    e.preventDefault();
  }

  removeDrink = (e) => {
    var drink = Object.assign({}, this.state.selectedDrink);
    Client.remove(drink, this.updateDrinks);
    e.preventDefault();
  }

  selectDrink = (e) => {
    let select = e.target;
    let option = select.selectedOptions[0];
    let potentialDrinks = this.state.drinks.filter(drink => drink._id === option.value);
    let drink = potentialDrinks.length > 0 ? potentialDrinks[0] : defaultDrink;

    this.setState({
      selectedDrink: Object.assign({}, drink)
    });
  }

  changeDrinkField = (e, field) => {
    var value = e.target.value;
    this.setState((prevState, props) => {
      let drink = Object.assign({}, prevState.selectedDrink);
      drink[field] = value;
      return { selectedDrink : drink };
    });
  }

  changeIngredientField = (e, ingredientId, field) => {
    var value = e.target.value;
    this.setState((prevState, props) => {
      let drink = Object.assign({}, prevState.selectedDrink);
      let ingredient = null;
      let potentialIngredient = drink.ingredients.filter(ingredient => ingredient._id === ingredientId);
      if(potentialIngredient.length > 0){
        ingredient = potentialIngredient[0];
        ingredient[field] = value;
      }
      return { selectedDrink : drink };
    });
  }

  addIngredient = (e) => {
    this.setState((prevState, props) => {
      let drink = Object.assign({}, prevState.selectedDrink);
      drink.ingredients = drink.ingredients.concat([{ _id: getKey(), name: '', amount: '' }]);
      return { selectedDrink: drink };
    });
    e.preventDefault();
  }

  removeIngredient = (e, id) => {
    this.setState((prevState, props) => {
      let drink = Object.assign({}, prevState.selectedDrink);
      drink.ingredients = drink.ingredients.filter(ingredient => ingredient._id !== id);
      return { selectedDrink: drink };
    });
    e.preventDefault();
  }

  render = () => {
    return (

        <form className="form form-horizontal">

Mod your drink!

            Choose

              <select
                className="form-control"
                onChange={this.selectDrink.bind(this)}>
                <option value="" default>New Drink</option>
                {(this.state.drinks.map(drink => <option key={drink._id} value={drink._id}>{drink.name}</option>))}
              </select>

          { <Drink
              {...this.state.selectedDrink}
              onSave={this.saveDrink}
              onRemove={this.removeDrink}
              onDrinkFieldChange={this.changeDrinkField}
              onIngredientFieldChange={this.changeIngredientField}
              onAddIngredient={this.addIngredient}
              onRemoveIngredient={this.removeIngredient} /> }
        </form>

    )
  }
}

export default Admin;<|endoftext|>


<commit_before>import React, { Component } from "react";
import { Mutation, Query } from "react-apollo";
import gql from "graphql-tag";
import { Input, Button } from "reactstrap";
import { InputField } from "../../generic/core";

const ARMORY_QUERY = gql`
  query Crew($simulatorId: ID!) {
    teams(simulatorId: $simulatorId) {
      id
      name
      type
      officers {
        id
        name
        inventory {
          id
        }
      }
    }
    crew(simulatorId: $simulatorId) {
      id
      name
      inventory {
        id
        name
        count
      }
    }
  }
`;

const CREW_SUB = gql`
  subscription CrewUpdate($simulatorId: ID) {
    crewUpdate(simulatorId: $simulatorId, killed: false) {
      id
      name
      inventory {
        id
        name
        count
      }
    }
  }
`;

const TEAM_SUB = gql`
  subscription TeamsUpdate($simulatorId: ID) {
    teamsUpdate(simulatorId: $simulatorId) {
      id
      name
      type
      officers {
        id
        name
        inventory {
          id
        }
      }
    }
  }
`;

const CrewChoice = ({ crew, teams, selectedCrew, updateSelectedCrew }) => {
  const teamCrew = teams
    .reduce((prev, next) => prev.concat(next.officers), [])
    .map(t => t.id);
  const sorter = (a, b) => {
    if (a.inventory.length > b.inventory.length) return -1;
    if (a.name > b.name) return 1;
    if (a.name  teamCrew.indexOf(c.id) === -1);
  return (
    <Input
      type="select"
      bsSize="sm"
      value={selectedCrew || "nothing"}
      onChange={updateSelectedCrew}
    >
      <option value="nothing" disabled>
        Select a Crew Member
      </option>
      {teams.map(t => (
        <optgroup key={t.id} label={`${t.type} - ${t.name}`}>
          {t.officers
            .concat()
            .sort(sorter)
            .map(c => (
              <option key={c.id} value={c.id}>
                {c.inventory.length > 0 ? "*" : ""} {c.name}
              </option>
            ))}
        </optgroup>
      ))}
      <optgroup label={`Unassigned`}>
        {filteredCrew
          .concat()
          .sort(sorter)
          .map(c => (
            <option key={c.id} value={c.id}>
              {c.inventory.length > 0 ? "*" : ""} {c.name}
            </option>
          ))}
      </optgroup>
    </Input>
  );
};

const ADD_INVENTORY = gql`
  mutation AddInventory($inventory: InventoryItemInput) {
    addInventory(inventory: $inventory)
  }
`;

const UPDATE_INVENTORY = gql`
  mutation UpdateCrewInventory($crewId: ID!, $inventory: [InventoryCount]!) {
    updateCrewInventory(crewId: $crewId, inventory: $inventory)
  }
`;

const CrewCargo = ({ simulatorId, crew: { id, name, inventory } }) => {
  const addInventory = mutate => {
    const iName = prompt("What is the name of the inventory?");
    if (!iName) return;
    const count = prompt("How many do you want to add?");
    if (!count || isNaN(parseInt(count, 10))) return;
    const variables = {
      inventory: {
        simulatorId,
        name: iName,
        metadata: {},
        crewCount: [{ crew: id, count }]
      }
    };
    mutate({ variables });
  };
  const updateInventoryQuantity = (update, invId, count) => {
    const variables = {
      crewId: id,
      inventory: [
        {
          inventory: invId,
          count: parseInt(count, 10)
        }
      ]
    };
    update({ variables });
  };
  return (

{name}
{" "}
      <Mutation mutation={ADD_INVENTORY}>
        {mutate => (
          <Button
            size="sm"
            color="primary"
            onClick={() => addInventory(mutate)}
          >
            Add Inventory
          </Button>
        )}
      </Mutation>
      {inventory.map(i => (
        <p key={`to-${i.id}`}>
          {i.name}{" "}
          <Mutation mutation={UPDATE_INVENTORY}>
            {update => (
              <InputField
                style={{
                  display: "inline-block",
                  minWidth: "20px"
                }}
                prompt={`What is the new quantity of ${i.name}?`}
                onClick={val => updateInventoryQuantity(update, i.id, val)}
              >
                {i.count}
              </InputField>
            )}
          </Mutation>

      ))}

  );
};
const ArmoryCoreData = ({ simulator }) => (
  <Query query={ARMORY_QUERY} variables={{ simulatorId: simulator.id }}>
    {({ subscribeToMore, loading, data: { crew, teams } }) =>
      !loading &&
      crew &&
      teams && (
        <ArmoryCore
          crew={crew}
          teams={teams}
          simulator={simulator}
          subscribe={() => {
            return {
              teams: subscribeToMore({
                document: TEAM_SUB,
                variables: { simulatorId: simulator.id },
                updateQuery: (previousResult, { subscriptionData }) => {
                  return Object.assign({}, previousResult, {
                    teams: subscriptionData.data.teamsUpdate
                  });
                }
              }),
              crew: subscribeToMore({
                document: CREW_SUB,
                variables: { simulatorId: simulator.id },
                updateQuery: (previousResult, { subscriptionData }) => {
                  return Object.assign({}, previousResult, {
                    crew: subscriptionData.data.crewUpdate
                  });
                }
              })
            };
          }}
        />
      )
    }
  </Query>
);

class ArmoryCore extends Component {
  state = { selectedCrew: null };
  componentDidMount() {
    const { teams, crew } = this.props.subscribe();
    this.teamsSub = teams;
    this.crewSub = crew;
  }
  componentWillUnmount() {
    this.teamsSub && this.teamsSub();
    this.crewSub && this.crewSub();
  }
  render() {
    const { selectedCrew } = this.state;
    const { crew, teams, simulator } = this.props;
    return (

        <CrewChoice
          crew={crew}
          teams={teams}
          selectedCrew={selectedCrew}
          updateSelectedCrew={e =>
            this.setState({ selectedCrew: e.target.value })
          }
        />
        {selectedCrew && (
          <CrewCargo
            simulatorId={simulator.id}
            crew={crew.find(c => c.id === selectedCrew)}
          />
        )}

    );
  }
}

export default ArmoryCoreData;
<commit_msg>Properly sort the armory core. Closes #1395<commit_after>import React, { Component } from "react";
import { Mutation, Query } from "react-apollo";
import gql from "graphql-tag";
import { Input, Button } from "reactstrap";
import { InputField } from "../../generic/core";

const ARMORY_QUERY = gql`
  query Crew($simulatorId: ID!) {
    teams(simulatorId: $simulatorId) {
      id
      name
      type
      officers {
        id
        name
        inventory {
          id
        }
      }
    }
    crew(simulatorId: $simulatorId) {
      id
      name
      inventory {
        id
        name
        count
      }
    }
  }
`;

const CREW_SUB = gql`
  subscription CrewUpdate($simulatorId: ID) {
    crewUpdate(simulatorId: $simulatorId, killed: false) {
      id
      name
      inventory {
        id
        name
        count
      }
    }
  }
`;

const TEAM_SUB = gql`
  subscription TeamsUpdate($simulatorId: ID) {
    teamsUpdate(simulatorId: $simulatorId) {
      id
      name
      type
      officers {
        id
        name
        inventory {
          id
        }
      }
    }
  }
`;

const CrewChoice = ({ crew, teams, selectedCrew, updateSelectedCrew }) => {
  const teamCrew = teams
    .reduce((prev, next) => prev.concat(next.officers), [])
    .map(t => t.id);
  const sorter = (a, b) => {
    if (a.inventory.length > b.inventory.length) return -1;
    if (a.inventory.length  b.name) return 1;
    if (a.name  teamCrew.indexOf(c.id) === -1);
  return (
    <Input
      type="select"
      bsSize="sm"
      value={selectedCrew || "nothing"}
      onChange={updateSelectedCrew}
    >
      <option value="nothing" disabled>
        Select a Crew Member
      </option>
      {teams.map(t => (
        <optgroup key={t.id} label={`${t.type} - ${t.name}`}>
          {t.officers
            .concat()
            .sort(sorter)
            .map(c => (
              <option key={c.id} value={c.id}>
                {c.inventory.length > 0 ? "*" : ""} {c.name}
              </option>
            ))}
        </optgroup>
      ))}
      <optgroup label={`Unassigned`}>
        {filteredCrew
          .concat()
          .sort(sorter)
          .map(c => (
            <option key={c.id} value={c.id}>
              {c.inventory.length > 0 ? "*" : ""} {c.name}
            </option>
          ))}
      </optgroup>
    </Input>
  );
};

const ADD_INVENTORY = gql`
  mutation AddInventory($inventory: InventoryItemInput) {
    addInventory(inventory: $inventory)
  }
`;

const UPDATE_INVENTORY = gql`
  mutation UpdateCrewInventory($crewId: ID!, $inventory: [InventoryCount]!) {
    updateCrewInventory(crewId: $crewId, inventory: $inventory)
  }
`;

const CrewCargo = ({ simulatorId, crew: { id, name, inventory } }) => {
  const addInventory = mutate => {
    const iName = prompt("What is the name of the inventory?");
    if (!iName) return;
    const count = prompt("How many do you want to add?");
    if (!count || isNaN(parseInt(count, 10))) return;
    const variables = {
      inventory: {
        simulatorId,
        name: iName,
        metadata: {},
        crewCount: [{ crew: id, count }]
      }
    };
    mutate({ variables });
  };
  const updateInventoryQuantity = (update, invId, count) => {
    const variables = {
      crewId: id,
      inventory: [
        {
          inventory: invId,
          count: parseInt(count, 10)
        }
      ]
    };
    update({ variables });
  };
  return (

{name}
{" "}
      <Mutation mutation={ADD_INVENTORY}>
        {mutate => (
          <Button
            size="sm"
            color="primary"
            onClick={() => addInventory(mutate)}
          >
            Add Inventory
          </Button>
        )}
      </Mutation>
      {inventory.map(i => (
        <p key={`to-${i.id}`}>
          {i.name}{" "}
          <Mutation mutation={UPDATE_INVENTORY}>
            {update => (
              <InputField
                style={{
                  display: "inline-block",
                  minWidth: "20px"
                }}
                prompt={`What is the new quantity of ${i.name}?`}
                onClick={val => updateInventoryQuantity(update, i.id, val)}
              >
                {i.count}
              </InputField>
            )}
          </Mutation>

      ))}

  );
};
const ArmoryCoreData = ({ simulator }) => (
  <Query query={ARMORY_QUERY} variables={{ simulatorId: simulator.id }}>
    {({ subscribeToMore, loading, data: { crew, teams } }) =>
      !loading &&
      crew &&
      teams && (
        <ArmoryCore
          crew={crew}
          teams={teams}
          simulator={simulator}
          subscribe={() => {
            return {
              teams: subscribeToMore({
                document: TEAM_SUB,
                variables: { simulatorId: simulator.id },
                updateQuery: (previousResult, { subscriptionData }) => {
                  return Object.assign({}, previousResult, {
                    teams: subscriptionData.data.teamsUpdate
                  });
                }
              }),
              crew: subscribeToMore({
                document: CREW_SUB,
                variables: { simulatorId: simulator.id },
                updateQuery: (previousResult, { subscriptionData }) => {
                  return Object.assign({}, previousResult, {
                    crew: subscriptionData.data.crewUpdate
                  });
                }
              })
            };
          }}
        />
      )
    }
  </Query>
);

class ArmoryCore extends Component {
  state = { selectedCrew: null };
  componentDidMount() {
    const { teams, crew } = this.props.subscribe();
    this.teamsSub = teams;
    this.crewSub = crew;
  }
  componentWillUnmount() {
    this.teamsSub && this.teamsSub();
    this.crewSub && this.crewSub();
  }
  render() {
    const { selectedCrew } = this.state;
    const { crew, teams, simulator } = this.props;
    return (

        <CrewChoice
          crew={crew}
          teams={teams}
          selectedCrew={selectedCrew}
          updateSelectedCrew={e =>
            this.setState({ selectedCrew: e.target.value })
          }
        />
        {selectedCrew && (
          <CrewCargo
            simulatorId={simulator.id}
            crew={crew.find(c => c.id === selectedCrew)}
          />
        )}

    );
  }
}

export default ArmoryCoreData;
<|endoftext|>


<commit_before>Template.galleryShow.onCreated(function() {
	var self = this;
	this.pageLimit = new ReactiveVar(pageLimit);
});

Template.galleryShow.onRendered(function(){
	var self = this;

	this.autorun(function () {
		Template.currentData();

		setTimeout(function () {
			self.$("#mygallery").justifiedGallery({
				rowHeight : 350,
				margins : 10,
				rel: 'group'
			}).on('jg.complete', function () {
				self.$(this).find('a').colorbox({
					maxWidth : '100%',
					maxHeight : '100%',
					opacity : 0.9,
					transition : 'elastic',
					current : ''
				});
			});
		}, 0);
	});

	this.autorun(function() {
		var limit = self.pageLimit.get();

		setTimeout(function () {
			self.$("#mygallery").justifiedGallery('norewind');
		}, 0);
	});

	// // is triggered every time we scroll
	// $(window).scroll(function() {
	// 	if ($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
	// 		incrementLimit();
	// 	}
	// });
});

Template.galleryShow.helpers({
	photos: function () {
		var limit = Template.instance().pageLimit.get();
		if (this._id) {
			return Photos.find({galleryId: this._id}, { limit: limit });
		} else {
			return Photos.find({}, { limit: limit });
		}
	},
	hidden: function () {
		var limit = Template.instance().pageLimit.get();
		var photosCount = this._id ?
		Photos.find({galleryId: this._id}).count() :
		Photos.find().count();

		if (photosCount <= limit) {
			return 'hidden';
		} else {
			return '';
		}
	}
});

Template.galleryShow.events({
	'click #load-more-btn': function (event, template) {
		incrementLimit(template);
	}
});

pageLimit = 10;

incrementLimit = function(template, inc) {
	inc = typeof inc !== 'undefined' ? inc : pageLimit;
	var limit = template.pageLimit.get();
	newLimit = limit + inc;
	template.pageLimit.set(newLimit);
};
<commit_msg>Fix first gallery load flick<commit_after>Template.galleryShow.onCreated(function() {
	var self = this;
	this.pageLimit = new ReactiveVar(pageLimit);
});

Template.galleryShow.onRendered(function(){
	var self = this;

	self.$("#mygallery").justifiedGallery({
		rowHeight : 350,
		margins : 10,
		rel: 'group'
	}).on('jg.complete', function () {
		self.$(this).find('a').colorbox({
			maxWidth : '100%',
			maxHeight : '100%',
			opacity : 0.9,
			transition : 'elastic',
			current : ''
		});
	});

	this.autorun(function () {
		Template.currentData();

		setTimeout(function () {
			self.$("#mygallery").justifiedGallery({
				rowHeight : 350,
				margins : 10,
				rel: 'group'
			}).on('jg.complete', function () {
				self.$(this).find('a').colorbox({
					maxWidth : '100%',
					maxHeight : '100%',
					opacity : 0.9,
					transition : 'elastic',
					current : ''
				});
			});
		}, 0);
	});

	this.autorun(function() {
		var limit = self.pageLimit.get();

		setTimeout(function () {
			self.$("#mygallery").justifiedGallery('norewind');
		}, 0);
	});

	// // is triggered every time we scroll
	// $(window).scroll(function() {
	// 	if ($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
	// 		incrementLimit();
	// 	}
	// });
});

Template.galleryShow.helpers({
	photos: function () {
		var limit = Template.instance().pageLimit.get();
		if (this._id) {
			return Photos.find({galleryId: this._id}, { limit: limit });
		} else {
			return Photos.find({}, { limit: limit });
		}
	},
	hidden: function () {
		var limit = Template.instance().pageLimit.get();
		var photosCount = this._id ?
		Photos.find({galleryId: this._id}).count() :
		Photos.find().count();

		if (photosCount <= limit) {
			return 'hidden';
		} else {
			return '';
		}
	}
});

Template.galleryShow.events({
	'click #load-more-btn': function (event, template) {
		incrementLimit(template);
	}
});

pageLimit = 10;

incrementLimit = function(template, inc) {
	inc = typeof inc !== 'undefined' ? inc : pageLimit;
	var limit = template.pageLimit.get();
	newLimit = limit + inc;
	template.pageLimit.set(newLimit);
};
<|endoftext|>


<commit_before>"use strict";

// Ordered
var substitutionPairs = [];

function add(slack, matrix) {
    substitutionPairs.push({
        slack: slack,
        matrix: matrix
    });
}

// slack -> matrix substitutions are performed top -> bottom
// matrix -> slack substitutions are performed bottom -> top
add("<", "<");
add(">", ">");
add("&", "&"); // & must be after all replacements involving &s.

var slackToMatrix = function(string) {
    for (var i = 0; i < substitutionPairs.length; ++i) {
        var pair = substitutionPairs[i];
        string = string.replace(pair.slack, pair.matrix);
    }
    return string;
};

var matrixToSlack = function(string) {
    for (var i = substitutionPairs.length - 1; i >= 0; --i) {
        var pair = substitutionPairs[i];
        string = string.replace(pair.matrix, pair.slack);
    }
    return string;
};

module.exports = {
    "matrixToSlack": matrixToSlack,
    "slackToMatrix": slackToMatrix
};
<commit_msg>jsdoc substitutions<commit_after>"use strict";

// Ordered
var substitutionPairs = [];

function add(slack, matrix) {
    substitutionPairs.push({
        slack: slack,
        matrix: matrix
    });
}

// slack -> matrix substitutions are performed top -> bottom
// matrix -> slack substitutions are performed bottom -> top
add("<", "<");
add(">", ">");
add("&", "&"); // & must be after all replacements involving &s.

/**
 * Performs any escaping, unescaping, or substituting required to make the text
 * of a Slack message appear like the text of a Matrix message.
 *
 * @param {string} string the text, in Slack's format.
 */
var slackToMatrix = function(string) {
    for (var i = 0; i < substitutionPairs.length; ++i) {
        var pair = substitutionPairs[i];
        string = string.replace(pair.slack, pair.matrix);
    }
    return string;
};

/**
 * Performs any escaping, unescaping, or substituting required to make the text
 * of a Matrix message appear like the text of a Slack message.
 *
 * @param {string} string the text, in Matrix's m.room.message format.
 */
var matrixToSlack = function(string) {
    for (var i = substitutionPairs.length - 1; i >= 0; --i) {
        var pair = substitutionPairs[i];
        string = string.replace(pair.matrix, pair.slack);
    }
    return string;
};

module.exports = {
    "matrixToSlack": matrixToSlack,
    "slackToMatrix": slackToMatrix
};
<|endoftext|>


<commit_before>var _ = require('lodash');

var db = require('../db');
var fblib = require('../lib/feedback');
var userlib = require('../lib/user');

function validatePotatoCaptcha(fbData, potatoCaptchaKeys) {
    var potatoCaptchaKeysExists = true;
    potatoCaptchaKeys.forEach(function(key) {
        if (!(key in fbData) || !fbData[key] || (_.isEmpty(fbData[key]) && key !== 'tuber')) {
            potatoCaptchaKeysExists = false;
        }
    });

    // tuber's value should always be blank, and sprout's value should always be potato (set by HTML)
    if (fbData['tuber'] || fbData['sprout'] !== 'potato') {
         potatoCaptchaKeysExists = false;
    }

    if (!potatoCaptchaKeysExists) {
        return null;
    }

    // We only allow the publicly accessible fields to be POST/PUT.
    return fblib.publicFeedbackObj(fbData);
}

module.exports = function(server) {
    // Sample usage:
    // if the optional parameter '_user' is included, the token must be valid:
    // % curl -X POST 'http://localhost:5000/feedback?_user=ssa_token' -H 'Content-Type: application/json' -H 'Accept: application/json' -d '{"page_url":"http://galaxy.mozilla.org/badpage","feedback":"This page is terrible"}'
    server.post({
        url: '/feedback',
        swagger: {
            nickname: 'feedback',
            notes: 'Submit feedback',
            summary: 'Submit feedback for a site page'
        },
        validation: {
            feedback: { isRequired: true },
            page_url: { isRequired: true }
        }
    }, db.redisView(function(client, done, req, res, wrap) {
        // We only allow the publicly accessible fields to be POST/PUT.

        var fbData = req.params;
        var potatoCaptchaKeys = ['sprout', 'tuber'];
        fbData = validatePotatoCaptcha(fbData, potatoCaptchaKeys);
        if (!fbData) {
            res.json(400, {error: 'bad_feedback_data'});
            return done();
        } else {
            fbData = fblib.publicFeedbackObj(fbData);
        }

        // TODO: wrap
        var email = req._email;

        if (!req._email) {
            fbData = saveFeedbackAndRespond(fbData);
            return done();
        } else {
            userlib.getUserFromEmail(client, email, function(err, result) {
                if (err || !result) {
                    res.json(500, {error: err || 'db_error'});
                    return done();
                }
                fbData.user = result.id;
                fbData = saveFeedbackAndRespond(fbData);
                return done();
            });
        }

        function saveFeedbackAndRespond(feedbackData) {
            feedbackData = fblib.newFeedback(client, feedbackData);
            res.json({success: true});
            return feedbackData;
        }
    }));
};
<commit_msg>Simplify potato-captcha verification<commit_after>var _ = require('lodash');

var db = require('../db');
var fblib = require('../lib/feedback');
var userlib = require('../lib/user');

// function validatePotatoCaptcha(fbData, potatoCaptchaKeys) {
//     var potatoCaptchaKeysExists = true;
//     potatoCaptchaKeys.forEach(function(key) {
//         if (!(key in fbData) || !fbData[key] || (_.isEmpty(fbData[key]) && key !== 'tuber')) {
//             potatoCaptchaKeysExists = false;
//         }
//     });

//     // tuber's value should always be blank, and sprout's value should always be potato (set by HTML)
//     if (fbData['tuber'] || fbData['sprout'] !== 'potato') {
//          potatoCaptchaKeysExists = false;
//     }

//     if (!potatoCaptchaKeysExists) {
//         return null;
//     }

//     // We only allow the publicly accessible fields to be POST/PUT.
//     return fblib.publicFeedbackObj(fbData);
// }

module.exports = function(server) {
    // Sample usage:
    // if the optional parameter '_user' is included, the token must be valid:
    // % curl -X POST 'http://localhost:5000/feedback?_user=ssa_token' -H 'Content-Type: application/json' -H 'Accept: application/json' -d '{"page_url":"http://galaxy.mozilla.org/badpage","feedback":"This page is terrible"}'
    server.post({
        url: '/feedback',
        swagger: {
            nickname: 'feedback',
            notes: 'Submit feedback',
            summary: 'Submit feedback for a site page'
        },
        validation: {
            feedback: { isRequired: true },
            page_url: { isRequired: true }
        }
    }, db.redisView(function(client, done, req, res, wrap) {
        // We only allow the publicly accessible fields to be POST/PUT.

        var fbData = req.params;
        // var potatoCaptchaKeys = ['sprout', 'tuber'];
        // fbData = validatePotatoCaptcha(fbData, potatoCaptchaKeys);
        // if (!fbData) {
        //     res.json(400, {error: 'bad_feedback_data'});
        //     return done();
        // } else {
        //     fbData = fblib.publicFeedbackObj(fbData);
        // }

        if (fbData['tuber'] || fbData['sprout'] !== 'potato') {
            res.json(400, {error: 'bad_feedback_data'});
            return done();
        }

        fbData = fblib.publicFeedbackObj(fbData);

        // TODO: wrap
        var email = req._email;

        if (!req._email) {
            fbData = saveFeedbackAndRespond(fbData);
            return done();
        } else {
            userlib.getUserFromEmail(client, email, function(err, result) {
                if (err || !result) {
                    res.json(500, {error: err || 'db_error'});
                    return done();
                }
                fbData.user = result.id;
                fbData = saveFeedbackAndRespond(fbData);
                return done();
            });
        }

        function saveFeedbackAndRespond(feedbackData) {
            feedbackData = fblib.newFeedback(client, feedbackData);
            res.json({success: true});
            return feedbackData;
        }
    }));
};
<|endoftext|>


<commit_before>const path = require('path');
const fs = require('fs');
// eslint-disable-next-line
const manifest = require('../dist/chrome/manifest.json');

fs.writeFileSync(
    path.join(__dirname, '../dist/firefox/manifest.json'),
    JSON.stringify(
        Object.assign({}, manifest, {
            applications: {
                gecko: {
                    id: 'extension@hyper-gwent.com',
                    strict_min_version: '53.0'
                }
            }
        }),
        null,
        2
    )
);
<commit_msg>Use compatible min Firefox version<commit_after>const path = require('path');
const fs = require('fs');
// eslint-disable-next-line
const manifest = require('../dist/chrome/manifest.json');

fs.writeFileSync(
    path.join(__dirname, '../dist/firefox/manifest.json'),
    JSON.stringify(
        Object.assign({}, manifest, {
            applications: {
                gecko: {
                    id: 'extension@hyper-gwent.com',
                    strict_min_version: '57.0'
                }
            }
        }),
        null,
        2
    )
);
<|endoftext|>