<commit_before>var map;
var service;

var viewModel;

var Place = function(place) {
  var self = this;

  this.id = ko.observable('');  // the place id of the place in Google Maps
  this.name = place;
  this.location = {lat: 0, lng: 0};
  this.description = ko.observable('');
  this.photo = ko.observable('');
  this.icon = ko.observable('');

  this.visibility = ko.observable(true);

  this.infoWindowContent = ko.computed(function() {

    var imgElement;
    if (this.photo() === '') {
      imgElement = '';
    } else {
      imgElement = '';
    }

    var content =
    imgElement +
    '
' + this.name + '
' +
    '
' +
    this.description() +
    '
';
    return content;
  }, this);

  $.ajax({
    url: 'https://en.wikipedia.org/w/api.php',
    dataType: 'jsonp',
    data: {
      action: 'query',
      format: 'json',
      prop: 'extracts',
      exsentences: '3',
      titles: self.name
    }
  }).done(function(result) {
    if (result.query === undefined) {
      // there is no wikipedia article in the result, which means no article found.
      self.description('
No article related to '+ self.name + ' can be found in Wikipedia.
');
      return;
    }

    var pages = result.query.pages;
    for (var pageid in pages) {
      if (pages.hasOwnProperty(pageid)) {
        var extract = pages[pageid].extract;

        self.description(extract + '
from Wikipedia
');

        break;
      }
    }

    // there is no wikipedia article in the result, which means no article found.
    self.description('
No article related to '+ self.name + ' can be found in Wikipedia.
');
  }).fail(function(error) {
    var message = 'Failed to get article related to '+ self.name + ' from Wikipedia.';
    self.description('
' + message + '
');
    console.log(message);
  });
};

var ViewModel = function() {
  var self = this;

  this.places = ko.observableArray([]);
  this.filter = ko.observable('');
  this.lastOpenedInfoWindow;  // keep track of last opened info window, to ensure that not more than 1 window is opened

  this.placeToMarkerMappings = [];  // place to marker mappings

  this.filter.subscribe(function(newValue) {
    self.updatePlaceVisibilities()
  });

  $.ajax({
    url: 'places.json',
    dataType: 'json'
  }).done(function(result) {
    var places = result.places;

    places.forEach(function(place) {
      var place = new Place(place);
      self.places.push(place);
      place.id.subscribe(function() {
        self.addMarker(place);
      }.bind(place));
      if (map !== undefined) {
        // Google Maps API is ready, lets update place info from Google Maps
        setTimeout(function() {
          self.updateSinglePlaceInfo(place);
        }, 100 * self.places().indexOf(place));
      } else {
        // Google Maps library is not loaded yet, the place info will be
        // update after the library is loaded.
        // See also: initMap()
      }
    });
  }).fail(function(error) {
    alert('Failed to get the list of places from server');
  });

  this.updatePlaceVisibilities = function() {
    var filter = self.filter().toLocaleUpperCase();
    self.places().forEach(function(place) {
      var name = place.name.toLocaleUpperCase();
      place.visibility(name.includes(filter));

      var marker = self.getMarker(place);
      if (marker !== undefined) {
        if (place.visibility() === true) {
          self.showMarker(marker);
        } else {
          self.hideMarker(marker);
        }
      }
    });
  };

  this.updateSinglePlaceInfo = function(place) {
    if (place.id() !== '') {
      // the place info are ready, no need to get it again
      return;
    }

    service.textSearch({query: place.name}, function(results, status) {
      if (status === google.maps.places.PlacesServiceStatus.OK) {
        place.location = {lat: results[0].geometry.location.lat(), lng: results[0].geometry.location.lng()};
        if (results[0].hasOwnProperty('photos')) {
          place.photo(results[0].photos[0].getUrl({maxWidth: 300}));
        }
        place.icon('https://maps.google.com/mapfiles/ms/icons/red-dot.png');

        // the id is a flag to indicate that the data are all fetched, so it has to be set at the end of callback.
        place.id(results[0].place_id);
      } else if (status === google.maps.places.PlacesServiceStatus.OVER_QUERY_LIMIT) {
        // wait 2 sec, then try getting data from Google Maps again
        setTimeout(function() {
          self.updateSinglePlaceInfo(place);
        }, 2000);
      } else {
        console.log('failed to get info of ' + place.name + ' from Google Maps');
      }
    });
  };

  this.getMarker = function(place) {
    for (var i = 0; i < self.placeToMarkerMappings.length; i++) {
      var mapping = self.placeToMarkerMappings[i];
      if (mapping.place === place) {
        return mapping.marker;
      }
    }

    return undefined;
  };

  this.updateAllPlaceInfo = function() {
    self.places().forEach(function(place){
      var marker = self.getMarker(place);
      if (marker === undefined) {
        setTimeout(function() {
          self.updateSinglePlaceInfo(place);
        }, 100 * self.places().indexOf(place));
      }
    });
  };

  this.setIconColor = function(place, color) {
    switch (color) {
      case 'red':
        place.icon('https://maps.google.com/mapfiles/ms/icons/red-dot.png');
        break;
      case 'yellow':
        place.icon('https://maps.google.com/mapfiles/ms/icons/yellow-dot.png');
        break;
      default:
        console.log(color + ' is not a valid icon color');
    }
  }

  this.moveMarkerToFront = function(marker, value) {
    if (marker === undefined) {
      // do nothing on an undefined marker
      return;
    }

    if (value === true) {
      marker.setZIndex(marker.getZIndex() + 1);
    } else {
      marker.setZIndex(marker.getZIndex() - 1);
    }
  };

  this.addMarker = function(place) {
    var id = place.id();
    var title = place.name;
    var position = new google.maps.LatLng(place.location.lat, place.location.lng);  // position should be 0, 0 here.
    var icon = place.icon();
    var infoWindowContent = place.infoWindowContent();

    var infowindow = new google.maps.InfoWindow({
      content: infoWindowContent,
      maxWidth: 300
    });

    place.infoWindowContent.subscribe(function(newValue) {
      infowindow.setContent(newValue);
    });

    var marker = new google.maps.Marker({
      id: id,
      title: title,
      position: position,
      animation: google.maps.Animation.DROP,
      icon: icon,
      zIndex: 0
    });

    place.icon.subscribe(function (newValue) {
      marker.setIcon(newValue);
    });

    marker.addListener('click', function() {
      // Close last opened info window if there is any.
      if (self.lastOpenedInfoWindow !== undefined) {
        self.lastOpenedInfoWindow.close();
      }

      infowindow.open(map, marker);

      marker.setAnimation(google.maps.Animation.BOUNCE);
      setTimeout(function() {
        marker.setAnimation(null);
      }, 700);

      self.lastOpenedInfoWindow = infowindow;
    });

    marker.addListener('click', function() {
      // Close last opened info window if there is any.
      if (self.lastOpenedInfoWindow !== undefined) {
        self.lastOpenedInfoWindow.close();
      }

      infowindow.open(map, marker);

      marker.setAnimation(google.maps.Animation.BOUNCE);
      setTimeout(function() {
        marker.setAnimation(null);
      }, 700);

      self.lastOpenedInfoWindow = infowindow;
    });

    marker.addListener('visible_changed', function() {
      infowindow.close();
    });

    marker.addListener('mouseover', function() {
      self.setIconColor(place, 'yellow');
      self.moveMarkerToFront(marker, true);
    });

    marker.addListener('mouseout', function() {
      self.setIconColor(place, 'red');
      self.moveMarkerToFront(marker, false);
    });

    // Display the new marker
    marker.setMap(map);

    self.placeToMarkerMappings.push({place: place, marker: marker});

    if (place.visibility() === true) {
      self.showMarker(marker);
    } else {
      self.hideMarker(marker);
    }
  };

  this.showInfoWindow = function(place) {
    var marker = self.getMarker(place);
    if (marker !== undefined) {
      new google.maps.event.trigger(marker, 'click');
    }
  };

  // show specified marker on the map
  this.showMarker = function(marker) {
    marker.setVisible(true);
  }

  // Hide specified marker from the map
  this.hideMarker = function(marker) {
    marker.setVisible(false);
  }
};

viewModel = new ViewModel();
ko.applyBindings(viewModel);

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 22.3964, lng: 114.1095},  // Set center to Hong Kong
    zoom: 10  // Set Zoom level to city
  });

  service = new google.maps.places.PlacesService(map);

  viewModel.updateAllPlaceInfo();
}

function showInfoWindow(place) {
  $('.row-offcanvas').removeClass('active');
  viewModel.showInfoWindow(place);
}

function highlightMarker(place) {
  var marker = viewModel.getMarker(place);
  if (marker !== undefined) {
    viewModel.setIconColor(place, 'yellow');
    viewModel.moveMarkerToFront(marker, true);
  }
};

function undoHighlightMarker(place) {
  var marker = viewModel.getMarker(place);
  if (marker !== undefined) {
    viewModel.setIconColor(place, 'red');
    viewModel.moveMarkerToFront(marker, false);
  }
}
<commit_msg>Show warning marker if no data of the place can be found in Google Maps<commit_after>var map;
var service;

var redMarker = 'https://maps.google.com/mapfiles/ms/icons/red-dot.png';
var yellowMarker = 'https://maps.google.com/mapfiles/ms/icons/yellow-dot.png';
var warningMarker = 'https://maps.google.com/mapfiles/kml/pal3/icon33.png';

var viewModel;

var Place = function(place) {
  var self = this;

  this.id = ko.observable('');  // the place id of the place in Google Maps
  this.name = place;
  this.location = {lat: 0, lng: 0};
  this.description = ko.observable('');
  this.photo = ko.observable('');
  this.icon = ko.observable('');

  this.visibility = ko.observable(true);

  this.infoWindowContent = ko.computed(function() {

    var imgElement;
    if (this.photo() === '') {
      imgElement = '';
    } else {
      imgElement = '';
    }

    var content =
    imgElement +
    '
' + this.name + '
' +
    '
' +
    this.description() +
    '
';
    return content;
  }, this);

  $.ajax({
    url: 'https://en.wikipedia.org/w/api.php',
    dataType: 'jsonp',
    data: {
      action: 'query',
      format: 'json',
      prop: 'extracts',
      exsentences: '3',
      titles: self.name
    }
  }).done(function(result) {
    if (result.query === undefined) {
      // there is no wikipedia article in the result, which means no article found.
      self.description('
No article related to '+ self.name + ' can be found in Wikipedia.
');
      return;
    }

    var pages = result.query.pages;
    for (var pageid in pages) {
      if (pages.hasOwnProperty(pageid)) {
        var extract = pages[pageid].extract;

        self.description(extract + '
from Wikipedia
');

        break;
      }
    }

    // there is no wikipedia article in the result, which means no article found.
    self.description('
No article related to '+ self.name + ' can be found in Wikipedia.
');
  }).fail(function(error) {
    var message = 'Failed to get article related to '+ self.name + ' from Wikipedia.';
    self.description('
' + message + '
');
    console.log(message);
  });
};

var ViewModel = function() {
  var self = this;

  this.places = ko.observableArray([]);
  this.filter = ko.observable('');
  this.lastOpenedInfoWindow;  // keep track of last opened info window, to ensure that not more than 1 window is opened

  this.placeToMarkerMappings = [];  // place to marker mappings

  this.filter.subscribe(function(newValue) {
    self.updatePlaceVisibilities()
  });

  $.ajax({
    url: 'places.json',
    dataType: 'json'
  }).done(function(result) {
    var places = result.places;

    places.forEach(function(place) {
      var place = new Place(place);
      self.places.push(place);
      place.id.subscribe(function() {
        self.addMarker(place);
      }.bind(place));
      if (map !== undefined) {
        // Google Maps API is ready, lets update place info from Google Maps
        setTimeout(function() {
          self.updateSinglePlaceInfo(place);
        }, 100 * self.places().indexOf(place));
      } else {
        // Google Maps library is not loaded yet, the place info will be
        // update after the library is loaded.
        // See also: initMap()
      }
    });
  }).fail(function(error) {
    alert('Failed to get the list of places from server');
  });

  this.updatePlaceVisibilities = function() {
    var filter = self.filter().toLocaleUpperCase();
    self.places().forEach(function(place) {
      var name = place.name.toLocaleUpperCase();
      place.visibility(name.includes(filter));

      var marker = self.getMarker(place);
      if (marker !== undefined) {
        if (place.visibility() === true) {
          self.showMarker(marker);
        } else {
          self.hideMarker(marker);
        }
      }
    });
  };

  this.updateSinglePlaceInfo = function(place) {
    if (place.id() !== '') {
      // the place info are ready, no need to get it again
      return;
    }

    service.textSearch({query: place.name}, function(results, status) {
      if (status === google.maps.places.PlacesServiceStatus.OK) {
        place.location = {lat: results[0].geometry.location.lat(), lng: results[0].geometry.location.lng()};
        if (results[0].hasOwnProperty('photos')) {
          place.photo(results[0].photos[0].getUrl({maxWidth: 300}));
        }
        place.icon(redMarker);

        // the id is a flag to indicate that the data are all fetched, so it has to be set at the end of callback.
        place.id(results[0].place_id);
      } else if (status === google.maps.places.PlacesServiceStatus.OVER_QUERY_LIMIT) {
        // wait 2 sec, then try getting data from Google Maps again
        setTimeout(function() {
          self.updateSinglePlaceInfo(place);
        }, 2000);
      } else {
        place.icon(warningMarker);
        console.log('Failed to get info of '+ place.name + ' from Google Maps.');
      }
    });
  };

  this.getMarker = function(place) {
    for (var i = 0; i < self.placeToMarkerMappings.length; i++) {
      var mapping = self.placeToMarkerMappings[i];
      if (mapping.place === place) {
        return mapping.marker;
      }
    }

    return undefined;
  };

  this.updateAllPlaceInfo = function() {
    self.places().forEach(function(place){
      var marker = self.getMarker(place);
      if (marker === undefined) {
        setTimeout(function() {
          self.updateSinglePlaceInfo(place);
        }, 100 * self.places().indexOf(place));
      }
    });
  };

  this.setIconColor = function(place, color) {
    switch (color) {
      case 'red':
        place.icon(redMarker);
        break;
      case 'yellow':
        place.icon(yellowMarker);
        break;
      default:
        console.log(color + ' is not a valid icon color');
    }
  }

  this.moveMarkerToFront = function(marker, value) {
    if (marker === undefined) {
      // do nothing on an undefined marker
      return;
    }

    if (value === true) {
      marker.setZIndex(marker.getZIndex() + 1);
    } else {
      marker.setZIndex(marker.getZIndex() - 1);
    }
  };

  this.addMarker = function(place) {
    var id = place.id();
    var title = place.name;
    var position = new google.maps.LatLng(place.location.lat, place.location.lng);  // position should be 0, 0 here.
    var icon = place.icon();
    var infoWindowContent = place.infoWindowContent();

    var infowindow = new google.maps.InfoWindow({
      content: infoWindowContent,
      maxWidth: 300
    });

    place.infoWindowContent.subscribe(function(newValue) {
      infowindow.setContent(newValue);
    });

    var marker = new google.maps.Marker({
      id: id,
      title: title,
      position: position,
      animation: google.maps.Animation.DROP,
      icon: icon,
      zIndex: 0
    });

    place.icon.subscribe(function (newValue) {
      marker.setIcon(newValue);
    });

    marker.addListener('click', function() {
      // Close last opened info window if there is any.
      if (self.lastOpenedInfoWindow !== undefined) {
        self.lastOpenedInfoWindow.close();
      }

      infowindow.open(map, marker);

      marker.setAnimation(google.maps.Animation.BOUNCE);
      setTimeout(function() {
        marker.setAnimation(null);
      }, 700);

      self.lastOpenedInfoWindow = infowindow;
    });

    marker.addListener('click', function() {
      // Close last opened info window if there is any.
      if (self.lastOpenedInfoWindow !== undefined) {
        self.lastOpenedInfoWindow.close();
      }

      infowindow.open(map, marker);

      marker.setAnimation(google.maps.Animation.BOUNCE);
      setTimeout(function() {
        marker.setAnimation(null);
      }, 700);

      self.lastOpenedInfoWindow = infowindow;
    });

    marker.addListener('visible_changed', function() {
      infowindow.close();
    });

    marker.addListener('mouseover', function() {
      self.setIconColor(place, 'yellow');
      self.moveMarkerToFront(marker, true);
    });

    marker.addListener('mouseout', function() {
      self.setIconColor(place, 'red');
      self.moveMarkerToFront(marker, false);
    });

    // Display the new marker
    marker.setMap(map);

    self.placeToMarkerMappings.push({place: place, marker: marker});

    if (place.visibility() === true) {
      self.showMarker(marker);
    } else {
      self.hideMarker(marker);
    }
  };

  this.showInfoWindow = function(place) {
    var marker = self.getMarker(place);
    if (marker !== undefined) {
      new google.maps.event.trigger(marker, 'click');
    }
  };

  // show specified marker on the map
  this.showMarker = function(marker) {
    marker.setVisible(true);
  }

  // Hide specified marker from the map
  this.hideMarker = function(marker) {
    marker.setVisible(false);
  }
};

viewModel = new ViewModel();
ko.applyBindings(viewModel);

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: 22.3964, lng: 114.1095},  // Set center to Hong Kong
    zoom: 10  // Set Zoom level to city
  });

  service = new google.maps.places.PlacesService(map);

  viewModel.updateAllPlaceInfo();
}

function showInfoWindow(place) {
  $('.row-offcanvas').removeClass('active');
  viewModel.showInfoWindow(place);
}

function highlightMarker(place) {
  var marker = viewModel.getMarker(place);
  if (marker !== undefined) {
    viewModel.setIconColor(place, 'yellow');
    viewModel.moveMarkerToFront(marker, true);
  }
};

function undoHighlightMarker(place) {
  var marker = viewModel.getMarker(place);
  if (marker !== undefined) {
    viewModel.setIconColor(place, 'red');
    viewModel.moveMarkerToFront(marker, false);
  }
}
<|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Info Cram 6000.
 *
 * The Initial Developer of the Original Code is
 * Jiří Mašek.
 * Portions created by the Initial Developer are Copyright (C) 2010
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * ***** END LICENSE BLOCK ***** */

/* ************************************************************************** *
 * ******************************** AARDVARK ******************************** *
 * ************************************************************************** */

selectowl.aardvark.resource = null;

/**
 * Spustí Aardvark.
 */
selectowl.aardvark.start = function( resource ) {
    this.resource = resource;
    var currentBrowser  = aardvarkUtils.currentBrowser();
    aardvarkSelector.start(currentBrowser);
}

/**
 * Zpracuje element vybraný pomocí aardvarku, tj. vygeneruje pro něj selektor
 * a přidá jej do stromu.
 *
 * @param elem      vybraný element
 */
selectowl.aardvark.onSelect = function(elem) {
  var _gui = selectowl.gui;

  var ts_context = selectowl.scenario.tree.getSelected();
  var context = ts_context ? ts_context.step.selector : null;

  // results
  var name;
  var selector;

  var currDoc = aardvarkUtils.currentDocument();

  //var parents = context == "" ? Sizzle("body", currDoc) : Sizzle(context, currDoc);
  var parents = context ? $(currDoc).find(context).parents().andSelf().get()/* <-- get() all of them*/ : $(currDoc).find('body').get();

  var topReached = false;
  var idFound = false;

  do
  {
      var node = elem.tagName.toLowerCase();

      // přidaní selektoru ID

      if (elem.id != "") {
          if (!name) {
              name = elem.id;
          }

          // ověření, zdali je ID v rámci dokumentu unikátní

          if (isUniqueID(elem.id, elem.ownerDocument)) {
              node += "#" + elem.id;

              idFound = true;
          } else {
              node += "[id=" + elem.id + "]";
          }
      }

      // přidaní selektoru třídy

      if (elem.className != "") {
          var classes  = elem.className.split(" ");

          for (var i in classes) {
              if (classes[i] != "selectowl-selection") {
                  if (!name) {
                      name = classes[i];
                  }

                  node += "." + classes[i];
              }
          }
      }

      selector = selector == undefined ? node : node + " " + selector;

      elem = elem.parentNode && elem.parentNode.nodeType == elem.ELEMENT_NODE ? elem.parentNode : null;

      // ověření, zdali rodič elementu zpracovávaného v cyklu není již
      // elementem nadřazeného kontextu

      for (var j = 0; j < parents.length; j++) {
          if (parents[j] == elem) {
              topReached = true;
              break;
          }
      }
  } while (!topReached && !idFound && elem != null);

  // přidání selektoru do stromu

  //_gui.addNode(indexOfContext, selector, name);

  selectowl.scenario.tree.createNewStep(this.resource, selector);
  aardvarkSelector.doCommand('quit');
}

///**
// * Ověří, jestli se daný element nachází v zadaném kontextu.
// *
// * @param elem      element
// * @param context   kontext
// * @return          true nachází-li se v kontextu,
// *                  false nenachází-li
// */
//selectowl.aardvark.isInContext = function(elem, context) {
//    var currentDocument = aardvarkUtils.currentDocument();
//
//    var selected = Sizzle(trim(context + " *"), currentDocument);
//
//    var isInContext = false;
//
//    for (var i = 0; i < selected.length; i++) {
//        if (selected[i] == elem) {
//            isInContext = true;
//            break;
//        }
//    }
//
//    return isInContext;
//}

///**
// * Vrátí index uzlu stromu, do jehož kontextu zapadá daný element.
// *
// * @param elem      element
// * @return          index uzlu stromu
// */
//selectowl.aardvark.getIndexOfContext = function(elem) {
//    var _gui = this._parent.gui;
//
//    var tree = _gui.get();
//
//    var index = tree.currentIndex;
//
//    if (index > 0) {
//        var context = _gui.getContext(index, true);
//
//        while (!this.isInContext(elem, context)) {
//            index = tree.view.getParentIndex(index);
//            context = _gui.getContext(index, true);
//        }
//
//        return index;
//    } else {
//        return 0;
//    }
//}
<commit_msg>added number restrictions into automatic generator of selectors<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Info Cram 6000.
 *
 * The Initial Developer of the Original Code is
 * Jiří Mašek.
 * Portions created by the Initial Developer are Copyright (C) 2010
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * ***** END LICENSE BLOCK ***** */

/* ************************************************************************** *
 * ******************************** AARDVARK ******************************** *
 * ************************************************************************** */

selectowl.aardvark.resource = null;

/**
 * Spustí Aardvark.
 */
selectowl.aardvark.start = function( resource ) {
    this.resource = resource;
    var currentBrowser  = aardvarkUtils.currentBrowser();
    aardvarkSelector.start(currentBrowser);
}

/**
 * Zpracuje element vybraný pomocí aardvarku, tj. vygeneruje pro něj selektor
 * a přidá jej do stromu.
 *
 * @param elem      vybraný element
 */
selectowl.aardvark.onSelect = function(elem) {
  var selector = this.getBestSelector(elem);
  selectowl.scenario.tree.createNewStep(this.resource, selector);
  aardvarkSelector.doCommand('quit');
};

selectowl.aardvark.getBestSelector = function(elem) {
  var orig = elem;

  var ts_context = selectowl.scenario.tree.getSelected();
  var context = ts_context ? ts_context.step.selector : null;

  // results
  var name;
  var selector;

  var currDoc = aardvarkUtils.currentDocument();

  //var parents = context == "" ? Sizzle("body", currDoc) : Sizzle(context, currDoc);
  var parents = context ? $(currDoc).find(context).parents().andSelf().get()/* <-- get() all of them*/ : $(currDoc).find('body').get();

  var topReached = false;
  var idFound = false;
  var isFound = false;
  do
  {
      var node = elem.tagName.toLowerCase();

      // přidaní selektoru ID

      if (elem.id != "") {
          if (!name) {
              name = elem.id;
          }

          // ověření, zdali je ID v rámci dokumentu unikátní

          if (isUniqueID(elem.id, elem.ownerDocument)) {
              node += "#" + elem.id;

              idFound = true;
          } else {
              node += "[id=" + elem.id + "]";
          }
      }

      // přidaní selektoru třídy

      if (elem.className != "") {
          var classes  = elem.className.split(" ");

          for (var i in classes) {
              if (classes[i] != "selectowl-selection") {
                  if (!name) {
                      name = classes[i];
                  }

                  node += "." + classes[i];
              }
          }
      }

      prev = elem;
      elem = (elem.parentNode && elem.parentNode.nodeType == elem.ELEMENT_NODE)  ?  elem.parentNode  :  null;

      // ověření, zdali rodič elementu zpracovávaného v cyklu není již
      // elementem nadřazeného kontextu

      for (var j = 0; j < parents.length; j++) {
          if (parents[j] == elem) {
              topReached = true;
              break;
          }
      }

      // index if needed to match properly!
      if (!idFound) {
        var idx = $(elem).children().index(prev);
        if (idx != -1) {
          node += ":eq(" + idx + ")";
        }
        console.log('looking for element: ' + prev.tagName + ' within element: ' + elem.tagName + ' with result idx: ' + idx);
      }

      selector = selector == undefined ? node : node + " " + selector;

      // already equivavent?
      var $found = $(currDoc).find(selector);
      if ($found.length == 1 && $found.get(0) == orig) {
        isFound = true;
      }

  } while (!topReached && !idFound && !isFound && elem != null);

  return selector;
};

///**
// * Ověří, jestli se daný element nachází v zadaném kontextu.
// *
// * @param elem      element
// * @param context   kontext
// * @return          true nachází-li se v kontextu,
// *                  false nenachází-li
// */
//selectowl.aardvark.isInContext = function(elem, context) {
//    var currentDocument = aardvarkUtils.currentDocument();
//
//    var selected = Sizzle(trim(context + " *"), currentDocument);
//
//    var isInContext = false;
//
//    for (var i = 0; i < selected.length; i++) {
//        if (selected[i] == elem) {
//            isInContext = true;
//            break;
//        }
//    }
//
//    return isInContext;
//}

///**
// * Vrátí index uzlu stromu, do jehož kontextu zapadá daný element.
// *
// * @param elem      element
// * @return          index uzlu stromu
// */
//selectowl.aardvark.getIndexOfContext = function(elem) {
//    var _gui = this._parent.gui;
//
//    var tree = _gui.get();
//
//    var index = tree.currentIndex;
//
//    if (index > 0) {
//        var context = _gui.getContext(index, true);
//
//        while (!this.isInContext(elem, context)) {
//            index = tree.view.getParentIndex(index);
//            context = _gui.getContext(index, true);
//        }
//
//        return index;
//    } else {
//        return 0;
//    }
//}
<|endoftext|>


<commit_before>/*global describe,it,takeScreenshot,browser,expect*/

describe("sap.m.SegmentedButton", function() {
	"use strict";

	browser.testrunner.currentSuite.meta.controlName = 'sap.m.SegmentedButton';

	it("should render SegmentedButton", function() {
		expect(takeScreenshot()).toLookAs("SegmentedButton_initial");
	}, 2000);

});<commit_msg>[INTERNAL] sap.m.SegmentedButton: visual test stabilisation<commit_after>/*global describe,it,takeScreenshot,browser,expect*/

describe("sap.m.SegmentedButton", function() {
	"use strict";

	browser.testrunner.currentSuite.meta.controlName = 'sap.m.SegmentedButton';

	it("should render SegmentedButton", function() {
		expect(takeScreenshot()).toLookAs("SegmentedButton_initial");
	}, 4000);

});<|endoftext|>


<commit_before>
/* global Graph, astar, ok, test, equal */

test( "Sanity Checks", function() {
  ok (typeof Graph !== "undefined", "Graph exists");
  ok (typeof astar !== "undefined", "Astar exists");
});

test( "Basic Horizontal", function() {

  var result1 = runSearch([[1],[1]], [0,0], [1,0]);
  equal (result1.text, "(1,0)", "One step down");

  var result2 = runSearch([[1],[1],[1]], [0,0], [2,0]);
  equal (result2.text, "(1,0)(2,0)", "Two steps down");

  var result3 = runSearch([[1],[1],[1],[1]], [0,0], [3,0]);
  equal (result3.text, "(1,0)(2,0)(3,0)", "Three steps down");

});

test( "Basic Vertical", function() {

  var result1 = runSearch([[1, 1]], [0,0], [0,1]);
  equal (result1.text, "(0,1)", "One step across");

  var result2 = runSearch([[1, 1, 1]], [0,0], [0,2]);
  equal (result2.text, "(0,1)(0,2)", "Two steps across");

  var result3 = runSearch([[1, 1, 1, 1]], [0,0], [0,3]);
  equal (result3.text, "(0,1)(0,2)(0,3)", "Three steps across");

});

test( "Basic Weighting", function() {

  var result1 = runSearch([[1, 1],
                           [2, 1]], [0,0], [1,1]);
  equal (result1.text, "(0,1)(1,1)", "Takes less weighted path");

  var result2 = runSearch([[1, 2],
                           [1, 1]], [0,0], [1,1]);
  equal (result2.text, "(1,0)(1,1)", "Takes less weighted path");

});

test( "Pathfinding", function() {
  var result1 = runSearch([
      [1,1,1,1],
      [0,1,1,0],
      [0,0,1,1]
  ], [0,0], [2,3]);

  equal (result1.text, "(0,1)(1,1)(1,2)(2,2)(2,3)", "Result is expected");
});

test( "Diagonal Pathfinding", function() {
  var result1 = runSearch(new Graph([
      [1,1,1,1],
      [0,1,1,0],
      [0,0,1,1]
  ], { diagonal: true}), [0,0], [2,3]);

  equal (result1.text, "(1,1)(2,2)(2,3)", "Result is expected");
});

test( "Pathfinding to closest", function() {
  var result1 = runSearch([
      [1,1,1,1],
      [0,1,1,0],
      [0,0,1,1]
  ], [0,0], [2,1], {closest: true});

  equal (result1.text, "(0,1)(1,1)", "Result is expected - pathed to closest node");

  var result2 = runSearch([
      [1,0,1,1],
      [0,1,1,0],
      [0,0,1,1]
  ], [0,0], [2,1], {closest: true});

  equal (result2.text, "", "Result is expected - start node was closest node");

  var result3 = runSearch([
      [1,1,1,1],
      [0,1,1,0],
      [0,1,1,1]
  ], [0,0], [2,1], {closest: true});

  equal (result3.text, "(0,1)(1,1)(2,1)", "Result is expected - target node was reachable");
});

test( "Path costs", function() {
  var graph1 = new Graph([
      [1,2,2],
      [1,1,2],
      [1,1,2],
  ], { diagonal: true});

  var straightNeighbor = graph1.grid[1][0].getCost(graph1.grid[0][0]),
      diagonalNeighbor = graph1.grid[1][1].getCost(graph1.grid[0][0]),
      diagonalWeightedNeighbor = graph1.grid[2][2].getCost(graph1.grid[1][1]);

  equal ((straightNeighbor == 1) , true, "Result is expected - neighbor cost is 1");
  equal ((diagonalNeighbor > 1 && diagonalNeighbor < 2) , true, "Result is expected - diagonal neighbor cost is more than 1, less than 2");
  equal ((diagonalWeightedNeighbor > 2 && diagonalWeightedNeighbor < 4), true, "Result is expected - diagonal neighbor cost for 2 weight node is more than 2, less than 4");
});

// Make sure that start / end position are re-opened between searches
// See https://github.com/bgrins/javascript-astar/issues/43.
test( "Multiple runs on the same graph", function() {
  var graph = new Graph([
      [1,1,0,1],
      [0,1,1,0],
      [0,0,1,1]
  ]);

  var result1 = runSearch(graph, [0,0], [2,3]);
  equal (result1.text, "(0,1)(1,1)(1,2)(2,2)(2,3)", "Result is expected");

  var result2 = runSearch(graph, [2,3], [0,0]);
  equal (result2.text, "(2,2)(1,2)(1,1)(0,1)(0,0)", "Result is expected");

});

function runSearch(graph, start, end, options) {
  if (!(graph instanceof Graph)) {
    graph = new Graph(graph);
  }
  start = graph.grid[start[0]][start[1]];
  end = graph.grid[end[0]][end[1]];
  var sTime = new Date(),
    result = astar.search(graph, start, end, options),
    eTime = new Date();
  return {
    result: result,
    text: pathToString(result),
    time: (eTime - sTime)
  };
}

function pathToString(result) {
  return result.map(function(node) {
    return "(" + node.x + "," + node.y + ")";
  }).join("");
}

test( "GPS Pathfinding", function() {
  var data = [
    {name: "Paris", lat: 48.8567, lng: 2.3508},
    {name: "Lyon", lat: 45.76, lng: 4.84},
    {name: "Marseille", lat: 43.2964, lng: 5.37},
    {name: "Bordeaux", lat: 44.84, lng: -0.58},
    {name: "Cannes", lat: 43.5513, lng: 7.0128},
    {name: "Toulouse", lat: 43.6045, lng: 1.444},
    {name: "Reims", lat: 49.2628, lng: 4.0347}
  ],
  links = {
    "Paris": ["Lyon", "Bordeaux", "Reims"],
    "Lyon": ["Paris", "Marseille"],
    "Marseille": ["Lyon", "Cannes", "Toulouse"],
    "Bordeaux": ["Toulouse", "Paris"],
    "Cannes": ["Marseille"],
    "Toulouse": ["Marseille", "Bordeaux"],
    "Reims": ["Paris"]
  };

  function CityGraph(data, links) {
    this.nodes = [];
    this.links = links;
    this.cities = {};

    for (var i = 0; i < data.length; ++i) {
      var city = data[i],
          obj = new CityNode(city.name, city.lat, city.lng);

      if (this.nodes.indexOf(obj) == -1) {
          this.nodes.push(obj);
      }

      this.cities[obj.name] = obj;
    }

    this.init();
  }

  CityGraph.prototype.init= Graph.prototype.init;

  CityGraph.prototype.cleanDirty = Graph.prototype.cleanDirty;

  CityGraph.prototype.markDirty = Graph.prototype.markDirty;

  CityGraph.prototype.neighbors = function (node) {
    var neighbors = [],
        ids = this.links[node.name];
    for (var i = 0, len = ids.length; i < len; ++i) {
      var name = ids[i],
          neighbor = this.cities[name];
      neighbors.push(neighbor);
    }
    return neighbors;
  };

  function CityNode(name, lat, lng) {
    this.name = name;
    this.lat = lat;
    this.lng = lng;
    this.longRad = this.lng * Math.PI / 180;
    this.latRad = this.lat * Math.PI / 180;
  }
  CityNode.prototype.weight = 1;
  CityNode.prototype.toString = function() {
      return "[" + this.name + " (" + this.lat + ", " + this.lng + ")]";
  };
  CityNode.prototype.isWall = function() {
      return this.weight === 0;
  };
  // Heuristic function
  CityNode.prototype.GPS_distance = function(city) {
      var x = (city.longRad - this.longRad) * Math.cos((this.latRad + city.latRad)/2),
          y = city.latRad - this.latRad,
          res = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)) * 6371;
      return res;
  };
  // Real cost function
  CityNode.prototype.getCost = function(city) {
    // Re-use heuristic function for now
    // TODO: Determine the real distance between cities (from another data set)
    return this.GPS_distance(city);
  };

  var graph = new CityGraph(data, links);

  var start = graph.cities["Paris"],
      end = graph.cities["Cannes"];

  var GPSheuristic = function(node0, node1) {
    return node0.GPS_distance(node1);
  };

  var result = astar.search(graph, start, end, {heuristic: GPSheuristic});
  equal(result.length, 3, "Cannes is 3 cities away from Paris");
  equal(result[0].name, "Lyon", "City #1 is Lyon");
  equal(result[1].name, "Marseille", "City #2 is Marseille");
  equal(result[2].name, "Cannes", "City #3 is Cannes");
});

// // https://gist.github.com/bgrins/581352
// function runBasic() {
//     var graph = new Graph([
//         [1,1,1,1],
//         [0,1,1,0],
//         [0,0,1,1]
//     ]);
//     var start = graph.grid[0][0];
//     var end = graph.grid[1][2];
//     var result = astar.search(graph, start, end);

//     return "
" + result.join(", ") + "
";
// }

// $(function() {
//     $("#runall").click(function() {

//         var result1 = runTest([
//             [1,1,1,1],
//             [0,1,1,0],
//             [0,0,1,1]
//         ], [0,0], [2,3]);

//         $("#test-output").append(result1.text);
//         $("#test-output").append(runBasic());
//         return false;
//     });
// });

<commit_msg>whitespace in test file<commit_after>
/* global Graph, astar, ok, test, equal */

test( "Sanity Checks", function() {
  ok (typeof Graph !== "undefined", "Graph exists");
  ok (typeof astar !== "undefined", "Astar exists");
});

test( "Basic Horizontal", function() {

  var result1 = runSearch([[1],[1]], [0,0], [1,0]);
  equal (result1.text, "(1,0)", "One step down");

  var result2 = runSearch([[1],[1],[1]], [0,0], [2,0]);
  equal (result2.text, "(1,0)(2,0)", "Two steps down");

  var result3 = runSearch([[1],[1],[1],[1]], [0,0], [3,0]);
  equal (result3.text, "(1,0)(2,0)(3,0)", "Three steps down");

});

test( "Basic Vertical", function() {

  var result1 = runSearch([[1, 1]], [0,0], [0,1]);
  equal (result1.text, "(0,1)", "One step across");

  var result2 = runSearch([[1, 1, 1]], [0,0], [0,2]);
  equal (result2.text, "(0,1)(0,2)", "Two steps across");

  var result3 = runSearch([[1, 1, 1, 1]], [0,0], [0,3]);
  equal (result3.text, "(0,1)(0,2)(0,3)", "Three steps across");

});

test( "Basic Weighting", function() {

  var result1 = runSearch([[1, 1],
                           [2, 1]], [0,0], [1,1]);
  equal (result1.text, "(0,1)(1,1)", "Takes less weighted path");

  var result2 = runSearch([[1, 2],
                           [1, 1]], [0,0], [1,1]);
  equal (result2.text, "(1,0)(1,1)", "Takes less weighted path");

});

test( "Pathfinding", function() {
  var result1 = runSearch([
      [1,1,1,1],
      [0,1,1,0],
      [0,0,1,1]
  ], [0,0], [2,3]);

  equal (result1.text, "(0,1)(1,1)(1,2)(2,2)(2,3)", "Result is expected");
});

test( "Diagonal Pathfinding", function() {
  var result1 = runSearch(new Graph([
      [1,1,1,1],
      [0,1,1,0],
      [0,0,1,1]
  ], { diagonal: true}), [0,0], [2,3]);

  equal (result1.text, "(1,1)(2,2)(2,3)", "Result is expected");
});

test( "Pathfinding to closest", function() {
  var result1 = runSearch([
      [1,1,1,1],
      [0,1,1,0],
      [0,0,1,1]
  ], [0,0], [2,1], {closest: true});

  equal (result1.text, "(0,1)(1,1)", "Result is expected - pathed to closest node");

  var result2 = runSearch([
      [1,0,1,1],
      [0,1,1,0],
      [0,0,1,1]
  ], [0,0], [2,1], {closest: true});

  equal (result2.text, "", "Result is expected - start node was closest node");

  var result3 = runSearch([
      [1,1,1,1],
      [0,1,1,0],
      [0,1,1,1]
  ], [0,0], [2,1], {closest: true});

  equal (result3.text, "(0,1)(1,1)(2,1)", "Result is expected - target node was reachable");
});

test( "Path costs", function() {
  var graph1 = new Graph([
      [1,2,2],
      [1,1,2],
      [1,1,2],
  ], { diagonal: true});

  var straightNeighbor = graph1.grid[1][0].getCost(graph1.grid[0][0]),
      diagonalNeighbor = graph1.grid[1][1].getCost(graph1.grid[0][0]),
      diagonalWeightedNeighbor = graph1.grid[2][2].getCost(graph1.grid[1][1]);

  equal ((straightNeighbor == 1) , true, "Result is expected - neighbor cost is 1");
  equal ((diagonalNeighbor > 1 && diagonalNeighbor < 2) , true, "Result is expected - diagonal neighbor cost is more than 1, less than 2");
  equal ((diagonalWeightedNeighbor > 2 && diagonalWeightedNeighbor < 4), true, "Result is expected - diagonal neighbor cost for 2 weight node is more than 2, less than 4");
});

// Make sure that start / end position are re-opened between searches
// See https://github.com/bgrins/javascript-astar/issues/43.
test( "Multiple runs on the same graph", function() {
  var graph = new Graph([
      [1,1,0,1],
      [0,1,1,0],
      [0,0,1,1]
  ]);

  var result1 = runSearch(graph, [0,0], [2,3]);
  equal (result1.text, "(0,1)(1,1)(1,2)(2,2)(2,3)", "Result is expected");

  var result2 = runSearch(graph, [2,3], [0,0]);
  equal (result2.text, "(2,2)(1,2)(1,1)(0,1)(0,0)", "Result is expected");

});

function runSearch(graph, start, end, options) {
  if (!(graph instanceof Graph)) {
    graph = new Graph(graph);
  }
  start = graph.grid[start[0]][start[1]];
  end = graph.grid[end[0]][end[1]];
  var sTime = new Date(),
    result = astar.search(graph, start, end, options),
    eTime = new Date();
  return {
    result: result,
    text: pathToString(result),
    time: (eTime - sTime)
  };
}

function pathToString(result) {
  return result.map(function(node) {
    return "(" + node.x + "," + node.y + ")";
  }).join("");
}

test( "GPS Pathfinding", function() {
  var data = [
    {name: "Paris", lat: 48.8567, lng: 2.3508},
    {name: "Lyon", lat: 45.76, lng: 4.84},
    {name: "Marseille", lat: 43.2964, lng: 5.37},
    {name: "Bordeaux", lat: 44.84, lng: -0.58},
    {name: "Cannes", lat: 43.5513, lng: 7.0128},
    {name: "Toulouse", lat: 43.6045, lng: 1.444},
    {name: "Reims", lat: 49.2628, lng: 4.0347}
  ],
  links = {
    "Paris": ["Lyon", "Bordeaux", "Reims"],
    "Lyon": ["Paris", "Marseille"],
    "Marseille": ["Lyon", "Cannes", "Toulouse"],
    "Bordeaux": ["Toulouse", "Paris"],
    "Cannes": ["Marseille"],
    "Toulouse": ["Marseille", "Bordeaux"],
    "Reims": ["Paris"]
  };

  function CityGraph(data, links) {
    this.nodes = [];
    this.links = links;
    this.cities = {};

    for (var i = 0; i < data.length; ++i) {
      var city = data[i],
          obj = new CityNode(city.name, city.lat, city.lng);

      if (this.nodes.indexOf(obj) == -1) {
          this.nodes.push(obj);
      }

      this.cities[obj.name] = obj;
    }

    this.init();
  }

  CityGraph.prototype.init= Graph.prototype.init;

  CityGraph.prototype.cleanDirty = Graph.prototype.cleanDirty;

  CityGraph.prototype.markDirty = Graph.prototype.markDirty;

  CityGraph.prototype.neighbors = function (node) {
    var neighbors = [],
        ids = this.links[node.name];
    for (var i = 0, len = ids.length; i < len; ++i) {
      var name = ids[i],
          neighbor = this.cities[name];
      neighbors.push(neighbor);
    }
    return neighbors;
  };

  function CityNode(name, lat, lng) {
    this.name = name;
    this.lat = lat;
    this.lng = lng;
    this.longRad = this.lng * Math.PI / 180;
    this.latRad = this.lat * Math.PI / 180;
  }
  CityNode.prototype.weight = 1;
  CityNode.prototype.toString = function() {
      return "[" + this.name + " (" + this.lat + ", " + this.lng + ")]";
  };
  CityNode.prototype.isWall = function() {
      return this.weight === 0;
  };
  // Heuristic function
  CityNode.prototype.GPS_distance = function(city) {
      var x = (city.longRad - this.longRad) * Math.cos((this.latRad + city.latRad)/2),
          y = city.latRad - this.latRad,
          res = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)) * 6371;
      return res;
  };
  // Real cost function
  CityNode.prototype.getCost = function(city) {
    // Re-use heuristic function for now
    // TODO: Determine the real distance between cities (from another data set)
    return this.GPS_distance(city);
  };

  var graph = new CityGraph(data, links);

  var start = graph.cities["Paris"],
      end = graph.cities["Cannes"];

  var GPSheuristic = function(node0, node1) {
    return node0.GPS_distance(node1);
  };

  var result = astar.search(graph, start, end, {heuristic: GPSheuristic});
  equal(result.length, 3, "Cannes is 3 cities away from Paris");
  equal(result[0].name, "Lyon", "City #1 is Lyon");
  equal(result[1].name, "Marseille", "City #2 is Marseille");
  equal(result[2].name, "Cannes", "City #3 is Cannes");
});

// // https://gist.github.com/bgrins/581352
// function runBasic() {
//     var graph = new Graph([
//         [1,1,1,1],
//         [0,1,1,0],
//         [0,0,1,1]
//     ]);
//     var start = graph.grid[0][0];
//     var end = graph.grid[1][2];
//     var result = astar.search(graph, start, end);

//     return "
" + result.join(", ") + "
";
// }

// $(function() {
//     $("#runall").click(function() {

//         var result1 = runTest([
//             [1,1,1,1],
//             [0,1,1,0],
//             [0,0,1,1]
//         ], [0,0], [2,3]);

//         $("#test-output").append(result1.text);
//         $("#test-output").append(runBasic());
//         return false;
//     });
// });

<|endoftext|>


<commit_before>'use strict';

/*
 * Toggle code visibility
 */
$('.pl-toggle-code').on('click', function () {
    // toggle the sibling pre element
    $(this).parent().next('.pl-preview+pre').toggle(250);
    $(this).toggleClass('active');
});

var autoCollapsed = false;
$('.nav-collapse').on('click', function () {
    autoCollapsed = false;
    $('body').toggleClass('pl-collapsed-nav');
});

/* collapse sidebar when necessary */
var checkNav = function () {
    var collapsed = $('body').hasClass('pl-collapsed-nav'),
        width = $(this).width();

    if (width <= 767 && !collapsed) {
        autoCollapsed = true;
        $('body').addClass('pl-collapsed-nav');
    } else if (width > 767 && autoCollapsed) {
        $('body').removeClass('pl-collapsed-nav');
    }
};

$(window).on('resize', checkNav);
$(document).on('ready', checkNav);

/*
 * Use bootstrap's scrollspy plugin to highlight subnav based on scroll position
 */
$('body').scrollspy({ target: '.pl-sidebar > .active', offset: 125 });

/* enable masks */
$(':input').inputmask();

/* select2 things */
$('.select2').select2({
    minimumResultsForSearch: 4
});

/* enable tooltips */
$('[data-toggle="tooltip"]').tooltip({container: 'body', delay: { show: 200, hide: 0 } });

/* enable datepickers */
$('.datepicker').datepicker({
    // autoSize: true,
    // showButtonPanel: true,
    numberOfMonths: 1,
    showOtherMonths: true
    // changeMonth: true,
    // changeYear: true
});

/* find checkboxes with the indeterminate attr and set the indeterminate property */
$('input[type="checkbox"][indeterminate]').each(function () {
    this.indeterminate = true;
});
<commit_msg>Adds code for interactive alert examples<commit_after>'use strict';

/*
 * Toggle code visibility
 */
$('.pl-toggle-code').on('click', function () {
    // toggle the sibling pre element
    $(this).parent().next('.pl-preview+pre').toggle(250);
    $(this).toggleClass('active');
});

var autoCollapsed = false;
$('.nav-collapse').on('click', function () {
    autoCollapsed = false;
    $('body').toggleClass('pl-collapsed-nav');
});

/* collapse sidebar when necessary */
var checkNav = function () {
    var collapsed = $('body').hasClass('pl-collapsed-nav'),
        width = $(this).width();

    if (width <= 767 && !collapsed) {
        autoCollapsed = true;
        $('body').addClass('pl-collapsed-nav');
    } else if (width > 767 && autoCollapsed) {
        $('body').removeClass('pl-collapsed-nav');
    }
};

$(window).on('resize', checkNav);
$(document).on('ready', checkNav);

/*
 * Use bootstrap's scrollspy plugin to highlight subnav based on scroll position
 */
$('body').scrollspy({ target: '.pl-sidebar > .active', offset: 125 });

/* enable masks */
$(':input').inputmask();

/* select2 things */
$('.select2').select2({
    minimumResultsForSearch: 4
});

/* enable tooltips */
$('[data-toggle="tooltip"]').tooltip({container: 'body', delay: { show: 200, hide: 0 } });

/* enable datepickers */
$('.datepicker').datepicker({
    // autoSize: true,
    // showButtonPanel: true,
    numberOfMonths: 1,
    showOtherMonths: true
    // changeMonth: true,
    // changeYear: true
});

/* find checkboxes with the indeterminate attr and set the indeterminate property */
$('input[type="checkbox"][indeterminate]').each(function () {
    this.indeterminate = true;
});

/* closable toast examples */
$('.pl-closable-toasts .toast .close').each(function () {
    $(this).on('click', function () {
        $(this).closest('.toast').slideUp(150);
    });
});

/* quick and dirty working toast examples */
$('.show-toasts').each(function () {
    var showToastButton = $(this);

    // get toasts and move to body
    var selector = showToastButton.attr('data-toast-target');
    var toastContainer = $(selector);
    toastContainer.hide();
    $(document.body).append(toastContainer);

    var closers = toastContainer.find('.close');
    var closersCount = closers.length;
    var closedCount = 0;
    closers.each(function () {
        $(this).on('click', function () {
            if (closersCount == ++closedCount) {
                closedCount = 0;
                setTimeout(function () {
                    toastContainer.hide();
                }, 150)
            }
        });
    });

    var showToast = function (toastEl) {
        toastEl.slideDown({
            duration: 150,
            complete: function () {
                if (toastEl.next().length) {
                    setTimeout(function () {
                        showToast(toastEl.next());
                    }, 1000);
                }
            }
        })
    }

    // show the toasts on click
    showToastButton.on('click', function() {
        toastContainer.toggle();
        toastContainer.css({
            position: 'fixed',
            top: '50px',
            right: '8px'
        });
        closedCount = 0;
        toastContainer.find('.toast').hide(0);
        showToast($(toastContainer.find('.toast')[0]));
    })
})
<|endoftext|>


<commit_before>"use strict";
const getLast = require("../utils/get-last");
const { literalline } = require("./doc-builders");

const isConcat = (doc) => Array.isArray(doc) || (doc && doc.type === "concat");
const getDocParts = (doc) => {
  if (Array.isArray(doc)) {
    return doc;
  }

  /* istanbul ignore next */
  if (doc.type !== "concat" && doc.type !== "fill") {
    throw new Error("Expect doc type to be `concat` or `fill`.");
  }

  return doc.parts;
};

// Using a unique object to compare by reference.
const traverseDocOnExitStackMarker = {};

function traverseDoc(doc, onEnter, onExit, shouldTraverseConditionalGroups) {
  const docsStack = [doc];

  while (docsStack.length > 0) {
    const doc = docsStack.pop();

    if (doc === traverseDocOnExitStackMarker) {
      onExit(docsStack.pop());
      continue;
    }

    if (onExit) {
      docsStack.push(doc, traverseDocOnExitStackMarker);
    }

    if (
      // Should Recurse
      !onEnter ||
      onEnter(doc) !== false
    ) {
      // When there are multiple parts to process,
      // the parts need to be pushed onto the stack in reverse order,
      // so that they are processed in the original order
      // when the stack is popped.
      if (isConcat(doc) || doc.type === "fill") {
        const parts = getDocParts(doc);
        for (let ic = parts.length, i = ic - 1; i >= 0; --i) {
          docsStack.push(parts[i]);
        }
      } else if (doc.type === "if-break") {
        if (doc.flatContents) {
          docsStack.push(doc.flatContents);
        }
        if (doc.breakContents) {
          docsStack.push(doc.breakContents);
        }
      } else if (doc.type === "group" && doc.expandedStates) {
        if (shouldTraverseConditionalGroups) {
          for (let ic = doc.expandedStates.length, i = ic - 1; i >= 0; --i) {
            docsStack.push(doc.expandedStates[i]);
          }
        } else {
          docsStack.push(doc.contents);
        }
      } else if (doc.contents) {
        docsStack.push(doc.contents);
      }
    }
  }
}

function mapDoc(doc, cb) {
  // Within a doc tree, the same subtrees can be found multiple times.
  // E.g., often this happens in conditional groups.
  // As an optimization (those subtrees can be huge) and to maintain the
  // reference structure of the tree, the mapping results are cached in
  // a map and reused.
  const mapped = new Map();

  return rec(doc);

  function rec(doc) {
    if (mapped.has(doc)) {
      return mapped.get(doc);
    }
    const result = process(doc);
    mapped.set(doc, result);
    return result;
  }

  function process(doc) {
    if (Array.isArray(doc)) {
      return cb(doc.map(rec));
    }

    if (doc.type === "concat" || doc.type === "fill") {
      const parts = doc.parts.map(rec);
      return cb({ ...doc, parts });
    }

    if (doc.type === "if-break") {
      const breakContents = doc.breakContents && rec(doc.breakContents);
      const flatContents = doc.flatContents && rec(doc.flatContents);
      return cb({ ...doc, breakContents, flatContents });
    }

    if (doc.type === "group" && doc.expandedStates) {
      const expandedStates = doc.expandedStates.map(rec);
      const contents = expandedStates[0];
      return cb({ ...doc, contents, expandedStates });
    }

    if (doc.contents) {
      const contents = rec(doc.contents);
      return cb({ ...doc, contents });
    }

    return cb(doc);
  }
}

function findInDoc(doc, fn, defaultValue) {
  let result = defaultValue;
  let hasStopped = false;
  function findInDocOnEnterFn(doc) {
    const maybeResult = fn(doc);
    if (maybeResult !== undefined) {
      hasStopped = true;
      result = maybeResult;
    }
    if (hasStopped) {
      return false;
    }
  }
  traverseDoc(doc, findInDocOnEnterFn);
  return result;
}

function willBreakFn(doc) {
  if (doc.type === "group" && doc.break) {
    return true;
  }
  if (doc.type === "line" && doc.hard) {
    return true;
  }
  if (doc.type === "break-parent") {
    return true;
  }
}

function willBreak(doc) {
  return findInDoc(doc, willBreakFn, false);
}

function breakParentGroup(groupStack) {
  if (groupStack.length > 0) {
    const parentGroup = getLast(groupStack);
    // Breaks are not propagated through conditional groups because
    // the user is expected to manually handle what breaks.
    if (!parentGroup.expandedStates && !parentGroup.break) {
      // An alternative truthy value allows to distinguish propagated group breaks
      // and not to print them as `group(..., { break: true })` in `--debug-print-doc`.
      parentGroup.break = "propagated";
    }
  }
  return null;
}

function propagateBreaks(doc) {
  const alreadyVisitedSet = new Set();
  const groupStack = [];
  function propagateBreaksOnEnterFn(doc) {
    if (doc.type === "break-parent") {
      breakParentGroup(groupStack);
    }
    if (doc.type === "group") {
      groupStack.push(doc);
      if (alreadyVisitedSet.has(doc)) {
        return false;
      }
      alreadyVisitedSet.add(doc);
    }
  }
  function propagateBreaksOnExitFn(doc) {
    if (doc.type === "group") {
      const group = groupStack.pop();
      if (group.break) {
        breakParentGroup(groupStack);
      }
    }
  }
  traverseDoc(
    doc,
    propagateBreaksOnEnterFn,
    propagateBreaksOnExitFn,
    /* shouldTraverseConditionalGroups */ true
  );
}

function removeLinesFn(doc) {
  // Force this doc into flat mode by statically converting all
  // lines into spaces (or soft lines into nothing). Hard lines
  // should still output because there's too great of a chance
  // of breaking existing assumptions otherwise.
  if (doc.type === "line" && !doc.hard) {
    return doc.soft ? "" : " ";
  }

  if (doc.type === "if-break") {
    return doc.flatContents || "";
  }

  return doc;
}

function removeLines(doc) {
  return mapDoc(doc, removeLinesFn);
}

const isHardline = (doc, nextDoc) =>
  doc &&
  doc.type === "line" &&
  doc.hard &&
  nextDoc &&
  nextDoc.type === "break-parent";
function stripDocTrailingHardlineFromDoc(doc) {
  if (!doc) {
    return doc;
  }

  if (isConcat(doc) || doc.type === "fill") {
    const parts = getDocParts(doc);

    while (parts.length > 1 && isHardline(...parts.slice(-2))) {
      parts.length -= 2;
    }

    if (parts.length > 0) {
      const lastPart = stripDocTrailingHardlineFromDoc(getLast(parts));
      parts[parts.length - 1] = lastPart;
    }
    return Array.isArray(doc) ? parts : { ...doc, parts };
  }

  switch (doc.type) {
    case "align":
    case "indent":
    case "indent-if-break":
    case "group":
    case "line-suffix":
    case "label": {
      const contents = stripDocTrailingHardlineFromDoc(doc.contents);
      return { ...doc, contents };
    }
    case "if-break": {
      const breakContents = stripDocTrailingHardlineFromDoc(doc.breakContents);
      const flatContents = stripDocTrailingHardlineFromDoc(doc.flatContents);
      return { ...doc, breakContents, flatContents };
    }
  }

  return doc;
}

function stripTrailingHardline(doc) {
  // HACK remove ending hardline, original PR: #1984
  return stripDocTrailingHardlineFromDoc(cleanDoc(doc));
}

function cleanDocFn(doc) {
  switch (doc.type) {
    case "fill":
      if (doc.parts.length === 0 || doc.parts.every((part) => part === "")) {
        return "";
      }
      break;
    case "group":
      if (!doc.contents && !doc.id && !doc.break && !doc.expandedStates) {
        return "";
      }
      // Remove nested only group
      if (
        doc.contents.type === "group" &&
        doc.contents.id === doc.id &&
        doc.contents.break === doc.break &&
        doc.contents.expandedStates === doc.expandedStates
      ) {
        return doc.contents;
      }
      break;
    case "align":
    case "indent":
    case "indent-if-break":
    case "line-suffix":
      if (!doc.contents) {
        return "";
      }
      break;
    case "if-break":
      if (!doc.flatContents && !doc.breakContents) {
        return "";
      }
      break;
  }

  if (!isConcat(doc)) {
    return doc;
  }

  const parts = [];
  for (const part of getDocParts(doc)) {
    if (!part) {
      continue;
    }
    const [currentPart, ...restParts] = isConcat(part)
      ? getDocParts(part)
      : [part];
    if (typeof currentPart === "string" && typeof getLast(parts) === "string") {
      parts[parts.length - 1] += currentPart;
    } else {
      parts.push(currentPart);
    }
    parts.push(...restParts);
  }

  if (parts.length === 0) {
    return "";
  }

  if (parts.length === 1) {
    return parts[0];
  }
  return Array.isArray(doc) ? parts : { ...doc, parts };
}
// A safer version of `normalizeDoc`
// - `normalizeDoc` concat strings and flat "concat" in `fill`, while `cleanDoc` don't
// - On `concat` object, `normalizeDoc` always return object with `parts`, `cleanDoc` may return strings
// - `cleanDoc` also remove nested `group`s and empty `fill`/`align`/`indent`/`line-suffix`/`if-break` if possible
function cleanDoc(doc) {
  return mapDoc(doc, (currentDoc) => cleanDocFn(currentDoc));
}

function normalizeParts(parts) {
  const newParts = [];

  const restParts = parts.filter(Boolean);
  while (restParts.length > 0) {
    const part = restParts.shift();

    if (!part) {
      continue;
    }

    if (isConcat(part)) {
      restParts.unshift(...getDocParts(part));
      continue;
    }

    if (
      newParts.length > 0 &&
      typeof getLast(newParts) === "string" &&
      typeof part === "string"
    ) {
      newParts[newParts.length - 1] += part;
      continue;
    }

    newParts.push(part);
  }

  return newParts;
}

function normalizeDoc(doc) {
  return mapDoc(doc, (currentDoc) => {
    if (Array.isArray(currentDoc)) {
      return normalizeParts(currentDoc);
    }
    if (!currentDoc.parts) {
      return currentDoc;
    }
    return {
      ...currentDoc,
      parts: normalizeParts(currentDoc.parts),
    };
  });
}

function replaceNewlinesWithLiterallines(doc) {
  return mapDoc(doc, (currentDoc) =>
    typeof currentDoc === "string" && currentDoc.includes("\n")
      ? currentDoc.split(/(\n)/).map((v, i) => (i % 2 === 0 ? v : literalline))
      : currentDoc
  );
}

module.exports = {
  isConcat,
  getDocParts,
  willBreak,
  traverseDoc,
  findInDoc,
  mapDoc,
  propagateBreaks,
  removeLines,
  stripTrailingHardline,
  normalizeParts,
  normalizeDoc,
  cleanDoc,
  replaceNewlinesWithLiterallines,
};
<commit_msg>Use `join` in `replaceNewlinesWithLiterallines` (#10860)<commit_after>"use strict";
const getLast = require("../utils/get-last");
const { literalline, join } = require("./doc-builders");

const isConcat = (doc) => Array.isArray(doc) || (doc && doc.type === "concat");
const getDocParts = (doc) => {
  if (Array.isArray(doc)) {
    return doc;
  }

  /* istanbul ignore next */
  if (doc.type !== "concat" && doc.type !== "fill") {
    throw new Error("Expect doc type to be `concat` or `fill`.");
  }

  return doc.parts;
};

// Using a unique object to compare by reference.
const traverseDocOnExitStackMarker = {};

function traverseDoc(doc, onEnter, onExit, shouldTraverseConditionalGroups) {
  const docsStack = [doc];

  while (docsStack.length > 0) {
    const doc = docsStack.pop();

    if (doc === traverseDocOnExitStackMarker) {
      onExit(docsStack.pop());
      continue;
    }

    if (onExit) {
      docsStack.push(doc, traverseDocOnExitStackMarker);
    }

    if (
      // Should Recurse
      !onEnter ||
      onEnter(doc) !== false
    ) {
      // When there are multiple parts to process,
      // the parts need to be pushed onto the stack in reverse order,
      // so that they are processed in the original order
      // when the stack is popped.
      if (isConcat(doc) || doc.type === "fill") {
        const parts = getDocParts(doc);
        for (let ic = parts.length, i = ic - 1; i >= 0; --i) {
          docsStack.push(parts[i]);
        }
      } else if (doc.type === "if-break") {
        if (doc.flatContents) {
          docsStack.push(doc.flatContents);
        }
        if (doc.breakContents) {
          docsStack.push(doc.breakContents);
        }
      } else if (doc.type === "group" && doc.expandedStates) {
        if (shouldTraverseConditionalGroups) {
          for (let ic = doc.expandedStates.length, i = ic - 1; i >= 0; --i) {
            docsStack.push(doc.expandedStates[i]);
          }
        } else {
          docsStack.push(doc.contents);
        }
      } else if (doc.contents) {
        docsStack.push(doc.contents);
      }
    }
  }
}

function mapDoc(doc, cb) {
  // Within a doc tree, the same subtrees can be found multiple times.
  // E.g., often this happens in conditional groups.
  // As an optimization (those subtrees can be huge) and to maintain the
  // reference structure of the tree, the mapping results are cached in
  // a map and reused.
  const mapped = new Map();

  return rec(doc);

  function rec(doc) {
    if (mapped.has(doc)) {
      return mapped.get(doc);
    }
    const result = process(doc);
    mapped.set(doc, result);
    return result;
  }

  function process(doc) {
    if (Array.isArray(doc)) {
      return cb(doc.map(rec));
    }

    if (doc.type === "concat" || doc.type === "fill") {
      const parts = doc.parts.map(rec);
      return cb({ ...doc, parts });
    }

    if (doc.type === "if-break") {
      const breakContents = doc.breakContents && rec(doc.breakContents);
      const flatContents = doc.flatContents && rec(doc.flatContents);
      return cb({ ...doc, breakContents, flatContents });
    }

    if (doc.type === "group" && doc.expandedStates) {
      const expandedStates = doc.expandedStates.map(rec);
      const contents = expandedStates[0];
      return cb({ ...doc, contents, expandedStates });
    }

    if (doc.contents) {
      const contents = rec(doc.contents);
      return cb({ ...doc, contents });
    }

    return cb(doc);
  }
}

function findInDoc(doc, fn, defaultValue) {
  let result = defaultValue;
  let hasStopped = false;
  function findInDocOnEnterFn(doc) {
    const maybeResult = fn(doc);
    if (maybeResult !== undefined) {
      hasStopped = true;
      result = maybeResult;
    }
    if (hasStopped) {
      return false;
    }
  }
  traverseDoc(doc, findInDocOnEnterFn);
  return result;
}

function willBreakFn(doc) {
  if (doc.type === "group" && doc.break) {
    return true;
  }
  if (doc.type === "line" && doc.hard) {
    return true;
  }
  if (doc.type === "break-parent") {
    return true;
  }
}

function willBreak(doc) {
  return findInDoc(doc, willBreakFn, false);
}

function breakParentGroup(groupStack) {
  if (groupStack.length > 0) {
    const parentGroup = getLast(groupStack);
    // Breaks are not propagated through conditional groups because
    // the user is expected to manually handle what breaks.
    if (!parentGroup.expandedStates && !parentGroup.break) {
      // An alternative truthy value allows to distinguish propagated group breaks
      // and not to print them as `group(..., { break: true })` in `--debug-print-doc`.
      parentGroup.break = "propagated";
    }
  }
  return null;
}

function propagateBreaks(doc) {
  const alreadyVisitedSet = new Set();
  const groupStack = [];
  function propagateBreaksOnEnterFn(doc) {
    if (doc.type === "break-parent") {
      breakParentGroup(groupStack);
    }
    if (doc.type === "group") {
      groupStack.push(doc);
      if (alreadyVisitedSet.has(doc)) {
        return false;
      }
      alreadyVisitedSet.add(doc);
    }
  }
  function propagateBreaksOnExitFn(doc) {
    if (doc.type === "group") {
      const group = groupStack.pop();
      if (group.break) {
        breakParentGroup(groupStack);
      }
    }
  }
  traverseDoc(
    doc,
    propagateBreaksOnEnterFn,
    propagateBreaksOnExitFn,
    /* shouldTraverseConditionalGroups */ true
  );
}

function removeLinesFn(doc) {
  // Force this doc into flat mode by statically converting all
  // lines into spaces (or soft lines into nothing). Hard lines
  // should still output because there's too great of a chance
  // of breaking existing assumptions otherwise.
  if (doc.type === "line" && !doc.hard) {
    return doc.soft ? "" : " ";
  }

  if (doc.type === "if-break") {
    return doc.flatContents || "";
  }

  return doc;
}

function removeLines(doc) {
  return mapDoc(doc, removeLinesFn);
}

const isHardline = (doc, nextDoc) =>
  doc &&
  doc.type === "line" &&
  doc.hard &&
  nextDoc &&
  nextDoc.type === "break-parent";
function stripDocTrailingHardlineFromDoc(doc) {
  if (!doc) {
    return doc;
  }

  if (isConcat(doc) || doc.type === "fill") {
    const parts = getDocParts(doc);

    while (parts.length > 1 && isHardline(...parts.slice(-2))) {
      parts.length -= 2;
    }

    if (parts.length > 0) {
      const lastPart = stripDocTrailingHardlineFromDoc(getLast(parts));
      parts[parts.length - 1] = lastPart;
    }
    return Array.isArray(doc) ? parts : { ...doc, parts };
  }

  switch (doc.type) {
    case "align":
    case "indent":
    case "indent-if-break":
    case "group":
    case "line-suffix":
    case "label": {
      const contents = stripDocTrailingHardlineFromDoc(doc.contents);
      return { ...doc, contents };
    }
    case "if-break": {
      const breakContents = stripDocTrailingHardlineFromDoc(doc.breakContents);
      const flatContents = stripDocTrailingHardlineFromDoc(doc.flatContents);
      return { ...doc, breakContents, flatContents };
    }
  }

  return doc;
}

function stripTrailingHardline(doc) {
  // HACK remove ending hardline, original PR: #1984
  return stripDocTrailingHardlineFromDoc(cleanDoc(doc));
}

function cleanDocFn(doc) {
  switch (doc.type) {
    case "fill":
      if (doc.parts.length === 0 || doc.parts.every((part) => part === "")) {
        return "";
      }
      break;
    case "group":
      if (!doc.contents && !doc.id && !doc.break && !doc.expandedStates) {
        return "";
      }
      // Remove nested only group
      if (
        doc.contents.type === "group" &&
        doc.contents.id === doc.id &&
        doc.contents.break === doc.break &&
        doc.contents.expandedStates === doc.expandedStates
      ) {
        return doc.contents;
      }
      break;
    case "align":
    case "indent":
    case "indent-if-break":
    case "line-suffix":
      if (!doc.contents) {
        return "";
      }
      break;
    case "if-break":
      if (!doc.flatContents && !doc.breakContents) {
        return "";
      }
      break;
  }

  if (!isConcat(doc)) {
    return doc;
  }

  const parts = [];
  for (const part of getDocParts(doc)) {
    if (!part) {
      continue;
    }
    const [currentPart, ...restParts] = isConcat(part)
      ? getDocParts(part)
      : [part];
    if (typeof currentPart === "string" && typeof getLast(parts) === "string") {
      parts[parts.length - 1] += currentPart;
    } else {
      parts.push(currentPart);
    }
    parts.push(...restParts);
  }

  if (parts.length === 0) {
    return "";
  }

  if (parts.length === 1) {
    return parts[0];
  }
  return Array.isArray(doc) ? parts : { ...doc, parts };
}
// A safer version of `normalizeDoc`
// - `normalizeDoc` concat strings and flat "concat" in `fill`, while `cleanDoc` don't
// - On `concat` object, `normalizeDoc` always return object with `parts`, `cleanDoc` may return strings
// - `cleanDoc` also remove nested `group`s and empty `fill`/`align`/`indent`/`line-suffix`/`if-break` if possible
function cleanDoc(doc) {
  return mapDoc(doc, (currentDoc) => cleanDocFn(currentDoc));
}

function normalizeParts(parts) {
  const newParts = [];

  const restParts = parts.filter(Boolean);
  while (restParts.length > 0) {
    const part = restParts.shift();

    if (!part) {
      continue;
    }

    if (isConcat(part)) {
      restParts.unshift(...getDocParts(part));
      continue;
    }

    if (
      newParts.length > 0 &&
      typeof getLast(newParts) === "string" &&
      typeof part === "string"
    ) {
      newParts[newParts.length - 1] += part;
      continue;
    }

    newParts.push(part);
  }

  return newParts;
}

function normalizeDoc(doc) {
  return mapDoc(doc, (currentDoc) => {
    if (Array.isArray(currentDoc)) {
      return normalizeParts(currentDoc);
    }
    if (!currentDoc.parts) {
      return currentDoc;
    }
    return {
      ...currentDoc,
      parts: normalizeParts(currentDoc.parts),
    };
  });
}

function replaceNewlinesWithLiterallines(doc) {
  return mapDoc(doc, (currentDoc) =>
    typeof currentDoc === "string" && currentDoc.includes("\n")
      ? join(literalline, currentDoc.split("\n"))
      : currentDoc
  );
}

module.exports = {
  isConcat,
  getDocParts,
  willBreak,
  traverseDoc,
  findInDoc,
  mapDoc,
  propagateBreaks,
  removeLines,
  stripTrailingHardline,
  normalizeParts,
  normalizeDoc,
  cleanDoc,
  replaceNewlinesWithLiterallines,
};
<|endoftext|>


<commit_before>var traceur = require('traceur');
var ParseTreeTransformer = traceur.get('codegeneration/ParseTreeTransformer').ParseTreeTransformer;

function ModuleImportNormalizeTransformer(map) {
  this.map = map;
  return ParseTreeTransformer.apply(this, arguments);
}
ModuleImportNormalizeTransformer.prototype = Object.create(ParseTreeTransformer.prototype);
ModuleImportNormalizeTransformer.prototype.transformModuleSpecifier = function(tree) {
  // shouldn't really mutate, should create a new specifier
  var depName = this.map(tree.token.processedValue) || tree.token.processedValue;
  tree.token.value = "'" + depName + "'";
  return tree;
}

function remap(source, map, fileName) {
  var compiler = new traceur.Compiler();

  var tree = compiler.parse(source, fileName);

  tree = new ModuleImportNormalizeTransformer(map).transformAny(tree);

  return Promise.resolve({
    source: compiler.write(tree)
  });
}
exports.remap = remap;

exports.compile = function(load, normalize) {

  var compiler = new traceur.Compiler({
    moduleName: load.name,
    modules: 'instantiate',
    script: false
  });

  var tree = compiler.parse(load.source, load.address);

  var transformer = new ModuleImportNormalizeTransformer(function(dep) {
    return normalize ? load.depMap[dep] : dep;
  });

  tree = compiler.transform(transformer.transformAny(tree), load.name);

  return Promise.resolve({
    source: compiler.write(tree)
  });
}<commit_msg>support loader.traceurOptions<commit_after>var traceur = require('traceur');
var ParseTreeTransformer = traceur.get('codegeneration/ParseTreeTransformer').ParseTreeTransformer;

function ModuleImportNormalizeTransformer(map) {
  this.map = map;
  return ParseTreeTransformer.apply(this, arguments);
}
ModuleImportNormalizeTransformer.prototype = Object.create(ParseTreeTransformer.prototype);
ModuleImportNormalizeTransformer.prototype.transformModuleSpecifier = function(tree) {
  // shouldn't really mutate, should create a new specifier
  var depName = this.map(tree.token.processedValue) || tree.token.processedValue;
  tree.token.value = "'" + depName + "'";
  return tree;
}

function remap(source, map, fileName) {
  var compiler = new traceur.Compiler();

  var tree = compiler.parse(source, fileName);

  tree = new ModuleImportNormalizeTransformer(map).transformAny(tree);

  return Promise.resolve({
    source: compiler.write(tree)
  });
}
exports.remap = remap;

exports.compile = function(load, normalize, loader) {

  var options = loader.traceurOptions || {};
  options.modules = 'instantiate';
  options.script = false;
  options.moduleName = load.name;
  options.sourceMaps = false;
  delete options.filename;

  var compiler = new traceur.Compiler(options);

  var tree = compiler.parse(load.source, load.address);

  var transformer = new ModuleImportNormalizeTransformer(function(dep) {
    return normalize ? load.depMap[dep] : dep;
  });

  tree = compiler.transform(transformer.transformAny(tree), load.name);

  return Promise.resolve({
    source: compiler.write(tree)
  });
}<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import TabBar from './TabBar';
import assert from 'assert';

export default function Switch(props) {
  const navState = props.navigationState;
  const selector = props.selector;
  const statem = props.statem;
  if (!selector && !statem) console.error('Selector should be defined.');
  let index = -1;
  if (!selector) {
    assert(statem.isIn, 'Wrong statem passed');
    // support Statem - Harel statecharts machine!
    navState.children.forEach((el, i) => {
      assert(el.default || el.state,
        `Either default or state should be defined for element=${el.key}`);
      if (el.default) {
        index = i;
      } else {
        assert(el.state.id, 'State doesn\'t have id');
        if (statem.isIn(el.state.id)) {
          index = i;
        }
      }
    });
    assert(index !== -1, 'No default scene is defined');
  } else {
    const selectedKey = selector(props);
    if (!selectedKey) console.error('Selector should return key.');
    navState.children.forEach((el, i) => {
      if (el.sceneKey === selectedKey) {
        index = i;
      }
    });
    if (index === -1) console.error(`A scene for key “${selectedKey}” does not exist.`);
  }
  const navigationState = index !== navState.index ? { ...navState, index } : navState;
  return (
    <TabBar
      onNavigate={props.onNavigate}
      navigationState={navigationState}
    />
  );
}

Switch.propTypes = {
  navigationState: PropTypes.object,
  onNavigate: PropTypes.func,
  selector: PropTypes.func,
  statem: PropTypes.any,
};
<commit_msg>Replace `assert` in Switch.js with custom `assert` (#846)<commit_after>import React, { PropTypes } from 'react';
import TabBar from './TabBar';
import { assert } from './Util';

export default function Switch(props) {
  const navState = props.navigationState;
  const selector = props.selector;
  const statem = props.statem;
  if (!selector && !statem) console.error('Selector should be defined.');
  let index = -1;
  if (!selector) {
    assert(statem.isIn, 'Wrong statem passed');
    // support Statem - Harel statecharts machine!
    navState.children.forEach((el, i) => {
      assert(el.default || el.state,
        `Either default or state should be defined for element=${el.key}`);
      if (el.default) {
        index = i;
      } else {
        assert(el.state.id, 'State doesn\'t have id');
        if (statem.isIn(el.state.id)) {
          index = i;
        }
      }
    });
    assert(index !== -1, 'No default scene is defined');
  } else {
    const selectedKey = selector(props);
    if (!selectedKey) console.error('Selector should return key.');
    navState.children.forEach((el, i) => {
      if (el.sceneKey === selectedKey) {
        index = i;
      }
    });
    if (index === -1) console.error(`A scene for key “${selectedKey}” does not exist.`);
  }
  const navigationState = index !== navState.index ? { ...navState, index } : navState;
  return (
    <TabBar
      onNavigate={props.onNavigate}
      navigationState={navigationState}
    />
  );
}

Switch.propTypes = {
  navigationState: PropTypes.object,
  onNavigate: PropTypes.func,
  selector: PropTypes.func,
  statem: PropTypes.any,
};
<|endoftext|>


<commit_before>app.directive('printDiv', function ()
{
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      element.bind('click', function(evt){
        evt.preventDefault();

        var loader= scope.$eval(attrs.loader);

        if (loader)
        loader(function ()
        {
           _.defer(function () { PrintElem(attrs.printDiv); });
        });
      });

      function PrintElem(elem)
      {
        PrintWithIframe($(elem).html());
      }

      function PrintWithIframe(data)
      {
        if ($('iframe#printf').size() == 0) {
          $('html').append('');  // an iFrame is added to the html content, then your div's contents are added to it and the iFrame's content is printed

          var mywindow = window.frames["printf"];
          mywindow.document.write('<title></title>'  // Your styles here, I needed the margins set up like this
                          + '
'
                          + data
                          + '
');

          $(mywindow.document).ready(function(){
            mywindow.print();
            setTimeout(function(){
              $('iframe#printf').remove();
            },
            2000);  // The iFrame is removed 2 seconds after print() is executed, which is enough for me, but you can play around with the value
          });
        }

        return true;
      }
    }
  };
});
<commit_msg>initial<commit_after><|endoftext|>