<commit_before>function main(fen, isPlayer, myColor, whoseTurn, isFinished, dests, wsUrl, isAnti) {
    if (myColor === "") myColor = null;
    var ground;
    var ws;
    var premove = null;
    var currentChatChannel = isPlayer ? "player" : "spectator";
    var chats = { player: [], spectator: [] };
    var clockInfo = { whiteUpdate: NaN, blackUpdate: NaN, whiteValue: NaN, blackValue: NaN, which: null };
    var clocksStarted = false;
    var stopClocks = false;
    var latestFlagRequest = 0;

    window.addEventListener("load", function () {
        ground = Chessground(document.getElementById("chessground"), {
            fen: fen,
            coordinates: true,
            orientation: myColor || "white",
            turnColor: whoseTurn,
            viewOnly: !isPlayer || isFinished,
            movable: {
                free: false,
                dropOff: "revert",
                showDests: false,
                dests: dests,
                color: myColor,
            },
            drawable: {
                enabled: true
            },
            events: {
                move: pieceMoved
            },
            premovable: {
                enabled: true,
                showDests: false,
                events: {
                    set: premoveSet,
                    unset: premoveUnset
                }
            }
        });

        document.getElementById("chat-input").addEventListener("keydown", chatKeyDown);
        if (document.getElementById("switch-to-players")) {
            document.getElementById("switch-to-players").addEventListener("click", switchToPlayersChat);
            document.getElementById("switch-to-spectators").addEventListener("click", switchToSpectatorsChat);
        }

        jsonXhr("/Variant960/Game/StoreAnonymousIdentifier", "POST", null, function (req, jsonResponse) {
            ws = new WebSocket(wsUrl);
            ws.addEventListener("open", wsOpened);
            ws.addEventListener("message", wsMessageReceived);
        },
        function (req, err) {
            displayError(err);
        });

    });

    function wsOpened() {
        ws.send(JSON.stringify({ "t": "syncClock" }));
        ws.send(JSON.stringify({ "t": "syncChat" }));
    }

    function wsMessageReceived(e) {
        var message = JSON.parse(e.data);
        switch (message.t) {
            case "moved":
                ground.set({
                    fen: message.fen,
                    lastMove: message.lastMove,
                    turnColor: message.turnColor,
                    movable: {
                        dests: message.dests
                    }
                });
                if (message.outcome) {
                    document.getElementById("game-result").textContent = message.outcome;
                    stopClockTicking();
                }
                if (isPlayer && myColor == message.turnColor && premove && !message.outcome) {
                    ws.send(JSON.stringify({ "t": "premove", "d": premove.origin + '-' + premove.destination }));
                    premoveUnset();
                    ground.set({
                        premovable: {
                            current: null
                        }
                    });
                }
                updateClockValue("white", message.clock.white);
                updateClockValue("black", message.clock.black);
                if (message.plies > 1) {
                    clockInfo.which = message.turnColor;
                    if (!clocksStarted) {
                        clocksStarted = true;
                        requestAnimationFrame(clockTick);
                    }
                }
                break;
            case "chat":
                chats[message.channel].push(message.msg);
                if (message.channel === currentChatChannel) {
                    var msgDiv = document.createElement("div");
                    msgDiv.innerHTML = message.msg;
                    document.getElementById("chat-content").appendChild(msgDiv);
                }
                break;
            case "clock":
                updateClockValue("white", message.white);
                updateClockValue("black", message.black);
                break;
            case "error":
                displayError(message.d);
                break;
            case "outcome":
                document.getElementById("game-result").textContent = message.outcome;
                stopClockTicking();
                break;
            case "chatSync":
                if (message.player) {
                    chats.player = message.player;
                }
                if (message.spectator) {
                    chats.spectator = message.spectator;
                }
                var placeholderEvent = { preventDefault: function () { } };
                if (currentChatChannel === "player") switchToPlayersChat(placeholderEvent);
                else switchToSpectatorsChat(placeholderEvent);
                break;
        }
    }

    function sendMoveMessage(orig, dest, promotion) {
        if (promotion) {
            ws.send(JSON.stringify({ "t": "move", "d": orig + '-' + dest + '-' + promotion.toLowerCase() }));
        } else {
            ws.send(JSON.stringify({ "t": "move", "d": orig + '-' + dest }));
        }
    }

    function pieceMoved(origin, destination, metadata) {
        if (ChessgroundExtensions.needsPromotion(ground, destination)) {
            ChessgroundExtensions.drawPromotionDialog(origin, destination, document.getElementById("chessground"), sendMoveMessage, ground, isAnti);
        } else {
            sendMoveMessage(origin, destination, null);
        }
    }

    function premoveSet(orig, dest) {
        premove = { origin: orig, destination: dest };
    }

    function premoveUnset() {
        premove = null;
    }

    function chatKeyDown(e) {
        e = e || window.event;
        if (e.keyCode !== 13) return;

        var messageToSend = document.getElementById("chat-input").value;
        document.getElementById("chat-input").value = "";
        ws.send(JSON.stringify({ "t": "chat", "d": messageToSend, "channel": currentChatChannel }));
    }

    function updateClockValue(which, seconds) {
        var latestUpdate = new Date();
        clockInfo[which + "Update"] = latestUpdate;
        clockInfo[which + "Value"] = seconds;
        updateClockElement(which);
    }

    function updateClockElement(which) {
        document.getElementById(which + "-clock").textContent = clockDisplay(clockInfo[which + "Value"]);
    }

    function clockDisplay(time) {
        var minutes = Math.floor(time / 60);
        var seconds = Math.floor((time % 60) * 10) / 10;
        return minutes + ":" + (seconds < 10 ? "0" + seconds.toFixed(1) : seconds.toFixed(1));
    }

    function clockTick() {
        if (stopClocks) return;
        var which = clockInfo.which;
        var latestUpdate = new Date();
        clockInfo[which + "Value"] = clockInfo[which + "Value"] - (latestUpdate - clockInfo[which + "Update"]) / 1000;
        clockInfo[which + "Update"] = latestUpdate;
        if (clockInfo[which + "Value"] <= 0 && (new Date() - latestFlagRequest) > 500) {
            latestFlagRequest = new Date();
            ws.send(JSON.stringify({ "t": "flag", "d": which }));
        }
        updateClockElement(which);
        requestAnimationFrame(clockTick);
    }

    function stopClockTicking() {
        stopClocks = true;
    }

    function switchToPlayersChat(e) {
        e = e || window.event;
        e.preventDefault();

        document.getElementById("chat-content").innerHTML = "";
        currentChatChannel = "player";
        var elem;
        for (var i = 0; i < chats.player.length; i++) {
            elem = document.createElement("div");
            elem.innerHTML = chats.player[i];
            document.getElementById("chat-content").appendChild(elem);
        }
    }

    function switchToSpectatorsChat(e) {
        e = e || window.event;
        e.preventDefault();

        document.getElementById("chat-content").innerHTML = "";
        currentChatChannel = "spectator";
        var elem;
        for (var i = 0; i < chats.spectator.length; i++) {
            elem = document.createElement("div");
            elem.innerHTML = chats.spectator[i];
            document.getElementById("chat-content").appendChild(elem);
        }
    }
}<commit_msg>Update style when switching chat channel<commit_after>function main(fen, isPlayer, myColor, whoseTurn, isFinished, dests, wsUrl, isAnti) {
    if (myColor === "") myColor = null;
    var ground;
    var ws;
    var premove = null;
    var currentChatChannel = isPlayer ? "player" : "spectator";
    var chats = { player: [], spectator: [] };
    var clockInfo = { whiteUpdate: NaN, blackUpdate: NaN, whiteValue: NaN, blackValue: NaN, which: null };
    var clocksStarted = false;
    var stopClocks = false;
    var latestFlagRequest = 0;

    window.addEventListener("load", function () {
        ground = Chessground(document.getElementById("chessground"), {
            fen: fen,
            coordinates: true,
            orientation: myColor || "white",
            turnColor: whoseTurn,
            viewOnly: !isPlayer || isFinished,
            movable: {
                free: false,
                dropOff: "revert",
                showDests: false,
                dests: dests,
                color: myColor,
            },
            drawable: {
                enabled: true
            },
            events: {
                move: pieceMoved
            },
            premovable: {
                enabled: true,
                showDests: false,
                events: {
                    set: premoveSet,
                    unset: premoveUnset
                }
            }
        });

        document.getElementById("chat-input").addEventListener("keydown", chatKeyDown);
        if (document.getElementById("switch-to-players")) {
            document.getElementById("switch-to-players").addEventListener("click", switchToPlayersChat);
            document.getElementById("switch-to-spectators").addEventListener("click", switchToSpectatorsChat);
        }

        jsonXhr("/Variant960/Game/StoreAnonymousIdentifier", "POST", null, function (req, jsonResponse) {
            ws = new WebSocket(wsUrl);
            ws.addEventListener("open", wsOpened);
            ws.addEventListener("message", wsMessageReceived);
        },
        function (req, err) {
            displayError(err);
        });

    });

    function wsOpened() {
        ws.send(JSON.stringify({ "t": "syncClock" }));
        ws.send(JSON.stringify({ "t": "syncChat" }));
    }

    function wsMessageReceived(e) {
        var message = JSON.parse(e.data);
        switch (message.t) {
            case "moved":
                ground.set({
                    fen: message.fen,
                    lastMove: message.lastMove,
                    turnColor: message.turnColor,
                    movable: {
                        dests: message.dests
                    }
                });
                if (message.outcome) {
                    document.getElementById("game-result").textContent = message.outcome;
                    stopClockTicking();
                }
                if (isPlayer && myColor == message.turnColor && premove && !message.outcome) {
                    ws.send(JSON.stringify({ "t": "premove", "d": premove.origin + '-' + premove.destination }));
                    premoveUnset();
                    ground.set({
                        premovable: {
                            current: null
                        }
                    });
                }
                updateClockValue("white", message.clock.white);
                updateClockValue("black", message.clock.black);
                if (message.plies > 1) {
                    clockInfo.which = message.turnColor;
                    if (!clocksStarted) {
                        clocksStarted = true;
                        requestAnimationFrame(clockTick);
                    }
                }
                break;
            case "chat":
                chats[message.channel].push(message.msg);
                if (message.channel === currentChatChannel) {
                    var msgDiv = document.createElement("div");
                    msgDiv.innerHTML = message.msg;
                    document.getElementById("chat-content").appendChild(msgDiv);
                }
                break;
            case "clock":
                updateClockValue("white", message.white);
                updateClockValue("black", message.black);
                break;
            case "error":
                displayError(message.d);
                break;
            case "outcome":
                document.getElementById("game-result").textContent = message.outcome;
                stopClockTicking();
                break;
            case "chatSync":
                if (message.player) {
                    chats.player = message.player;
                }
                if (message.spectator) {
                    chats.spectator = message.spectator;
                }
                var placeholderEvent = { preventDefault: function () { } };
                if (currentChatChannel === "player") switchToPlayersChat(placeholderEvent);
                else switchToSpectatorsChat(placeholderEvent);
                break;
        }
    }

    function sendMoveMessage(orig, dest, promotion) {
        if (promotion) {
            ws.send(JSON.stringify({ "t": "move", "d": orig + '-' + dest + '-' + promotion.toLowerCase() }));
        } else {
            ws.send(JSON.stringify({ "t": "move", "d": orig + '-' + dest }));
        }
    }

    function pieceMoved(origin, destination, metadata) {
        if (ChessgroundExtensions.needsPromotion(ground, destination)) {
            ChessgroundExtensions.drawPromotionDialog(origin, destination, document.getElementById("chessground"), sendMoveMessage, ground, isAnti);
        } else {
            sendMoveMessage(origin, destination, null);
        }
    }

    function premoveSet(orig, dest) {
        premove = { origin: orig, destination: dest };
    }

    function premoveUnset() {
        premove = null;
    }

    function chatKeyDown(e) {
        e = e || window.event;
        if (e.keyCode !== 13) return;

        var messageToSend = document.getElementById("chat-input").value;
        document.getElementById("chat-input").value = "";
        ws.send(JSON.stringify({ "t": "chat", "d": messageToSend, "channel": currentChatChannel }));
    }

    function updateClockValue(which, seconds) {
        var latestUpdate = new Date();
        clockInfo[which + "Update"] = latestUpdate;
        clockInfo[which + "Value"] = seconds;
        updateClockElement(which);
    }

    function updateClockElement(which) {
        document.getElementById(which + "-clock").textContent = clockDisplay(clockInfo[which + "Value"]);
    }

    function clockDisplay(time) {
        var minutes = Math.floor(time / 60);
        var seconds = Math.floor((time % 60) * 10) / 10;
        return minutes + ":" + (seconds < 10 ? "0" + seconds.toFixed(1) : seconds.toFixed(1));
    }

    function clockTick() {
        if (stopClocks) return;
        var which = clockInfo.which;
        var latestUpdate = new Date();
        clockInfo[which + "Value"] = clockInfo[which + "Value"] - (latestUpdate - clockInfo[which + "Update"]) / 1000;
        clockInfo[which + "Update"] = latestUpdate;
        if (clockInfo[which + "Value"] <= 0 && (new Date() - latestFlagRequest) > 500) {
            latestFlagRequest = new Date();
            ws.send(JSON.stringify({ "t": "flag", "d": which }));
        }
        updateClockElement(which);
        requestAnimationFrame(clockTick);
    }

    function stopClockTicking() {
        stopClocks = true;
    }

    function switchToPlayersChat(e) {
        e = e || window.event;
        e.preventDefault();

        document.getElementById("chat-content").innerHTML = "";
        currentChatChannel = "player";
        var elem;
        for (var i = 0; i < chats.player.length; i++) {
            elem = document.createElement("div");
            elem.innerHTML = chats.player[i];
            document.getElementById("chat-content").appendChild(elem);
        }

        if (document.getElementById("switch-to-players")) {
            document.getElementById("switch-to-players").classList.add("selected-chat");
            document.getElementById("switch-to-spectators").classList.remove("selected-chat");
        }
    }

    function switchToSpectatorsChat(e) {
        e = e || window.event;
        e.preventDefault();

        document.getElementById("chat-content").innerHTML = "";
        currentChatChannel = "spectator";
        var elem;
        for (var i = 0; i < chats.spectator.length; i++) {
            elem = document.createElement("div");
            elem.innerHTML = chats.spectator[i];
            document.getElementById("chat-content").appendChild(elem);
        }

        if (document.getElementById("switch-to-players")) {
            document.getElementById("switch-to-players").classList.remove("selected-chat");
            document.getElementById("switch-to-spectators").classList.add("selected-chat");
        }
    }
}<|endoftext|>


<commit_before>var LogEntries = require('le_node');
var assert = require('assert');

var log = function() {

  // seneca custom log handlers
  function debugHandler() {
    //    console.log(JSON.stringify(arguments));

    if (process.env.LOGENTRIES_ENABLED === 'true') {
      assert.ok(process.env.LOGENTRIES_DEBUG_TOKEN, 'No LOGENTRIES_DEBUG_TOKEN set');
      var le = new LogEntries({
        token: process.env.LOGENTRIES_DEBUG_TOKEN,
        flatten: true,
        flattenArrays: true
      });

      le.log('debug', arguments);
    }
  }

  function errorHandler() {
    console.error(JSON.stringify(arguments));

    if (process.env.LOGENTRIES_ENABLED === 'true') {
      assert.ok(process.env.LOGENTRIES_ERRORS_TOKEN, 'No LOGENTRIES_ERROR_TOKEN set');
      var le = new LogEntries({
        token: process.env.LOGENTRIES_ERRORS_TOKEN,
        flatten: true,
        flattenArrays: true
      });

      le.log('err', arguments);
    }
  }

  return {
    map:[{
      level:'debug', handler: debugHandler
    }, {
      level:'error', handler: errorHandler
    }]
  };
}

module.exports = {
  log: log(),

  'main': {
    'timeout': 66666
  },

  'bodyparser': {
    'json': {
      'limit': '10mb'
    }
  },

  // TODO does this still work?
  'user-roles': {
    roles: {
      'basic-user': {
        prefixmap: {
          '/dashboard/dojo-list': 1,
          '/dashboard/my-dojos': 1,
          '/dashboard/start-dojo': 1
        }
      },
      'cdf-admin': {
        prefixmap: {
          '/dashboard/dojo-list': 1,
          '/dashboard/my-dojos': 1,
          '/dashboard/start-dojo': 1,
          '/dashboard/manage-dojos': 1,
          '/dashboard/stats': 1
        }
      }
    }
  },

  //All of these routes are restricted.
  //Routes below can be unrestricted by adding them to the relevant user role above
  'web-access': {
    prefixlist: [
      '/dashboard/dojo-list',
      '/dashboard/my-dojos',
      '/dashboard/start-dojo',
      '/dashboard/manage-dojos',
      '/dashboard/stats',
      '/admin'
    ]
  },

  redis: {
    "host": process.env.REDIS_HOST || process.env.DOCKER_HOST_IP || process.env.TARGETIP || '127.0.0.1',
    "port": process.env.REDIS_PORT || 6379 // this is either configurable or in docker locally
  },

  webclient: {
    adultforum: process.env.ADULT_FORUM || 'http://localhost:4567'
  }

};
<commit_msg>increase timeout<commit_after>var LogEntries = require('le_node');
var assert = require('assert');

var log = function() {

  // seneca custom log handlers
  function debugHandler() {
    //    console.log(JSON.stringify(arguments));

    if (process.env.LOGENTRIES_ENABLED === 'true') {
      assert.ok(process.env.LOGENTRIES_DEBUG_TOKEN, 'No LOGENTRIES_DEBUG_TOKEN set');
      var le = new LogEntries({
        token: process.env.LOGENTRIES_DEBUG_TOKEN,
        flatten: true,
        flattenArrays: true
      });

      le.log('debug', arguments);
    }
  }

  function errorHandler() {
    console.error(JSON.stringify(arguments));

    if (process.env.LOGENTRIES_ENABLED === 'true') {
      assert.ok(process.env.LOGENTRIES_ERRORS_TOKEN, 'No LOGENTRIES_ERROR_TOKEN set');
      var le = new LogEntries({
        token: process.env.LOGENTRIES_ERRORS_TOKEN,
        flatten: true,
        flattenArrays: true
      });

      le.log('err', arguments);
    }
  }

  return {
    map:[{
      level:'debug', handler: debugHandler
    }, {
      level:'error', handler: errorHandler
    }]
  };
}

module.exports = {
  log: log(),

  'main': {
    'timeout': 120000
  },

  'bodyparser': {
    'json': {
      'limit': '10mb'
    }
  },

  // TODO does this still work?
  'user-roles': {
    roles: {
      'basic-user': {
        prefixmap: {
          '/dashboard/dojo-list': 1,
          '/dashboard/my-dojos': 1,
          '/dashboard/start-dojo': 1
        }
      },
      'cdf-admin': {
        prefixmap: {
          '/dashboard/dojo-list': 1,
          '/dashboard/my-dojos': 1,
          '/dashboard/start-dojo': 1,
          '/dashboard/manage-dojos': 1,
          '/dashboard/stats': 1
        }
      }
    }
  },

  //All of these routes are restricted.
  //Routes below can be unrestricted by adding them to the relevant user role above
  'web-access': {
    prefixlist: [
      '/dashboard/dojo-list',
      '/dashboard/my-dojos',
      '/dashboard/start-dojo',
      '/dashboard/manage-dojos',
      '/dashboard/stats',
      '/admin'
    ]
  },

  redis: {
    "host": process.env.REDIS_HOST || process.env.DOCKER_HOST_IP || process.env.TARGETIP || '127.0.0.1',
    "port": process.env.REDIS_PORT || 6379 // this is either configurable or in docker locally
  },

  webclient: {
    adultforum: process.env.ADULT_FORUM || 'http://localhost:4567'
  }

};
<|endoftext|>


<commit_before>(function ( $ ) {
	var ev = new $.Event('remove'),
	orig = $.fn.remove;
	$.fn.remove = function() {
		$(this).trigger(ev);
		return orig.apply(this, arguments);
	}
	var tabs = [];
	$.fn.bootstrapDynamicTabs = function(options) {
		var settings = $.extend({
            // These are the defaults.K
        }, options );

		if(this.find('.nav-tabs').length==0){
			this.append($('<ul/>', {class: 'nav nav-tabs'}).sortable({
				connectWith: this
			}));
		}else{
			this.find('.nav-tabs').sortable({
				connectWith: this
			});
		}

		if(this.find('.tab-content').length==0){
			this.append($('<div/>', {class: 'tab-content'}));
		}

		return this;
	};

	$.fn.addTab = function(options){
		var settings = $.extend({
            // These are the defaults.
            title: "Titulo Padrão",
            closable: true

        }, options );

		if(!settings.id){
			settings.id = trataId(settings.title);
		}else{
			settings.id = trataId(settings.id)
		}

		if(tabs.indexOf(settings.id)>=0){
			var aba = this.find('.nav-tabs').find('li').find('a[href="#'+settings.id+'"]');
			aba.tab('show');
			$(settings.id).tab('show');
		}else{

			tabs.push(settings.id);

			btn_close = $('<button/>',{
				class: 'close',
				type: 'button'
			}).text('x').click(function(){
				closer = $(this);
				a = closer.parent();
				href = a.attr('href');
				a.parent().remove();
				var ativo = $(href).hasClass('active');
				$(href).remove();
				var idx = href.substring(1)
				tabs.splice(tabs.indexOf(idx),1);
				if(ativo){
					$('.nav-tabs li:eq(0) a').tab('show');
				}

			});

			this.find('.active').removeClass('active')

			var ancora = $('<a/>',{
				href: '#'+settings.id,
				'data-toggle': 'tab'
			});

			if(settings.closable){
				ancora.mousedown(function(e) {
					e.stopPropagation();
					if(e.which == 2){
						a = $(this);
						href = a.attr('href');
						a.parent().remove();
						var ativo = $(href).hasClass('active');
						$(href).remove();
						var idx = href.substring(1)
						tabs.splice(tabs.indexOf(idx),1);
						if(ativo){
							$('.nav-tabs li:eq(0) a').tab('show');
						}
						return false;
					}
				})
			}

			if(settings.icon){
				ancora.append($('<i/>').addClass(settings.icon)).append(' ')
			}
			if(settings.closable){
				ancora.append(btn_close)
			}
			ancora.append(settings.title)

			//Carregando scripts
			if(settings.loadScripts){

				if(typeof(settings.loadScripts) == 'string'){
					var script = $('<script/>',{
						type:"text/javascript",
						src: settings.loadScripts
					});
					$('head').append(script)
					btn_close.on('click',function(){
						script.remove();
					})
				}else if(typeof(settings.loadScripts) == 'object'){
					var scripts = [];
					for(var i = 0 ; i < settings.loadScripts.length; i++){
						var script = $('<script/>',{
							type:"text/javascript",
							src: settings.loadScripts[i]
						});
						scripts.push(script);
						$('head').append(script);

					}
					btn_close.on('click',function(){
						for(var i = 0 ; i < scripts.length; i++){
							scripts[i].remove();
						}

					})
				}
			}

			//Carregand CSS
			if(settings.loadStyles){
				if(typeof(settings.loadStyles) == 'string'){
					var style = $('<link/>',{
						href: settings.loadStyles,
						rel: 'stylesheet',
						type: 'text/css'
					});
					$('head').append(style);
					btn_close.on('click', function(){
						style.remove();
					})

				}else if(typeof(settings.loadStyles) == 'object'){
					var styles = [];
					for(var i = 0 ; i < settings.loadStyles.length; i++){
						var style = $('<link/>',{
							href: settings.loadStyles[i],
							rel: 'stylesheet',
							type: 'text/css'
						});
						styles.push(style);
						$('head').append(style);
					}
					btn_close.on('click',function(){
						for(var i = 0 ; i < styles.length; i++){
							styles[i].remove();
						}

					})
				}
			}

			this.find('.nav-tabs').append($('<li/>', {class:'active'})
				.append(ancora));

			this.find('.tab-content').append($('<div/>', {
				class:'tab-pane active',
				id: settings.id
			}));

			var pagina = this.find('.tab-content').find('#'+settings.id);

			// pagina.append($('<script>').text('alert("23")'))

			if(settings.text){
				pagina.text(settings.text)
			}

			if(settings.html){
				pagina.html(settings.html)
			}

			if(settings.ajaxUrl){
				$.ajax({
		            mimeType: 'text/html; charset=utf-8', // ! Need set mimeType only when run from local file
		            url: settings.ajaxUrl,
		            type: 'GET',
		            success: function(data) {
		            	pagina.html(data)
		            },
		            error: function (jqXHR, textStatus, errorThrown) {
		            	alert(errorThrown);
		            },
		            dataType: "html"
		            // async: false
		        });
			}

		}
		return this;

	}

	$.fn.closeById = function(id){

		a = this.find('.nav-tabs').find('a[href="#'+id+'"]');
		href = a.attr('href');
		a.parent().remove();
		var ativo = $(href).hasClass('active');
		$(href).remove();
		var idx = href.substring(1)
		tabs.splice(tabs.indexOf(idx),1);
		if(ativo){
			$('.nav-tabs li:eq(0) a').tab('show');
		}
	}

	function trataId(s){
		var r=s.toLowerCase();
		r = r.replace(new RegExp("\\s", 'g'),"");
		r = r.replace(new RegExp("[àáâãäå]", 'g'),"a");
		r = r.replace(new RegExp("æ", 'g'),"ae");
		r = r.replace(new RegExp("ç", 'g'),"c");
		r = r.replace(new RegExp("[èéêë]", 'g'),"e");
		r = r.replace(new RegExp("[ìíîï]", 'g'),"i");
		r = r.replace(new RegExp("ñ", 'g'),"n");
		r = r.replace(new RegExp("[òóôõö]", 'g'),"o");
		r = r.replace(new RegExp("œ", 'g'),"oe");
		r = r.replace(new RegExp("[ùúûü]", 'g'),"u");
		r = r.replace(new RegExp("[ýÿ]", 'g'),"y");
		r = r.replace(new RegExp("\\W", 'g'),"");
		r = r.replace(/[^\w\s]/gi, '');
		return r;
	}

}( jQuery ));
<commit_msg>Assinatura<commit_after>/*!
 * Bootstrap Dynamic Tabs v1.0.3 (https://github.com/JayrAlencar/bootstrap-dynamic-tabs)
 *
 * Copyright 2015 Jayr Alencar (http://jayralencar.com.br)
 * Licensed under the The MIT License (MIT) (https://github.com/JayrAlencar/bootstrap-dynamic-tabs/blob/master/LICENSE)
 */
 (function ( $ ) {
 	var ev = new $.Event('remove'),
 	orig = $.fn.remove;
 	$.fn.remove = function() {
 		$(this).trigger(ev);
 		return orig.apply(this, arguments);
 	}
 	var tabs = [];
 	$.fn.bootstrapDynamicTabs = function(options) {
 		var settings = $.extend({
            // These are the defaults.K
        }, options );

 		if(this.find('.nav-tabs').length==0){
 			this.append($('<ul/>', {class: 'nav nav-tabs'}).sortable({
 				connectWith: this
 			}));
 		}else{
 			this.find('.nav-tabs').sortable({
 				connectWith: this
 			});
 		}

 		if(this.find('.tab-content').length==0){
 			this.append($('<div/>', {class: 'tab-content'}));
 		}

 		return this;
 	};

 	$.fn.addTab = function(options){
 		var settings = $.extend({
            // These are the defaults.
            title: "Titulo Padrão",
            closable: true

        }, options );

 		if(!settings.id){
 			settings.id = trataId(settings.title);
 		}else{
 			settings.id = trataId(settings.id)
 		}

 		if(tabs.indexOf(settings.id)>=0){
 			var aba = this.find('.nav-tabs').find('li').find('a[href="#'+settings.id+'"]');
 			aba.tab('show');
 			$(settings.id).tab('show');
 		}else{

 			tabs.push(settings.id);

 			btn_close = $('<button/>',{
 				class: 'close',
 				type: 'button'
 			}).text('x').click(function(){
 				closer = $(this);
 				a = closer.parent();
 				href = a.attr('href');
 				a.parent().remove();
 				var ativo = $(href).hasClass('active');
 				$(href).remove();
 				var idx = href.substring(1)
 				tabs.splice(tabs.indexOf(idx),1);
 				if(ativo){
 					$('.nav-tabs li:eq(0) a').tab('show');
 				}

 			});

 			this.find('.active').removeClass('active')

 			var ancora = $('<a/>',{
 				href: '#'+settings.id,
 				'data-toggle': 'tab'
 			});

 			if(settings.closable){
 				ancora.mousedown(function(e) {
 					e.stopPropagation();
 					if(e.which == 2){
 						a = $(this);
 						href = a.attr('href');
 						a.parent().remove();
 						var ativo = $(href).hasClass('active');
 						$(href).remove();
 						var idx = href.substring(1)
 						tabs.splice(tabs.indexOf(idx),1);
 						if(ativo){
 							$('.nav-tabs li:eq(0) a').tab('show');
 						}
 						return false;
 					}
 				})
 			}

 			if(settings.icon){
 				ancora.append($('<i/>').addClass(settings.icon)).append(' ')
 			}
 			if(settings.closable){
 				ancora.append(btn_close)
 			}
 			ancora.append(settings.title)

			//Carregando scripts
			if(settings.loadScripts){

				if(typeof(settings.loadScripts) == 'string'){
					var script = $('<script/>',{
						type:"text/javascript",
						src: settings.loadScripts
					});
					$('head').append(script)
					btn_close.on('click',function(){
						script.remove();
					})
				}else if(typeof(settings.loadScripts) == 'object'){
					var scripts = [];
					for(var i = 0 ; i < settings.loadScripts.length; i++){
						var script = $('<script/>',{
							type:"text/javascript",
							src: settings.loadScripts[i]
						});
						scripts.push(script);
						$('head').append(script);

					}
					btn_close.on('click',function(){
						for(var i = 0 ; i < scripts.length; i++){
							scripts[i].remove();
						}

					})
				}
			}

			//Carregand CSS
			if(settings.loadStyles){
				if(typeof(settings.loadStyles) == 'string'){
					var style = $('<link/>',{
						href: settings.loadStyles,
						rel: 'stylesheet',
						type: 'text/css'
					});
					$('head').append(style);
					btn_close.on('click', function(){
						style.remove();
					})

				}else if(typeof(settings.loadStyles) == 'object'){
					var styles = [];
					for(var i = 0 ; i < settings.loadStyles.length; i++){
						var style = $('<link/>',{
							href: settings.loadStyles[i],
							rel: 'stylesheet',
							type: 'text/css'
						});
						styles.push(style);
						$('head').append(style);
					}
					btn_close.on('click',function(){
						for(var i = 0 ; i < styles.length; i++){
							styles[i].remove();
						}

					})
				}
			}

			this.find('.nav-tabs').append($('<li/>', {class:'active'})
				.append(ancora));

			this.find('.tab-content').append($('<div/>', {
				class:'tab-pane active',
				id: settings.id
			}));

			var pagina = this.find('.tab-content').find('#'+settings.id);

			// pagina.append($('<script>').text('alert("23")'))

			if(settings.text){
				pagina.text(settings.text)
			}

			if(settings.html){
				pagina.html(settings.html)
			}

			if(settings.ajaxUrl){
				$.ajax({
		            mimeType: 'text/html; charset=utf-8', // ! Need set mimeType only when run from local file
		            url: settings.ajaxUrl,
		            type: 'GET',
		            success: function(data) {
		            	pagina.html(data)
		            },
		            error: function (jqXHR, textStatus, errorThrown) {
		            	alert(errorThrown);
		            },
		            dataType: "html"
		            // async: false
		        });
			}

		}
		return this;

	}

	$.fn.closeById = function(id){

		a = this.find('.nav-tabs').find('a[href="#'+id+'"]');
		href = a.attr('href');
		a.parent().remove();
		var ativo = $(href).hasClass('active');
		$(href).remove();
		var idx = href.substring(1)
		tabs.splice(tabs.indexOf(idx),1);
		if(ativo){
			$('.nav-tabs li:eq(0) a').tab('show');
		}
	}

	function trataId(s){
		var r=s.toLowerCase();
		r = r.replace(new RegExp("\\s", 'g'),"");
		r = r.replace(new RegExp("[àáâãäå]", 'g'),"a");
		r = r.replace(new RegExp("æ", 'g'),"ae");
		r = r.replace(new RegExp("ç", 'g'),"c");
		r = r.replace(new RegExp("[èéêë]", 'g'),"e");
		r = r.replace(new RegExp("[ìíîï]", 'g'),"i");
		r = r.replace(new RegExp("ñ", 'g'),"n");
		r = r.replace(new RegExp("[òóôõö]", 'g'),"o");
		r = r.replace(new RegExp("œ", 'g'),"oe");
		r = r.replace(new RegExp("[ùúûü]", 'g'),"u");
		r = r.replace(new RegExp("[ýÿ]", 'g'),"y");
		r = r.replace(new RegExp("\\W", 'g'),"");
		r = r.replace(/[^\w\s]/gi, '');
		return r;
	}

}( jQuery ));
<|endoftext|>


<commit_before>// This script is designed to be run within the react-native-android-builder Docker image
// It copies just the files it needs from the source 'fixtures' directory in the destination,
// before running gradlew (to avoid the need to download gradle multiple times).
const common = require('./common')
const fs = require('fs')
const path = require('path')

module.exports = {
  getRnDirectories: function getRnDirectories (within) {
    // Returns a list of path that look React Native test fixture folder under 'within'
    const isRnDirectory = source => fs.lstatSync(source).isDirectory() && source.match(/rn0\.[1-9][0-9]/)
    const getDirs = source => fs.readdirSync(source).map(name => path.join(source, name)).filter(isRnDirectory)
    return getDirs(within)
  },
  gather: function gather (fixtures, gatherDir) {
    // Used to gather the Gradle skeleton for each test fixture locally, for COPYing by the Dockerfile
    const target = path.resolve(gatherDir)
    console.log(`Gathering fixture files from ${fixtures}`)
    const rnDirs = this.getRnDirectories(fixtures)
    rnDirs.forEach((dir) => {
      const shortDir = path.relative(fixtures, dir)
      const copyTo = `${target}/${shortDir}/android/`
      common.run(`mkdir -p ${copyTo}`)
      common.run(`rsync -a ${dir}/android/gradle ${copyTo}`)
      common.run(`rsync ${dir}/android/build.gradle ${copyTo}`)
      common.run(`rsync ${dir}/android/gradle.properties ${copyTo}`)
      common.run(`rsync ${dir}/android/gradlew ${copyTo}`)
    })
  },
  prepare: function prepare (fixtures) {
    // Run 'gradlew' in each Android to force early download of Gradle
    const rnDirs = this.getRnDirectories(fixtures)
    rnDirs.forEach((dir) => {
      console.log(`Preparing Gradle builds for ${dir}`)
      common.changeDir(path.join(dir, 'android'))
      common.run('./gradlew build', true)
    })
  },
  buildAndroid: function buildAndroid (sourceFixtures, destFixtures) {
    const version = process.env.NOTIFIER_VERSION || common.determineVersion()
    const rnVersion = process.env.REACT_NATIVE_VERSION
    const registryUrl = process.env.REGISTRY_URL

    let jsSourceDir = 'scenario_js'
    if (process.env.JS_SOURCE_DIR) {
      jsSourceDir = process.env.JS_SOURCE_DIR
    }

    let artefactName = rnVersion
    if (process.env.ARTEFACT_NAME) {
      artefactName = process.env.ARTEFACT_NAME
    }

    console.log(`Installing notifier version: ${version}`)

    // Copy in files required
    common.run(`rsync -a ${sourceFixtures}/${rnVersion} ${destFixtures}`, true)
    common.run(`rsync -a ${sourceFixtures}/app/${jsSourceDir}/ ${destFixtures}/${rnVersion}`, true)
    common.run(`rsync -a ${sourceFixtures}/reactnative ${destFixtures}/${rnVersion}/android/app/src/main/java/com`, true)

    // JavaScript layer
    console.log(`Changing directory to: ${destFixtures}/${rnVersion}`)
    common.changeDir(`${destFixtures}/${rnVersion}`)
    common.run(`npm install --registry ${registryUrl}`, true)

    // Install notifier
    let command = `npm install @bugsnag/react-native@${version}  --registry ${registryUrl}`
    common.run(command, true)

    // Install any required secondary files
    if (fs.existsSync('./install.sh')) {
      console.log('Installing secondary requirements')
      common.run(`BUGSNAG_VERSION=${version} ./install.sh`, true)
    }

    // Native layer
    common.changeDir('android')
    common.run('./gradlew assembleRelease', true)

    // Finally, copy the APK back to the host
    fs.copyFileSync(`${destFixtures}/${rnVersion}/android/app/build/outputs/apk/release/app-release.apk`, `/app/build/${artefactName}.apk`)
  },
  buildIOS: function buildIOS () {
    const version = process.env.NOTIFIER_VERSION || common.determineVersion()
    const rnVersion = process.env.REACT_NATIVE_VERSION
    const registryUrl = process.env.REGISTRY_URL
    const fixtureDir = 'test/react-native/features/fixtures'
    const targetDir = `${fixtureDir}/${rnVersion}`
    const initialDir = process.cwd()

    let jsSourceDir = 'scenario_js'
    if (process.env.JS_SOURCE_DIR) {
      jsSourceDir = process.env.JS_SOURCE_DIR
    }

    let artefactName = rnVersion
    if (process.env.ARTEFACT_NAME) {
      artefactName = process.env.ARTEFACT_NAME
    }

    // We're not in docker so check the above are set
    if (rnVersion === undefined || registryUrl === undefined) {
      throw new Error('Both REACT_NATIVE_VERSION and REGISTRY_URL environment variables must be set')
    }

    // Copy the JS code into the test fixture
    console.log(`Copying JS app data from ${fixtureDir}/app to ${targetDir}`)
    common.run(`cp -r ${fixtureDir}/app/${jsSourceDir}/ ${targetDir}`, true)

    // JavaScript layer
    console.log(`Changing directory to: ${targetDir} and running "npm install"`)
    common.changeDir(`${targetDir}`)
    common.run(`npm install --registry ${registryUrl}`, true)

    // Install notifier
    console.log(`Installing notifier: ${version}`)
    let command = `npm install @bugsnag/react-native@${version}  --registry ${registryUrl}`
    common.run(command, true)

    // Install navigation trackers
    command = `npm install @bugsnag/plugin-react-navigation@${version} --registry ${registryUrl}`
    common.run(command, true)
    command = `npm install @bugsnag/plugin-react-native-navigation@${version} --registry ${registryUrl}`
    common.run(command, true)

    // Install any required secondary files
    if (fs.existsSync('./install.sh')) {
      common.run(`BUGSNAG_VERSION=${version} ./install.sh`, true)
    }

    // Performing local build steps
    console.log('Locating local build script')
    if (!fs.existsSync('./build.sh')) {
      throw new Error('Local iOS build file at ./build.sh could not be found')
    }
    common.run('./build.sh', true)

    // Copy file out to build directory
    common.changeDir(initialDir)
    if (!fs.existsSync('build')) {
      common.run('mkdir build')
    }
    fs.copyFileSync(`${targetDir}/output/output.ipa`, `build/${artefactName}.ipa`)
  }
}
<commit_msg>Tests/RN-native-nav: Avoid conflict in test script<commit_after>// This script is designed to be run within the react-native-android-builder Docker image
// It copies just the files it needs from the source 'fixtures' directory in the destination,
// before running gradlew (to avoid the need to download gradle multiple times).
const common = require('./common')
const fs = require('fs')
const path = require('path')

module.exports = {
  getRnDirectories: function getRnDirectories (within) {
    // Returns a list of path that look React Native test fixture folder under 'within'
    const isRnDirectory = source => fs.lstatSync(source).isDirectory() && source.match(/rn0\.[1-9][0-9]/)
    const getDirs = source => fs.readdirSync(source).map(name => path.join(source, name)).filter(isRnDirectory)
    return getDirs(within)
  },
  gather: function gather (fixtures, gatherDir) {
    // Used to gather the Gradle skeleton for each test fixture locally, for COPYing by the Dockerfile
    const target = path.resolve(gatherDir)
    console.log(`Gathering fixture files from ${fixtures}`)
    const rnDirs = this.getRnDirectories(fixtures)
    rnDirs.forEach((dir) => {
      const shortDir = path.relative(fixtures, dir)
      const copyTo = `${target}/${shortDir}/android/`
      common.run(`mkdir -p ${copyTo}`)
      common.run(`rsync -a ${dir}/android/gradle ${copyTo}`)
      common.run(`rsync ${dir}/android/build.gradle ${copyTo}`)
      common.run(`rsync ${dir}/android/gradle.properties ${copyTo}`)
      common.run(`rsync ${dir}/android/gradlew ${copyTo}`)
    })
  },
  prepare: function prepare (fixtures) {
    // Run 'gradlew' in each Android to force early download of Gradle
    const rnDirs = this.getRnDirectories(fixtures)
    rnDirs.forEach((dir) => {
      console.log(`Preparing Gradle builds for ${dir}`)
      common.changeDir(path.join(dir, 'android'))
      common.run('./gradlew build', true)
    })
  },
  buildAndroid: function buildAndroid (sourceFixtures, destFixtures) {
    const version = process.env.NOTIFIER_VERSION || common.determineVersion()
    const rnVersion = process.env.REACT_NATIVE_VERSION
    const registryUrl = process.env.REGISTRY_URL

    let jsSourceDir = 'scenario_js'
    if (process.env.JS_SOURCE_DIR) {
      jsSourceDir = process.env.JS_SOURCE_DIR
    }

    let artefactName = rnVersion
    if (process.env.ARTEFACT_NAME) {
      artefactName = process.env.ARTEFACT_NAME
    }

    console.log(`Installing notifier version: ${version}`)

    // Copy in files required
    common.run(`rsync -a ${sourceFixtures}/${rnVersion} ${destFixtures}`, true)
    common.run(`rsync -a ${sourceFixtures}/app/${jsSourceDir}/ ${destFixtures}/${rnVersion}`, true)
    common.run(`rsync -a ${sourceFixtures}/reactnative ${destFixtures}/${rnVersion}/android/app/src/main/java/com`, true)

    // JavaScript layer
    console.log(`Changing directory to: ${destFixtures}/${rnVersion}`)
    common.changeDir(`${destFixtures}/${rnVersion}`)
    common.run(`npm install --registry ${registryUrl}`, true)

    // Install notifier
    let command = `npm install @bugsnag/react-native@${version}  --registry ${registryUrl}`
    common.run(command, true)

    // Install any required secondary files
    if (fs.existsSync('./install.sh')) {
      console.log('Installing secondary requirements')
      common.run(`BUGSNAG_VERSION=${version} ./install.sh`, true)
    }

    // Native layer
    common.changeDir('android')
    common.run('./gradlew assembleRelease', true)

    // Finally, copy the APK back to the host
    fs.copyFileSync(`${destFixtures}/${rnVersion}/android/app/build/outputs/apk/release/app-release.apk`, `/app/build/${artefactName}.apk`)
  },
  buildIOS: function buildIOS () {
    const version = process.env.NOTIFIER_VERSION || common.determineVersion()
    const rnVersion = process.env.REACT_NATIVE_VERSION
    const registryUrl = process.env.REGISTRY_URL
    const fixtureDir = 'test/react-native/features/fixtures'
    const targetDir = `${fixtureDir}/${rnVersion}`
    const initialDir = process.cwd()

    let jsSourceDir = 'scenario_js'
    if (process.env.JS_SOURCE_DIR) {
      jsSourceDir = process.env.JS_SOURCE_DIR
    }

    let artefactName = rnVersion
    if (process.env.ARTEFACT_NAME) {
      artefactName = process.env.ARTEFACT_NAME
    }

    // We're not in docker so check the above are set
    if (rnVersion === undefined || registryUrl === undefined) {
      throw new Error('Both REACT_NATIVE_VERSION and REGISTRY_URL environment variables must be set')
    }

    // Copy the JS code into the test fixture
    console.log(`Copying JS app data from ${fixtureDir}/app to ${targetDir}`)
    common.run(`cp -r ${fixtureDir}/app/${jsSourceDir}/ ${targetDir}`, true)

    // JavaScript layer
    console.log(`Changing directory to: ${targetDir} and running "npm install"`)
    common.changeDir(`${targetDir}`)
    common.run(`npm install --registry ${registryUrl}`, true)

    // Install notifier
    console.log(`Installing notifier: ${version}`)
    let command = `npm install @bugsnag/react-native@${version}  --registry ${registryUrl}`
    common.run(command, true)

    // Install any required secondary files
    if (fs.existsSync('./install.sh')) {
      common.run(`BUGSNAG_VERSION=${version} ./install.sh`, true)
    }

    // Performing local build steps
    console.log('Locating local build script')
    if (!fs.existsSync('./build.sh')) {
      throw new Error('Local iOS build file at ./build.sh could not be found')
    }
    common.run('./build.sh', true)

    // Copy file out to build directory
    common.changeDir(initialDir)
    if (!fs.existsSync('build')) {
      common.run('mkdir build')
    }
    fs.copyFileSync(`${targetDir}/output/output.ipa`, `build/${artefactName}.ipa`)
  }
}
<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

var gulp = require('gulp');
var filter = require('gulp-filter');
var es = require('event-stream');
var gulptslint = require('gulp-tslint');
var tslint = require('tslint');

var all = [
	'*',
	'build/**/*',
	'extensions/**/*',
	'scripts/**/*',
	'src/**/*',
	'test/**/*'
];

var eolFilter = [
	'**',
	'!ThirdPartyNotices.txt',
	'!LICENSE.txt',
	'!extensions/**/out/**',
	'!**/node_modules/**',
	'!**/fixtures/**',
	'!**/*.{svg,exe,png,bmp,scpt,bat,cmd,cur,ttf,woff,eot}',
	'!build/{lib,tslintRules}/**/*.js',
	'!build/monaco/**',
	'!build/win32/**'
];

var indentationFilter = [
	'**',
	'!ThirdPartyNotices.txt',
	'!**/*.md',
	'!**/*.template',
	'!**/*.yml',
	'!**/lib/**',
	'!**/*.d.ts',
	'!**/*.d.ts.recipe',
	'!extensions/typescript/server/**',
	'!test/assert.js',
	'!**/package.json',
	'!**/npm-shrinkwrap.json',
	'!**/octicons/**',
	'!**/vs/languages/sass/test/common/example.scss',
	'!**/vs/languages/less/common/parser/less.grammar.txt',
	'!**/vs/languages/css/common/buildscripts/css-schema.xml',
	'!**/vs/base/common/marked/raw.marked.js',
	'!**/vs/base/common/winjs.base.raw.js',
	'!**/vs/base/node/terminateProcess.sh',
	'!**/vs/nls.js',
	'!**/vs/css.js',
	'!**/vs/loader.js',
	'!extensions/**/snippets/**',
	'!extensions/**/syntaxes/**',
	'!extensions/**/themes/**',
	'!extensions/**/colorize-fixtures/**',
	'!extensions/vscode-api-tests/testWorkspace/**'
];

var copyrightFilter = [
	'**',
	'!**/*.desktop',
	'!**/*.json',
	'!**/*.html',
	'!**/*.template',
	'!**/test/**',
	'!**/*.md',
	'!**/*.bat',
	'!**/*.cmd',
	'!resources/win32/bin/code.js',
	'!**/*.xml',
	'!**/*.sh',
	'!**/*.txt',
	'!**/*.xpm',
	'!extensions/markdown/media/tomorrow.css'
];

var tslintFilter = [
	'src/**/*.ts',
	'extensions/**/*.ts',
	'!**/*.d.ts',
	'!**/typings/**',
	'!src/vs/base/**/*.test.ts',
	'!src/vs/languages/**/*.test.ts',
	'!src/vs/workbench/**/*.test.ts',
	'!extensions/**/*.test.ts'
];

var copyrightHeader = [
	'/*---------------------------------------------------------------------------------------------',
	' *  Copyright (c) Microsoft Corporation. All rights reserved.',
	' *  Licensed under the MIT License. See License.txt in the project root for license information.',
	' *--------------------------------------------------------------------------------------------*/'
].join('\n');

function failureReporter(failure) {
	var name = failure.name || failure.fileName;
	var position = failure.startPosition;
	var line = position.lineAndCharacter ? position.lineAndCharacter.line : position.line;
	var character = position.lineAndCharacter ? position.lineAndCharacter.character : position.character;

	console.error(
		name
		+ ':' + (line + 1)
		+ ':' + (character + 1)
		+ ': ' + failure.failure
	);
}

gulp.task('tslint', function () {
	var options = { summarizeFailureOutput: true };

	function reporter(failures) {
		failures.forEach(failureReporter);
	}

	return gulp.src(all, { base: '.' })
		.pipe(filter(tslintFilter))
		.pipe(gulptslint({ rulesDirectory: 'build/lib/tslint' }))
		.pipe(gulptslint.report(reporter, options));
});

var hygiene = exports.hygiene = function (some, options) {
	options = options || {};
	var errorCount = 0;

	var eol = es.through(function (file) {
		if (/\r\n?/g.test(file.contents.toString('utf8'))) {
			console.error(file.relative + ': Bad EOL found');
			errorCount++;
		}

		this.emit('data', file);
	});

	var indentation = es.through(function (file) {
		file.contents
			.toString('utf8')
			.split(/\r\n|\r|\n/)
			.forEach(function (line, i) {
				if (/^\s*$/.test(line)) {
					// empty or whitespace lines are OK
				} else if (/^[\t]*[^\s]/.test(line)) {
					// good indent
				} else if (/^[\t]* \*/.test(line)) {
					// block comment using an extra space
				} else {
					console.error(file.relative + '(' + (i + 1) + ',1): Bad whitespace indentation');
					errorCount++;
				}
			});

		this.emit('data', file);
	});

	var copyrights = es.through(function (file) {
		if (file.contents.toString('utf8').indexOf(copyrightHeader) !== 0) {
			console.error(file.relative + ': Missing or bad copyright statement');
			errorCount++;
		}

		this.emit('data', file);
	});

	var tsl = es.through(function(file) {
		var configuration = tslint.findConfiguration(null, '.');
		var options = {
			formatter: 'json',
			configuration: configuration,
			rulesDirectory: 'build/lib/tslint'
		};
		var contents = file.contents.toString('utf8');
		var linter = new tslint(file.relative, contents, options);
		var result = linter.lint();
		if (result.failureCount > 0) {
			result.failures.forEach(failureReporter);
			errorCount += result.failureCount;
		}
		this.emit('data', file);
	});

	return gulp.src(some || all, { base: '.' })
		.pipe(filter(function (f) { return !f.stat.isDirectory(); }))
		.pipe(filter(eolFilter))
		.pipe(options.skipEOL ? es.through() : eol)
		.pipe(filter(indentationFilter))
		.pipe(indentation)
		.pipe(filter(copyrightFilter))
		.pipe(copyrights)
		.pipe(filter(tslintFilter))
		.pipe(tsl)
		.pipe(es.through(null, function () {
			if (errorCount > 0) {
				this.emit('error', 'Hygiene failed with ' + errorCount + ' errors. Check \'build/gulpfile.hygiene.js\'.');
			} else {
				this.emit('end');
			}
		}));
};

gulp.task('hygiene', function () {
	return hygiene();
});

// this allows us to run this as a git pre-commit hook
if (require.main === module) {
	var cp = require('child_process');
	cp.exec('git config core.autocrlf', function (err, out) {
		var skipEOL = out.trim() === 'true';

		cp.exec('git diff --cached --name-only', { maxBuffer: 2000 * 1024 }, function (err, out) {
			if (err) {
				console.error();
				console.error(err);
				process.exit(1);
			}

			var some = out
				.split(/\r?\n/)
				.filter(function (l) { return !!l; });

			hygiene(some, { skipEOL: skipEOL }).on('error', function (err) {
				console.error();
				console.error(err);
				process.exit(1);
			});
		});
	});
}
<commit_msg>cleanup hygiene<commit_after>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

const gulp = require('gulp');
const filter = require('gulp-filter');
const es = require('event-stream');
const gulptslint = require('gulp-tslint');
const tslint = require('tslint');

const all = [
	'*',
	'build/**/*',
	'extensions/**/*',
	'scripts/**/*',
	'src/**/*',
	'test/**/*'
];

const eolFilter = [
	'**',
	'!ThirdPartyNotices.txt',
	'!LICENSE.txt',
	'!extensions/**/out/**',
	'!**/node_modules/**',
	'!**/fixtures/**',
	'!**/*.{svg,exe,png,bmp,scpt,bat,cmd,cur,ttf,woff,eot}',
	'!build/{lib,tslintRules}/**/*.js',
	'!build/monaco/**',
	'!build/win32/**'
];

const indentationFilter = [
	'**',
	'!ThirdPartyNotices.txt',
	'!**/*.md',
	'!**/*.template',
	'!**/*.yml',
	'!**/lib/**',
	'!**/*.d.ts',
	'!**/*.d.ts.recipe',
	'!extensions/typescript/server/**',
	'!test/assert.js',
	'!**/package.json',
	'!**/npm-shrinkwrap.json',
	'!**/octicons/**',
	'!**/vs/languages/sass/test/common/example.scss',
	'!**/vs/languages/less/common/parser/less.grammar.txt',
	'!**/vs/languages/css/common/buildscripts/css-schema.xml',
	'!**/vs/base/common/marked/raw.marked.js',
	'!**/vs/base/common/winjs.base.raw.js',
	'!**/vs/base/node/terminateProcess.sh',
	'!**/vs/nls.js',
	'!**/vs/css.js',
	'!**/vs/loader.js',
	'!extensions/**/snippets/**',
	'!extensions/**/syntaxes/**',
	'!extensions/**/themes/**',
	'!extensions/**/colorize-fixtures/**',
	'!extensions/vscode-api-tests/testWorkspace/**'
];

const copyrightFilter = [
	'**',
	'!**/*.desktop',
	'!**/*.json',
	'!**/*.html',
	'!**/*.template',
	'!**/test/**',
	'!**/*.md',
	'!**/*.bat',
	'!**/*.cmd',
	'!resources/win32/bin/code.js',
	'!**/*.xml',
	'!**/*.sh',
	'!**/*.txt',
	'!**/*.xpm',
	'!extensions/markdown/media/tomorrow.css'
];

const tslintFilter = [
	'src/**/*.ts',
	'extensions/**/*.ts',
	'!**/*.d.ts',
	'!**/typings/**',
	'!src/vs/base/**/*.test.ts',
	'!src/vs/languages/**/*.test.ts',
	'!src/vs/workbench/**/*.test.ts',
	'!extensions/**/*.test.ts'
];

const copyrightHeader = [
	'/*---------------------------------------------------------------------------------------------',
	' *  Copyright (c) Microsoft Corporation. All rights reserved.',
	' *  Licensed under the MIT License. See License.txt in the project root for license information.',
	' *--------------------------------------------------------------------------------------------*/'
].join('\n');

function reportFailures(failures) {
	failures.forEach(failure => {
		const name = failure.name || failure.fileName;
		const position = failure.startPosition;
		const line = position.lineAndCharacter ? position.lineAndCharacter.line : position.line;
		const character = position.lineAndCharacter ? position.lineAndCharacter.character : position.character;

		console.error(`${ name }:${ line + 1}:${ character + 1 }:${ failure.failure }`);
	});
}

gulp.task('tslint', () => {
	const options = { summarizeFailureOutput: true };

	return gulp.src(all, { base: '.' })
		.pipe(filter(tslintFilter))
		.pipe(gulptslint({ rulesDirectory: 'build/lib/tslint' }))
		.pipe(gulptslint.report(reportFailures, options));
});

const hygiene = exports.hygiene = (some, options) => {
	options = options || {};
	let errorCount = 0;

	const eol = es.through(function (file) {
		if (/\r\n?/g.test(file.contents.toString('utf8'))) {
			console.error(file.relative + ': Bad EOL found');
			errorCount++;
		}

		this.emit('data', file);
	});

	const indentation = es.through(function (file) {
		file.contents
			.toString('utf8')
			.split(/\r\n|\r|\n/)
			.forEach((line, i) => {
				if (/^\s*$/.test(line)) {
					// empty or whitespace lines are OK
				} else if (/^[\t]*[^\s]/.test(line)) {
					// good indent
				} else if (/^[\t]* \*/.test(line)) {
					// block comment using an extra space
				} else {
					console.error(file.relative + '(' + (i + 1) + ',1): Bad whitespace indentation');
					errorCount++;
				}
			});

		this.emit('data', file);
	});

	const copyrights = es.through(function (file) {
		if (file.contents.toString('utf8').indexOf(copyrightHeader) !== 0) {
			console.error(file.relative + ': Missing or bad copyright statement');
			errorCount++;
		}

		this.emit('data', file);
	});

	const tsl = es.through(function(file) {
		const configuration = tslint.findConfiguration(null, '.');
		const options = { configuration, formatter: 'json', rulesDirectory: 'build/lib/tslint' };
		const contents = file.contents.toString('utf8');
		const linter = new tslint(file.relative, contents, options);
		const result = linter.lint();

		if (result.failureCount > 0) {
			reportFailures(result.failures);
			errorCount += result.failureCount;
		}

		this.emit('data', file);
	});

	return gulp.src(some || all, { base: '.' })
		.pipe(filter(f => !f.stat.isDirectory()))
		.pipe(filter(eolFilter))
		.pipe(options.skipEOL ? es.through() : eol)
		.pipe(filter(indentationFilter))
		.pipe(indentation)
		.pipe(filter(copyrightFilter))
		.pipe(copyrights)
		.pipe(filter(tslintFilter))
		.pipe(tsl)
		.pipe(es.through(null, function () {
			if (errorCount > 0) {
				this.emit('error', 'Hygiene failed with ' + errorCount + ' errors. Check \'build/gulpfile.hygiene.js\'.');
			} else {
				this.emit('end');
			}
		}));
};

gulp.task('hygiene', () => hygiene());

// this allows us to run hygiene as a git pre-commit hook
if (require.main === module) {
	const cp = require('child_process');

	cp.exec('git config core.autocrlf', (err, out) => {
		const skipEOL = out.trim() === 'true';

		cp.exec('git diff --cached --name-only', { maxBuffer: 2000 * 1024 }, (err, out) => {
			if (err) {
				console.error();
				console.error(err);
				process.exit(1);
			}

			const some = out
				.split(/\r?\n/)
				.filter(l => !!l);

			hygiene(some, { skipEOL: skipEOL }).on('error', err => {
				console.error();
				console.error(err);
				process.exit(1);
			});
		});
	});
}
<|endoftext|>


<commit_before>/**
 * Intelligently recommend entities via customizable, fuzzy recognition.
 * @class UITypeaheadInput
 */

import UIView from '../UIView';
import React from 'react';
import cx from 'classnames';
import {indexOf, map, noop, reduce} from 'lodash';

class UITypeaheadInput extends UIView {
    initialState() {
        return {
            entityMatchIndices: [],
            selectedEntityIndex: -1,
            uuid: this.uuid()
        };
    }

    componentWillMount() {
        if (this.props.defaultValue) {
            this.computeMatches(this.props.defaultValue);
        }
    }

    getSelectedEntityContent() {
        let entity = this.props.entities[this.state.selectedEntityIndex];

        return entity ? entity.content : '';
    }

    renderNotification() {
        return (

                {this.getSelectedEntityContent()}

        );
    }

    renderHint() {
        if (this.props.hint) {
            let userText = this.state.userInput;
            let raw = this.getSelectedEntityContent();
            let processed = '';

            if (   raw
                && raw.toLowerCase().indexOf(userText.toLowerCase()) === 0) {
                processed = raw.replace(new RegExp(userText, 'i'), userText);
            }

            return (
                <input {...this.props.hintAttributes}
                       ref='hint'
                       type='text'
                       className={cx({
                           'ui-typeahead-hint': true,
                           [this.props.hintAttributes.className]: !!this.props.hintAttributes.className
                       })}
                       value={processed}
                       disabled={true}
                       tabIndex='-1' />
            );
        }
    }

    handleMatchClick(index) {
        this.setState({selectedEntityIndex: index}, () => this.setValueWithSelectedEntity());
    }

    markMatchSubstring(entityContent, userInput) {
        if (this.props.markFunc) {
            return this.props.markFunc(entityContent, userInput);
        }

        let seekValue = userInput.toLowerCase();
        let indexStart = entityContent.toLowerCase().indexOf(seekValue);
        let indexEnd = indexStart + seekValue.length;

        return [
            {entityContent.slice(0, indexStart)},
            {entityContent.slice(indexStart, indexEnd)},
            {entityContent.slice(indexEnd)}
        ];
    }

    renderMatches() {
        if (this.state.entityMatchIndices.length) {
            return (

                    {map(this.state.entityMatchIndices, (index) => {
                        let entity = this.props.entities[index];

                        return (
                            <div {...entity}
                                 className={cx({
                                     'ui-typeahead-match': true,
                                     'ui-typeahead-match-selected': this.state.selectedEntityIndex === index,
                                     [entity.className]: !!entity.className
                                 })}
                                 key={this.createHashedKey(entity.content)}
                                 onClick={this.handleMatchClick.bind(this, index)}>
                                {this.markMatchSubstring(entity.content, this.state.userInput)}

                        );
                    })}

            );
        }
    }

    selectMatch(delta) {
        let matches = this.state.entityMatchIndices;
        let totalMatches = matches.length;
        let nextIndex = indexOf(matches, this.state.selectedEntityIndex) + delta;

        if (totalMatches) {
            if (nextIndex < 0) {
                nextIndex = totalMatches - 1; // reverse loop
            } else if (nextIndex >= totalMatches) {
                nextIndex = 0; // loop
            }

            this.setState({ selectedEntityIndex: matches[nextIndex] });
        }
    }

    resetMatches() {
        this.setState({
            selectedEntityIndex: -1,
            entityMatchIndices: []
        });
    }

    getInputNode() {
        return this.refs.input;
    }

    focusInput() {
        this.getInputNode().focus();
    }

    setValue(newValue) {
        this.getInputNode().value = newValue;

        this.setState({ userInput: newValue });
        this.resetMatches();
        this.focusInput();
    }

    cursorAtEndOfInput() {
        let node = this.getInputNode();

        return node.selectionStart === node.selectionEnd && node.selectionEnd === node.value.length;
    }

    setValueWithSelectedEntity() {
        this.props.onEntitySelected(this.state.selectedEntityIndex);

        if (this.props.clearPartialInputOnSelection) {
            this.setValue('');
        } else {
            this.setValue(this.getSelectedEntityContent());
        }
    }

    handleKeyDown(event) {
        switch (event.key) {
        case 'ArrowLeft':
            if (event.target.selectionStart > 1) {
                event.stopPropagation();
            }

            break;

        case 'Tab':
        case 'ArrowRight':
            if (   this.state.selectedEntityIndex !== -1
                && this.cursorAtEndOfInput()
                && this.getInputNode() === event.target) {
                event.nativeEvent.preventDefault();
                this.setValueWithSelectedEntity();
            }

            break;

        case 'ArrowUp':
            event.nativeEvent.preventDefault(); // block cursor movement
            this.selectMatch(-1);
            this.focusInput();
            break;

        case 'ArrowDown':
            event.nativeEvent.preventDefault(); // block cursor movement
            this.selectMatch(1);
            this.focusInput();
            break;

        case 'Escape':
            if (   this.state.selectedEntityIndex !== -1
                && this.getInputNode() === event.target) {
                this.resetMatches();
            }

            break;

        case 'Enter':
            if (   this.state.selectedEntityIndex !== -1
                && this.getInputNode() === event.target) {
                event.nativeEvent.preventDefault();
                this.setValueWithSelectedEntity();
            } else {
                this.props.onComplete(this.state.userInput);
            }

            break;
        }
    }

    // The default implementation is a simple "starts-with" search
    getMatchIndices(currentValue, entities) {
        if (this.props.matchFunc) {
            return this.props.matchFunc(currentValue, entities);
        }

        let seekValue = currentValue.toLowerCase();

        return reduce(entities, function seekMatch(result, entity, index) {
            return entity.content.toLowerCase().indexOf(seekValue) === 0 ? (result.push(index) && result) : result;
        }, []);
    }

    computeMatches(currentValue) {
        let entities = this.props.entities;
        let matches = currentValue === '' ? [] : this.getMatchIndices(currentValue, entities);

        this.setState({
            userInput: currentValue,
            selectedEntityIndex: matches.length ? matches[0] : -1,
            entityMatchIndices: matches
        });
    }

    handleInput(event) {
        this.computeMatches(event.target.value);

        if (this.props.onInput) {
            event.persist();
            this.props.onInput(event);
        }
    }

    render() {
        return (

                {this.renderNotification()}
                {this.renderHint()}

                <input {...this.props}
                       ref='input'
                       className={cx({
                           'ui-typeahead': true,
                           [this.props.className]: !!this.props.className
                       })}
                       aria-controls={this.state.uuid}
                       onInput={this.handleInput.bind(this)} />

                {this.renderMatches()}

        );
    }
}

UITypeaheadInput.propTypes = {
    className: React.PropTypes.string,
    clearPartialInputOnSelection: React.PropTypes.bool,
    defaultValue: React.PropTypes.string,
    entities: React.PropTypes.arrayOf(
        React.PropTypes.shape({
            content: React.PropTypes.string
        })
    ),
    hint: React.PropTypes.bool,
    hintAttributes: React.PropTypes.object,
    markFunc: React.PropTypes.func,
    matchFunc: React.PropTypes.func,
    matchWrapperAttributes: React.PropTypes.object,
    offscreenClass: React.PropTypes.string,
    onComplete: React.PropTypes.func,
    onInput: React.PropTypes.func,
    onEntitySelected: React.PropTypes.func,
    type: React.PropTypes.string,
    wrapperAttributes: React.PropTypes.object
};

UITypeaheadInput.defaultProps = {
    clearPartialInputOnSelection: false,
    entities: [],
    hintAttributes: {},
    matchWrapperAttributes: {},
    offscreenClass: 'ui-offscreen',
    onComplete: noop,
    onEntitySelected: noop,
    type: 'text',
    wrapperAttributes: {}
};

export default UITypeaheadInput;
<commit_msg>Recalculate typeahead match stuff if the entities change<commit_after>/**
 * Intelligently recommend entities via customizable, fuzzy recognition.
 * @class UITypeaheadInput
 */

import UIView from '../UIView';
import React from 'react';
import cx from 'classnames';
import {indexOf, map, noop, reduce} from 'lodash';

class UITypeaheadInput extends UIView {
    initialState() {
        return {
            entityMatchIndices: [],
            selectedEntityIndex: -1,
            uuid: this.uuid()
        };
    }

    componentWillMount() {
        if (this.props.defaultValue) {
            this.computeMatches(this.props.defaultValue);
        }
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.entities !== this.props.entities) {
            this.computeMatches(this.state.userInput, nextProps.entities);
        }
    }

    getSelectedEntityContent() {
        let entity = this.props.entities[this.state.selectedEntityIndex];

        return entity ? entity.content : '';
    }

    renderNotification() {
        return (

                {this.getSelectedEntityContent()}

        );
    }

    renderHint() {
        if (this.props.hint) {
            let userText = this.state.userInput;
            let raw = this.getSelectedEntityContent();
            let processed = '';

            if (   raw
                && raw.toLowerCase().indexOf(userText.toLowerCase()) === 0) {
                processed = raw.replace(new RegExp(userText, 'i'), userText);
            }

            return (
                <input {...this.props.hintAttributes}
                       ref='hint'
                       type='text'
                       className={cx({
                           'ui-typeahead-hint': true,
                           [this.props.hintAttributes.className]: !!this.props.hintAttributes.className
                       })}
                       value={processed}
                       disabled={true}
                       tabIndex='-1' />
            );
        }
    }

    handleMatchClick(index) {
        this.setState({selectedEntityIndex: index}, () => this.setValueWithSelectedEntity());
    }

    markMatchSubstring(entityContent, userInput) {
        if (this.props.markFunc) {
            return this.props.markFunc(entityContent, userInput);
        }

        let seekValue = userInput.toLowerCase();
        let indexStart = entityContent.toLowerCase().indexOf(seekValue);
        let indexEnd = indexStart + seekValue.length;

        return [
            {entityContent.slice(0, indexStart)},
            {entityContent.slice(indexStart, indexEnd)},
            {entityContent.slice(indexEnd)}
        ];
    }

    renderMatches() {
        if (this.state.entityMatchIndices.length) {
            return (

                    {map(this.state.entityMatchIndices, (index) => {
                        let entity = this.props.entities[index];

                        return (
                            <div {...entity}
                                 className={cx({
                                     'ui-typeahead-match': true,
                                     'ui-typeahead-match-selected': this.state.selectedEntityIndex === index,
                                     [entity.className]: !!entity.className
                                 })}
                                 key={this.createHashedKey(entity.content)}
                                 onClick={this.handleMatchClick.bind(this, index)}>
                                {this.markMatchSubstring(entity.content, this.state.userInput)}

                        );
                    })}

            );
        }
    }

    selectMatch(delta) {
        let matches = this.state.entityMatchIndices;
        let totalMatches = matches.length;
        let nextIndex = indexOf(matches, this.state.selectedEntityIndex) + delta;

        if (totalMatches) {
            if (nextIndex < 0) {
                nextIndex = totalMatches - 1; // reverse loop
            } else if (nextIndex >= totalMatches) {
                nextIndex = 0; // loop
            }

            this.setState({ selectedEntityIndex: matches[nextIndex] });
        }
    }

    resetMatches() {
        this.setState({
            selectedEntityIndex: -1,
            entityMatchIndices: []
        });
    }

    getInputNode() {
        return this.refs.input;
    }

    focusInput() {
        this.getInputNode().focus();
    }

    setValue(newValue) {
        this.getInputNode().value = newValue;

        this.setState({ userInput: newValue });
        this.resetMatches();
        this.focusInput();
    }

    cursorAtEndOfInput() {
        let node = this.getInputNode();

        return node.selectionStart === node.selectionEnd && node.selectionEnd === node.value.length;
    }

    setValueWithSelectedEntity() {
        this.props.onEntitySelected(this.state.selectedEntityIndex);

        if (this.props.clearPartialInputOnSelection) {
            this.setValue('');
        } else {
            this.setValue(this.getSelectedEntityContent());
        }
    }

    handleKeyDown(event) {
        switch (event.key) {
        case 'ArrowLeft':
            if (event.target.selectionStart > 1) {
                event.stopPropagation();
            }

            break;

        case 'Tab':
        case 'ArrowRight':
            if (   this.state.selectedEntityIndex !== -1
                && this.cursorAtEndOfInput()
                && this.getInputNode() === event.target) {
                event.nativeEvent.preventDefault();
                this.setValueWithSelectedEntity();
            }

            break;

        case 'ArrowUp':
            event.nativeEvent.preventDefault(); // block cursor movement
            this.selectMatch(-1);
            this.focusInput();
            break;

        case 'ArrowDown':
            event.nativeEvent.preventDefault(); // block cursor movement
            this.selectMatch(1);
            this.focusInput();
            break;

        case 'Escape':
            if (   this.state.selectedEntityIndex !== -1
                && this.getInputNode() === event.target) {
                this.resetMatches();
            }

            break;

        case 'Enter':
            if (   this.state.selectedEntityIndex !== -1
                && this.getInputNode() === event.target) {
                event.nativeEvent.preventDefault();
                this.setValueWithSelectedEntity();
            } else {
                this.props.onComplete(this.state.userInput);
            }

            break;
        }
    }

    // The default implementation is a simple "starts-with" search
    getMatchIndices(currentValue, entities) {
        if (this.props.matchFunc) {
            return this.props.matchFunc(currentValue, entities);
        }

        let seekValue = currentValue.toLowerCase();

        return reduce(entities, function seekMatch(result, entity, index) {
            return entity.content.toLowerCase().indexOf(seekValue) === 0 ? (result.push(index) && result) : result;
        }, []);
    }

    computeMatches(currentValue, entities = this.props.entities) {
        let matches = currentValue === '' ? [] : this.getMatchIndices(currentValue, entities);

        this.setState({
            userInput: currentValue,
            selectedEntityIndex: matches.length ? matches[0] : -1,
            entityMatchIndices: matches
        });
    }

    handleInput(event) {
        this.computeMatches(event.target.value);

        if (this.props.onInput) {
            event.persist();
            this.props.onInput(event);
        }
    }

    render() {
        return (

                {this.renderNotification()}
                {this.renderHint()}

                <input {...this.props}
                       ref='input'
                       className={cx({
                           'ui-typeahead': true,
                           [this.props.className]: !!this.props.className
                       })}
                       aria-controls={this.state.uuid}
                       onInput={this.handleInput.bind(this)} />

                {this.renderMatches()}

        );
    }
}

UITypeaheadInput.propTypes = {
    className: React.PropTypes.string,
    clearPartialInputOnSelection: React.PropTypes.bool,
    defaultValue: React.PropTypes.string,
    entities: React.PropTypes.arrayOf(
        React.PropTypes.shape({
            content: React.PropTypes.string
        })
    ),
    hint: React.PropTypes.bool,
    hintAttributes: React.PropTypes.object,
    markFunc: React.PropTypes.func,
    matchFunc: React.PropTypes.func,
    matchWrapperAttributes: React.PropTypes.object,
    offscreenClass: React.PropTypes.string,
    onComplete: React.PropTypes.func,
    onInput: React.PropTypes.func,
    onEntitySelected: React.PropTypes.func,
    type: React.PropTypes.string,
    wrapperAttributes: React.PropTypes.object
};

UITypeaheadInput.defaultProps = {
    clearPartialInputOnSelection: false,
    entities: [],
    hintAttributes: {},
    matchWrapperAttributes: {},
    offscreenClass: 'ui-offscreen',
    onComplete: noop,
    onEntitySelected: noop,
    type: 'text',
    wrapperAttributes: {}
};

export default UITypeaheadInput;
<|endoftext|>


<commit_before>import React, { Component, PropTypes as t } from 'react'

import { Button } from 'reactstrap'
import Media from '../Media'

import { updateList } from '../../actions/medias.js'
import { start, play, pause } from '../../actions/player.js'

import { graphql } from 'react-apollo'
import { connect } from 'react-redux'

import _get from 'lodash.get'
import _set from 'lodash.set'

import style from './style.styl'

class MediaList extends Component {
  constructor(props) {
    super(props)
  }

  componentWillReceiveProps(props) {
    if (!props.data.loading && props.data.medias !== this.props.data.medias) {
      props.updateList(props.data.medias)
    }

    if (props.data.medias.length - props.current < 10)
      this.props.loadMore()
  }

  render() {
    const { data, play, loadMore } = this.props
    return (

        {
          !data || data.loading ?

Loading...

          :

            {
              data.medias.map((media, i) =>
                <Media
                  key={i}
                  list={this.props.uniqueId}

                  index={i}
                  onPlay={() => play(this.props.player, i)}
                  {...media}
                />
              )
            }

        }
        <Button
          outline
          onClick={loadMore}
          className={style.loadMore}
        >
          Load More...
        </Button>

    )
  }
}

const mediaType = t.shape({
  id: t.string.isRequired,
  title: t.string.isRequired,
  url: t.string.isRequired,
  thumbnail: t.string,
  artist: t.string,
  description: t.string,
})

const dataType = t.shape({
  loading: t.bool.isRequired,
  medias: t.arrayOf(mediaType),
})

MediaList.propTypes = {
  data: dataType,
  uniqueId: t.string.isRequired,
  loadMore: t.func,
  play: t.func.isRequired,
}

const mapStateToProps = ({player}) => ({
  current: player.current,
  playing: player.playing,
  player
})
const mapDispatchToProps = (dispatch, ownProps) => ({
  play: (player, index) => {
    if (player.list === ownProps.uniqueId && index === player.current)
      player.playing ? dispatch(pause()) : dispatch(play())
    else
      dispatch({ type: 'START', payload: {
        current: index,
        list: ownProps.uniqueId,
        play: true
      }})
  },
  updateList: (list) => {
    dispatch(updateList(ownProps.uniqueId, list))
  }
})

export function withMedias(
  graphqlQuery,
  uniqueId,
  mediasPath = 'medias',
  vars = () => {}
) {
  return graphql(graphqlQuery, {
    options: (props) => ({
      variables: { ...vars(props), skip: 0 },
      forceFetch: true
    }),
    props: ({data, ownProps: props}) => ({
      data,
      uniqueId: typeof uniqueId === 'string' ? uniqueId : uniqueId(props),
      loadMore: () => data.fetchMore({
        variables: { skip: _get(data, mediasPath).length },
        updateQuery: (prev, { fetchMoreResult }) => {
          if (!fetchMoreResult.data) return prev
          let newData = Object.assign({}, prev)
          _set(newData, mediasPath, [
            ..._get(prev, mediasPath),
            ..._get(fetchMoreResult.data, mediasPath)
          ])
          return newData
        }
      })
    })
  })
}

export default connect(mapStateToProps, mapDispatchToProps)(MediaList)
<commit_msg>Fix medialist with hot loader<commit_after>import React, { Component, PropTypes as t } from 'react'

import { Button } from 'reactstrap'
import Media from '../Media'

import { updateList } from '../../actions/medias.js'
import { start, play, pause } from '../../actions/player.js'

import { graphql } from 'react-apollo'
import { connect } from 'react-redux'

import _get from 'lodash.get'
import _set from 'lodash.set'

import style from './style.styl'

class MediaList extends Component {
  constructor(props) {
    super(props)
  }

  componentWillReceiveProps(props) {
    if (!props.data.loading && props.data.medias !== this.props.data.medias) {
      props.updateList(props.data.medias)
    }

    if (!props.data.loading && props.data.medias.length - props.current < 10)
      this.props.loadMore()
  }

  render() {
    const { data, play, loadMore } = this.props
    return (

        {
          !data || data.loading ?

Loading...

          :

            {
              data.medias.map((media, i) =>
                <Media
                  key={i}
                  list={this.props.uniqueId}

                  index={i}
                  onPlay={() => play(this.props.player, i)}
                  {...media}
                />
              )
            }

        }
        <Button
          outline
          onClick={loadMore}
          className={style.loadMore}
        >
          Load More...
        </Button>

    )
  }
}

const mediaType = t.shape({
  id: t.string.isRequired,
  title: t.string.isRequired,
  url: t.string.isRequired,
  thumbnail: t.string,
  artist: t.string,
  description: t.string,
})

const dataType = t.shape({
  loading: t.bool.isRequired,
  medias: t.arrayOf(mediaType),
})

MediaList.propTypes = {
  data: dataType,
  uniqueId: t.string.isRequired,
  loadMore: t.func,
  play: t.func.isRequired,
}

const mapStateToProps = ({player}) => ({
  current: player.current,
  playing: player.playing,
  player
})
const mapDispatchToProps = (dispatch, ownProps) => ({
  play: (player, index) => {
    if (player.list === ownProps.uniqueId && index === player.current)
      player.playing ? dispatch(pause()) : dispatch(play())
    else
      dispatch({ type: 'START', payload: {
        current: index,
        list: ownProps.uniqueId,
        play: true
      }})
  },
  updateList: (list) => {
    dispatch(updateList(ownProps.uniqueId, list))
  }
})

export function withMedias(
  graphqlQuery,
  uniqueId,
  mediasPath = 'medias',
  vars = () => {}
) {
  return graphql(graphqlQuery, {
    options: (props) => ({
      variables: { ...vars(props), skip: 0 },
      forceFetch: true
    }),
    props: ({data, ownProps: props}) => ({
      data,
      uniqueId: typeof uniqueId === 'string' ? uniqueId : uniqueId(props),
      loadMore: () => data.fetchMore({
        variables: { skip: _get(data, mediasPath).length },
        updateQuery: (prev, { fetchMoreResult }) => {
          if (!fetchMoreResult.data) return prev
          let newData = Object.assign({}, prev)
          _set(newData, mediasPath, [
            ..._get(prev, mediasPath),
            ..._get(fetchMoreResult.data, mediasPath)
          ])
          return newData
        }
      })
    })
  })
}

export default connect(mapStateToProps, mapDispatchToProps)(MediaList)
<|endoftext|>


<commit_before>/*
* ---
* GLOBAL VARIABLES MODULE
* ---
*
* Sets up global variables for use by other modules.
* I'm trying to be fairly rigorous in documenting these since they're
* generally bad practice.
*
*/

/*
* CSRF token variable
* ---
*
* CodePen uses a meta tag to defend against XSRF.
*
* This variable grabs that tag's content to allow POST requests
* which are required to change settings/save Pens/etc.
*
*/
var csrfToken = $("meta[name='csrf-token']").attr("content");

/*
* Base URL variable
* ---
*
* Sets the base URL to be used with AJAX requests
* (it can vary due to https/non-https pages).
*
*/
var baseUrl = window.location.origin + "/";

/*
* Init Data Variable
* ---
*
* Grabs a copy of the init-data hidden input that's used on all CodePen pages.
*
* Awkwardly, these are actually merged into the window object by CodePen but
* this is an easier way to get organized access to everything.
*
* The JSON parsing gets incredibly awkward... Would prefer something easier.
*/
var initData = (function(){
  var data = $("#init-data").val();
  data = data.replace(/"{/g, '{') // Strips quotes from curly brackets
             .replace(/}"/g, '}')
             .replace(/\\"/g, '"') // Strips the first layer of slashes
             .replace(/\\"/g, '"'); // Strips the second layer of slashes
  return JSON.parse(data);
})();

// Sends initData off to init.js since content scripts can't access the window object.
// This allows conditional loading of modules based on initData.
var sendDataToContentScript = new CustomEvent("initDataMessage", {detail: initData});
window.dispatchEvent(sendDataToContentScript);<commit_msg>Fix title since it isn't *really* a module<commit_after>/*
* ---
* GLOBAL VARIABLES
* ---
*
* Sets up global variables for use by other modules.
* I'm trying to be fairly rigorous in documenting these since they're
* generally bad practice.
*
*/

/*
* CSRF token variable
* ---
*
* CodePen uses a meta tag to defend against XSRF.
*
* This variable grabs that tag's content to allow POST requests
* which are required to change settings/save Pens/etc.
*
*/
var csrfToken = $("meta[name='csrf-token']").attr("content");

/*
* Base URL variable
* ---
*
* Sets the base URL to be used with AJAX requests
* (it can vary due to https/non-https pages).
*
*/
var baseUrl = window.location.origin + "/";

/*
* Init Data Variable
* ---
*
* Grabs a copy of the init-data hidden input that's used on all CodePen pages.
*
* Awkwardly, these are actually merged into the window object by CodePen but
* this is an easier way to get organized access to everything.
*
* The JSON parsing gets incredibly awkward... Would prefer something easier.
*/
var initData = (function(){
  var data = $("#init-data").val();
  data = data.replace(/"{/g, '{') // Strips quotes from curly brackets
             .replace(/}"/g, '}')
             .replace(/"\[/g, '\[') // Strips quotes from square brackets
             .replace(/\]"/g, '\]')
             .replace(/\\"/g, '"') // Strips the first layer of slashes
             .replace(/\\"/g, '"'); // Strips the second layer of slashes
  return JSON.parse(data);
})();

// Sends initData off to init.js since content scripts can't access the window object.
// This allows conditional loading of modules based on initData.
var sendDataToContentScript = new CustomEvent("init-data-ready", {detail: initData});
window.dispatchEvent(sendDataToContentScript);<|endoftext|>


<commit_before>'use strict';
var createHash = require('create-hash/browser');
var Transform = require('stream').Transform;
var inherits = require('inherits')
var zeroBuffer = new Buffer(128)
zeroBuffer.fill(0)

module.exports = Hmac
inherits(Hmac, Transform)
function Hmac (alg, key) {
  if(!(this instanceof Hmac)) return new Hmac(alg, key)

  Transform.call(this)
  this._opad = opad
  this._alg = alg

  var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64

  key = this._key = !Buffer.isBuffer(key) ? new Buffer(key) : key

  if(key.length > blocksize) {
    key = createHash(alg).update(key).digest()
  } else if(key.length < blocksize) {
    key = Buffer.concat([key, zeroBuffer], blocksize)
  }

  var ipad = this._ipad = new Buffer(blocksize)
  var opad = this._opad = new Buffer(blocksize)

  for(var i = 0; i < blocksize; i++) {
    ipad[i] = key[i] ^ 0x36
    opad[i] = key[i] ^ 0x5C
  }

  this._hash = createHash(alg).update(ipad)
}

Hmac.prototype.update = function (data, enc) {
  this.write(data, enc)
  return this
}

Hmac.prototype._transform = function (data, _, next) {
  this._hash.update(data)
  next()
}

Hmac.prototype._flush = function (next) {
  var h = this._hash.digest()
  this.push(createHash(this._alg).update(this._opad).update(h).digest())
  next()
}

Hmac.prototype.digest = function (enc) {
  this.end()
  var outData = new Buffer('')
  var chunk
  while ((chunk = this.read())) {
    outData = Buffer.concat([outData, chunk])
  }
  if (enc) {
    outData = outData.toString(enc)
  }
  return outData
}
<commit_msg>some optimizations to make it lazier<commit_after>'use strict';
var createHash = require('create-hash/browser');
var Transform = require('stream').Transform;
var inherits = require('inherits')
var zeroBuffer = new Buffer(128)
zeroBuffer.fill(0)

module.exports = function createHmac(alg, key) {
  return new Hmac(alg, key)
}
inherits(Hmac, Transform)
function Hmac (alg, key) {

  Transform.call(this);
  this._opad = opad
  this._alg = alg

  var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64

  key = this._key = (typeof key === 'string') ? new Buffer(key) : key

  if(key.length > blocksize) {
    key = createHash(alg).update(key).digest()
  } else if(key.length < blocksize) {
    key = Buffer.concat([key, zeroBuffer], blocksize)
  }

  var ipad = this._ipad = new Buffer(blocksize)
  var opad = this._opad = new Buffer(blocksize)

  for(var i = 0; i < blocksize; i++) {
    ipad[i] = key[i] ^ 0x36
    opad[i] = key[i] ^ 0x5C
  }

  this._hash = createHash(alg).update(ipad)
}

Hmac.prototype.update = function (data, enc) {
  if (typeof data === 'string') {
    data = new Buffer(data, enc)
  }
  this._hash.update(data)
  return this
}

Hmac.prototype._transform = function (data, enc, next) {
  if (enc) {
    data = new Buffer(data, enc)
  }
  this._hash.update(data)
  next()
}

Hmac.prototype._flush = function (next) {
  this.push(this.digest())
  next()
}

Hmac.prototype.digest = function (enc) {
  var h = this._hash.digest()
  var outData = createHash(this._alg).update(this._opad).update(h).digest();
  if (enc) {
    outData = outData.toString(enc)
  }
  return outData
}
<|endoftext|>


<commit_before>define('button', {})<commit_msg>button<commit_after>nb.define('button', {})<|endoftext|>