<commit_before>(function (global) {
  "use strict";

  var BrowserControl = function BrowserControl(view, homeurl) {
    this.webview = view;
    this.homeurl = homeurl;
  };
  global.BrowserControl = BrowserControl;

  BrowserControl.prototype.back = function back() {
    var webview = global.document.querySelector(this.webview);
    if (webview.canGoBack()) webview.back();
    return this;
  };

  BrowserControl.prototype.forward = function forward() {
    var webview = global.document.querySelector(this.webview);
    if (webview.canGoForward()) webview.forward();
    return this;
  };

  BrowserControl.prototype.reload = function reload() {
    var webview = global.document.querySelector(this.webview);
    webview.reload();
    return this;
  };

  BrowserControl.prototype.home = function home() {
    var webview = global.document.querySelector(this.webview);
    webview.src = this.homeurl;
    return this;
  };

  var TitleBar = function TitleBar(position, titlebar_icon_url, titlebar_text, allowChangingPosition, browser) {
      if (typeof position !== "string") position = "top";
      if (typeof allowChangingPosition !== "boolean") allowChangingPosition = false;
      if (typeof browser !== "object" || !(browser instanceof BrowserControl)) browser = undefined;

      if (!global.document.getElementById("content")) throw "you need to have all things wrapped inside
!";
      if (position !== "left" && position !== "right" && position !== "top" && position !== "bottom") throw "wrong position!";

      this._name = position + "-titlebar";
      this._position = position;
      this.__build_done = false;

      chrome.storage.sync.get("titlebar_position", (function(result) {
         if (typeof result === "object" && typeof result["titlebar_position"] === "string") {
            if (result.titlebar_position === "left" || result.titlebar_position === "right" || result.titlebar_position === "top" || result.titlebar_position === "bottom") {
                position = result.titlebar_position;
                this._name = position + "-titlebar";
                this._position = position;
            }
         }

         this.__build_done = true;
      }).bind(this));

      this._icon = titlebar_icon_url;
      this._text = titlebar_text;
      this.allowChangingPosition = allowChangingPosition;
      this._browser = browser;
  };
  global.TitleBar = TitleBar;

  TitleBar.prototype.closeWindow = function closeWindow(e) {
    if (e.altKey && this.allowChangingPosition) { //change titlebar position
      this.unbind();
      if (this._position === "left") {
        this._position = "top";
      } else if (this._position === "top") {
        this._position = "right";
      } else if (this._position === "right") {
        this._position = "bottom";
      } else {
        this._position = "left";
      }
      this._name = this._position + "-titlebar";
      this.bind();

      this.buttons.closeButton.title = "Change titlebar position";
      this.buttons.closeButton.className += " position";
      chrome.storage.sync.set({"titlebar_position": this._position});
    } else { //close
      global.chrome.app.window.current().close();
    }
    return this;
  };

  TitleBar.prototype.minimizeWindow = function minimizeWindow(e) {
    var window = global.chrome.app.window.current();
    if (window.isMinimized() || window.isMaximized()) {
      window.restore();
    } else if (e.altKey) {
      window.maximize();
    } else {
      window.minimize();
    }

    return this;
  };

  TitleBar.prototype.creator = {};

  TitleBar.prototype.creator.updateImageUrl = function updateImageUrl(image_id, new_image_url) {
    var image = global.document.getElementById(image_id);
    if (image)
      image.src = new_image_url;
    return this;
  };

  TitleBar.prototype.creator.createImage = function createImage(image_id, image_url) {
    var image = global.document.createElement("img");
    image.setAttribute("id", image_id);
    image.src = image_url;
    return image;
  };

  TitleBar.prototype.creator.createButton = function createButton(button_name, buttonText, titleText, normal_image_url,
    hover_image_url, click_func) {
    var button = global.document.createElement("div");
    button.setAttribute("class", "titlebar-button " + button_name);
    if (normal_image_url) {
      var button_img = this.createImage(button_name + "-image", normal_image_url);
      button.appendChild(button_img);
      if (hover_image_url) {
        button.onmouseover = (function () {
          this.updateImageUrl(button_name + "-image", hover_image_url);
        }).bind(this);
        button.onmouseout = (function () {
          this.updateImageUrl(button_name + "-image", normal_image_url);
        }).bind(this);
      }
    }
    if (click_func) {
      button.onclick = click_func;
    }
    if (titleText) {
      button.title = titleText;
    }
    if (buttonText) {
      button.innerHTML = buttonText;
    }
    return button;
  };

  TitleBar.prototype.focus = function focusTitlebar(focus) {
    var bg_color = focus ? "#23232C" : "#555959";
    var titlebar = global.document.getElementById(this._name);
    if (titlebar)
      titlebar.style.backgroundColor = bg_color;
  };

  TitleBar.prototype.bind = function addTitlebar() {

    if (!this.__build_done) {
      setTimeout(this.bind.bind(this), 100);
      return;
    }

    this.buttons = {};
    var document = global.document;
    var titlebar = document.createElement("div");
    titlebar.setAttribute("id", this._name);
    titlebar.setAttribute("class", this._name);

    var icon = document.createElement("div");
    icon.setAttribute("class", this._name + "-icon");
    icon.appendChild(this.creator.createImage(this._name + "icon", this._icon));
    titlebar.appendChild(icon);

    var title = document.createElement("div");
    title.setAttribute("class", this._name + "-text");
    title.innerText = this._text;
    titlebar.appendChild(title);

    var closeTitle = "Close";
    var closeChangeTitle = "\n\n(Alt+click changes titlebar position)";
    var closeButton = this.creator.createButton(this._name + "-button titlebar-close-button",
      "", closeTitle + (this.allowChangingPosition ? closeChangeTitle : ""), null, null, this.closeWindow.bind(this));
    titlebar.appendChild(closeButton);
    this.buttons.closeButton = closeButton;

    var minimizeTitle = "Minimize";
    var minimizeChangeTitle = "\n\n(Alt+click maximizes window)";
    var minimizeButton = this.creator.createButton(this._name + "-button titlebar-minimize-button",
      "", minimizeTitle + minimizeChangeTitle, null, null, this.minimizeWindow.bind(this));
    titlebar.appendChild(minimizeButton);
    this.buttons.minimizeButton = minimizeButton;

    this.__MonitorAltKey = (function MonitorAltKey(e) {
      if (!e) e = window.event;

      if (e.type === "keydown" && e.keyCode === 18) {
        if (this.allowChangingPosition && this.buttons.closeButton.className.search("position") === -1) {
          this.buttons.closeButton.title = "Change titlebar position";
          this.buttons.closeButton.className += " position";
        }
        if (this.buttons.minimizeButton.className.search("maximize") === -1) {
          this.buttons.minimizeButton.title = "Maximize window";
          this.buttons.minimizeButton.className += " maximize";
        }
      } else if (e.type === "keyup" && e.keyCode === 18) {
        if (this.allowChangingPosition && this.buttons.closeButton.className.search("position") !== -1) {
          this.buttons.closeButton.title = closeTitle + closeChangeTitle;
          this.buttons.closeButton.className = this.buttons.closeButton.className.replace(" position", "");
        }
        if (this.buttons.minimizeButton.className.search("maximize") !== -1) {
          this.buttons.minimizeButton.title = minimizeTitle + minimizeChangeTitle;
          this.buttons.minimizeButton.className = this.buttons.minimizeButton.className.replace(" maximize", "");
        }
      }
    }).bind(this);

    document.addEventListener("keydown", this.__MonitorAltKey);
    document.addEventListener("keyup", this.__MonitorAltKey);

    if (this._browser) {
      var backButton = this.creator.createButton(this._name + "-button titlebar-back-button",
        "", "Back", null, null, this._browser.back.bind(this._browser));
      titlebar.appendChild(backButton);
      this.buttons.backButton = backButton;

      var forwardButton = this.creator.createButton(this._name + "-button titlebar-forward-button",
        "", "Forward", null, null, this._browser.forward.bind(this._browser));
      titlebar.appendChild(forwardButton);
      this.buttons.forwardButton = forwardButton;

      var reloadButton = this.creator.createButton(this._name + "-button titlebar-reload-button",
        "", "Reload", null, null, this._browser.reload.bind(this._browser));
      titlebar.appendChild(reloadButton);
      this.buttons.reloadButton = reloadButton;

      var homeButton = this.creator.createButton(this._name + "-button titlebar-home-button",
        "", "Home", null, null, this._browser.home.bind(this._browser));
      titlebar.appendChild(homeButton);
      this.buttons.homeButton = homeButton;
    }

    var divider = document.createElement("div");
    divider.setAttribute("class", this._name + "-divider");
    titlebar.appendChild(divider);

    document.body.appendChild(titlebar);

    this.onfocus = (function () {
      this.focus(true);
    }).bind(this);
    global.addEventListener("focus", this.onfocus);
    this.onblur = (function () {
      this.focus(false);
    }).bind(this);
    global.addEventListener("blur", this.onblur);
    this.onresize = this.updateContentStyle.bind(this);
    global.addEventListener("resize", this.onresize);

    this.updateContentStyle();
  };

  TitleBar.prototype.unbind = function removeTitlebar() {
    var document = global.document;
    var titlebar = document.getElementById(this._name);
    if (titlebar) {
      document.body.removeChild(titlebar);
      if (this.onfocus) global.removeEventListener("focus", this.onfocus);
      if (this.onblur) global.removeEventListener("blur", this.onblur);
      if (this.onresize) global.removeEventListener("resize", this.onresize);
      if (this.__MonitorAltKey) {
        document.removeEventListener("keydown", this.__MonitorAltKey);
        document.removeEventListener("keyup", this.__MonitorAltKey);
      }
      this.resetContentStyle();
    }
  };

  TitleBar.prototype.resetContentStyle = function resetContentStyle() {
    var document = global.document;
    var content = document.getElementById("content");
    if (!content)
      return;
    content.setAttribute("style", "");
  };

  TitleBar.prototype.updateContentStyle = function updateContentStyle() {
    if (this.callUpdateContent) clearTimeout(this.callUpdateContent);
    this.callUpdateContent = setTimeout((function () {
      var document = global.document;
      var content = document.getElementById("content");
      if (!content)
        return;

      var titlebar = document.getElementById(this._name);
      if (titlebar) {
        var left = 0;
        var top = 0;
        var width = global.outerWidth;
        var height = global.outerHeight;

        switch (this._position) {
        case "top":
          height -= titlebar.offsetHeight;
          top += titlebar.offsetHeight;
          break;
        case "bottom":
          height -= titlebar.offsetHeight;
          break;
        case "left":
          width -= titlebar.offsetWidth;
          left += titlebar.offsetWidth;
          break;
        case "right":
          width -= titlebar.offsetWidth;
          break;
        default:
          return;
        }

        var contentStyle = "position: absolute; ";
        contentStyle += "left: " + left + "px; ";
        contentStyle += "top: " + top + "px; ";
        contentStyle += "width: " + width + "px; ";
        contentStyle += "height: " + height + "px; ";
        content.setAttribute("style", contentStyle);
      }
    }).bind(this), 100);
  };
})(window);
<commit_msg>fix minimize on maximized state<commit_after>(function (global) {
  "use strict";

  var BrowserControl = function BrowserControl(view, homeurl) {
    this.webview = view;
    this.homeurl = homeurl;
  };
  global.BrowserControl = BrowserControl;

  BrowserControl.prototype.back = function back() {
    var webview = global.document.querySelector(this.webview);
    if (webview.canGoBack()) webview.back();
    return this;
  };

  BrowserControl.prototype.forward = function forward() {
    var webview = global.document.querySelector(this.webview);
    if (webview.canGoForward()) webview.forward();
    return this;
  };

  BrowserControl.prototype.reload = function reload() {
    var webview = global.document.querySelector(this.webview);
    webview.reload();
    return this;
  };

  BrowserControl.prototype.home = function home() {
    var webview = global.document.querySelector(this.webview);
    webview.src = this.homeurl;
    return this;
  };

  var TitleBar = function TitleBar(position, titlebar_icon_url, titlebar_text, allowChangingPosition, browser) {
      if (typeof position !== "string") position = "top";
      if (typeof allowChangingPosition !== "boolean") allowChangingPosition = false;
      if (typeof browser !== "object" || !(browser instanceof BrowserControl)) browser = undefined;

      if (!global.document.getElementById("content")) throw "you need to have all things wrapped inside
!";
      if (position !== "left" && position !== "right" && position !== "top" && position !== "bottom") throw "wrong position!";

      this._name = position + "-titlebar";
      this._position = position;
      this.__build_done = false;

      chrome.storage.sync.get("titlebar_position", (function(result) {
         if (typeof result === "object" && typeof result["titlebar_position"] === "string") {
            if (result.titlebar_position === "left" || result.titlebar_position === "right" || result.titlebar_position === "top" || result.titlebar_position === "bottom") {
                position = result.titlebar_position;
                this._name = position + "-titlebar";
                this._position = position;
            }
         }

         this.__build_done = true;
      }).bind(this));

      this._icon = titlebar_icon_url;
      this._text = titlebar_text;
      this.allowChangingPosition = allowChangingPosition;
      this._browser = browser;
  };
  global.TitleBar = TitleBar;

  TitleBar.prototype.closeWindow = function closeWindow(e) {
    if (e.altKey && this.allowChangingPosition) { //change titlebar position
      this.unbind();
      if (this._position === "left") {
        this._position = "top";
      } else if (this._position === "top") {
        this._position = "right";
      } else if (this._position === "right") {
        this._position = "bottom";
      } else {
        this._position = "left";
      }
      this._name = this._position + "-titlebar";
      this.bind();

      this.buttons.closeButton.title = "Change titlebar position";
      this.buttons.closeButton.className += " position";
      chrome.storage.sync.set({"titlebar_position": this._position});
    } else { //close
      global.chrome.app.window.current().close();
    }
    return this;
  };

  TitleBar.prototype.minimizeWindow = function minimizeWindow(e) {
    var window = global.chrome.app.window.current();
    if (e.altKey) {
      if (window.isMaximized()) {
        window.restore();
      } else {
        window.maximize();
      }
    } else {
        window.minimize();
    }

    return this;
  };

  TitleBar.prototype.creator = {};

  TitleBar.prototype.creator.updateImageUrl = function updateImageUrl(image_id, new_image_url) {
    var image = global.document.getElementById(image_id);
    if (image)
      image.src = new_image_url;
    return this;
  };

  TitleBar.prototype.creator.createImage = function createImage(image_id, image_url) {
    var image = global.document.createElement("img");
    image.setAttribute("id", image_id);
    image.src = image_url;
    return image;
  };

  TitleBar.prototype.creator.createButton = function createButton(button_name, buttonText, titleText, normal_image_url,
    hover_image_url, click_func) {
    var button = global.document.createElement("div");
    button.setAttribute("class", "titlebar-button " + button_name);
    if (normal_image_url) {
      var button_img = this.createImage(button_name + "-image", normal_image_url);
      button.appendChild(button_img);
      if (hover_image_url) {
        button.onmouseover = (function () {
          this.updateImageUrl(button_name + "-image", hover_image_url);
        }).bind(this);
        button.onmouseout = (function () {
          this.updateImageUrl(button_name + "-image", normal_image_url);
        }).bind(this);
      }
    }
    if (click_func) {
      button.onclick = click_func;
    }
    if (titleText) {
      button.title = titleText;
    }
    if (buttonText) {
      button.innerHTML = buttonText;
    }
    return button;
  };

  TitleBar.prototype.focus = function focusTitlebar(focus) {
    var bg_color = focus ? "#23232C" : "#555959";
    var titlebar = global.document.getElementById(this._name);
    if (titlebar)
      titlebar.style.backgroundColor = bg_color;
  };

  TitleBar.prototype.bind = function addTitlebar() {

    if (!this.__build_done) {
      setTimeout(this.bind.bind(this), 100);
      return;
    }

    this.buttons = {};
    var document = global.document;
    var titlebar = document.createElement("div");
    titlebar.setAttribute("id", this._name);
    titlebar.setAttribute("class", this._name);

    var icon = document.createElement("div");
    icon.setAttribute("class", this._name + "-icon");
    icon.appendChild(this.creator.createImage(this._name + "icon", this._icon));
    titlebar.appendChild(icon);

    var title = document.createElement("div");
    title.setAttribute("class", this._name + "-text");
    title.innerText = this._text;
    titlebar.appendChild(title);

    var closeTitle = "Close";
    var closeChangeTitle = "\n\n(Alt+click changes titlebar position)";
    var closeButton = this.creator.createButton(this._name + "-button titlebar-close-button",
      "", closeTitle + (this.allowChangingPosition ? closeChangeTitle : ""), null, null, this.closeWindow.bind(this));
    titlebar.appendChild(closeButton);
    this.buttons.closeButton = closeButton;

    var minimizeTitle = "Minimize";
    var minimizeChangeTitle = "\n\n(Alt+click maximizes window)";
    var minimizeButton = this.creator.createButton(this._name + "-button titlebar-minimize-button",
      "", minimizeTitle + minimizeChangeTitle, null, null, this.minimizeWindow.bind(this));
    titlebar.appendChild(minimizeButton);
    this.buttons.minimizeButton = minimizeButton;

    this.__MonitorAltKey = (function MonitorAltKey(e) {
      if (!e) e = window.event;

      if (e.type === "keydown" && e.keyCode === 18) {
        if (this.allowChangingPosition && this.buttons.closeButton.className.search("position") === -1) {
          this.buttons.closeButton.title = "Change titlebar position";
          this.buttons.closeButton.className += " position";
        }
        if (this.buttons.minimizeButton.className.search("maximize") === -1) {
          this.buttons.minimizeButton.title = "Maximize window";
          this.buttons.minimizeButton.className += " maximize";
        }
      } else if (e.type === "keyup" && e.keyCode === 18) {
        if (this.allowChangingPosition && this.buttons.closeButton.className.search("position") !== -1) {
          this.buttons.closeButton.title = closeTitle + closeChangeTitle;
          this.buttons.closeButton.className = this.buttons.closeButton.className.replace(" position", "");
        }
        if (this.buttons.minimizeButton.className.search("maximize") !== -1) {
          this.buttons.minimizeButton.title = minimizeTitle + minimizeChangeTitle;
          this.buttons.minimizeButton.className = this.buttons.minimizeButton.className.replace(" maximize", "");
        }
      }
    }).bind(this);

    document.addEventListener("keydown", this.__MonitorAltKey);
    document.addEventListener("keyup", this.__MonitorAltKey);

    if (this._browser) {
      var backButton = this.creator.createButton(this._name + "-button titlebar-back-button",
        "", "Back", null, null, this._browser.back.bind(this._browser));
      titlebar.appendChild(backButton);
      this.buttons.backButton = backButton;

      var forwardButton = this.creator.createButton(this._name + "-button titlebar-forward-button",
        "", "Forward", null, null, this._browser.forward.bind(this._browser));
      titlebar.appendChild(forwardButton);
      this.buttons.forwardButton = forwardButton;

      var reloadButton = this.creator.createButton(this._name + "-button titlebar-reload-button",
        "", "Reload", null, null, this._browser.reload.bind(this._browser));
      titlebar.appendChild(reloadButton);
      this.buttons.reloadButton = reloadButton;

      var homeButton = this.creator.createButton(this._name + "-button titlebar-home-button",
        "", "Home", null, null, this._browser.home.bind(this._browser));
      titlebar.appendChild(homeButton);
      this.buttons.homeButton = homeButton;
    }

    var divider = document.createElement("div");
    divider.setAttribute("class", this._name + "-divider");
    titlebar.appendChild(divider);

    document.body.appendChild(titlebar);

    this.onfocus = (function () {
      this.focus(true);
    }).bind(this);
    global.addEventListener("focus", this.onfocus);
    this.onblur = (function () {
      this.focus(false);
    }).bind(this);
    global.addEventListener("blur", this.onblur);
    this.onresize = this.updateContentStyle.bind(this);
    global.addEventListener("resize", this.onresize);

    this.updateContentStyle();
  };

  TitleBar.prototype.unbind = function removeTitlebar() {
    var document = global.document;
    var titlebar = document.getElementById(this._name);
    if (titlebar) {
      document.body.removeChild(titlebar);
      if (this.onfocus) global.removeEventListener("focus", this.onfocus);
      if (this.onblur) global.removeEventListener("blur", this.onblur);
      if (this.onresize) global.removeEventListener("resize", this.onresize);
      if (this.__MonitorAltKey) {
        document.removeEventListener("keydown", this.__MonitorAltKey);
        document.removeEventListener("keyup", this.__MonitorAltKey);
      }
      this.resetContentStyle();
    }
  };

  TitleBar.prototype.resetContentStyle = function resetContentStyle() {
    var document = global.document;
    var content = document.getElementById("content");
    if (!content)
      return;
    content.setAttribute("style", "");
  };

  TitleBar.prototype.updateContentStyle = function updateContentStyle() {
    if (this.callUpdateContent) clearTimeout(this.callUpdateContent);
    this.callUpdateContent = setTimeout((function () {
      var document = global.document;
      var content = document.getElementById("content");
      if (!content)
        return;

      var titlebar = document.getElementById(this._name);
      if (titlebar) {
        var left = 0;
        var top = 0;
        var width = global.outerWidth;
        var height = global.outerHeight;

        switch (this._position) {
        case "top":
          height -= titlebar.offsetHeight;
          top += titlebar.offsetHeight;
          break;
        case "bottom":
          height -= titlebar.offsetHeight;
          break;
        case "left":
          width -= titlebar.offsetWidth;
          left += titlebar.offsetWidth;
          break;
        case "right":
          width -= titlebar.offsetWidth;
          break;
        default:
          return;
        }

        var contentStyle = "position: absolute; ";
        contentStyle += "left: " + left + "px; ";
        contentStyle += "top: " + top + "px; ";
        contentStyle += "width: " + width + "px; ";
        contentStyle += "height: " + height + "px; ";
        content.setAttribute("style", contentStyle);
      }
    }).bind(this), 100);
  };
})(window);
<|endoftext|>


<commit_before>//    Copyright (C) 2011 by Mobile Developer Solutions http://www.mobiledevelopersolutions.com
//
//    Permission is hereby granted, free of charge, to any person obtaining a copy
//    of this software and associated documentation files (the "Software"), to deal
//    in the Software without restriction, including without limitation the rights
//    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//    copies of the Software, and to permit persons to whom the Software is
//    furnished to do so, subject to the following conditions:
//
//    The above copyright notice and this permission notice shall be included in
//    all copies or substantial portions of the Software.
//
//    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//    THE SOFTWARE.
//

// Manage the My Apps page

$('#page-home').live('pageinit', function(event){

    $('#page-home').live("swipeleft", function () {
        $.mobile.changePage($("#page-guest"), {transition: 'slide'});
    });

    $('a.projects').live('click', function() {
        var proj_name = $(this).text();
        var useWeinre = ($('a#weinre_btn_' + proj_name).find('.ui-icon-weinre').css('background-image').indexOf('grey') > 0) ? false : true;
        var link = serverUrl + (useWeinre ? "/runWeinre/" : "/runProject/") + proj_name;
        console.log("AppLaudLog: run project : " + link);
        navigator.app.loadUrl(link + "/assets/www/index.html");
        return false;
    });

    var saveLocalProjectList = function (list) {
        localStorage.applaud_project_list = JSON.stringify(list);
    };

    var buildProjectList = function(list) {
        var i;
        for(i = 0 ; i < list.length; i++) {
            $('

'
                    + list[i].project
                    + '

').appendTo('ul#project_list');
            $('a#weinre_btn_' + list[i].project.replace(' ','')).toggle(function() {
                $(this).find('.ui-icon-weinre').css('background-image', 'url(images/weinreblue18x18.png)');
              }, function() {
                  $(this).find('.ui-icon-weinre').css('background-image', 'url(images/weinregrey18x18.png)');
              });
        }
        $('span#my_project_cnt').html(i + " Project" + ((i>1)? "s" : ""));
        $('div#project_list_container').removeClass('hidden');
        $('div#project_list_container').trigger('expand');
        $("ul#project_list").listview('refresh');
    };

    $('div#project_list_container').live('expand',function(){
        $('span#project_hint').html("Tap to Run; Toggle Weinre");
    });
    $('div#project_list_container').live('collapse',function(){
        $('span#project_hint').html("Expand to See Projects");
    });

    $('a#get_project_list').live('click', function() {
        var showedError = false;
        console.log("AppLaudLog: get_project_list click");
        $.ajax({ url : serverUrl + "/getProjects", data : {}, cache : false,
            beforeSend : function(jqXHR, settings) {
                    fadingMsg('Getting Project List..');
                    $('ul#project_list').empty();
            },
            success : function(r, textStatus) {
                if (r.success) {
                    // Always means list has at least 1 item
                    buildProjectList(r.list);
                    saveLocalProjectList(r.list);
                } else {
                    $('div#project_list_container').addClass('hidden');
                    saveLocalProjectList({});
                    if (r.error === 'Authentication failed. Please re-login.') {
                        navigator.notification.confirm(
                            r.error,
                            onLogin,
                            'Project List Refresh',
                            'Login,Close'
                        );
                    } else {
                        navigator.notification.alert(
                            r.error + " Create a project with New->Project in AppLaud Cloud.",
                            null,
                            'Project List Refresh',
                            'Close'
                        );
                    }
                }
            },
            error : function(jqXHR, textStatus, errorThrown) {
                $('div#project_list_container').addClass('hidden');
                saveLocalProjectList({});
                if (!showedError) {
                    var errormsg;
                    showedError = true;
                    if (errorThrown === '') {
                        errormsg = 'Check network connection.';
                    } else {
                        errormsg = errorThrown;
                    }
                    navigator.notification.alert(
                            'Error: ' + errormsg,
                            null,
                            'Project List Refresh',
                            'Close'
                          );
                    console.log('AppLaudLog: Get Projects returned with Error: ' + errormsg);
                    // no connection: error / blank
                }
            },
            complete : function(jqXHR, textStatus) {
                $('#fading_msg').remove();
                if ((!showedError) && textStatus === 'error') {
                    console.log('AppLaudLog: Get Projects completed with Error.');
                }
            }
        });
    });

    var apkUser, apkSession, apkMap;

    var buildApkList = function(apkList) {
        var i;
        apkMap = {};
        for(i = 0 ; i < apkList.length; i++) {
            var appName = apkList[i].appName;
            var fullPath = apkList[i].link;
            var buildType =
                fullPath.indexOf('-basic.apk') > 0 ? '[basic]' : fullPath.indexOf('-weinre.apk') > 0 ? '[weinre]' : '[release]';
            var id = appName + buildType;
            apkMap[id] = fullPath;
            $('

'
                    + appName + ' ' + buildType
                    + '

').appendTo('ul#apk_list');
        }
        $('span#my_apk_cnt').html(i + " APK" + ((i>1)? "s" : ""));
        $('div#apk_list_container').removeClass('hidden');
        $('div#apk_list_container').trigger('expand');
        $("ul#apk_list").listview('refresh');
    };

    $('a.apks').live('click', function() {
        var id = $(this).attr('id');
        window.plugins.childBrowser.openExternal(serverUrl + '/downloadApk' + '?file=' + apkMap[id] + '&user=' + apkUser + '&session=' + apkSession);
    });

    $('div#apk_list_container').live('expand',function(){
        $('#apk_hint').html("Tap to Download (Install, Run)");
    });
    $('div#apk_list_container').live('collapse',function(){
        $('#apk_hint').html("Expand to See APKs");
    });

    $('a#get_apk_list').click(function() {
        var showedError = false;
        console.log("AppLaudLog: get_apk_list");
        $.ajax({ url : serverUrl + "/getApks", data : {}, cache : false,
            beforeSend : function(jqXHR, settings) {
                fadingMsg('Getting APK List..');
                $('ul#apk_list').empty();
            },
            success : function(r, textStatus) {
                if (r.success) {
                    // Always means list has at least 1 item
                    buildApkList(r.list);
                    apkUser = r.user;
                    apkSession = r.session;
                } else {
                    $('div#apk_list_container').addClass('hidden');
                    if (r.error === 'Authentication failed. Please re-login.') {
                        navigator.notification.confirm(
                                r.error,
                                onLogin,
                                'APK List Refresh',
                                'Login,Close'
                        );
                    } else {
                        navigator.notification.alert(
                                'No APKs found. To build a project run Package->Build in AppLaud Cloud.',
                                null,
                                'APK List Refresh',
                                'Close'
                        );
                    }
                }
            },
            error : function(jqXHR, textStatus, errorThrown) {
                $('div#apk_list_container').addClass('hidden');
                if (!showedError) {
                    var errormsg;
                    if (errorThrown === '') { errormsg = 'Check network connection.'; }
                    else { errormsg =  errorThrown; }
                    alert('Get Apks Request returned with Error: ' + errormsg);
                    console.log('AppLaudLog: Get Apks returned with Error: ' + errormsg);
                    // no connection: error / blank
                    showedError = true;
                }
            },
            complete : function(jqXHR, textStatus) {
                $('#fading_msg').remove();
                if ((!showedError) && textStatus === 'error') {
                    console.log('AppLaudLog: Get Apks completed with Error.');
                }
            }
        });
    });
});<commit_msg>fix for return from loadUrl crash on tablet<commit_after>//    Copyright (C) 2011 by Mobile Developer Solutions http://www.mobiledevelopersolutions.com
//
//    Permission is hereby granted, free of charge, to any person obtaining a copy
//    of this software and associated documentation files (the "Software"), to deal
//    in the Software without restriction, including without limitation the rights
//    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//    copies of the Software, and to permit persons to whom the Software is
//    furnished to do so, subject to the following conditions:
//
//    The above copyright notice and this permission notice shall be included in
//    all copies or substantial portions of the Software.
//
//    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//    THE SOFTWARE.
//

// Manage the My Apps page

$('#page-home').live('pageinit', function(event){

    $('#page-home').live("swipeleft", function () {
        $.mobile.changePage($("#page-guest"), {transition: 'slide', changeHash: false});
    });

    $('a.projects').live('click', function() {
        var proj_name = $(this).text();
        var useWeinre = ($('a#weinre_btn_' + proj_name).find('.ui-icon-weinre').css('background-image').indexOf('grey') > 0) ? false : true;
        var link = serverUrl + (useWeinre ? "/runWeinre/" : "/runProject/") + proj_name;
        console.log("AppLaudLog: run project : " + link);
        navigator.app.loadUrl(link + "/assets/www/index.html");
        return false;
    });

    var saveLocalProjectList = function (list) {
        localStorage.applaud_project_list = JSON.stringify(list);
    };

    var buildProjectList = function(list) {
        var i;
        for(i = 0 ; i < list.length; i++) {
            $('

'
                    + list[i].project
                    + '

').appendTo('ul#project_list');
            $('a#weinre_btn_' + list[i].project.replace(' ','')).toggle(function() {
                $(this).find('.ui-icon-weinre').css('background-image', 'url(images/weinreblue18x18.png)');
              }, function() {
                  $(this).find('.ui-icon-weinre').css('background-image', 'url(images/weinregrey18x18.png)');
              });
        }
        $('span#my_project_cnt').html(i + " Project" + ((i>1)? "s" : ""));
        $('div#project_list_container').removeClass('hidden');
        $('div#project_list_container').trigger('expand');
        $("ul#project_list").listview('refresh');
    };

    $('div#project_list_container').live('expand',function(){
        $('span#project_hint').html("Tap to Run; Toggle Weinre");
    });
    $('div#project_list_container').live('collapse',function(){
        $('span#project_hint').html("Expand to See Projects");
    });

    $('a#get_project_list').live('click', function() {
        var showedError = false;
        console.log("AppLaudLog: get_project_list click");
        $.ajax({ url : serverUrl + "/getProjects", data : {}, cache : false,
            beforeSend : function(jqXHR, settings) {
                    fadingMsg('Getting Project List..');
                    $('ul#project_list').empty();
            },
            success : function(r, textStatus) {
                if (r.success) {
                    // Always means list has at least 1 item
                    buildProjectList(r.list);
                    saveLocalProjectList(r.list);
                } else {
                    $('div#project_list_container').addClass('hidden');
                    saveLocalProjectList({});
                    if (r.error === 'Authentication failed. Please re-login.') {
                        navigator.notification.confirm(
                            r.error,
                            onLogin,
                            'Project List Refresh',
                            'Login,Close'
                        );
                    } else {
                        navigator.notification.alert(
                            r.error + " Create a project with New->Project in AppLaud Cloud.",
                            null,
                            'Project List Refresh',
                            'Close'
                        );
                    }
                }
            },
            error : function(jqXHR, textStatus, errorThrown) {
                $('div#project_list_container').addClass('hidden');
                saveLocalProjectList({});
                if (!showedError) {
                    var errormsg;
                    showedError = true;
                    if (errorThrown === '') {
                        errormsg = 'Check network connection.';
                    } else {
                        errormsg = errorThrown;
                    }
                    navigator.notification.alert(
                            'Error: ' + errormsg,
                            null,
                            'Project List Refresh',
                            'Close'
                          );
                    console.log('AppLaudLog: Get Projects returned with Error: ' + errormsg);
                    // no connection: error / blank
                }
            },
            complete : function(jqXHR, textStatus) {
                $('#fading_msg').remove();
                if ((!showedError) && textStatus === 'error') {
                    console.log('AppLaudLog: Get Projects completed with Error.');
                }
            }
        });
    });

    var apkUser, apkSession, apkMap;

    var buildApkList = function(apkList) {
        var i;
        apkMap = {};
        for(i = 0 ; i < apkList.length; i++) {
            var appName = apkList[i].appName;
            var fullPath = apkList[i].link;
            var buildType =
                fullPath.indexOf('-basic.apk') > 0 ? '[basic]' : fullPath.indexOf('-weinre.apk') > 0 ? '[weinre]' : '[release]';
            var id = appName + buildType;
            apkMap[id] = fullPath;
            $('

'
                    + appName + ' ' + buildType
                    + '

').appendTo('ul#apk_list');
        }
        $('span#my_apk_cnt').html(i + " APK" + ((i>1)? "s" : ""));
        $('div#apk_list_container').removeClass('hidden');
        $('div#apk_list_container').trigger('expand');
        $("ul#apk_list").listview('refresh');
    };

    $('a.apks').live('click', function() {
        var id = $(this).attr('id');
        window.plugins.childBrowser.openExternal(serverUrl + '/downloadApk' + '?file=' + apkMap[id] + '&user=' + apkUser + '&session=' + apkSession);
    });

    $('div#apk_list_container').live('expand',function(){
        $('#apk_hint').html("Tap to Download (Install, Run)");
    });
    $('div#apk_list_container').live('collapse',function(){
        $('#apk_hint').html("Expand to See APKs");
    });

    $('a#get_apk_list').click(function() {
        var showedError = false;
        console.log("AppLaudLog: get_apk_list");
        $.ajax({ url : serverUrl + "/getApks", data : {}, cache : false,
            beforeSend : function(jqXHR, settings) {
                fadingMsg('Getting APK List..');
                $('ul#apk_list').empty();
            },
            success : function(r, textStatus) {
                if (r.success) {
                    // Always means list has at least 1 item
                    buildApkList(r.list);
                    apkUser = r.user;
                    apkSession = r.session;
                } else {
                    $('div#apk_list_container').addClass('hidden');
                    if (r.error === 'Authentication failed. Please re-login.') {
                        navigator.notification.confirm(
                                r.error,
                                onLogin,
                                'APK List Refresh',
                                'Login,Close'
                        );
                    } else {
                        navigator.notification.alert(
                                'No APKs found. To build a project run Package->Build in AppLaud Cloud.',
                                null,
                                'APK List Refresh',
                                'Close'
                        );
                    }
                }
            },
            error : function(jqXHR, textStatus, errorThrown) {
                $('div#apk_list_container').addClass('hidden');
                if (!showedError) {
                    var errormsg;
                    if (errorThrown === '') { errormsg = 'Check network connection.'; }
                    else { errormsg =  errorThrown; }
                    alert('Get Apks Request returned with Error: ' + errormsg);
                    console.log('AppLaudLog: Get Apks returned with Error: ' + errormsg);
                    // no connection: error / blank
                    showedError = true;
                }
            },
            complete : function(jqXHR, textStatus) {
                $('#fading_msg').remove();
                if ((!showedError) && textStatus === 'error') {
                    console.log('AppLaudLog: Get Apks completed with Error.');
                }
            }
        });
    });
});<|endoftext|>


<commit_before>
const expect = require('chai').expect;
const RG = require('../../../client/src/battles');

describe('OverWorld.createOverWorld', function() {
    this.timeout(5000);

    it('can create an overworld with features', () => {
        const owConf = {
            owTilesX: 20,
            owTilesY: 10,
            worldX: 200,
            worldY: 100,
            nLevelsX: 4,
            nLevelsY: 2,
            areaX: 4,
            areaY: 2,
            nVWalls: [0.8]
        };
        const [world, worldConf] = RG.OverWorld.createOverWorld(owConf);
        expect(world).to.exist;
        expect(worldConf).to.exist;

        const area = worldConf.area[0];
        expect(area.nCities).to.be.above(5);
        expect(area.city.length).to.be.equal(area.nCities);
        expect(area.nDungeons).to.be.above(5);
    });
});
<commit_msg>Increased timeout for now.<commit_after>
const expect = require('chai').expect;
const RG = require('../../../client/src/battles');

describe('OverWorld.createOverWorld', function() {
    this.timeout(7000);

    it('can create an overworld with features', () => {
        const owConf = {
            owTilesX: 20,
            owTilesY: 10,
            worldX: 200,
            worldY: 100,
            nLevelsX: 4,
            nLevelsY: 2,
            areaX: 4,
            areaY: 2,
            nVWalls: [0.8]
        };
        const [world, worldConf] = RG.OverWorld.createOverWorld(owConf);
        expect(world).to.exist;
        expect(worldConf).to.exist;

        const area = worldConf.area[0];
        expect(area.nCities).to.be.above(5);
        expect(area.city.length).to.be.equal(area.nCities);
        expect(area.nDungeons).to.be.above(5);
    });
});
<|endoftext|>


<commit_before>import DS from 'ember-data';
import attr from 'ember-data/attr';
import { Projection } from 'ember-flexberry-data';

let Employee = Projection.Model.extend({
  'First Name': attr('string'),
  'Last Name': attr('string'),
  'Birth Date': attr('date'),
  Age: attr('number'),
  Name: attr('string'),
  Surname: attr('string'),
  CountryName: attr('string'),
  Price: attr('decimal'),
  Country: DS.belongsTo('country'),
  Creator: DS.belongsTo('creator'),
  Manager: DS.belongsTo('employee'),
  Tags: DS.hasMany('tag'),
  externalId: attr('guid')
});

Employee.defineProjection('EmployeeTestProjection', 'employee', {
  firstName: Projection.attr('First Name'),
  lastName: Projection.attr('Last Name'),
  birthDate: Projection.attr('Birth Date'),
  employee1: Projection.belongsTo('employee', 'Reports To', {
    firstName: Projection.attr('Reports To - First Name')
  }),
  tmpChildren: Projection.hasMany('employee', 'Tmp Children', {
    lastName: Projection.attr('Tmp Children - Last Name')
  })
});

export default Employee;
<commit_msg>Feature employee model add boolean attribute<commit_after>import DS from 'ember-data';
import attr from 'ember-data/attr';
import { Projection } from 'ember-flexberry-data';

let Employee = Projection.Model.extend({
  'First Name': attr('string'),
  'Last Name': attr('string'),
  'Birth Date': attr('date'),
  Age: attr('number'),
  Name: attr('string'),
  Surname: attr('string'),
  CountryName: attr('string'),
  Price: attr('decimal'),
  Active: attr('boolean'),
  Country: DS.belongsTo('country'),
  Creator: DS.belongsTo('creator'),
  Manager: DS.belongsTo('employee'),
  Tags: DS.hasMany('tag'),
  externalId: attr('guid')
});

Employee.defineProjection('EmployeeTestProjection', 'employee', {
  firstName: Projection.attr('First Name'),
  lastName: Projection.attr('Last Name'),
  birthDate: Projection.attr('Birth Date'),
  employee1: Projection.belongsTo('employee', 'Reports To', {
    firstName: Projection.attr('Reports To - First Name')
  }),
  tmpChildren: Projection.hasMany('employee', 'Tmp Children', {
    lastName: Projection.attr('Tmp Children - Last Name')
  })
});

export default Employee;
<|endoftext|>


<commit_before>/**
 *
 * Copyright 2015 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var gulp = require('gulp');
var del = require('del');
var runSequence = require('run-sequence');
var eslint = require('gulp-eslint');
var path = require('path');
var glob = require('glob');
var browserify = require('browserify');
var gutil = require('gulp-util');
var source = require('vinyl-source-stream');
var uglify = require('gulp-uglify');
var gulpif = require('gulp-if');
var streamify = require('gulp-streamify');
var replace = require('gulp-replace');
var license = require('gulp-license');
var sourcemaps = require('gulp-sourcemaps');
var rename = require('gulp-rename');

gulp.task('scripts:watch', function() {
  gulp.watch(GLOBAL.config.src + '/**/*.js', ['scripts']);
  gulp.watch('./.eslintrc', ['scripts']);
});

// Takes a set of objects defining inputs of javascript files
// to run through browserify and babelify
function compileES6Bundles(browserifyBundles, cb) {
  // Check if there is anything to do
  if (browserifyBundles.length === 0) {
    return cb();
  }

  var finishedCount = 0;
  browserifyBundles.forEach(function(bundle) {
    var browserifyBundle = browserify({
      entries: [bundle.srcPath]
    })
    .transform('babelify', {presets: ['es2015']});

    return browserifyBundle.bundle()
      .on('log', gutil.log.bind(gutil, 'Browserify Log'))
      .on('error', gutil.log.bind(gutil, 'Browserify Error'))
      .pipe(source(bundle.outputFilename))
      .pipe(replace(/@VERSION@/g, GLOBAL.config.version))

      // If this is a production build - minify JS
      .pipe(gulpif(GLOBAL.config.env === 'prod', streamify(uglify())))
      .pipe(license(GLOBAL.config.license, GLOBAL.config.licenseOptions))
      .pipe(gulp.dest(bundle.dest))
      .on('end', function() {
        finishedCount++;

        if (finishedCount === browserifyBundles.length) {
          cb();
        }
      });
  });
}

// This takes a source path and finds all files ending
// with .es6.js and creates the bundles to run through browserify
// and babelify
function generateES6Bundles(srcPath, cb) {
  if (!srcPath) {
    return cb(new Error('Invalid source path given to generateES6Bundles'));
  }

  var es6Filepaths = glob.sync(srcPath + '/**/*.es6.js');

  var browserifyBundles = [];
  es6Filepaths.forEach(function(filepath) {
    var filename = path.basename(filepath);
    var directoryOfFile = path.dirname(filepath);
    var relativeDirectory = path.relative(
      srcPath,
      directoryOfFile);

    // Replace .es6.js with .js for the final output
    var outputFilename =
      filename.substring(0, filename.length - '.es6.js'.length) + '.js';

    browserifyBundles.push({
      srcPath: './' + filepath,
      outputFilename: outputFilename,
      dest: path.join(GLOBAL.config.dest, relativeDirectory)
    });
  });

  compileES6Bundles(browserifyBundles, cb);
}

gulp.task('scripts:eslint', function() {
  return gulp.src([GLOBAL.config.src + '/**/*.js'])

    // eslint() attaches the lint output to the eslint property,
    // of the file object so it can be used by other modules.
    .pipe(eslint())

    // eslint.format() outputs the lint results to the console.
    // Alternatively use eslint.formatEach() (see Docs).
    .pipe(eslint.format())

    // To have the process exit with an error code (1) on
    // lint error, return the stream and pipe to failOnError last.
    .pipe(gulpif(GLOBAL.config.env === 'prod', eslint.failOnError()));
});

gulp.task('scripts:es6', function(cb) {
  generateES6Bundles(GLOBAL.config.src, cb);
});

gulp.task('scripts:es5', function() {
  return gulp.src([GLOBAL.config.src + '/**/*.es5.js'])
    .pipe(gulpif(GLOBAL.config.env !== 'prod', sourcemaps.init()))

    // Remove the .es5 from the end of the file name using gulp-rename
    .pipe(rename(function(filePath) {
      var fileExtensionLength = '.es5'.length;
      filePath.basename = filePath.basename.substr(
        0, filePath.basename.length - fileExtensionLength);
    }))

    .pipe(replace(/@VERSION@/g, GLOBAL.config.version))
    .pipe(gulpif(GLOBAL.config.env === 'prod', uglify()))
    .pipe(license(GLOBAL.config.license, GLOBAL.config.licenseOptions))
    .pipe(gulpif(GLOBAL.config.env !== 'prod', sourcemaps.write()))
    .pipe(gulp.dest(GLOBAL.config.dest));
});

// Delete any files currently in the scripts destination path
gulp.task('scripts:clean', function(cb) {
  del([GLOBAL.config.dest + '/**/*.js'], {dot: true})
    .then(function() {
      cb();
    });
});

gulp.task('scripts', function(cb) {
  runSequence(
    [
      'scripts:clean',
      'scripts:eslint'
    ],
    [
      'scripts:es6',
      'scripts:es5'
    ],
    cb
  );
});
<commit_msg>No longer stop working when browserify throws an error<commit_after>/**
 *
 * Copyright 2015 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var gulp = require('gulp');
var del = require('del');
var runSequence = require('run-sequence');
var eslint = require('gulp-eslint');
var path = require('path');
var glob = require('glob');
var browserify = require('browserify');
var gutil = require('gulp-util');
var source = require('vinyl-source-stream');
var uglify = require('gulp-uglify');
var gulpif = require('gulp-if');
var streamify = require('gulp-streamify');
var replace = require('gulp-replace');
var license = require('gulp-license');
var sourcemaps = require('gulp-sourcemaps');
var rename = require('gulp-rename');

gulp.task('scripts:watch', function() {
  gulp.watch(GLOBAL.config.src + '/**/*.js', ['scripts']);
  gulp.watch(['./.eslintrc', './.eslintignore'], ['scripts']);
});

// Takes a set of objects defining inputs of javascript files
// to run through browserify and babelify
function compileES6Bundles(browserifyBundles, cb) {
  // Check if there is anything to do
  if (browserifyBundles.length === 0) {
    return cb();
  }

  var finishedCount = 0;
  browserifyBundles.forEach(function(bundle) {
    var browserifyBundle = browserify({
      entries: [bundle.srcPath]
    })
    .transform('babelify', {presets: ['es2015']});

    try {
      return browserifyBundle.bundle()
        .on('log', gutil.log.bind(gutil, 'Browserify Log'))
        .on('error', function(err) {
          gutil.log('Browserify Error', err);
          this.emit('end');
        })
        .pipe(source(bundle.outputFilename))
        .pipe(replace(/@VERSION@/g, GLOBAL.config.version))

        // If this is a production build - minify JS
        .pipe(gulpif(GLOBAL.config.env === 'prod', streamify(uglify())))
        .pipe(license(GLOBAL.config.license, GLOBAL.config.licenseOptions))
        .pipe(gulp.dest(bundle.dest))
        .on('end', function() {
          finishedCount++;

          if (finishedCount === browserifyBundles.length) {
            cb();
          }
        });
    } catch (exception) {
      console.log(exception);
    }
  });
}

// This takes a source path and finds all files ending
// with .es6.js and creates the bundles to run through browserify
// and babelify
function generateES6Bundles(srcPath, cb) {
  if (!srcPath) {
    return cb(new Error('Invalid source path given to generateES6Bundles'));
  }

  var es6Filepaths = glob.sync(srcPath + '/**/*.es6.js');

  var browserifyBundles = [];
  es6Filepaths.forEach(function(filepath) {
    var filename = path.basename(filepath);
    var directoryOfFile = path.dirname(filepath);
    var relativeDirectory = path.relative(
      srcPath,
      directoryOfFile);

    // Replace .es6.js with .js for the final output
    var outputFilename =
      filename.substring(0, filename.length - '.es6.js'.length) + '.js';

    browserifyBundles.push({
      srcPath: './' + filepath,
      outputFilename: outputFilename,
      dest: path.join(GLOBAL.config.dest, relativeDirectory)
    });
  });

  compileES6Bundles(browserifyBundles, cb);
}

gulp.task('scripts:eslint', function() {
  return gulp.src([GLOBAL.config.src + '/**/*.js'])

    // eslint() attaches the lint output to the eslint property,
    // of the file object so it can be used by other modules.
    .pipe(eslint())

    // eslint.format() outputs the lint results to the console.
    // Alternatively use eslint.formatEach() (see Docs).
    .pipe(eslint.format())

    // To have the process exit with an error code (1) on
    // lint error, return the stream and pipe to failOnError last.
    .pipe(gulpif(GLOBAL.config.env === 'prod', eslint.failOnError()));
});

gulp.task('scripts:es6', function(cb) {
  generateES6Bundles(GLOBAL.config.src, cb);
});

gulp.task('scripts:es5', function() {
  return gulp.src([GLOBAL.config.src + '/**/*.es5.js'])
    .pipe(gulpif(GLOBAL.config.env !== 'prod', sourcemaps.init()))

    // Remove the .es5 from the end of the file name using gulp-rename
    .pipe(rename(function(filePath) {
      var fileExtensionLength = '.es5'.length;
      filePath.basename = filePath.basename.substr(
        0, filePath.basename.length - fileExtensionLength);
    }))

    .pipe(replace(/@VERSION@/g, GLOBAL.config.version))
    .pipe(gulpif(GLOBAL.config.env === 'prod', uglify()))
    .pipe(license(GLOBAL.config.license, GLOBAL.config.licenseOptions))
    .pipe(gulpif(GLOBAL.config.env !== 'prod', sourcemaps.write()))
    .pipe(gulp.dest(GLOBAL.config.dest));
});

// Delete any files currently in the scripts destination path
gulp.task('scripts:clean', function(cb) {
  del([GLOBAL.config.dest + '/**/*.js'], {dot: true})
    .then(function() {
      cb();
    });
});

gulp.task('scripts', function(cb) {
  runSequence(
    [
      'scripts:clean',
      'scripts:eslint'
    ],
    [
      'scripts:es6',
      'scripts:es5'
    ],
    cb
  );
});
<|endoftext|>


<commit_before>'use strict';

import gulp     from 'gulp';
import gulplog  from 'gulplog';
import notifier from 'node-notifier';
import uglify   from 'uglifyjs-webpack-plugin';
import webpack  from 'webpack';
import path     from 'path';
import {paths, plugins, config} from '../config';

gulp.task('build:js', (callback) => {

  let options = {
    entry: path.resolve(paths.source.files.mainJS),
    output: {
      path: path.resolve(paths.dest.folders.scripts),
      filename: config.isDevelop ? 'build.js' : 'build.min.js'
    },
    watch: config.isDevelop,
    module: {
      loaders: [{
        test: /\.js$/,
        use: [
          { loader: 'ng-annotate-loader' },
          { loader: 'babel-loader' }
        ]
      }]
    },
    plugins: []
  };

  if (!config.isDevelop) options.plugins.push( new uglify() );

  webpack(options, (err, stats) => {
    if (!err) err = stats.toJson().errors[0];

    if (err) {
      notifier.notify({
        title: 'webpack',
        message: err
      });

      gulplog.error(err);
    } else {
      gulplog.info(stats.toString({colors: true}));
    }

    if (!options.watch && err) {
      callback(err);
    } else {
      callback();
    }
  });

});<commit_msg>Переработал таск build:js<commit_after>'use strict';

import gulp     from 'gulp';
import gulplog  from 'gulplog';
import notifier from 'node-notifier';
import uglify   from 'uglifyjs-webpack-plugin';
import webpack  from 'webpack';
import path     from 'path';
import {paths, plugins, config} from '../config';

const scripts = {
  test: /\.js$/,
  loader: 'ng-annotate-loader!babel-loader'
};

const templates = {
  test: /\.pug$/,
  loader: 'ngtemplate-loader!html-loader!pug-html-loader'
}

gulp.task('build:js', (callback) => {

  let options = {
    entry: path.resolve(paths.source.files.mainJS),
    output: {
      path: path.resolve(paths.dest.folders.scripts),
      filename: config.isDevelop ? 'build.js' : 'build.min.js'
    },
    devtool: (config.isDevelop ? 'eval' : false),
    watch: config.isDevelop,
    module: {loaders: [scripts, templates]},
    plugins: []
  };

  if (!config.isDevelop) options.plugins.push(new uglify());

  runWebpack(options, callback);

});

function runWebpack(options, callback) {

  webpack(options, (err, stats) => {
    if (!err) err = stats.toJson().errors[0];

    if (err) {
      notifier.notify({
        title: 'webpack',
        message: err
      });
      gulplog.error(err);
    } else {
      gulplog.info(stats.toString({colors: true}));
    }

    if (!options.watch && err) {
      callback(err);
    } else {
      callback();
    }
  });

}<|endoftext|>


<commit_before>/*globals Handlebars, moment, jQuery */

(function($) {
  // Get the current url
  Handlebars.registerHelper('windowLocation', function(place_id) {
    return window.location;
  });

  // Change new lines to
 tags. This one is better than Swag.
  Handlebars.registerHelper('nlToBr', function(str) {
    if (str) {
      str = Handlebars.Utils.escapeExpression(str);
      return new Handlebars.SafeString(str.replace(/\r?\n|\r/g, '
'));
    } else {
      return str;
    }
  });

  // Date and time ------------------------------------------------------------
  Handlebars.registerHelper('formatDateTime', function(datetime, format) {
    if (datetime) {
      return moment(datetime).format(format);
    }
    return '';
  });

  Handlebars.registerHelper('fromNow', function(datetime) {
    if (datetime) {
      return moment(datetime).fromNow();
    }
    return '';
  });

  // Iteration ----------------------------------------------------------------
  Handlebars.registerHelper('times', function(n, options) {
    var accum = '', i;
    for(i = 0; i < n; ++i){
      accum += options.fn(i);
    }
    return accum;
  });

  Handlebars.registerHelper('range', function(from, to, options) {
    // Range is INCLUSIVE of the ends. Useful for things like
    // pagination links.
    var accum = '', i;
    for(i = from; i <= to; i++){
      accum += options.fn(i);
    }
    return accum;
  });

  // HTML ---------------------------------------------------------------------
  Handlebars.registerHelper('select', function(value, options) {
    var $el = $('
').html(options.fn(this)),
      selectValue = function(v) {
        $el.find('[value="'+v+'"]').attr({
          checked: 'checked',
          selected: 'selected'
        });
      };

    if ($.isArray(value)) {
      jQuery.each(function(i, v) {
        selectValue(v);
      });
    } else {
      selectValue(value);
    }

    return $el.html();
  });

}(jQuery));<commit_msg>Add missing `$.each` parameter in `select` helper<commit_after>/*globals Handlebars, moment, jQuery */

(function($) {
  // Get the current url
  Handlebars.registerHelper('windowLocation', function(place_id) {
    return window.location;
  });

  // Change new lines to
 tags. This one is better than Swag.
  Handlebars.registerHelper('nlToBr', function(str) {
    if (str) {
      str = Handlebars.Utils.escapeExpression(str);
      return new Handlebars.SafeString(str.replace(/\r?\n|\r/g, '
'));
    } else {
      return str;
    }
  });

  // Date and time ------------------------------------------------------------
  Handlebars.registerHelper('formatDateTime', function(datetime, format) {
    if (datetime) {
      return moment(datetime).format(format);
    }
    return '';
  });

  Handlebars.registerHelper('fromNow', function(datetime) {
    if (datetime) {
      return moment(datetime).fromNow();
    }
    return '';
  });

  // Iteration ----------------------------------------------------------------
  Handlebars.registerHelper('times', function(n, options) {
    var accum = '', i;
    for(i = 0; i < n; ++i){
      accum += options.fn(i);
    }
    return accum;
  });

  Handlebars.registerHelper('range', function(from, to, options) {
    // Range is INCLUSIVE of the ends. Useful for things like
    // pagination links.
    var accum = '', i;
    for(i = from; i <= to; i++){
      accum += options.fn(i);
    }
    return accum;
  });

  // HTML ---------------------------------------------------------------------
  Handlebars.registerHelper('select', function(value, options) {
    var $el = $('
').html(options.fn(this)),
      selectValue = function(v) {
        $el.find('[value="'+v+'"]').attr({
          checked: 'checked',
          selected: 'selected'
        });
      };

    if ($.isArray(value)) {
      jQuery.each(value, function(i, v) {
        selectValue(v);
      });
    } else {
      selectValue(value);
    }

    return $el.html();
  });

}(jQuery));
<|endoftext|>