<commit_before>function OFraMP(containerID, settings) {
  this.__init(containerID, settings);
}

OFraMP.prototype = {
  container: undefined,
  settings: undefined,
  mv: undefined,
  settingsUI: undefined,

  atomDetails: undefined,
  relatedFragments: undefined,

  popup: undefined,
  popupTitle: undefined,
  popupContent: undefined,

  enterMoleculeButton: undefined,
  findFragmentsButton: undefined,

  relatedFragmentViewers: undefined,
  activeFragment: undefined,

  uiInitializedEvent: new Event('uiinitialized'),
  moleculeEnteredEvent: new Event('moleculeentered'),

  __init: function(containerID, settings) {
    this.container = document.getElementById(containerID);
    this.settings = $ext.merge($ext.copy(DEFAULT_SETTINGS), settings);
    this.__initUI();
    this.showInsertMoleculePopup();
  },

  __initUI: function() {
    var lb = document.createElement('div');
    lb.id = "leftbar";
    lb.className = "sidebar border_box";
    lb.style.visibility = "hidden";
    this.container.appendChild(lb);
    this.__initAtomDetails(lb);

    var rb = document.createElement('div');
    rb.id = "rightbar";
    rb.className = "sidebar border_box";
    rb.style.visibility = "hidden";
    this.container.appendChild(rb);
    this.__initRelatedFragments(rb);

    this.popup = document.createElement('div');
    this.popup.id = "popup";
    this.popup.className = "border_box";
    this.popup.style.visibility = "hidden";
    this.container.appendChild(this.popup);
    this.__initPopup(this.popup);

    var emb = document.createElement('button');
    emb.id = "enter_molecule";
    emb.className = "border_box";
    emb.style.visibility = "hidden";
    this.container.appendChild(emb);
    this.__initEMB(emb);
    this.enterMoleculeButton = emb;

    var ffb = document.createElement('button');
    ffb.id = "find_fragments";
    ffb.className = "border_box";
    ffb.style.visibility = "hidden";
    this.container.appendChild(ffb);
    this.__initFFB(ffb);
    this.findFragmentsButton = ffb;

    var cc = document.createElement('div');
    cc.id = "canvas_container";
    this.container.appendChild(cc);
    this.__initMainViewer(cc);

    if(!$ext.onBrokenIE()) {
      this.__initSettingsUI();
    }

    this.container.dispatchEvent(this.uiInitializedEvent);
  },

  __initAtomDetails: function(container) {
    var ad = document.createElement('div');
    ad.id = "atom_details";
    container.appendChild(ad);
    this.atomDetails = ad;
  },

  __initRelatedFragments: function(container) {
    var rf = document.createElement('div');
    rf.id = "related_fragments";
    container.appendChild(rf);
    this.relatedFragments = rf;
  },

  __initPopup: function(container) {
    this.popupTitle = document.createElement('div');
    this.popupTitle.id = "popup_title";

    this.popupContent = document.createElement('div');
    this.popupContent.id = "popup_content";

    container.appendChild(this.popupTitle);
    container.appendChild(document.createElement('hr'));
    container.appendChild(this.popupContent);
  },

  __initEMB: function(elem) {
    elem.appendChild(document.createTextNode("Submit a new molecule"));
    var _this = this;
    $ext.dom.onMouseClick(elem, function() {
      _this.showInsertMoleculePopup();
    }, 0);
  },

  __initFFB: function(elem) {
    elem.appendChild(document.createTextNode("Find matching fragments"));
    elem.disabled = "disabled";
    var _this = this;
    $ext.dom.onMouseClick(elem, function() {
      _this.mv.getMatchingFragments();
    }, 0);
  },

  __initMainViewer: function(container) {
    this.mv = new MoleculeViewer(this, "main_molecule", "canvas_container");
  },

  __initSettingsUI: function() {
    this.settingsUI = new dat.GUI({
      name: 'OFraMP Settings',
      savable: true
    });

    var _this = this;
    var settingsObj = $ext.extend($ext.copy(this.settings), {
      getMV: function() {
        return _this.mv;
      }
    });
    this.settingsUI.addAll(settingsObj, this.settings, $ext.object
        .extrapolate(SETTINGS_OPTIONS));
  },

  __initMP: function() {
    this.enterMoleculeButton.style.visibility = "visible";
    this.findFragmentsButton.style.visibility = "visible";
  },

  showPopup: function(title, content) {
    $ext.dom.clear(this.popupTitle);
    $ext.dom.clear(this.popupContent);
    this.popupTitle.appendChild(document.createTextNode(title));
    this.popupContent.appendChild(content);
    this.popup.style.visibility = 'visible';
  },

  hidePopup: function() {
    this.popup.style.visibility = "hidden";
  },

  showInsertMoleculePopup: function() {
    var _this = this;

    var title = "Please enter a molecule data string";

    var content = document.createElement('div');

    var ta = document.createElement('textarea');
    ta.placeholder = "Insert SMILES / InChI string here";
    content.appendChild(ta);

    var cbs = document.createElement('div');
    cbs.className = 'controls';
    content.appendChild(cbs);

    var sb = document.createElement('button');
    sb.appendChild(document.createTextNode("Submit"));
    sb.onclick = function() {
      _this.mv.showMolecule(ta.value);
      if(!_this.mv.molecule) {
        _this.mv.setupInteraction();
        _this.__initMP();
      }
      _this.container.dispatchEvent(_this.moleculeEnteredEvent);
      _this.hidePopup();
    }
    cbs.appendChild(sb);

    var rb = document.createElement('button');
    rb.appendChild(document.createTextNode("Random molecule"));
    rb.onclick = function() {
      ta.value = $ext.array.randomElement(PREDEFINED_MOLECULES);
    }
    cbs.appendChild(rb);

    var cb = document.createElement('button');
    cb.style.float = 'right';
    cb.appendChild(document.createTextNode("Cancel"));
    cb.onclick = function() {
      if(!_this.mv.molecule) {
        _this.mv.showMolecule($ext.array.randomElement(PREDEFINED_MOLECULES));
        _this.mv.setupInteraction();
        _this.__initMP();
        _this.container.dispatchEvent(_this.moleculeEnteredEvent);
      }
      _this.hidePopup();
    }
    cbs.appendChild(cb);

    this.showPopup(title, content);
  },

  showSelectionDetails: function(selection) {
    function addTableRow(table, label, value) {
      var row = document.createElement('tr');
      var head = document.createElement('th');
      head.appendChild(document.createTextNode(label));
      var data = document.createElement('td');
      data.appendChild(document.createTextNode(value));
      row.appendChild(head);
      row.appendChild(data);
      table.appendChild(row);
    }

    $ext.dom.clear(this.atomDetails);
    if(selection.length === 1) {
      var atom = selection[0];
    }

    var ts = document.createElement('span');
    ts.className = "title";
    if(atom) {
      var tn = document.createTextNode("Atom details");
    } else {
      var tn = document.createTextNode("Selection details");
    }
    ts.appendChild(tn);
    this.atomDetails.appendChild(ts);

    var c = document.createElement('canvas');
    c.width = 228;
    c.height = 130;
    var ctx = c.getContext('2d');

    var sl = new AtomList(this.mv.molecule, selection);
    var center = sl.getCenterPoint();
    var size = sl.getSize();

    // Increase selection size when the ratio is off
    var r = size.w / size.h;
    if(r > c.width / c.height) {
      size.h *= r * c.height / c.width;
    } else {
      size.w *= (1 / r) * c.width / c.height;
    }

    var dx = Math.max(c.width, size.w) / 2;
    var dy = Math.max(c.height, size.h) / 2;
    var wf = c.width / (2 * dx);
    var hf = c.height / (2 * dy);
    var f = wf < hf ? wf : hf;

    var id = this.mv.ctx.getImageData(center.x - dx, center.y - dy, 2 * dx,
        2 * dy);

    var tc = document.createElement('canvas');
    tc.width = id.width;
    tc.height = id.height;
    tc.getContext("2d").putImageData(id, 0, 0);

    ctx.scale(f, f);
    ctx.drawImage(tc, 0, 0);
    this.atomDetails.appendChild(c);

    var dt = document.createElement('table');

    if(atom) {
      addTableRow(dt, "ID", atom.id);
      addTableRow(dt, "Element", atom.element);
      addTableRow(dt, "Charge", atom.charge || "unknown");
    } else {
      // Get the unparameterised atoms
      var uas = $ext.array.filter(selection, function(atom) {
        return atom.charge === undefined;
      });
      // Get the charged of all atoms
      var cs = $ext.array.map(selection, function(atom) {
        return atom.charge || 0;
      });

      addTableRow(dt, "Selection count", selection.length);
      addTableRow(dt, "Unparameterised", uas.length);
      addTableRow(dt, "Parameterised", selection.length - uas.length);
      addTableRow(dt, "Total charge", $ext.array.sum(cs));
    }

    this.atomDetails.appendChild(dt);

    var ffb = document.createElement('button');
    ffb.className = "border_box";
    ffb.appendChild(document.createTextNode("Find matching fragments"));
    this.atomDetails.appendChild(ffb);
    var _this = this;
    $ext.dom.onMouseClick(ffb, function() {
      _this.mv.getMatchingFragments();
    }, 0);

    if(atom) {
      var ecb = document.createElement('button');
      ecb.className = "border_box";
      ecb.disabled = "disabled";
      ecb.appendChild(document.createTextNode("Edit charge"));
      this.atomDetails.appendChild(ecb);
      $ext.dom.onMouseClick(ecb, function() {
        alert("TODO =)");
      }, 0);
    }

    this.atomDetails.parentElement.style.visibility = "visible";
    this.atomDetails.parentElement.style.opacity = "1.0";
  },

  hideSelectionDetails: function() {
    this.atomDetails.parentElement.style.visibility = "hidden";
    this.atomDetails.parentElement.style.opacity = "0.0";
  },

  showRelatedFragments: function(fragments) {
    $ext.dom.clear(this.relatedFragments);
    this.relatedFragmentViewers = new Array();

    var ts = document.createElement('span');
    ts.className = "title";
    ts.appendChild(document.createTextNode("Found " + fragments.length
        + " fragments"));
    this.relatedFragments.appendChild(ts);

    $ext.each(fragments, function(fragment, i) {
      var fc = document.createElement('div');
      fc.id = "fc_" + i;
      fc.className = "fragment";
      this.relatedFragments.appendChild(fc);

      var ab = document.createElement('button');
      ab.className = "border_box";
      ab.disabled = "disabled";
      ab.appendChild(document.createTextNode("Select fragment"));
      $ext.dom.onMouseClick(ab, function() {
        console.log("TODO");
      }, 0);
      fc.appendChild(ab);

      var _this = this;
      var mv = new MoleculeViewer(this, "fragment_" + i, fc.id, 228, 130);
      mv.showMolecule(fragment, function(molecule) {
        molecule.bestFit();

        $ext.dom.onMouseClick(this.canvas, function() {
          ab.disabled = "";

          if(_this.activeFragment && _this.activeFragment !== molecule.mv) {
            // Disable the currently active fragment's button
            _this.activeFragment.canvas.parentElement
                .getElementsByClassName("border_box")[0].disabled = "disabled";
          }
          _this.activeFragment = molecule.mv;

          // TODO
          var m = _this.mv.molecule.find(molecule.dataStr.split(''))[0];
          $ext.each(m, function(atom, i) {
            atom.previewCharge = molecule.atoms.get(i + 1).charge;
          });
          _this.redraw();
        }, 0);
      });
      this.relatedFragmentViewers.push(mv);
    }, this);

    this.relatedFragments.parentElement.style.visibility = "visible";
    this.relatedFragments.parentElement.style.opacity = "1.0";
  },

  hideRelatedFragments: function() {
    this.relatedFragments.parentElement.style.visibility = "hidden";
    this.relatedFragments.parentElement.style.opacity = "0.0";
  },

  /*
   * Set the size of the main molecule viewer to width x height.
   */
  setMVSize: function(width, height) {
    this.mv.setCanvasSize(width, height)
  },

  /*
   * Move the molecule dx in the x direction and dy on the y axis.
   */
  move: function(dx, dy) {
    if(!this.mv || !this.mv.molecule) {
      return;
    }

    this.mv.move(dx, dy);
  },

  /*
   * Zoom on the center of the molecule with a factor f.
   */
  zoom: function(f) {
    if(!this.mv || !this.mv.molecule) {
      return;
    }

    this.mv.zoom(f);
  },

  /*
   * Zoom on the position (x, y) with a factor f.
   */
  zoomOn: function(x, y, f) {
    if(!this.mv || !this.mv.molecule) {
      return;
    }

    this.mv.zoomOn(x, y, f);
  },

  /*
   * Fit the molecule on the canvas.
   */
  bestFit: function() {
    if(!this.mv || !this.mv.molecule) {
      return;
    }

    this.mv.molecule.bestFit();
    this.redraw();
  },

  /*
   * Show the molecule in minimum size on the canvas.
   */
  minimize: function() {
    if(!this.mv || !this.mv.molecule) {
      return;
    }

    this.mv.molecule.minimize();
    this.redraw();
  },

  /*
   * Show the molecule in ideal size on the canvas.
   */
  idealize: function() {
    if(!this.mv || !this.mv.molecule) {
      return;
    }

    this.mv.molecule.idealize();
    this.redraw();
  },

  /*
   * Show the molecule in maximum size on the canvas.
   */
  maximize: function() {
    if(!this.mv || !this.mv.molecule) {
      return;
    }

    this.mv.molecule.maximize();
    this.redraw();
  },

  /*
   * Reset the atom positions to those obtained with OAPoC.
   */
  resetPositions: function() {
    if(!this.mv || !this.mv.molecule) {
      return;
    }

    this.mv.molecule.resetPositions();
    this.redraw();
  },

  /*
   * Get the molecule canvas data as a Base64 string.
   */
  getMVDataURI: function(format) {
    return this.mv.canvas.toDataURL(format);
  },

  /*
   * Redraw the molecule canvas.
   */
  redraw: function() {
    if(!this.mv) {
      return;
    }

    this.mv.redraw();
  }
};
<commit_msg>Charges can now also be applied.<commit_after>function OFraMP(containerID, settings) {
  this.__init(containerID, settings);
}

OFraMP.prototype = {
  container: undefined,
  settings: undefined,
  mv: undefined,
  settingsUI: undefined,

  atomDetails: undefined,
  relatedFragments: undefined,

  popup: undefined,
  popupTitle: undefined,
  popupContent: undefined,

  enterMoleculeButton: undefined,
  findFragmentsButton: undefined,

  relatedFragmentViewers: undefined,
  activeFragment: undefined,

  uiInitializedEvent: new Event('uiinitialized'),
  moleculeEnteredEvent: new Event('moleculeentered'),

  __init: function(containerID, settings) {
    this.container = document.getElementById(containerID);
    this.settings = $ext.merge($ext.copy(DEFAULT_SETTINGS), settings);
    this.__initUI();
    this.showInsertMoleculePopup();
  },

  __initUI: function() {
    var lb = document.createElement('div');
    lb.id = "leftbar";
    lb.className = "sidebar border_box";
    lb.style.visibility = "hidden";
    this.container.appendChild(lb);
    this.__initAtomDetails(lb);

    var rb = document.createElement('div');
    rb.id = "rightbar";
    rb.className = "sidebar border_box";
    rb.style.visibility = "hidden";
    this.container.appendChild(rb);
    this.__initRelatedFragments(rb);

    this.popup = document.createElement('div');
    this.popup.id = "popup";
    this.popup.className = "border_box";
    this.popup.style.visibility = "hidden";
    this.container.appendChild(this.popup);
    this.__initPopup(this.popup);

    var emb = document.createElement('button');
    emb.id = "enter_molecule";
    emb.className = "border_box";
    emb.style.visibility = "hidden";
    this.container.appendChild(emb);
    this.__initEMB(emb);
    this.enterMoleculeButton = emb;

    var ffb = document.createElement('button');
    ffb.id = "find_fragments";
    ffb.className = "border_box";
    ffb.style.visibility = "hidden";
    this.container.appendChild(ffb);
    this.__initFFB(ffb);
    this.findFragmentsButton = ffb;

    var cc = document.createElement('div');
    cc.id = "canvas_container";
    this.container.appendChild(cc);
    this.__initMainViewer(cc);

    if(!$ext.onBrokenIE()) {
      this.__initSettingsUI();
    }

    this.container.dispatchEvent(this.uiInitializedEvent);
  },

  __initAtomDetails: function(container) {
    var ad = document.createElement('div');
    ad.id = "atom_details";
    container.appendChild(ad);
    this.atomDetails = ad;
  },

  __initRelatedFragments: function(container) {
    var rf = document.createElement('div');
    rf.id = "related_fragments";
    container.appendChild(rf);
    this.relatedFragments = rf;
  },

  __initPopup: function(container) {
    this.popupTitle = document.createElement('div');
    this.popupTitle.id = "popup_title";

    this.popupContent = document.createElement('div');
    this.popupContent.id = "popup_content";

    container.appendChild(this.popupTitle);
    container.appendChild(document.createElement('hr'));
    container.appendChild(this.popupContent);
  },

  __initEMB: function(elem) {
    elem.appendChild(document.createTextNode("Submit a new molecule"));
    var _this = this;
    $ext.dom.onMouseClick(elem, function() {
      _this.showInsertMoleculePopup();
    }, 0);
  },

  __initFFB: function(elem) {
    elem.appendChild(document.createTextNode("Find matching fragments"));
    elem.disabled = "disabled";
    var _this = this;
    $ext.dom.onMouseClick(elem, function() {
      _this.mv.getMatchingFragments();
    }, 0);
  },

  __initMainViewer: function(container) {
    this.mv = new MoleculeViewer(this, "main_molecule", "canvas_container");
  },

  __initSettingsUI: function() {
    this.settingsUI = new dat.GUI({
      name: 'OFraMP Settings',
      savable: true
    });

    var _this = this;
    var settingsObj = $ext.extend($ext.copy(this.settings), {
      getMV: function() {
        return _this.mv;
      }
    });
    this.settingsUI.addAll(settingsObj, this.settings, $ext.object
        .extrapolate(SETTINGS_OPTIONS));
  },

  __initMP: function() {
    this.enterMoleculeButton.style.visibility = "visible";
    this.findFragmentsButton.style.visibility = "visible";
  },

  showPopup: function(title, content) {
    $ext.dom.clear(this.popupTitle);
    $ext.dom.clear(this.popupContent);
    this.popupTitle.appendChild(document.createTextNode(title));
    this.popupContent.appendChild(content);
    this.popup.style.visibility = 'visible';
  },

  hidePopup: function() {
    this.popup.style.visibility = "hidden";
  },

  showInsertMoleculePopup: function() {
    var _this = this;

    var title = "Please enter a molecule data string";

    var content = document.createElement('div');

    var ta = document.createElement('textarea');
    ta.placeholder = "Insert SMILES / InChI string here";
    content.appendChild(ta);

    var cbs = document.createElement('div');
    cbs.className = 'controls';
    content.appendChild(cbs);

    var sb = document.createElement('button');
    sb.appendChild(document.createTextNode("Submit"));
    sb.onclick = function() {
      _this.mv.showMolecule(ta.value);
      if(!_this.mv.molecule) {
        _this.mv.setupInteraction();
        _this.__initMP();
      }
      _this.container.dispatchEvent(_this.moleculeEnteredEvent);
      _this.hidePopup();
    }
    cbs.appendChild(sb);

    var rb = document.createElement('button');
    rb.appendChild(document.createTextNode("Random molecule"));
    rb.onclick = function() {
      ta.value = $ext.array.randomElement(PREDEFINED_MOLECULES);
    }
    cbs.appendChild(rb);

    var cb = document.createElement('button');
    cb.style.float = 'right';
    cb.appendChild(document.createTextNode("Cancel"));
    cb.onclick = function() {
      if(!_this.mv.molecule) {
        _this.mv.showMolecule($ext.array.randomElement(PREDEFINED_MOLECULES));
        _this.mv.setupInteraction();
        _this.__initMP();
        _this.container.dispatchEvent(_this.moleculeEnteredEvent);
      }
      _this.hidePopup();
    }
    cbs.appendChild(cb);

    this.showPopup(title, content);
  },

  showSelectionDetails: function(selection) {
    function addTableRow(table, label, value) {
      var row = document.createElement('tr');
      var head = document.createElement('th');
      head.appendChild(document.createTextNode(label));
      var data = document.createElement('td');
      data.appendChild(document.createTextNode(value));
      row.appendChild(head);
      row.appendChild(data);
      table.appendChild(row);
    }

    $ext.dom.clear(this.atomDetails);
    if(selection.length === 1) {
      var atom = selection[0];
    }

    var ts = document.createElement('span');
    ts.className = "title";
    if(atom) {
      var tn = document.createTextNode("Atom details");
    } else {
      var tn = document.createTextNode("Selection details");
    }
    ts.appendChild(tn);
    this.atomDetails.appendChild(ts);

    var c = document.createElement('canvas');
    c.width = 228;
    c.height = 130;
    var ctx = c.getContext('2d');

    var sl = new AtomList(this.mv.molecule, selection);
    var center = sl.getCenterPoint();
    var size = sl.getSize();

    // Increase selection size when the ratio is off
    var r = size.w / size.h;
    if(r > c.width / c.height) {
      size.h *= r * c.height / c.width;
    } else {
      size.w *= (1 / r) * c.width / c.height;
    }

    var dx = Math.max(c.width, size.w) / 2;
    var dy = Math.max(c.height, size.h) / 2;
    var wf = c.width / (2 * dx);
    var hf = c.height / (2 * dy);
    var f = wf < hf ? wf : hf;

    var id = this.mv.ctx.getImageData(center.x - dx, center.y - dy, 2 * dx,
        2 * dy);

    var tc = document.createElement('canvas');
    tc.width = id.width;
    tc.height = id.height;
    tc.getContext("2d").putImageData(id, 0, 0);

    ctx.scale(f, f);
    ctx.drawImage(tc, 0, 0);
    this.atomDetails.appendChild(c);

    var dt = document.createElement('table');

    if(atom) {
      addTableRow(dt, "ID", atom.id);
      addTableRow(dt, "Element", atom.element);
      addTableRow(dt, "Charge", atom.charge || "unknown");
    } else {
      // Get the unparameterised atoms
      var uas = $ext.array.filter(selection, function(atom) {
        return atom.charge === undefined;
      });
      // Get the charged of all atoms
      var cs = $ext.array.map(selection, function(atom) {
        return atom.charge || 0;
      });

      addTableRow(dt, "Selection count", selection.length);
      addTableRow(dt, "Unparameterised", uas.length);
      addTableRow(dt, "Parameterised", selection.length - uas.length);
      addTableRow(dt, "Total charge", $ext.array.sum(cs));
    }

    this.atomDetails.appendChild(dt);

    var ffb = document.createElement('button');
    ffb.className = "border_box";
    ffb.appendChild(document.createTextNode("Find matching fragments"));
    this.atomDetails.appendChild(ffb);
    var _this = this;
    $ext.dom.onMouseClick(ffb, function() {
      _this.mv.getMatchingFragments();
    }, 0);

    if(atom) {
      var ecb = document.createElement('button');
      ecb.className = "border_box";
      ecb.disabled = "disabled";
      ecb.appendChild(document.createTextNode("Edit charge"));
      this.atomDetails.appendChild(ecb);
      $ext.dom.onMouseClick(ecb, function() {
        alert("TODO =)");
      }, 0);
    }

    this.atomDetails.parentElement.style.visibility = "visible";
    this.atomDetails.parentElement.style.opacity = "1.0";
  },

  hideSelectionDetails: function() {
    this.atomDetails.parentElement.style.visibility = "hidden";
    this.atomDetails.parentElement.style.opacity = "0.0";
  },

  showRelatedFragments: function(fragments) {
    $ext.dom.clear(this.relatedFragments);
    this.relatedFragmentViewers = new Array();

    var ts = document.createElement('span');
    ts.className = "title";
    ts.appendChild(document.createTextNode("Found " + fragments.length
        + " fragments"));
    this.relatedFragments.appendChild(ts);

    $ext.each(fragments, function(fragment, i) {
      var fc = document.createElement('div');
      fc.id = "fc_" + i;
      fc.className = "fragment";
      this.relatedFragments.appendChild(fc);

      var ab = document.createElement('button');
      ab.className = "border_box";
      ab.disabled = "disabled";
      ab.appendChild(document.createTextNode("Select fragment"));
      fc.appendChild(ab);

      var _this = this;
      var mv = new MoleculeViewer(this, "fragment_" + i, fc.id, 228, 130);
      mv.showMolecule(fragment, function(molecule) {
        molecule.bestFit();

        $ext.dom.onMouseClick(this.canvas, function() {
          ab.disabled = "";

          if(_this.activeFragment && _this.activeFragment !== molecule.mv) {
            // Disable the currently active fragment's button
            _this.activeFragment.canvas.parentElement
                .getElementsByClassName("border_box")[0].disabled = "disabled";
          }
          _this.activeFragment = molecule.mv;

          // TODO
          var m = _this.mv.molecule.find(molecule.dataStr.split(''))[0];
          $ext.each(m, function(atom, i) {
            atom.previewCharge = molecule.atoms.get(i + 1).charge;
          });
          _this.redraw();
        }, 0);
      });
      this.relatedFragmentViewers.push(mv);

      $ext.dom.onMouseClick(ab, function() {
        // TODO
        var m = _this.mv.molecule.find(mv.molecule.dataStr.split(''))[0];
        $ext.each(m, function(atom, i) {
          atom.charge = mv.molecule.atoms.get(i + 1).charge;
        });
        _this.mv.molecule.setSelected([]);
        _this.mv.molecule.dehighlight();
        _this.hideSelectionDetails();
        _this.hideRelatedFragments();
        _this.redraw();
      }, 0);
    }, this);

    this.relatedFragments.parentElement.style.visibility = "visible";
    this.relatedFragments.parentElement.style.opacity = "1.0";
  },

  hideRelatedFragments: function() {
    this.relatedFragments.parentElement.style.visibility = "hidden";
    this.relatedFragments.parentElement.style.opacity = "0.0";
  },

  /*
   * Set the size of the main molecule viewer to width x height.
   */
  setMVSize: function(width, height) {
    this.mv.setCanvasSize(width, height)
  },

  /*
   * Move the molecule dx in the x direction and dy on the y axis.
   */
  move: function(dx, dy) {
    if(!this.mv || !this.mv.molecule) {
      return;
    }

    this.mv.move(dx, dy);
  },

  /*
   * Zoom on the center of the molecule with a factor f.
   */
  zoom: function(f) {
    if(!this.mv || !this.mv.molecule) {
      return;
    }

    this.mv.zoom(f);
  },

  /*
   * Zoom on the position (x, y) with a factor f.
   */
  zoomOn: function(x, y, f) {
    if(!this.mv || !this.mv.molecule) {
      return;
    }

    this.mv.zoomOn(x, y, f);
  },

  /*
   * Fit the molecule on the canvas.
   */
  bestFit: function() {
    if(!this.mv || !this.mv.molecule) {
      return;
    }

    this.mv.molecule.bestFit();
    this.redraw();
  },

  /*
   * Show the molecule in minimum size on the canvas.
   */
  minimize: function() {
    if(!this.mv || !this.mv.molecule) {
      return;
    }

    this.mv.molecule.minimize();
    this.redraw();
  },

  /*
   * Show the molecule in ideal size on the canvas.
   */
  idealize: function() {
    if(!this.mv || !this.mv.molecule) {
      return;
    }

    this.mv.molecule.idealize();
    this.redraw();
  },

  /*
   * Show the molecule in maximum size on the canvas.
   */
  maximize: function() {
    if(!this.mv || !this.mv.molecule) {
      return;
    }

    this.mv.molecule.maximize();
    this.redraw();
  },

  /*
   * Reset the atom positions to those obtained with OAPoC.
   */
  resetPositions: function() {
    if(!this.mv || !this.mv.molecule) {
      return;
    }

    this.mv.molecule.resetPositions();
    this.redraw();
  },

  /*
   * Get the molecule canvas data as a Base64 string.
   */
  getMVDataURI: function(format) {
    return this.mv.canvas.toDataURL(format);
  },

  /*
   * Redraw the molecule canvas.
   */
  redraw: function() {
    if(!this.mv) {
      return;
    }

    this.mv.redraw();
  }
};
<|endoftext|>


<commit_before>/* --------------------------------------- *
* Guerrilla UI                             *
* @author: Garrett Haptonstall (FearDread) *
* @module: GUI Core                        *
* ---------------------------------------- */
var GUI;

/**
 * @todo - add two way / single data binding logic feature
 * @todo - add default config that will change behavior of GUI core
 * @tood - load modules via dependency injection, built framework should only contain core objects
 * @todo - allow async dependency loading to keep framework light - loads modules / plugins only when called via dependency array
 **/

// GUI Core
GUI = (function($) {

    // Make sure we have jQuery
    if (typeof $ === 'undefined' || $ === null) {
        throw new Error('Guerrilla UI requires jQuery library.');
    }

    // GUI Constructor
    function GUI() {

        // default config
        this.config = {
            name: 'Guerrilla UI',
            /* Logging verbosity */
            logLevel: 0,
            /* Single page app or Multiple page site */
            mode: 'multi',
            /* GUI library version */
            version: '0.4.7',
            jquery: true,
            animations: false
        };

        // ability to pass optional config object
        this.configure = function(options) {

            if (options !== null && utils.isObj(options)) {
                // set custom config options
                this.config = utils.merge(this.config, options);

                // set logging verbosity
                this.debug.level = this.config.logLevel || 0;
            }
        };

        // private objects & arrays for tracking
        this._modules = {};
        this._plugins = [];
        this._instances = {};
        this._sandboxes = {};
        this._running = {};
        this._imports = [];

        // add broker to core object
        this._broker = new Broker(this);
        this.Broker = Broker;

        this.attach = function(imports) {
            console.log('dynamic asyn module loading.');
            console.log('imports = ', imports);
        };
    }

    // console log wrapper
    GUI.prototype.debug = {
        level: 0,
        history: [],
        timeout: 5000,

        /**
         * Adds a warning message to the console.
         *
         * @param {String} out the message
        **/
        warn: function(out) {
            if (this.level < 2) {

                [].unshift.call(arguments, 'WARN:');

                if (typeof window !== undefined && window.console && console.warn) {

                    this._logger("warn", [].slice.call(arguments));

                } else if (window.console && console.log) {

                    this._logger("log", [].slice.call(arguments));

                } else if (window.opera && window.opera.postError) {

                    window.opera.postError("WARNING: " + out);

                }
            }
        },

        /**
         * Adds a message to the console.
         *
         * @param {String} out the message
        **/
        log: function(out) {
            if (this.level < 1) {
                if (window.console && console.log) {

                    [].unshift.call(arguments, 'Debug:');

                    this._logger("log", [].slice.call(arguments));

                } else if (window.opera && window.opera.postError) {

                    window.opera.postError("DEBUG: " + out);

                }
            }
        },

        _logger: function(type, arr) {

            this.history.push({type:arr});

            if (console.log.apply) {

                console[type].apply(console, arr);

            } else {

                console[type](arr);
            }
        },

        _stackTrace: function() {

            this.log(this.history);
        }
    };

    /* Public Methods */
    /******************/

    /**
     * Create new GUI module
     *
     * @param id {string} - module identifier
     * @param creator {function}  logic to execute inside module namespace
     * @param options {object} - optional object of extra parameters that will be passed to load()
     * @return this {object}
    **/
    GUI.prototype.create = function(id, creator, options) {
        var error;

        if (!options || options === null) {
          options = {};
        }

        error = utils.isType("string", id, "module ID") || utils.isType("function", creator, "creator") || utils.isType("object", options, "option parameter");

        if (error) {
          this.debug.warn("could not register module '" + id + "': " + error);
          return this;
        }

        if (id in this._modules) {
          this.debug.log("module " + id + " was already registered");
          return this;
        }

        this._modules[id] = {
          id: id,
          creator: creator,
          options: options
        };

        return this;
    };

    /**
     * Starts module with new sandbox instance
     *
     * @param moduleId {string} - module name or identifier
     * @param opt {object} - optional options object
     * @param cb {function} - callback function
     * @return boot {function} - call boot method and create new sandbox instance
    **/
    GUI.prototype.start = function(moduleId, opt, cb) {
        var error, id, initInst;

        if (!opt || opt === null) {
            opt = {};
        }
        if (!cb || cb === null) {
            cb = function() {};
        }

        if (arguments.length === 0) {
            return this._startAll();
        }

        if (moduleId instanceof Array) {
            return this._startAll(moduleId, opt);
        }

        if (typeof moduleId === "function") {
            return this._startAll(null, moduleId);
        }

        if (typeof opt === "function") {
            cb = opt;
            opt = {};
        }

        error = utils.isType("string", moduleId, "module ID") || utils.isType("object", opt, "second parameter") || (!this._modules[moduleId] ? "module doesn't exist" : void 0);

        if (error) {
            return this._fail(error, cb);
        }

        id = opt.instanceId || moduleId;

        if (this._running[id] === true) {
            return this._fail(new Error("module was already started"), cb);
        }

        initInst = (function(_this) {
            return function(err, instance, opt) {
                if (err) {
                    return _this._fail(err, cb);
                }

                try {
                    if (utils.hasArgs(instance.load, 2)) {
                        return instance.load(opt, function(err) {

                            if (!err) {
                                _this._running[id] = true;
                            }

                            return cb(err);
                        });
                    } else {

                        instance.load(opt);
                        _this._running[id] = true;

                        return cb();
                    }
                } catch (_error) {
                    e = _error;
                    return _this._fail(e, cb);
                }
            };
        })(this);

        return this.boot((function(_this) {

            return function(err) {

                if (err) {
                    return _this._fail(err, cb);
                }

                return _this._createInstance(moduleId, opt, initInst);
            };
        })(this));
    };

    /**
     * Loads plugin to Sandbox or Core classes
     *
     * @param plugin {function} - method with plugin logic
     * @param opt {object} - optional options object to be accessed in plugin
     * @return this {object}
    **/
    GUI.prototype.use = function(plugin, opt) {
        var i, len, p;

        if (utils.isArr(plugin)) {

            for (i = 0, len = plugin.length; i < len; i++) {
                p = plugin[i];

                switch (typeof p) {
                    case "function":
                        this.use(p);
                        break;

                    case "object":
                        this.use(p.plugin, p.options);
                }
            }

      } else {
          // must be function
          if (!utils.isFunc(plugin)) {
              return this;
          }

          // add to _plugins array
          this._plugins.push({
              creator: plugin,
              options: opt
          });
      }

      return this;
    };

    /**
     * Stops all running instances
     *
     * @param id {string} - module identifier
     * @param callback {function} - optional callback to run when module stopped
     * @return this {object}
    **/
    GUI.prototype.stop = function(id, callback) {
        var instance;

        if (cb === null) {
            cb = function() {};
        }

        if (arguments.length === 0 || typeof id === "function") {
            utils.run.all((function() {
                var results = [], x;

                for (x in this._instances) {
                    results.push(x);
                }

                return results;

            }).call(this), ((function(_this) {
                return function() {
                    return _this.stop.apply(_this, arguments);
                };
            })(this)), id, true);

        } else if (instance === this._instances[id]) {

            // remove instance from instances cache
            delete this._instances[id];

            // disable any events registered by module
            this._broker.off(instance);

            // run unload method in stopped modules
            this._runSandboxPlugins('unload', this._sandboxes[id], (function(_this) {
                return function(err) {
                    if (utils.hasArgs(instance.unload)) {

                        return instance.unload(function(err2) {
                            delete _this._running[id];

                            return cb(err || err2);
                        });
                    } else {

                        if (typeof instance.unload === "function") {
                            instance.unload();
                        }

                        delete _this._running[id];

                        return cb(err);
                    }
                };
            })(this));
        }

        return this;
    };

    /**
     * Register jQuery plugins to $ nameSpace
     *
     * @param plugin {object} - plugin object with all logic
     * @param module {string} - identifier for jQuery plugin
     * @return {function} - initialized jQuery plugin
    **/
    GUI.prototype.plugin = function(plugin, module) {
        var _this = this;

        if (plugin.fn && utils.isFunc(plugin.fn)) {

            $.fn[module.toLowerCase()] = function(options) {

                return new plugin.fn(this, options);
            };
        } else {

            GUI.log('Error :: Missing ' + plugin + ' fn() method.');
        }
    };

    /**
     * Load single or all available core plugins
     *
     * @param cb {function} - callback to execute after plugins loaded
     * @return this {object} - return GUI object with tasks array
    **/
    GUI.prototype.boot = function(cb) {
        var core, p, tasks;

        core = this;

        tasks = (function() {
            var j, len, ref, results;

            ref = this._plugins;
            results = [];

            for (j = 0, len = ref.length; j < len; j++) {
                p = ref[j];

                if (p.booted !== true) {
                    results.push((function(p) {

                        if (utils.hasArgs(p.creator, 3)) {
                            return function(next) {
                                var plugin;

                                return p.creator(core, p.options, function(err) {
                                    if (!err) {
                                        p.booted = true;
                                        p.plugin = plugin;
                                    }

                                    return next();
                                });
                            };
                        } else {
                            return function(next) {
                                p.plugin = p.creator(core, p.options);
                                p.booted = true;

                                return next();
                            };
                        }
                    })(p));
                }
            }

            return results;

        }).call(this);

        utils.run.series(tasks, cb, true);

        return this;
    };

    /* Private Methods */
    /*******************/

    /**
      * Called when starting module fails
      *
      * @param ev {object} - message or error object
      * @param cb {function} - callback method to run with error string / object
      * @return this {object}
    **/
    GUI.prototype._fail = function(ev, cb) {
        this.debug.warn(ev);

        cb(new Error("could not start module: " + ev.message));

        return this;
    };

    /**
      * Called when starting module fails
      *
      * @param mods {function} - method with array of all modules to start
      * @param cb {function} - callback method to run once modules started
      * @return this {object}
    **/
    GUI.prototype._startAll = function(mods, cb) {
        var done, startAction;

        // start all stored modules
        if (!mods || mods === null) {
            mods = (function() {
                var results = [], m;

                for (m in this._modules) {
                    results.push(m);
                }

                return results;
            }).call(this);
        }

        // self executing action
        startAction = (function(_this) {
            return function(m, next) {
                return _this.start(m, _this._modules[m].options, next);
            };
        })(this);

        // optional done callback for async loading
        done = function(err) {
            var e, i, j, k, len, mdls, modErrors, x;

            if ((err !== null ? err.length : void 0) > 0) {
                modErrors = {};

                for (i = j = 0, len = err.length; j < len; i = ++j) {
                    x = err[i];

                    if (x !== null) {
                        modErrors[mods[i]] = x;
                    }
                }

                // store all available modules errors
                mdls = (function() {
                    var results = [], k;

                    for (k in modErrors) {
                        results.push("'" + k + "'");
                    }

                    return results;
                })();

                e = new Error("errors occurred in the following modules: " + mdls);
                e.moduleErrors = modErrors;
            }

            return typeof cb === "function" ? cb(e) : void 0;
        };

        // run all modules in parallel formation
        utils.run.all(mods, startAction, done, true);

        return this;
    };

    /**
      * Create new sandbox instance and attach to module
      *
      * @param moduleId {string} - the module to create sandbox instance for
      * @param o {object} - options object
      * @param cb {function} - callback method to run once instance created
      * @return {function} - run sandboxed instances
    **/
    GUI.prototype._createInstance = function(moduleId, o, cb) {
        var Sandbox, iOpts, id, j, key, len, module, obj, opt, ref, sb, val;

        opt = o.options;
        id = o.instanceId || moduleId;

        module = this._modules[moduleId];

        if (this._instances[id]) {
            return cb(this._instances[id]);
        }

        iOpts = {};
        ref = [module.options, opt];

        for (j = 0, len = ref.length; j < len; j++) {
            obj = ref[j];

            if (obj) {
                for (key in obj) {
                    val = obj[key];

                    if (!iOpts[key] || iOpts[key] === null) {
                        iOpts[key] = val;
                    }
                }
            }
        }

        // create new API Sandbox
        sb = new API().create(this, id, iOpts, moduleId);

        // add config object if avail
        if (this.config && this.config !== null) {
          sb.config = this.config;
        }

        // run sandboxed instance load method
        return this._runSandboxPlugins('load', sb, (function(_this) {
            return function(err) {
                var instance;

                instance = new module.creator(sb);

                if (typeof instance.load !== "function") {

                    // determine if module is jQuery plugin
                    if (instance.fn && typeof instance.fn === 'function') {
                        return _this.plugin(instance, id);
                    }

                    return cb(new Error("module has no 'load' or 'fn' method"));
                }

                // store instance and sandbox
                _this._instances[id] = instance;
                _this._sandboxes[id] = sb;

                return cb(null, instance, iOpts);
            };
        })(this));
    };

    /**
      * Sets up needed tasks for module initializations
      *
      * @param ev {string} - check module for load / unload methods
      * @param sb {object} - the sandbox instance
      * @param cb {function} - callback method to run once instances initialized
      * @return {function} - utils.run.seris
    **/
    GUI.prototype._runSandboxPlugins = function(ev, sb, cb) {
        var p, tasks;

        tasks = (function() {
            var j, len, ref, ref1, results;

            ref = this._plugins;
            results = [];

            for (j = 0, len = ref.length; j < len; j++) {
                p = ref[j];

                if (typeof ((ref1 = p.plugin) !== null ? ref1[ev] : void 0) === "function") {
                    results.push((function(p) {
                        var fn;
                        fn = p.plugin[ev];

                        return function(next) {
                            if (utils.hasArgs(fn, 3)) {
                                return fn(sb, p.options, next);
                            } else {
                                fn(sb, p.options);
                                return next();
                            }
                        };
                    })(p));
                }
            }

            return results;

        }).call(this);

        return utils.run.series(tasks, cb, true);
    };

    return GUI;

})(jQuery);
<commit_msg>--add injector and binder classes to core object for applying in core module logic.<commit_after>/* --------------------------------------- *
* Guerrilla UI                             *
* @author: Garrett Haptonstall (FearDread) *
* @module: GUI Core                        *
* ---------------------------------------- */
var GUI;

/**
 * @todo - add two way / single data binding logic feature
 * @todo - add default config that will change behavior of GUI core
 * @tood - load modules via dependency injection, built framework should only contain core objects
 * @todo - allow async dependency loading to keep framework light - loads modules / plugins only when called via dependency array
 **/

// GUI Core
GUI = (function ($) {

    // Make sure we have jQuery
    if (typeof $ === 'undefined' || $ === null) {
        throw new Error('Guerrilla UI requires jQuery library.');
    }

    // GUI Constructor
    function GUI() {

        // default config
        this.config = {
            name: 'Guerrilla UI',
            /* Logging verbosity */
            logLevel: 0,
            /* Single page app or Multiple page site */
            mode: 'multi',
            /* GUI library version */
            version: '0.4.7',
            jquery: true,
            animations: false
        };

        this.injector = Injector;
        this.binder = new Binder();

        // ability to pass optional config object
        this.configure = function (options) {

            if (options !== null && utils.isObj(options)) {
                // set custom config options
                this.config = utils.merge(this.config, options);

                // set logging verbosity
                this.debug.level = this.config.logLevel || 0;
            }
        };

        // private objects & arrays for tracking
        this._modules = {};
        this._plugins = [];
        this._instances = {};
        this._sandboxes = {};
        this._running = {};
        this._dependencies = {};

        // add broker to core object
        this._broker = new Broker(this);
        this.Broker = Broker;

        this.attach = function(imports) {
            console.log('dynamic asyn module loading.');
            console.log('imports = ', imports);
        };
    }

    // console log wrapper
    GUI.prototype.debug = {
        level: 0,
        history: [],
        timeout: 5000,

        /**
         * Adds a warning message to the console.
         *
         * @param {String} out the message
        **/
        warn: function(out) {
            if (this.level < 2) {

                [].unshift.call(arguments, 'WARN:');

                if (typeof window !== undefined && window.console && console.warn) {

                    this._logger("warn", [].slice.call(arguments));

                } else if (window.console && console.log) {

                    this._logger("log", [].slice.call(arguments));

                } else if (window.opera && window.opera.postError) {

                    window.opera.postError("WARNING: " + out);

                }
            }
        },

        /**
         * Adds a message to the console.
         *
         * @param {String} out the message
        **/
        log: function(out) {
            if (this.level < 1) {
                if (window.console && console.log) {

                    [].unshift.call(arguments, 'Debug:');

                    this._logger("log", [].slice.call(arguments));

                } else if (window.opera && window.opera.postError) {

                    window.opera.postError("DEBUG: " + out);

                }
            }
        },

        _logger: function(type, arr) {

            this.history.push({type:arr});

            if (console.log.apply) {

                console[type].apply(console, arr);

            } else {

                console[type](arr);
            }
        },

        _stackTrace: function() {

            this.log(this.history);
        }
    };

    /* Public Methods */
    /******************/

    /**
     * Create new GUI module
     *
     * @param id {string} - module identifier
     * @param creator {function}  logic to execute inside module namespace
     * @param options {object} - optional object of extra parameters that will be passed to load()
     * @return this {object}
    **/
    GUI.prototype.create = function(id, creator, options) {
        var error;

        if (!options || options === null) {
          options = {};
        }

        error = utils.isType("string", id, "module ID") || utils.isType("function", creator, "creator") || utils.isType("object", options, "option parameter");

        if (error) {
          this.debug.warn("could not register module '" + id + "': " + error);
          return this;
        }

        if (id in this._modules) {
          this.debug.log("module " + id + " was already registered");
          return this;
        }

        this._modules[id] = {
          id: id,
          creator: creator,
          options: options
        };

        return this;
    };

    /**
     * Starts module with new sandbox instance
     *
     * @param moduleId {string} - module name or identifier
     * @param opt {object} - optional options object
     * @param cb {function} - callback function
     * @return boot {function} - call boot method and create new sandbox instance
    **/
    GUI.prototype.start = function(moduleId, opt, cb) {
        var error, id, initInst;

        if (!opt || opt === null) {
            opt = {};
        }
        if (!cb || cb === null) {
            cb = function() {};
        }

        if (arguments.length === 0) {
            return this._startAll();
        }

        if (moduleId instanceof Array) {
            return this._startAll(moduleId, opt);
        }

        if (typeof moduleId === "function") {
            return this._startAll(null, moduleId);
        }

        if (typeof opt === "function") {
            cb = opt;
            opt = {};
        }

        error = utils.isType("string", moduleId, "module ID") || utils.isType("object", opt, "second parameter") || (!this._modules[moduleId] ? "module doesn't exist" : void 0);

        if (error) {
            return this._fail(error, cb);
        }

        id = opt.instanceId || moduleId;

        if (this._running[id] === true) {
            return this._fail(new Error("module was already started"), cb);
        }

        initInst = (function($this) {
            return function(err, instance, opt) {
                if (err) {
                    return $this._fail(err, cb);
                }

                try {
                    if (utils.hasArgs(instance.load, 2)) {
                        return instance.load(opt, function(err) {

                            if (!err) {
                                $this._running[id] = true;
                            }

                            return cb(err);
                        });
                    } else {

                        instance.load(opt);
                        $this._running[id] = true;

                        return cb();
                    }
                } catch (_error) {
                    e = _error;

                    return $this._fail(e, cb);
                }
            };
        })(this);

        return this.boot((function ($this) {

            return function (err) {

                if (err) {
                    return $this._fail(err, cb);
                }

                return $this._createInstance(moduleId, opt, initInst);
            };
        })(this));
    };

    /**
     * Loads plugin to Sandbox or Core classes
     *
     * @param plugin {function} - method with plugin logic
     * @param opt {object} - optional options object to be accessed in plugin
     * @return this {object}
    **/
    GUI.prototype.use = function(plugin, opt) {
        var i, len, p;

        if (utils.isArr(plugin)) {

            for (i = 0, len = plugin.length; i < len; i++) {
                p = plugin[i];

                switch (typeof p) {
                    case "function":
                        this.use(p);
                        break;

                    case "object":
                        this.use(p.plugin, p.options);
                }
            }

      } else {
          // must be function
          if (!utils.isFunc(plugin)) {
              return this;
          }

          // add to _plugins array
          this._plugins.push({
              creator: plugin,
              options: opt
          });
      }

      return this;
    };

    /**
     * Stops all running instances
     *
     * @param id {string} - module identifier
     * @param callback {function} - optional callback to run when module stopped
     * @return this {object}
    **/
    GUI.prototype.stop = function(id, callback) {
        var instance;

        if (cb === null) {
            cb = function() {};
        }

        if (arguments.length === 0 || typeof id === "function") {
            utils.run.all((function() {
                var results = [], x;

                for (x in this._instances) {
                    results.push(x);
                }

                return results;

            }).call(this), ((function($this) {
                return function() {
                    return $this.stop.apply($this, arguments);
                };
            })(this)), id, true);

        } else if (instance === this._instances[id]) {

            // remove instance from instances cache
            delete this._instances[id];

            // disable any events registered by module
            this._broker.off(instance);

            // run unload method in stopped modules
            this._runSandboxPlugins('unload', this._sandboxes[id], (function($this) {
                return function(err) {
                    if (utils.hasArgs(instance.unload)) {

                        return instance.unload(function(err2) {
                            delete $this._running[id];

                            return cb(err || err2);
                        });
                    } else {

                        if (typeof instance.unload === "function") {
                            instance.unload();
                        }

                        delete $this._running[id];

                        return cb(err);
                    }
                };
            })(this));
        }

        return this;
    };

    /**
     * Register jQuery plugins to $ nameSpace
     *
     * @param plugin {object} - plugin object with all logic
     * @param module {string} - identifier for jQuery plugin
     * @return {function} - initialized jQuery plugin
    **/
    GUI.prototype.plugin = function(plugin, module) {
        var $this = this;

        if (plugin.fn && utils.isFunc(plugin.fn)) {

            $.fn[module.toLowerCase()] = function(options) {

                return new plugin.fn(this, options);
            };
        } else {

            GUI.log('Error :: Missing ' + plugin + ' fn() method.');
        }
    };

    /**
     * Load single or all available core plugins
     *
     * @param cb {function} - callback to execute after plugins loaded
     * @return this {object} - return GUI object with tasks array
    **/
    GUI.prototype.boot = function(cb) {
        var core, p, tasks;

        core = this;

        tasks = (function() {
            var j, len, ref, results;

            ref = this._plugins;
            results = [];

            for (j = 0, len = ref.length; j < len; j++) {
                p = ref[j];

                if (p.booted !== true) {
                    results.push((function(p) {

                        if (utils.hasArgs(p.creator, 3)) {
                            return function(next) {
                                var plugin;

                                return p.creator(core, p.options, function(err) {
                                    if (!err) {
                                        p.booted = true;
                                        p.plugin = plugin;
                                    }

                                    return next();
                                });
                            };
                        } else {
                            return function(next) {
                                p.plugin = p.creator(core, p.options);
                                p.booted = true;

                                return next();
                            };
                        }
                    })(p));
                }
            }

            return results;

        }).call(this);

        utils.run.series(tasks, cb, true);

        return this;
    };

    /* Private Methods */
    /*******************/

    /**
      * Called when starting module fails
      *
      * @param ev {object} - message or error object
      * @param cb {function} - callback method to run with error string / object
      * @return this {object}
    **/
    GUI.prototype._fail = function(ev, cb) {
        this.debug.warn(ev);

        cb(new Error("could not start module: " + ev.message));

        return this;
    };

    /**
      * Called when starting module fails
      *
      * @param mods {function} - method with array of all modules to start
      * @param cb {function} - callback method to run once modules started
      * @return this {object}
    **/
    GUI.prototype._startAll = function(mods, cb) {
        var done, startAction;

        // start all stored modules
        if (!mods || mods === null) {
            mods = (function() {
                var results = [], m;

                for (m in this._modules) {
                    results.push(m);
                }

                return results;
            }).call(this);
        }

        // self executing action
        startAction = (function($this) {
            return function(m, next) {
                return $this.start(m, $this._modules[m].options, next);
            };
        })(this);

        // optional done callback for async loading
        done = function(err) {
            var e, i, j, k, len, mdls, modErrors, x;

            if ((err !== null ? err.length : void 0) > 0) {
                modErrors = {};

                for (i = j = 0, len = err.length; j < len; i = ++j) {
                    x = err[i];

                    if (x !== null) {
                        modErrors[mods[i]] = x;
                    }
                }

                // store all available modules errors
                mdls = (function() {
                    var results = [], k;

                    for (k in modErrors) {
                        results.push("'" + k + "'");
                    }

                    return results;
                })();

                e = new Error("errors occurred in the following modules: " + mdls);
                e.moduleErrors = modErrors;
            }

            return typeof cb === "function" ? cb(e) : void 0;
        };

        // run all modules in parallel formation
        utils.run.all(mods, startAction, done, true);

        return this;
    };

    /**
      * Create new sandbox instance and attach to module
      *
      * @param moduleId {string} - the module to create sandbox instance for
      * @param o {object} - options object
      * @param cb {function} - callback method to run once instance created
      * @return {function} - run sandboxed instances
    **/
    GUI.prototype._createInstance = function(moduleId, o, cb) {
        var Sandbox, iOpts, id, j, key, len, module, obj, opt, ref, sb, val;

        opt = o.options;
        id = o.instanceId || moduleId;

        module = this._modules[moduleId];

        if (this._instances[id]) {
            return cb(this._instances[id]);
        }

        iOpts = {};
        ref = [module.options, opt];

        for (j = 0, len = ref.length; j < len; j++) {
            obj = ref[j];

            if (obj) {
                for (key in obj) {
                    val = obj[key];

                    if (!iOpts[key] || iOpts[key] === null) {
                        iOpts[key] = val;
                    }
                }
            }
        }

        // create new API Sandbox
        sb = new API().create(this, id, iOpts, moduleId);

        // add config object if avail
        if (this.config && this.config !== null) {
          sb.config = this.config;
        }

        // run sandboxed instance load method
        return this._runSandboxPlugins('load', sb, (function($this) {
            return function(err) {
                var instance;

                instance = new module.creator(sb);

                if (typeof instance.load !== "function") {

                    // determine if module is jQuery plugin
                    if (instance.fn && typeof instance.fn === 'function') {
                        return $this.plugin(instance, id);
                    }

                    return cb(new Error("module has no 'load' or 'fn' method"));
                }

                // store instance and sandbox
                $this._instances[id] = instance;
                $this._sandboxes[id] = sb;

                return cb(null, instance, iOpts);
            };
        })(this));
    };

    /**
      * Sets up needed tasks for module initializations
      *
      * @param ev {string} - check module for load / unload methods
      * @param sb {object} - the sandbox instance
      * @param cb {function} - callback method to run once instances initialized
      * @return {function} - utils.run.seris
    **/
    GUI.prototype._runSandboxPlugins = function(ev, sb, cb) {
        var p, tasks;

        tasks = (function() {
            var j, len, ref, ref1, results;

            ref = this._plugins;
            results = [];

            for (j = 0, len = ref.length; j < len; j++) {
                p = ref[j];

                if (typeof ((ref1 = p.plugin) !== null ? ref1[ev] : void 0) === "function") {
                    results.push((function(p) {
                        var fn;
                        fn = p.plugin[ev];

                        return function(next) {
                            if (utils.hasArgs(fn, 3)) {
                                return fn(sb, p.options, next);
                            } else {
                                fn(sb, p.options);
                                return next();
                            }
                        };
                    })(p));
                }
            }

            return results;

        }).call(this);

        return utils.run.series(tasks, cb, true);
    };

    return GUI;

})(jQuery);
<|endoftext|>


<commit_before>/**
 * @fileoverview Description of file, its uses and information
 * about its dependencies.
 */

'use strict';

/**
 *
 * @type {*|exports|module.exports}
 */
var cloud;

/**
 *
 * @type {*|exports|module.exports}
 */
var meta;

/**
 *
 * @type {*|exports|module.exports}
 */
var setting;

/**
 *
 * @type {*|exports|module.exports}
 */
var utils;

/**
 *
 * @type {*|exports|module.exports}
 */
var backboneEvents;

/**
 *
 * @type {*|exports|module.exports}
 */
var urlparser = require('./../../../browser/modules/urlparser');

/**
 *
 * @type {array}
 */
var urlVars = urlparser.urlVars;

/**
 * @type {string}
 */
var db = urlparser.db;

var layers;

var onEachFeature = [];

var pointToLayer = [];

var onLoad = [];

var onSelect = [];

var onMouseOver = [];

var cm = [];

var styles = [];

var store = [];

var automatic = true;

/**
 *
 * @type {{set: module.exports.set, init: module.exports.init}}
 */
module.exports = {

    set: function (o) {
        cloud = o.cloud;
        setting = o.setting;
        utils = o.utils;
        meta = o.meta;
        layers = o.layers;
        backboneEvents = o.backboneEvents;
        return this;
    },

    init: function () {

        var me = this;

        utils.createMainTab("vectorlayers", "Vektor lag");

        $('#main-tabs a[href="#vectorlayer-content"]').tab('show');

        if (!urlVars.px && !urlVars.py) {

            $(document).arrive('.refresh-vector-layer', function () {

                $(this).on("click", function (e) {

                    $("#info-modal-top.slide-left").animate({
                        left: "0"
                    }, 500);

                    var id = ($(this).parent().prev().children("input").data('gc2-id-vec'));

                    $("#vectorlayer-table-div").empty().append('
');

                    var table = gc2table.init({
                        el: "#vectorlayer-table",
                        geocloud2: cloud.get(),
                        store: store[id],
                        cm: cm[id],
                        autoUpdate: false,
                        autoPan: false,
                        openPopUp: false,
                        setViewOnSelect: false,
                        setSelectedStyle: false,
                        responsive: true,
                        callCustomOnload: true,
                        height: 400,
                        onSelect: onSelect[id],
                        onMouseOver: onMouseOver[id],
                        locale: window._vidiLocale.replace("_", "-"),
                        ns: "#vectorlayer-table-div"
                    });

                    table.loadDataInTable();

                    e.stopPropagation();

                });

            });

            $(document).arrive('[data-gc2-id-vec]', function () {

                $(this).on("change", function (e) {

                    me.switchLayer(($(this).data('gc2-id-vec')), $(this).context.checked);

                    e.stopPropagation();

                });
            });
        }

        backboneEvents.get().on("ready:meta", function () {

            if (automatic) {
                me.createLayerTree();
            }

        })
    },

    createLayerTree: function () {

        let base64name, arr, groups = [], metaData, i, l, displayInfo, subOrderHeader, icon, dataAttr, styleFn;

        metaData = meta.getMetaData();

        for (i = 0; i < metaData.data.length; ++i) {
            groups[i] = metaData.data[i].layergroup;
        }

        arr = array_unique(groups.reverse());

        metaData.data.reverse();

        for (i = 0; i < arr.length; ++i) {

            if (arr[i] && arr[i] !== "[Ungrouped]") {
                l = [];
                base64name = Base64.encode(arr[i]).replace(/=/g, "");
                $("#vectorlayers").append('

0 /
 ' + arr[i] + '

');
                $("#vectorgroup-" + base64name).append('

');

                for (let u = 0; u < metaData.data.length; ++u) {
                    if (metaData.data[u].layergroup == arr[i]) {

                        // if (JSON.parse(metaData.data[u].meta) !== null && typeof JSON.parse(metaData.data[u].meta).vectorstyle !== "undefined") {
                        //     try {
                        //         styleFn = eval("(" + JSON.parse(metaData.data[u].meta).vectorstyle + ")");
                        //     } catch (e) {
                        //         styleFn = function () {
                        //         };
                        //     }
                        // }

                        var text = (metaData.data[u].f_table_title === null || metaData.data[u].f_table_title === "") ? metaData.data[u].f_table_name : metaData.data[u].f_table_title,
                            id;

                        try {
                            icon = " ";
                        } catch (e) {
                            icon = "";
                        }

                        // If meta.usetiles is true, when add layers as tiles instead of vectors
                        if (JSON.parse(metaData.data[u].meta) !== null && typeof JSON.parse(metaData.data[u].meta).usetiles !== "undefined" && JSON.parse(metaData.data[u].meta).usetiles === true) {

                            id = metaData.data[u].f_table_schema + "." + metaData.data[u].f_table_name;
                            dataAttr = "data-gc2-id";

                        } else {

                            id = "v:" + metaData.data[u].f_table_schema + "." + metaData.data[u].f_table_name;
                            dataAttr = "data-gc2-id-vec";

                            if (!metaData.data[u].baselayer) {
                                store[id] = new geocloud.sqlStore({
                                    jsonp: false,
                                    method: "POST",
                                    host: "",
                                    db: db,
                                    uri: "/api/sql",
                                    clickable: false,
                                    id: id,
                                    name: id,
                                    lifetime: 0,
                                    styleMap: styles[id],
                                    sql: "SELECT * FROM " + metaData.data[u].f_table_schema + "." + metaData.data[u].f_table_name + " LIMIT 500",
                                    onLoad: function (l) {

                                        if (l === undefined) {
                                            return
                                        }

                                        var me = l;
                                        try {
                                            $('*[data-gc2-id-vec="' + me.id + '"]').parent().siblings().children().removeClass("fa-spin")
                                        } catch (e) {
                                        }
                                        layers.decrementCountLoading(me.id);
                                        backboneEvents.get().trigger("doneLoading:layers", me.id);
                                        if (onLoad[me.id] !== undefined) {
                                            onLoad[me.id](l);
                                        }
                                    },

                                    onEachFeature: onEachFeature[id],

                                    pointToLayer: pointToLayer[id]

                                });
                            }
                        }

                        if (!metaData.data[u].baselayer) {

                            displayInfo = (metaData.data[u].meta !== null && $.parseJSON(metaData.data[u].meta) !== null && typeof $.parseJSON(metaData.data[u].meta).meta_desc !== "undefined") ? "inline" : "none";

                            subOrderHeader = (typeof metaData.data[u].extra !== "undefined" && metaData.data[u].extra !== null) ? metaData.data[u].extra : "";

                            $("#vectorcollapse" + base64name).append('

' + subOrderHeader + '

<input type="checkbox" ' + dataAttr + '="' + id + '">' + icon + "" + text + '

');
                            l.push({});

                        }

                    }
                }
                $("#vectorlayer-panel-" + base64name + " span:eq(1)").html(l.length);

                // Remove the group if empty
                // =========================
                if (l.length === 0) {
                    $("#vectorlayer-panel-" + base64name).remove();
                }

                // Open the first panel
                // ====================
                $("#vectorlayers div:first").find("a").trigger("click");
            }
        }
        backboneEvents.get().trigger("ready:vectorLayers");
    },

    // Turn layers on/off
    // ==================
    switchLayer: function (id, visible) {

        let el = $('*[data-gc2-id-vec="' + id + '"]');

        if (visible) {

            el.parent().siblings().children().addClass("fa-spin");

            try {

                cloud.get().map.addLayer(cloud.get().getLayersByName(id));

            }

            catch (e) {

                console.info(id + " added to the map.");

                cloud.get().layerControl.addOverlay(store[id].layer, id);
                cloud.get().map.addLayer(cloud.get().getLayersByName(id));

            }

            finally {

                store[id].load();
                el.prop('checked', true);
                layers.incrementCountLoading(id);
                backboneEvents.get().trigger("startLoading:layers", id);
            }

        } else {

            store[id].abort();
            store[id].reset();
            cloud.get().map.removeLayer(cloud.get().getLayersByName(id));
            el.prop('checked', false);

        }

    },

    setOnEachFeature: function (layer, fn) {
        onEachFeature[layer] = fn;
    },

    setOnLoad: function (layer, fn) {
        onLoad[layer] = fn;
    },

    setOnSelect: function (layer, fn) {
        onSelect[layer] = fn;
    },

    setOnMouseOver: function (layer, fn) {
        onMouseOver[layer] = fn;
    },

    setCM: function (layer, c) {

        cm[layer] = c;
    },

    setStyle: function (layer, s) {

        styles[layer] = s;
    },

    setPointToLayer: function (layer, fn) {

        pointToLayer[layer] = fn;
    },

    setAutomatic: function (b) {
        automatic = b;
    },

    getStores: function () {
        return store;
    },

    load: function (id) {
        store[id].load();
    }
};<commit_msg>Switch layer now return "promise" so caller can call ".done()" and get GeoJSON<commit_after>/**
 * @fileoverview Description of file, its uses and information
 * about its dependencies.
 */

'use strict';

/**
 *
 * @type {*|exports|module.exports}
 */
var cloud;

/**
 *
 * @type {*|exports|module.exports}
 */
var meta;

/**
 *
 * @type {*|exports|module.exports}
 */
var setting;

/**
 *
 * @type {*|exports|module.exports}
 */
var utils;

/**
 *
 * @type {*|exports|module.exports}
 */
var backboneEvents;

/**
 *
 * @type {*|exports|module.exports}
 */
var urlparser = require('./../../../browser/modules/urlparser');

/**
 *
 * @type {array}
 */
var urlVars = urlparser.urlVars;

/**
 * @type {string}
 */
var db = urlparser.db;

var layers;

var onEachFeature = [];

var pointToLayer = [];

var onLoad = [];

var onSelect = [];

var onMouseOver = [];

var cm = [];

var styles = [];

var store = [];

var automatic = true;

/**
 *
 * @type {{set: module.exports.set, init: module.exports.init}}
 */
module.exports = {

    set: function (o) {
        cloud = o.cloud;
        setting = o.setting;
        utils = o.utils;
        meta = o.meta;
        layers = o.layers;
        backboneEvents = o.backboneEvents;
        return this;
    },

    init: function () {

        var me = this;

        utils.createMainTab("vectorlayers", "Vektor lag");

        $('#main-tabs a[href="#vectorlayer-content"]').tab('show');

        if (!urlVars.px && !urlVars.py) {

            $(document).arrive('.refresh-vector-layer', function () {

                $(this).on("click", function (e) {

                    $("#info-modal-top.slide-left").animate({
                        left: "0"
                    }, 500);

                    var id = ($(this).parent().prev().children("input").data('gc2-id-vec'));

                    $("#vectorlayer-table-div").empty().append('
');

                    var table = gc2table.init({
                        el: "#vectorlayer-table",
                        geocloud2: cloud.get(),
                        store: store[id],
                        cm: cm[id],
                        autoUpdate: false,
                        autoPan: false,
                        openPopUp: false,
                        setViewOnSelect: false,
                        setSelectedStyle: false,
                        responsive: true,
                        callCustomOnload: true,
                        height: 400,
                        onSelect: onSelect[id],
                        onMouseOver: onMouseOver[id],
                        locale: window._vidiLocale.replace("_", "-"),
                        ns: "#vectorlayer-table-div"
                    });

                    table.loadDataInTable();

                    e.stopPropagation();

                });

            });

            $(document).arrive('[data-gc2-id-vec]', function () {

                $(this).on("change", function (e) {

                    me.switchLayer(($(this).data('gc2-id-vec')), $(this).context.checked);

                    e.stopPropagation();

                });
            });
        }

        backboneEvents.get().on("ready:meta", function () {

            if (automatic) {
                me.createLayerTree();
            }

        })
    },

    createLayerTree: function () {

        let base64name, arr, groups = [], metaData, i, l, displayInfo, subOrderHeader, icon, dataAttr, styleFn;

        metaData = meta.getMetaData();

        for (i = 0; i < metaData.data.length; ++i) {
            groups[i] = metaData.data[i].layergroup;
        }

        arr = array_unique(groups.reverse());

        metaData.data.reverse();

        for (i = 0; i < arr.length; ++i) {

            if (arr[i] && arr[i] !== "[Ungrouped]") {
                l = [];
                base64name = Base64.encode(arr[i]).replace(/=/g, "");
                $("#vectorlayers").append('

0 /
 ' + arr[i] + '

');
                $("#vectorgroup-" + base64name).append('

');

                for (let u = 0; u < metaData.data.length; ++u) {
                    if (metaData.data[u].layergroup == arr[i]) {

                        // if (JSON.parse(metaData.data[u].meta) !== null && typeof JSON.parse(metaData.data[u].meta).vectorstyle !== "undefined") {
                        //     try {
                        //         styleFn = eval("(" + JSON.parse(metaData.data[u].meta).vectorstyle + ")");
                        //     } catch (e) {
                        //         styleFn = function () {
                        //         };
                        //     }
                        // }

                        var text = (metaData.data[u].f_table_title === null || metaData.data[u].f_table_title === "") ? metaData.data[u].f_table_name : metaData.data[u].f_table_title,
                            id;

                        try {
                            icon = " ";
                        } catch (e) {
                            icon = "";
                        }

                        // If meta.usetiles is true, when add layers as tiles instead of vectors
                        if (JSON.parse(metaData.data[u].meta) !== null && typeof JSON.parse(metaData.data[u].meta).usetiles !== "undefined" && JSON.parse(metaData.data[u].meta).usetiles === true) {

                            id = metaData.data[u].f_table_schema + "." + metaData.data[u].f_table_name;
                            dataAttr = "data-gc2-id";

                        } else {

                            id = "v:" + metaData.data[u].f_table_schema + "." + metaData.data[u].f_table_name;
                            dataAttr = "data-gc2-id-vec";

                            if (!metaData.data[u].baselayer) {
                                store[id] = new geocloud.sqlStore({
                                    jsonp: false,
                                    method: "POST",
                                    host: "",
                                    db: db,
                                    uri: "/api/sql",
                                    clickable: true,
                                    id: id,
                                    name: id,
                                    lifetime: 0,
                                    styleMap: styles[id],
                                    sql: "SELECT * FROM " + metaData.data[u].f_table_schema + "." + metaData.data[u].f_table_name + " LIMIT 500",
                                    onLoad: function (l) {

                                        if (l === undefined) {
                                            return
                                        }

                                        var me = l;
                                        try {
                                            $('*[data-gc2-id-vec="' + me.id + '"]').parent().siblings().children().removeClass("fa-spin")
                                        } catch (e) {
                                        }
                                        layers.decrementCountLoading(me.id);
                                        backboneEvents.get().trigger("doneLoading:layers", me.id);
                                        if (onLoad[me.id] !== undefined) {
                                            onLoad[me.id](l);
                                        }
                                    },

                                    onEachFeature: onEachFeature[id],

                                    pointToLayer: pointToLayer[id]

                                });
                            }
                        }

                        if (!metaData.data[u].baselayer) {

                            displayInfo = (metaData.data[u].meta !== null && $.parseJSON(metaData.data[u].meta) !== null && typeof $.parseJSON(metaData.data[u].meta).meta_desc !== "undefined") ? "inline" : "none";

                            subOrderHeader = (typeof metaData.data[u].extra !== "undefined" && metaData.data[u].extra !== null) ? metaData.data[u].extra : "";

                            $("#vectorcollapse" + base64name).append('
' + (subOrderHeader !== "" ? '
' + subOrderHeader + '
':'') + '
<input type="checkbox" ' + dataAttr + '="' + id + '">' + icon + "" + text + '

');
                            l.push({});

                        }

                    }
                }
                $("#vectorlayer-panel-" + base64name + " span:eq(1)").html(l.length);

                // Remove the group if empty
                // =========================
                if (l.length === 0) {
                    $("#vectorlayer-panel-" + base64name).remove();
                }

                // Open the first panel
                // ====================
                $("#vectorlayers div:first").find("a").trigger("click");
            }
        }
        backboneEvents.get().trigger("ready:vectorLayers");
    },

    // Turn layers on/off
    // ==================
    switchLayer: function (id, visible) {

        let el = $('*[data-gc2-id-vec="' + id + '"]');

        if (visible) {

            el.parent().siblings().children().addClass("fa-spin");

            try {

                cloud.get().map.addLayer(cloud.get().getLayersByName(id));

            }

            catch (e) {

                console.info(id + " added to the map.");

                cloud.get().layerControl.addOverlay(store[id].layer, id);
                cloud.get().map.addLayer(cloud.get().getLayersByName(id));

            }

            finally {

                el.prop('checked', true);
                layers.incrementCountLoading(id);
                backboneEvents.get().trigger("startLoading:layers", id);

            }
            // XHR promise, so with call back ".done()"
            return store[id].load();

        } else {

            store[id].abort();
            store[id].reset();
            cloud.get().map.removeLayer(cloud.get().getLayersByName(id));
            el.prop('checked', false);
            // Return dummy ".done()"
            return {
                done: function () {
                }
            };

        }

    },

    setOnEachFeature: function (layer, fn) {
        onEachFeature[layer] = fn;
    },

    setOnLoad: function (layer, fn) {
        onLoad[layer] = fn;
    },

    setOnSelect: function (layer, fn) {
        onSelect[layer] = fn;
    },

    setOnMouseOver: function (layer, fn) {
        onMouseOver[layer] = fn;
    },

    setCM: function (layer, c) {

        cm[layer] = c;
    },

    setStyle: function (layer, s) {

        styles[layer] = s;
    },

    setPointToLayer: function (layer, fn) {

        pointToLayer[layer] = fn;
    },

    setAutomatic: function (b) {
        automatic = b;
    },

    getStores: function () {
        return store;
    },

    load: function (id) {
        store[id].load();
    }
};<|endoftext|>


<commit_before>#!/usr/bin/env node

/**
 * Clones several projects that are known to follow "JavaScript Standard Style" and runs
 * the `standard` style checker to verify that it passes without warnings. This helps
 * ensure we don't accidentally introduce new style rules that cause previously "good"
 * code to start failing with new warnings! (And if we do, then that needs to be a MAJOR
 * VERSION BUMP.)
 */

var cp = require('child_process')
var extend = require('xtend')
var mkdirp = require('mkdirp')
var path = require('path')
var rimraf = require('rimraf')
var series = require('run-series')
var test = require('tape')

var TMP = path.join(__dirname, '..', 'tmp')
var SEMISTANDARD = path.join(__dirname, '..', 'bin', 'cmd.js')

var URLS = [
  'https://github.com/Flet/cursorfun.git',
  'https://github.com/bnolan/scenevr.git',
  'https://github.com/patrickarlt/acetate.git'
]

var MODULES = {}
URLS.forEach(function (url) {
  var name = /\/([^\/]+)\.git$/.exec(url)[1]
  MODULES[name] = url
})

test('clone repos from github', function (t) {
  t.plan(1)
  rimraf.sync(TMP)
  mkdirp.sync(TMP)

  series(Object.keys(MODULES).map(function (name) {
    var url = MODULES[name]
    return function (cb) {
      var args = [ 'clone', '--depth', 1, url, path.join(TMP, name) ]
      // TODO: Start `git` in a way that works on Windows – PR welcome!
      spawn('git', args, {}, cb)
    }
  }), function (err) {
    if (err) throw err
    t.pass('cloned repos')
  })
})

test('lint repos', function (t) {
  t.plan(URLS.length)
  series(Object.keys(MODULES).map(function (name) {
    return function (cb) {
      var cwd = path.join(TMP, name)
      console.log('!!!!!!!!!' + cwd)
      spawn(SEMISTANDARD, [], { cwd: cwd }, function (err) {
        t.error(err, name)
        cb(null)
      })
    }
  }))
})

function spawn (command, args, opts, cb) {
  var child = cp.spawn(command, args, extend({ stdio: 'inherit' }, opts))
  child.on('error', cb)
  child.on('close', function (code) {
    if (code !== 0) cb(new Error('non-zero exit code: ' + code))
    else cb(null)
  })
  return child
}
<commit_msg>update scenevr url<commit_after>#!/usr/bin/env node

/**
 * Clones several projects that are known to follow "JavaScript Standard Style" and runs
 * the `standard` style checker to verify that it passes without warnings. This helps
 * ensure we don't accidentally introduce new style rules that cause previously "good"
 * code to start failing with new warnings! (And if we do, then that needs to be a MAJOR
 * VERSION BUMP.)
 */

var cp = require('child_process')
var extend = require('xtend')
var mkdirp = require('mkdirp')
var path = require('path')
var rimraf = require('rimraf')
var series = require('run-series')
var test = require('tape')

var TMP = path.join(__dirname, '..', 'tmp')
var SEMISTANDARD = path.join(__dirname, '..', 'bin', 'cmd.js')

var URLS = [
  'https://github.com/Flet/cursorfun.git',
  'https://github.com/scenevr/server.git',
  'https://github.com/patrickarlt/acetate.git'
]

var MODULES = {}
URLS.forEach(function (url) {
  var name = /\/([^\/]+)\.git$/.exec(url)[1]
  MODULES[name] = url
})

test('clone repos from github', function (t) {
  t.plan(1)
  rimraf.sync(TMP)
  mkdirp.sync(TMP)

  series(Object.keys(MODULES).map(function (name) {
    var url = MODULES[name]
    return function (cb) {
      var args = [ 'clone', '--depth', 1, url, path.join(TMP, name) ]
      // TODO: Start `git` in a way that works on Windows – PR welcome!
      spawn('git', args, {}, cb)
    }
  }), function (err) {
    if (err) throw err
    t.pass('cloned repos')
  })
})

test('lint repos', function (t) {
  t.plan(URLS.length)
  series(Object.keys(MODULES).map(function (name) {
    return function (cb) {
      var cwd = path.join(TMP, name)
      console.log('!!!!!!!!!' + cwd)
      spawn(SEMISTANDARD, [], { cwd: cwd }, function (err) {
        t.error(err, name)
        cb(null)
      })
    }
  }))
})

function spawn (command, args, opts, cb) {
  var child = cp.spawn(command, args, extend({ stdio: 'inherit' }, opts))
  child.on('error', cb)
  child.on('close', function (code) {
    if (code !== 0) cb(new Error('non-zero exit code: ' + code))
    else cb(null)
  })
  return child
}
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { Link } from 'react-router'
import { connect } from 'react-redux'
import { userLogoutReq } from '../actions/user-actions'
import '../styles/NavBar.css'
import '../styles/Colors.css'

class NavBar extends Component {
  render() {
    return (

Match Finder

Seattle Sounders 2017 Season

        { this.props.user.user ?

            <button className="action-button" onClick={(e) => {this.props.logout(e)}} > Logout</button>

          :

            <Link to="/login"  className="nav-bar-item" >
            <button className="action-button">Login</button>
          </ Link>

        }

    )
  }
}

const mapStateToProps = (state) => {
  return {
    user: state.user
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    logout: (e) => {
      e.preventDefault();
      return dispatch(userLogoutReq())
    }
  }
}

const NavBarContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)(NavBar)

export default NavBarContainer
<commit_msg>link back to main page<commit_after>import React, { Component } from 'react'
import { Link } from 'react-router'
import { connect } from 'react-redux'
import { userLogoutReq } from '../actions/user-actions'
import '../styles/NavBar.css'
import '../styles/Colors.css'

class NavBar extends Component {
  render() {
    return (

          <Link to="/">

Match Finder

          </Link>

Seattle Sounders 2017 Season

        { this.props.user.user ?

            <button className="action-button" onClick={(e) => {this.props.logout(e)}} > Logout</button>

          :

            <Link to="/login"  className="nav-bar-item" >
            <button className="action-button">Login</button>
          </ Link>

        }

    )
  }
}

const mapStateToProps = (state) => {
  return {
    user: state.user
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    logout: (e) => {
      e.preventDefault();
      return dispatch(userLogoutReq())
    }
  }
}

const NavBarContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)(NavBar)

export default NavBarContainer
<|endoftext|>