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

var FolderStatistics = {
  domain: 'extensions.folderstatistics@clear-code.com.',

  get Prefs() {
    if (!this._Prefs) {
      let ns = {};
      Components.utils.import('resource://folderstatistics-modules/prefs.js', ns);
      this._Prefs = ns.prefs;
    }
    return this._Prefs
  },
  _Prefs: null,

  get TextIO() {
    if (!this._TextIO) {
      let ns = {};
      Components.utils.import('resource://folderstatistics-modules/textIO.jsm', ns);
      this._TextIO = ns.textIO;
    }
    return this._TextIO
  },
  _TextIO: null,

  get bundle() {
    if (!this._bundle) {
      let ns = {};
      Components.utils.import('resource://folderstatistics-modules/stringBundle.js', ns);
      this._bundle = ns.stringBundle.get('chrome://folderstatistics/locale/messages.properties');
    }
    return this._bundle
  },
  _bundle: null,

  onPopupShowing: function FolderStatistics_onPopupShowing(aEvent) {
    var popup = aEvent.currentTarget;

    this.allAccounts.forEach(function(aAccount) {
      aAccount = aAccount.QueryInterface(Ci.nsIMsgAccount);
      var server = aAccount.incomingServer;
      var type = server.type;
      if (!/^(pop3|imap|none)$/.test(type))
        return;
      try {
        var item = document.createElement('menuitem');
        item.setAttribute('label', server.prettyName);
        item.setAttribute('value', server.key);
        popup.appendChild(item);
      }
      catch(error) {
        Components.utils.reportError(error);
      }
    }, this);
  },

  onPopupHiding: function FolderStatistics_onPopupHiding(aEvent) {
    var popup = aEvent.currentTarget;
    var range = document.createRange();
    range.selectNodeContents(popup);
    range.deleteContents();
    range.detach();
  },

  onCommand: function FolderStatistics_onCommand(aEvent) {
    var item = aEvent.target;
    var server = this.getServer(item.value);

    var now = new Date();
    var fileName = this.Prefs.getLocalizedPref(this.domain + 'defaultFileName');
    fileName = fileName
      .replace(/\%account/gi, server.rootFolder.prettyName)
      .replace(/\%yyyy/gi, now.getFullYear())
      .replace(/\%mm/gi, ('0' + (now.getMonth() + 1)).slice(-2))
      .replace(/\%dd/gi, ('0' + now.getDate()).slice(-2));

    var defaultExtension = '.csv';

    var self = this;
    this.asyncPickSaveFile(
      this.bundle.getString('picker.title.csv'),
      fileName + defaultExtension,
      function(aFile) {
        if (!aFile)
          return;

        if (!/\.[^a-z0-9]+$/i.test(aFile.leafName) &&
            self.Prefs.getPref(self.domain + 'addDefaultExtension'))
          aFile.initWithPath(aFile.path + defaultExtension);

        try {
          var sizeNotation = self.Prefs.getPref(self.domain + 'CSV.sizeNotation');
          var statistics = self.getFoldersStatistics(server.rootFolder.subFolders, null, sizeNotation);
          var linefeed = self.Prefs.getPref(self.domain + 'CSV.linefeed');
          var header   = self.Prefs.getPref(self.domain + 'CSV.header');
          var encoding = self.Prefs.getPref(self.domain + 'CSV.encoding');
          var csv = self.toCSV(statistics, {
                linefeed:     linefeed,
                header:       header,
                sizeNotation: sizeNotation
              });
          self.TextIO.writeTo(csv, aFile, encoding);
          alert(self.bundle.getFormattedString('picker.report.csv', [server.rootFolder.prettyName, aFile.path]));
        }
        catch(error) {
          Components.utils.reportError(error);
        }
      }
    );
  },

  get allAccounts() {
    var accountManager = Cc['@mozilla.org/messenger/account-manager;1'].getService(Ci.nsIMsgAccountManager);
    var accounts = accountManager.accounts;
    var accountsArray = [];
    if (accounts instanceof Ci.nsISupportsArray) {
      for (let i = 0, maxi = accounts.Count(); i < maxi; i++) {
        accountsArray.push(accounts.GetElementAt(i));
      }
    } else if (accounts instanceof Ci.nsIArray) {
      for (let i = 0, maxi = accounts.length; i < maxi; i++) {
        accountsArray.push(accounts.queryElementAt(i));
      }
    }
    return accountsArray;
  },

  getServer: function FolderStatistics_getServer(aKey) {
    var foundServer;
    this.allAccounts.some(function(aAccount) {
      aAccount = aAccount.QueryInterface(Ci.nsIMsgAccount);
      var server = aAccount.incomingServer;
      if (server.key == aKey)
        return foundServer = server;
    }, this);
    return foundServer;
  },

  SIZE_NOTATION_AUTO:   0,
  SIZE_NOTATION_BYTES:  1 << 0,
  SIZE_NOTATION_KBYTES: 1 << 1,

  getFoldersStatistics: function FolderStatistics_getFoldersStatistics(aFolders, aParent, aSizeNotation) {
    var foldersArray = [];
    while (aFolders.hasMoreElements()) {
      let folder = aFolders.getNext().QueryInterface(Ci.nsIMsgFolder);
      foldersArray.push(this.getFolderStatistics(folder, aParent, aSizeNotation));
    }
    return foldersArray;
  },
  getFolderStatistics: function FolderStatistics_getFolderStatistics(aFolder, aParent, aSizeNotation) {
    var size = aFolder.sizeOnDisk; // bytes
    if (aSizeNotation == this.SIZE_NOTATION_KBYTES) {
      size = Math.round(size / 1024);
    }
    var item = {
      name:     aFolder.prettyName,
      fullName: (aParent ? aParent + '/' : '') + aFolder.prettyName,
      count:    aFolder.getTotalMessages(false),
      size:     size
    };
    var children = this.getFoldersStatistics(aFolder.subFolders, item.fullName, aSizeNotation);
    if (children.length > 0)
      item.children = children;
    return item;
  },

  toCSV: function FolderStatistics_toCSV(aItems, aOptions) {
    aOptions = aOptions || {};

    var rows = [];
    aItems.forEach(function(aItem) {
      rows = rows.concat(this.itemToRows(aItem));
    }, this);
    rows = rows.map(function(aRow) {
      return aRow.map(this.escapeStringForCSV).join(',');
    }, this).sort();

    if (aOptions.header) {
      let sizeLabel = this.bundle.getString('header.size');
      switch (aOptions.sizeNotation) {
        case this.SIZE_NOTATION_BYTES:
          sizeLabel += ' (bytes)';
          break;
        case this.SIZE_NOTATION_KBYTES:
          sizeLabel += ' (kbytes)';
          break;
        default:
          break;
      }
      rows.unshift([
        this.bundle.getString('header.folder'),
        this.bundle.getString('header.count'),
        sizeLabel
      ].map(this.escapeStringForCSV));
    }

    return rows.join(aOptions.linefeed || aOptions.lineFeed || '\n');
  },
  escapeStringForCSV: function FolderStatistics_escapeStringForCSV(aValue) {
    if (typeof aValue == 'string')
      return '"' + aValue.replace(/"/g, '""') + '"';
    else
      return aValue;
  },

  itemToRows: function FolderStatistics_itemToRows(aItem) {
    var rows = [];
    rows.push([aItem.fullName, Math.max(aItem.count, 0), aItem.size]);
    if (aItem.children) {
      aItem.children.forEach(function(aChild) {
        rows = rows.concat(this.itemToRows(aChild));
      }, this);
    }
    return rows;
  },

  asyncPickSaveFile: function FolderStatistics_asyncPickSaveFile(aTitle, aDefaultFileName, aCallback) {
    var filePicker = Cc['@mozilla.org/filepicker;1']
        .createInstance(Ci.nsIFilePicker);

    filePicker.init(
      window,
      aTitle,
      filePicker.modeSave
    );
    if (aDefaultFileName)
      filePicker.defaultString = aDefaultFileName;

    var handleResult = function(aResult) {
      var picked;
      if (aResult == filePicker.returnOK || aResult == filePicker.returnReplace) {
        picked = filePicker.file.QueryInterface(Ci.nsILocalFile);
      }
      else {
        picked = null;
      }
      aCallback(picked);
    };

    if (typeof filePicker.open != 'function') { // Gecko 18 and olders
      setTimeout(function() {
        handleResult(filePicker.show());
      }, 0);
    }
    else {
      filePicker.open({ done: handleResult });
    }
  }
};
<commit_msg>Don't dulicate dot in the file name<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

var FolderStatistics = {
  domain: 'extensions.folderstatistics@clear-code.com.',

  get Prefs() {
    if (!this._Prefs) {
      let ns = {};
      Components.utils.import('resource://folderstatistics-modules/prefs.js', ns);
      this._Prefs = ns.prefs;
    }
    return this._Prefs
  },
  _Prefs: null,

  get TextIO() {
    if (!this._TextIO) {
      let ns = {};
      Components.utils.import('resource://folderstatistics-modules/textIO.jsm', ns);
      this._TextIO = ns.textIO;
    }
    return this._TextIO
  },
  _TextIO: null,

  get bundle() {
    if (!this._bundle) {
      let ns = {};
      Components.utils.import('resource://folderstatistics-modules/stringBundle.js', ns);
      this._bundle = ns.stringBundle.get('chrome://folderstatistics/locale/messages.properties');
    }
    return this._bundle
  },
  _bundle: null,

  onPopupShowing: function FolderStatistics_onPopupShowing(aEvent) {
    var popup = aEvent.currentTarget;

    this.allAccounts.forEach(function(aAccount) {
      aAccount = aAccount.QueryInterface(Ci.nsIMsgAccount);
      var server = aAccount.incomingServer;
      var type = server.type;
      if (!/^(pop3|imap|none)$/.test(type))
        return;
      try {
        var item = document.createElement('menuitem');
        item.setAttribute('label', server.prettyName);
        item.setAttribute('value', server.key);
        popup.appendChild(item);
      }
      catch(error) {
        Components.utils.reportError(error);
      }
    }, this);
  },

  onPopupHiding: function FolderStatistics_onPopupHiding(aEvent) {
    var popup = aEvent.currentTarget;
    var range = document.createRange();
    range.selectNodeContents(popup);
    range.deleteContents();
    range.detach();
  },

  onCommand: function FolderStatistics_onCommand(aEvent) {
    var item = aEvent.target;
    var server = this.getServer(item.value);

    var now = new Date();
    var fileName = this.Prefs.getLocalizedPref(this.domain + 'defaultFileName');
    fileName = fileName
      .replace(/\%account/gi, server.rootFolder.prettyName)
      .replace(/\%yyyy/gi, now.getFullYear())
      .replace(/\%mm/gi, ('0' + (now.getMonth() + 1)).slice(-2))
      .replace(/\%dd/gi, ('0' + now.getDate()).slice(-2));

    var defaultExtension = '.csv';

    var self = this;
    this.asyncPickSaveFile(
      this.bundle.getString('picker.title.csv'),
      fileName + defaultExtension,
      function(aFile) {
        if (!aFile)
          return;

        if (!/\.[^a-z0-9]+$/i.test(aFile.leafName) &&
            self.Prefs.getPref(self.domain + 'addDefaultExtension'))
          aFile.initWithPath(aFile.path.replace(/\.$/, '') + defaultExtension);

        try {
          var sizeNotation = self.Prefs.getPref(self.domain + 'CSV.sizeNotation');
          var statistics = self.getFoldersStatistics(server.rootFolder.subFolders, null, sizeNotation);
          var linefeed = self.Prefs.getPref(self.domain + 'CSV.linefeed');
          var header   = self.Prefs.getPref(self.domain + 'CSV.header');
          var encoding = self.Prefs.getPref(self.domain + 'CSV.encoding');
          var csv = self.toCSV(statistics, {
                linefeed:     linefeed,
                header:       header,
                sizeNotation: sizeNotation
              });
          self.TextIO.writeTo(csv, aFile, encoding);
          alert(self.bundle.getFormattedString('picker.report.csv', [server.rootFolder.prettyName, aFile.path]));
        }
        catch(error) {
          Components.utils.reportError(error);
        }
      }
    );
  },

  get allAccounts() {
    var accountManager = Cc['@mozilla.org/messenger/account-manager;1'].getService(Ci.nsIMsgAccountManager);
    var accounts = accountManager.accounts;
    var accountsArray = [];
    if (accounts instanceof Ci.nsISupportsArray) {
      for (let i = 0, maxi = accounts.Count(); i < maxi; i++) {
        accountsArray.push(accounts.GetElementAt(i));
      }
    } else if (accounts instanceof Ci.nsIArray) {
      for (let i = 0, maxi = accounts.length; i < maxi; i++) {
        accountsArray.push(accounts.queryElementAt(i));
      }
    }
    return accountsArray;
  },

  getServer: function FolderStatistics_getServer(aKey) {
    var foundServer;
    this.allAccounts.some(function(aAccount) {
      aAccount = aAccount.QueryInterface(Ci.nsIMsgAccount);
      var server = aAccount.incomingServer;
      if (server.key == aKey)
        return foundServer = server;
    }, this);
    return foundServer;
  },

  SIZE_NOTATION_AUTO:   0,
  SIZE_NOTATION_BYTES:  1 << 0,
  SIZE_NOTATION_KBYTES: 1 << 1,

  getFoldersStatistics: function FolderStatistics_getFoldersStatistics(aFolders, aParent, aSizeNotation) {
    var foldersArray = [];
    while (aFolders.hasMoreElements()) {
      let folder = aFolders.getNext().QueryInterface(Ci.nsIMsgFolder);
      foldersArray.push(this.getFolderStatistics(folder, aParent, aSizeNotation));
    }
    return foldersArray;
  },
  getFolderStatistics: function FolderStatistics_getFolderStatistics(aFolder, aParent, aSizeNotation) {
    var size = aFolder.sizeOnDisk; // bytes
    if (aSizeNotation == this.SIZE_NOTATION_KBYTES) {
      size = Math.round(size / 1024);
    }
    var item = {
      name:     aFolder.prettyName,
      fullName: (aParent ? aParent + '/' : '') + aFolder.prettyName,
      count:    aFolder.getTotalMessages(false),
      size:     size
    };
    var children = this.getFoldersStatistics(aFolder.subFolders, item.fullName, aSizeNotation);
    if (children.length > 0)
      item.children = children;
    return item;
  },

  toCSV: function FolderStatistics_toCSV(aItems, aOptions) {
    aOptions = aOptions || {};

    var rows = [];
    aItems.forEach(function(aItem) {
      rows = rows.concat(this.itemToRows(aItem));
    }, this);
    rows = rows.map(function(aRow) {
      return aRow.map(this.escapeStringForCSV).join(',');
    }, this).sort();

    if (aOptions.header) {
      let sizeLabel = this.bundle.getString('header.size');
      switch (aOptions.sizeNotation) {
        case this.SIZE_NOTATION_BYTES:
          sizeLabel += ' (bytes)';
          break;
        case this.SIZE_NOTATION_KBYTES:
          sizeLabel += ' (kbytes)';
          break;
        default:
          break;
      }
      rows.unshift([
        this.bundle.getString('header.folder'),
        this.bundle.getString('header.count'),
        sizeLabel
      ].map(this.escapeStringForCSV));
    }

    return rows.join(aOptions.linefeed || aOptions.lineFeed || '\n');
  },
  escapeStringForCSV: function FolderStatistics_escapeStringForCSV(aValue) {
    if (typeof aValue == 'string')
      return '"' + aValue.replace(/"/g, '""') + '"';
    else
      return aValue;
  },

  itemToRows: function FolderStatistics_itemToRows(aItem) {
    var rows = [];
    rows.push([aItem.fullName, Math.max(aItem.count, 0), aItem.size]);
    if (aItem.children) {
      aItem.children.forEach(function(aChild) {
        rows = rows.concat(this.itemToRows(aChild));
      }, this);
    }
    return rows;
  },

  asyncPickSaveFile: function FolderStatistics_asyncPickSaveFile(aTitle, aDefaultFileName, aCallback) {
    var filePicker = Cc['@mozilla.org/filepicker;1']
        .createInstance(Ci.nsIFilePicker);

    filePicker.init(
      window,
      aTitle,
      filePicker.modeSave
    );
    if (aDefaultFileName)
      filePicker.defaultString = aDefaultFileName;

    var handleResult = function(aResult) {
      var picked;
      if (aResult == filePicker.returnOK || aResult == filePicker.returnReplace) {
        picked = filePicker.file.QueryInterface(Ci.nsILocalFile);
      }
      else {
        picked = null;
      }
      aCallback(picked);
    };

    if (typeof filePicker.open != 'function') { // Gecko 18 and olders
      setTimeout(function() {
        handleResult(filePicker.show());
      }, 0);
    }
    else {
      filePicker.open({ done: handleResult });
    }
  }
};
<|endoftext|>


<commit_before>var map;
var pois = [];
var markerlayer;
var myLocation = null;
var OSM_URL = "http://overpass.osm.rambler.ru/cgi/interpreter?data=%5Bout:json%5D;";
var berlin;

function initMap() {
	markerlayer = L.layerGroup();
	berlin = new L.LatLng(52.5213616409873, 13.4101340342265);

	map = new L.Map('map', {
		center: berlin,
		zoom: 13
	});

	// create a CloudMade tile layer
	var cloudmadeUrl = 'http://{s}.tile.cloudmade.com/97b13b2de7f543d784fbc30129b14ae0/1714@2x/256/{z}/{x}/{y}.png';
	var osmAttr = '© OpenStreetMap contributors, CC-BY-SA';
	var attribution = 'Map data ' + osmAttr + ', Imagery © CloudMade';

	cloudmade = new L.TileLayer(cloudmadeUrl, {maxZoom: 18, attribution: attribution, detectRetina: true});
	map.addLayer(cloudmade);
	map.addLayer(markerlayer);
}

function loadPOI(tag) {

	//remove old markers
	markerlayer.clearLayers();

	//get map bounds from current window
	var southwest = map.getBounds().getSouthWest();
	var northeast = map.getBounds().getNorthEast();

	//build URL
//	var OSM_PARAMS = "node["+tag+ "](" +southwest.lat+  ","  +southwest.lng+  ","  +northeast.lat+ "," +northeast.lng +");out;";
	var OSM_PARAMS = "node["+tag+ "](around:2000," +myLocation.lat+  ","  +myLocation.lng+ ");out;";

	console.log(OSM_PARAMS);
	var URL = OSM_URL + encodeURIComponent(OSM_PARAMS);

	//show loading indicator
	$("#loading").show();

	//load POIs from OSM
	var markers = [];
	$.getJSON(URL)
	.done( function(data) {

		//remove loading indicator
		$("#loading").hide()

		//build markers
		pois = data['elements'];

		if(pois.length == 0) {
			$('#modal_no_pois').modal();
			return;
		};

		$.each(pois, function(index, poi) {
			lat = poi['lat'];
			lon = poi['lon'];
	    	markers.push(new L.Marker([lat, lon]));
	  	});

	  	//add markers to map
		console.log(markers);
		newmarkers = L.layerGroup(markers);
		markerlayer.addLayer(newmarkers);

		//if no geolocation, finish here
		if(myLocation === null){
			return;
		}

		//find nearest marker
		var distance = Number.MAX_VALUE;
		var nearest = null;
		$.each(markers, function(i, marker) {
			temp = marker.getLatLng();
			dist = temp.distanceTo(myLocation);
			if(marker.getLatLng().distanceTo(myLocation) < distance) {
				distance = marker.getLatLng().distanceTo(myLocation);
				nearest = marker;
			}
		})

		//zoom map
		map.fitBounds(new L.LatLngBounds([myLocation, nearest.getLatLng(), myLocation]));

	})
	.fail( function(jqxhr, textStatus, error ) {
		var err = textStatus + ', ' + error;
		console.log( "Request Failed: " + err);
	});
}

function onLocationFound(e) {
    var radius = e.accuracy / 2;

    L.marker(e.latlng).addTo(map).bindPopup("You are within " + radius + " meters from this point").openPopup();

    L.circle(e.latlng, radius).addTo(map);
	myLocation = e.latlng;
}

function onLocationError(e) {
    alert(e.message);
}

window.onload = function() {

	initMap();

	// setup geolocation
	map.on('locationfound', onLocationFound);
	map.on('locationerror', onLocationError);
	map.locate({setView: true, maxZoom: 16});

	//setup dropdown listener
	$('#mydropdown').change(function()
		{
		  var tag = "";
		  switch($(this).val())
		{
		case 'Playground':
		  tag="leisure=playground";
		  break;
		case 'Tabletennis':
		  tag="sport=table_tennis";
		  break;
		case 'ATM':
		  tag="amenity=atm";
		  break;
		case 'Taxi':
		  tag="amenity=taxi";
		  break;
		case 'Fuel':
		  tag="amenity=fuel";
		  break;
		case 'Postbox':
		  tag="amenity=post_box";
		  break;
		case 'Telephone':
		  tag="amenity=telephone";
		  break;
		case 'Water':
		  tag="amenity=drinking_water";
		  break;
		case 'Charging':
		  tag="amenity=charging_station";
		  break;
		default:
		  tag='';
		  break;
		}

		//load POIs into map
		loadPOI(tag);
	});

};
<commit_msg>changed marker and added pharmacy<commit_after>var map;
var pois = [];
var markerlayer;
var myLocation = null;
var OSM_URL = "http://overpass.osm.rambler.ru/cgi/interpreter?data=%5Bout:json%5D;";
var berlin;
var icon_user;

function initMap() {
	markerlayer = L.layerGroup();
	berlin = new L.LatLng(52.5213616409873, 13.4101340342265);

	icon_user = L.icon({
	    iconUrl: 'app/images/user.svg',
	    iconRetinaUrl: 'app/images/user.png',
	    iconSize: [40, 40],
	    iconAnchor: [20, 20],
	    popupAnchor: [10, -20],
	 //   shadowUrl: 'my-icon-shadow.png',
	 //   shadowRetinaUrl: 'my-icon-shadow@2x.png',
	    shadowSize: [68, 95],
	    shadowAnchor: [22, 94]
	});

	map = new L.Map('map', {
		center: berlin,
		zoom: 13
	});

	// create a CloudMade tile layer
	var cloudmadeUrl = 'http://{s}.tile.cloudmade.com/97b13b2de7f543d784fbc30129b14ae0/1714@2x/256/{z}/{x}/{y}.png';
	var osmAttr = '© OpenStreetMap contributors, CC-BY-SA';
	var attribution = 'Map data ' + osmAttr + ', Imagery © CloudMade';

	cloudmade = new L.TileLayer(cloudmadeUrl, {maxZoom: 18, attribution: attribution, detectRetina: true});
	map.addLayer(cloudmade);
	map.addLayer(markerlayer);
}

function loadPOI(tag) {

	//remove old markers
	markerlayer.clearLayers();

	//get map bounds from current window
	var southwest = map.getBounds().getSouthWest();
	var northeast = map.getBounds().getNorthEast();

	//build URL
//	var OSM_PARAMS = "node["+tag+ "](" +southwest.lat+  ","  +southwest.lng+  ","  +northeast.lat+ "," +northeast.lng +");out;";
	var OSM_PARAMS = "node["+tag+ "](around:2000," +myLocation.lat+  ","  +myLocation.lng+ ");out;";

	console.log(OSM_PARAMS);
	var URL = OSM_URL + encodeURIComponent(OSM_PARAMS);

	//show loading indicator
	$("#loading").show();

	//load POIs from OSM
	var markers = [];
	$.getJSON(URL)
	.done( function(data) {

		//remove loading indicator
		$("#loading").hide()

		//build markers
		pois = data['elements'];

		if(pois.length == 0) {
			$('#modal_no_pois').modal();
			return;
		};

		$.each(pois, function(index, poi) {
			lat = poi['lat'];
			lon = poi['lon'];
	    	markers.push(new L.Marker([lat, lon]));
	  	});

	  	//add markers to map
		console.log(markers);
		newmarkers = L.layerGroup(markers);
		markerlayer.addLayer(newmarkers);

		//if no geolocation, finish here
		if(myLocation === null){
			return;
		}

		//find nearest marker
		var distance = Number.MAX_VALUE;
		var nearest = null;
		$.each(markers, function(i, marker) {
			temp = marker.getLatLng();
			dist = temp.distanceTo(myLocation);
			if(marker.getLatLng().distanceTo(myLocation) < distance) {
				distance = marker.getLatLng().distanceTo(myLocation);
				nearest = marker;
			}
		})

		//zoom map
		map.fitBounds(new L.LatLngBounds([myLocation, nearest.getLatLng(), myLocation]));

	})
	.fail( function(jqxhr, textStatus, error ) {
		var err = textStatus + ', ' + error;
		console.log( "Request Failed: " + err);
	});
}

function onLocationFound(e) {
    var radius = e.accuracy / 2;

    L.marker(e.latlng, {icon: icon_user}).addTo(map).bindPopup("You are somewhere here").openPopup();

    L.circle(e.latlng, radius).addTo(map);
	myLocation = e.latlng;
}

function onLocationError(e) {
    alert(e.message);
}

window.onload = function() {

	initMap();

	// setup geolocation
	map.on('locationfound', onLocationFound);
	map.on('locationerror', onLocationError);
	map.locate({setView: true, maxZoom: 16});

	//setup dropdown listener
	$('#mydropdown').change(function()
		{
		  var tag = "";
		  switch($(this).val())
		{
		case 'Playground':
		  tag="leisure=playground";
		  break;
		case 'Tabletennis':
		  tag="sport=table_tennis";
		  break;
		case 'ATM':
		  tag="amenity=atm";
		  break;
		case 'Pharmacy':
		  tag="amenity=pharmacy";
		  break;
		case 'Taxi':
		  tag="amenity=taxi";
		  break;
		case 'Fuel':
		  tag="amenity=fuel";
		  break;
		case 'Postbox':
		  tag="amenity=post_box";
		  break;
		case 'Telephone':
		  tag="amenity=telephone";
		  break;
		case 'Water':
		  tag="amenity=drinking_water";
		  break;
		case 'Charging':
		  tag="amenity=charging_station";
		  break;
		default:
		  tag='';
		  break;
		}

		//load POIs into map
		loadPOI(tag);
	});

	function reloadCurrentMapWindow() {
		//get current zoom level and check
	    //get current map coordinates

		//get current tag
		//go
	}
};
<|endoftext|>


<commit_before>/*global ServiceRegistry, ProjectConfig, ares, ComponentsRegistry, async, enyo, Phonegap, AresI18n */

/* ilibProjectView covers Project-view specific translations. */
var ilibProjectView = AresI18n.resolve.bind(null, AresI18n.setBundle(navigator.language, "$assets/project-view/resources"));

/**
 * This kind is the top kind of project handling. It contains:
 * - The project list
 * - the interface towards the user's file (harmonia)
 * - Popups to manage projects (create, scan, error ...)
 */
enyo.kind({
	name: "ProjectView",
	kind: "FittableColumns",
	classes: "enyo-unselectable",
	debug: false,
	published: {
		// harcoded until ENYO-2755 is fixed
		panelIndex: 0
	},
	components: [
		{kind: "ProjectList",
			onCreateProject: "createProjectAction",
			onOpenProject: "openProjectAction",
			onSearchProjects: "searchProjectsAction",
			onDuplicateProject: "duplicateProjectAction",
			onProjectRemoved: "projectRemoved",
			name: "projectList"
		},
		{kind: "ProjectWizardCreate", canGenerate: false, name: "projectWizardCreate", classes:"ares-masked-content-popup"},
		{kind: "ProjectWizardScan", canGenerate: false, name: "projectWizardScan", classes:"ares-masked-content-popup"},
		{kind: "ProjectWizardModify", canGenerate: false,
			name: "projectWizardModify"
		},
		{kind: "ProjectWizardCopy", name: "projectWizardCopy", classes:"ares-masked-content-popup"}
	],
	handlers: {
		onAddProjectInList: "addProjectInList"
	},
	events: {
		onHideWaitPopup: "",
		onShowWaitPopup: "",
		onError: "",
		onProjectSelected: "",
		onProjectSave: "",
		onRegisterMe: ""
	},
	create: function() {
		ares.setupTraceLogger(this);
		this.inherited(arguments);
		this.doRegisterMe({name:"projectView", reference:this});

		// i18n Checking
		this.trace("ilibProjectView: Cancel=", ilibProjectView("Cancel"));
	},
	/**
	 * Refresh the {ProjectView} (if relevant), following a change of the given file
	 * @param {Object} toSelectId. Asynchronous
	 */
	refreshFileTree: function(toSelectId,next) {
		ComponentsRegistry.getComponent("harmonia").refreshFileTree(toSelectId,next);
	},
	searchProjectsAction: function(inSender, inEvent) {
		this.$.projectWizardScan.setHeaderText(ilibProjectView("Select a folder hierarchy"));
		this.$.projectWizardScan.setRecurse(true);
		this.$.projectWizardScan.show();
		return true; //Stop event propagation
	},
	openProjectAction: function(inSender, inEvent) {
		this.$.projectWizardScan.setHeaderText(ilibProjectView("Select an existing Ares application folder (contains a project.json file)"));
		this.$.projectWizardScan.setRecurse(false);
		this.$.projectWizardScan.show();
		return true; //Stop event propagation
	},
	duplicateProjectAction: function(inSender, inEvent) {
		if(!this.currentProject()){
			this.doError({msg: "Please project list select item."});
			return false;
		}

		this.$.projectWizardCopy.start( this.currentProject() );
		return true; //Stop event propagation
	},
	createProjectAction: function(inSender, inEvent) {
		this.$.projectWizardCreate.start();
		return true; //Stop event propagation
	},
	addProjectInList: function(inSender, inEvent) {
		this.doHideWaitPopup();
		try {
			// Add an entry into the project list
			this.$.projectList.addProject(inEvent.name, inEvent.folderId, inEvent.service, inEvent.dontSelect);
		} catch(e) {
			var msg = e.toString();
			this.error(msg);
			this.doError({msg: msg});
			return false;
		}
		return true; //Stop event propagation
	},
	currentProject: function() {
		return this.$.projectList.getSelectedProject() ;
	},
	/**
	 *
	 * @param {Object} project
	 * @param {Function} next
	 */
	setupProjectConfig: function(project, next) {
		ares.assertCb(next);

		var pname = project.getName();
		if ( this.currentProject() && pname === this.currentProject().getName() ) {
			this.trace("skip setup of already selected project" + pname);
			next();
			return;
		}

		// FIXME: temporary hack to create config.json on the
		// fly if needed... would be better to create/load it
		// when the workspace is loaded & when a new project
		// is created that would save per-click HTTP traffic
		// to the FileSystemService.
		var self = this;
		var config = new ProjectConfig();
		this.trace("setup project config init on "+ project.getName() );
		var initData = {
			service: project.getService(),
			folderId: project.getFolderId()
		};

		async.series(
			[
				// read default config from remote server
				config.init.bind(config, initData) ,
				function (next) {
					self.trace("ProjectView: setup project set config on "+ project.getName() );
					self.initializeValidPgbConf(project, config.data.providers.phonegap.enabled);
					project.setConfig(config);

					self.initializeDownloadStatus(project, config.data.providers.phonegap.enabled);
					next();
				},
				function (next) {
					// Pass service definition & configuration to Harmonia
					// & consequently to HermesFileTree
					self.trace("ProjectView: setup project on harmonia "+ project.getName() );
					ComponentsRegistry.getComponent("harmonia").setProject(project, next);
				}

			],
			function (err) {
				self.trace("ProjectView: setup project config done on " + project.getName() + " err is ",err );
				if (err) {
					self.doError({msg: err.toString(), err: err});
				}
				next(err);
			}
		);
	},
	/**
	 * Initialize the attribute "downloadStatus" of the project
	 *
	 * this attribute is used only by Phonegap Build.
	 * @private
	 */
	initializeDownloadStatus: function(inProject, inPhonegapEnabled) {
		if (inProject.getDownloadStatus() === undefined && inPhonegapEnabled) {
			var downloadStatus = {};
			var index = 0;

			for (index in Phonegap.UIConfiguration.platformDrawersContent) {
				downloadStatus[Phonegap.UIConfiguration.platformDrawersContent[index].id] = "Ready for download";
			}

			inProject.setDownloadStatus(downloadStatus);
		}
	},

	initializeValidPgbConf: function(inProject, inPhonegapEnabled) {
		if (inProject.getValidPgbConf() === undefined && inPhonegapEnabled) {
			var pgbValidation = {};
			var pgbUiData = Phonegap.UIConfiguration.commonDrawersContent.concat(Phonegap.UIConfiguration.platformDrawersContent);
			var index =0;

			for (index in pgbUiData) {
				//The creation of the pgbValidation drawer attribute and its initialization are done in the same time.
				pgbValidation[pgbUiData[index].id] = {};

				for (var i=0, maxLength = pgbUiData[index].rows.length; i<maxLength; i++) {
					//The creation of the pgbValidation row attribute and its initialization are done in the same time.
					pgbValidation[pgbUiData[index].id][pgbUiData[index].rows[i].name] = true;
				}
				pgbValidation[pgbUiData[index].id]["validDrawer"] = true;
			}

			inProject.setValidPgbConf(pgbValidation);
		}
	},

	projectRemoved: function(inSender, inEvent) {
		ComponentsRegistry.getComponent("harmonia").setProject(null, ares.noNext);
	},
	/**
	 * Request to save project and perform action
	 * @param {Ares.Model.Project} project
	 * @param {String} serviceType
	 * @param {String} action
	 */
	projectSaveAndAction: function(project, serviceType, action) {
		var cb = function (err) {
			if (err) {
				this.trace(err);
			} else {
				this.projectAction( project, serviceType, action);
			}
		};
		if (project) {
			this.doProjectSave({ project: project, callback: cb.bind(this) });
		}
	},
	/**
	 * @private
	 */
	projectAction: function(project, serviceType, action) {
		var self = this;
		this.doShowWaitPopup({msg: "Starting: " + action, service: serviceType});
		// TODO: Must be reworked to allow the selection of builder/tester in the UI - ENYO-2049
		var services = ServiceRegistry.instance.getServicesByType(serviceType);
		var provider =	services[services.length - 1];
		if (!provider) {
			this.doError({msg: 'No ' + serviceType + ' service available'});
		} else if (typeof provider[action] !== 'function') {
			this.doError({msg: 'Service ' + provider.name + ' does not provide action: ' + action});
		} else {
			provider[action](project, function(inError) {
				self.doHideWaitPopup();
				self.refreshFileTree(project.getFolderId());
				if (inError) {
					self.doError({msg: inError.toString(), err: inError});
				}
			});
		}
	},

	launchPreview: function (project) {
		var cb = function (err) {
			if (err) {
				this.trace(err);
			} else {
				this._launchPreview(project);
			}
		};
		this.doProjectSave({ project: project, callback: cb.bind(this) });
	},

	_launchPreview: function (project) {
		var config = project.getConfig() ;
		var topFile = config.data.preview.top_file ;
		var projectUrl = project.getProjectUrl() + '/' + topFile ;

		var winLoc = window.location.toString()
			    .replace(/\/ide\/$/,'/preview/preview.html') // Ares std
			    .replace('/ide/index.html','/preview/preview.html') // Ares minified
			    .replace('/ide/debug.html','/ide/preview.html') // Ares debug (every files)
			    .replace('/ide/test.html','/ide/preview.html'); // Ares-under-test
		var previewUrl = winLoc
				+ ( winLoc.indexOf('?') != -1 ? '&' : '?' )
				+ 'url=' + encodeURIComponent(projectUrl)+'&name=' + project.id;

		this.trace("preview on URL ", previewUrl) ;

		window.open(
			previewUrl,
			'_blank', // ensure that a new window is created each time preview is tapped
			'scrollbars=0,menubar=1,resizable=1',
			false
		);
	}
});
<commit_msg>ENYO-3784: abort build if no target found (or if there's outage inside project configuration)<commit_after>/*global ServiceRegistry, ProjectConfig, ares, ComponentsRegistry, async, enyo, Phonegap, AresI18n */

/* ilibProjectView covers Project-view specific translations. */
var ilibProjectView = AresI18n.resolve.bind(null, AresI18n.setBundle(navigator.language, "$assets/project-view/resources"));

/**
 * This kind is the top kind of project handling. It contains:
 * - The project list
 * - the interface towards the user's file (harmonia)
 * - Popups to manage projects (create, scan, error ...)
 */
enyo.kind({
	name: "ProjectView",
	kind: "FittableColumns",
	classes: "enyo-unselectable",
	debug: false,
	published: {
		// harcoded until ENYO-2755 is fixed
		panelIndex: 0
	},
	components: [
		{kind: "ProjectList",
			onCreateProject: "createProjectAction",
			onOpenProject: "openProjectAction",
			onSearchProjects: "searchProjectsAction",
			onDuplicateProject: "duplicateProjectAction",
			onProjectRemoved: "projectRemoved",
			name: "projectList"
		},
		{kind: "ProjectWizardCreate", canGenerate: false, name: "projectWizardCreate", classes:"ares-masked-content-popup"},
		{kind: "ProjectWizardScan", canGenerate: false, name: "projectWizardScan", classes:"ares-masked-content-popup"},
		{kind: "ProjectWizardModify", canGenerate: false,
			name: "projectWizardModify"
		},
		{kind: "ProjectWizardCopy", name: "projectWizardCopy", classes:"ares-masked-content-popup"}
	],
	handlers: {
		onAddProjectInList: "addProjectInList"
	},
	events: {
		onHideWaitPopup: "",
		onShowWaitPopup: "",
		onError: "",
		onProjectSelected: "",
		onProjectSave: "",
		onRegisterMe: ""
	},
	create: function() {
		ares.setupTraceLogger(this);
		this.inherited(arguments);
		this.doRegisterMe({name:"projectView", reference:this});

		// i18n Checking
		this.trace("ilibProjectView: Cancel=", ilibProjectView("Cancel"));
	},
	/**
	 * Refresh the {ProjectView} (if relevant), following a change of the given file
	 * @param {Object} toSelectId. Asynchronous
	 */
	refreshFileTree: function(toSelectId,next) {
		ComponentsRegistry.getComponent("harmonia").refreshFileTree(toSelectId,next);
	},
	searchProjectsAction: function(inSender, inEvent) {
		this.$.projectWizardScan.setHeaderText(ilibProjectView("Select a folder hierarchy"));
		this.$.projectWizardScan.setRecurse(true);
		this.$.projectWizardScan.show();
		return true; //Stop event propagation
	},
	openProjectAction: function(inSender, inEvent) {
		this.$.projectWizardScan.setHeaderText(ilibProjectView("Select an existing Ares application folder (contains a project.json file)"));
		this.$.projectWizardScan.setRecurse(false);
		this.$.projectWizardScan.show();
		return true; //Stop event propagation
	},
	duplicateProjectAction: function(inSender, inEvent) {
		if(!this.currentProject()){
			this.doError({msg: "Please project list select item."});
			return false;
		}

		this.$.projectWizardCopy.start( this.currentProject() );
		return true; //Stop event propagation
	},
	createProjectAction: function(inSender, inEvent) {
		this.$.projectWizardCreate.start();
		return true; //Stop event propagation
	},
	addProjectInList: function(inSender, inEvent) {
		this.doHideWaitPopup();
		try {
			// Add an entry into the project list
			this.$.projectList.addProject(inEvent.name, inEvent.folderId, inEvent.service, inEvent.dontSelect);
		} catch(e) {
			var msg = e.toString();
			this.error(msg);
			this.doError({msg: msg});
			return false;
		}
		return true; //Stop event propagation
	},
	currentProject: function() {
		return this.$.projectList.getSelectedProject() ;
	},
	/**
	 *
	 * @param {Object} project
	 * @param {Function} next
	 */
	setupProjectConfig: function(project, next) {
		ares.assertCb(next);

		var pname = project.getName();
		if ( this.currentProject() && pname === this.currentProject().getName() ) {
			this.trace("skip setup of already selected project" + pname);
			next();
			return;
		}

		// FIXME: temporary hack to create config.json on the
		// fly if needed... would be better to create/load it
		// when the workspace is loaded & when a new project
		// is created that would save per-click HTTP traffic
		// to the FileSystemService.
		var self = this;
		var config = new ProjectConfig();
		this.trace("setup project config init on "+ project.getName() );
		var initData = {
			service: project.getService(),
			folderId: project.getFolderId()
		};

		async.series(
			[
				// read default config from remote server
				config.init.bind(config, initData) ,
				function (next) {
					self.trace("ProjectView: setup project set config on "+ project.getName() );
					self.initializeValidPgbConf(project, config.data.providers.phonegap.enabled);
					project.setConfig(config);

					self.initializeDownloadStatus(project, config.data.providers.phonegap.enabled);
					next();
				},
				function (next) {
					// Pass service definition & configuration to Harmonia
					// & consequently to HermesFileTree
					self.trace("ProjectView: setup project on harmonia "+ project.getName() );
					ComponentsRegistry.getComponent("harmonia").setProject(project, next);
				}

			],
			function (err) {
				self.trace("ProjectView: setup project config done on " + project.getName() + " err is ",err );
				if (err) {
					self.doError({msg: err.toString(), err: err});
				}
				next(err);
			}
		);
	},
	/**
	 * Initialize the attribute "downloadStatus" of the project
	 *
	 * this attribute is used only by Phonegap Build.
	 * @private
	 */
	initializeDownloadStatus: function(inProject, inPhonegapEnabled) {
		if (inProject.getDownloadStatus() === undefined && inPhonegapEnabled) {
			var downloadStatus = {};
			var index = 0;

			for (index in Phonegap.UIConfiguration.platformDrawersContent) {
				downloadStatus[Phonegap.UIConfiguration.platformDrawersContent[index].id] = "Ready for download";
			}

			inProject.setDownloadStatus(downloadStatus);
		}
	},

	initializeValidPgbConf: function(inProject, inPhonegapEnabled) {
		if (inProject.getValidPgbConf() === undefined && inPhonegapEnabled) {
			var pgbValidation = {};
			var pgbUiData = Phonegap.UIConfiguration.commonDrawersContent.concat(Phonegap.UIConfiguration.platformDrawersContent);
			var index =0;

			for (index in pgbUiData) {
				//The creation of the pgbValidation drawer attribute and its initialization are done in the same time.
				pgbValidation[pgbUiData[index].id] = {};

				for (var i=0, maxLength = pgbUiData[index].rows.length; i<maxLength; i++) {
					//The creation of the pgbValidation row attribute and its initialization are done in the same time.
					pgbValidation[pgbUiData[index].id][pgbUiData[index].rows[i].name] = true;
				}
				pgbValidation[pgbUiData[index].id]["validDrawer"] = true;
			}

			inProject.setValidPgbConf(pgbValidation);
		}
	},

	projectRemoved: function(inSender, inEvent) {
		ComponentsRegistry.getComponent("harmonia").setProject(null, ares.noNext);
	},
	/**
	 * Request to save project and perform action
	 * @param {Ares.Model.Project} project
	 * @param {String} serviceType
	 * @param {String} action
	 */
	projectSaveAndAction: function(project, serviceType, action) {
		var cb = function (err) {
			if (err) {
				this.trace(err);
			} else {
				this.projectAction( project, serviceType, action);
			}
		};
		if (project) {
			this.doProjectSave({ project: project, callback: cb.bind(this) });
		}
	},
	/**
	 * @private
	 */
	projectAction: function(project, serviceType, action) {
		var self = this;
		this.doShowWaitPopup({msg: "Starting: " + action, service: serviceType});
		// TODO: Must be reworked to allow the selection of builder/tester in the UI - ENYO-2049
		var services = ServiceRegistry.instance.getServicesByType(serviceType);
		var provider =	services[services.length - 1];
		if (!provider) {
			this.doError({msg: 'No ' + serviceType + ' service available'});
		} else if (typeof provider[action] !== 'function') {
			this.doError({msg: 'Service ' + provider.name + ' does not provide action: ' + action});
		} else {
			// Check if PhoneGap Build plugin is enabled that at least one target has been selected
			if (serviceType === "build" && action === "build") {
				var abortMsg = "";
				if (project) {
					var config = project.getConfig();
					if (config && config.data && config.data.providers) {
						var phonegap = config.data.providers.phonegap;
						if (phonegap !== undefined) {
							if (phonegap.enabled) {
								var targets = phonegap.targets;
								if (targets !== undefined && Object.keys(targets).length === 0) {
									abortMsg = "No targets selected, build aborted";
								}
							} else {
								abortMsg = "Phonegap build not enabled, build aborted";
							}
						} else {
							abortMsg = "No PhoneGap Build configuration, build aborted";
						}
					} else {
						abortMsg = "No project configuration available, build aborted";
					}
				} else {
					abortMsg = "No project selected, build aborted";
				}

				if (abortMsg !== "") {
					this.doError({msg: abortMsg});
					this.doHideWaitPopup();
					return true;
				}
			}

			provider[action](project, function(inError) {
				self.doHideWaitPopup();
				self.refreshFileTree(project.getFolderId());
				if (inError) {
					self.doError({msg: inError.toString(), err: inError});
				}
			});
		}
	},

	launchPreview: function (project) {
		var cb = function (err) {
			if (err) {
				this.trace(err);
			} else {
				this._launchPreview(project);
			}
		};
		this.doProjectSave({ project: project, callback: cb.bind(this) });
	},

	_launchPreview: function (project) {
		var config = project.getConfig() ;
		var topFile = config.data.preview.top_file ;
		var projectUrl = project.getProjectUrl() + '/' + topFile ;

		var winLoc = window.location.toString()
			    .replace(/\/ide\/$/,'/preview/preview.html') // Ares std
			    .replace('/ide/index.html','/preview/preview.html') // Ares minified
			    .replace('/ide/debug.html','/ide/preview.html') // Ares debug (every files)
			    .replace('/ide/test.html','/ide/preview.html'); // Ares-under-test
		var previewUrl = winLoc
				+ ( winLoc.indexOf('?') != -1 ? '&' : '?' )
				+ 'url=' + encodeURIComponent(projectUrl)+'&name=' + project.id;

		this.trace("preview on URL ", previewUrl) ;

		window.open(
			previewUrl,
			'_blank', // ensure that a new window is created each time preview is tapped
			'scrollbars=0,menubar=1,resizable=1',
			false
		);
	}
});
<|endoftext|>


<commit_before><commit_msg>[FIX] web: avoid interactions between drag and drop tests<commit_after><|endoftext|>


<commit_before>{
	"translatorID":"b6d0a7a-d076-48ae-b2f0-b6de28b194e",
	"translatorType":4,
	"label":"ScienceDirect",
	"creator":"Michael Berkowitz",
	"target":"https?://[^/]*science-?direct\\.com[^/]*/science(\\/article)?(\\?(?:.+\\&|)ob=(?:ArticleURL|ArticleListURL|PublicationURL))?",
	"minVersion":"1.0.0b3.r1",
	"maxVersion":null,
	"priority":100,
	"inRepository":true,
	"lastUpdated":"2008-12-04 10:06:00"
}

function detectWeb(doc, url) {
	if ((url.indexOf("_ob=DownloadURL") != -1) || doc.title == "ScienceDirect Login") {
		return false;
	}
	if((!url.match("pdf") && url.indexOf("_ob=ArticleURL") == -1 && url.indexOf("/article/") == -1) || url.indexOf("/journal/") != -1) {
		return "multiple";
	} else if (!url.match("pdf")) {
		return "journalArticle";
	}
}

function doWeb(doc, url) {
	var namespace = doc.documentElement.namespaceURI;
	var nsResolver = namespace ? function(prefix) {
		if (prefix == 'x') return namespace; else return null;
	} : null;

    	// MCB-04dec08: Old guest detection logic was broken, the check of advertisement has not been fully vetted
		//if (!doc.evaluate('//img[contains(@src, "guest_user.gif")]', doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext()) {
		if (!doc.evaluate('//div[@title = "Advertisement."]', doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext()) {
		var articles = new Array();
		if(detectWeb(doc, url) == "multiple") {
			//search page
			var items = new Object();
			var xpath;
			if (url.indexOf("_ob=PublicationURL") != -1) {
				// not sure if this case still arises. may need to be fixed at some point
				xpath = '//table[@class="txt"]/tbody/tr/td[2]';
			} else {
				xpath = '//div[@class="font3"][@id="bodyMainResults"]/table/tbody/tr/td[2]/a';
			}
			var rows = doc.evaluate(xpath, doc, nsResolver, XPathResult.ANY_TYPE, null);
			var next_row;
			while (next_row = rows.iterateNext()) {
				var title = next_row.textContent;
				var link = next_row.href;
				if (!title.match(/PDF \(/) && !title.match(/Related Articles/)) items[link] = title;
			}
			items = Zotero.selectItems(items);
			for (var i in items) {
				articles.push(i);
			}
		} else {
			articles = [url];
		}
		Zotero.Utilities.processDocuments(articles, function(newDoc) {
			var doi = newDoc.evaluate('//div[@class="articleHeaderInner"][@id="articleHeader"]/a[contains(text(), "doi")]', newDoc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().textContent.substr(4);

			// MCB-04dec08: grab the correct PDF link, there are at least 2 versions
			// MCB-04dec08: In RARE cases the PDF link does not exists...need some logic here and below in the item.attachments section
			var tempPDF = newDoc.evaluate('//a[@class="noul" and div/div[contains(text(), "PDF")]]', newDoc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext();
			var PDF = (tempPDF) ?
					   tempPDF.href :
					   newDoc.evaluate('//a[@class="noul" and contains(text(), "PDF")]', newDoc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().href;

			var url = newDoc.location.href;
			var get = newDoc.evaluate('//a[img[contains(@src, "exportarticle_a.gif")]]', newDoc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().href;
			Zotero.Utilities.HTTP.doGet(get, function(text) {
				var md5 = text.match(/<input type=hidden name=md5 value=([^>]+)>/)[1];
				var acct = text.match(/<input type=hidden name=_acct value=([^>]+)>/)[1];
				var userid = text.match(/<input type=hidden name=_userid value=([^>]+)>/)[1];
				var uoikey = text.match(/<input type=hidden name=_uoikey value=([^>]+)>/)[1];
				if (text.match(/<input type=hidden name=_ArticleListID value=([^>]+)>/)) {
					var alid = text.match(/<input type=hidden name=_ArticleListID value=([^>]+)>/)[1];
				}
				if (alid) {
					var docID = "_ArticleListID=" + alid + "&_uoikey=" + uoikey;
				} else {
					var docID = "_uoikey=" + uoikey;
				}
				var post = "_ob=DownloadURL&_method=finish&_acct=" + acct + "&_userid=" + userid + "&_docType=FLA&" + docID + "&md5=" + md5 + "&count=1&JAVASCRIPT_ON=Y&format=cite-abs&citation-type=RIS&Export=Export&x=26&y=17";
				var baseurl = url.match(/https?:\/\/[^/]+\//)[0];
				Zotero.Utilities.HTTP.doPost(baseurl + 'science', post, function(text) {
					var translator = Zotero.loadTranslator("import");
					translator.setTranslator("32d59d2d-b65a-4da4-b0a3-bdd3cfb979e7");
					translator.setString(text);
					translator.setHandler("itemDone", function(obj, item) {
						item.attachments = [
							{url:url, title:"ScienceDirect Snapshot", mimeType:"text/html"},
							{url:PDF, title:"ScienceDirect Full Text PDF", mimeType:"application/pdf"}
						];

						if(item.notes[0]) {
							item.abstractNote = item.notes[0].note;
							item.notes = new Array();
						}
						if (doi) {
							item.DOI = doi;
						}
						item.complete();
					});
					translator.translate();
				});
			});
		}, function() {Zotero.done;});
	} else {
		var articles = new Array();
		if (detectWeb(doc, url) == "multiple") {
			var items = new Object();
			if (url.indexOf("_ob=PublicationURL") != -1) {
				xpath = '//table[@class="txt"]/tbody/tr[1]/td[2]';
				// not sure whether this case still exists
			} else {
				xpath = '//div[@class="font3"][@id="bodyMainResults"]/table/tbody/tr/td[2]/a';
			}
			var rows = doc.evaluate(xpath, doc, nsResolver, XPathResult.ANY_TYPE, null);
			var next_row;
			while (next_row = rows.iterateNext()) {
				var title = next_row.textContent;
				var link = next_row.href;
				items[link] = title;
			}
			items = Zotero.selectItems(items);
			for (var i in items) {
				articles.push(i);
			}
		} else {
			articles = [url];
		}
		Zotero.Utilities.processDocuments(articles, function(doc2) {
			var item = new Zotero.Item("journalArticle");
			item.repository = "ScienceDirect";
			item.url = doc2.location.href;
			var title = doc2.title.match(/^[^-]+\-([^:]+):(.*)$/);
			item.title = Zotero.Utilities.trimInternal(title[2]);
			item.publicationTitle = Zotero.Utilities.trimInternal(title[1]);
			voliss = doc2.evaluate('//div[@class="pageText"][@id="sdBody"]/table/tbody/tr/td[1]', doc2, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().textContent;
			if (voliss.match(/Volume\s+\d+/)) item.volume = voliss.match(/Volume\s+(\d+)/)[1];
			if (voliss.match(/Issues?\s+[^,]+/)) item.issue = voliss.match(/Issues?\s+([^,]+)/)[1];
			if (voliss.match(/(J|F|M|A|S|O|N|D)\w+\s+\d{4}/)) item.date = voliss.match(/(J|F|M|A|S|O|N|D)\w+\s+\d{4}/)[0];
			if (voliss.match(/Pages?\s+[^,^\s]+/)) item.pages = voliss.match(/Pages?\s+([^,^\s]+)/)[1];
			item.DOI = doc2.evaluate('//div[@class="articleHeaderInner"][@id="articleHeader"]/a[contains(text(), "doi")]', doc2, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().textContent.substr(4);
			var abspath = '//div[@class="articleHeaderInner"][@id="articleHeader"]/div[@class="articleText"]/p';
			var absx = doc2.evaluate(abspath, doc2, nsResolver, XPathResult.ANY_TYPE, null);
			var ab;
			item.abstractNote = ""
			while (ab = absx.iterateNext()) {
				item.abstractNote += Zotero.Utilities.trimInternal(ab.textContent) + " ";
			}
			if (item.abstractNote.substr(0, 7) == "Summary") {
				item.abstractNote = item.abstractNote.substr(9);
			}
			var tagpath = '//div[@class="articleText"]/p[strong[starts-with(text(), "Keywords:")]]';
			if (doc2.evaluate(tagpath, doc2, nsResolver, XPathResult.ANY_TYPE, null).iterateNext()) {
				if (doc2.evaluate(tagpath, doc2, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().textContent.split(":")[1]) {
					var tags = doc2.evaluate(tagpath, doc2, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().textContent.split(":")[1].split(";");
					for (var i in tags) {
						item.tags.push(Zotero.Utilities.trimInternal(tags[i]));
					}
				}
			}
			item.attachments.push({url:doc2.location.href, title:"ScienceDirect Snapshot", mimeType:"text/html"});
			Zotero.Utilities.HTTP.doGet(item.url, function(text) {
				var aus = text.match(/<strong>\s+<p>.*<\/strong>/)[0].replace(/<sup>/g, "$").replace(/<\/sup>/g, "$");
				aus = aus.replace(/\$[^$]*\$/g, "");
				aus = aus.replace(/<a[^>]*>/g, "$").replace(/<\/a[^>]*>/g, "$");
				aus = aus.replace(/\$[^$]*\$/g, "");
				aus = Zotero.Utilities.cleanTags(aus);
				aus = aus.split(/(,|and)/);
				for (var a in aus) {
					if (aus[a] != "," && aus[a] != "and" && aus[a].match(/\w+/)) {
						item.creators.push(Zotero.Utilities.cleanAuthor(Zotero.Utilities.trimInternal(aus[a]), "author"));
					}
				}
				item.complete();
			});
		}, function() {Zotero.done;});
	}
	Zotero.wait();
}<commit_msg>Extended characters were lost on import from ScienceDirect<commit_after>{
	"translatorID":"b6d0a7a-d076-48ae-b2f0-b6de28b194e",
	"translatorType":4,
	"label":"ScienceDirect",
	"creator":"Michael Berkowitz",
	"target":"https?://[^/]*science-?direct\\.com[^/]*/science(\\/article)?(\\?(?:.+\\&|)ob=(?:ArticleURL|ArticleListURL|PublicationURL))?",
	"minVersion":"1.0.0b3.r1",
	"maxVersion":null,
	"priority":100,
	"inRepository":true,
	"lastUpdated":"2008-12-04 10:06:00"
}

function detectWeb(doc, url) {
	if ((url.indexOf("_ob=DownloadURL") != -1) || doc.title == "ScienceDirect Login") {
		return false;
	}
	if((!url.match("pdf") && url.indexOf("_ob=ArticleURL") == -1 && url.indexOf("/article/") == -1) || url.indexOf("/journal/") != -1) {
		return "multiple";
	} else if (!url.match("pdf")) {
		return "journalArticle";
	}
}

function doWeb(doc, url) {
	var namespace = doc.documentElement.namespaceURI;
	var nsResolver = namespace ? function(prefix) {
		if (prefix == 'x') return namespace; else return null;
	} : null;

    	// MCB-04dec08: Old guest detection logic was broken, the check of advertisement has not been fully vetted
		//if (!doc.evaluate('//img[contains(@src, "guest_user.gif")]', doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext()) {
		if (!doc.evaluate('//div[@title = "Advertisement."]', doc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext()) {
		var articles = new Array();
		if(detectWeb(doc, url) == "multiple") {
			//search page
			var items = new Object();
			var xpath;
			if (url.indexOf("_ob=PublicationURL") != -1) {
				// not sure if this case still arises. may need to be fixed at some point
				xpath = '//table[@class="txt"]/tbody/tr/td[2]';
			} else {
				xpath = '//div[@class="font3"][@id="bodyMainResults"]/table/tbody/tr/td[2]/a';
			}
			var rows = doc.evaluate(xpath, doc, nsResolver, XPathResult.ANY_TYPE, null);
			var next_row;
			while (next_row = rows.iterateNext()) {
				var title = next_row.textContent;
				var link = next_row.href;
				if (!title.match(/PDF \(/) && !title.match(/Related Articles/)) items[link] = title;
			}
			items = Zotero.selectItems(items);
			for (var i in items) {
				articles.push(i);
			}
		} else {
			articles = [url];
		}
		Zotero.Utilities.processDocuments(articles, function(newDoc) {
			var doi = newDoc.evaluate('//div[@class="articleHeaderInner"][@id="articleHeader"]/a[contains(text(), "doi")]', newDoc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().textContent.substr(4);

			// MCB-04dec08: grab the correct PDF link, there are at least 2 versions
			// MCB-04dec08: In RARE cases the PDF link does not exists...need some logic here and below in the item.attachments section
			var tempPDF = newDoc.evaluate('//a[@class="noul" and div/div[contains(text(), "PDF")]]', newDoc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext();
			var PDF = (tempPDF) ?
					   tempPDF.href :
					   newDoc.evaluate('//a[@class="noul" and contains(text(), "PDF")]', newDoc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().href;

			var url = newDoc.location.href;
			var get = newDoc.evaluate('//a[img[contains(@src, "exportarticle_a.gif")]]', newDoc, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().href;
			Zotero.Utilities.HTTP.doGet(get, function(text) {
				var md5 = text.match(/<input type=hidden name=md5 value=([^>]+)>/)[1];
				var acct = text.match(/<input type=hidden name=_acct value=([^>]+)>/)[1];
				var userid = text.match(/<input type=hidden name=_userid value=([^>]+)>/)[1];
				var uoikey = text.match(/<input type=hidden name=_uoikey value=([^>]+)>/)[1];
				if (text.match(/<input type=hidden name=_ArticleListID value=([^>]+)>/)) {
					var alid = text.match(/<input type=hidden name=_ArticleListID value=([^>]+)>/)[1];
				}
				if (alid) {
					var docID = "_ArticleListID=" + alid + "&_uoikey=" + uoikey;
				} else {
					var docID = "_uoikey=" + uoikey;
				}
				var post = "_ob=DownloadURL&_method=finish&_acct=" + acct + "&_userid=" + userid + "&_docType=FLA&" + docID + "&md5=" + md5 + "&count=1&JAVASCRIPT_ON=Y&format=cite-abs&citation-type=RIS&Export=Export&x=26&y=17";
				var baseurl = url.match(/https?:\/\/[^/]+\//)[0];
				Zotero.Utilities.HTTP.doPost(baseurl + 'science', post, function(text) {
					var translator = Zotero.loadTranslator("import");
					translator.setTranslator("32d59d2d-b65a-4da4-b0a3-bdd3cfb979e7");
					translator.setString(text);
					translator.setHandler("itemDone", function(obj, item) {
						item.attachments = [
							{url:url, title:"ScienceDirect Snapshot", mimeType:"text/html"},
							{url:PDF, title:"ScienceDirect Full Text PDF", mimeType:"application/pdf"}
						];

						if(item.notes[0]) {
							item.abstractNote = item.notes[0].note;
							item.notes = new Array();
						}
						if (doi) {
							item.DOI = doi;
						}
						item.complete();
					});
					translator.translate();
				}, false, 'windows-1252');
			});
		}, function() {Zotero.done;});
	} else {
		var articles = new Array();
		if (detectWeb(doc, url) == "multiple") {
			var items = new Object();
			if (url.indexOf("_ob=PublicationURL") != -1) {
				xpath = '//table[@class="txt"]/tbody/tr[1]/td[2]';
				// not sure whether this case still exists
			} else {
				xpath = '//div[@class="font3"][@id="bodyMainResults"]/table/tbody/tr/td[2]/a';
			}
			var rows = doc.evaluate(xpath, doc, nsResolver, XPathResult.ANY_TYPE, null);
			var next_row;
			while (next_row = rows.iterateNext()) {
				var title = next_row.textContent;
				var link = next_row.href;
				items[link] = title;
			}
			items = Zotero.selectItems(items);
			for (var i in items) {
				articles.push(i);
			}
		} else {
			articles = [url];
		}
		Zotero.Utilities.processDocuments(articles, function(doc2) {
			var item = new Zotero.Item("journalArticle");
			item.repository = "ScienceDirect";
			item.url = doc2.location.href;
			var title = doc2.title.match(/^[^-]+\-([^:]+):(.*)$/);
			item.title = Zotero.Utilities.trimInternal(title[2]);
			item.publicationTitle = Zotero.Utilities.trimInternal(title[1]);
			voliss = doc2.evaluate('//div[@class="pageText"][@id="sdBody"]/table/tbody/tr/td[1]', doc2, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().textContent;
			if (voliss.match(/Volume\s+\d+/)) item.volume = voliss.match(/Volume\s+(\d+)/)[1];
			if (voliss.match(/Issues?\s+[^,]+/)) item.issue = voliss.match(/Issues?\s+([^,]+)/)[1];
			if (voliss.match(/(J|F|M|A|S|O|N|D)\w+\s+\d{4}/)) item.date = voliss.match(/(J|F|M|A|S|O|N|D)\w+\s+\d{4}/)[0];
			if (voliss.match(/Pages?\s+[^,^\s]+/)) item.pages = voliss.match(/Pages?\s+([^,^\s]+)/)[1];
			item.DOI = doc2.evaluate('//div[@class="articleHeaderInner"][@id="articleHeader"]/a[contains(text(), "doi")]', doc2, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().textContent.substr(4);
			var abspath = '//div[@class="articleHeaderInner"][@id="articleHeader"]/div[@class="articleText"]/p';
			var absx = doc2.evaluate(abspath, doc2, nsResolver, XPathResult.ANY_TYPE, null);
			var ab;
			item.abstractNote = ""
			while (ab = absx.iterateNext()) {
				item.abstractNote += Zotero.Utilities.trimInternal(ab.textContent) + " ";
			}
			if (item.abstractNote.substr(0, 7) == "Summary") {
				item.abstractNote = item.abstractNote.substr(9);
			}
			var tagpath = '//div[@class="articleText"]/p[strong[starts-with(text(), "Keywords:")]]';
			if (doc2.evaluate(tagpath, doc2, nsResolver, XPathResult.ANY_TYPE, null).iterateNext()) {
				if (doc2.evaluate(tagpath, doc2, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().textContent.split(":")[1]) {
					var tags = doc2.evaluate(tagpath, doc2, nsResolver, XPathResult.ANY_TYPE, null).iterateNext().textContent.split(":")[1].split(";");
					for (var i in tags) {
						item.tags.push(Zotero.Utilities.trimInternal(tags[i]));
					}
				}
			}
			item.attachments.push({url:doc2.location.href, title:"ScienceDirect Snapshot", mimeType:"text/html"});
			Zotero.Utilities.HTTP.doGet(item.url, function(text) {
				var aus = text.match(/<strong>\s+<p>.*<\/strong>/)[0].replace(/<sup>/g, "$").replace(/<\/sup>/g, "$");
				aus = aus.replace(/\$[^$]*\$/g, "");
				aus = aus.replace(/<a[^>]*>/g, "$").replace(/<\/a[^>]*>/g, "$");
				aus = aus.replace(/\$[^$]*\$/g, "");
				aus = Zotero.Utilities.cleanTags(aus);
				aus = aus.split(/(,|and)/);
				for (var a in aus) {
					if (aus[a] != "," && aus[a] != "and" && aus[a].match(/\w+/)) {
						item.creators.push(Zotero.Utilities.cleanAuthor(Zotero.Utilities.trimInternal(aus[a]), "author"));
					}
				}
				item.complete();
			});
		}, function() {Zotero.done;});
	}
	Zotero.wait();
}<|endoftext|>


<commit_before>/**
 * Creates files
 *
 * https://www.npmjs.com/package/grunt-file-creator
 */

var grunt = require('grunt'),
	component = grunt.option('name') || '',
	date = new Date().toISOString().substring(0, 10);

module.exports = {
	componentFiles: [
		{
			file: '<%= Config.PRIVATE_DIR %>/component/' + component + '/' + component + '.scss',
			method: function (fs, fd, done) {
				var content = "@charset \"utf-8\";\n" +
					"/**\n" +
					" * brandung " + component + " v1.0.0\n" +
					" *\n" +
					" * Copyright brandung GmbH & Co.KG\n" +
					" * http://www.brandung.de/\n" +
					" *\n" +
					" * Date: " + date + "\n" +
					" * MIT License (MIT)\n" +
					" */\n" +
					"\n" +
					"@import '../../sass/partials/functions';\n" +
					"@import '../../sass/partials/variables';\n" +
					"@import '../../sass/partials/mixins';\n" +
					"\n" +
					"." + component + " {\n" +
					"\t\n" +
					"}\n";

				fs.writeSync(fd, content);

				done();
			}
		},
		{
			file: '<%= Config.PRIVATE_DIR %>/component/' + component + '/' + component + '.tpl',
			method: function (fs, fd, done) {
				var content = "\n" +
					"

";

				fs.writeSync(fd, content);

				done();
			}
		}
	]
};<commit_msg>BFW-42: insert new SASS module handling in create:component task<commit_after>/**
 * Creates files
 *
 * https://www.npmjs.com/package/grunt-file-creator
 */

var grunt = require('grunt'),
	component = grunt.option('name') || '',
	date = new Date().toISOString().substring(0, 10);

module.exports = {
	componentFiles: [
		{
			file: '<%= Config.PRIVATE_DIR %>/component/' + component + '/' + component + '.scss',
			method: function (fs, fd, done) {
				var content = "@charset \"utf-8\";\n" +
					"/**\n" +
					" * brandung " + component + " v1.0.0\n" +
					" *\n" +
					" * Copyright brandung GmbH & Co.KG\n" +
					" * http://www.brandung.de/\n" +
					" *\n" +
					" * Date: " + date + "\n" +
					" * MIT License (MIT)\n" +
					" */\n" +
					"\n" +
					"@import '../../sass/partials/functions';\n" +
					"@import '../../sass/partials/variables';\n" +
					"@import '../../sass/partials/mixins';\n" +
					"\n" +
					"$module: '" + component + "';\n"+
					"\n" +
					"// block\n" +
					"%#{$module} {\n" +
					"\t\n"+
					"}\n\n\n"+
					"// element\n\n\n" +
					"// modifier\n\n" +
					"\n\n" +
					"// module class selector\n" +
					".#{$module} {\n" +
					"\t@extend %#{$module};\n"+
					"}\n";

				fs.writeSync(fd, content);

				done();
			}
		},
		{
			file: '<%= Config.PRIVATE_DIR %>/component/' + component + '/' + component + '.tpl',
			method: function (fs, fd, done) {
				var content = "\n" +
					"

";

				fs.writeSync(fd, content);

				done();
			}
		}
	]
};<|endoftext|>


<commit_before>// @flow

import Relay from 'react-relay/classic';
import fromGraphQL from 'react-relay/lib/fromGraphQL';

const QUERIES = {
  "build_header/build": Relay.QL`
    query BuildsShowBuild($build: ID!) {
      build(slug: $build) {
        id
        createdBy {
          __typename
          ...on UnregisteredUser {
            name
            email
            avatar {
              url
            }
          }
          ...on User {
            id
            name
            email
            avatar {
              url
            }
          }
        }
      }
    }
  `,
  "build_header/viewer": Relay.QL`
    query BuildsShowViewer {
      viewer {
        emails(first: 50) {
          edges {
            node {
              id
              address
              verified
            }
          }
        }
      }
    }
  `,
  "organization_show/organization": Relay.QL`
    query PipelinesList($organization: ID!, $team: TeamSelector, $pageSize: Int, $pipelineFilter: String) {
      organization(slug: $organization) {
        id
        slug
        name
        permissions {
          pipelineCreate {
            code
            allowed
            message
          }
        }
        teams(first: 100) {
          edges {
            node {
              id
              name
              slug
              description
              permissions {
                pipelineView {
                  allowed
                }
              }
            }
            cursor
          }
          pageInfo {
            hasNextPage
            hasPreviousPage
          }
        }
        pipelines(first: $pageSize, search: $pipelineFilter, team: $team, order: NAME_WITH_FAVORITES_FIRST) {
          edges {
            node {
              id
              name
              slug
              description
              url
              favorite
              defaultBranch
              permissions {
                pipelineFavorite {
                  allowed
                }
              }
              metrics(first: 6) {
                edges {
                  node {
                    label
                    value
                    url
                    id
                  }
                  cursor
                }
                pageInfo {
                  hasNextPage
                  hasPreviousPage
                }
              }
              builds(first: 1, branch: "%default", state: [ RUNNING, CANCELING, PASSED, FAILED, CANCELED, BLOCKED ]) {
                edges {
                  node {
                    id
                    message
                    url
                    commit
                    state
                    startedAt
                    finishedAt
                    canceledAt
                    scheduledAt
                    createdBy {
                      __typename
                      ... on User {
                        id
                        name
                        avatar {
                          url
                        }
                      }
                      ...on UnregisteredUser {
                        name
                        avatar {
                          url
                        }
                      }
                    }
                  }
                  cursor
                }
                pageInfo {
                  hasNextPage
                  hasPreviousPage
                }
              }
            }
            cursor
          }
          pageInfo {
            hasNextPage
            hasPreviousPage
          }
        }
      }
    }
  `,
  "navigation/organization": Relay.QL`
    query NavigationOrganization($organization: ID!) {
      organization(slug: $organization) {
        name
        id
        slug
        agents {
          count
        }
        permissions {
          pipelineView {
            allowed
          }
          agentView {
            allowed
          }
          organizationUpdate {
            allowed
          }
          organizationInvitationCreate {
            allowed
          }
          notificationServiceUpdate {
            allowed
          }
          organizationBillingUpdate {
            allowed
          }
          teamView {
            allowed
          }
        }
      }
    }
  `,
  "navigation/viewer": Relay.QL`
    query NavigationViewer {
      viewer {
        id
        user {
          name,
          avatar {
            url
          }
          id
        }
      }
    }
  `,
  "settings_navigation/organization": Relay.QL`
    query GetOrganization($organization: ID!) {
      organization(slug: $organization) {
        id
        name
        slug
        invitations(state: PENDING) {
          count
        }
        permissions {
          organizationUpdate {
            allowed
          }
          organizationMemberView {
            allowed
          }
          notificationServiceUpdate {
            allowed
          }
          organizationBillingUpdate {
            allowed
          }
          teamView {
            allowed
          }
          teamEnabledChange {
            allowed
          }
          auditEventsView {
            allowed
          }
        }
      }
    }
  `,
  "agents/index": Relay.QL`
    query AgentIndex($organization: ID!) {
      organization(slug: $organization) {
        id
        permissions {
          agentTokenView {
            allowed
          }
        }
        agentTokens(first:50, revoked:false) {
          edges {
            node {
              id
              description
              public
              token
            }
            cursor
          },
          pageInfo {
            hasNextPage
            hasPreviousPage
          }
        }
      }
    }
  `,
  "agents/show": Relay.QL`
    query($slug: ID!) {
      agent(slug: $slug) {
        id
        name
        organization {
          id
          name
          slug
        }
        connectedAt
        connectionState
        disconnectedAt
        hostname
        id
        ipAddress
        job {
          __typename
          ... on JobTypeCommand {
            id
            label
            command
            url
            build {
              number
              pipeline {
                name
                id
              }
              id
            }
          }
        }
        lostAt
        metaData
        operatingSystem {
          name
        }
        permissions {
          agentStop {
            allowed
            code
            message
          }
        }
        pid
        pingedAt
        public
        stoppedAt
        stoppedBy {
          name
          id
        }
        userAgent
        uuid
        version
      }
    }
  `,
  "teams/index": Relay.QL`
    query($organization: ID!) {
      organization(slug: $organization) {
        id
        name
        slug
        permissions {
          teamView {
            allowed
            code
            message
          }
          teamEnabledChange {
            allowed
            code
            message
          }
          teamCreate {
            allowed
          }
        }
      }
    }
  `,
  "sso/index": Relay.QL`
    query($organization: ID!) {
      organization(slug: $organization) {
        id
        name
        slug
        permissions {
          organizationUpdate {
            allowed
          }
        }
      }
    }
  `,
  "pipeline/header": Relay.QL`
    query($pipeline: ID!) {
      pipeline(slug: $pipeline) {
        id
        name
        description
        url
        slug
        defaultBranch
        organization {
          name
          slug
          id
        }
        repository {
          url
          provider {
            __typename
            url
          }
        }
        builds {
          count
        }
        scheduledBuilds: builds(state: SCHEDULED) {
          count
        }
        runningBuilds: builds(state: RUNNING) {
          count
        }
        permissions {
          pipelineUpdate {
            allowed
            code
            message
          }
          buildCreate {
            allowed
            code
            message
          }
        }
      }
    }
  `,
  "pipeline/settings": Relay.QL`
    query($pipeline: ID!) {
      pipeline(slug: $pipeline) {
        id
        name
        slug
        organization {
          slug
          permissions {
            teamView {
              allowed
            }
          }
        }
        repository {
          provider {
            __typename
            name
          }
        }
        teams {
          count
        }
        schedules {
          count
        }
        permissions {
          pipelineUpdate {
            allowed
          }
        }
      }
    }
  `,
  "pipeline/teams_settings": Relay.QL`
    query($pipeline: ID!) {
      pipeline(slug: $pipeline) {
        id
        slug
        name
        organization {
          id
          slug
        }
        teams(first: 500) {
          count
          edges {
            node {
              id
              accessLevel
              team {
                id
                name
                description
                slug
                members {
                  count
                }
                pipelines {
                  count
                }
              }
              permissions {
                teamPipelineUpdate {
                  allowed
                }
                teamPipelineDelete {
                  allowed
                }
              }
            }
          }
        }
      }
    }
  `,
  "build_show/annotations": Relay.QL`
    query BuildAnnotations($build: ID!) {
      build(slug: $build) {
        id
	annotations(first: 10) {
          edges {
            node {
              id
              style
              body {
                html
              }
            }
            cursor
          }
          pageInfo {
            hasNextPage
            hasPreviousPage
          }
        }
      }
    }
  `,
  "graphql_console/snippet": Relay.QL`
    query GraphQLSnippet($uuid: String!) {
      graphQLSnippet(uuid: $uuid) {
        query
        operationName
        url
      }
    }
  `
};

class RelayPreloader {
  preload(id: string, payload: Object, variables: Object) {
    // Get the concrete query
    const concrete = QUERIES[id];
    if (!concrete) {
      throw new Error(`No concrete query defined for \`${id}\``);
    }

    // Create a Relay-readable GraphQL query with the variables loaded in
    const query = fromGraphQL.Query(concrete);
    query.__variables__ = variables;

    // Load it with the payload into the Relay store
    Relay.Store.getStoreData().handleQueryPayload(query, payload);
  }
}

export default new RelayPreloader();
<commit_msg>Preload the `allPipelines` count on the organization show page<commit_after>// @flow

import Relay from 'react-relay/classic';
import fromGraphQL from 'react-relay/lib/fromGraphQL';

const QUERIES = {
  "build_header/build": Relay.QL`
    query BuildsShowBuild($build: ID!) {
      build(slug: $build) {
        id
        createdBy {
          __typename
          ...on UnregisteredUser {
            name
            email
            avatar {
              url
            }
          }
          ...on User {
            id
            name
            email
            avatar {
              url
            }
          }
        }
      }
    }
  `,
  "build_header/viewer": Relay.QL`
    query BuildsShowViewer {
      viewer {
        emails(first: 50) {
          edges {
            node {
              id
              address
              verified
            }
          }
        }
      }
    }
  `,
  "organization_show/organization": Relay.QL`
    query PipelinesList($organization: ID!, $team: TeamSelector, $pageSize: Int, $pipelineFilter: String) {
      organization(slug: $organization) {
        id
        slug
        name
        permissions {
          pipelineCreate {
            code
            allowed
            message
          }
        }
        teams(first: 100) {
          edges {
            node {
              id
              name
              slug
              description
              permissions {
                pipelineView {
                  allowed
                }
              }
            }
            cursor
          }
          pageInfo {
            hasNextPage
            hasPreviousPage
          }
        }
        allPipelines: pipelines(team: $team) {
          count
        }
        pipelines(first: $pageSize, search: $pipelineFilter, team: $team, order: NAME_WITH_FAVORITES_FIRST) {
          edges {
            node {
              id
              name
              slug
              description
              url
              favorite
              defaultBranch
              permissions {
                pipelineFavorite {
                  allowed
                }
              }
              metrics(first: 6) {
                edges {
                  node {
                    label
                    value
                    url
                    id
                  }
                  cursor
                }
                pageInfo {
                  hasNextPage
                  hasPreviousPage
                }
              }
              builds(first: 1, branch: "%default", state: [ RUNNING, CANCELING, PASSED, FAILED, CANCELED, BLOCKED ]) {
                edges {
                  node {
                    id
                    message
                    url
                    commit
                    state
                    startedAt
                    finishedAt
                    canceledAt
                    scheduledAt
                    createdBy {
                      __typename
                      ... on User {
                        id
                        name
                        avatar {
                          url
                        }
                      }
                      ...on UnregisteredUser {
                        name
                        avatar {
                          url
                        }
                      }
                    }
                  }
                  cursor
                }
                pageInfo {
                  hasNextPage
                  hasPreviousPage
                }
              }
            }
            cursor
          }
          pageInfo {
            hasNextPage
            hasPreviousPage
          }
        }
      }
    }
  `,
  "navigation/organization": Relay.QL`
    query NavigationOrganization($organization: ID!) {
      organization(slug: $organization) {
        name
        id
        slug
        agents {
          count
        }
        permissions {
          pipelineView {
            allowed
          }
          agentView {
            allowed
          }
          organizationUpdate {
            allowed
          }
          organizationInvitationCreate {
            allowed
          }
          notificationServiceUpdate {
            allowed
          }
          organizationBillingUpdate {
            allowed
          }
          teamView {
            allowed
          }
        }
      }
    }
  `,
  "navigation/viewer": Relay.QL`
    query NavigationViewer {
      viewer {
        id
        user {
          name,
          avatar {
            url
          }
          id
        }
      }
    }
  `,
  "settings_navigation/organization": Relay.QL`
    query GetOrganization($organization: ID!) {
      organization(slug: $organization) {
        id
        name
        slug
        invitations(state: PENDING) {
          count
        }
        permissions {
          organizationUpdate {
            allowed
          }
          organizationMemberView {
            allowed
          }
          notificationServiceUpdate {
            allowed
          }
          organizationBillingUpdate {
            allowed
          }
          teamView {
            allowed
          }
          teamEnabledChange {
            allowed
          }
          auditEventsView {
            allowed
          }
        }
      }
    }
  `,
  "agents/index": Relay.QL`
    query AgentIndex($organization: ID!) {
      organization(slug: $organization) {
        id
        permissions {
          agentTokenView {
            allowed
          }
        }
        agentTokens(first:50, revoked:false) {
          edges {
            node {
              id
              description
              public
              token
            }
            cursor
          },
          pageInfo {
            hasNextPage
            hasPreviousPage
          }
        }
      }
    }
  `,
  "agents/show": Relay.QL`
    query($slug: ID!) {
      agent(slug: $slug) {
        id
        name
        organization {
          id
          name
          slug
        }
        connectedAt
        connectionState
        disconnectedAt
        hostname
        id
        ipAddress
        job {
          __typename
          ... on JobTypeCommand {
            id
            label
            command
            url
            build {
              number
              pipeline {
                name
                id
              }
              id
            }
          }
        }
        lostAt
        metaData
        operatingSystem {
          name
        }
        permissions {
          agentStop {
            allowed
            code
            message
          }
        }
        pid
        pingedAt
        public
        stoppedAt
        stoppedBy {
          name
          id
        }
        userAgent
        uuid
        version
      }
    }
  `,
  "teams/index": Relay.QL`
    query($organization: ID!) {
      organization(slug: $organization) {
        id
        name
        slug
        permissions {
          teamView {
            allowed
            code
            message
          }
          teamEnabledChange {
            allowed
            code
            message
          }
          teamCreate {
            allowed
          }
        }
      }
    }
  `,
  "sso/index": Relay.QL`
    query($organization: ID!) {
      organization(slug: $organization) {
        id
        name
        slug
        permissions {
          organizationUpdate {
            allowed
          }
        }
      }
    }
  `,
  "pipeline/header": Relay.QL`
    query($pipeline: ID!) {
      pipeline(slug: $pipeline) {
        id
        name
        description
        url
        slug
        defaultBranch
        organization {
          name
          slug
          id
        }
        repository {
          url
          provider {
            __typename
            url
          }
        }
        builds {
          count
        }
        scheduledBuilds: builds(state: SCHEDULED) {
          count
        }
        runningBuilds: builds(state: RUNNING) {
          count
        }
        permissions {
          pipelineUpdate {
            allowed
            code
            message
          }
          buildCreate {
            allowed
            code
            message
          }
        }
      }
    }
  `,
  "pipeline/settings": Relay.QL`
    query($pipeline: ID!) {
      pipeline(slug: $pipeline) {
        id
        name
        slug
        organization {
          slug
          permissions {
            teamView {
              allowed
            }
          }
        }
        repository {
          provider {
            __typename
            name
          }
        }
        teams {
          count
        }
        schedules {
          count
        }
        permissions {
          pipelineUpdate {
            allowed
          }
        }
      }
    }
  `,
  "pipeline/teams_settings": Relay.QL`
    query($pipeline: ID!) {
      pipeline(slug: $pipeline) {
        id
        slug
        name
        organization {
          id
          slug
        }
        teams(first: 500) {
          count
          edges {
            node {
              id
              accessLevel
              team {
                id
                name
                description
                slug
                members {
                  count
                }
                pipelines {
                  count
                }
              }
              permissions {
                teamPipelineUpdate {
                  allowed
                }
                teamPipelineDelete {
                  allowed
                }
              }
            }
          }
        }
      }
    }
  `,
  "build_show/annotations": Relay.QL`
    query BuildAnnotations($build: ID!) {
      build(slug: $build) {
        id
	annotations(first: 10) {
          edges {
            node {
              id
              style
              body {
                html
              }
            }
            cursor
          }
          pageInfo {
            hasNextPage
            hasPreviousPage
          }
        }
      }
    }
  `,
  "graphql_console/snippet": Relay.QL`
    query GraphQLSnippet($uuid: String!) {
      graphQLSnippet(uuid: $uuid) {
        query
        operationName
        url
      }
    }
  `
};

class RelayPreloader {
  preload(id: string, payload: Object, variables: Object) {
    // Get the concrete query
    const concrete = QUERIES[id];
    if (!concrete) {
      throw new Error(`No concrete query defined for \`${id}\``);
    }

    // Create a Relay-readable GraphQL query with the variables loaded in
    const query = fromGraphQL.Query(concrete);
    query.__variables__ = variables;

    // Load it with the payload into the Relay store
    Relay.Store.getStoreData().handleQueryPayload(query, payload);
  }
}

export default new RelayPreloader();
<|endoftext|>