<commit_before>'use strict';

import * as helper from './helper.js';

export default class ContainerView {

  constructor(inspectorContent, originalParent, originalElements) {

    this._inspectorContent = inspectorContent;
    this._showedLevel = 0;
    this._maxNestedLevel = 0;
    this._isSingleZoom = false;
    this.isGlobalZoom = false;
    this.isZoomable = false;

    this._create(originalParent, originalElements);
  }

  getShowedLevel() {
    return this._showedLevel;
  }

  getMaxNestedLevel() {
    return this._maxNestedLevel;
  }

  _create(originalParent, originalElements) {
    // Create a new div with the position and size of the original container.
    // This div will be used as new root and is absolutely positioned. Thus it
    // is easier to position the actual elements correctly.
    var newParent = document.createElement('div');
    newParent.id = 'created--root';
    helper.copySpacing(newParent, originalParent);
    helper.copySize(newParent, originalParent);

    this._inspectorContent.appendChild(newParent);

    for (let i = 0; i < originalElements.length; i++) {
      if (originalElements[i].tagName != 'SCRIPT' && originalElements[i].tagName != 'LINK') {
        this._copyElement(newParent, originalElements[i]);
      }
    }
  }

  _copyElement(parentElement, element, nested = false, nestingLevel = 0) {
    let newElement = document.createElement('div');

    // Set style information for the new element
    helper.copySpacing(newElement, element);
    newElement.style.border = '1px solid' + helper.getRandomColor();
    newElement.style.display =  window.getComputedStyle(element, null).display;
    newElement.classList.add('created');

    // Only the last children of the hierarchy need an actual sizement.
    // All other elements are sized by their children
    if(element.children.length === 0) {
      helper.copySize(newElement, element);
    }

    // Child elements are hidden by default --> only first hierarchy level is shown
    if(nested) {
      newElement.style.visibility = 'hidden';
      newElement.classList.add('nested_' + nestingLevel);
    }

    if(element.id === "") {
      element.id = helper.getRandomId();
    }
    newElement.dataset.id = element.id;
    // This is a really ugly hack to get only the text of the actual element
    newElement.dataset.content = jQuery(element).clone().children().remove().end().text().trim();
    parentElement.appendChild(newElement);

    // Keep hierarchy information by adding child elements recursively
    if(element.children.length > 0) {
      nestingLevel += 1;

      for(let j = 0; j <  element.children.length; j++) {
        this._copyElement(newElement, element.children[j], true, nestingLevel);
      }
    }

    if (nestingLevel > this._maxNestedLevel) {
      this._maxNestedLevel = nestingLevel;
    }

    // Click handler
    let context = this;
    newElement.onclick = function() {
      context._handleOnClick(event, newElement, element, context);
    }

  }

  zoom(elements) {
    if(!this.isZoomable) {
      this.makeElementsZoomable(elements);
    }

    let maxCount = 1;
    let count = 1;

    for(let i = 0; i < elements.length; i++){
      if(elements[i].children.length > 0) {
        let numberOfChildren = jQuery(elements[i]).find('.created').length;
        this._increaseByHierarchyLevel(elements[i], numberOfChildren, true);

        // Reset counters
        maxCount = 1;
        count = 1;
      } else {
        this._increaseByHierarchyLevel(elements[i], 1, false);
      }
      if(this.isGlobalZoom) {
        elements[i].insertAdjacentHTML('afterbegin', elements[i].dataset.content);
      }
    }
  }

  makeElementsZoomable(elements) {
    // Define event handlers for the created elements
    let context = this;
    for(let i = 0; i < elements.length; i++) {
      elements[i].addEventListener('mouseover', function() {
        context._handleMouseOver(event, elements[i]);
      });
      elements[i].addEventListener('mouseleave', function() {
        context._handleMouseLeave(event, elements[i], elements);
      });
    }
    this.isZoomable = true;
  }

  deleteElements() {
    this._inspectorContent.querySelector('#created--root').remove();

    this._showedLevel = 0;
    this._maxNestedLevel = 0;
  }

  showNextHierarchyLevel(allElements) {
    // Find all elements with desired level and show them
    let elements = jQuery(allElements).find('.nested_' + (this._showedLevel + 1));
    if(elements.length > 0) {
      this.showElements(elements);
      this._showedLevel += 1;
    }
  }

  showElements(elements) {
    for(let i = 0; i < elements.length; i++) {
      elements[i].style.visibility = 'visible';
    }
  }

  //
  // Zoom view hover functionality
  //

  _handleMouseOver(e, element) {
    e.stopPropagation();

    let allParentElements = jQuery(element).parents('.created');
    let allChildElemets = jQuery(element).find('.created');
    let allElements = $.merge(allParentElements, allChildElemets);

    // Increase elements
    if(!this._isSingleZoom && !this.isGlobalZoom && this._isHighestElementOfHierarchy(element)){
      var elementsToZoom = $.merge([element], allElements);
      this.zoom(elementsToZoom);
      this._isSingleZoom = true;
    }

    // Highlighting
    for(let i = 0; i < allElements.length; i++) {
      allElements[i].style.backgroundColor = 'white';
    }
    element.style.backgroundColor = 'lightgrey';
  }

  _handleMouseLeave(e, element, allElements) {
    e.stopPropagation();

    // Reset highlighting
    for(let i = 0; i < allElements.length; i++) {
      allElements[i].style.backgroundColor = 'initial';
    }

    var infoLabels = this._inspectorContent.querySelectorAll(".infoLabel");
    for(let i = infoLabels.length - 1; 0 <= i; i--) {
      if(infoLabels[i] && infoLabels[i].parentElement) {
        if (infoLabels[i] != null) {
          infoLabels[i].parentElement.removeChild(infoLabels[i]);
        }
      }
    }

    // Decrease elements again
    if(this._isHighestElementOfHierarchy(element) && this._isSingleZoom) {
      this._undoZoom(element, element.children.length > 0);
      this._isSingleZoom = false;
    }
  }

  //
  // Zoom view helper functions
  //

  _increaseByHierarchyLevel(element, numberOfChildren, isParent)  {
    if (isParent) {
      // Increase by number of children + own increasement + cancel out padding of the child elements
      // The original element is necessary here because child elements increase automatically
      // with their parents. Thus they would be way to big.
      let originalElement = this._inspectorContent.querySelector('#' + element.dataset.id);
      element.style.height = parseFloat(originalElement.offsetHeight) +
        (numberOfChildren + 1) * helper.getDistanceValue() +
        numberOfChildren * 3 * helper.getDistanceValue() +
        'px';
      element.style.width = parseFloat(originalElement.offsetWidth) +
        (numberOfChildren + 1) * helper.getDistanceValue() +
        numberOfChildren * 3 * helper.getDistanceValue() +
        'px';
    }
    else {
      element.style.height = parseInt(element.style.height, 10) + 2 * helper.getDistanceValue() + 'px';
      element.style.width = parseInt(element.style.width, 10) + 2 * helper.getDistanceValue() + 'px';
    }

    var paddingValue = parseInt(element.style.padding, 10);
    if (paddingValue < 20 ) {
      element.style.padding = helper.getDistanceValue() + 'px';
    }
  }

  _decreaseByHierarchyLevel(element, numberOfChildren, isParent)  {
    let originalElement = this._inspectorContent.querySelector('#' + element.dataset.id);
    if (isParent) {
      // Since parent elements did not have an inital size
      // it is sufficient to remove the computed value here.
      element.style.removeProperty('height');
      element.style.removeProperty('width');
    }
    else {
      element.style.height = parseInt(element.style.height, 10) - 2 * helper.getDistanceValue() + 'px';
      element.style.width = parseInt(element.style.width, 10) - 2 * helper.getDistanceValue() + 'px';
    }
    // Reset the added padding
    helper.copySpacing(element, originalElement);
  }

  _undoZoom(element, isParent) {
    // Resize element to its original size
    let tmp = jQuery(element).find('.created').length;
    let numberOfChildren = tmp > 0 ? tmp : 1 ;

    this._decreaseByHierarchyLevel(element, numberOfChildren, isParent);

    // Resize all child elements
    if(element.children.length > 0) {
      for (let i = 0; i < element.children.length; i++) {
        this._undoZoom(element.children[i], element.children[i].children.length > 0);
      }
    }
  }

  _isHighestElementOfHierarchy(element) {
    return element.parentElement == this._inspectorContent.querySelector('#created--root');
  }

  //
  // Click handlers
  //
  _handleOnClick(e, newElement, originalElement, context) {
    // Pass click event
    if(this.isGlobalZoom) {
      // Measure click event of original element
      let start = new Date().getTime();
      originalElement.click();
      let end = new Date().getTime();

      // Write the time below the newly created element
      let informationNode = document.createElement('div');
      informationNode.className = "informationNode";
      informationNode.innerHTML = 'Time: ' + (end-start).toString() + ' ms';
      if(originalElement.classList.length > 0) {
        informationNode.innerHTML += ', Class(es): ' + originalElement.classList;
      }
      if(originalElement.id != undefined) {
        informationNode.innerHTML += ', ID: ' + originalElement.id ;
      }

      informationNode.style.left = parseFloat(newElement.offsetLeft) + 1 + 'px';
      informationNode.style.top = parseFloat(newElement.offsetTop) + 1 + 'px';
      informationNode.style.opacity = '0';
      let informationNodeWidth =  parseFloat(newElement.offsetWidth) - 7 + 'px';
      informationNode.style.width = informationNodeWidth;

      informationNode.addEventListener('mouseover', function() {
        this.style.overflow = 'visible';
        this.style.whiteSpace = 'normal';
      });

      informationNode.addEventListener('mouseleave', function() {
        this.style.overflow = 'hidden';
        this.style.whiteSpace = 'nowrap';
      });

      newElement.parentNode.insertBefore(informationNode, newElement.nextSibling);

      let fadeSpeed = 25;
      let intId = setInterval(function(){
        let newOpacity = parseFloat(informationNode.style.opacity) + 0.1;
        informationNode.style.opacity = newOpacity.toString();
        if(informationNode.style.opacity == '1'){
            clearInterval(intId);
        }
      }, fadeSpeed);

      // Remove information node after a few seconds
      window.setTimeout(function() {
        if (informationNode != null) {
          let intId = setInterval(function() {
              let newOpacity = parseFloat(informationNode.style.opacity) - 0.1;
              informationNode.style.opacity = newOpacity.toString();
              if(informationNode.style.opacity == '0'){
                  clearInterval(intId);
              }
          }, fadeSpeed);
          newElement.parentNode.removeChild(informationNode);
        }
      }, 4000);
    } else {
      originalElement.click();

      // Highlight original element
      originalElement.style.backgroundColor = 'red';
      window.setTimeout(function(){
        originalElement.style.backgroundColor = 'initial';
      }, 1000);
    }
    e.stopPropagation();
  }
}
<commit_msg>Add tagName for elements which have no text content in the zoomed view<commit_after>'use strict';

import * as helper from './helper.js';

export default class ContainerView {

  constructor(inspectorContent, originalParent, originalElements) {

    this._inspectorContent = inspectorContent;
    this._showedLevel = 0;
    this._maxNestedLevel = 0;
    this._isSingleZoom = false;
    this.isGlobalZoom = false;
    this.isZoomable = false;

    this._create(originalParent, originalElements);
  }

  getShowedLevel() {
    return this._showedLevel;
  }

  getMaxNestedLevel() {
    return this._maxNestedLevel;
  }

  _create(originalParent, originalElements) {
    // Create a new div with the position and size of the original container.
    // This div will be used as new root and is absolutely positioned. Thus it
    // is easier to position the actual elements correctly.
    var newParent = document.createElement('div');
    newParent.id = 'created--root';
    helper.copySpacing(newParent, originalParent);
    helper.copySize(newParent, originalParent);

    this._inspectorContent.appendChild(newParent);

    for (let i = 0; i < originalElements.length; i++) {
      if (originalElements[i].tagName != 'SCRIPT' && originalElements[i].tagName != 'LINK') {
        this._copyElement(newParent, originalElements[i]);
      }
    }
  }

  _copyElement(parentElement, element, nested = false, nestingLevel = 0) {
    let newElement = document.createElement('div');

    // Set style information for the new element
    helper.copySpacing(newElement, element);
    newElement.style.border = '1px solid' + helper.getRandomColor();
    newElement.style.display =  window.getComputedStyle(element, null).display;
    newElement.classList.add('created');

    // Only the last children of the hierarchy need an actual sizement.
    // All other elements are sized by their children
    if(element.children.length === 0) {
      helper.copySize(newElement, element);
    }

    // Child elements are hidden by default --> only first hierarchy level is shown
    if(nested) {
      newElement.style.visibility = 'hidden';
      newElement.classList.add('nested_' + nestingLevel);
    }

    if(element.id === "") {
      element.id = helper.getRandomId();
    }
    newElement.dataset.id = element.id;
    // This is a really ugly hack to get only the text of the actual element
    let text = jQuery(element).clone().children().remove().end().text().trim();
    newElement.dataset.content = (text.length > 0) ? text : element.tagName;
    parentElement.appendChild(newElement);

    // Keep hierarchy information by adding child elements recursively
    if(element.children.length > 0) {
      nestingLevel += 1;

      for(let j = 0; j <  element.children.length; j++) {
        this._copyElement(newElement, element.children[j], true, nestingLevel);
      }
    }

    if (nestingLevel > this._maxNestedLevel) {
      this._maxNestedLevel = nestingLevel;
    }

    // Click handler
    let context = this;
    newElement.onclick = function() {
      context._handleOnClick(event, newElement, element, context);
    }

  }

  zoom(elements) {
    if(!this.isZoomable) {
      this.makeElementsZoomable(elements);
    }

    let maxCount = 1;
    let count = 1;

    for(let i = 0; i < elements.length; i++){
      if(elements[i].children.length > 0) {
        let numberOfChildren = jQuery(elements[i]).find('.created').length;
        this._increaseByHierarchyLevel(elements[i], numberOfChildren, true);

        // Reset counters
        maxCount = 1;
        count = 1;
      } else {
        this._increaseByHierarchyLevel(elements[i], 1, false);
      }
      if(this.isGlobalZoom) {
        elements[i].insertAdjacentHTML('afterbegin', elements[i].dataset.content);
      }
    }
  }

  makeElementsZoomable(elements) {
    // Define event handlers for the created elements
    let context = this;
    for(let i = 0; i < elements.length; i++) {
      elements[i].addEventListener('mouseover', function() {
        context._handleMouseOver(event, elements[i]);
      });
      elements[i].addEventListener('mouseleave', function() {
        context._handleMouseLeave(event, elements[i], elements);
      });
    }
    this.isZoomable = true;
  }

  deleteElements() {
    this._inspectorContent.querySelector('#created--root').remove();

    this._showedLevel = 0;
    this._maxNestedLevel = 0;
  }

  showNextHierarchyLevel(allElements) {
    // Find all elements with desired level and show them
    let elements = jQuery(allElements).find('.nested_' + (this._showedLevel + 1));
    if(elements.length > 0) {
      this.showElements(elements);
      this._showedLevel += 1;
    }
  }

  showElements(elements) {
    for(let i = 0; i < elements.length; i++) {
      elements[i].style.visibility = 'visible';
    }
  }

  //
  // Zoom view hover functionality
  //

  _handleMouseOver(e, element) {
    e.stopPropagation();

    let allParentElements = jQuery(element).parents('.created');
    let allChildElemets = jQuery(element).find('.created');
    let allElements = $.merge(allParentElements, allChildElemets);

    // Increase elements
    if(!this._isSingleZoom && !this.isGlobalZoom && this._isHighestElementOfHierarchy(element)){
      var elementsToZoom = $.merge([element], allElements);
      this.zoom(elementsToZoom);
      this._isSingleZoom = true;
    }

    // Highlighting
    for(let i = 0; i < allElements.length; i++) {
      allElements[i].style.backgroundColor = 'white';
    }
    element.style.backgroundColor = 'lightgrey';
  }

  _handleMouseLeave(e, element, allElements) {
    e.stopPropagation();

    // Reset highlighting
    for(let i = 0; i < allElements.length; i++) {
      allElements[i].style.backgroundColor = 'initial';
    }

    var infoLabels = this._inspectorContent.querySelectorAll(".infoLabel");
    for(let i = infoLabels.length - 1; 0 <= i; i--) {
      if(infoLabels[i] && infoLabels[i].parentElement) {
        if (infoLabels[i] != null) {
          infoLabels[i].parentElement.removeChild(infoLabels[i]);
        }
      }
    }

    // Decrease elements again
    if(this._isHighestElementOfHierarchy(element) && this._isSingleZoom) {
      this._undoZoom(element, element.children.length > 0);
      this._isSingleZoom = false;
    }
  }

  //
  // Zoom view helper functions
  //

  _increaseByHierarchyLevel(element, numberOfChildren, isParent)  {
    if (isParent) {
      // Increase by number of children + own increasement + cancel out padding of the child elements
      // The original element is necessary here because child elements increase automatically
      // with their parents. Thus they would be way to big.
      let originalElement = this._inspectorContent.querySelector('#' + element.dataset.id);
      element.style.height = parseFloat(originalElement.offsetHeight) +
        (numberOfChildren + 1) * helper.getDistanceValue() +
        numberOfChildren * 3 * helper.getDistanceValue() +
        'px';
      element.style.width = parseFloat(originalElement.offsetWidth) +
        (numberOfChildren + 1) * helper.getDistanceValue() +
        numberOfChildren * 3 * helper.getDistanceValue() +
        'px';
    }
    else {
      element.style.height = parseInt(element.style.height, 10) + 2 * helper.getDistanceValue() + 'px';
      element.style.width = parseInt(element.style.width, 10) + 2 * helper.getDistanceValue() + 'px';
    }

    var paddingValue = parseInt(element.style.padding, 10);
    if (paddingValue < 20 ) {
      element.style.padding = helper.getDistanceValue() + 'px';
    }
  }

  _decreaseByHierarchyLevel(element, numberOfChildren, isParent)  {
    let originalElement = this._inspectorContent.querySelector('#' + element.dataset.id);
    if (isParent) {
      // Since parent elements did not have an inital size
      // it is sufficient to remove the computed value here.
      element.style.removeProperty('height');
      element.style.removeProperty('width');
    }
    else {
      element.style.height = parseInt(element.style.height, 10) - 2 * helper.getDistanceValue() + 'px';
      element.style.width = parseInt(element.style.width, 10) - 2 * helper.getDistanceValue() + 'px';
    }
    // Reset the added padding
    helper.copySpacing(element, originalElement);
  }

  _undoZoom(element, isParent) {
    // Resize element to its original size
    let tmp = jQuery(element).find('.created').length;
    let numberOfChildren = tmp > 0 ? tmp : 1 ;

    this._decreaseByHierarchyLevel(element, numberOfChildren, isParent);

    // Resize all child elements
    if(element.children.length > 0) {
      for (let i = 0; i < element.children.length; i++) {
        this._undoZoom(element.children[i], element.children[i].children.length > 0);
      }
    }
  }

  _isHighestElementOfHierarchy(element) {
    return element.parentElement == this._inspectorContent.querySelector('#created--root');
  }

  //
  // Click handlers
  //
  _handleOnClick(e, newElement, originalElement, context) {
    // Pass click event
    if(this.isGlobalZoom) {
      // Measure click event of original element
      let start = new Date().getTime();
      originalElement.click();
      let end = new Date().getTime();

      // Write the time below the newly created element
      let informationNode = document.createElement('div');
      informationNode.className = "informationNode";
      informationNode.innerHTML = 'Time: ' + (end-start).toString() + ' ms';
      if(originalElement.classList.length > 0) {
        informationNode.innerHTML += ', Class(es): ' + originalElement.classList;
      }
      if(originalElement.id != undefined) {
        informationNode.innerHTML += ', ID: ' + originalElement.id ;
      }

      informationNode.style.left = parseFloat(newElement.offsetLeft) + 1 + 'px';
      informationNode.style.top = parseFloat(newElement.offsetTop) + 1 + 'px';
      informationNode.style.opacity = '0';
      let informationNodeWidth =  parseFloat(newElement.offsetWidth) - 7 + 'px';
      informationNode.style.width = informationNodeWidth;

      informationNode.addEventListener('mouseover', function() {
        this.style.overflow = 'visible';
        this.style.whiteSpace = 'normal';
      });

      informationNode.addEventListener('mouseleave', function() {
        this.style.overflow = 'hidden';
        this.style.whiteSpace = 'nowrap';
      });

      newElement.parentNode.insertBefore(informationNode, newElement.nextSibling);

      let fadeSpeed = 25;
      let intId = setInterval(function(){
        let newOpacity = parseFloat(informationNode.style.opacity) + 0.1;
        informationNode.style.opacity = newOpacity.toString();
        if(informationNode.style.opacity == '1'){
            clearInterval(intId);
        }
      }, fadeSpeed);

      // Remove information node after a few seconds
      window.setTimeout(function() {
        if (informationNode != null) {
          let intId = setInterval(function() {
              let newOpacity = parseFloat(informationNode.style.opacity) - 0.1;
              informationNode.style.opacity = newOpacity.toString();
              if(informationNode.style.opacity == '0'){
                  clearInterval(intId);
              }
          }, fadeSpeed);
          newElement.parentNode.removeChild(informationNode);
        }
      }, 4000);
    } else {
      originalElement.click();

      // Highlight original element
      originalElement.style.backgroundColor = 'red';
      window.setTimeout(function(){
        originalElement.style.backgroundColor = 'initial';
      }, 1000);
    }
    e.stopPropagation();
  }
}
<|endoftext|>


<commit_before>// View model for the courses page
function pageViewModel(gvm) {
    gvm.userId = -1;
    gvm.studentlistName = ko.observable('Name');
    gvm.listId = -1
    // Page specific i18n bindings
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("AccountTitle");}, gvm);
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("EditListTitle");}, gvm);

    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    gvm.myLists = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("myLists");}, gvm);
    gvm.addStudListBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("addStudListBtn");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.codeTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CodeTableTitle");}, gvm);
    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.descTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DescTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.firstname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Firstname");}, gvm);
    gvm.lastname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Lastname");}, gvm);
    gvm.email = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Email");}, gvm);
    gvm.memberSince = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("MemberSince");}, gvm);
    gvm.myProjects = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("MyProjects");}, gvm);

    gvm.tabledata = ko.observableArray([]);

    gvm.addTableData = function(id, firstname, lastname, username) {
        // Push data
        var tblOject = {tid: id, tfirstname: firstname, tlastname: lastname, tusername: username};
        gvm.tabledata.push(tblOject);

        $('#editbtn-' + id).bind('click', function(event, data) {
            showEditStudentModal(tblOject);
            event.stopPropagation();
        });

        $('#removebtn-' + id).bind('click', function(event, data){
            // Delete the table item
            deleteTableItem(id, tblOject);
            event.stopPropagation();
        });
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }

}

function showEditStudentModal(tblObject) {
    resetGeneralModal();
    setGeneralModalTitle("Edit Student");
    setGeneralModalBody('<form id="updateStudent"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + tblObject.tfirstname + '" " name="firstname" value="' + tblObject.tfirstname + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + tblObject.tlastname + '" name="lastname" value="' + tblObject.tlastname + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + tblObject.tusername + '" name="username" value="' + tblObject.tusername + '"> \

 \
        </form>');
    $.getJSON()

    addGeneralModalButton(i18n.__("SaveBtn"), function(){
        updateStudent(tblObject.tid, $('#updateStudent').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })

    showGeneralModal();
}

function showNewStudentModal() {
    resetGeneralModal();
    setGeneralModalTitle("Add Student");
    setGeneralModalBody('<form id="newStudentFrom"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('NameTableTitle') + '" " name="name"> \
                <button id="searchStudent" class="btn btn-default">Search</button> \

 \
        </form>');
    $.getJSON();

    addGeneralModalButton(i18n.__("AddBtn"), function(){
        addNewStudent($('#newStudentFrom').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })

    showGeneralModal();
}

function addNewStudent(serialData, callback) {
    console.log(serialData);
    $.ajax({
        url: "/api/newstudent/" + viewModel.listId,
        type: "POST",
        data: serialData,
        success: function(data) {
            viewModel.addTableData(data['id'], data['firstname'], data['lastname'], data['mail']);
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

function updateStudent(id, object, callback) {
    $.ajax({
        url: "/api/studentrapport/" + id,
        type: "PUT",
        data: object,
        success: function(data) {
            loadStudentTable();
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

function deleteTableItem(id, tblObject){
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen?", function(val){
        if(val){
            $.ajax({
                url: '/api/studentlistrapport/' + $("#page-header").data('value') + '/delete/student/' + id,
                type: "DELETE",
                success: function() {
                    viewModel.tabledata.remove(tblObject);
                }
            });
        }
    });
}

function loadStudentTable() {
    $.getJSON('/api/studentlistrapporten/students/' + $("#page-header").data('value'), function(data) {
        viewModel.clearTable();
        // Load table data
        $.each(data, function(i, item) {
            viewModel.addTableData(item.id, item.firstname, item.lastname, item.username);
        });
    });
}

function initPage() {
    $.getJSON('/api/studentlistrapport/info/' + $("#page-header").data('value'), function(data) {
        console.log(data[0].id);
        viewModel.studentlistName(data[0].name);
        viewModel.listId = (data[0].id);
    });

    $('#addStudent').click(function(){
        showNewStudentModal();
    });

    $('#searchStudent').click(function() {
        console.log('Clicked search');
    });

    loadStudentTable();

}<commit_msg>autocomplete weggesmeten, search functie in de plaats :p<commit_after>// View model for the courses page
function pageViewModel(gvm) {
    gvm.userId = -1;
    gvm.studentlistName = ko.observable('Name');
    gvm.listId = -1
    // Page specific i18n bindings
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("AccountTitle");}, gvm);
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("EditListTitle");}, gvm);

    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    gvm.myLists = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("myLists");}, gvm);
    gvm.addStudListBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("addStudListBtn");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.codeTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CodeTableTitle");}, gvm);
    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.descTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DescTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.firstname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Firstname");}, gvm);
    gvm.lastname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Lastname");}, gvm);
    gvm.email = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Email");}, gvm);
    gvm.memberSince = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("MemberSince");}, gvm);
    gvm.myProjects = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("MyProjects");}, gvm);

    gvm.tabledata = ko.observableArray([]);

    gvm.addTableData = function(id, firstname, lastname, username) {
        // Push data
        var tblOject = {tid: id, tfirstname: firstname, tlastname: lastname, tusername: username};
        gvm.tabledata.push(tblOject);

        $('#editbtn-' + id).bind('click', function(event, data) {
            showEditStudentModal(tblOject);
            event.stopPropagation();
        });

        $('#removebtn-' + id).bind('click', function(event, data){
            // Delete the table item
            deleteTableItem(id, tblOject);
            event.stopPropagation();
        });
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }

}

function showEditStudentModal(tblObject) {
    resetGeneralModal();
    setGeneralModalTitle("Edit Student");
    setGeneralModalBody('<form id="updateStudent"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + tblObject.tfirstname + '" " name="firstname" value="' + tblObject.tfirstname + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + tblObject.tlastname + '" name="lastname" value="' + tblObject.tlastname + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + tblObject.tusername + '" name="username" value="' + tblObject.tusername + '"> \

 \
        </form>');
    $.getJSON()

    addGeneralModalButton(i18n.__("SaveBtn"), function(){
        updateStudent(tblObject.tid, $('#updateStudent').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })

    showGeneralModal();
}

function showNewStudentModal() {
    resetGeneralModal();
    setGeneralModalTitle("Add Student");
    setGeneralModalBody('<form id="newStudentFrom"> \

 \
                <input type="text" class="form-control input-lg col-md-5" placeholder="' + i18n.__('NameTableTitle') + '" " name="name"> \
                <button id="searchStudent" class="btn btn-default">Search</button> \

 \
        </form>');
    $.getJSON();

    addGeneralModalButton(i18n.__("AddBtn"), function(){
        addNewStudent($('#newStudentFrom').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })

    showGeneralModal();
}

function addNewStudent(serialData, callback) {
    console.log(serialData);
    $.ajax({
        url: "/api/newstudent/" + viewModel.listId,
        type: "POST",
        data: serialData,
        success: function(data) {
            viewModel.addTableData(data['id'], data['firstname'], data['lastname'], data['mail']);
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

function updateStudent(id, object, callback) {
    $.ajax({
        url: "/api/studentrapport/" + id,
        type: "PUT",
        data: object,
        success: function(data) {
            loadStudentTable();
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

function deleteTableItem(id, tblObject){
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen?", function(val){
        if(val){
            $.ajax({
                url: '/api/studentlistrapport/' + $("#page-header").data('value') + '/delete/student/' + id,
                type: "DELETE",
                success: function() {
                    viewModel.tabledata.remove(tblObject);
                }
            });
        }
    });
}

function loadStudentTable() {
    $.getJSON('/api/studentlistrapporten/students/' + $("#page-header").data('value'), function(data) {
        viewModel.clearTable();
        // Load table data
        $.each(data, function(i, item) {
            viewModel.addTableData(item.id, item.firstname, item.lastname, item.username);
        });
    });
}

function initPage() {
    $.getJSON('/api/studentlistrapport/info/' + $("#page-header").data('value'), function(data) {
        console.log(data[0].id);
        viewModel.studentlistName(data[0].name);
        viewModel.listId = (data[0].id);
    });

    $('#addStudent').click(function(){
        showNewStudentModal();
    });

    $('#searchStudent').click(function() {
        console.log('Clicked search');
    });

    loadStudentTable();

}<|endoftext|>


<commit_before>var sys = require('sys');
var net = require('net');
//var mqtt = require('mqtt');
var mqtt = require('mqtt');

var io  = require('socket.io').listen(5000);

io.on('connection', function(socket){
  console.log('a user connected');
  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});

client = mqtt.createClient();

client.subscribe('#');
//client.publish('messages', 'hello me!');
client.on('message', function(topic, message) {
  console.log(message);
  io.sockets.emit('mqtt',{'topic':String(topic),'payload':String(message)});
});
<commit_msg>Added uniqe instance for each connection to socket.io towards mqtt to get retained messages<commit_after>var sys = require('sys');
var net = require('net');
//var mqtt = require('mqtt');
var mqtt = require('mqtt');

var io  = require('socket.io').listen(5000);

io.on('connection', function(socket){
  console.log('a user connected');

  socket.mqtt = mqtt.createClient();
  socket.mqtt.subscribe('#');

  //Forward all messages to socket.io
  socket.mqtt.on('message', function(topic, message) {
    console.log(message);
    io.sockets.emit('mqtt',{'topic':String(topic),'payload':String(message)});
  });

  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});

//client = mqtt.createClient();

//client.subscribe('#');
//client.publish('messages', 'hello me!');
//client.on('message', function(topic, message) {
//  console.log(message);
//  io.sockets.emit('mqtt',{'topic':String(topic),'payload':String(message)});
//});
<|endoftext|>


<commit_before>var React = require('React');
var ReactNativeViewAttributes = require('ReactNativeViewAttributes');
var StyleSheet = require('StyleSheet');
var createReactNativeComponentClass = require('createReactNativeComponentClass');
var PropTypes = require('ReactPropTypes');
var LayoutPropTypes = require('LayoutPropTypes');
var StyleSheetPropType = require('StyleSheetPropType');
var NativeMethodsMixin = require('NativeMethodsMixin');
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
var FBLoginManager = require('NativeModules').FBLoginManager;

var FBLogin = React.createClass({
  statics: {
    Events: FBLoginManager.Events,
  },

  propTypes: {
    style: StyleSheetPropType(LayoutPropTypes),
    permissions: PropTypes.array, // default: ["public_profile", "email"]
    onLogin: PropTypes.func,
    onLogout: PropTypes.func,
    onLoginFound: PropTypes.func,
    onLoginNotFound: PropTypes.func,
    onError: PropTypes.func,
    onCancel: PropTypes.func,
    onPermissionsMissing: PropTypes.func,
  },

  getInitialState: function(){
    return {
      credentials: null,
      subscriptions: [],
    };
  },

  mixins: [NativeMethodsMixin],

  componentWillMount: function(){
    var _this = this;
    var subscriptions = this.state.subscriptions;

    // For each event key in FBLoginManager constantsToExport
    // Create listener and call event handler from props
    // e.g.  this.props.onError, this.props.onLogin
    Object.keys(FBLoginManager.Events).forEach(function(event){
      subscriptions.push(RCTDeviceEventEmitter.addListener(
        FBLoginManager.Events[event],
        (eventData) => {
          // event handler defined? call it and pass along any event data
          var eventHandler = _this.props["on"+event];
          eventHandler && eventHandler(eventData);
        }
      ));
    })

    // Add listeners to state
    this.setState({ subscriptions : subscriptions });
  },

  componentWillUnmount: function(){
    var subscriptions = this.state.subscriptions;
    subscriptions.forEach(function(subscription){
      subscription.remove();
    });
  },

  componentDidMount: function(){
    var _this = this;
    FBLoginManager.getCredentials(function(error, data){
      if (!error) {
        _this.setState({ credentials : data.credentials });
      } else {
        _this.setState({ credentials : null });
      }
    });
  },

  render: function() {
    var props = {
      ...this.props,
      style: ([styles.base, this.props.style]),
    };

    return <RCTFBLogin {...props} />
  },
});

var RCTFBLogin = createReactNativeComponentClass({
  validAttributes: {
    ...ReactNativeViewAttributes.UIView,
    permissions: true,
  },
  uiViewClassName: 'RCTFBLogin',
});

var styles = StyleSheet.create({
  base: {
    width: 175,
    height: 30,
  },
});

module.exports = FBLogin;
<commit_msg>Use correct CommonJS `require` paths for react native 0.8.0<commit_after>var React = require('react-native');
var {
  StyleSheet,
  PropTypes,
  NativeModules
} = React;
var createReactNativeComponentClass = require('react-native/Libraries/ReactNative/createReactNativeComponentClass');
var ReactNativeViewAttributes = require('react-native/Libraries/ReactNative/ReactNativeViewAttributes');
var LayoutPropTypes = require('react-native/Libraries/StyleSheet/LayoutPropTypes');
var StyleSheetPropType = require('react-native/Libraries/StyleSheet/StyleSheetPropType');
var NativeMethodsMixin = require('react-native/Libraries/ReactIOS/NativeMethodsMixin');
var RCTDeviceEventEmitter = require('react-native/Libraries/Device/RCTDeviceEventEmitter');
var StyleSheetPropType = require('react-native/Libraries/StyleSheet/StyleSheetPropType');

var { FBLoginManager } = NativeModules;

var FBLogin = React.createClass({
  statics: {
    Events: FBLoginManager.Events,
  },

  propTypes: {
    style: StyleSheetPropType(LayoutPropTypes),
    permissions: PropTypes.array, // default: ["public_profile", "email"]
    onLogin: PropTypes.func,
    onLogout: PropTypes.func,
    onLoginFound: PropTypes.func,
    onLoginNotFound: PropTypes.func,
    onError: PropTypes.func,
    onCancel: PropTypes.func,
    onPermissionsMissing: PropTypes.func,
  },

  getInitialState: function(){
    return {
      credentials: null,
      subscriptions: [],
    };
  },

  mixins: [NativeMethodsMixin],

  componentWillMount: function(){
    var _this = this;
    var subscriptions = this.state.subscriptions;

    // For each event key in FBLoginManager constantsToExport
    // Create listener and call event handler from props
    // e.g.  this.props.onError, this.props.onLogin
    Object.keys(FBLoginManager.Events).forEach(function(event){
      subscriptions.push(RCTDeviceEventEmitter.addListener(
        FBLoginManager.Events[event],
        (eventData) => {
          // event handler defined? call it and pass along any event data
          var eventHandler = _this.props["on"+event];
          eventHandler && eventHandler(eventData);
        }
      ));
    })

    // Add listeners to state
    this.setState({ subscriptions : subscriptions });
  },

  componentWillUnmount: function(){
    var subscriptions = this.state.subscriptions;
    subscriptions.forEach(function(subscription){
      subscription.remove();
    });
  },

  componentDidMount: function(){
    var _this = this;
    FBLoginManager.getCredentials(function(error, data){
      if (!error) {
        _this.setState({ credentials : data.credentials });
      } else {
        _this.setState({ credentials : null });
      }
    });
  },

  render: function() {
    var props = {
      ...this.props,
      style: ([styles.base, this.props.style]),
    };

    return <RCTFBLogin {...props} />
  },
});

var RCTFBLogin = createReactNativeComponentClass({
  validAttributes: {
    ...ReactNativeViewAttributes.UIView,
    permissions: true,
  },
  uiViewClassName: 'RCTFBLogin',
});

var styles = StyleSheet.create({
  base: {
    width: 175,
    height: 30,
  },
});

module.exports = FBLogin;
<|endoftext|>


<commit_before>"use strict";

var React = require("react");
var Swipable = require("../Swipable");
var CarouselMixin = require("../CarouselMixin");
var getClassName = require("../utils/getClassName");

module.exports = React.createClass({
    displayName: "Carousel",

    mixins: [Swipable, CarouselMixin],

    calculatePageStyle: function (index) {
        return {
            width: this.props.pageWidth + "px",
            height: this.props.pageHeight + "px",
            opacity: index === this.props.pageIndex ? "1.0" : "0.0",
        };
    },

    renderPage: function (buffer, pageView) {
        return React.DOM.div({
            className: this.props.baseClass + "__page",
            key: buffer.index,
            style: this.calculatePageStyle(buffer.index),
        }, pageView);
    },

    calculateStyle: function () {
        return {
            width: (this.props.width) + "px",
            height: (this.props.height) + "px",
            left: (-this.props.embedWidth) + "px",
            top: (-this.props.embedHeight) + "px",
        };
    },

    render: function () {
        if ( this.props.pages.length === 0 ) {
            // (jussi-kalliokoski): Nothing to render. Avoids infinite loop in calculateBuffers().
            return React.DOM.div();
        }

        return React.DOM.div({
            className: this.props.baseClass,
            onTouchStart: this.handleTouchStart,
            onTouchMove: this.handleTouchMove,
            onTouchEnd: this.handleTouchEnd,
            onTouchCancel: this.handleTouchCancel,
            style: this.calculateStyle(),
        },
            this.renderPages()
        );
    },
});
<commit_msg>Added z-indexing for Fader.<commit_after>"use strict";

var React = require("react");
var Swipable = require("../Swipable");
var CarouselMixin = require("../CarouselMixin");
var getClassName = require("../utils/getClassName");

module.exports = React.createClass({
    displayName: "Carousel",

    mixins: [Swipable, CarouselMixin],

    calculatePageStyle: function (index) {
        return {
            width: this.props.pageWidth + "px",
            height: this.props.pageHeight + "px",
            opacity: index === this.props.pageIndex ? "1.0" : "0.0",
            zIndex: this.props.zIndexMax - Math.abs(index - this.props.pageIndex),
        };
    },

    renderPage: function (buffer, pageView) {
        return React.DOM.div({
            className: this.props.baseClass + "__page",
            key: buffer.index,
            style: this.calculatePageStyle(buffer.index),
        }, pageView);
    },

    calculateStyle: function () {
        return {
            width: (this.props.width) + "px",
            height: (this.props.height) + "px",
            left: (-this.props.embedWidth) + "px",
            top: (-this.props.embedHeight) + "px",
        };
    },

    render: function () {
        if ( this.props.pages.length === 0 ) {
            // (jussi-kalliokoski): Nothing to render. Avoids infinite loop in calculateBuffers().
            return React.DOM.div();
        }

        return React.DOM.div({
            className: this.props.baseClass,
            onTouchStart: this.handleTouchStart,
            onTouchMove: this.handleTouchMove,
            onTouchEnd: this.handleTouchEnd,
            onTouchCancel: this.handleTouchCancel,
            style: this.calculateStyle(),
        },
            this.renderPages()
        );
    },
});
<|endoftext|>


<commit_before>//  Freestyle Sotware, Inc.
//  INTERFACE - A React Native UI Library

//  ------------------------------------------------------------

'use strict';

var React = require('react-native');
var {
    StyleSheet,
    View,
    Text,
    Image,
    PixelRatio,
    ScrollView,
    TextInput,
    TouchableHighlight,
    SwitchIOS,
    PickerIOS
} = React;

var {
    baseColor,
    baseFont,
    baseImage,
    sharedStyle,
    serverAddress,
} = require('./BaseStyles');

var tinyColor = require("tinycolor2");

// Template -------------------------------------------------------------------

var FormExample = React.createClass ({

    getInitialState() {
        return {
            markAsComplete: true,
            followupNeeded: true,
        };
    },

    render() {
        return (
            <View style={styles.container}>
                <Image style={styles.backdrop} source={{ uri: baseImage.backdrop}}>
                    <View style={sharedStyle.overlay} />
                    <ScrollView
                        keyboardDismissMode={true}
                        keyboardShouldPersistTaps={false}
                        automaticallyAdjustContentInsets="false">

                        <View style={styles.form}>

                            <TextInput
                                style={styles.editfield}
                                placeholder={"Company"}
                                placeholderTextColor={tinyColor(baseColor.black.toString("hsl")).setAlpha(0.35).toRgbString()}
                                keyboardType={"default"}
                                autoCorrect={false}
                                clearButtonMode={"while-editing"}
                            />
                            <View style={styles.underline} />

                            <TextInput
                                style={styles.editfield}
                                placeholder={"Email"}
                                placeholderTextColor={tinyColor(baseColor.black.toString("hsl")).setAlpha(0.35).toRgbString()}
                                keyboardType={"email-address"}
                                autoCorrect={false}
                                clearButtonMode={"while-editing"}
                            />
                            <View style={styles.underline} />

                            <TextInput
                                style={styles.editfield}
                                password={true}
                                placeholder={"Password"}
                                placeholderTextColor={tinyColor(baseColor.black.toString("hsl")).setAlpha(0.35).toRgbString()}
                                keyboardType={"ascii-capable"}
                                autoCorrect={false}
                                clearButtonMode={"while-editing"}
                            />
                            <View style={styles.underline} />

                            <View style={styles.switch}>
                                <Text style={styles.switcherLabel}>Mark as complete</Text>
                                <View style={styles.switcher}>
                                    <SwitchIOS
                                        style={styles.switcher}
                                        onValueChange={(value) => this.setState({markAsComplete: value})}
                                        value={this.state.markAsComplete}
                                        thumbTintColor={baseColor.black}
                                        tintColor={baseColor.black}
                                        onTintColor={baseColor.color}
                                    />
                                </View>
                            </View>
                            <View style={styles.underline} />

                            <View style={styles.switch}>
                                <Text style={styles.switcherLabel}>Follow up needed</Text>
                                <View style={styles.switcher}>
                                    <SwitchIOS
                                        style={styles.switcher}
                                        onValueChange={(value) => this.setState({followupNeeded: value})}
                                        value={this.state.followupNeeded}
                                        thumbTintColor={baseColor.black}
                                        tintColor={baseColor.black}
                                        onTintColor={baseColor.color}
                                    />
                                </View>
                            </View>
                            <View style={styles.underline} />

                            <TouchableHighlight style={styles.button} underlayColor={baseColor.color}>
                                <Text style={styles.buttonLabel}>AUTHORIZE</Text>
                            </TouchableHighlight>

                            <Text style={styles.description}>
                                Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
                                incididunt ut labore et dolore magna aliqua.
                            </Text>
                            <Text style={styles.description}>
                                Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
                                ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit
                                esse cillum dolore eu fugiat nulla pariatur.
                            </Text>

                        </View>

                    </ScrollView>
                </Image>
            </View>
		);
	},

});

// Styling --------------------------------------------------------------------

var styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: baseColor.white,
    },

    backdrop: {
        flex: 1,
        resizeMode: "cover",
        backgroundColor: "transparent",
    },

    form: {
        flex: 1,
        marginTop: 20,
        paddingLeft: 12,
        paddingRight: 12,
        backgroundColor: "transparent",
    },

    editfield: {
        ...baseFont.medium,
        height: 46,
        marginTop: 8,
        padding: 8,
        backgroundColor: "transparent",
    },
    underline: {
        height: 1,
        backgroundColor: "transparent",
        borderBottomWidth: 1 / PixelRatio.get(),
        borderBottomColor: tinyColor(baseColor.white.toString("hsl")).setAlpha(0.25).toRgbString(),
    },

    switch: {
        flexDirection: "row",
        height: 46,
        marginTop: 8,
        padding: 8,
        alignItems: "center",
    },
    switcherLabel: {
        ...baseFont.medium,
        marginTop: 2,
    },
    switcher: {
        flex: 1,
        alignSelf: "flex-end",
    },

    button: {
        alignItems: "center",
        marginTop: 32,
        marginBottom: 16,
        padding: 8,
        borderWidth: 1/ PixelRatio.get(),
        borderRadius: 20,
        borderColor: baseColor.black,
        backgroundColor: tinyColor(baseColor.black.toString("hsl")).setAlpha(0.20).toRgbString(),
    },
    buttonLabel: {
        ...baseFont.medium,
    },

    description: {
        ...baseFont.small,
        marginTop: 16,
    }

});

// ----------------------------------------------------------------------------

module.exports = FormExample;
<commit_msg>Minor edit<commit_after>//  Freestyle Sotware, Inc.
//  INTERFACE - A React Native UI Library

//  ------------------------------------------------------------

'use strict';

var React = require('react-native');
var {
    StyleSheet,
    View,
    Text,
    Image,
    PixelRatio,
    ScrollView,
    TextInput,
    TouchableHighlight,
    SwitchIOS,
    PickerIOS
} = React;

var {
    baseColor,
    baseFont,
    baseImage,
    sharedStyle,
    serverAddress,
} = require('./BaseStyles');

var tinyColor = require("tinycolor2");

// Template -------------------------------------------------------------------

var FormExample = React.createClass ({

    getInitialState() {
        return {
            markAsComplete: true,
            followupNeeded: true,
        };
    },

    render() {
        return (
            <View style={styles.container}>
                <Image style={styles.backdrop} source={{ uri: baseImage.backdrop}}>
                    <View style={sharedStyle.overlay} />

                    <ScrollView
                        keyboardDismissMode={true}
                        keyboardShouldPersistTaps={false}
                        automaticallyAdjustContentInsets="false">

                        <View style={styles.form}>

                            <TextInput
                                style={styles.editfield}
                                placeholder={"Company"}
                                placeholderTextColor={tinyColor(baseColor.black.toString("hsl")).setAlpha(0.35).toRgbString()}
                                keyboardType={"default"}
                                autoCorrect={false}
                                clearButtonMode={"while-editing"}
                            />
                            <View style={styles.underline} />

                            <TextInput
                                style={styles.editfield}
                                placeholder={"Email"}
                                placeholderTextColor={tinyColor(baseColor.black.toString("hsl")).setAlpha(0.35).toRgbString()}
                                keyboardType={"email-address"}
                                autoCorrect={false}
                                clearButtonMode={"while-editing"}
                            />
                            <View style={styles.underline} />

                            <TextInput
                                style={styles.editfield}
                                password={true}
                                placeholder={"Password"}
                                placeholderTextColor={tinyColor(baseColor.black.toString("hsl")).setAlpha(0.35).toRgbString()}
                                keyboardType={"ascii-capable"}
                                autoCorrect={false}
                                clearButtonMode={"while-editing"}
                            />
                            <View style={styles.underline} />

                            <View style={styles.switch}>
                                <Text style={styles.switcherLabel}>Mark as complete</Text>
                                <View style={styles.switcher}>
                                    <SwitchIOS
                                        style={styles.switcher}
                                        onValueChange={(value) => this.setState({markAsComplete: value})}
                                        value={this.state.markAsComplete}
                                        thumbTintColor={baseColor.black}
                                        tintColor={baseColor.black}
                                        onTintColor={baseColor.color}
                                    />
                                </View>
                            </View>
                            <View style={styles.underline} />

                            <View style={styles.switch}>
                                <Text style={styles.switcherLabel}>Follow up needed</Text>
                                <View style={styles.switcher}>
                                    <SwitchIOS
                                        style={styles.switcher}
                                        onValueChange={(value) => this.setState({followupNeeded: value})}
                                        value={this.state.followupNeeded}
                                        thumbTintColor={baseColor.black}
                                        tintColor={baseColor.black}
                                        onTintColor={baseColor.color}
                                    />
                                </View>
                            </View>
                            <View style={styles.underline} />

                            <TouchableHighlight style={styles.button} underlayColor={baseColor.color}>
                                <Text style={styles.buttonLabel}>AUTHORIZE</Text>
                            </TouchableHighlight>

                            <Text style={styles.description}>
                                Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
                                incididunt ut labore et dolore magna aliqua.
                            </Text>
                            <Text style={styles.description}>
                                Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
                                ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit
                                esse cillum dolore eu fugiat nulla pariatur.
                            </Text>

                        </View>

                    </ScrollView>
                </Image>
            </View>
		);
	},

});

// Styling --------------------------------------------------------------------

var styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: baseColor.white,
    },

    backdrop: {
        flex: 1,
        resizeMode: "cover",
        backgroundColor: "transparent",
    },

    form: {
        flex: 1,
        marginTop: 20,
        paddingLeft: 12,
        paddingRight: 12,
        backgroundColor: "transparent",
    },

    editfield: {
        ...baseFont.medium,
        height: 46,
        marginTop: 8,
        padding: 8,
        backgroundColor: "transparent",
    },
    underline: {
        height: 1,
        backgroundColor: "transparent",
        borderBottomWidth: 1 / PixelRatio.get(),
        borderBottomColor: tinyColor(baseColor.white.toString("hsl")).setAlpha(0.25).toRgbString(),
    },

    switch: {
        flexDirection: "row",
        height: 46,
        marginTop: 8,
        padding: 8,
        alignItems: "center",
    },
    switcherLabel: {
        ...baseFont.medium,
        marginTop: 2,
    },
    switcher: {
        flex: 1,
        alignSelf: "flex-end",
    },

    button: {
        alignItems: "center",
        marginTop: 32,
        marginBottom: 16,
        padding: 8,
        borderWidth: 1/ PixelRatio.get(),
        borderRadius: 20,
        borderColor: baseColor.black,
        backgroundColor: tinyColor(baseColor.black.toString("hsl")).setAlpha(0.20).toRgbString(),
    },
    buttonLabel: {
        ...baseFont.medium,
    },

    description: {
        ...baseFont.small,
        marginTop: 16,
    }

});

// ----------------------------------------------------------------------------

module.exports = FormExample;
<|endoftext|>


<commit_before>'use strict';

const sprintf = require('sprintf')
const request = require('request')
const parser = require('cheerio')

const URL = 'http://www.sky56.cn/track/track/result?tracking_number=%s'

const sky = {}

/**
 * Get Sky56 info
 * Supports PQ... and NL... ids
 * Async
 *
 * @param id
 * @param callback(Error, SkyInfo)
 */
sky.getInfo = function (id, callback) {
    request(sprintf(URL, id), function (error, response, body) {
        if (error || response.statusCode != 200) {
            callback(error)
            return
        }

        const json = JSON.parse(body)

        // Not found
        if (json.message.indexOf('No result found for your query.') != -1) {
            callback(new Error("No data or invalid data provided!"))
            return
        }

        let entity = null
        switch(id.charAt(0)) {
            case 'N': // Netherlands Post surface mail
                entity = createNLSkyEntity(id, json)
                break
            default: // Spain express, correos line
                entity = createSkyEntity(id, json)
        }

        callback(null, entity)
    })
}

/*
|--------------------------------------------------------------------------
| Correos Line Parse
|--------------------------------------------------------------------------
*/
/**
 * Create SkyInfo entity from json
 * @param id
 * @param json
 */
function createSkyEntity(id, json) {
    let infos = json.message.split('
')
    let messages = infos.splice(infos.length - 4,4)
    let table = messages[messages.length-1]
    let $ = parser.load(table)

    let states = []
    const fields = ['date', 'area', 'status']
    $('tr').each(function (i) {
        if(i == 0) return

        let state = {}

        $(this).children().each(function (s) {
            state[fields[s]] = $(this).text()
        })
        states.push(state)
    })

    let parsedMessages = infos.map(message => {
        let idx1 = message.indexOf(" ")
        let idx2 = message.indexOf(" ", idx1+1)
        let date = message.substr(0, idx2)
        let m = message.substr(idx2 + 1, message.length)
        return {
            date: date,
            message: m.trim()
        }
    })

    return new SkyInfo({
        id: id,
        'messages': parsedMessages,
        'status': states.reverse()
    })
}

function SkyInfo(obj) {
    this.id = obj.id
    this.messages = obj.messages
    this.status = obj.status

    this.isNL = () => {
        return this.id.charAt(0) == 'N'
    }
}

/*
|--------------------------------------------------------------------------
| Netherlands Post surface mail Parse
|--------------------------------------------------------------------------
*/
function createNLSkyEntity(id, json) {
    let infos = json.message.split('
').filter(m => m.length != 0)

    let parsedStatus = infos.map(message => {
        let idx1 = message.indexOf(",")
        let idx2 = message.indexOf("--", idx1+1)
        let area = message.substr(0, idx1)
        let status = message.substr(idx1+1, idx2 - idx1 - 1)
        let date = message.substr(idx2 + 2)
        return {
            area: area,
            status: status.trim().capitalizeFirstLetter(),
            date: date
        }
    })

    return new SkyInfo({
        id: id,
        'status': parsedStatus
    })
}

/*
|--------------------------------------------------------------------------
| Utils
|--------------------------------------------------------------------------
*/
String.prototype.capitalizeFirstLetter = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

module.exports = sky<commit_msg>Fixed asci comma in the sky info<commit_after>'use strict';

const sprintf = require('sprintf')
const request = require('request')
const parser = require('cheerio')

const URL = 'http://www.sky56.cn/track/track/result?tracking_number=%s'

const sky = {}

/**
 * Get Sky56 info
 * Supports PQ... and NL... ids
 * Async
 *
 * @param id
 * @param callback(Error, SkyInfo)
 */
sky.getInfo = function (id, callback) {
    request(sprintf(URL, id), function (error, response, body) {
        if (error || response.statusCode != 200) {
            callback(error)
            return
        }

        const json = JSON.parse(body)

        // Not found
        if (json.message.indexOf('No result found for your query.') != -1) {
            callback(new Error("No data or invalid data provided!"))
            return
        }

        let entity = null
        switch(id.charAt(0)) {
            case 'N': // Netherlands Post surface mail
                entity = createNLSkyEntity(id, json)
                break
            default: // Spain express, correos line
                entity = createSkyEntity(id, json)
        }

        callback(null, entity)
    })
}

/*
|--------------------------------------------------------------------------
| Correos Line Parse
|--------------------------------------------------------------------------
*/
/**
 * Create SkyInfo entity from json
 * @param id
 * @param json
 */
function createSkyEntity(id, json) {
    let infos = json.message.split('
')
    let messages = infos.splice(infos.length - 4,4)
    let table = messages[messages.length-1]
    let $ = parser.load(table)

    let states = []
    const fields = ['date', 'area', 'status']
    $('tr').each(function (i) {
        if(i == 0) return

        let state = {}

        $(this).children().each(function (s) {
            state[fields[s]] = $(this).text()
        })
        states.push(state)
    })

    let parsedMessages = infos.map(message => {
        let idx1 = message.indexOf(" ")
        let idx2 = message.indexOf(" ", idx1+1)
        let date = message.substr(0, idx2)
        let m = message.substr(idx2 + 1, message.length)
        return {
            date: date,
            message: m.trim()
        }
    })

    return new SkyInfo({
        id: id,
        'messages': parsedMessages,
        'status': states.reverse()
    })
}

function SkyInfo(obj) {
    this.id = obj.id
    this.messages = obj.messages
    this.status = obj.status

    this.isNL = () => {
        return this.id.charAt(0) == 'N'
    }
}

/*
|--------------------------------------------------------------------------
| Netherlands Post surface mail Parse
|--------------------------------------------------------------------------
*/
function createNLSkyEntity(id, json) {
    let infos = json.message.replace('，', ',').split('
').filter(m => m.length != 0)

    let parsedStatus = infos.map(message => {
        let idx1 = message.indexOf(",")
        let idx2 = message.indexOf("--", idx1+1)
        let area = message.substr(0, idx1)
        let status = message.substr(idx1+1, idx2 - idx1 - 1)
        let date = message.substr(idx2 + 2)
        return {
            area: area,
            status: status.trim().capitalizeFirstLetter(),
            date: date
        }
    })

    return new SkyInfo({
        id: id,
        'status': parsedStatus
    })
}

/*
|--------------------------------------------------------------------------
| Utils
|--------------------------------------------------------------------------
*/
String.prototype.capitalizeFirstLetter = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

module.exports = sky<|endoftext|>


<commit_before>/*global defineSuite*/
defineSuite([
        'Scene/PerInstanceColorAppearance',
        'Core/ColorGeometryInstanceAttribute',
        'Core/GeometryInstance',
        'Core/Rectangle',
        'Core/RectangleGeometry',
        'Renderer/ClearCommand',
        'Scene/Appearance',
        'Scene/Primitive',
        'Specs/createContext',
        'Specs/createFrameState',
        'Specs/render'
    ], function(
        PerInstanceColorAppearance,
        ColorGeometryInstanceAttribute,
        GeometryInstance,
        Rectangle,
        RectangleGeometry,
        ClearCommand,
        Appearance,
        Primitive,
        createContext,
        createFrameState,
        render) {
    'use strict';

    var context;
    var frameState;
    var rectangle;
    var primitive;

    beforeAll(function() {
        context = createContext();

        rectangle = Rectangle.fromDegrees(-10.0, -10.0, 10.0, 10.0);
        primitive = new Primitive({
            geometryInstances : new GeometryInstance({
                geometry : new RectangleGeometry({
                    vertexFormat : PerInstanceColorAppearance.VERTEX_FORMAT,
                    rectangle : rectangle
                }),
                attributes : {
                    color : new ColorGeometryInstanceAttribute(1.0, 1.0, 0.0, 1.0)
                }
            }),
            asynchronous : false
        });
    });

    afterAll(function() {
        primitive = primitive && primitive.destroy();
        context.destroyForSpecs();
    });

    beforeEach(function() {
        frameState = createFrameState(context);
        frameState.camera.setView({ destination : rectangle });
        var us = context.uniformState;
        us.update(frameState);
    });

    it('constructor', function() {
        var a = new PerInstanceColorAppearance();

        expect(a.material).not.toBeDefined();
        expect(a.vertexShaderSource).toBeDefined();
        expect(a.fragmentShaderSource).toBeDefined();
        expect(a.renderState).toEqual(Appearance.getDefaultRenderState(true, false));
        expect(a.vertexFormat).toEqual(PerInstanceColorAppearance.VERTEX_FORMAT);
        expect(a.flat).toEqual(false);
        expect(a.faceForward).toEqual(true);
        expect(a.translucent).toEqual(true);
        expect(a.closed).toEqual(false);
    });

    it('renders', function() {
        primitive.appearance = new PerInstanceColorAppearance();

        ClearCommand.ALL.execute(context);
        expect(context.readPixels()).toEqual([0, 0, 0, 0]);

        render(frameState, primitive);
        expect(context.readPixels()).not.toEqual([0, 0, 0, 0]);
    });

    it('renders flat', function() {
        primitive.appearance = new PerInstanceColorAppearance({
            flat : true,
            translucent : false,
            closed : true
        });

        ClearCommand.ALL.execute(context);
        expect(context.readPixels()).toEqual([0, 0, 0, 0]);

        render(frameState, primitive);
        expect(context.readPixels()).not.toEqual([0, 0, 0, 0]);
    });

}, 'WebGL');
<commit_msg>Refactored PerInstanceColorAppearancSpec<commit_after>/*global defineSuite*/
defineSuite([
        'Scene/PerInstanceColorAppearance',
        'Core/ColorGeometryInstanceAttribute',
        'Core/GeometryInstance',
        'Core/Rectangle',
        'Core/RectangleGeometry',
        'Renderer/ClearCommand',
        'Scene/Appearance',
        'Scene/Primitive',
        'Specs/createScene'
    ], function(
        PerInstanceColorAppearance,
        ColorGeometryInstanceAttribute,
        GeometryInstance,
        Rectangle,
        RectangleGeometry,
        ClearCommand,
        Appearance,
        Primitive,
        createScene) {
    'use strict';

    var scene;
    var rectangle;
    var primitive;

    beforeAll(function() {
        scene = createScene();
        scene.primitives.destroyPrimitives = false;
        rectangle = Rectangle.fromDegrees(-10.0, -10.0, 10.0, 10.0);
        scene.camera.setView({ destination : rectangle });
    });

    afterAll(function() {
        scene.destroyForSpecs();
    });

    beforeEach(function() {
        primitive = new Primitive({
            geometryInstances : new GeometryInstance({
                geometry : new RectangleGeometry({
                    vertexFormat : PerInstanceColorAppearance.VERTEX_FORMAT,
                    rectangle : rectangle
                }),
                attributes : {
                    color : new ColorGeometryInstanceAttribute(1.0, 1.0, 0.0, 1.0)
                }
            }),
            asynchronous : false
        });
    });

    afterEach(function() {
        scene.primitives.removeAll();
        primitive = primitive && primitive.destroy();
    });

    it('constructor', function() {
        var a = new PerInstanceColorAppearance();

        expect(a.material).not.toBeDefined();
        expect(a.vertexShaderSource).toBeDefined();
        expect(a.fragmentShaderSource).toBeDefined();
        expect(a.renderState).toEqual(Appearance.getDefaultRenderState(true, false));
        expect(a.vertexFormat).toEqual(PerInstanceColorAppearance.VERTEX_FORMAT);
        expect(a.flat).toEqual(false);
        expect(a.faceForward).toEqual(true);
        expect(a.translucent).toEqual(true);
        expect(a.closed).toEqual(false);
    });

    it('renders', function() {
        primitive.appearance = new PerInstanceColorAppearance();

        expect(scene.renderForSpecs()).toEqual([0, 0, 0, 255]);

        scene.primitives.add(primitive);
        expect(scene.renderForSpecs()).not.toEqual([0, 0, 0, 255]);
    });

    it('renders flat', function() {
        primitive.appearance = new PerInstanceColorAppearance({
            flat : true,
            translucent : false,
            closed : true
        });

        expect(scene.renderForSpecs()).toEqual([0, 0, 0, 255]);

        scene.primitives.add(primitive);
        expect(scene.renderForSpecs()).not.toEqual([0, 0, 0, 255]);
    });

}, 'WebGL');
<|endoftext|>


<commit_before>"use strict";

module.exports = ReplaceSupers;

var traverse = require("../../traverse");
var t        = require("../../types");

/**
 * Description
 *
 * @param {Object} opts
 */

function ReplaceSupers(opts) {
  this.topLevelThisReference = null;
  this.methodNode            = opts.methodNode;
  this.className             = opts.className;
  this.superName             = opts.superName;
  this.isLoose               = opts.isLoose;
  this.scope                 = opts.scope;
  this.file                  = opts.file;
}

/**
 * Sets a super class value of the named property.
 *
 * @example
 *
 *   _set(Object.getPrototypeOf(CLASS.prototype), "METHOD", "VALUE", this)
 *
 * @param {Node} property
 * @param {boolean} isStatic
 * @param {boolean} isComputed
 *
 * @returns {Node}
 */
ReplaceSupers.prototype.setSuperProperty = function (property, value, isStatic, isComputed, thisExpression) {
  return t.callExpression(
    this.file.addHelper("set"),
    [
      t.callExpression(
        t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")),
        [
          isStatic ? this.className : t.memberExpression(this.className, t.identifier("prototype"))
        ]
      ),
      isComputed ? property : t.literal(property.name),
      value,
      thisExpression
    ]
  );
};

/**
 * Gets a node representing the super class value of the named property.
 *
 * @example
 *
 *   _get(Object.getPrototypeOf(CLASS.prototype), "METHOD", this)
 *
 * @param {Node} property
 * @param {boolean} isStatic
 * @param {boolean} isComputed
 *
 * @returns {Node}
 */

ReplaceSupers.prototype.superProperty = function (property, isStatic, isComputed, thisExpression) {
  return t.callExpression(
    this.file.addHelper("get"),
    [
      t.callExpression(
        t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")),
        [
          isStatic ? this.className : t.memberExpression(this.className, t.identifier("prototype"))
        ]
      ),
      isComputed ? property : t.literal(property.name),
      thisExpression
    ]
  );
};

/**
 * Description
 *
 * @param {Object} node
 * @param {Object} id
 * @param {Object} parent
 * @returns {Object}
 */

ReplaceSupers.prototype.looseSuperProperty = function (methodNode, id, parent) {
  var methodName = methodNode.key;
  var superName  = this.superName || t.identifier("Function");

  if (parent.property === id) {
    return;
  } else if (t.isCallExpression(parent, { callee: id })) {
    // super(); -> ClassName.prototype.MethodName.call(this);
    parent.arguments.unshift(t.thisExpression());

    if (methodName.name === "constructor") {
      // constructor() { super(); }
      return t.memberExpression(superName, t.identifier("call"));
    } else {
      id = superName;

      // foo() { super(); }
      if (!methodNode.static) {
        id = t.memberExpression(id, t.identifier("prototype"));
      }

      id = t.memberExpression(id, methodName, methodNode.computed);
      return t.memberExpression(id, t.identifier("call"));
    }
  } else if (t.isMemberExpression(parent) && !methodNode.static) {
    // super.test -> ClassName.prototype.test
    return t.memberExpression(superName, t.identifier("prototype"));
  } else {
    return superName;
  }
};

/**
 * Description
 */

ReplaceSupers.prototype.replace = function () {
  this.traverseLevel(this.methodNode.value, true);
};

var visitor = {
  enter: function (node, parent, scope, context, state) {
    var topLevel = state.topLevel;
    var self = state.self;

    if (t.isFunction(node) && !t.isArrowFunctionExpression(node)) {
      // we need to call traverseLevel again so we're context aware
      self.traverseLevel(node, false);
      return context.skip();
    }

    if (t.isProperty(node, { method: true }) || t.isMethodDefinition(node)) {
      // break on object methods
      return context.skip();
    }

    var getThisReference = topLevel ?
      // top level so `this` is the instance
      t.thisExpression :
      // not in the top level so we need to create a reference
      self.getThisReference;

    var callback = self.specHandle;
    if (self.isLoose) callback = self.looseHandle;
    return callback.call(self, getThisReference, node, parent);
  }
};

/**
 * Description
 *
 * @param {Object} node
 * @param {Boolean} topLevel
 */

ReplaceSupers.prototype.traverseLevel = function (node, topLevel) {
  var state = { self: this, topLevel: topLevel };
  traverse(node, visitor, this.scope, state);
};

/**
 * Description
 */

ReplaceSupers.prototype.getThisReference = function () {
  if (this.topLevelThisReference) {
    return this.topLevelThisReference;
  } else {
    var ref = this.topLevelThisReference = this.file.generateUidIdentifier("this");
    this.methodNode.value.body.body.unshift(t.variableDeclaration("var", [
      t.variableDeclarator(this.topLevelThisReference, t.thisExpression())
    ]));
    return ref;
  }
};

/**
 * Description
 *
 * @param {Function} getThisReference
 * @param {Object} node
 * @param {Object} parent
 */

ReplaceSupers.prototype.looseHandle = function (getThisReference, node, parent) {
  if (t.isIdentifier(node, { name: "super" })) {
    return this.looseSuperProperty(this.methodNode, node, parent);
  } else if (t.isCallExpression(node)) {
    var callee = node.callee;
    if (!t.isMemberExpression(callee)) return;
    if (callee.object.name !== "super") return;

    // super.test(); -> ClassName.prototype.MethodName.call(this);
    t.appendToMemberExpression(callee, t.identifier("call"));
    node.arguments.unshift(getThisReference());
  }
};

/**
 * Description
 *
 * @param {Function} getThisReference
 * @param {Object} node
 * @param {Object} parent
 */

ReplaceSupers.prototype.specHandle = function (getThisReference, node, parent) {
  var methodNode = this.methodNode;
  var property;
  var computed;
  var args;
  var thisReference;

  if (t.isIdentifier(node, { name: "super" })) {
    if (!(t.isMemberExpression(parent) && !parent.computed && parent.property === node)) {
      throw this.file.errorWithNode(node, "illegal use of bare super");
    }
  } else if (t.isCallExpression(node)) {
    var callee = node.callee;
    if (t.isIdentifier(callee, { name: "super" })) {
      // super(); -> _get(Object.getPrototypeOf(ClassName), "MethodName", this).call(this);
      property = methodNode.key;
      computed = methodNode.computed;
      args = node.arguments;

      // bare `super` call is illegal inside non-constructors
      //  - https://esdiscuss.org/topic/super-call-in-methods
      //  - https://twitter.com/wycats/status/544553184396836864
      if (methodNode.key.name !== "constructor") {
        var methodName = methodNode.key.name || "METHOD_NAME";
        throw this.file.errorWithNode(node, "Direct super call is illegal in non-constructor, use super." + methodName + "() instead");
      }
    } else {
      if (!t.isMemberExpression(callee)) return;
      if (callee.object.name !== "super") return;

      // super.test(); -> _get(Object.getPrototypeOf(ClassName.prototype), "test", this).call(this);
      property = callee.property;
      computed = callee.computed;
      args = node.arguments;
    }
  } else if (t.isMemberExpression(node)) {
    if (!t.isIdentifier(node.object, { name: "super" })) return;

    // super.name; -> _get(Object.getPrototypeOf(ClassName.prototype), "name", this);
    property = node.property;
    computed = node.computed;
  } else if (t.isAssignmentExpression(node)) {
    if (!t.isIdentifier(node.left.object, { name: "super" })) return;
    if (methodNode.kind !== "set") return;

    thisReference = getThisReference();
    // super.name = "val"; -> _set(Object.getPrototypeOf(ClassName.prototype), "name", this);
    return this.setSuperProperty(node.left.property, node.right, methodNode.static, node.left.computed, thisReference);
  }

  if (!property) return;

  thisReference = getThisReference();
  var superProperty = this.superProperty(property, methodNode.static, computed, thisReference);
  if (args) {
    if (args.length === 1 && t.isSpreadElement(args[0])) {
      // super(...arguments);
      return t.callExpression(
        t.memberExpression(superProperty, t.identifier("apply")),
        [thisReference, args[0].argument]
      );
    } else {
      return t.callExpression(
        t.memberExpression(superProperty, t.identifier("call")),
        [thisReference].concat(args)
      );
    }
  } else {
    return superProperty;
  }
};
<commit_msg>fix incorrect getThisReference bind - fixes #688<commit_after>"use strict";

module.exports = ReplaceSupers;

var traverse = require("../../traverse");
var t        = require("../../types");

/**
 * Description
 *
 * @param {Object} opts
 */

function ReplaceSupers(opts) {
  this.topLevelThisReference = null;
  this.methodNode            = opts.methodNode;
  this.className             = opts.className;
  this.superName             = opts.superName;
  this.isLoose               = opts.isLoose;
  this.scope                 = opts.scope;
  this.file                  = opts.file;
}

/**
 * Sets a super class value of the named property.
 *
 * @example
 *
 *   _set(Object.getPrototypeOf(CLASS.prototype), "METHOD", "VALUE", this)
 *
 * @param {Node} property
 * @param {boolean} isStatic
 * @param {boolean} isComputed
 *
 * @returns {Node}
 */
ReplaceSupers.prototype.setSuperProperty = function (property, value, isStatic, isComputed, thisExpression) {
  return t.callExpression(
    this.file.addHelper("set"),
    [
      t.callExpression(
        t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")),
        [
          isStatic ? this.className : t.memberExpression(this.className, t.identifier("prototype"))
        ]
      ),
      isComputed ? property : t.literal(property.name),
      value,
      thisExpression
    ]
  );
};

/**
 * Gets a node representing the super class value of the named property.
 *
 * @example
 *
 *   _get(Object.getPrototypeOf(CLASS.prototype), "METHOD", this)
 *
 * @param {Node} property
 * @param {boolean} isStatic
 * @param {boolean} isComputed
 *
 * @returns {Node}
 */

ReplaceSupers.prototype.superProperty = function (property, isStatic, isComputed, thisExpression) {
  return t.callExpression(
    this.file.addHelper("get"),
    [
      t.callExpression(
        t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")),
        [
          isStatic ? this.className : t.memberExpression(this.className, t.identifier("prototype"))
        ]
      ),
      isComputed ? property : t.literal(property.name),
      thisExpression
    ]
  );
};

/**
 * Description
 *
 * @param {Object} node
 * @param {Object} id
 * @param {Object} parent
 * @returns {Object}
 */

ReplaceSupers.prototype.looseSuperProperty = function (methodNode, id, parent) {
  var methodName = methodNode.key;
  var superName  = this.superName || t.identifier("Function");

  if (parent.property === id) {
    return;
  } else if (t.isCallExpression(parent, { callee: id })) {
    // super(); -> ClassName.prototype.MethodName.call(this);
    parent.arguments.unshift(t.thisExpression());

    if (methodName.name === "constructor") {
      // constructor() { super(); }
      return t.memberExpression(superName, t.identifier("call"));
    } else {
      id = superName;

      // foo() { super(); }
      if (!methodNode.static) {
        id = t.memberExpression(id, t.identifier("prototype"));
      }

      id = t.memberExpression(id, methodName, methodNode.computed);
      return t.memberExpression(id, t.identifier("call"));
    }
  } else if (t.isMemberExpression(parent) && !methodNode.static) {
    // super.test -> ClassName.prototype.test
    return t.memberExpression(superName, t.identifier("prototype"));
  } else {
    return superName;
  }
};

/**
 * Description
 */

ReplaceSupers.prototype.replace = function () {
  this.traverseLevel(this.methodNode.value, true);
};

var visitor = {
  enter: function (node, parent, scope, context, state) {
    var topLevel = state.topLevel;
    var self = state.self;

    if (t.isFunction(node) && !t.isArrowFunctionExpression(node)) {
      // we need to call traverseLevel again so we're context aware
      self.traverseLevel(node, false);
      return context.skip();
    }

    if (t.isProperty(node, { method: true }) || t.isMethodDefinition(node)) {
      // break on object methods
      return context.skip();
    }

    var getThisReference = topLevel ?
      // top level so `this` is the instance
      t.thisExpression :
      // not in the top level so we need to create a reference
      self.getThisReference.bind(self);

    var callback = self.specHandle;
    if (self.isLoose) callback = self.looseHandle;
    return callback.call(self, getThisReference, node, parent);
  }
};

/**
 * Description
 *
 * @param {Object} node
 * @param {Boolean} topLevel
 */

ReplaceSupers.prototype.traverseLevel = function (node, topLevel) {
  var state = { self: this, topLevel: topLevel };
  traverse(node, visitor, this.scope, state);
};

/**
 * Description
 */

ReplaceSupers.prototype.getThisReference = function () {
  if (this.topLevelThisReference) {
    return this.topLevelThisReference;
  } else {
    var ref = this.topLevelThisReference = this.file.generateUidIdentifier("this");
    this.methodNode.value.body.body.unshift(t.variableDeclaration("var", [
      t.variableDeclarator(this.topLevelThisReference, t.thisExpression())
    ]));
    return ref;
  }
};

/**
 * Description
 *
 * @param {Function} getThisReference
 * @param {Object} node
 * @param {Object} parent
 */

ReplaceSupers.prototype.looseHandle = function (getThisReference, node, parent) {
  if (t.isIdentifier(node, { name: "super" })) {
    return this.looseSuperProperty(this.methodNode, node, parent);
  } else if (t.isCallExpression(node)) {
    var callee = node.callee;
    if (!t.isMemberExpression(callee)) return;
    if (callee.object.name !== "super") return;

    // super.test(); -> ClassName.prototype.MethodName.call(this);
    t.appendToMemberExpression(callee, t.identifier("call"));
    node.arguments.unshift(getThisReference());
  }
};

/**
 * Description
 *
 * @param {Function} getThisReference
 * @param {Object} node
 * @param {Object} parent
 */

ReplaceSupers.prototype.specHandle = function (getThisReference, node, parent) {
  var methodNode = this.methodNode;
  var property;
  var computed;
  var args;
  var thisReference;

  if (t.isIdentifier(node, { name: "super" })) {
    if (!(t.isMemberExpression(parent) && !parent.computed && parent.property === node)) {
      throw this.file.errorWithNode(node, "illegal use of bare super");
    }
  } else if (t.isCallExpression(node)) {
    var callee = node.callee;
    if (t.isIdentifier(callee, { name: "super" })) {
      // super(); -> _get(Object.getPrototypeOf(ClassName), "MethodName", this).call(this);
      property = methodNode.key;
      computed = methodNode.computed;
      args = node.arguments;

      // bare `super` call is illegal inside non-constructors
      //  - https://esdiscuss.org/topic/super-call-in-methods
      //  - https://twitter.com/wycats/status/544553184396836864
      if (methodNode.key.name !== "constructor") {
        var methodName = methodNode.key.name || "METHOD_NAME";
        throw this.file.errorWithNode(node, "Direct super call is illegal in non-constructor, use super." + methodName + "() instead");
      }
    } else {
      if (!t.isMemberExpression(callee)) return;
      if (callee.object.name !== "super") return;

      // super.test(); -> _get(Object.getPrototypeOf(ClassName.prototype), "test", this).call(this);
      property = callee.property;
      computed = callee.computed;
      args = node.arguments;
    }
  } else if (t.isMemberExpression(node)) {
    if (!t.isIdentifier(node.object, { name: "super" })) return;

    // super.name; -> _get(Object.getPrototypeOf(ClassName.prototype), "name", this);
    property = node.property;
    computed = node.computed;
  } else if (t.isAssignmentExpression(node)) {
    if (!t.isIdentifier(node.left.object, { name: "super" })) return;
    if (methodNode.kind !== "set") return;

    thisReference = getThisReference();
    // super.name = "val"; -> _set(Object.getPrototypeOf(ClassName.prototype), "name", this);
    return this.setSuperProperty(node.left.property, node.right, methodNode.static, node.left.computed, thisReference);
  }

  if (!property) return;

  thisReference = getThisReference();
  var superProperty = this.superProperty(property, methodNode.static, computed, thisReference);
  if (args) {
    if (args.length === 1 && t.isSpreadElement(args[0])) {
      // super(...arguments);
      return t.callExpression(
        t.memberExpression(superProperty, t.identifier("apply")),
        [thisReference, args[0].argument]
      );
    } else {
      return t.callExpression(
        t.memberExpression(superProperty, t.identifier("call")),
        [thisReference].concat(args)
      );
    }
  } else {
    return superProperty;
  }
};
<|endoftext|>