<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2016, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* 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.                                             */
/* -------------------------------------------------------------------------- */

define(function(require) {
  require('jquery');
  require('foundation');

  Foundation.Dropdown.defaults.positionClass = 'left';
  Foundation.Dropdown.defaults.closeOnClick = true;
  Foundation.DropdownMenu.defaults.closeOnClick = true;
  Foundation.DropdownMenu.defaults.disableHover = true;
  Foundation.DropdownMenu.defaults.clickOpen = true;

  var DASHBOARD_TAB_ID = require('tabs/dashboard-tab/tabId');
  var SETTINGS_TAB_ID = require('tabs/settings-tab/tabId');
  var PROVISION_TAB_ID = require('tabs/provision-tab/tabId');
  var Sunstone = require('sunstone');
  var Config = require('sunstone-config');
  var OpenNebula = require('opennebula');
  var Notifier = require('utils/notifier');
  var Menu = require('utils/menu');
  var Locale = require('utils/locale');

  var UserAndZoneTemplate = require('hbs!sunstone/user_and_zone');

  var _commonDialogs = [
    require('utils/dialogs/confirm'),
    require('utils/dialogs/confirm-with-select'),
    require('utils/dialogs/generic-confirm'),
    require('utils/dialogs/clusters'),
    require('utils/dialogs/overcommit')
  ]

  //$(window).load(function() {
  //   $('#loading').hide();
  //});

  $(document).ready(function() {
    Sunstone.addDialogs(_commonDialogs);
    Sunstone.addMainTabs();
    Sunstone.insertTabs();

    if (Config.isTabEnabled(PROVISION_TAB_ID)){
      Menu.insertProvision();
    }else{
      Menu.insert();
    }

    _setupAccordion();
    _setupCloseDropdownsOnClick();
    _insertUserAndZoneSelector();

    if (Config.isTabEnabled(PROVISION_TAB_ID)) {
      Sunstone.showTab(PROVISION_TAB_ID);
      $('#loading').hide();
    } else if (Config.isTabEnabled(DASHBOARD_TAB_ID)) {
      Sunstone.showTab(DASHBOARD_TAB_ID);
      $('#loading').hide();
    }
  });

  function _setupCloseDropdownsOnClick() {
    $(document).on("click", '.is-dropdown-submenu-item > a', function() {
      $('.is-active > a', $(this).closest('.dropdown')).trigger('click');
    });
  }

  function _setupAccordion() {
    $(document).on("click", ".accordion_advanced_toggle", function() {
      if ($(this).hasClass("active")) {
        $(this).removeClass("active");
      } else {
        $(this).addClass("active");
      }

      $(".content", $(this).closest(".accordion_advanced")).toggle();

      return false;
    })
  }

  function _insertUserAndZoneSelector() {
    $(".user-zone-info").html(UserAndZoneTemplate({
      displayName: config['display_name'],
      settingsTabEnabled: Config.isTabEnabled(SETTINGS_TAB_ID),
      availableViews: config['available_views'],
      zoneName: config['zone_name']
    })).foundation();

    $('.quickconf_view[view="' + config['user_config']["default_view"] + '"] i').addClass('fa-check');
    $(".user-zone-info a.quickconf_view_header").click(function() {
      var context = $(this).closest('ul');
      $(".quickconf_view", context).toggle();

      return false;
    });

    $(".user-zone-info a.quickconf_view").click(function() {
      var sunstone_setting = {DEFAULT_VIEW : $(this).attr("view")};
      Sunstone.runAction("User.append_sunstone_setting_refresh", -1, sunstone_setting);
    });

    function zoneRefresh() {
      // Populate Zones dropdown
      OpenNebula.Zone.list({
        timeout: true,
        success: function (request, obj_list) {
          $('.zone-ul').empty();
          $.each(obj_list, function() {
            var icon;

            if(this.ZONE.NAME == config['zone_name']){
              icon = ''
            } else {
              icon = ''
            }

            $('.zone-ul').append('
' +
              '' + icon + ' ' + this.ZONE.NAME + '
');
          });
        },
        error: Notifier.onError
      });
    }

    $('#zonelector').on("click", function() {
      zoneRefresh();
    });

    $(".user-zone-info").on("click", 'a.zone-choice', function() {
       $.ajax({
         url: 'config',
         type: "GET",
         headers: {
           "ZONE_NAME" : this.id
         },
         dataType: "json",
         success: function() {
           window.location.href = ".";
         },
         error: function(response) {
           Notifier.onError(null, OpenNebula.Error(response))
         }
       });
     });

    $("a.logout", $(".user-zone-info ")).click(function() {
      OpenNebula.Auth.logout({
          success: function() {
            window.location.href = "login";
          },
          error: Notifier.onError
        });

      return false;
    });

    $(".user-zone-info a.configuration").click(function() {
      //$(document).foundation('dropdown', 'closeall');
      Sunstone.showTab(SETTINGS_TAB_ID);
    });
  }
});
<commit_msg>Bug #4606: Fix modal windows closing with dataTable pagination buttons<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2016, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* 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.                                             */
/* -------------------------------------------------------------------------- */

define(function(require) {
  require('jquery');
  require('foundation');

  Foundation.Dropdown.defaults.positionClass = 'left';
  Foundation.Dropdown.defaults.closeOnClick = true;
  Foundation.DropdownMenu.defaults.closeOnClick = true;
  Foundation.DropdownMenu.defaults.disableHover = true;
  Foundation.DropdownMenu.defaults.clickOpen = true;
  Foundation.Reveal.defaults.closeOnClick = false;

  var DASHBOARD_TAB_ID = require('tabs/dashboard-tab/tabId');
  var SETTINGS_TAB_ID = require('tabs/settings-tab/tabId');
  var PROVISION_TAB_ID = require('tabs/provision-tab/tabId');
  var Sunstone = require('sunstone');
  var Config = require('sunstone-config');
  var OpenNebula = require('opennebula');
  var Notifier = require('utils/notifier');
  var Menu = require('utils/menu');
  var Locale = require('utils/locale');

  var UserAndZoneTemplate = require('hbs!sunstone/user_and_zone');

  var _commonDialogs = [
    require('utils/dialogs/confirm'),
    require('utils/dialogs/confirm-with-select'),
    require('utils/dialogs/generic-confirm'),
    require('utils/dialogs/clusters'),
    require('utils/dialogs/overcommit')
  ]

  //$(window).load(function() {
  //   $('#loading').hide();
  //});

  $(document).ready(function() {
    Sunstone.addDialogs(_commonDialogs);
    Sunstone.addMainTabs();
    Sunstone.insertTabs();

    if (Config.isTabEnabled(PROVISION_TAB_ID)){
      Menu.insertProvision();
    }else{
      Menu.insert();
    }

    _setupAccordion();
    _setupCloseDropdownsOnClick();
    _insertUserAndZoneSelector();

    if (Config.isTabEnabled(PROVISION_TAB_ID)) {
      Sunstone.showTab(PROVISION_TAB_ID);
      $('#loading').hide();
    } else if (Config.isTabEnabled(DASHBOARD_TAB_ID)) {
      Sunstone.showTab(DASHBOARD_TAB_ID);
      $('#loading').hide();
    }
  });

  function _setupCloseDropdownsOnClick() {
    $(document).on("click", '.is-dropdown-submenu-item > a', function() {
      $('.is-active > a', $(this).closest('.dropdown')).trigger('click');
    });
  }

  function _setupAccordion() {
    $(document).on("click", ".accordion_advanced_toggle", function() {
      if ($(this).hasClass("active")) {
        $(this).removeClass("active");
      } else {
        $(this).addClass("active");
      }

      $(".content", $(this).closest(".accordion_advanced")).toggle();

      return false;
    })
  }

  function _insertUserAndZoneSelector() {
    $(".user-zone-info").html(UserAndZoneTemplate({
      displayName: config['display_name'],
      settingsTabEnabled: Config.isTabEnabled(SETTINGS_TAB_ID),
      availableViews: config['available_views'],
      zoneName: config['zone_name']
    })).foundation();

    $('.quickconf_view[view="' + config['user_config']["default_view"] + '"] i').addClass('fa-check');
    $(".user-zone-info a.quickconf_view_header").click(function() {
      var context = $(this).closest('ul');
      $(".quickconf_view", context).toggle();

      return false;
    });

    $(".user-zone-info a.quickconf_view").click(function() {
      var sunstone_setting = {DEFAULT_VIEW : $(this).attr("view")};
      Sunstone.runAction("User.append_sunstone_setting_refresh", -1, sunstone_setting);
    });

    function zoneRefresh() {
      // Populate Zones dropdown
      OpenNebula.Zone.list({
        timeout: true,
        success: function (request, obj_list) {
          $('.zone-ul').empty();
          $.each(obj_list, function() {
            var icon;

            if(this.ZONE.NAME == config['zone_name']){
              icon = ''
            } else {
              icon = ''
            }

            $('.zone-ul').append('
' +
              '' + icon + ' ' + this.ZONE.NAME + '
');
          });
        },
        error: Notifier.onError
      });
    }

    $('#zonelector').on("click", function() {
      zoneRefresh();
    });

    $(".user-zone-info").on("click", 'a.zone-choice', function() {
       $.ajax({
         url: 'config',
         type: "GET",
         headers: {
           "ZONE_NAME" : this.id
         },
         dataType: "json",
         success: function() {
           window.location.href = ".";
         },
         error: function(response) {
           Notifier.onError(null, OpenNebula.Error(response))
         }
       });
     });

    $("a.logout", $(".user-zone-info ")).click(function() {
      OpenNebula.Auth.logout({
          success: function() {
            window.location.href = "login";
          },
          error: Notifier.onError
        });

      return false;
    });

    $(".user-zone-info a.configuration").click(function() {
      //$(document).foundation('dropdown', 'closeall');
      Sunstone.showTab(SETTINGS_TAB_ID);
    });
  }
});
<|endoftext|>


<commit_before>$(document).ready(function() {
	var arr = $("#carousel > div");

	var curr = 0;

	$($("#carousel > div").get((arr.length+curr-1) % arr.length)).switchClass("carousel-img", "outfocus-left");
	$($("#carousel > div").get(curr)).switchClass("carousel-img", "focus");
	$($("#carousel > div").get((arr.length+curr+1) % arr.length)).switchClass("carousel-img", "outfocus-right");

	var loopFunc = function() {
		//$("#carousel > div").each(function(index, elem) {
/*		for(var i = 0; i < $("#carousel > div").length; i++) {
			switch ($($("#carousel > div").get(i)).attr('class')) {
				case "focus":
					$($("#carousel > div").get(i)).switchClass("focus", "outfocus-left");
					break;
				case "outfocus-left":
					$($("#carousel > div").get(i)).switchClass("outfocus-left", "carousel-img");
					break;
				case "outfocus-right":
					$($("#carousel > div").get(i)).switchClass("outfocus-right", "focus");
					break;
				default:
					if(i == curr) {
						$($("#carousel > div").get(i)).switchClass("carousel-img", "outfocus-right");
					}
			}

		}//);*/
		$($("#carousel > div").get((arr.length+curr-1) % arr.length)).switchClass("outfocus-left", "carousel-img");
		$($("#carousel > div").get(curr)).switchClass("focus", "outfocus-left");
		$($("#carousel > div").get((arr.length+curr+1) % arr.length)).switchClass("outfocus-right", "focus");
		$($("#carousel > div").get((arr.length+curr+2) % arr.length)).switchClass("carousel-img", "outfocus-right");

		curr++;
		if(curr >= arr.length) {
			curr = curr % arr.length
		}
	}

	setInterval(loopFunc, 7500);
});<commit_msg>Carousel now starts at a random picture, not the same one each time.<commit_after>$(document).ready(function() {
	var arr = $("#carousel > div");

	var curr = Math.floor((Math.random() * arr.length))

	$($("#carousel > div").get((arr.length+curr-1) % arr.length)).switchClass("carousel-img", "outfocus-left");
	$($("#carousel > div").get(curr)).switchClass("carousel-img", "focus");
	$($("#carousel > div").get((arr.length+curr+1) % arr.length)).switchClass("carousel-img", "outfocus-right");

	var loopFunc = function() {
		//$("#carousel > div").each(function(index, elem) {
/*		for(var i = 0; i < $("#carousel > div").length; i++) {
			switch ($($("#carousel > div").get(i)).attr('class')) {
				case "focus":
					$($("#carousel > div").get(i)).switchClass("focus", "outfocus-left");
					break;
				case "outfocus-left":
					$($("#carousel > div").get(i)).switchClass("outfocus-left", "carousel-img");
					break;
				case "outfocus-right":
					$($("#carousel > div").get(i)).switchClass("outfocus-right", "focus");
					break;
				default:
					if(i == curr) {
						$($("#carousel > div").get(i)).switchClass("carousel-img", "outfocus-right");
					}
			}

		}//);*/
		$($("#carousel > div").get((arr.length+curr-1) % arr.length)).switchClass("outfocus-left", "carousel-img");
		$($("#carousel > div").get(curr)).switchClass("focus", "outfocus-left");
		$($("#carousel > div").get((arr.length+curr+1) % arr.length)).switchClass("outfocus-right", "focus");
		$($("#carousel > div").get((arr.length+curr+2) % arr.length)).switchClass("carousel-img", "outfocus-right");

		curr++;
		if(curr >= arr.length) {
			curr = curr % arr.length
		}
	}

	setInterval(loopFunc, 7500);
});<|endoftext|>


<commit_before>(function($){

    define("ace/mode/animo", function(require, exports, module) {

        var oop = require("pilot/oop");
        var TextMode = require("ace/mode/text").Mode;
        var Tokenizer = require("ace/tokenizer").Tokenizer;
        var AnimoHighlightRules = require("ace/mode/animo_highlight_rules").AnimoHighlightRules;

        var Mode = function() {
            this.$tokenizer = new Tokenizer(new AnimoHighlightRules().getRules());
        };
        oop.inherits(Mode, TextMode);

        (function() {
            // Extra logic goes here. (see below)
        }).call(Mode.prototype);

        exports.Mode = Mode;

    });

    define('ace/mode/animo_highlight_rules', function(require, exports, module) {

        var oop = require("pilot/oop");
        var lang = require("pilot/lang");
        var TextHighlightRules = require("ace/mode/text_highlight_rules").TextHighlightRules;

        var AnimoHighlightRules = function() {

            var operators = lang.arrayToMap(
                ("the an any ~ all ~~ prefer get <~~ this ?is ?has each " +
                 "use weak-use with eq gt ge lt le ne not and or id 's " +
                 "add delete set replace -> --> value qname ptrn").split(" ")
            );

            var ml = lang.arrayToMap(
                ("\\ @ $ !-- !! [!CDATA[ ?? &# ").split(" ")
            );

            var prefix = lang.arrayToMap(
                ("\\ @ $ &# ").split(" ")
            );

            var suffix = lang.arrayToMap(
                ("'s ").split(" ")
            );

            this.$rules = {
                "start" : [
                    {
                        token : "constant.language",
                        regex : "\\(|\\)|,"
                    }, {
                        token : "constant.numeric", // hex
                        regex : "0[xX][0-9a-fA-F]+\\b"
                    }, {
                        token : "constant.numeric", // float
                        regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
                    }, {
                        token : function(value) {
                            if (operators.hasOwnProperty(value))
                                return "keyword";
                            else if (
                                        ml.hasOwnProperty(value) ||
                                        prefix.hasOwnProperty(value[0]) ||
                                        prefix.hasOwnProperty(value.substr(0, 2))
                                    )
                                return "constant.language";
                            else
                                return "identifier";
                        },
                        regex : '[^,."\\s\\(\\)]+'
                    }, {
                        token : "string",
                        regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
                    }
                ]
            };

        }

        oop.inherits(AnimoHighlightRules, TextHighlightRules);
        exports.AnimoHighlightRules = AnimoHighlightRules;

    });

    var strip, sinput;

    if (window.MozWebSocket) {
        window.WebSocket = window.MozWebSocket;
    }

    window.addEventListener('popstate', function(event){
        select(event.state);
    }, false);

    var uri = "ws://" + window.location.host + "/ws";

    var socket = new WebSocket(uri, "src");
    socket.onmessage = function (event) {
        var id = title(event.data);
        var tab = search(id);
        if (tab.length == 0) {
            append(id, event.data);
        } else {
            strip.select(tab);
        }
    };
    socket.onopen = function (event) {
        var id = window.location.hash.substr(1);
        socket.send(id == "" ? "new" : id);
        onopen(event);
    };

    function onopen(event) {
        setInterval(function() {
              event.target.send("");
        }, 5 * 60 * 1000);
    }

    function open(id) {
        socket.send(id);
    }

    function select(id) {
        var tab = search(id)
        if (tab.length == 0) {
            open(id);
        } else {
            strip.select(tab);
            tab[0].editor.focus();
        }
    }

    var AnimoMode = require("ace/mode/animo").Mode;
    var commands = require("pilot/canon");

    commands.addCommand({
        name: 'save',
        bindKey: {
            win: 'Ctrl-S',
            mac: 'Command-S',
            sender: 'editor'
        },
        exec: function(env, args, request) {
            var tab = strip.select()[0];
            tab.socket.send(tab.editor.getSession().getValue());
        }
    });

    commands.addCommand({
        name: 'close',
        bindKey: {
            win: 'Ctrl-W',
            mac: 'Command-W',
            sender: 'editor'
        },
        exec: function(env, args, request) {
            var tab = strip.select();
            window.history.back();
            tab[0].socket.close();
            strip.remove(tab);
        }
    });

    commands.addCommand({
        name: 'open',
        bindKey: {
            win: 'Ctrl-O',
            mac: 'Command-O',
            sender: 'editor'
        },
        exec: function(env, args, request) {
            sinput.focus();
        }
    });

    commands.addCommand({
        name: 'lookup',
        bindKey: {
            win: 'Ctrl-B',
            mac: 'Command-B',
            sender: 'editor'
        },
        exec: function(env, args, request) {
            var tab = strip.select()[0];
            var pos = tab.editor.getCursorPosition();
            var token = tab.editor.getSession().bgTokenizer.lines[pos.row].tokens;
            var t = 0, n = 0, s = 0;
            for (var i = 0; i < token.length; i++) {
                n += token[i].value.length;
                if (n > pos.column) {
                    t = i;
                    break;
                }
                s = n;
            }
            if (t > 0 && s == pos.column && token[t].type != "identifier") {
                t--;
            }
            if (token[t].type == "identifier") {
                select(token[t].value);
            }
        }
    });

    function title(data) {
        return data.split("\n")[0].split(" ")[1].split(".")[0];
    }

    function search(title) {
        return strip.tabGroup.children("#"+title);
    }

    function push(id) {
        window.history.pushState(id, null, window.location.pathname + "#" + id);
    }

    function append(id, content) {
        push(id);
        strip.append([{text : id}]);
        var tab = strip.tabGroup.children("li").last().attr({id : id});
        strip.select(tab);
        var editor = ace.edit(
            $(strip.contentElement(tab.index())).css({
                position : "absolute",
                top : 36, right : 0, bottom : 0, left : 0,
                padding : 0, overflow : "hidden"
            }).html("

").children().css({
                position : "absolute",
                top : 4, right : 4, bottom : 4, left : 4,
                overflow : "hidden"
            }).get(0)
        );
        editor.getSession().setMode(new AnimoMode());
        editor.getSession().setValue(content);
        editor.focus();
        var socket = new WebSocket(uri, "save");
        socket.onmessage = function (event) {
            var id = title(event.data);
            tab.attr({id : id});
            tab.children("span").text(id);
            editor.getSession().setValue(event.data);
        };
        socket.onopen = onopen;
        tab[0].socket = socket;
        tab[0].editor = editor;
    }

    $.fn.ideEditor = function() {
        strip = $(this).kendoTabStrip({
            animation : {
                open : {
                    effects: "none"
                }
            },
            select : function(tab) {
                push($(tab.item).attr("id"));
                tab.item.editor.focus();
            }
        }).data("kendoTabStrip");
        return strip;
    };

    $.fn.ideSearch = function () {
        sinput = $(this)
        sinput.keypress(function(event) {
            if (event.which == 13) {
                select($(event.target).val());
            } else if (event.which == 0) {
                strip.select()[0].editor.focus();
            }
        });
        return sinput;
    };

})(jQuery);
<commit_msg>bugfix<commit_after>(function($){

    define("ace/mode/animo", function(require, exports, module) {

        var oop = require("pilot/oop");
        var TextMode = require("ace/mode/text").Mode;
        var Tokenizer = require("ace/tokenizer").Tokenizer;
        var AnimoHighlightRules = require("ace/mode/animo_highlight_rules").AnimoHighlightRules;

        var Mode = function() {
            this.$tokenizer = new Tokenizer(new AnimoHighlightRules().getRules());
        };
        oop.inherits(Mode, TextMode);

        (function() {
            // Extra logic goes here. (see below)
        }).call(Mode.prototype);

        exports.Mode = Mode;

    });

    define('ace/mode/animo_highlight_rules', function(require, exports, module) {

        var oop = require("pilot/oop");
        var lang = require("pilot/lang");
        var TextHighlightRules = require("ace/mode/text_highlight_rules").TextHighlightRules;

        var AnimoHighlightRules = function() {

            var operators = lang.arrayToMap(
                ("the an any ~ all ~~ prefer get <~~ this ?is ?has each " +
                 "use weak-use with eq gt ge lt le ne not and or id 's " +
                 "add delete set replace -> --> value qname ptrn").split(" ")
            );

            var ml = lang.arrayToMap(
                ("\\ @ $ !-- !! [!CDATA[ ?? &# ").split(" ")
            );

            var prefix = lang.arrayToMap(
                ("\\ @ $ &# ").split(" ")
            );

            var suffix = lang.arrayToMap(
                ("'s ").split(" ")
            );

            this.$rules = {
                "start" : [
                    {
                        token : "constant.language",
                        regex : "\\(|\\)|,"
                    }, {
                        token : "constant.numeric", // hex
                        regex : "0[xX][0-9a-fA-F]+\\b"
                    }, {
                        token : "constant.numeric", // float
                        regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
                    }, {
                        token : function(value) {
                            if (operators.hasOwnProperty(value))
                                return "keyword";
                            else if (
                                        ml.hasOwnProperty(value) ||
                                        prefix.hasOwnProperty(value[0]) ||
                                        prefix.hasOwnProperty(value.substr(0, 2))
                                    )
                                return "constant.language";
                            else
                                return "identifier";
                        },
                        regex : '[^,."\\s\\(\\)]+'
                    }, {
                        token : "string",
                        regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
                    }
                ]
            };

        }

        oop.inherits(AnimoHighlightRules, TextHighlightRules);
        exports.AnimoHighlightRules = AnimoHighlightRules;

    });

    var strip, sinput;

    if (window.MozWebSocket) {
        window.WebSocket = window.MozWebSocket;
    }

    window.addEventListener('popstate', function(event){
        select(event.state);
    }, false);

    var uri = "ws://" + window.location.host + "/ws";

    var socket = new WebSocket(uri, "src");
    socket.onmessage = function (event) {
        var id = title(event.data);
        var tab = search(id);
        if (tab.length == 0) {
            append(id, event.data);
        } else {
            strip.select(tab);
        }
    };
    socket.onopen = function (event) {
        var id = window.location.hash.substr(1);
        socket.send(id == "" ? "new" : id);
        onopen(event);
    };

    function onopen(event) {
        setInterval(function() {
              event.target.send("");
        }, 5 * 60 * 1000);
    }

    function open(id) {
        socket.send(id);
    }

    function select(id) {
        var tab = search(id)
        if (tab.length == 0) {
            open(id);
        } else {
            strip.select(tab);
            tab[0].editor.focus();
        }
    }

    var AnimoMode = require("ace/mode/animo").Mode;
    var commands = require("pilot/canon");

    commands.addCommand({
        name: 'save',
        bindKey: {
            win: 'Ctrl-S',
            mac: 'Command-S',
            sender: 'editor'
        },
        exec: function(env, args, request) {
            var tab = strip.select()[0];
            tab.socket.send(tab.editor.getSession().getValue());
        }
    });

    commands.addCommand({
        name: 'close',
        bindKey: {
            win: 'Ctrl-W',
            mac: 'Command-W',
            sender: 'editor'
        },
        exec: function(env, args, request) {
            var tab = strip.select();
            window.history.back();
            tab[0].socket.close();
            strip.remove(tab);
        }
    });

    commands.addCommand({
        name: 'open',
        bindKey: {
            win: 'Ctrl-O',
            mac: 'Command-O',
            sender: 'editor'
        },
        exec: function(env, args, request) {
            sinput.focus();
        }
    });

    commands.addCommand({
        name: 'lookup',
        bindKey: {
            win: 'Ctrl-B',
            mac: 'Command-B',
            sender: 'editor'
        },
        exec: function(env, args, request) {
            var tab = strip.select()[0];
            var pos = tab.editor.getCursorPosition();
            var token = tab.editor.getSession().bgTokenizer.lines[pos.row].tokens;
            var t = 0, n = 0, s = 0;
            for (var i = 0; i < token.length; i++) {
                n += token[i].value.length;
                if (n > pos.column) {
                    t = i;
                    break;
                }
                s = n;
            }
            if (t > 0 && s == pos.column && token[t].type != "identifier") {
                t--;
            }
            if (token[t].type == "identifier") {
                select(token[t].value);
            }
        }
    });

    function title(data) {
        return data.split("\n")[0].split(" ")[1].split(".")[0];
    }

    function search(title) {
        return strip.tabGroup.children("#"+title);
    }

    function push(id) {
        window.history.pushState(id, null, window.location.pathname + "#" + id);
    }

    function append(id, content) {
        push(id);
        strip.append([{text : id}]);
        var tab = strip.tabGroup.children("li").last().attr({id : id});
        strip.select(tab);
        var editor = ace.edit(
            $(strip.contentElement(tab.index())).css({
                position : "absolute",
                top : 36, right : 0, bottom : 0, left : 0,
                padding : 0, overflow : "hidden"
            }).html("

").children().css({
                position : "absolute",
                top : 4, right : 4, bottom : 4, left : 4,
                overflow : "hidden"
            }).get(0)
        );
        editor.getSession().setMode(new AnimoMode());
        editor.getSession().setValue(content);
        editor.focus();
        var socket = new WebSocket(uri, "save");
        socket.onmessage = function (event) {
            var id = title(event.data);
            tab.attr({id : id});
            tab.children("span").text(id);
            editor.getSession().setValue(event.data);
        };
        socket.onopen = onopen;
        tab[0].socket = socket;
        tab[0].editor = editor;
    }

    $.fn.ideEditor = function() {
        strip = $(this).kendoTabStrip({
            animation : {
                open : {
                    effects: "none"
                }
            },
            select : function(tab) {
                push($(tab.item).attr("id"));
                tab.item.editor.focus();
            }
        }).data("kendoTabStrip");
        return strip;
    };

    $.fn.ideSearch = function () {
        sinput = $(this)
        sinput.keypress(function(event) {
            if (event.keyCode == kendo.keys.ENTER) {
                select($(event.target).val());
            } else if (event.keyCode == kendo.keys.ESC) {
                strip.select()[0].editor.focus();
            }
        });
        return sinput;
    };

})(jQuery);
<|endoftext|>


<commit_before>define([
    'crafty'
], function(Crafty) {

  'use strict';

  var TILE_WIDTH = 32;
  var ASSETS = {
    'sprites': {
      'images/game/player.png': {
        'tile': TILE_WIDTH,
        'tileh': TILE_WIDTH,
        'map': {'SpritePlayer': [0, 0]},
      },
      'images/game/wall.png': {
        'tile': TILE_WIDTH,
        'tileh': TILE_WIDTH,
        'map': {'SpriteWall': [0, 0]}
      },
	  'images/game/door.png': {
		'tile': TILE_WIDTH,
		'tileh': TILE_WIDTH,
		'map': {'SpriteDoor': [0,0]}
	  }
    }
  }

  var _player;
  var _modelAdpt;
  var _playerModelAdpt;

  function initCrafty() {
    Crafty.c('Player', {
      init: function() {
        this.requires('2D, Canvas, Fourway, Collision, SpritePlayer, SpriteAnimation')
            .fourway(_playerModelAdpt.getSpeed())
            .reel('PlayerMovingRight',600, 0, 0, 1)
            .reel('PlayerMovingUp',   600, 1, 0, 1)
            .reel('PlayerMovingLeft', 600, 2, 0, 1)
            .reel('PlayerMovingDown', 600, 3, 0, 1)
            .onHit('Solid', this.stopMovement)
			.onHit('Door', this.useDoor);

        this.bind('NewDirection', function(data) {
          if (data.x > 0) {
            this.animate('PlayerMovingRight', -1);
          } else if (data.x < 0) {
            this.animate('PlayerMovingLeft', -1);
          } else if (data.y > 0) {
            this.animate('PlayerMovingDown', -1);
          } else if (data.y < 0) {
            this.animate('PlayerMovingUp', -1);
          } else {
            this.pauseAnimation();
          }

        });
      },

      stopMovement: function() {
        if (this._movement) {
          this.x -= this._movement.x;
          this.y -= this._movement.y;
        }
      },

	  useDoor: function(doorParts) {
	    console.log(doorParts[0]);
		//Model stuff.
	  }

    });

    Crafty.c('Wall', {
      init: function() {
        this.requires('2D, Canvas, Solid, SpriteWall');
      }
    });

	Crafty.c('Door', {
	  init: function() {
	    this.requires('2D, Canvas, SpriteDoor');
	  }
	});

    Crafty.init(_modelAdpt.getGridSpecs().width * TILE_WIDTH,
                _modelAdpt.getGridSpecs().height * TILE_WIDTH,
                document.getElementById('game-stage'));

    Crafty.load(ASSETS, function() {
    });

  }

  function start() {
    Crafty.background('blue');

    setupBarriers();
  }

  function makePlayerView(playerModelAdpt) {
    _playerModelAdpt = playerModelAdpt;

    _player = Crafty.e('Player').attr({x: TILE_WIDTH * 2, y: TILE_WIDTH * 2});
                                // .fourway(_playerModelAdpt.getSpeed());

    return _player;
  }

  function setupBarriers() {
	var gateways = _modelAdpt.getGateways();

    for (var j = 0; j < _modelAdpt.getGridSpecs().width; j++) {
	  if(!('north' in gateways && (j == _modelAdpt.getGridSpecs().width/2 || j == _modelAdpt.getGridSpecs().width/2-1))) {
		Crafty.e('Wall').attr({x: j * TILE_WIDTH, y: 0});
	  }
	  else {
	    Crafty.e('Door').attr({x: j * TILE_WIDTH, y: 0, doorID: gateways['north']});
	  }
	  if(!('south' in gateways && (j == _modelAdpt.getGridSpecs().width/2 || j == _modelAdpt.getGridSpecs().width/2-1))) {
		Crafty.e('Wall').attr({x: j * TILE_WIDTH, y: (_modelAdpt.getGridSpecs().height - 1) * TILE_WIDTH});
	  }
	  else {
	    Crafty.e('Door').attr({x: j * TILE_WIDTH, y: (_modelAdpt.getGridSpecs().height - 1) * TILE_WIDTH, doorID: gateways['south']});
	  }
    }

    for (var i = 0; i < _modelAdpt.getGridSpecs().height; i++) {
	  if(!('west' in gateways && (i == _modelAdpt.getGridSpecs().height/2 || i == _modelAdpt.getGridSpecs().height/2-1))) {
	    Crafty.e('Wall').attr({x: 0, y: i * TILE_WIDTH});
	  }
	  else {
	    Crafty.e('Door').attr({x: 0, y: i * TILE_WIDTH, doorID: gateways['west']});
	  }
	  if(!('east' in gateways && (i == _modelAdpt.getGridSpecs().height/2 || i == _modelAdpt.getGridSpecs().height/2-1))) {
        Crafty.e('Wall').attr({x: (_modelAdpt.getGridSpecs().width - 1) * TILE_WIDTH, y: i * TILE_WIDTH});
	  }
	  else {
	    Crafty.e('Door').attr({x: (_modelAdpt.getGridSpecs().width - 1) * TILE_WIDTH, y: i * TILE_WIDTH, doorID: gateways['east']});
	  }
    }

  }

  return function GameView(modelAdpt) {
    _modelAdpt = modelAdpt;

    document.getElementById('speed-inc').addEventListener('click', function() {
      _playerModelAdpt.onSpeedIncClick();
    });

    document.getElementById('speed-dec').addEventListener('click', function() {
      _playerModelAdpt.onSpeedDecClick();
    });

    initCrafty();

    this.start = start;
    this.makePlayerView = makePlayerView;
  }
});
<commit_msg>Found doorIDs in useDoor function<commit_after>define([
    'crafty'
], function(Crafty) {

  'use strict';

  var TILE_WIDTH = 32;
  var ASSETS = {
    'sprites': {
      'images/game/player.png': {
        'tile': TILE_WIDTH,
        'tileh': TILE_WIDTH,
        'map': {'SpritePlayer': [0, 0]},
      },
      'images/game/wall.png': {
        'tile': TILE_WIDTH,
        'tileh': TILE_WIDTH,
        'map': {'SpriteWall': [0, 0]}
      },
	  'images/game/door.png': {
		'tile': TILE_WIDTH,
		'tileh': TILE_WIDTH,
		'map': {'SpriteDoor': [0,0]}
	  }
    }
  }

  var _player;
  var _modelAdpt;
  var _playerModelAdpt;

  function initCrafty() {
    Crafty.c('Player', {
      init: function() {
        this.requires('2D, Canvas, Fourway, Collision, SpritePlayer, SpriteAnimation')
            .fourway(_playerModelAdpt.getSpeed())
            .reel('PlayerMovingRight',600, 0, 0, 1)
            .reel('PlayerMovingUp',   600, 1, 0, 1)
            .reel('PlayerMovingLeft', 600, 2, 0, 1)
            .reel('PlayerMovingDown', 600, 3, 0, 1)
            .onHit('Solid', this.stopMovement)
			.onHit('Door', this.useDoor);

        this.bind('NewDirection', function(data) {
          if (data.x > 0) {
            this.animate('PlayerMovingRight', -1);
          } else if (data.x < 0) {
            this.animate('PlayerMovingLeft', -1);
          } else if (data.y > 0) {
            this.animate('PlayerMovingDown', -1);
          } else if (data.y < 0) {
            this.animate('PlayerMovingUp', -1);
          } else {
            this.pauseAnimation();
          }

        });
      },

      stopMovement: function() {
        if (this._movement) {
          this.x -= this._movement.x;
          this.y -= this._movement.y;
        }
      },

	  useDoor: function(doorParts) {
	    console.log(doorParts[0].obj.doorID);
		//Model stuff.
	  }

    });

    Crafty.c('Wall', {
      init: function() {
        this.requires('2D, Canvas, Solid, SpriteWall');
      }
    });

	Crafty.c('Door', {
	  init: function() {
	    this.requires('2D, Canvas, SpriteDoor');
	  }
	});

    Crafty.init(_modelAdpt.getGridSpecs().width * TILE_WIDTH,
                _modelAdpt.getGridSpecs().height * TILE_WIDTH,
                document.getElementById('game-stage'));

    Crafty.load(ASSETS, function() {
    });

  }

  function start() {
    Crafty.background('blue');

    setupBarriers();
  }

  function makePlayerView(playerModelAdpt) {
    _playerModelAdpt = playerModelAdpt;

    _player = Crafty.e('Player').attr({x: TILE_WIDTH * 2, y: TILE_WIDTH * 2});
                                // .fourway(_playerModelAdpt.getSpeed());

    return _player;
  }

  function setupBarriers() {
	var gateways = _modelAdpt.getGateways();

    for (var j = 0; j < _modelAdpt.getGridSpecs().width; j++) {
	  if(!('north' in gateways && (j == _modelAdpt.getGridSpecs().width/2 || j == _modelAdpt.getGridSpecs().width/2-1))) {
		Crafty.e('Wall').attr({x: j * TILE_WIDTH, y: 0});
	  }
	  else {
	    Crafty.e('Door').attr({x: j * TILE_WIDTH, y: 0, doorID: gateways['north']});
	  }
	  if(!('south' in gateways && (j == _modelAdpt.getGridSpecs().width/2 || j == _modelAdpt.getGridSpecs().width/2-1))) {
		Crafty.e('Wall').attr({x: j * TILE_WIDTH, y: (_modelAdpt.getGridSpecs().height - 1) * TILE_WIDTH});
	  }
	  else {
	    Crafty.e('Door').attr({x: j * TILE_WIDTH, y: (_modelAdpt.getGridSpecs().height - 1) * TILE_WIDTH, doorID: gateways['south']});
	  }
    }

    for (var i = 0; i < _modelAdpt.getGridSpecs().height; i++) {
	  if(!('west' in gateways && (i == _modelAdpt.getGridSpecs().height/2 || i == _modelAdpt.getGridSpecs().height/2-1))) {
	    Crafty.e('Wall').attr({x: 0, y: i * TILE_WIDTH});
	  }
	  else {
	    Crafty.e('Door').attr({x: 0, y: i * TILE_WIDTH, doorID: gateways['west']});
	  }
	  if(!('east' in gateways && (i == _modelAdpt.getGridSpecs().height/2 || i == _modelAdpt.getGridSpecs().height/2-1))) {
        Crafty.e('Wall').attr({x: (_modelAdpt.getGridSpecs().width - 1) * TILE_WIDTH, y: i * TILE_WIDTH});
	  }
	  else {
	    Crafty.e('Door').attr({x: (_modelAdpt.getGridSpecs().width - 1) * TILE_WIDTH, y: i * TILE_WIDTH, doorID: gateways['east']});
	  }
    }

  }

  return function GameView(modelAdpt) {
    _modelAdpt = modelAdpt;

    document.getElementById('speed-inc').addEventListener('click', function() {
      _playerModelAdpt.onSpeedIncClick();
    });

    document.getElementById('speed-dec').addEventListener('click', function() {
      _playerModelAdpt.onSpeedDecClick();
    });

    initCrafty();

    this.start = start;
    this.makePlayerView = makePlayerView;
  }
});
<|endoftext|>


<commit_before>
var Setting=function(options) {
  this.name=options.name[0];
  this.type=options.type;
  this.value=options.value;
  this.callback=options.callback;
  this.tooltip=options.name[1];

  this.clean=function() {
    return this.name.replace(" ","-").replace("%","");
  };

  if(this.clean() in localStorage) {
    this.value=JSON.parse(localStorage[this.clean()]);
  }

  if(this.type != "button") {
    this.callback();
  }

  this.html=$("

");
  $("#settings").append(this.html);

  this.html.append(""+this.name+"");

  if(this.value) this.html.addClass("on");
  else this.html.removeClass("on");

  this.toggle=function() {
    this.value=!this.value;
    if(this.value) this.html.addClass("on");
    else this.html.removeClass("on");
    this.callback();
    this.save();
  };

  this.save=function() {
    localStorage[this.clean()]=JSON.stringify(this.value);
  };

  var that=this;
  if(this.type == "bool") {
    this.html.click(function() {
      that.toggle.call(that);
    });
  } else if(this.type == "button") {
    this.html.click(function() {
      that.callback.call(that);
      that.save();
    });
  }

};

function settings_init_pre() {
  prop.settings=[];
}

function settings_init() {
  setting_add(["reset","reset the simulation"],"button",null,function() {
    craft_reset();
  });
  setting_add(["f9r-dev1","three engines, 1/3 fuel"],"button",null,function() {
    craft_reset("f9r-dev1");
  });
  setting_add(["f9r-dev2","nine engines, full fuel"],"button",null,function() {
    craft_reset("f9r-dev2");
  });
  setting_add(["flip left-right","flip the engine vector direction"],"bool",true,function() {
    if(this.value) {
      prop.input.vector_flip=true;
      console.log(this.value);
    } else {
      prop.input.vector_flip=false;
      console.log(this.value);
    }
  });
  setting_add(["minimap","show the minimap"],"bool",true,function() {
    if(this.value) prop.ui.minimap.enabled=true;
    else prop.ui.minimap.enabled=false;
  });
  setting_add(["hard mode","enable for realism"],"bool",true,function() {
    if(this.value) {
      prop.craft.min_throttle=0.7;
      prop.craft.vector_max=radians(1.5);
      prop.craft.crash_velocity=2;
      prop.craft.crash_angle=radians(5);
    } else {
      prop.craft.min_throttle=0;
      prop.craft.vector_max=radians(3);
      prop.craft.crash_velocity=3;
      prop.craft.crash_angle=radians(10);
    }
  });
//  setting_add(["allow two engines","allow two engine usage in addition to one and three engines"],"bool",false,function() {
//    if(this.value) prop.input.two=true;
//    else prop.input.two=false;
//  });
  setting_add(["sound effects","moo"],"bool",false,function() {
    if(this.value) prop.audio.enabled=true;
    else prop.audio.enabled=false;
  });
}

function setting_add(name,type,value,callback) {
  prop.settings.push(new Setting({
    name:name,
    type:type,
    value:value,
    callback:callback
  }));
}
<commit_msg>removed logging<commit_after>
var Setting=function(options) {
  this.name=options.name[0];
  this.type=options.type;
  this.value=options.value;
  this.callback=options.callback;
  this.tooltip=options.name[1];

  this.clean=function() {
    return this.name.replace(" ","-").replace("%","");
  };

  if(this.clean() in localStorage) {
    this.value=JSON.parse(localStorage[this.clean()]);
  }

  if(this.type != "button") {
    this.callback();
  }

  this.html=$("

");
  $("#settings").append(this.html);

  this.html.append(""+this.name+"");

  if(this.value) this.html.addClass("on");
  else this.html.removeClass("on");

  this.toggle=function() {
    this.value=!this.value;
    if(this.value) this.html.addClass("on");
    else this.html.removeClass("on");
    this.callback();
    this.save();
  };

  this.save=function() {
    localStorage[this.clean()]=JSON.stringify(this.value);
  };

  var that=this;
  if(this.type == "bool") {
    this.html.click(function() {
      that.toggle.call(that);
    });
  } else if(this.type == "button") {
    this.html.click(function() {
      that.callback.call(that);
      that.save();
    });
  }

};

function settings_init_pre() {
  prop.settings=[];
}

function settings_init() {
  setting_add(["reset","reset the simulation"],"button",null,function() {
    craft_reset();
  });
  setting_add(["f9r-dev1","three engines, 1/3 fuel"],"button",null,function() {
    craft_reset("f9r-dev1");
  });
  setting_add(["f9r-dev2","nine engines, full fuel"],"button",null,function() {
    craft_reset("f9r-dev2");
  });
  setting_add(["flip left-right","flip the engine vector direction"],"bool",true,function() {
    if(this.value) {
      prop.input.vector_flip=true;
    } else {
      prop.input.vector_flip=false;
    }
  });
  setting_add(["minimap","show the minimap"],"bool",true,function() {
    if(this.value) prop.ui.minimap.enabled=true;
    else prop.ui.minimap.enabled=false;
  });
  setting_add(["hard mode","enable for realism"],"bool",true,function() {
    if(this.value) {
      prop.craft.min_throttle=0.7;
      prop.craft.vector_max=radians(1.5);
      prop.craft.crash_velocity=2;
      prop.craft.crash_angle=radians(5);
    } else {
      prop.craft.min_throttle=0;
      prop.craft.vector_max=radians(3);
      prop.craft.crash_velocity=3;
      prop.craft.crash_angle=radians(10);
    }
  });
//  setting_add(["allow two engines","allow two engine usage in addition to one and three engines"],"bool",false,function() {
//    if(this.value) prop.input.two=true;
//    else prop.input.two=false;
//  });
  setting_add(["sound effects","moo"],"bool",false,function() {
    if(this.value) prop.audio.enabled=true;
    else prop.audio.enabled=false;
  });
}

function setting_add(name,type,value,callback) {
  prop.settings.push(new Setting({
    name:name,
    type:type,
    value:value,
    callback:callback
  }));
}
<|endoftext|>


<commit_before>'use strict';

const _ = require('underscore');
const hogan = require('hogan.js/lib/compiler');
const types = require('../ractive_types');

const parser = require('./parser');
const stack = require('./stack');
const logger = require('./compiler_logger');

/**
 * Gets the current buffer from htmlparser and processes it
 * Used to handle section tags inside attribute values
 */
function processBuffer() {
  if (!parser.inRelevantState()) {
    return;
  }
  let runningName = parser.getSection();
  if (parser.inAttributeName()) {
    if (runningName) {
      parser.clearBuffer();
      stack.createObject({
        type: 'attributename',
        value: runningName
      });
    }
  } else if (parser.afterAttributeName()) {
    parser.endAttribute();
  } else if (parser.inAttributeValue()) {
    parser.clearBuffer();
    stack.createObject({
      type: 'attributevalue',
      value: runningName
    });
  } else if (parser.inComment()) {
    parser.clearBuffer();
    if (stack.inComment()) {
      stack.createObject(runningName);
    } else {
      stack.openElement(types.COMMENT, runningName);
    }
  }
}

/**
 * [processHoganObject description]
 * @param  {Object}  token              Nested mustache tree object
 * @param  {booelan} inDynamicAttribute Whether we are in a dynamic attribute
 */
function processHoganObject(token, inDynamicAttribute) {
  if (!token) {
    return;
  }
  if (Array.isArray(token)) {
    for (let i = 0; i < token.length; i++) {
      processHoganObject(token[i], inDynamicAttribute);
    }
    return;
  }

  // Any time we hit a mustache node, check the buffer
  if (token.tag !== '_t') {
    processBuffer();
  }

  let obj;
  switch (token.tag) {
    case '!':
      // Leave control comments in as interpolators
      if (token.n.indexOf('w/') > -1) {
        obj = {};
        obj.type = types.INTERPOLATOR;
        obj.value = '!' + token.n;
        stack.createObject(obj);
      }
      break;
    case '#':
      obj = stack.openElement(types.SECTION, token.n.toString());
      processHoganObject(token.nodes, parser.inAttributeName());
      processBuffer();
      stack.closeElement(obj);
      break;
    case '^':
      obj = stack.openElement(types.SECTION_UNLESS, token.n.toString());
      processHoganObject(token.nodes, parser.inAttributeName());
      processBuffer();
      stack.closeElement(obj);
      break;
    case '>':
      obj = {};
      obj.type = types.PARTIAL;
      obj.value = token.n.toString();
      stack.createObject(obj);
      break;
    case '&':
    case '{':
      obj = {};
      obj.type = types.TRIPLE;
      obj.value = token.n.toString();
      stack.createObject(obj);
      break;
    case '_v':
      obj = {};
      obj.type = types.INTERPOLATOR;
      obj.value = token.n.toString();
      stack.createObject(obj);
      break;
    case '_t':
      if (inDynamicAttribute) {
        stack.createObject(token.text.toString());
      } else {
        parser.write(token.text.toString());
      }
      break;
    case '\n':
      if (!inDynamicAttribute) {
        parser.write('\n');
      }
      break;
    default:
      logger.exception('Unexpected mustache type found', token);
  }
}

/**
 * Processes a template string into a Template
 *
 * @param  {string} template Mustache template string
 * @return {Object}          Processed template object
 */
function getTemplate(template, options) {
  stack.clear();
  parser.reset();

  let opts = typeof options === 'undefined' ? {} : options;
  opts.strict = typeof opts.strict === 'boolean' ? opts.strict : true;
  opts.preserveWhitespace = typeof opts.preserveWhitespace === 'boolean' ? opts.preserveWhitespace : false;
  opts.validateHtml = opts.validateHtml != null ? opts.validateHtml : 'strict';
  opts.logger = opts.logger != null ? opts.logger : {};

  logger.setStrictMode(opts.strict);
  logger.setOverrides(opts.logger);
  stack.setHtmlValidation(opts.validateHtml);

  let templateStr = template.toString();
  // Normalize whitespace within tokens
  // {{ #foo }} !== {{#foo}} in Hogan's eyes
  templateStr = templateStr.replace(/\{\{\s+([#^\/])(\S*?)\s*\}\}/g, function(match, symbol, key) {
    return '{{' + symbol + key + '}}';
  });
  let tokenTree = hogan.parse(hogan.scan(templateStr, null, opts.preserveWhitespace), templateStr, {preserveWhitespace: opts.preserveWhitespace});
  processHoganObject(tokenTree);
  let output = {};

  if (stack.stack.length > 0) {
    logger.exception('Not all tags were closed properly', stack.stack);
  }

  parser.end();
  output.templateObj = stack.getOutput();
  const Template = require('../template');
  output.template = new Template(output.templateObj);
  output.source = template;
  output.tokens = {};
  _.each(stack.tokens, function(values, type) {
    output.tokens[type] = _.keys(values);
  });
  return output;
}

module.exports = getTemplate;
<commit_msg>Adding partial and comments to the whitespace normalization check<commit_after>'use strict';

const _ = require('underscore');
const hogan = require('hogan.js/lib/compiler');
const types = require('../ractive_types');

const parser = require('./parser');
const stack = require('./stack');
const logger = require('./compiler_logger');

/**
 * Gets the current buffer from htmlparser and processes it
 * Used to handle section tags inside attribute values
 */
function processBuffer() {
  if (!parser.inRelevantState()) {
    return;
  }
  let runningName = parser.getSection();
  if (parser.inAttributeName()) {
    if (runningName) {
      parser.clearBuffer();
      stack.createObject({
        type: 'attributename',
        value: runningName
      });
    }
  } else if (parser.afterAttributeName()) {
    parser.endAttribute();
  } else if (parser.inAttributeValue()) {
    parser.clearBuffer();
    stack.createObject({
      type: 'attributevalue',
      value: runningName
    });
  } else if (parser.inComment()) {
    parser.clearBuffer();
    if (stack.inComment()) {
      stack.createObject(runningName);
    } else {
      stack.openElement(types.COMMENT, runningName);
    }
  }
}

/**
 * [processHoganObject description]
 * @param  {Object}  token              Nested mustache tree object
 * @param  {booelan} inDynamicAttribute Whether we are in a dynamic attribute
 */
function processHoganObject(token, inDynamicAttribute) {
  if (!token) {
    return;
  }
  if (Array.isArray(token)) {
    for (let i = 0; i < token.length; i++) {
      processHoganObject(token[i], inDynamicAttribute);
    }
    return;
  }

  // Any time we hit a mustache node, check the buffer
  if (token.tag !== '_t') {
    processBuffer();
  }

  let obj;
  switch (token.tag) {
    case '!':
      // Leave control comments in as interpolators
      if (token.n.indexOf('w/') > -1) {
        obj = {};
        obj.type = types.INTERPOLATOR;
        obj.value = '!' + token.n;
        stack.createObject(obj);
      }
      break;
    case '#':
      obj = stack.openElement(types.SECTION, token.n.toString());
      processHoganObject(token.nodes, parser.inAttributeName());
      processBuffer();
      stack.closeElement(obj);
      break;
    case '^':
      obj = stack.openElement(types.SECTION_UNLESS, token.n.toString());
      processHoganObject(token.nodes, parser.inAttributeName());
      processBuffer();
      stack.closeElement(obj);
      break;
    case '>':
      obj = {};
      obj.type = types.PARTIAL;
      obj.value = token.n.toString();
      stack.createObject(obj);
      break;
    case '&':
    case '{':
      obj = {};
      obj.type = types.TRIPLE;
      obj.value = token.n.toString();
      stack.createObject(obj);
      break;
    case '_v':
      obj = {};
      obj.type = types.INTERPOLATOR;
      obj.value = token.n.toString();
      stack.createObject(obj);
      break;
    case '_t':
      if (inDynamicAttribute) {
        stack.createObject(token.text.toString());
      } else {
        parser.write(token.text.toString());
      }
      break;
    case '\n':
      if (!inDynamicAttribute) {
        parser.write('\n');
      }
      break;
    default:
      logger.exception('Unexpected mustache type found', token);
  }
}

/**
 * Processes a template string into a Template
 *
 * @param  {string} template Mustache template string
 * @return {Object}          Processed template object
 */
function getTemplate(template, options) {
  stack.clear();
  parser.reset();

  let opts = typeof options === 'undefined' ? {} : options;
  opts.strict = typeof opts.strict === 'boolean' ? opts.strict : true;
  opts.preserveWhitespace = typeof opts.preserveWhitespace === 'boolean' ? opts.preserveWhitespace : false;
  opts.validateHtml = opts.validateHtml != null ? opts.validateHtml : 'strict';
  opts.logger = opts.logger != null ? opts.logger : {};

  logger.setStrictMode(opts.strict);
  logger.setOverrides(opts.logger);
  stack.setHtmlValidation(opts.validateHtml);

  let templateStr = template.toString();
  // Normalize whitespace within tokens
  // {{ #foo }} !== {{#foo}} in Hogan's eyes
  templateStr = templateStr.replace(/\{\{\s+([#^\/>!])(\S*?)\s*\}\}/g, function(match, symbol, key) {
    return '{{' + symbol + key + '}}';
  });
  let tokenTree = hogan.parse(hogan.scan(templateStr, null, opts.preserveWhitespace), templateStr, {preserveWhitespace: opts.preserveWhitespace});
  processHoganObject(tokenTree);
  let output = {};

  if (stack.stack.length > 0) {
    logger.exception('Not all tags were closed properly', stack.stack);
  }

  parser.end();
  output.templateObj = stack.getOutput();
  const Template = require('../template');
  output.template = new Template(output.templateObj);
  output.source = template;
  output.tokens = {};
  _.each(stack.tokens, function(values, type) {
    output.tokens[type] = _.keys(values);
  });
  return output;
}

module.exports = getTemplate;
<|endoftext|>


<commit_before>var J = J || {};
//-----------------------------------
//
// J.Viewer - test webGL overlay atop OpenSeaDragon
//
//-----------------------------------

J.Viewer = function(baseLayer) {
}

J.Viewer.prototype.init = function() {

    // Open a seaDragon with two layers
    var openSD = OpenSeadragon({
        tileSources: 'babel/babel.dzi',
        id: this.container || 'viaWebGL',
        prefixUrl: '../../images/'
    });

    // Make a link to webGL
    var seaGL = new SeaDragonGL();
    seaGL.vShader = '../../shaders/square.glsl';
    seaGL.fShader = '../../shaders/edge.glsl';
    seaGL.tileSize = 512;

    var load = function(callback, e) {
        // via webGL
        callback(e);
    }

    var draw = function(callback, e) {

        if (e.tile.loaded !==1) {
            e.tile.loaded = 1;
            callback(e);
        }
    }

    seaGL['tile-drawing'] = draw;

    seaGL.init(openSD);
}<commit_msg>readme<commit_after>var J = J || {};
//-----------------------------------
//
// J.Viewer - test webGL overlay atop OpenSeaDragon
//
//-----------------------------------

J.Viewer = function(baseLayer) {
}

J.Viewer.prototype.init = function() {

    // Open a seaDragon with two layers
    var openSD = OpenSeadragon({
        tileSources: '../../sources/babel/babel.dzi',
        id: this.container || 'viaWebGL',
        prefixUrl: '../../images/'
    });

    // Make a link to webGL
    var seaGL = new SeaDragonGL();
    seaGL.vShader = '../../shaders/square.glsl';
    seaGL.fShader = '../../shaders/edge.glsl';
    seaGL.tileSize = 512;

    var load = function(callback, e) {
        // via webGL
        callback(e);
    }

    var draw = function(callback, e) {

        if (e.tile.loaded !==1) {
            e.tile.loaded = 1;
            callback(e);
        }
    }

    seaGL['tile-drawing'] = draw;

    seaGL.init(openSD);
}<|endoftext|>


<commit_before>Demo.static.pages.icons = function ( demo ) {
	var i, len, iconSet, iconsFieldset, iconWidget, selector,
		icons = {
			movement: [
				'arrowLast',
				'arrowNext',
				'downTriangle',
				'upTriangle',
				'first',
				'previous',
				'next',
				'last',
				'expand',
				'collapse',
				'move',
				'draggable'
			],
			content: [
				'article',
				'articles',
				'articleCheck',
				'articleSearch',
				'articleRedirect',
				'citeArticle',
				'book',
				'history',
				'info',
				'journal',
				'newspaper',
				'folderPlaceholder',
				'die',
				'download',
				'tag',
				'upload',
				'window'
			],
			alerts: [
				'alert',
				'bell',
				'bellOn',
				'comment',
				'message',
				'notice',
				'speechBubble',
				'speechBubbleAdd',
				'speechBubbles',
				'tray'
			],
			interactions: [
				'add',
				'advanced',
				'browser',
				'cancel',
				'check',
				'clear',
				'clock',
				'close',
				'ellipsis',
				'feedback',
				'funnel',
				'heart',
				'help',
				'key',
				'keyboard',
				'logOut',
				'newWindow',
				'printer',
				'search',
				'settings',
				'subtract',
				'sun',
				'watchlist'
			],
			moderation: [
				'block',
				'unBlock',
				'clip',
				'unClip',
				'flag',
				'unFlag',
				'lock',
				'unLock',
				'star',
				'halfStar',
				'unStar',
				'trash',
				'unTrash',
				'pushPin',
				'ongoingConversation'
			],
			'editing-core': [
				'edit',
				'editLock',
				'editUndo',
				'link',
				'linkExternal',
				'linkSecure',
				'redo',
				'undo'
			],
			'editing-styling': [
				'bigger',
				'smaller',
				'subscript',
				'superscript',
				'bold',
				'highlight',
				'italic',
				'strikethrough',
				'underline',
				'textDirLTR',
				'textDirRTL',
				'textStyle'
			],
			'editing-list': [
				'indent',
				'listBullet',
				'listNumbered',
				'outdent'
			],
			'editing-advanced': [
				'alignCentre',
				'alignLeft',
				'alignRight',
				'attachment',
				'calendar',
				'code',
				'find',
				'language',
				'layout',
				'markup',
				'newline',
				'noWikiText',
				'outline',
				'puzzle',
				'quotes',
				'quotesAdd',
				'searchCaseSensitive',
				'searchDiacritics',
				'searchRegularExpression',
				'signature',
				'specialCharacter',
				'table',
				'tableAddColumnAfter',
				'tableAddColumnBefore',
				'tableAddRowAfter',
				'tableAddRowBefore',
				'tableCaption',
				'tableMergeCells',
				'templateAdd',
				'wikiText'
			],
			media: [
				'fullScreen',
				'image',
				'imageAdd',
				'imageLock',
				'imageGallery',
				'play',
				'stop'
			],
			location: [
				'map',
				'mapPin',
				'mapPinAdd',
				'mapTrail'
			],
			user: [
				'userActive',
				'userAvatar',
				'userInactive',
				'userTalk'
			],
			layout: [
				'menu',
				'stripeFlow',
				'stripeSummary',
				'stripeToC',
				'viewCompact',
				'viewDetails'
			],
			accessibility: [
				'bright',
				'halfBright',
				'notBright',
				'eye',
				'eyeClosed',
				'moon',
				'largerText',
				'smallerText',
				'visionSimulator'
			],
			wikimedia: [
				'logoCC',
				'logoWikimediaCommons',
				'logoWikimediaDiscovery',
				'logoWikipedia'
			]
		},
		indicators = [
			'alert',
			'clear',
			'down',
			'next',
			'previous',
			'required',
			'search',
			'up'
		],
		iconsFieldsets = [],
		iconsWidgets = [],
		indicatorsFieldset = new OO.ui.FieldsetLayout( { label: 'Indicators' } );

	for ( i = 0, len = indicators.length; i < len; i++ ) {
		indicatorsFieldset.addItems( [
			new OO.ui.FieldLayout(
				new OO.ui.IndicatorWidget( {
					indicator: indicators[ i ],
					title: indicators[ i ]
				} ),
				{
					align: 'inline',
					label: indicators[ i ]
				}
			)
		] );
	}
	for ( iconSet in icons ) {
		iconsFieldset = new OO.ui.FieldsetLayout( { label: 'Icons – ' + iconSet } );
		iconsFieldsets.push( iconsFieldset );

		for ( i = 0, len = icons[ iconSet ].length; i < len; i++ ) {
			iconWidget = new OO.ui.IconWidget( {
				icon: icons[ iconSet ][ i ],
				title: icons[ iconSet ][ i ]
			} );
			iconsWidgets.push( iconWidget );
			iconsFieldset.addItems( [
				new OO.ui.FieldLayout( iconWidget, {
					label: icons[ iconSet ][ i ],
					align: 'inline'
				} )
			] );
		}
	}

	selector = new OO.ui.ButtonSelectWidget( {
		items: [
			new OO.ui.ButtonOptionWidget( {
				label: 'None',
				flags: [],
				data: {
					progressive: false,
					constructive: false,
					destructive: false
				}
			} ),
			new OO.ui.ButtonOptionWidget( {
				label: 'Progressive',
				flags: [ 'progressive' ],
				data: {
					progressive: true,
					constructive: false,
					destructive: false
				}
			} ),
			new OO.ui.ButtonOptionWidget( {
				label: 'Destructive',
				flags: [ 'destructive' ],
				data: {
					progressive: false,
					constructive: false,
					destructive: true
				}
			} )
		]
	} );

	selector
		.on( 'select', function ( selected ) {
			iconsWidgets.forEach( function ( iconWidget ) {
				iconWidget.setFlags( selected.getData() );
			} );
		} )
		.selectItemByData( {
			progressive: false,
			constructive: false,
			destructive: false
		} );

	demo.$element.append(
		new OO.ui.PanelLayout( {
			expanded: false,
			framed: true
		} ).$element
			.addClass( 'demo-container demo-icons' )
			.attr( 'role', 'main' )
			.append(
				selector.$element,
				indicatorsFieldset.$element,
				iconsFieldsets.map( function ( item ) { return item.$element[ 0 ]; } )
			)
	);
};
<commit_msg>demos: Remove deprecated 'sun' icon from demo<commit_after>Demo.static.pages.icons = function ( demo ) {
	var i, len, iconSet, iconsFieldset, iconWidget, selector,
		icons = {
			movement: [
				'arrowLast',
				'arrowNext',
				'downTriangle',
				'upTriangle',
				'first',
				'previous',
				'next',
				'last',
				'expand',
				'collapse',
				'move',
				'draggable'
			],
			content: [
				'article',
				'articles',
				'articleCheck',
				'articleSearch',
				'articleRedirect',
				'citeArticle',
				'book',
				'history',
				'info',
				'journal',
				'newspaper',
				'folderPlaceholder',
				'die',
				'download',
				'tag',
				'upload',
				'window'
			],
			alerts: [
				'alert',
				'bell',
				'bellOn',
				'comment',
				'message',
				'notice',
				'speechBubble',
				'speechBubbleAdd',
				'speechBubbles',
				'tray'
			],
			interactions: [
				'add',
				'advanced',
				'browser',
				'cancel',
				'check',
				'clear',
				'clock',
				'close',
				'ellipsis',
				'feedback',
				'funnel',
				'heart',
				'help',
				'key',
				'keyboard',
				'logOut',
				'newWindow',
				'printer',
				'search',
				'settings',
				'subtract',
				'watchlist'
			],
			moderation: [
				'block',
				'unBlock',
				'clip',
				'unClip',
				'flag',
				'unFlag',
				'lock',
				'unLock',
				'star',
				'halfStar',
				'unStar',
				'trash',
				'unTrash',
				'pushPin',
				'ongoingConversation'
			],
			'editing-core': [
				'edit',
				'editLock',
				'editUndo',
				'link',
				'linkExternal',
				'linkSecure',
				'redo',
				'undo'
			],
			'editing-styling': [
				'bigger',
				'smaller',
				'subscript',
				'superscript',
				'bold',
				'highlight',
				'italic',
				'strikethrough',
				'underline',
				'textDirLTR',
				'textDirRTL',
				'textStyle'
			],
			'editing-list': [
				'indent',
				'listBullet',
				'listNumbered',
				'outdent'
			],
			'editing-advanced': [
				'alignCentre',
				'alignLeft',
				'alignRight',
				'attachment',
				'calendar',
				'code',
				'find',
				'language',
				'layout',
				'markup',
				'newline',
				'noWikiText',
				'outline',
				'puzzle',
				'quotes',
				'quotesAdd',
				'searchCaseSensitive',
				'searchDiacritics',
				'searchRegularExpression',
				'signature',
				'specialCharacter',
				'table',
				'tableAddColumnAfter',
				'tableAddColumnBefore',
				'tableAddRowAfter',
				'tableAddRowBefore',
				'tableCaption',
				'tableMergeCells',
				'templateAdd',
				'wikiText'
			],
			media: [
				'fullScreen',
				'image',
				'imageAdd',
				'imageLock',
				'imageGallery',
				'play',
				'stop'
			],
			location: [
				'map',
				'mapPin',
				'mapPinAdd',
				'mapTrail'
			],
			user: [
				'userActive',
				'userAvatar',
				'userInactive',
				'userTalk'
			],
			layout: [
				'menu',
				'stripeFlow',
				'stripeSummary',
				'stripeToC',
				'viewCompact',
				'viewDetails'
			],
			accessibility: [
				'bright',
				'halfBright',
				'notBright',
				'eye',
				'eyeClosed',
				'moon',
				'largerText',
				'smallerText',
				'visionSimulator'
			],
			wikimedia: [
				'logoCC',
				'logoWikimediaCommons',
				'logoWikimediaDiscovery',
				'logoWikipedia'
			]
		},
		indicators = [
			'alert',
			'clear',
			'down',
			'next',
			'previous',
			'required',
			'search',
			'up'
		],
		iconsFieldsets = [],
		iconsWidgets = [],
		indicatorsFieldset = new OO.ui.FieldsetLayout( { label: 'Indicators' } );

	for ( i = 0, len = indicators.length; i < len; i++ ) {
		indicatorsFieldset.addItems( [
			new OO.ui.FieldLayout(
				new OO.ui.IndicatorWidget( {
					indicator: indicators[ i ],
					title: indicators[ i ]
				} ),
				{
					align: 'inline',
					label: indicators[ i ]
				}
			)
		] );
	}
	for ( iconSet in icons ) {
		iconsFieldset = new OO.ui.FieldsetLayout( { label: 'Icons – ' + iconSet } );
		iconsFieldsets.push( iconsFieldset );

		for ( i = 0, len = icons[ iconSet ].length; i < len; i++ ) {
			iconWidget = new OO.ui.IconWidget( {
				icon: icons[ iconSet ][ i ],
				title: icons[ iconSet ][ i ]
			} );
			iconsWidgets.push( iconWidget );
			iconsFieldset.addItems( [
				new OO.ui.FieldLayout( iconWidget, {
					label: icons[ iconSet ][ i ],
					align: 'inline'
				} )
			] );
		}
	}

	selector = new OO.ui.ButtonSelectWidget( {
		items: [
			new OO.ui.ButtonOptionWidget( {
				label: 'None',
				flags: [],
				data: {
					progressive: false,
					constructive: false,
					destructive: false
				}
			} ),
			new OO.ui.ButtonOptionWidget( {
				label: 'Progressive',
				flags: [ 'progressive' ],
				data: {
					progressive: true,
					constructive: false,
					destructive: false
				}
			} ),
			new OO.ui.ButtonOptionWidget( {
				label: 'Destructive',
				flags: [ 'destructive' ],
				data: {
					progressive: false,
					constructive: false,
					destructive: true
				}
			} )
		]
	} );

	selector
		.on( 'select', function ( selected ) {
			iconsWidgets.forEach( function ( iconWidget ) {
				iconWidget.setFlags( selected.getData() );
			} );
		} )
		.selectItemByData( {
			progressive: false,
			constructive: false,
			destructive: false
		} );

	demo.$element.append(
		new OO.ui.PanelLayout( {
			expanded: false,
			framed: true
		} ).$element
			.addClass( 'demo-container demo-icons' )
			.attr( 'role', 'main' )
			.append(
				selector.$element,
				indicatorsFieldset.$element,
				iconsFieldsets.map( function ( item ) { return item.$element[ 0 ]; } )
			)
	);
};
<|endoftext|>


<commit_before>'use strict';

const { concat, map } = require('lodash');
const copy = require('recursive-copy');
const path = require('path');

const cleanBuildDirectory = require('./cleanBuildDirectory');
const compose = require('./compose');
const events = require('./events');
const loadPatternGraph = require('./loadPatternGraph');
const logger = require('./log');
const PatternGraph = require('./pattern_graph').PatternGraph;
const CompileState = require('./object_factory').CompileState;
const processMetaPattern = require('./processMetaPattern');
const pe = require('./pattern_exporter');
const lh = require('./lineage_hunter');
const pm = require('./plugin_manager');
const pluginMananger = new pm();
const markModifiedPatterns = require('./markModifiedPatterns');
const parseAllLinks = require('./parseAllLinks');
const render = require('./render');
const Pattern = require('./object_factory').Pattern;

let fs = require('fs-extra'); // eslint-disable-line
let pattern_exporter = new pe(); // eslint-disable-line

const lineage_hunter = new lh();

module.exports = async (deletePatternDir, patternlab, additionalData) => {
  await pluginMananger.raiseEvent(
    patternlab,
    events.PATTERNLAB_BUILD_START,
    patternlab
  );

  const paths = patternlab.config.paths;

  //
  // CHECK INCREMENTAL BUILD GRAPH
  //
  const graph = (patternlab.graph = loadPatternGraph(
    patternlab,
    deletePatternDir
  ));
  const graphNeedsUpgrade = !PatternGraph.checkVersion(graph);
  if (graphNeedsUpgrade) {
    logger.info(
      'Due to an upgrade, a complete rebuild is required and the public/patterns directory was deleted. ' +
        'Incremental build is available again on the next successful run.'
    );

    // Ensure that the freshly built graph has the latest version again.
    patternlab.graph.upgradeVersion();
  }

  // Flags
  patternlab.incrementalBuildsEnabled = !(
    deletePatternDir || graphNeedsUpgrade
  );

  //
  // CLEAN BUILD DIRECTORY, maybe
  //
  return cleanBuildDirectory(
    patternlab.incrementalBuildsEnabled,
    patternlab
  ).then(() => {
    patternlab.buildGlobalData(additionalData);

    return patternlab
      .processAllPatternsIterative(paths.source.patterns)
      .then(async () => {
        await pluginMananger.raiseEvent(
          patternlab,
          events.PATTERNLAB_PATTERN_ITERATION_END,
          patternlab
        );

        //now that all the main patterns are known, look for any links that might be within data and expand them
        //we need to do this before expanding patterns & partials into extendedTemplates, otherwise we could lose the data -> partial reference
        parseAllLinks(patternlab);

        //dive again to recursively include partials, filling out the
        //extendedTemplate property of the patternlab.patterns elements

        return patternlab
          .processAllPatternsRecursive(paths.source.patterns)
          .then(() => {
            //take the user defined head and foot and process any data and patterns that apply

            //todo this need to be made aware of multiple ui kits
            //perhaps we can check for a convention like [uikitname]_00-head.mustache, and if found, add them to patternlab.uikits[uikitname].userFoot
            //then, if present, use those during compose()
            const headPatternPromise = processMetaPattern(
              `_00-head.${patternlab.config.patternExtension}`,
              'userHead',
              patternlab
            );
            const footPatternPromise = processMetaPattern(
              `_01-foot.${patternlab.config.patternExtension}`,
              'userFoot',
              patternlab
            );

            return Promise.all([headPatternPromise, footPatternPromise])
              .then(() => {
                //cascade any patternStates
                lineage_hunter.cascade_pattern_states(patternlab);

                //set the pattern-specific header by compiling the general-header with data, and then adding it to the meta header
                return render(
                  Pattern.createEmpty({
                    // todo should this be uikit.header?
                    extendedTemplate: patternlab.header,
                  }),
                  {
                    cacheBuster: patternlab.cacheBuster,
                  }
                )
                  .then(results => {
                    patternlab.data.patternLabHead = results;

                    // If deletePatternDir == true or graph needs to be updated
                    // rebuild all patterns
                    let patternsToBuild = null;

                    // If deletePatternDir == true or graph needs to be updated
                    // rebuild all patterns
                    patternsToBuild = null;

                    if (patternlab.incrementalBuildsEnabled) {
                      // When the graph was loaded from file, some patterns might have been moved/deleted between runs
                      // so the graph data become out of sync
                      patternlab.graph.sync().forEach(n => {
                        logger.info('[Deleted/Moved] ' + n);
                      });

                      // TODO Find created or deleted files
                      const now = new Date().getTime();
                      markModifiedPatterns(now, patternlab);
                      patternsToBuild = patternlab.graph.compileOrder();
                    } else {
                      // build all patterns, mark all to be rebuilt
                      patternsToBuild = patternlab.patterns;
                      for (const p of patternsToBuild) {
                        p.compileState = CompileState.NEEDS_REBUILD;
                      }
                    }
                    //render all patterns last, so lineageR works
                    const allPatternsPromise = patternsToBuild.map(
                      async pattern =>
                        await compose(
                          pattern,
                          patternlab
                        )
                    );
                    //copy non-pattern files like JavaScript
                    const allJS = patternsToBuild.map(pattern => {
                      const { name, patternPartial, subdir } = pattern;
                      const {
                        source: { patterns: sourceDir },
                        public: { patterns: publicDir },
                      } = patternlab.config.paths;
                      const src = path.join(sourceDir, subdir);
                      const dest = path.join(publicDir, name);
                      return map(patternlab.uikits, uikit => {
                        return copy(
                          src,
                          path.resolve(process.cwd(), uikit.outputDir, dest),
                          {
                            overwrite: true,
                            filter: ['*.js'],
                            rename: () => {
                              return `${patternPartial}.js`;
                            },
                          }
                        ).on(copy.events.COPY_FILE_COMPLETE, () => {
                          logger.debug(
                            `Copied JavaScript files from ${src} to ${dest}`
                          );
                        });
                      });
                    });
                    return Promise.all(concat(allPatternsPromise, allJS))
                      .then(() => {
                        // Saves the pattern graph when all files have been compiled
                        PatternGraph.storeToFile(patternlab);
                        if (patternlab.config.exportToGraphViz) {
                          PatternGraph.exportToDot(
                            patternlab,
                            'dependencyGraph.dot'
                          );
                          logger.info(
                            `Exported pattern graph to ${path.join(
                              patternlab.config.paths.public.root,
                              'dependencyGraph.dot'
                            )}`
                          );
                        }

                        //export patterns if necessary
                        pattern_exporter.export_patterns(patternlab);
                      })
                      .catch(reason => {
                        console.log(reason);
                        logger.error('Error rendering patterns');
                      });
                  })
                  .catch(reason => {
                    console.log(reason);
                    logger.error('Error rendering pattern lab header');
                  });
              })
              .catch(reason => {
                console.log(reason);
                logger.error('Error processing meta patterns');
              });
          })
          .catch(reason => {
            console.log(reason);
            logger.error('Error processing patterns recursively');
          });
      })
      .catch(reason => {
        console.log(reason);
        logger.error('Error in buildPatterns()');
      });
  });
};
<commit_msg>fix(core): re-add cleanPublic fix<commit_after>'use strict';

const { concat, map } = require('lodash');
const copy = require('recursive-copy');
const path = require('path');

const cleanBuildDirectory = require('./cleanBuildDirectory');
const compose = require('./compose');
const events = require('./events');
const loadPatternGraph = require('./loadPatternGraph');
const logger = require('./log');
const PatternGraph = require('./pattern_graph').PatternGraph;
const CompileState = require('./object_factory').CompileState;
const processMetaPattern = require('./processMetaPattern');
const pe = require('./pattern_exporter');
const lh = require('./lineage_hunter');
const pm = require('./plugin_manager');
const pluginMananger = new pm();
const markModifiedPatterns = require('./markModifiedPatterns');
const parseAllLinks = require('./parseAllLinks');
const render = require('./render');
const Pattern = require('./object_factory').Pattern;

let fs = require('fs-extra'); // eslint-disable-line
let pattern_exporter = new pe(); // eslint-disable-line

const lineage_hunter = new lh();

module.exports = async (deletePatternDir, patternlab, additionalData) => {
  await pluginMananger.raiseEvent(
    patternlab,
    events.PATTERNLAB_BUILD_START,
    patternlab
  );

  const paths = patternlab.config.paths;

  //
  // CHECK INCREMENTAL BUILD GRAPH
  //
  const graph = (patternlab.graph = loadPatternGraph(
    patternlab,
    patternlab.config.cleanPublic
  ));
  const graphNeedsUpgrade = !PatternGraph.checkVersion(graph);
  if (graphNeedsUpgrade) {
    logger.info(
      'Due to an upgrade, a complete rebuild is required and the public/patterns directory was deleted. ' +
        'Incremental build is available again on the next successful run.'
    );

    // Ensure that the freshly built graph has the latest version again.
    patternlab.graph.upgradeVersion();
  }

  // Flags
  patternlab.incrementalBuildsEnabled = !(
    patternlab.config.cleanPublic || graphNeedsUpgrade
  );

  //
  // CLEAN BUILD DIRECTORY, maybe
  //
  return cleanBuildDirectory(
    patternlab.incrementalBuildsEnabled,
    patternlab
  ).then(() => {
    patternlab.buildGlobalData(additionalData);

    return patternlab
      .processAllPatternsIterative(paths.source.patterns)
      .then(async () => {
        await pluginMananger.raiseEvent(
          patternlab,
          events.PATTERNLAB_PATTERN_ITERATION_END,
          patternlab
        );

        //now that all the main patterns are known, look for any links that might be within data and expand them
        //we need to do this before expanding patterns & partials into extendedTemplates, otherwise we could lose the data -> partial reference
        parseAllLinks(patternlab);

        //dive again to recursively include partials, filling out the
        //extendedTemplate property of the patternlab.patterns elements

        return patternlab
          .processAllPatternsRecursive(paths.source.patterns)
          .then(() => {
            //take the user defined head and foot and process any data and patterns that apply

            //todo this need to be made aware of multiple ui kits
            //perhaps we can check for a convention like [uikitname]_00-head.mustache, and if found, add them to patternlab.uikits[uikitname].userFoot
            //then, if present, use those during compose()
            const headPatternPromise = processMetaPattern(
              `_00-head.${patternlab.config.patternExtension}`,
              'userHead',
              patternlab
            );
            const footPatternPromise = processMetaPattern(
              `_01-foot.${patternlab.config.patternExtension}`,
              'userFoot',
              patternlab
            );

            return Promise.all([headPatternPromise, footPatternPromise])
              .then(() => {
                //cascade any patternStates
                lineage_hunter.cascade_pattern_states(patternlab);

                //set the pattern-specific header by compiling the general-header with data, and then adding it to the meta header
                return render(
                  Pattern.createEmpty({
                    // todo should this be uikit.header?
                    extendedTemplate: patternlab.header,
                  }),
                  {
                    cacheBuster: patternlab.cacheBuster,
                  }
                )
                  .then(results => {
                    patternlab.data.patternLabHead = results;

                    // If deletePatternDir == true or graph needs to be updated
                    // rebuild all patterns
                    let patternsToBuild = null;

                    // If deletePatternDir == true or graph needs to be updated
                    // rebuild all patterns
                    patternsToBuild = null;

                    if (patternlab.incrementalBuildsEnabled) {
                      // When the graph was loaded from file, some patterns might have been moved/deleted between runs
                      // so the graph data become out of sync
                      patternlab.graph.sync().forEach(n => {
                        logger.info('[Deleted/Moved] ' + n);
                      });

                      // TODO Find created or deleted files
                      const now = new Date().getTime();
                      markModifiedPatterns(now, patternlab);
                      patternsToBuild = patternlab.graph.compileOrder();
                    } else {
                      // build all patterns, mark all to be rebuilt
                      patternsToBuild = patternlab.patterns;
                      for (const p of patternsToBuild) {
                        p.compileState = CompileState.NEEDS_REBUILD;
                      }
                    }
                    //render all patterns last, so lineageR works
                    const allPatternsPromise = patternsToBuild.map(
                      async pattern =>
                        await compose(
                          pattern,
                          patternlab
                        )
                    );
                    //copy non-pattern files like JavaScript
                    const allJS = patternsToBuild.map(pattern => {
                      const { name, patternPartial, subdir } = pattern;
                      const {
                        source: { patterns: sourceDir },
                        public: { patterns: publicDir },
                      } = patternlab.config.paths;
                      const src = path.join(sourceDir, subdir);
                      const dest = path.join(publicDir, name);
                      return map(patternlab.uikits, uikit => {
                        return copy(
                          src,
                          path.resolve(process.cwd(), uikit.outputDir, dest),
                          {
                            overwrite: true,
                            filter: ['*.js'],
                            rename: () => {
                              return `${patternPartial}.js`;
                            },
                          }
                        ).on(copy.events.COPY_FILE_COMPLETE, () => {
                          logger.debug(
                            `Copied JavaScript files from ${src} to ${dest}`
                          );
                        });
                      });
                    });
                    return Promise.all(concat(allPatternsPromise, allJS))
                      .then(() => {
                        // Saves the pattern graph when all files have been compiled
                        PatternGraph.storeToFile(patternlab);
                        if (patternlab.config.exportToGraphViz) {
                          PatternGraph.exportToDot(
                            patternlab,
                            'dependencyGraph.dot'
                          );
                          logger.info(
                            `Exported pattern graph to ${path.join(
                              patternlab.config.paths.public.root,
                              'dependencyGraph.dot'
                            )}`
                          );
                        }

                        //export patterns if necessary
                        pattern_exporter.export_patterns(patternlab);
                      })
                      .catch(reason => {
                        console.log(reason);
                        logger.error('Error rendering patterns');
                      });
                  })
                  .catch(reason => {
                    console.log(reason);
                    logger.error('Error rendering pattern lab header');
                  });
              })
              .catch(reason => {
                console.log(reason);
                logger.error('Error processing meta patterns');
              });
          })
          .catch(reason => {
            console.log(reason);
            logger.error('Error processing patterns recursively');
          });
      })
      .catch(reason => {
        console.log(reason);
        logger.error('Error in buildPatterns()');
      });
  });
};
<|endoftext|>


<commit_before>import Context from "../context/Context";
import i18next from "i18next";
import XHR from "i18next-xhr-backend";

class Translation {
    static init(options = {relativePath: null, fileExtension: null}) {
        return new Promise((resolve, reject) => {
            if (!options.relativePath) {
                reject("Please specify relativePath like 'new_'");
                return;
            }
            i18next
                .use(XHR)
                .init({
                    lng: Context.lcid.toString(),
                    fallbackLng: "1033",
                    backend: {
                        loadPath: this.getLoadPath(options.relativePath, options.fileExtension)
                    }
                }, (err, t) => {
                    err ? reject(err) : resolve(t);
                });
        });
    }

    static getLoadPath(relativePath = "", fileExtension = "json") {
        const resourceVersion = window.top.WEB_RESOURCE_ORG_VERSION_NUMBER || "",
            clientUrl = Context.clientUrl;
        let path = relativePath;
        path = path.startsWith(".") ? path.substr(1) : path;
        path = !path.startsWith("/") ? `/${path}` : path;
        return `${clientUrl}/${resourceVersion}/WebResources/${path}/{{lng}}.${fileExtension}`;
    }

    static translate(text, options) {
        if (text instanceof Array) {
            const translations = [];
            for (const txt of text) {
                translations.push(this.translate(txt, options));
            }
            return translations;
        } else {
            return i18next.t(text, options);
        }
    }

    static t(text, options) {
        return this.translate(text, options);
    }
}
export default Translation;
<commit_msg>Translation error handling<commit_after>import Context from "../context/Context";
import i18next from "i18next";
import XHR from "i18next-xhr-backend";

class Translation {
    static init(options = {relativePath: null, fileExtension: null}) {
        return new Promise((resolve, reject) => {
            if (!options.relativePath) {
                reject("Please specify relativePath like 'new_'");
                return;
            }
            i18next
                .use(XHR)
                .init({
                    lng: Context.lcid.toString(),
                    fallbackLng: "1033",
                    backend: {
                        loadPath: this.getLoadPath(options.relativePath, options.fileExtension)
                    }
                }, (err, t) => {
                    if (err) {
                        console.log(err.join("/n"));
                    }
                    resolve(t);
                });
        });
    }

    static getLoadPath(relativePath = "", fileExtension = "json") {
        const resourceVersion = window.top.WEB_RESOURCE_ORG_VERSION_NUMBER || "",
            clientUrl = Context.clientUrl;
        let path = relativePath;
        path = path.startsWith(".") ? path.substr(1) : path;
        path = !path.startsWith("/") ? `/${path}` : path;
        return `${clientUrl}/${resourceVersion}/WebResources/${path}/{{lng}}.${fileExtension}`;
    }

    static translate(text, options) {
        if (text instanceof Array) {
            const translations = [];
            for (const txt of text) {
                translations.push(this.translate(txt, options));
            }
            return translations;
        } else {
            return i18next.t(text, options);
        }
    }

    static t(text, options) {
        return this.translate(text, options);
    }
}
export default Translation;
<|endoftext|>


<commit_before>var tree_map = document.getElementById('tree_map')
    lang = document.documentElement.lang,
    squares = tree_map.getAttribute('squares'),
    group = tree_map.getAttribute('group'),
    depths = tree_map.getAttribute('depths').split('+'),
    dataset = tree_map.getAttribute('dataset'),
    filters = tree_map.getAttribute('filters'),
    urls = ['http://api.staging.dataviva.info/metadata/' + squares,
            'http://api.staging.dataviva.info/metadata/' + (group == 'section' ? 'product_section' : group),
            'http://api.staging.dataviva.info/' + dataset + '/year/' + squares + '/' + group + '?' + filters
    ];

dictionary['state'] = lang == 'en' ? 'State' : 'Estado';
dictionary['municipality'] = lang == 'en' ? 'Municipality' : 'Municipio';
dictionary['section'] = lang == 'en' ? 'Section' : 'Seção';
dictionary['product'] = lang == 'en' ? 'Product' : 'Produto';

var buildData = function(apiResponse, squaresMetadata, groupMetadata) {

    var getAttrByName = function(item, attr) {
        var index = headers.indexOf(attr);
        return item[index];
    }

    var data = [];
    var headers = apiResponse.headers;

    apiResponse.data.forEach(function(item) {
        try {
            var dataItem = {};

            headers.forEach(function(header){
                dataItem[header] = getAttrByName(item, header);
            });

            dataItem[squares] = squaresMetadata[dataItem[squares]]['name_' + lang];
            if (group == 'section')
                dataItem['icon'] = '/static/img/icons/' + group + '/section_' + dataItem[group] + '.png';
            dataItem[group] = groupMetadata[dataItem[group]]['name_' + lang];

            data.push(dataItem);
        } catch(e) {

        }
    });

    return data;
}

var loadViz = function(data) {

    var depthSelectorHelper = function(array, element) {
        var newArray = array.slice(0);
        newArray.splice(newArray.indexOf(element), 1);
        newArray.splice(0, 0, element);
        newArray.forEach(function(item, index){
            newArray[index] = {[dictionary[item]] : item}
        })
        return newArray;
    };

    var viz = d3plus.viz()
        .container('#tree_map')
        .data(data)
        .type('tree_map')
        .id(depths)
        .size('value')
        .depth(depths.length-1)
        .color(group)
        .labels({'align': 'left', 'valign': 'top'})
        .background('transparent')
        .ui([
            {
                'method' : 'size',
                'label': dictionary['value'],
                'value' : [{[dictionary['value']]: 'value'}, {'KG': 'kg'}]
            },
            {
                'method': function(value) {
                    viz.depth(depths.indexOf(value))
                        .draw();
                },
                'default': depths.indexOf(squares),
                'type': 'drop',
                'label': dictionary['depth'],
                'value': depthSelectorHelper(depths, squares)
            }
        ])
        .format({
            'text': function(text) {
                return text == 'value' || text == 'share' ? dictionary[text] : text;
            }
        })
        .icon({'value': 'icon', 'style': 'knockout'})
        .legend({'size': 40, 'filters': true, 'order': {'sort': 'desc', 'value': 'size'}})
        .time('year')
        .draw();
};

var loading = dataviva.ui.loading('.loading').text(dictionary['loading']);

$(document).ready(function() {
    ajaxQueue(
        urls,
        function(responses){
            var squaresMetadata = responses[0],
                groupMetadata = responses[1],
                data = buildData(responses[2], squaresMetadata, groupMetadata);

            loading.hide();
            loadViz(data);
        })
});<commit_msg>Refactors depth selector helper<commit_after>var tree_map = document.getElementById('tree_map')
    lang = document.documentElement.lang,
    squares = tree_map.getAttribute('squares'),
    group = tree_map.getAttribute('group'),
    depths = tree_map.getAttribute('depths').split('+'),
    dataset = tree_map.getAttribute('dataset'),
    filters = tree_map.getAttribute('filters'),
    urls = ['http://api.staging.dataviva.info/metadata/' + squares,
            'http://api.staging.dataviva.info/metadata/' + (group == 'section' ? 'product_section' : group),
            'http://api.staging.dataviva.info/' + dataset + '/year/' + squares + '/' + group + '?' + filters
    ];

dictionary['state'] = lang == 'en' ? 'State' : 'Estado';
dictionary['municipality'] = lang == 'en' ? 'Municipality' : 'Municipio';
dictionary['section'] = lang == 'en' ? 'Section' : 'Seção';
dictionary['product'] = lang == 'en' ? 'Product' : 'Produto';

var buildData = function(apiResponse, squaresMetadata, groupMetadata) {

    var getAttrByName = function(item, attr) {
        var index = headers.indexOf(attr);
        return item[index];
    }

    var data = [];
    var headers = apiResponse.headers;

    apiResponse.data.forEach(function(item) {
        try {
            var dataItem = {};

            headers.forEach(function(header){
                dataItem[header] = getAttrByName(item, header);
            });

            dataItem[squares] = squaresMetadata[dataItem[squares]]['name_' + lang];
            if (group == 'section')
                dataItem['icon'] = '/static/img/icons/' + group + '/section_' + dataItem[group] + '.png';
            dataItem[group] = groupMetadata[dataItem[group]]['name_' + lang];

            data.push(dataItem);
        } catch(e) {

        };
    });

    return data;
}

var loadViz = function(data) {

    var depthSelectorHelper = function(depths, squares) {
        var array = depths.slice(0);
        array.splice(array.indexOf(squares), 1);
        array.splice(0, 0, squares);
        array.forEach(function(item, i){
            array[i] = {[dictionary[item]] : item};
        });

        return {
            'method': function(value) {
                viz.depth(depths.indexOf(value));
                viz.draw();
            },
            'default': depths.indexOf(squares),
            'type': 'drop',
            'label': dictionary['depth'],
            'value': array
        };
    };

    var viz = d3plus.viz()
        .container('#tree_map')
        .data(data)
        .type('tree_map')
        .id(depths)
        .size('value')
        .depth(depths.length-1)
        .color(group)
        .labels({'align': 'left', 'valign': 'top'})
        .background('transparent')
        .ui([
            {
                'method' : 'size',
                'label': dictionary['value'],
                'value' : [{[dictionary['value']]: 'value'}, {'KG': 'kg'}]
            },
            depthSelectorHelper(depths, squares)
        ])
        .format({
            'text': function(text) {
                return text == 'value' || text == 'share' ? dictionary[text] : text;
            }
        })
        .icon({'value': 'icon', 'style': 'knockout'})
        .legend({'size': 40, 'filters': true, 'order': {'sort': 'desc', 'value': 'size'}})
        .time('year')
        .draw();
};

var loading = dataviva.ui.loading('.loading').text(dictionary['loading']);

$(document).ready(function() {
    ajaxQueue(
        urls,
        function(responses){
            var squaresMetadata = responses[0],
                groupMetadata = responses[1],
                data = buildData(responses[2], squaresMetadata, groupMetadata);

            loading.hide();
            loadViz(data);
        })
});<|endoftext|>