<commit_before>import ons from 'onsenui';
import {Router} from 'aurelia-router';
import {inject, bindable} from 'aurelia-framework';
import {Database} from '../services/db';
import {Storage} from '../services/storage';

@inject(Router, Database, Storage)
export class Home {
  @bindable selection;
  @bindable currentResults;
  results;
  isFiltered;

  constructor(router, db, storage) {
    this.router = router;
    this.db = db;
    this.storage = storage;
  }

  activate(params) {

  }

  attached() {
    if (ons.platform.isAndroid()) {
      this._map.classList.add('map--material');
    }
    this.map = L.map(this._map, {
      attributionControl: false
    });

    this.basemap = L.gridLayer.googleMutant({
      type: 'roadmap', // valid values are 'roadmap', 'satellite', 'terrain' and 'hybrid'
      styles: [{
        featureType: "poi",
        elementType: "labels.icon",
        stylers: [{ visibility: "off" }]
      }]
    }).addTo(this.map);

    this.buildingsLayer = L.markerClusterGroup({
      maxClusterRadius: 40
    }).addTo(this.map);

    this.markers = L.featureGroup().addTo(this.map);

    this.locateControl = L.control.locate({
      showPopup: false,
      locateControl: {}
    }).addTo(this.map);
    this.locateControl._start = this.locateControl.start.bind(this.locateControl);
    this.locateControl._stop = this.locateControl.stop.bind(this.locateControl);
    this.locateControl._setView = this.locateControl.setView.bind(this.locateControl);
    this.locateControl.stop = this.onLocateControlStop.bind(this);
    this.locateControl.start = this.onLocateControlStart.bind(this);
    this.locateControl.setView = this.onLocateControlSetView.bind(this);

    let mapbounds = this.storage.getItem('mapbounds');
    if (mapbounds) {
      this.map.fitBounds(mapbounds);
    } else {
      this.map.setView([46.801111, 8.226667], 7);
    }

    if (this.storage.getItem('geolocation')) {
      this.locateControl.start();
    }

    this.map.on('moveend', this.updateMapView, this);

    this.buildingsLayer.on('click', this.onBuildingClick, this);
    this.buildings = this.db.data.buildings;
  }

  onBuildingClick(e) {
    this.selection = e.layer.data;
  }

  deselect() {
    this.selection = null;
  }

  selectionChanged(newValue, oldValue) {
    this.markers.clearLayers();
    if (newValue) {
      let marker = L.marker([newValue.lat, newValue.lng]);
      this.markers.addLayer(marker);
      this.roomlist.scrollTop = 0;
      setTimeout(() => {
        this.map.invalidateSize({
          pan: false
        });
        if (!this.map.getBounds().contains(marker.getLatLng())) {
          this.locateControl._onDrag();
          this.map.setView(marker.getLatLng(), this.map.getZoom());
          marker._bringToFront();
        }
      }, 50);
    } else {
      setTimeout(() => {
        this.map.invalidateSize({
          pan: false
        });
      }, 50);
    }
  }

  set buildings(value) {
    this.buildingsLayer.clearLayers();
    value.forEach(building => {
      // TODO: marker icons
      let myIcon = L.divIcon({
        className: 'leaflet-system-icon fa fa-deaf',
        iconSize: 22
      });
      let marker = L.marker([building.lat, building.lng], {icon: myIcon});
      marker.data = building;
      this.buildingsLayer.addLayer(marker);
    });
  }

  get buildings() {
    return this.buildingsLayer.getLayers().map(layer => layer.data);
  }

  updateMapView(evt) {
    let bounds = evt.target.getBounds();
    this.storage.setItem('mapbounds', [
      [bounds.getSouth(), bounds.getWest()],
      [bounds.getNorth(), bounds.getEast()]
    ]);
  }

  onLocateControlStart() {
    this.storage.setItem('geolocation', true);
    this.locateControl.isLocatingStart = true;
    this.locateControl._start();
  }

  onLocateControlStop() {
    this.storage.setItem('geolocation', false);
    this.locateControl._stop();
  }

  onLocateControlSetView() {
    if (this.locateControl.isLocatingStart) {
      this.locateControl.isLocatingStart = false;
      this.locateControl.options.keepCurrentZoomLevel = false;
      this.locateControl.options.locateOptions.maxZoom = this.map.getZoom() < 15 ? 15 : this.map.getZoom();
      this.locateControl._setView();
      this.locateControl.options.keepCurrentZoomLevel = true;
      this.locateControl.options.locateOptions.maxZoom = Infinity;
    } else {
      this.locateControl._setView();
    }
  }

  getRoomName(room) {
    let name = `${room.raum} ${room.raumnummer}`.trim();
    if (!name) {
      name = room.gebaeude;
    }
    if (!name) {
      let type = this.db.data.roomtypes.find((type) => {
        return type.typID === room.typID;
      });
      name = type.typ;
    }
    return name;
  }

  showMenu() {
    let menu = document.getElementById('menu');
    menu.open();
  }

  showSearch() {
    this._search.show();
    this._searchinput.focus();
    this.isSearching = true;
    this.currentSearchText = this.searchText;
    this.currentResults = this.results;
  }

  cancelSearch() {
    this._search.hide();
    this.currentSearchText = '';
    this.currentResults = {};
    this.isSearching = false;
  }

  clearSearch() {
    this.searchText = this.currentSearchText = '';
    this.buildings = this.db.data.buildings;
    this.selection = null;
  }

  showList() {
    this.router.navigateToRoute('list');
  }

  showRoom(room) {
    this.router.navigateToRoute('room', {id: room.anlageID});
  }

  searchCategory(item) {
    this.isFiltered = true;
    this._search.hide();
    this.searchText = this.currentSearchText = item.typ;
    this.buildings = this.db.queryBuildingsByRoomType(item);
    this.results = this.currentResults = {
      buildings: this.buildings,
      locations: []
    };
    this.selection = null;
    this.zoomToNearest();
  }

  zoomToNearest() {
    let center = this.map.getCenter();
    let closest = L.GeometryUtil.closestLayer(this.map, this.buildingsLayer.getLayers(), center);
    if (!this.map.getBounds().contains(closest.layer.getLatLng())) {
      let bounds = L.latLngBounds(closest.layer.getLatLng(), center);
      this.locateControl._onDrag();
      this.map.fitBounds(bounds, {
        maxZoom: this.map.getZoom(),
        padding: [40, 40]
      });
    }
  }

  clearCurrentSearch() {
    this.currentSearchText = '';
    this.currentResults = {
      buildings: [],
      locations: []
    };
    this._searchinput.focus();
  }

  onBuildingResultClick(building) {
    if (!this.isFiltered) {
      this.buildings = this.db.data.buildings;
    }
    this.searchText = this.currentSearchText;
    this.results = this.currentResults;
    this.selection = null;
    this._search.hide();
    this.map.once('moveend', () => {
      this.selection = building;
    });
    this.locateControl._onDrag();
    this.map.setView([building.lat, building.lng], 17);
  }

  onLocationResultClick(location) {
    if (!this.isFiltered) {
      this.buildings = this.db.data.buildings;
    }
    this.searchText = this.currentSearchText;
    this.results = this.currentResults;
    this.selection = null;
    this._search.hide();
    this.locateControl._onDrag();
    this.map.fitBounds(location.bounds);
  }

  onSearch() {
    this.currentResults = this.db.search(this.currentSearchText, 20);
  }

  onSearchInput() {
    this.isFiltered = false;
    this.currentResults = this.db.search(this._searchinput.value, 10);
  }
}
<commit_msg>show room detail on marker click<commit_after>import ons from 'onsenui';
import {Router} from 'aurelia-router';
import {inject, bindable} from 'aurelia-framework';
import {Database} from '../services/db';
import {Storage} from '../services/storage';

@inject(Router, Database, Storage)
export class Home {
  @bindable selection;
  @bindable currentResults;
  results;
  isFiltered;

  constructor(router, db, storage) {
    this.router = router;
    this.db = db;
    this.storage = storage;
  }

  activate(params) {

  }

  attached() {
    if (ons.platform.isAndroid()) {
      this._map.classList.add('map--material');
    }
    this.map = L.map(this._map, {
      attributionControl: false
    });

    this.basemap = L.gridLayer.googleMutant({
      type: 'roadmap', // valid values are 'roadmap', 'satellite', 'terrain' and 'hybrid'
      styles: [{
        featureType: "poi",
        elementType: "labels.icon",
        stylers: [{ visibility: "off" }]
      }]
    }).addTo(this.map);

    this.buildingsLayer = L.markerClusterGroup({
      maxClusterRadius: 40
    }).addTo(this.map);

    this.markers = L.featureGroup().addTo(this.map);

    this.locateControl = L.control.locate({
      showPopup: false,
      locateControl: {}
    }).addTo(this.map);
    this.locateControl._start = this.locateControl.start.bind(this.locateControl);
    this.locateControl._stop = this.locateControl.stop.bind(this.locateControl);
    this.locateControl._setView = this.locateControl.setView.bind(this.locateControl);
    this.locateControl.stop = this.onLocateControlStop.bind(this);
    this.locateControl.start = this.onLocateControlStart.bind(this);
    this.locateControl.setView = this.onLocateControlSetView.bind(this);

    let mapbounds = this.storage.getItem('mapbounds');
    if (mapbounds) {
      this.map.fitBounds(mapbounds);
    } else {
      this.map.setView([46.801111, 8.226667], 7);
    }

    if (this.storage.getItem('geolocation')) {
      this.locateControl.start();
    }

    this.map.on('moveend', this.updateMapView, this);
    this.markers.on('click', this.onMarkerClick, this);
    this.buildingsLayer.on('click', this.onBuildingClick, this);
    this.buildings = this.db.data.buildings;
  }

  onBuildingClick(e) {
    if (this.selection === e.layer.data && this.selection.rooms.length === 1) {
      this.showRoom(this.selection.rooms[0]);
    } else {
      this.selection = e.layer.data;
    }
  }

  onMarkerClick(e) {
    if (this.selection && this.selection.rooms.length === 1) {
      this.showRoom(this.selection.rooms[0]);
    }
  }

  deselect() {
    this.selection = null;
  }

  selectionChanged(newValue, oldValue) {
    this.markers.clearLayers();
    if (newValue) {
      let marker = L.marker([newValue.lat, newValue.lng]);
      this.markers.addLayer(marker);
      this.roomlist.scrollTop = 0;
      setTimeout(() => {
        this.map.invalidateSize({
          pan: false
        });
        if (!this.map.getBounds().contains(marker.getLatLng())) {
          this.locateControl._onDrag();
          this.map.setView(marker.getLatLng(), this.map.getZoom());
          marker._bringToFront();
        }
      }, 50);
    } else {
      setTimeout(() => {
        this.map.invalidateSize({
          pan: false
        });
      }, 50);
    }
  }

  set buildings(value) {
    this.buildingsLayer.clearLayers();
    value.forEach(building => {
      // TODO: marker icons
      let myIcon = L.divIcon({
        className: 'leaflet-system-icon fa fa-deaf',
        iconSize: 22
      });
      let marker = L.marker([building.lat, building.lng], {icon: myIcon});
      marker.data = building;
      this.buildingsLayer.addLayer(marker);
    });
  }

  get buildings() {
    return this.buildingsLayer.getLayers().map(layer => layer.data);
  }

  updateMapView(evt) {
    let bounds = evt.target.getBounds();
    this.storage.setItem('mapbounds', [
      [bounds.getSouth(), bounds.getWest()],
      [bounds.getNorth(), bounds.getEast()]
    ]);
  }

  onLocateControlStart() {
    this.storage.setItem('geolocation', true);
    this.locateControl.isLocatingStart = true;
    this.locateControl._start();
  }

  onLocateControlStop() {
    this.storage.setItem('geolocation', false);
    this.locateControl._stop();
  }

  onLocateControlSetView() {
    if (this.locateControl.isLocatingStart) {
      this.locateControl.isLocatingStart = false;
      this.locateControl.options.keepCurrentZoomLevel = false;
      this.locateControl.options.locateOptions.maxZoom = this.map.getZoom() < 15 ? 15 : this.map.getZoom();
      this.locateControl._setView();
      this.locateControl.options.keepCurrentZoomLevel = true;
      this.locateControl.options.locateOptions.maxZoom = Infinity;
    } else {
      this.locateControl._setView();
    }
  }

  getRoomName(room) {
    let name = `${room.raum} ${room.raumnummer}`.trim();
    if (!name) {
      name = room.gebaeude;
    }
    if (!name) {
      let type = this.db.data.roomtypes.find((type) => {
        return type.typID === room.typID;
      });
      name = type.typ;
    }
    return name;
  }

  showMenu() {
    let menu = document.getElementById('menu');
    menu.open();
  }

  showSearch() {
    this._search.show();
    this._searchinput.focus();
    this.isSearching = true;
    this.currentSearchText = this.searchText;
    this.currentResults = this.results;
  }

  cancelSearch() {
    this._search.hide();
    this.currentSearchText = '';
    this.currentResults = {};
    this.isSearching = false;
  }

  clearSearch() {
    this.searchText = this.currentSearchText = '';
    this.buildings = this.db.data.buildings;
    this.selection = null;
  }

  showList() {
    this.router.navigateToRoute('list');
  }

  showRoom(room) {
    this.router.navigateToRoute('room', {id: room.anlageID});
  }

  searchCategory(item) {
    this.isFiltered = true;
    this._search.hide();
    this.searchText = this.currentSearchText = item.typ;
    this.buildings = this.db.queryBuildingsByRoomType(item);
    this.results = this.currentResults = {
      buildings: this.buildings,
      locations: []
    };
    this.selection = null;
    this.zoomToNearest();
  }

  zoomToNearest() {
    let center = this.map.getCenter();
    let closest = L.GeometryUtil.closestLayer(this.map, this.buildingsLayer.getLayers(), center);
    if (!this.map.getBounds().contains(closest.layer.getLatLng())) {
      let bounds = L.latLngBounds(closest.layer.getLatLng(), center);
      this.locateControl._onDrag();
      this.map.fitBounds(bounds, {
        maxZoom: this.map.getZoom(),
        padding: [40, 40]
      });
    }
  }

  clearCurrentSearch() {
    this.currentSearchText = '';
    this.currentResults = {
      buildings: [],
      locations: []
    };
    this._searchinput.focus();
  }

  onBuildingResultClick(building) {
    if (!this.isFiltered) {
      this.buildings = this.db.data.buildings;
    }
    this.searchText = this.currentSearchText;
    this.results = this.currentResults;
    this.selection = null;
    this._search.hide();
    this.map.once('moveend', () => {
      this.selection = building;
    });
    this.locateControl._onDrag();
    this.map.setView([building.lat, building.lng], 17);
  }

  onLocationResultClick(location) {
    if (!this.isFiltered) {
      this.buildings = this.db.data.buildings;
    }
    this.searchText = this.currentSearchText;
    this.results = this.currentResults;
    this.selection = null;
    this._search.hide();
    this.locateControl._onDrag();
    this.map.fitBounds(location.bounds);
  }

  onSearch() {
    this.currentResults = this.db.search(this.currentSearchText, 20);
  }

  onSearchInput() {
    this.isFiltered = false;
    this.currentResults = this.db.search(this._searchinput.value, 10);
  }
}
<|endoftext|>


<commit_before>/**
 * 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.
 */

/**
 * Implementing Drag and Drop functionality in AngularJS is easier than ever.
 * Demo: http://codef0rmer.github.com/angular-dragdrop/
 *
 * @version 1.0.0
 *
 * (c) 2013 Amit Gharat a.k.a codef0rmer <amit.2006.it@gmail.com> - amitgharat.wordpress.com
 */

var jqyoui = angular.module('ngDragDrop', []).service('service', ['$timeout', function($timeout) {
  this.callEventCallback = function (scope, callbackName, event, ui) {
    if (!callbackName) {
      return;
    }
    var args = [event, ui];
    var match = callbackName.match(/^(.+)\((.+)\)$/);
    if (match !== null) {
      callbackName = match[1];
      values = eval('[' + match[0].replace(/^(.+)\(/, '').replace(/\)/, '') + ']');
      args.push.apply(args, values);
    }
    scope[callbackName].apply(scope, args);
  };

  this.invokeDrop = function ($draggable, $droppable, scope, event, ui) {
    var dragModel = '',
        dropModel = '',
        dragSettings = {},
        dropSettings = {},
        jqyoui_pos = null,
        dragItem = {},
        dropItem = {},
        $droppableDraggable = null;

    dragModel = $draggable.attr('ng-model');
    dropModel = $droppable.attr('ng-model');
    $droppableDraggable = $droppable.find('[jqyoui-draggable]:last');
    dropSettings = scope.$eval($droppable.attr('jqyoui-droppable')) || [];
    dragSettings = scope.$eval($draggable.attr('jqyoui-draggable')) || [];
    jqyoui_pos = angular.isArray(scope[dragModel]) ? dragSettings.index : null,
    dragItem = angular.isArray(scope[dragModel]) ? scope[dragModel][jqyoui_pos] : scope[dragModel];
    dropItem = ( angular.isArray(scope[dropModel]) && dropSettings && dropSettings.index !== undefined ?
      scope[dropModel][dropSettings.index] :
      !angular.isArray(scope[dropModel]) ?
      scope[dropModel] :
      {}
    ) || {};

    if (dragSettings.animate === true) {
      this.move($draggable, $droppableDraggable.length > 0 ? $droppableDraggable : $droppable, null, 'fast', dropSettings, null);
      this.move($droppableDraggable.length > 0 && !dropSettings.multiple ? $droppableDraggable : [], $draggable.parent('[jqyoui-droppable]'), jqyoui.startXY, 'fast', dropSettings, function() {
        $timeout(function() {
          // Do not move this into move() to avoid flickering issue
          $draggable.css({'position': 'relative', 'left': '', 'top': ''});
          $droppableDraggable.css({'position': 'relative', 'left': '', 'top': ''});

          this.mutateDraggable(scope, dropSettings, dragSettings, dragModel, dropModel, dropItem, $draggable);
          this.mutateDroppable(scope, dropSettings, dragSettings, dropModel, dragItem, jqyoui_pos);
          service.callEventCallback(scope, dropSettings.onDrop, event, ui);
        }.bind(this));
      }.bind(this));
    } else {
      $timeout(function() {
        this.mutateDraggable(scope, dropSettings, dragSettings, dragModel, dropModel, dropItem, $draggable);
        this.mutateDroppable(scope, dropSettings, dragSettings, dropModel, dragItem, jqyoui_pos);
        this.callEventCallback(scope, dropSettings.onDrop, event, ui);
      }.bind(this));
    }
  };

  this.move = function($fromEl, $toEl, toPos, duration, dropSettings, callback) {
    if ($fromEl.length === 0) {
      if (callback) {
        window.setTimeout(function() {
          callback();
        }, 300);
      }
      return false;
    }

    var zIndex = 9999,
        fromPos = $fromEl.offset(),
        wasVisible = $toEl && $toEl.is(':visible');

    if (toPos === null && $toEl.length > 0) {
      if ($toEl.attr('jqyoui-draggable') !== undefined && $toEl.attr('ng-model') !== undefined && $toEl.is(':visible') && dropSettings && dropSettings.multiple) {
        toPos = $toEl.offset();
        if (dropSettings.stack === false) {
          toPos.left+= $toEl.outerWidth(true);
        } else {
          toPos.top+= $toEl.outerHeight(true);
        }
      } else {
        toPos = $toEl.css({'visibility': 'hidden', 'display': 'block'}).offset();
        $toEl.css({'visibility': '','display': wasVisible ? '' : 'none'});
      }
    }

    $fromEl.css({'position': 'absolute', 'z-index': zIndex})
      .css(fromPos)
      .animate(toPos, duration, function() {
        if (callback) callback();
      });
  };

  this.mutateDroppable = function(scope, dropSettings, dragSettings, dropModel, dragItem, jqyoui_pos) {
    if (angular.isArray(scope[dropModel])) {
      if (dropSettings && dropSettings.index >= 0) {
        scope[dropModel][dropSettings.index] = dragItem;
      } else {
        scope[dropModel].push(dragItem);
      }
      if (dragSettings && dragSettings.placeholder) {
        scope[dropModel][scope[dropModel].length - 1]['jqyoui_pos'] = jqyoui_pos;
      }
    } else {
      scope[dropModel] = dragItem;
      if (dragSettings && dragSettings.placeholder) {
        scope[dropModel]['jqyoui_pos'] = jqyoui_pos;
      }
    }
  };

  this.mutateDraggable = function(scope, dropSettings, dragSettings, dragModel, dropModel, dropItem, $draggable) {
    var isEmpty = $.isEmptyObject(dropItem);

    if (dragSettings && dragSettings.placeholder) {
      if (angular.isArray(scope[dragModel]) && dragSettings.index !== undefined) {
        scope[dragModel][dragSettings.index] = dropItem;
      } else {
        scope[dragModel] = dropItem;
      }
    } else {
      if (angular.isArray(scope[dragModel])) {
        if (isEmpty) {
          scope[dragModel].splice(dragSettings.index, 1);
        } else {
          scope[dragModel][dragSettings.index] = dropItem;
        }
      } else {
        // Fix: LIST(object) to LIST(array) - model does not get updated using just scope[dragModel] = {...}
        // P.S.: Could not figure out why it happened
        scope[dragModel] = dropItem;
        if (scope.$parent) scope.$parent[dragModel] = dropItem;
      }
    }

    $draggable.css({'z-index': '', 'left': '', 'top': ''});
  };
}]).directive('jqyouiDraggable', ['service', function(service) {
  return {
    require: '?jqyouiDroppable',
    restrict: 'A',
    link: function(scope, element, attrs) {
      var dragSettings;
      var updateDraggable = function(newValue, oldValue) {
        if (newValue) {
          dragSettings = scope.$eval(element.attr('jqyoui-draggable')) || [];
          element
            .draggable({disabled: false})
            .draggable(scope.$eval(attrs.jqyouiOptions) || {})
            .draggable({
              start: function(event, ui) {
                $(this).css('z-index', 99999);
                jqyoui.startXY = $(this).offset();
                service.callEventCallback(scope, dragSettings.onStart, event, ui);
              },
              stop: function(event, ui) {
                service.callEventCallback(scope, dragSettings.onStop, event, ui);
              },
              drag: function(event, ui) {
                service.callEventCallback(scope, dragSettings.onDrag, event, ui);
              }
            });
        } else {
          element.draggable({disabled: true});
        }
      };
      scope.$watch(function() { return scope.$eval(attrs.drag); }, updateDraggable);
      updateDraggable();
    }
  };
}]).directive('jqyouiDroppable', ['service', function(service) {
  return {
    restrict: 'A',
    priority: 1,
    link: function(scope, element, attrs) {
      var updateDroppable = function(newValue, oldValue) {
        if (newValue) {
          element
            .droppable({disabled: false})
            .droppable(scope.$eval(attrs.jqyouiOptions) || {})
            .droppable({
              over: function(event, ui) {
                var dropSettings = scope.$eval(angular.element(this).attr('jqyoui-droppable')) || [];
                service.callEventCallback(scope, dropSettings.onOver, event, ui);
              },
              out: function(event, ui) {
                var dropSettings = scope.$eval(angular.element(this).attr('jqyoui-droppable')) || [];
                service.callEventCallback(scope, dropSettings.onOut, event, ui);
              },
              drop: function(event, ui) {
                service.invokeDrop(angular.element(ui.draggable), angular.element(this), scope, event, ui);
              }
            });
        } else {
          element.droppable({disabled: true});
        }
      };

      scope.$watch(function() { return scope.$eval(attrs.drop); }, updateDroppable);
      updateDroppable();
    }
  };
}]);<commit_msg>Renamed service to avoid possible conflicts<commit_after>/**
 * 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.
 */

/**
 * Implementing Drag and Drop functionality in AngularJS is easier than ever.
 * Demo: http://codef0rmer.github.com/angular-dragdrop/
 *
 * @version 1.0.0
 *
 * (c) 2013 Amit Gharat a.k.a codef0rmer <amit.2006.it@gmail.com> - amitgharat.wordpress.com
 */

var jqyoui = angular.module('ngDragDrop', []).service('ngDragDropService', ['$timeout', function($timeout) {
  this.callEventCallback = function (scope, callbackName, event, ui) {
    if (!callbackName) {
      return;
    }
    var args = [event, ui];
    var match = callbackName.match(/^(.+)\((.+)\)$/);
    if (match !== null) {
      callbackName = match[1];
      values = eval('[' + match[0].replace(/^(.+)\(/, '').replace(/\)/, '') + ']');
      args.push.apply(args, values);
    }
    scope[callbackName].apply(scope, args);
  };

  this.invokeDrop = function ($draggable, $droppable, scope, event, ui) {
    var dragModel = '',
        dropModel = '',
        dragSettings = {},
        dropSettings = {},
        jqyoui_pos = null,
        dragItem = {},
        dropItem = {},
        $droppableDraggable = null;

    dragModel = $draggable.attr('ng-model');
    dropModel = $droppable.attr('ng-model');
    $droppableDraggable = $droppable.find('[jqyoui-draggable]:last');
    dropSettings = scope.$eval($droppable.attr('jqyoui-droppable')) || [];
    dragSettings = scope.$eval($draggable.attr('jqyoui-draggable')) || [];
    jqyoui_pos = angular.isArray(scope[dragModel]) ? dragSettings.index : null,
    dragItem = angular.isArray(scope[dragModel]) ? scope[dragModel][jqyoui_pos] : scope[dragModel];
    dropItem = ( angular.isArray(scope[dropModel]) && dropSettings && dropSettings.index !== undefined ?
      scope[dropModel][dropSettings.index] :
      !angular.isArray(scope[dropModel]) ?
      scope[dropModel] :
      {}
    ) || {};

    if (dragSettings.animate === true) {
      this.move($draggable, $droppableDraggable.length > 0 ? $droppableDraggable : $droppable, null, 'fast', dropSettings, null);
      this.move($droppableDraggable.length > 0 && !dropSettings.multiple ? $droppableDraggable : [], $draggable.parent('[jqyoui-droppable]'), jqyoui.startXY, 'fast', dropSettings, function() {
        $timeout(function() {
          // Do not move this into move() to avoid flickering issue
          $draggable.css({'position': 'relative', 'left': '', 'top': ''});
          $droppableDraggable.css({'position': 'relative', 'left': '', 'top': ''});

          this.mutateDraggable(scope, dropSettings, dragSettings, dragModel, dropModel, dropItem, $draggable);
          this.mutateDroppable(scope, dropSettings, dragSettings, dropModel, dragItem, jqyoui_pos);
          this.callEventCallback(scope, dropSettings.onDrop, event, ui);
        }.bind(this));
      }.bind(this));
    } else {
      $timeout(function() {
        this.mutateDraggable(scope, dropSettings, dragSettings, dragModel, dropModel, dropItem, $draggable);
        this.mutateDroppable(scope, dropSettings, dragSettings, dropModel, dragItem, jqyoui_pos);
        this.callEventCallback(scope, dropSettings.onDrop, event, ui);
      }.bind(this));
    }
  };

  this.move = function($fromEl, $toEl, toPos, duration, dropSettings, callback) {
    if ($fromEl.length === 0) {
      if (callback) {
        window.setTimeout(function() {
          callback();
        }, 300);
      }
      return false;
    }

    var zIndex = 9999,
        fromPos = $fromEl.offset(),
        wasVisible = $toEl && $toEl.is(':visible');

    if (toPos === null && $toEl.length > 0) {
      if ($toEl.attr('jqyoui-draggable') !== undefined && $toEl.attr('ng-model') !== undefined && $toEl.is(':visible') && dropSettings && dropSettings.multiple) {
        toPos = $toEl.offset();
        if (dropSettings.stack === false) {
          toPos.left+= $toEl.outerWidth(true);
        } else {
          toPos.top+= $toEl.outerHeight(true);
        }
      } else {
        toPos = $toEl.css({'visibility': 'hidden', 'display': 'block'}).offset();
        $toEl.css({'visibility': '','display': wasVisible ? '' : 'none'});
      }
    }

    $fromEl.css({'position': 'absolute', 'z-index': zIndex})
      .css(fromPos)
      .animate(toPos, duration, function() {
        if (callback) callback();
      });
  };

  this.mutateDroppable = function(scope, dropSettings, dragSettings, dropModel, dragItem, jqyoui_pos) {
    if (angular.isArray(scope[dropModel])) {
      if (dropSettings && dropSettings.index >= 0) {
        scope[dropModel][dropSettings.index] = dragItem;
      } else {
        scope[dropModel].push(dragItem);
      }
      if (dragSettings && dragSettings.placeholder) {
        scope[dropModel][scope[dropModel].length - 1]['jqyoui_pos'] = jqyoui_pos;
      }
    } else {
      scope[dropModel] = dragItem;
      if (dragSettings && dragSettings.placeholder) {
        scope[dropModel]['jqyoui_pos'] = jqyoui_pos;
      }
    }
  };

  this.mutateDraggable = function(scope, dropSettings, dragSettings, dragModel, dropModel, dropItem, $draggable) {
    var isEmpty = $.isEmptyObject(dropItem);

    if (dragSettings && dragSettings.placeholder) {
      if (angular.isArray(scope[dragModel]) && dragSettings.index !== undefined) {
        scope[dragModel][dragSettings.index] = dropItem;
      } else {
        scope[dragModel] = dropItem;
      }
    } else {
      if (angular.isArray(scope[dragModel])) {
        if (isEmpty) {
          scope[dragModel].splice(dragSettings.index, 1);
        } else {
          scope[dragModel][dragSettings.index] = dropItem;
        }
      } else {
        // Fix: LIST(object) to LIST(array) - model does not get updated using just scope[dragModel] = {...}
        // P.S.: Could not figure out why it happened
        scope[dragModel] = dropItem;
        if (scope.$parent) scope.$parent[dragModel] = dropItem;
      }
    }

    $draggable.css({'z-index': '', 'left': '', 'top': ''});
  };
}]).directive('jqyouiDraggable', ['ngDragDropService', function(ngDragDropService) {
  return {
    require: '?jqyouiDroppable',
    restrict: 'A',
    link: function(scope, element, attrs) {
      var dragSettings;
      var updateDraggable = function(newValue, oldValue) {
        if (newValue) {
          dragSettings = scope.$eval(element.attr('jqyoui-draggable')) || [];
          element
            .draggable({disabled: false})
            .draggable(scope.$eval(attrs.jqyouiOptions) || {})
            .draggable({
              start: function(event, ui) {
                $(this).css('z-index', 99999);
                jqyoui.startXY = $(this).offset();
                ngDragDropService.callEventCallback(scope, dragSettings.onStart, event, ui);
              },
              stop: function(event, ui) {
                ngDragDropService.callEventCallback(scope, dragSettings.onStop, event, ui);
              },
              drag: function(event, ui) {
                ngDragDropService.callEventCallback(scope, dragSettings.onDrag, event, ui);
              }
            });
        } else {
          element.draggable({disabled: true});
        }
      };
      scope.$watch(function() { return scope.$eval(attrs.drag); }, updateDraggable);
      updateDraggable();
    }
  };
}]).directive('jqyouiDroppable', ['ngDragDropService', function(ngDragDropService) {
  return {
    restrict: 'A',
    priority: 1,
    link: function(scope, element, attrs) {
      var updateDroppable = function(newValue, oldValue) {
        if (newValue) {
          element
            .droppable({disabled: false})
            .droppable(scope.$eval(attrs.jqyouiOptions) || {})
            .droppable({
              over: function(event, ui) {
                var dropSettings = scope.$eval(angular.element(this).attr('jqyoui-droppable')) || [];
                ngDragDropService.callEventCallback(scope, dropSettings.onOver, event, ui);
              },
              out: function(event, ui) {
                var dropSettings = scope.$eval(angular.element(this).attr('jqyoui-droppable')) || [];
                ngDragDropService.callEventCallback(scope, dropSettings.onOut, event, ui);
              },
              drop: function(event, ui) {
                ngDragDropService.invokeDrop(angular.element(ui.draggable), angular.element(this), scope, event, ui);
              }
            });
        } else {
          element.droppable({disabled: true});
        }
      };

      scope.$watch(function() { return scope.$eval(attrs.drop); }, updateDroppable);
      updateDroppable();
    }
  };
}]);<|endoftext|>


<commit_before>import { app, BrowserWindow, Menu, shell } from 'electron';

let menu;
let template;
let mainWindow = null;

if (process.env.NODE_ENV === 'production') {
  const sourceMapSupport = require('source-map-support'); // eslint-disable-line
  sourceMapSupport.install();
}

if (process.env.NODE_ENV === 'development') {
  require('electron-debug')(); // eslint-disable-line global-require
  const path = require('path'); // eslint-disable-line
  const p = path.join(__dirname, '..', 'app', 'node_modules'); // eslint-disable-line
  require('module').globalPaths.push(p); // eslint-disable-line
}

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

const installExtensions = async () => {
  if (process.env.NODE_ENV === 'development') {
    const installer = require('electron-devtools-installer'); // eslint-disable-line global-require

    const extensions = [
      'REACT_DEVELOPER_TOOLS',
      'REDUX_DEVTOOLS'
    ];
    const forceDownload = !!process.env.UPGRADE_EXTENSIONS;
    for (const name of extensions) { // eslint-disable-line
      try {
        await installer.default(installer[name], forceDownload);
      } catch (e) {} // eslint-disable-line
    }
  }
};

app.on('ready', async () => {
  await installExtensions();

  mainWindow = new BrowserWindow({
    show: false,
    width: 1024,
    height: 728,
    icon: `file://${__dirname}/assets/BrancherLogo.png`
  });

  mainWindow.loadURL(`file://${__dirname}/app.html`);

  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.show();
    mainWindow.focus();
  });

  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  if (process.env.NODE_ENV === 'development') {
    mainWindow.openDevTools();
    mainWindow.webContents.on('context-menu', (e, props) => {
      const { x, y } = props;

      Menu.buildFromTemplate([{
        label: 'Inspect element',
        click() {
          mainWindow.inspectElement(x, y);
        }
      }]).popup(mainWindow);
    });
  }

  if (process.platform === 'darwin') {
    template = [{
      label: 'Electron',
      submenu: [{
        label: 'About ElectronReact',
        selector: 'orderFrontStandardAboutPanel:'
      }, {
        type: 'separator'
      }, {
        label: 'Services',
        submenu: []
      }, {
        type: 'separator'
      }, {
        label: 'Hide ElectronReact',
        accelerator: 'Command+H',
        selector: 'hide:'
      }, {
        label: 'Hide Others',
        accelerator: 'Command+Shift+H',
        selector: 'hideOtherApplications:'
      }, {
        label: 'Show All',
        selector: 'unhideAllApplications:'
      }, {
        type: 'separator'
      }, {
        label: 'Quit',
        accelerator: 'Command+Q',
        click() {
          app.quit();
        }
      }]
    }, {
      label: 'Edit',
      submenu: [{
        label: 'Undo',
        accelerator: 'Command+Z',
        selector: 'undo:'
      }, {
        label: 'Redo',
        accelerator: 'Shift+Command+Z',
        selector: 'redo:'
      }, {
        type: 'separator'
      }, {
        label: 'Cut',
        accelerator: 'Command+X',
        selector: 'cut:'
      }, {
        label: 'Copy',
        accelerator: 'Command+C',
        selector: 'copy:'
      }, {
        label: 'Paste',
        accelerator: 'Command+V',
        selector: 'paste:'
      }, {
        label: 'Select All',
        accelerator: 'Command+A',
        selector: 'selectAll:'
      }]
    }, {
      label: 'View',
      submenu: (process.env.NODE_ENV === 'development') ? [{
        label: 'Reload',
        accelerator: 'Command+R',
        click() {
          mainWindow.webContents.reload();
        }
      }, {
        label: 'Toggle Full Screen',
        accelerator: 'Ctrl+Command+F',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle Developer Tools',
        accelerator: 'Alt+Command+I',
        click() {
          mainWindow.toggleDevTools();
        }
      }] : [{
        label: 'Toggle Full Screen',
        accelerator: 'Ctrl+Command+F',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }]
    }, {
      label: 'Window',
      submenu: [{
        label: 'Minimize',
        accelerator: 'Command+M',
        selector: 'performMiniaturize:'
      }, {
        label: 'Close',
        accelerator: 'Command+W',
        selector: 'performClose:'
      }, {
        type: 'separator'
      }, {
        label: 'Bring All to Front',
        selector: 'arrangeInFront:'
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click() {
          shell.openExternal('http://electron.atom.io');
        }
      }, {
        label: 'Documentation',
        click() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
        }
      }, {
        label: 'Community Discussions',
        click() {
          shell.openExternal('https://discuss.atom.io/c/electron');
        }
      }, {
        label: 'Search Issues',
        click() {
          shell.openExternal('https://github.com/atom/electron/issues');
        }
      }]
    }];

    menu = Menu.buildFromTemplate(template);
    Menu.setApplicationMenu(menu);
  } else {
    template = [{
      label: '&File',
      submenu: [{
        label: '&Open',
        accelerator: 'Ctrl+O'
      }, {
        label: '&Close',
        accelerator: 'Ctrl+W',
        click() {
          mainWindow.close();
        }
      }]
    }, {
      label: '&View',
      submenu: (process.env.NODE_ENV === 'development') ? [{
        label: '&Reload',
        accelerator: 'Ctrl+R',
        click() {
          mainWindow.webContents.reload();
        }
      }, {
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle &Developer Tools',
        accelerator: 'Alt+Ctrl+I',
        click() {
          mainWindow.toggleDevTools();
        }
      }] : [{
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click() {
          shell.openExternal('http://electron.atom.io');
        }
      }, {
        label: 'Documentation',
        click() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
        }
      }, {
        label: 'Community Discussions',
        click() {
          shell.openExternal('https://discuss.atom.io/c/electron');
        }
      }, {
        label: 'Search Issues',
        click() {
          shell.openExternal('https://github.com/atom/electron/issues');
        }
      }]
    }];
    menu = Menu.buildFromTemplate(template);
    mainWindow.setMenu(menu);
  }
});
<commit_msg>Remove icon<commit_after>import { app, BrowserWindow, Menu, shell } from 'electron';

let menu;
let template;
let mainWindow = null;

if (process.env.NODE_ENV === 'production') {
  const sourceMapSupport = require('source-map-support'); // eslint-disable-line
  sourceMapSupport.install();
}

if (process.env.NODE_ENV === 'development') {
  require('electron-debug')(); // eslint-disable-line global-require
  const path = require('path'); // eslint-disable-line
  const p = path.join(__dirname, '..', 'app', 'node_modules'); // eslint-disable-line
  require('module').globalPaths.push(p); // eslint-disable-line
}

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

const installExtensions = async () => {
  if (process.env.NODE_ENV === 'development') {
    const installer = require('electron-devtools-installer'); // eslint-disable-line global-require

    const extensions = [
      'REACT_DEVELOPER_TOOLS',
      'REDUX_DEVTOOLS'
    ];
    const forceDownload = !!process.env.UPGRADE_EXTENSIONS;
    for (const name of extensions) { // eslint-disable-line
      try {
        await installer.default(installer[name], forceDownload);
      } catch (e) {} // eslint-disable-line
    }
  }
};

app.on('ready', async () => {
  await installExtensions();

  mainWindow = new BrowserWindow({
    show: false,
    width: 1024,
    height: 728
  });

  mainWindow.loadURL(`file://${__dirname}/app.html`);

  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.show();
    mainWindow.focus();
  });

  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  if (process.env.NODE_ENV === 'development') {
    mainWindow.openDevTools();
    mainWindow.webContents.on('context-menu', (e, props) => {
      const { x, y } = props;

      Menu.buildFromTemplate([{
        label: 'Inspect element',
        click() {
          mainWindow.inspectElement(x, y);
        }
      }]).popup(mainWindow);
    });
  }

  if (process.platform === 'darwin') {
    template = [{
      label: 'Electron',
      submenu: [{
        label: 'About ElectronReact',
        selector: 'orderFrontStandardAboutPanel:'
      }, {
        type: 'separator'
      }, {
        label: 'Services',
        submenu: []
      }, {
        type: 'separator'
      }, {
        label: 'Hide ElectronReact',
        accelerator: 'Command+H',
        selector: 'hide:'
      }, {
        label: 'Hide Others',
        accelerator: 'Command+Shift+H',
        selector: 'hideOtherApplications:'
      }, {
        label: 'Show All',
        selector: 'unhideAllApplications:'
      }, {
        type: 'separator'
      }, {
        label: 'Quit',
        accelerator: 'Command+Q',
        click() {
          app.quit();
        }
      }]
    }, {
      label: 'Edit',
      submenu: [{
        label: 'Undo',
        accelerator: 'Command+Z',
        selector: 'undo:'
      }, {
        label: 'Redo',
        accelerator: 'Shift+Command+Z',
        selector: 'redo:'
      }, {
        type: 'separator'
      }, {
        label: 'Cut',
        accelerator: 'Command+X',
        selector: 'cut:'
      }, {
        label: 'Copy',
        accelerator: 'Command+C',
        selector: 'copy:'
      }, {
        label: 'Paste',
        accelerator: 'Command+V',
        selector: 'paste:'
      }, {
        label: 'Select All',
        accelerator: 'Command+A',
        selector: 'selectAll:'
      }]
    }, {
      label: 'View',
      submenu: (process.env.NODE_ENV === 'development') ? [{
        label: 'Reload',
        accelerator: 'Command+R',
        click() {
          mainWindow.webContents.reload();
        }
      }, {
        label: 'Toggle Full Screen',
        accelerator: 'Ctrl+Command+F',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle Developer Tools',
        accelerator: 'Alt+Command+I',
        click() {
          mainWindow.toggleDevTools();
        }
      }] : [{
        label: 'Toggle Full Screen',
        accelerator: 'Ctrl+Command+F',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }]
    }, {
      label: 'Window',
      submenu: [{
        label: 'Minimize',
        accelerator: 'Command+M',
        selector: 'performMiniaturize:'
      }, {
        label: 'Close',
        accelerator: 'Command+W',
        selector: 'performClose:'
      }, {
        type: 'separator'
      }, {
        label: 'Bring All to Front',
        selector: 'arrangeInFront:'
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click() {
          shell.openExternal('http://electron.atom.io');
        }
      }, {
        label: 'Documentation',
        click() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
        }
      }, {
        label: 'Community Discussions',
        click() {
          shell.openExternal('https://discuss.atom.io/c/electron');
        }
      }, {
        label: 'Search Issues',
        click() {
          shell.openExternal('https://github.com/atom/electron/issues');
        }
      }]
    }];

    menu = Menu.buildFromTemplate(template);
    Menu.setApplicationMenu(menu);
  } else {
    template = [{
      label: '&File',
      submenu: [{
        label: '&Open',
        accelerator: 'Ctrl+O'
      }, {
        label: '&Close',
        accelerator: 'Ctrl+W',
        click() {
          mainWindow.close();
        }
      }]
    }, {
      label: '&View',
      submenu: (process.env.NODE_ENV === 'development') ? [{
        label: '&Reload',
        accelerator: 'Ctrl+R',
        click() {
          mainWindow.webContents.reload();
        }
      }, {
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle &Developer Tools',
        accelerator: 'Alt+Ctrl+I',
        click() {
          mainWindow.toggleDevTools();
        }
      }] : [{
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click() {
          shell.openExternal('http://electron.atom.io');
        }
      }, {
        label: 'Documentation',
        click() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
        }
      }, {
        label: 'Community Discussions',
        click() {
          shell.openExternal('https://discuss.atom.io/c/electron');
        }
      }, {
        label: 'Search Issues',
        click() {
          shell.openExternal('https://github.com/atom/electron/issues');
        }
      }]
    }];
    menu = Menu.buildFromTemplate(template);
    mainWindow.setMenu(menu);
  }
});
<|endoftext|>


<commit_before>var fs = require('fs');

var timeout = 60;
var path = "/smoke/";
var exitCode = 0;

var system = require('system');
var args = system.args;
if (args[1]) {
  timeout = parseInt(args[1]);
}

var list = fs.list("." + path);
var files = [];
for(var i = 0; i < list.length; i++){
  var file = list[i]
  if (file.indexOf('.html') > 0) {
    files.unshift(file);
  }
}

var runTest = function (file, callback) {
  var out = []
  var tId;
  var processOutput = function() {
    var expectedarry = page.evaluateJavaScript(function () {
      var retarry = [];
      $('expectedoutput').contents().filter(function(){
        return this.nodeType == 8;
      }).each(function(i, e){
          retarry.push($.trim(e.nodeValue))
        });

      return retarry;
    });

    var gotoutput = out.join("\n")
    var expectedoutput = expectedarry.join("\n")
    if (gotoutput !== expectedoutput) {
      console.log('ERROR: unexpected output expected::::');
      console.log(expectedoutput)
      console.log('but got::::::::::::::::::::::::::::::');
      console.log(gotoutput)
      console.log("\n")
    }
    page.close();
    callback();
  }
  var updateTimer = function(ms) {
    if (ms == null) {
      var pageTimeout = page.evaluateJavaScript(function () {
        return $('testingtimer').contents()[0];
      });
      ms = pageTimeout == null ? timeout : Number(pageTimeout.nodeValue);
    }
    if (tId) clearTimeout(tId);
    tId = setTimeout(processOutput, ms);
  }
  var page = require('webpage').create();
  page.onError = function(msg, trace) {
    var msgStack = ['ERROR: ' + msg];
    if (trace && trace.length) {
      msgStack.push('TRACE:');
      trace.forEach(function(t) {
        msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line + (t.function ? ' (in function ' + t.function +')' : ''));
      });
    }
    console.error(msgStack.join('\n'));
    updateTimer(0);
    exitCode = 1;
  };
  page.onInitialized = function () {
    // this is executed 'after the web page is created but before a URL is loaded.
    // The callback may be used to change global objects.' ... according to the docs
    page.evaluate(function () {
      window.addEventListener('dreeminit', function (e) { console.log('~~DONE~~') }, false);
    });
    // add missing methods to phantom, specifically Function.bind(). See https://github.com/ariya/phantomjs/issues/10522
    page.injectJs('./lib/es5-shim.min.js');
  };
  page.onResourceError = function(resourceError) {
    console.log('RESOURCE ERROR: ' + resourceError.errorString + ', URL: ' + resourceError.url + ', File: ' + file);
    updateTimer(0);
  };
  page.onConsoleMessage = function(msg, lineNum, sourceId) {
    if (msg === '~~DONE~~') {
      updateTimer();
      return;
    }
    out.push(msg)
//    console.log(msg)
  };
  page.open('http://127.0.0.1:8080' + path + file + '?test');
}

var loadNext = function() {
  var file = files.pop();
  if (file) {
    console.log("RUNNING TEST: ", file)
    runTest(file, loadNext);
  } else {
    phantom.exit(exitCode);
  }
}

loadNext();
<commit_msg>phantom filter<commit_after>var fs = require('fs');

var timeout = 60;
var filter = undefined
var path = "/smoke/";
var exitCode = 0;

var system = require('system');
var args = system.args;

if (args[1]) {
  if(parseInt(args[1]) == args[1])
    timeout = parseInt(args[1]);
  else
    filter = args[1]
}

var list = fs.list("." + path);
var files = [];
for(var i = 0; i < list.length; i++){
  var file = list[i]
  if (file.indexOf('.html') > 0) {
    files.unshift(file);
  }
}

var runTest = function (file, callback) {
  var out = []
  var tId;
  var processOutput = function() {
    var expectedarry = page.evaluateJavaScript(function () {
      var retarry = [];
      $('expectedoutput').contents().filter(function(){
        return this.nodeType == 8;
      }).each(function(i, e){
          retarry.push($.trim(e.nodeValue))
        });

      return retarry;
    });

    var gotoutput = out.join("\n")
    var expectedoutput = expectedarry.join("\n")
    if (gotoutput !== expectedoutput) {
      console.log('ERROR: unexpected output expected::::');
      console.log(expectedoutput)
      console.log('but got::::::::::::::::::::::::::::::');
      console.log(gotoutput)
      console.log("\n")
    }
    page.close();
    callback();
  }
  var updateTimer = function(ms) {
    if (ms == null) {
      var pageTimeout = page.evaluateJavaScript(function () {
        return $('testingtimer').contents()[0];
      });
      ms = pageTimeout == null ? timeout : Number(pageTimeout.nodeValue);
    }
    if (tId) clearTimeout(tId);
    tId = setTimeout(processOutput, ms);
  }
  var page = require('webpage').create();
  page.onError = function(msg, trace) {
    var msgStack = ['ERROR: ' + msg];
    if (trace && trace.length) {
      msgStack.push('TRACE:');
      trace.forEach(function(t) {
        msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line + (t.function ? ' (in function ' + t.function +')' : ''));
      });
    }
    console.error(msgStack.join('\n'));
    updateTimer(0);
    exitCode = 1;
  };
  page.onInitialized = function () {
    // this is executed 'after the web page is created but before a URL is loaded.
    // The callback may be used to change global objects.' ... according to the docs
    page.evaluate(function () {
      window.addEventListener('dreeminit', function (e) { console.log('~~DONE~~') }, false);
    });
    // add missing methods to phantom, specifically Function.bind(). See https://github.com/ariya/phantomjs/issues/10522
    page.injectJs('./lib/es5-shim.min.js');
  };
  page.onResourceError = function(resourceError) {
    console.log('RESOURCE ERROR: ' + resourceError.errorString + ', URL: ' + resourceError.url + ', File: ' + file);
    updateTimer(0);
  };
  page.onConsoleMessage = function(msg, lineNum, sourceId) {
    if (msg === '~~DONE~~') {
      updateTimer();
      return;
    }
    out.push(msg)
//    console.log(msg)
  };
  page.open('http://127.0.0.1:8080' + path + file + '?test');
}

var loadNext = function() {
  var file = files.pop();
  if (file) {
    if(filter !== undefined){
      if(file.indexOf(filter) !== -1){
        console.log("FILTERED TEST: ", file)
        runTest(file, loadNext);
      }
      else loadNext()
    }
    else{
      console.log("RUNNING TEST: ", file)
      runTest(file, loadNext);
    }
  } else {
    phantom.exit(exitCode);
  }
}

loadNext();
<|endoftext|>


<commit_before>'use strict';

var self = post;
module.exports = self;

var async = require('async');
var _ = require('underscore');

var configHandler = require('../../common/configHandler.js');

function post(req, res) {
  var bag = {
    reqBody: req.body,
    resBody: {},
    component: 'workers'
  };

  bag.who = util.format('workers|%s', self.name);
  logger.info(bag.who, 'Starting');

  async.series([
      _checkInputParams.bind(null, bag),
      _get.bind(null, bag),
      _updateWorker.bind(null, bag),
      _post.bind(null, bag)
    ],
    function (err) {
      logger.info(bag.who, 'Completed');
      if (err)
        return respondWithError(res, err);

      sendJSONResponse(res, bag.resBody);
    }
  );
}

function _checkInputParams(bag, next) {
  var who = bag.who + '|' + _checkInputParams.name;
  logger.verbose(who, 'Inside');

  if (!_.has(bag.reqBody, 'address') || _.isEmpty(bag.reqBody.address))
    return next(
      new ActErr(who, ActErr.DataNotFound,
        'Missing body data :address')
    );

  bag.workerAddress = bag.reqBody.address;

  if (!_.has(bag.reqBody, 'name'))
    return next(
      new ActErr(who, ActErr.DataNotFound,
        'Missing body data :name')
    );

  bag.workerName = bag.reqBody.name;

  return next();
}

function _get(bag, next) {
  var who = bag.who + '|' + _get.name;
  logger.verbose(who, 'Inside');

  configHandler.get(bag.component,
    function (err, workers) {
      if (err)
        return next(
          new ActErr(who, ActErr.DataNotFound,
            'Failed to get ' + bag.component, err)
        );

      if (!_.isArray(workers))
        return next(
          new ActErr(who, ActErr.DataNotFound,
            'No configuration in database for ' + bag.component)
        );

      bag.config = workers;
      return next();
    }
  );
}

function _updateWorker(bag, next) {
  var who = bag.who + '|' + _updateWorker.name;
  logger.verbose(who, 'Inside');

  var newWorker = {
    address: bag.workerAddress,
    name: bag.workerName,
    isInitialized: false,
    isInstalled: false,
    port: 2377
  };

  var nameInUse = _.findWhere(bag.config, {name: bag.workerName});
  if (nameInUse && (nameInUse.address !== bag.workerAddress))
    return next(
      new ActErr(who, ActErr.OperationFailed,
        'Worker name ' + bag.workerName + ' is already in use.')
    );

  var workerExists = false;
  _.each(bag.config,
    function (worker) {
      if (worker.address === bag.workerAddress) {
        workerExists = true;
        _.extend(worker, newWorker);
      }
    }
  );

  if (!workerExists)
    bag.config.push(newWorker);

  return next();
}

function _post(bag, next) {
  var who = bag.who + '|' + _post.name;
  logger.verbose(who, 'Inside');

  configHandler.put(bag.component, bag.config,
    function (err, response) {
      if (err)
        return next(
          new ActErr(who, ActErr.OperationFailed,
            'Failed to update config for ' + bag.component, err)
        );

      bag.resBody = response;
      return next();
    }
  );
}
<commit_msg>Only default isInstalled and isInitialized to false for new nodes<commit_after>'use strict';

var self = post;
module.exports = self;

var async = require('async');
var _ = require('underscore');

var configHandler = require('../../common/configHandler.js');

function post(req, res) {
  var bag = {
    reqBody: req.body,
    resBody: {},
    component: 'workers'
  };

  bag.who = util.format('workers|%s', self.name);
  logger.info(bag.who, 'Starting');

  async.series([
      _checkInputParams.bind(null, bag),
      _get.bind(null, bag),
      _updateWorker.bind(null, bag),
      _post.bind(null, bag)
    ],
    function (err) {
      logger.info(bag.who, 'Completed');
      if (err)
        return respondWithError(res, err);

      sendJSONResponse(res, bag.resBody);
    }
  );
}

function _checkInputParams(bag, next) {
  var who = bag.who + '|' + _checkInputParams.name;
  logger.verbose(who, 'Inside');

  if (!_.has(bag.reqBody, 'address') || _.isEmpty(bag.reqBody.address))
    return next(
      new ActErr(who, ActErr.DataNotFound,
        'Missing body data :address')
    );

  bag.workerAddress = bag.reqBody.address;

  if (!_.has(bag.reqBody, 'name'))
    return next(
      new ActErr(who, ActErr.DataNotFound,
        'Missing body data :name')
    );

  bag.workerName = bag.reqBody.name;

  return next();
}

function _get(bag, next) {
  var who = bag.who + '|' + _get.name;
  logger.verbose(who, 'Inside');

  configHandler.get(bag.component,
    function (err, workers) {
      if (err)
        return next(
          new ActErr(who, ActErr.DataNotFound,
            'Failed to get ' + bag.component, err)
        );

      if (!_.isArray(workers))
        return next(
          new ActErr(who, ActErr.DataNotFound,
            'No configuration in database for ' + bag.component)
        );

      bag.config = workers;
      return next();
    }
  );
}

function _updateWorker(bag, next) {
  var who = bag.who + '|' + _updateWorker.name;
  logger.verbose(who, 'Inside');

  var newWorker = {
    address: bag.workerAddress,
    name: bag.workerName,
    port: 2377
  };

  var nameInUse = _.findWhere(bag.config, {name: bag.workerName});
  if (nameInUse && (nameInUse.address !== bag.workerAddress))
    return next(
      new ActErr(who, ActErr.OperationFailed,
        'Worker name ' + bag.workerName + ' is already in use.')
    );

  var workerExists = false;
  _.each(bag.config,
    function (worker) {
      if (worker.address === bag.workerAddress) {
        workerExists = true;
        _.extend(worker, newWorker);
      }
    }
  );

  if (!workerExists) {
    newWorker.isInitialized = false;
    newWorker.isInstalled = false;
    bag.config.push(newWorker);
  }

  return next();
}

function _post(bag, next) {
  var who = bag.who + '|' + _post.name;
  logger.verbose(who, 'Inside');

  configHandler.put(bag.component, bag.config,
    function (err, response) {
      if (err)
        return next(
          new ActErr(who, ActErr.OperationFailed,
            'Failed to update config for ' + bag.component, err)
        );

      bag.resBody = response;
      return next();
    }
  );
}
<|endoftext|>


<commit_before>import ons from 'onsenui';
import {Router} from 'aurelia-router';
import {inject, bindable} from 'aurelia-framework';
import {Database} from '../services/db';
import {Search} from '../services/search';
import {Storage} from '../services/storage';

@inject(Router, Database, Storage, Search)
export class Home {
  @bindable selection;
  @bindable currentResults;
  results;
  isFiltered;

  constructor(router, db, storage, search) {
    this.router = router;
    this.db = db;
    this.storage = storage;
    this.search = search;
  }

  activate(params) {

  }

  attached() {
    if (ons.platform.isAndroid()) {
      this._map.classList.add('map--material');
    }
    this.map = L.map(this._map, {
      attributionControl: false
    });

    this.basemap = L.gridLayer.googleMutant({
      type: 'roadmap', // valid values are 'roadmap', 'satellite', 'terrain' and 'hybrid'
      styles: [{
        featureType: "poi",
        elementType: "labels.icon",
        stylers: [{ visibility: "off" }]
      }]
    }).addTo(this.map);

    this.buildingsLayer = L.markerClusterGroup({
      maxClusterRadius: 40
    }).addTo(this.map);

    this.markers = L.featureGroup().addTo(this.map);

    this.locateControl = L.control.locate({
      showPopup: false,
      locateControl: {}
    }).addTo(this.map);
    this.locateControl._start = this.locateControl.start.bind(this.locateControl);
    this.locateControl._stop = this.locateControl.stop.bind(this.locateControl);
    this.locateControl._setView = this.locateControl.setView.bind(this.locateControl);
    this.locateControl.stop = this.onLocateControlStop.bind(this);
    this.locateControl.start = this.onLocateControlStart.bind(this);
    this.locateControl.setView = this.onLocateControlSetView.bind(this);

    let mapbounds = this.storage.getItem('mapbounds');
    if (mapbounds) {
      this.map.fitBounds(mapbounds);
    } else {
      this.map.setView([46.801111, 8.226667], 7);
    }

    if (this.storage.getItem('geolocation')) {
      this.locateControl.start();
    }

    this.map.on('moveend', this.updateMapView, this);
    this.markers.on('click', this.onMarkerClick, this);
    this.buildingsLayer.on('click', this.onBuildingClick, this);
    this.buildings = this.db.data.buildings;
  }

  onBuildingClick(e) {
    if (this.selection === e.layer.data && this.selection.rooms.length === 1) {
      this.showRoom(this.selection.rooms[0]);
    } else {
      this.selection = e.layer.data;
    }
  }

  onMarkerClick(e) {
    if (this.selection && this.selection.rooms.length === 1) {
      this.showRoom(this.selection.rooms[0]);
    }
  }

  deselect() {
    this.selection = null;
  }

  selectionChanged(newValue, oldValue) {
    this.markers.clearLayers();
    if (newValue) {
      let marker = L.marker([newValue.lat, newValue.lng]);
      this.markers.addLayer(marker);
      this.roomlist.scrollTop = 0;
      setTimeout(() => {
        this.map.invalidateSize({
          pan: false
        });
        if (!this.map.getBounds().contains(marker.getLatLng())) {
          this.locateControl._onDrag();
          this.map.setView(marker.getLatLng(), this.map.getZoom());
          marker._bringToFront();
        }
      }, 50);
    } else {
      setTimeout(() => {
        this.map.invalidateSize({
          pan: false
        });
      }, 50);
    }
  }

  set buildings(value) {
    this.buildingsLayer.clearLayers();
    value.forEach(building => {
      // TODO: marker icons
      let myIcon = L.divIcon({
        className: 'leaflet-system-icon fa fa-deaf',
        iconSize: 22
      });
      let marker = L.marker([building.lat, building.lng], {icon: myIcon});
      marker.data = building;
      this.buildingsLayer.addLayer(marker);
    });
  }

  get buildings() {
    return this.buildingsLayer.getLayers().map(layer => layer.data);
  }

  updateMapView(evt) {
    let bounds = evt.target.getBounds();
    this.storage.setItem('mapbounds', [
      [bounds.getSouth(), bounds.getWest()],
      [bounds.getNorth(), bounds.getEast()]
    ]);
  }

  onLocateControlStart() {
    this.storage.setItem('geolocation', true);
    this.locateControl.isLocatingStart = true;
    this.locateControl._start();
  }

  onLocateControlStop() {
    this.storage.setItem('geolocation', false);
    this.locateControl._stop();
  }

  onLocateControlSetView() {
    if (this.locateControl.isLocatingStart) {
      this.locateControl.isLocatingStart = false;
      this.locateControl.options.keepCurrentZoomLevel = false;
      this.locateControl.options.locateOptions.maxZoom = this.map.getZoom() < 15 ? 15 : this.map.getZoom();
      this.locateControl._setView();
      this.locateControl.options.keepCurrentZoomLevel = true;
      this.locateControl.options.locateOptions.maxZoom = Infinity;
    } else {
      this.locateControl._setView();
    }
  }

  getRoomName(room) {
    let name = `${room.raum} ${room.raumnummer}`.trim();
    if (!name) {
      name = room.gebaeude;
    }
    if (!name) {
      let type = this.db.data.roomtypes.find((type) => {
        return type.typID === room.typID;
      });
      name = type.typ;
    }
    return name;
  }

  showMenu() {
    let menu = document.getElementById('menu');
    menu.open();
  }

  showSearch() {
    this._search.show();
    this._searchinput.focus();
    this.isSearching = true;
    this.currentSearchText = this.searchText;
    this.currentResults = this.results;
  }

  cancelSearch() {
    this._search.hide();
    this.currentSearchText = '';
    this.currentResults = {};
    this.isSearching = false;
  }

  clearSearch() {
    this.searchText = this.currentSearchText = '';
    this.buildings = this.db.data.buildings;
    this.selection = null;
  }

  showList() {
    this.router.navigateToRoute('list');
  }

  showRoom(room) {
    this.router.navigateToRoute('room', {id: room.anlageID});
  }

  searchCategory(item) {
    this.isFiltered = true;
    this._search.hide();
    this.searchText = this.currentSearchText = item.typ;
    this.buildings = this.db.queryBuildingsByRoomType(item);
    this.results = this.currentResults = {
      buildings: this.buildings,
      locations: []
    };
    this.selection = null;
    this.zoomToNearest();
  }

  zoomToNearest() {
    let center = this.map.getCenter();
    let closest = L.GeometryUtil.closestLayer(this.map, this.buildingsLayer.getLayers(), center);
    if (!this.map.getBounds().contains(closest.layer.getLatLng())) {
      let bounds = L.latLngBounds(closest.layer.getLatLng(), center);
      this.locateControl._onDrag();
      this.map.fitBounds(bounds, {
        maxZoom: this.map.getZoom(),
        padding: [40, 40]
      });
    }
  }

  clearCurrentSearch() {
    this.currentSearchText = '';
    this.currentResults = {
      buildings: [],
      locations: []
    };
    this._searchinput.focus();
  }

  onBuildingResultClick(building) {
    if (!this.isFiltered) {
      this.buildings = this.db.data.buildings;
    }
    this.searchText = this.currentSearchText;
    this.results = this.currentResults;
    this.selection = null;
    this._search.hide();
    this.map.once('moveend', () => {
      this.selection = building;
    });
    this.locateControl._onDrag();
    this.map.setView([building.lat, building.lng], 17);
  }

  onLocationResultClick(location) {
    if (!this.isFiltered) {
      this.buildings = this.db.data.buildings;
    }
    this.searchText = this.currentSearchText;
    this.results = this.currentResults;
    this.selection = null;
    this._search.hide();
    this.locateControl._onDrag();
    this.map.fitBounds(location.bounds);
  }

  onSearch() {
    this.currentResults = this.search.execute(this.currentSearchText, 20);
  }

  onSearchInput() {
    this.isFiltered = false;
    this.currentResults = this.search.execute(this._searchinput.value, 10);
  }
}
<commit_msg>open room detail on double click<commit_after>import ons from 'onsenui';
import {Router} from 'aurelia-router';
import {inject, bindable} from 'aurelia-framework';
import {Database} from '../services/db';
import {Search} from '../services/search';
import {Storage} from '../services/storage';

@inject(Router, Database, Storage, Search)
export class Home {
  @bindable selection;
  @bindable currentResults;
  results;
  isFiltered;

  constructor(router, db, storage, search) {
    this.router = router;
    this.db = db;
    this.storage = storage;
    this.search = search;
  }

  activate(params) {

  }

  attached() {
    if (ons.platform.isAndroid()) {
      this._map.classList.add('map--material');
    }
    this.map = L.map(this._map, {
      attributionControl: false
    });

    this.basemap = L.gridLayer.googleMutant({
      type: 'roadmap', // valid values are 'roadmap', 'satellite', 'terrain' and 'hybrid'
      styles: [{
        featureType: "poi",
        elementType: "labels.icon",
        stylers: [{ visibility: "off" }]
      }]
    }).addTo(this.map);

    this.buildingsLayer = L.markerClusterGroup({
      maxClusterRadius: 40
    }).addTo(this.map);

    this.markers = L.featureGroup().addTo(this.map);

    this.locateControl = L.control.locate({
      showPopup: false,
      locateControl: {}
    }).addTo(this.map);
    this.locateControl._start = this.locateControl.start.bind(this.locateControl);
    this.locateControl._stop = this.locateControl.stop.bind(this.locateControl);
    this.locateControl._setView = this.locateControl.setView.bind(this.locateControl);
    this.locateControl.stop = this.onLocateControlStop.bind(this);
    this.locateControl.start = this.onLocateControlStart.bind(this);
    this.locateControl.setView = this.onLocateControlSetView.bind(this);

    let mapbounds = this.storage.getItem('mapbounds');
    if (mapbounds) {
      this.map.fitBounds(mapbounds);
    } else {
      this.map.setView([46.801111, 8.226667], 7);
    }

    if (this.storage.getItem('geolocation')) {
      this.locateControl.start();
    }

    this.map.on('moveend', this.updateMapView, this);
    this.markers.on('click', this.onMarkerClick, this);
    this.buildingsLayer.on('click', this.onBuildingClick, this);
    this.buildingsLayer.on('dblclick', this.onBuildingDoubleClick, this);
    this.buildings = this.db.data.buildings;
  }

  onBuildingClick(e) {
    if (this.selection === e.layer.data && this.selection.rooms.length === 1) {
      this.showRoom(this.selection.rooms[0]);
    } else {
      this.selection = e.layer.data;
    }
  }

  onBuildingDoubleClick(e) {
    this.selection = e.layer.data;
    if (this.selection.rooms.length === 1) {
      this.showRoom(this.selection.rooms[0]);
    }
  }

  onMarkerClick(e) {
    if (this.selection && this.selection.rooms.length === 1) {
      this.showRoom(this.selection.rooms[0]);
    }
  }

  deselect() {
    this.selection = null;
  }

  selectionChanged(newValue, oldValue) {
    this.markers.clearLayers();
    if (newValue) {
      let marker = L.marker([newValue.lat, newValue.lng]);
      this.markers.addLayer(marker);
      this.roomlist.scrollTop = 0;
      setTimeout(() => {
        this.map.invalidateSize({
          pan: false
        });
        if (!this.map.getBounds().contains(marker.getLatLng())) {
          this.locateControl._onDrag();
          this.map.setView(marker.getLatLng(), this.map.getZoom());
          marker._bringToFront();
        }
      }, 50);
    } else {
      setTimeout(() => {
        this.map.invalidateSize({
          pan: false
        });
      }, 50);
    }
  }

  set buildings(value) {
    this.buildingsLayer.clearLayers();
    value.forEach(building => {
      // TODO: marker icons
      let myIcon = L.divIcon({
        className: 'leaflet-system-icon fa fa-deaf',
        iconSize: 22
      });
      let marker = L.marker([building.lat, building.lng], {icon: myIcon});
      marker.data = building;
      this.buildingsLayer.addLayer(marker);
    });
  }

  get buildings() {
    return this.buildingsLayer.getLayers().map(layer => layer.data);
  }

  updateMapView(evt) {
    let bounds = evt.target.getBounds();
    this.storage.setItem('mapbounds', [
      [bounds.getSouth(), bounds.getWest()],
      [bounds.getNorth(), bounds.getEast()]
    ]);
  }

  onLocateControlStart() {
    this.storage.setItem('geolocation', true);
    this.locateControl.isLocatingStart = true;
    this.locateControl._start();
  }

  onLocateControlStop() {
    this.storage.setItem('geolocation', false);
    this.locateControl._stop();
  }

  onLocateControlSetView() {
    if (this.locateControl.isLocatingStart) {
      this.locateControl.isLocatingStart = false;
      this.locateControl.options.keepCurrentZoomLevel = false;
      this.locateControl.options.locateOptions.maxZoom = this.map.getZoom() < 15 ? 15 : this.map.getZoom();
      this.locateControl._setView();
      this.locateControl.options.keepCurrentZoomLevel = true;
      this.locateControl.options.locateOptions.maxZoom = Infinity;
    } else {
      this.locateControl._setView();
    }
  }

  getRoomName(room) {
    let name = `${room.raum} ${room.raumnummer}`.trim();
    if (!name) {
      name = room.gebaeude;
    }
    if (!name) {
      let type = this.db.data.roomtypes.find((type) => {
        return type.typID === room.typID;
      });
      name = type.typ;
    }
    return name;
  }

  showMenu() {
    let menu = document.getElementById('menu');
    menu.open();
  }

  showSearch() {
    this._search.show();
    this._searchinput.focus();
    this.isSearching = true;
    this.currentSearchText = this.searchText;
    this.currentResults = this.results;
  }

  cancelSearch() {
    this._search.hide();
    this.currentSearchText = '';
    this.currentResults = {};
    this.isSearching = false;
  }

  clearSearch() {
    this.searchText = this.currentSearchText = '';
    this.buildings = this.db.data.buildings;
    this.selection = null;
  }

  showList() {
    this.router.navigateToRoute('list');
  }

  showRoom(room) {
    this.router.navigateToRoute('room', {id: room.anlageID});
  }

  searchCategory(item) {
    this.isFiltered = true;
    this._search.hide();
    this.searchText = this.currentSearchText = item.typ;
    this.buildings = this.db.queryBuildingsByRoomType(item);
    this.results = this.currentResults = {
      buildings: this.buildings,
      locations: []
    };
    this.selection = null;
    this.zoomToNearest();
  }

  zoomToNearest() {
    let center = this.map.getCenter();
    let closest = L.GeometryUtil.closestLayer(this.map, this.buildingsLayer.getLayers(), center);
    if (!this.map.getBounds().contains(closest.layer.getLatLng())) {
      let bounds = L.latLngBounds(closest.layer.getLatLng(), center);
      this.locateControl._onDrag();
      this.map.fitBounds(bounds, {
        maxZoom: this.map.getZoom(),
        padding: [40, 40]
      });
    }
  }

  clearCurrentSearch() {
    this.currentSearchText = '';
    this.currentResults = {
      buildings: [],
      locations: []
    };
    this._searchinput.focus();
  }

  onBuildingResultClick(building) {
    if (!this.isFiltered) {
      this.buildings = this.db.data.buildings;
    }
    this.searchText = this.currentSearchText;
    this.results = this.currentResults;
    this.selection = null;
    this._search.hide();
    this.map.once('moveend', () => {
      this.selection = building;
    });
    this.locateControl._onDrag();
    this.map.setView([building.lat, building.lng], 17);
  }

  onLocationResultClick(location) {
    if (!this.isFiltered) {
      this.buildings = this.db.data.buildings;
    }
    this.searchText = this.currentSearchText;
    this.results = this.currentResults;
    this.selection = null;
    this._search.hide();
    this.locateControl._onDrag();
    this.map.fitBounds(location.bounds);
  }

  onSearch() {
    this.currentResults = this.search.execute(this.currentSearchText, 20);
  }

  onSearchInput() {
    this.isFiltered = false;
    this.currentResults = this.search.execute(this._searchinput.value, 10);
  }
}
<|endoftext|>


<commit_before>import { app, BrowserWindow, Menu, shell, ipcMain } from 'electron';
import os from 'os';
import open from 'open';
import { autoUpdater } from 'electron-updater';
import * as chromeFinder from 'lighthouse/chrome-launcher/chrome-finder';
import { sync as syncActions } from './actions';

let menu;
let template;
let mainWindow = null;

if (process.env.NODE_ENV === 'production') {
  const sourceMapSupport = require('source-map-support'); // eslint-disable-line
  sourceMapSupport.install();
}

if (process.env.NODE_ENV === 'development') {
  require('electron-debug')(); // eslint-disable-line global-require
  const path = require('path'); // eslint-disable-line
  const p = path.join(__dirname, '..', 'app', 'node_modules'); // eslint-disable-line
  require('module').globalPaths.push(p); // eslint-disable-line
}

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

const installExtensions = async () => {
  if (process.env.NODE_ENV === 'development') {
    const installer = require('electron-devtools-installer'); // eslint-disable-line global-require

    const extensions = [
      'REACT_DEVELOPER_TOOLS',
      'REDUX_DEVTOOLS'
    ];

    const forceDownload = !!process.env.UPGRADE_EXTENSIONS;

    // TODO: Use async interation statement.
    //       Waiting on https://github.com/tc39/proposal-async-iteration
    //       Promises will fail silently, which isn't what we want in development
    return Promise
      .all(extensions.map(name => installer.default(installer[name], forceDownload)))
      .catch(console.log);
  }
};

app.on('ready', async () => {
  await installExtensions();
  const resizable = (process.env.NODE_ENV === 'development' || process.env.BUILD === 'dev');

  mainWindow = new BrowserWindow({
    show: false,
    width: 663,
    height: 769,
    resizable: resizable
  });

  mainWindow.loadURL(`file://${__dirname}/app.html`);

  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.show();
    mainWindow.focus();
    checkUpdates();
  });

  mainWindow.webContents.on('new-window', function(event, url){
    event.preventDefault();
    let platform = os.platform();
    let chromeInstalls = chromeFinder[platform]();
    if(chromeInstalls.length === 0){
      // no chrome installs found, open user's default browser
      open(url);
    } else {
      open(url, chromeInstalls[0], function(error){
        if(error){
          // couldn't open chrome, try OS default
          open(url);
        }
      });
    }
  });
  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  if (process.env.NODE_ENV === 'development' || process.env.BUILD === 'dev') {
    mainWindow.openDevTools();
    mainWindow.webContents.on('context-menu', (e, props) => {
      const { x, y } = props;

      Menu.buildFromTemplate([{
        label: 'Inspect element',
        click() {
          mainWindow.inspectElement(x, y);
        }
      }]).popup(mainWindow);
    });
  }

  if (process.platform === 'darwin') {
    template = [{
      label: 'Tidepool Uploader',
      submenu: [{
        label: 'About Tidepool Uploader',
        selector: 'orderFrontStandardAboutPanel:'
      }, {
        type: 'separator'
      }, {
        label: 'Hide Tidepool Uploader',
        accelerator: 'Command+H',
        selector: 'hide:'
      }, {
        label: 'Hide Others',
        accelerator: 'Command+Shift+H',
        selector: 'hideOtherApplications:'
      }, {
        label: 'Show All',
        selector: 'unhideAllApplications:'
      }, {
        type: 'separator'
      }, {
        label: 'Quit',
        accelerator: 'Command+Q',
        click() {
          app.quit();
        }
      }]
    }, {
      label: 'Edit',
      submenu: [{
        label: 'Undo',
        accelerator: 'Command+Z',
        selector: 'undo:'
      }, {
        label: 'Redo',
        accelerator: 'Shift+Command+Z',
        selector: 'redo:'
      }, {
        type: 'separator'
      }, {
        label: 'Cut',
        accelerator: 'Command+X',
        selector: 'cut:'
      }, {
        label: 'Copy',
        accelerator: 'Command+C',
        selector: 'copy:'
      }, {
        label: 'Paste',
        accelerator: 'Command+V',
        selector: 'paste:'
      }, {
        label: 'Select All',
        accelerator: 'Command+A',
        selector: 'selectAll:'
      }]
    }, {
      label: 'View',
      submenu: (process.env.NODE_ENV === 'development' || process.env.BUILD === 'dev') ?
      [
        {
          label: 'Reload',
          accelerator: 'Command+R',
          click() {
            mainWindow.webContents.reload();
          }
        }, {
          label: 'Toggle Full Screen',
          accelerator: 'Ctrl+Command+F',
          click() {
            mainWindow.setFullScreen(!mainWindow.isFullScreen());
          }
        }, {
          label: 'Toggle Developer Tools',
          accelerator: 'Alt+Command+I',
          click() {
            mainWindow.toggleDevTools();
          }
        }
      ] : [
        {
          label: 'Toggle Full Screen',
          accelerator: 'Ctrl+Command+F',
          click() {
            mainWindow.setFullScreen(!mainWindow.isFullScreen());
          }
        }, {
          label: 'Toggle Developer Tools',
          accelerator: 'Alt+Command+I',
          click() {
            mainWindow.toggleDevTools();
          }
        }
      ]
    }, {
      label: 'Window',
      submenu: [{
        label: 'Minimize',
        accelerator: 'Command+M',
        selector: 'performMiniaturize:'
      }, {
        label: 'Close',
        accelerator: 'Command+W',
        selector: 'performClose:'
      }, {
        type: 'separator'
      }, {
        label: 'Bring All to Front',
        selector: 'arrangeInFront:'
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click() {
          shell.openExternal('http://electron.atom.io');
        }
      }, {
        label: 'Documentation',
        click() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
        }
      }, {
        label: 'Community Discussions',
        click() {
          shell.openExternal('https://discuss.atom.io/c/electron');
        }
      }, {
        label: 'Search Issues',
        click() {
          shell.openExternal('https://github.com/atom/electron/issues');
        }
      }]
    }];

    menu = Menu.buildFromTemplate(template);
    Menu.setApplicationMenu(menu);
  } else {
    template = [{
      label: '&File',
      submenu: [{
        label: '&Open',
        accelerator: 'Ctrl+O'
      }, {
        label: '&Close',
        accelerator: 'Ctrl+W',
        click() {
          mainWindow.close();
        }
      }]
    }, {
      label: '&View',
      submenu: (process.env.NODE_ENV === 'development' || process.env.BUILD === 'dev') ? [{
        label: '&Reload',
        accelerator: 'Ctrl+R',
        click() {
          mainWindow.webContents.reload();
        }
      }, {
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle &Developer Tools',
        accelerator: 'Alt+Ctrl+I',
        click() {
          mainWindow.toggleDevTools();
        }
      }] : [{
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle &Developer Tools',
        accelerator: 'Alt+Ctrl+I',
        click() {
          mainWindow.toggleDevTools();
        }
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click() {
          shell.openExternal('http://electron.atom.io');
        }
      }, {
        label: 'Documentation',
        click() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
        }
      }, {
        label: 'Community Discussions',
        click() {
          shell.openExternal('https://discuss.atom.io/c/electron');
        }
      }, {
        label: 'Search Issues',
        click() {
          shell.openExternal('https://github.com/atom/electron/issues');
        }
      }]
    }];
    menu = Menu.buildFromTemplate(template);
    mainWindow.setMenu(menu);
  }
});

function checkUpdates(){
  // in production NODE_ENV or *any* type of BUILD (including BUILD === 'dev')
  // we check for updates, but not if NODE_ENV is 'development' and BUILD is unset
  // this prevents a Webpack build error that masks other build errors during local development
  if (process.env.NODE_ENV === 'production' || process.env.BUILD) {
    autoUpdater.checkForUpdates();
  }
}

setInterval(checkUpdates, 1000 * 60 * 60 * 24);

let manualCheck = false;

function sendAction(action) {
  mainWindow.webContents.send('action', action);
}

autoUpdater.on('checking-for-update', () => {
  if(manualCheck) {
    manualCheck = false;
    sendAction(syncActions.manualCheckingForUpdates());
  } else {
    sendAction(syncActions.autoCheckingForUpdates());
  }
});

autoUpdater.on('update-available', (ev, info) => {
  sendAction(syncActions.updateAvailable(info));
  /*
  Example `info`
  {
    "version":"0.310.0-alpha",
    "releaseDate":"2017-04-03T22:29:55.809Z",
    "url":"https://github.com/tidepool-org/chrome-uploader/releases/download/v0.310.0-alpha/tidepool-uploader-dev-0.310.0-alpha-mac.zip",
    "releaseJsonUrl":"https://github.com//tidepool-org/chrome-uploader/releases/download/v0.310.0-alpha/latest-mac.json"
  }
   */
});

autoUpdater.on('update-not-available', (ev, info) => {
  sendAction(syncActions.updateNotAvailable(info));
});

autoUpdater.on('error', (ev, err) => {
  sendAction(syncActions.autoUpdateError(err));
});

autoUpdater.on('update-downloaded', (ev, info) => {
  sendAction(syncActions.updateDownloaded(info));
});

ipcMain.on('autoUpdater', (event, arg) => {
  if(arg === 'checkForUpdates') {
    manualCheck = true;
  }
  autoUpdater[arg]();
});

if(!app.isDefaultProtocolClient('tidepoolupload')){
  app.setAsDefaultProtocolClient('tidepoolupload');
}

app.on('window-all-closed', () => {
  app.quit();
});
<commit_msg>update help menus<commit_after>import { app, BrowserWindow, Menu, shell, ipcMain } from 'electron';
import os from 'os';
import open from 'open';
import { autoUpdater } from 'electron-updater';
import * as chromeFinder from 'lighthouse/chrome-launcher/chrome-finder';
import { sync as syncActions } from './actions';

let menu;
let template;
let mainWindow = null;

if (process.env.NODE_ENV === 'production') {
  const sourceMapSupport = require('source-map-support'); // eslint-disable-line
  sourceMapSupport.install();
}

if (process.env.NODE_ENV === 'development') {
  require('electron-debug')(); // eslint-disable-line global-require
  const path = require('path'); // eslint-disable-line
  const p = path.join(__dirname, '..', 'app', 'node_modules'); // eslint-disable-line
  require('module').globalPaths.push(p); // eslint-disable-line
}

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

const installExtensions = async () => {
  if (process.env.NODE_ENV === 'development') {
    const installer = require('electron-devtools-installer'); // eslint-disable-line global-require

    const extensions = [
      'REACT_DEVELOPER_TOOLS',
      'REDUX_DEVTOOLS'
    ];

    const forceDownload = !!process.env.UPGRADE_EXTENSIONS;

    // TODO: Use async interation statement.
    //       Waiting on https://github.com/tc39/proposal-async-iteration
    //       Promises will fail silently, which isn't what we want in development
    return Promise
      .all(extensions.map(name => installer.default(installer[name], forceDownload)))
      .catch(console.log);
  }
};

app.on('ready', async () => {
  await installExtensions();
  const resizable = (process.env.NODE_ENV === 'development' || process.env.BUILD === 'dev');

  mainWindow = new BrowserWindow({
    show: false,
    width: 663,
    height: 769,
    resizable: resizable
  });

  mainWindow.loadURL(`file://${__dirname}/app.html`);

  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.show();
    mainWindow.focus();
    checkUpdates();
  });

  mainWindow.webContents.on('new-window', function(event, url){
    event.preventDefault();
    let platform = os.platform();
    let chromeInstalls = chromeFinder[platform]();
    if(chromeInstalls.length === 0){
      // no chrome installs found, open user's default browser
      open(url);
    } else {
      open(url, chromeInstalls[0], function(error){
        if(error){
          // couldn't open chrome, try OS default
          open(url);
        }
      });
    }
  });
  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  if (process.env.NODE_ENV === 'development' || process.env.BUILD === 'dev') {
    mainWindow.openDevTools();
    mainWindow.webContents.on('context-menu', (e, props) => {
      const { x, y } = props;

      Menu.buildFromTemplate([{
        label: 'Inspect element',
        click() {
          mainWindow.inspectElement(x, y);
        }
      }]).popup(mainWindow);
    });
  }

  if (process.platform === 'darwin') {
    template = [{
      label: 'Tidepool Uploader',
      submenu: [{
        label: 'About Tidepool Uploader',
        selector: 'orderFrontStandardAboutPanel:'
      }, {
        label: 'Check for Updates',
        click() {
          manualCheck = true;
          autoUpdater.checkForUpdates();
        }
      }, {
        type: 'separator'
      }, {
        label: 'Hide Tidepool Uploader',
        accelerator: 'Command+H',
        selector: 'hide:'
      }, {
        label: 'Hide Others',
        accelerator: 'Command+Shift+H',
        selector: 'hideOtherApplications:'
      }, {
        label: 'Show All',
        selector: 'unhideAllApplications:'
      }, {
        type: 'separator'
      }, {
        label: 'Quit',
        accelerator: 'Command+Q',
        click() {
          app.quit();
        }
      }]
    }, {
      label: 'Edit',
      submenu: [{
        label: 'Undo',
        accelerator: 'Command+Z',
        selector: 'undo:'
      }, {
        label: 'Redo',
        accelerator: 'Shift+Command+Z',
        selector: 'redo:'
      }, {
        type: 'separator'
      }, {
        label: 'Cut',
        accelerator: 'Command+X',
        selector: 'cut:'
      }, {
        label: 'Copy',
        accelerator: 'Command+C',
        selector: 'copy:'
      }, {
        label: 'Paste',
        accelerator: 'Command+V',
        selector: 'paste:'
      }, {
        label: 'Select All',
        accelerator: 'Command+A',
        selector: 'selectAll:'
      }]
    }, {
      label: 'View',
      submenu: (process.env.NODE_ENV === 'development' || process.env.BUILD === 'dev') ?
      [
        {
          label: 'Reload',
          accelerator: 'Command+R',
          click() {
            mainWindow.webContents.reload();
          }
        }, {
          label: 'Toggle Full Screen',
          accelerator: 'Ctrl+Command+F',
          click() {
            mainWindow.setFullScreen(!mainWindow.isFullScreen());
          }
        }, {
          label: 'Toggle Developer Tools',
          accelerator: 'Alt+Command+I',
          click() {
            mainWindow.toggleDevTools();
          }
        }
      ] : [
        {
          label: 'Toggle Full Screen',
          accelerator: 'Ctrl+Command+F',
          click() {
            mainWindow.setFullScreen(!mainWindow.isFullScreen());
          }
        }, {
          label: 'Toggle Developer Tools',
          accelerator: 'Alt+Command+I',
          click() {
            mainWindow.toggleDevTools();
          }
        }
      ]
    }, {
      label: 'Window',
      submenu: [{
        label: 'Minimize',
        accelerator: 'Command+M',
        selector: 'performMiniaturize:'
      }, {
        label: 'Close',
        accelerator: 'Command+W',
        selector: 'performClose:'
      }, {
        type: 'separator'
      }, {
        label: 'Bring All to Front',
        selector: 'arrangeInFront:'
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Get Support',
        click() {
          shell.openExternal('http://support.tidepool.org/');
        }
      }, {
        label: 'Check for Updates',
        click() {
          manualCheck = true;
          autoUpdater.checkForUpdates();
        }
      }, {
        label: 'Privacy Policy',
        click() {
          shell.openExternal('https://tidepool.org/legal/privacy-policy-2-0');
        }
      }, {
        label: 'Report an issue...',
        click() {
          shell.openExternal('https://github.com/tidepool-org/chrome-uploader/issues');
        }
      }]
    }];

    menu = Menu.buildFromTemplate(template);
    Menu.setApplicationMenu(menu);
  } else {
    template = [{
      label: '&File',
      submenu: [{
        label: '&Open',
        accelerator: 'Ctrl+O'
      }, {
        label: '&Close',
        accelerator: 'Ctrl+W',
        click() {
          mainWindow.close();
        }
      }]
    }, {
      label: '&View',
      submenu: (process.env.NODE_ENV === 'development' || process.env.BUILD === 'dev') ? [{
        label: '&Reload',
        accelerator: 'Ctrl+R',
        click() {
          mainWindow.webContents.reload();
        }
      }, {
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle &Developer Tools',
        accelerator: 'Alt+Ctrl+I',
        click() {
          mainWindow.toggleDevTools();
        }
      }] : [{
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click() {
          mainWindow.setFullScreen(!mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle &Developer Tools',
        accelerator: 'Alt+Ctrl+I',
        click() {
          mainWindow.toggleDevTools();
        }
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Get Support',
        click() {
          shell.openExternal('http://support.tidepool.org/');
        }
      }, {
        label: 'Privacy Policy',
        click() {
          shell.openExternal('https://tidepool.org/legal/privacy-policy-2-0');
        }
      }, {
        label: 'Report an issue...',
        click() {
          shell.openExternal('https://github.com/tidepool-org/chrome-uploader/issues');
        }
      }]
    }];
    menu = Menu.buildFromTemplate(template);
    mainWindow.setMenu(menu);
  }
});

function checkUpdates(){
  // in production NODE_ENV or *any* type of BUILD (including BUILD === 'dev')
  // we check for updates, but not if NODE_ENV is 'development' and BUILD is unset
  // this prevents a Webpack build error that masks other build errors during local development
  if (process.env.NODE_ENV === 'production' || process.env.BUILD) {
    autoUpdater.checkForUpdates();
  }
}

setInterval(checkUpdates, 1000 * 60 * 60 * 24);

let manualCheck = false;

function sendAction(action) {
  mainWindow.webContents.send('action', action);
}

autoUpdater.on('checking-for-update', () => {
  if(manualCheck) {
    manualCheck = false;
    sendAction(syncActions.manualCheckingForUpdates());
  } else {
    sendAction(syncActions.autoCheckingForUpdates());
  }
});

autoUpdater.on('update-available', (ev, info) => {
  sendAction(syncActions.updateAvailable(info));
  /*
  Example `info`
  {
    "version":"0.310.0-alpha",
    "releaseDate":"2017-04-03T22:29:55.809Z",
    "url":"https://github.com/tidepool-org/chrome-uploader/releases/download/v0.310.0-alpha/tidepool-uploader-dev-0.310.0-alpha-mac.zip",
    "releaseJsonUrl":"https://github.com//tidepool-org/chrome-uploader/releases/download/v0.310.0-alpha/latest-mac.json"
  }
   */
});

autoUpdater.on('update-not-available', (ev, info) => {
  sendAction(syncActions.updateNotAvailable(info));
});

autoUpdater.on('error', (ev, err) => {
  sendAction(syncActions.autoUpdateError(err));
});

autoUpdater.on('update-downloaded', (ev, info) => {
  sendAction(syncActions.updateDownloaded(info));
});

ipcMain.on('autoUpdater', (event, arg) => {
  if(arg === 'checkForUpdates') {
    manualCheck = true;
  }
  autoUpdater[arg]();
});

if(!app.isDefaultProtocolClient('tidepoolupload')){
  app.setAsDefaultProtocolClient('tidepoolupload');
}

app.on('window-all-closed', () => {
  app.quit();
});
<|endoftext|>