<commit_before>var _gStart, _gEnd;
var _gColors = {};

$(function() {
	var cstring;
	if(typeof(Storage) !== "undefined") {
		cstring = localStorage.getItem("johwanghee.papas.colors");
	}

	if(cstring != undefined && cstring.length > 0) {
		parseData(cstring);
	} else {
		$.get(url+"assets/colors.csv", function(data) {
			parseData(data);
			if(typeof(Storage) !== "undefined") {
				localStorage.setItem("johwanghee.papas.colors",data);
			}
		});
	}

	$("#searchText").keyup(function() {
		search($(this).val());
	});

	$(window).scroll(function() {
		if($(window).scrollTop() + window.innerHeight == $(document).height()) {
			displayColors();
		}
	});
});

function search(searchKeys) {
	if(searchKeys == '') {
		displayColors(_gColors[_gBrand]);
	} else {
		var temps = [];
		var i, key;
		var keys = searchKeys.split(',');
		var c;
		for(i in keys) {
			key = keys[i];
			if(key.length > 1) {
				c = getColors(_gColors[_gBrand], _gSearchType, key);
				if(c.length > 0) {
					temps.push.apply(temps, [[0,'▽   " '+key+' " search result : '+c.length+'   ▽']]);
					temps.push.apply(temps, c);
				}
			}
		}
		displayColors(temps);
	}
}

function parseData(data) {
	_gStart = performance.now();
	var results = Papa.parse(data, buildConfig());
	_gColors['all'] = results.data;
	var i, temp, type;
	for(i in results.data) {
		temp = results.data[i];
		type = temp[1];
		if(_gColors[type] == undefined) {
			_gColors[type] = [];
		}
		_gColors[type].push(temp);
	}
	displayColors(_gColors['all']);
}

function getColors(data, type, key) {
	var temp = [];
	var i;
	var color;
	if(key != undefined && key.length > 0) {
		for(i in data) {
			color = data[i];
			switch(type) {
				case 'NO':
					if(color[2].toUpperCase().indexOf(key.toUpperCase()) > -1) {
						temp.push(color);
					}
					break;
				case 'NM':
					if(color[5].toUpperCase().indexOf(key.toUpperCase()) > -1) {
						temp.push(color);
					}
					break;
				case 'HX':
					if(color[4].toUpperCase().indexOf(key.toUpperCase()) > -1) {
						temp.push(color);
					}
					break;
			}
		}
	}
	return temp;
}

function buildConfig() {
	return {
		delimiter: "",
		newline: "",
		header: false,
		dynamicTyping: false,
		preview: 0,
		step: undefined,
		encoding: "",
		worker: false,
		comments: "#",
		complete: completeFn,
		error: errorFn,
		download: false,
		fastMode: false,
		skipEmptyLines: true,
		chunk: undefined
	};
}

function errorFn(error, file) {
	console.log("ERROR:", error, file);
}

function completeFn() {
	_gEnd = performance.now();
}

var _gTempColor;
function displayColors(data) {
	if(data != undefined) {
		_gTempColor = data.slice(0);
		$("#colors").empty();
	}
	if(_gTempColor == undefined || _gTempColor.length == 0) {
		return false;
	}
	var margin = $("#nav").height()+5;
	var colors = _gTempColor.slice(0);
	var topCel = '
{title}

';
	var cel = '
{no}
{name} - 0x{hex}
{type} : {matt}
';
	var i,len;
	var el;
	var color;
	len = colors.length;
	if(len > 50) len = 50;

	for(i=0;i<len;++i) {
		color = colors[i];
		if(color[0] == 0) {
			el = topCel;
			el = el.replace("{title}",color[1]);
			el = el.replace("{margin}",(i==0)? margin : 1 );
		} else {
			el = cel;
			el = el.replace("{color}",color[4]);
			el = el.replace("{no}",color[2]);
			el = el.replace("{name}",color[5]);
			el = el.replace("{hex}",color[4]);
			el = el.replace("{type}",color[6]);
			el = el.replace("{matt}",color[7]);
			el = el.replace("{margin}",(i==0)? margin : 1 );
		}
		$("#colors").append(el);
		_gTempColor.splice( 0, 1 );
	}
}

var _gSearchType = 'NO';
var _gBrand = 'all';
var _gSearchTypeLabel = {"NO":"Model No.","NM":"Color Name","HX":"Hex Code"}
function changeSearchType(type) {
	_gSearchType = type;
	var txt = "Search ( {type} )";
	txt = txt.replace("{type}",_gSearchTypeLabel[type]);
	$("#searchLabel").text(txt);
}

function changeBrand(brand) {
	_gBrand = brand;
	var txt = "Brand ( {brand} )";
	txt = txt.replace("{brand}",brand);
	$("#brandLebel").text(txt);
	search($("#searchText").val());
}
<commit_msg>bug fix<commit_after>var _gStart, _gEnd;
var _gColors = {};

$(function() {
	var cstring;
	if(typeof(Storage) !== "undefined") {
		cstring = localStorage.getItem("johwanghee.papas.colors");
	}

	if(cstring != undefined && cstring.length > 0) {
		parseData(cstring);
	} else {
		$.get(url+"assets/colors.csv", function(data) {
			parseData(data);
			if(typeof(Storage) !== "undefined") {
				localStorage.setItem("johwanghee.papas.colors",data);
			}
		});
	}

	$("#searchText").keyup(function() {
		search($(this).val());
	});

	$(window).scroll(function() {
		if($(window).scrollTop() + window.innerHeight == $(document).height()) {
			displayColors();
		}
	});
});

function search(searchKeys) {
	if(searchKeys == '') {
		displayColors(_gColors[_gBrand]);
	} else {
		var temps = [];
		var i, key;
		var keys = searchKeys.split(',');
		var c;
		for(i in searchKeys) {
			key = searchKeys[i];
			if(key.length > 1) {
				c = getColors(_gColors[_gBrand], _gSearchType, key);
				if(c.length > 0) {
					temps.push.apply(temps, [[0,'▽   " '+key+' " search result : '+c.length+'   ▽']]);
					temps.push.apply(temps, c);
				}
			}
		}
		displayColors(temps);
	}
}

function parseData(data) {
	_gStart = performance.now();
	var results = Papa.parse(data, buildConfig());
	_gColors['all'] = results.data;
	var i, temp, type;
	for(i in results.data) {
		temp = results.data[i];
		type = temp[1];
		if(_gColors[type] == undefined) {
			_gColors[type] = [];
		}
		_gColors[type].push(temp);
	}
	displayColors(_gColors['all']);
}

function getColors(data, type, key) {
	var temp = [];
	var i;
	var color;
	if(key != undefined && key.length > 0) {
		for(i in data) {
			color = data[i];
			switch(type) {
				case 'NO':
					if(color[2].toUpperCase().indexOf(key.toUpperCase()) > -1) {
						temp.push(color);
					}
					break;
				case 'NM':
					if(color[5].toUpperCase().indexOf(key.toUpperCase()) > -1) {
						temp.push(color);
					}
					break;
				case 'HX':
					if(color[4].toUpperCase().indexOf(key.toUpperCase()) > -1) {
						temp.push(color);
					}
					break;
			}
		}
	}
	return temp;
}

function buildConfig() {
	return {
		delimiter: "",
		newline: "",
		header: false,
		dynamicTyping: false,
		preview: 0,
		step: undefined,
		encoding: "",
		worker: false,
		comments: "#",
		complete: completeFn,
		error: errorFn,
		download: false,
		fastMode: false,
		skipEmptyLines: true,
		chunk: undefined
	};
}

function errorFn(error, file) {
	console.log("ERROR:", error, file);
}

function completeFn() {
	_gEnd = performance.now();
}

var _gTempColor;
function displayColors(data) {
	if(data != undefined) {
		_gTempColor = data.slice(0);
		$("#colors").empty();
	}
	if(_gTempColor == undefined || _gTempColor.length == 0) {
		return false;
	}
	var margin = $("#nav").height()+5;
	var colors = _gTempColor.slice(0);
	var topCel = '
{title}

';
	var cel = '
{no}
{name} - 0x{hex}
{type} : {matt}
';
	var i,len;
	var el;
	var color;
	len = colors.length;
	if(len > 50) len = 50;

	for(i=0;i<len;++i) {
		color = colors[i];
		if(color[0] == 0) {
			el = topCel;
			el = el.replace("{title}",color[1]);
			el = el.replace("{margin}",(i==0)? margin : 1 );
		} else {
			el = cel;
			el = el.replace("{color}",color[4]);
			el = el.replace("{no}",color[2]);
			el = el.replace("{name}",color[5]);
			el = el.replace("{hex}",color[4]);
			el = el.replace("{type}",color[6]);
			el = el.replace("{matt}",color[7]);
			el = el.replace("{margin}",(i==0)? margin : 1 );
		}
		$("#colors").append(el);
		_gTempColor.splice( 0, 1 );
	}
}

var _gSearchType = 'NO';
var _gBrand = 'all';
var _gSearchTypeLabel = {"NO":"Model No.","NM":"Color Name","HX":"Hex Code"}
function changeSearchType(type) {
	_gSearchType = type;
	var txt = "Search ( {type} )";
	txt = txt.replace("{type}",_gSearchTypeLabel[type]);
	$("#searchLabel").text(txt);
}

function changeBrand(brand) {
	_gBrand = brand;
	var txt = "Brand ( {brand} )";
	txt = txt.replace("{brand}",brand);
	$("#brandLebel").text(txt);
	search($("#searchText").val());
}
<|endoftext|>


<commit_before>define([
    'underscore',
    'orotranslation/js/translator',
    'oroui/js/app/views/base/view',
    'oroui/js/modal'
], function(_, __, BaseView, Modal) {
    'use strict';

    var AttendeeNotifierView = BaseView.extend({
        /** @property {Array} */
        exclusions: [
            'input[name="input_action"]',
            'input[name$="[backgroundColor]"]',
            'select[name*="[reminders]"]',
            'input[name*="[reminders]"]',
            'select[name*="[calendarUid]"]'
        ],

        /**
         * @constructor
         */
        initialize: function() {
            var self = this;
            this.$form = this.$el.closest('form');
            this.$form.on('select2-data-loaded', function() {
                self.formInitialState = self.getFormState();
                self.attendeeInitialValues = self.getAttendeeValues();
            });
            this.formInitialState = this.getFormState();
            this.attendeeInitialValues = this.getAttendeeValues();
            this.isModalShown = false;

            this.$form.parent().on('submit.' + this.cid, _.bind(function(e) {
                if (!this.isModalShown && this.getFormState() !== this.formInitialState && this.hasAttendees() &&
                    _.intersection(this.attendeeInitialValues, this.getAttendeeValues()).length > 0
                    // since we notify all added and deleted users anyway we need ask only about users that were
                    // invited before and left in attendees for now
                ) {
                    this.getConfirmDialog().open();
                    this.isModalShown = true;
                    e.preventDefault();
                }
            }, this));
        },

        /**
         * @inheritDoc
         */
        dispose: function() {
            if (!this.disposed) {
                if (this.$form) {
                    this.$form.parent().off('.' + this.cid);
                }
                if (this.confirmModal) {
                    this.confirmModal.dispose();
                    delete this.confirmModal;
                }
            }
            AttendeeNotifierView.__super__.dispose.call(this);
        },

        getAttendeeValues: function() {
            var value = this.$form.find('input[name*="[attendees]"]').val();
            return value.length > 0 ? value.split(';') : [];
        },

        hasAttendees: function() {
            return this.$form.find('input[name*="[attendees]"]').val().indexOf('entityId') >= 0;
        },

        getConfirmDialog: function() {
            if (!this.confirmModal) {
                this.confirmModal = AttendeeNotifierView.createConfirmNotificationDialog();
                this.listenTo(this.confirmModal, 'ok', _.bind(function() {
                    this.$form.find('input[name*="[notifyAttendees]"]').val('all');
                    this.$form.submit();
                    this.isModalShown = false;
                }, this));
                this.listenTo(this.confirmModal, 'cancel', _.bind(function() {
                    this.$form.find('input[name*="[notifyAttendees]"]').val('added_or_deleted');
                    this.$form.submit();
                    this.isModalShown = false;
                }, this));
                this.listenTo(this.confirmModal, 'close', _.bind(function() {
                    this.isModalShown = false;
                }, this));
            }
            return this.confirmModal;
        },

        getFormState: function() {
            return this.$form.find(':input:not(' + this.exclusions.join(', ') + ')').serialize();
        }
    }, {
        createConfirmNotificationDialog: function() {
            return new Modal({
                title: __('Notify guests title'),
                okText: __('Notify'),
                cancelText: __('Don\'t notify'),
                content: __('Notify guests message'),
                className: 'modal modal-primary',
                okButtonClass: 'btn-primary btn-large',
                handleClose: true
            });
        }
    });

    return AttendeeNotifierView;
});
<commit_msg>BB-7408: FrontStore > Popup style broken on role edit page (#9717)<commit_after>define([
    'underscore',
    'orotranslation/js/translator',
    'oroui/js/app/views/base/view',
    'oroui/js/modal'
], function(_, __, BaseView, Modal) {
    'use strict';

    var AttendeeNotifierView = BaseView.extend({
        /** @property {Array} */
        exclusions: [
            'input[name="input_action"]',
            'input[name$="[backgroundColor]"]',
            'select[name*="[reminders]"]',
            'input[name*="[reminders]"]',
            'select[name*="[calendarUid]"]'
        ],

        /**
         * @constructor
         */
        initialize: function() {
            var self = this;
            this.$form = this.$el.closest('form');
            this.$form.on('select2-data-loaded', function() {
                self.formInitialState = self.getFormState();
                self.attendeeInitialValues = self.getAttendeeValues();
            });
            this.formInitialState = this.getFormState();
            this.attendeeInitialValues = this.getAttendeeValues();
            this.isModalShown = false;

            this.$form.parent().on('submit.' + this.cid, _.bind(function(e) {
                if (!this.isModalShown && this.getFormState() !== this.formInitialState && this.hasAttendees() &&
                    _.intersection(this.attendeeInitialValues, this.getAttendeeValues()).length > 0
                    // since we notify all added and deleted users anyway we need ask only about users that were
                    // invited before and left in attendees for now
                ) {
                    this.getConfirmDialog().open();
                    this.isModalShown = true;
                    e.preventDefault();
                }
            }, this));
        },

        /**
         * @inheritDoc
         */
        dispose: function() {
            if (!this.disposed) {
                if (this.$form) {
                    this.$form.parent().off('.' + this.cid);
                }
                if (this.confirmModal) {
                    this.confirmModal.dispose();
                    delete this.confirmModal;
                }
            }
            AttendeeNotifierView.__super__.dispose.call(this);
        },

        getAttendeeValues: function() {
            var value = this.$form.find('input[name*="[attendees]"]').val();
            return value.length > 0 ? value.split(';') : [];
        },

        hasAttendees: function() {
            return this.$form.find('input[name*="[attendees]"]').val().indexOf('entityId') >= 0;
        },

        getConfirmDialog: function() {
            if (!this.confirmModal) {
                this.confirmModal = AttendeeNotifierView.createConfirmNotificationDialog();
                this.listenTo(this.confirmModal, 'ok', _.bind(function() {
                    this.$form.find('input[name*="[notifyAttendees]"]').val('all');
                    this.$form.submit();
                    this.isModalShown = false;
                }, this));
                this.listenTo(this.confirmModal, 'cancel', _.bind(function() {
                    this.$form.find('input[name*="[notifyAttendees]"]').val('added_or_deleted');
                    this.$form.submit();
                    this.isModalShown = false;
                }, this));
                this.listenTo(this.confirmModal, 'close', _.bind(function() {
                    this.isModalShown = false;
                }, this));
            }
            return this.confirmModal;
        },

        getFormState: function() {
            return this.$form.find(':input:not(' + this.exclusions.join(', ') + ')').serialize();
        }
    }, {
        createConfirmNotificationDialog: function() {
            return new Modal({
                title: __('Notify guests title'),
                okText: __('Notify'),
                cancelText: __('Don\'t notify'),
                content: __('Notify guests message'),
                className: 'modal modal-primary',
                handleClose: true
            });
        }
    });

    return AttendeeNotifierView;
});
<|endoftext|>


<commit_before>/* eslint-env browser, jquery */
/* global filterXSS */
// allow some attributes
var whiteListAttr = ['id', 'class', 'style']
window.whiteListAttr = whiteListAttr
// allow link starts with '.', '/' and custom protocol with '://', exclude link starts with javascript://
var linkRegex = /^(?!javascript:\/\/)([\w|-]+:\/\/)|^([.|/])+/i
// allow data uri, from https://gist.github.com/bgrins/6194623
var dataUriRegex = /^\s*data:([a-z]+\/[a-z0-9-+.]+(;[a-z-]+=[a-z0-9-]+)?)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@/?%\s]*)\s*$/i
// custom white list
var whiteList = filterXSS.whiteList
// allow ol specify start number
whiteList['ol'] = ['start']
// allow li specify value number
whiteList['li'] = ['value']
// allow style tag
whiteList['style'] = []
// allow kbd tag
whiteList['kbd'] = []
// allow ifram tag with some safe attributes
whiteList['iframe'] = ['allowfullscreen', 'name', 'referrerpolicy', 'sandbox', 'src', 'width', 'height']
// allow details tag
whiteList['details'] = []
// allow summary tag for details
whiteList['summary'] = []
// allow ruby tag
whiteList['ruby'] = []
// allow rt tag for ruby
whiteList['rt'] = []
// allow figure tag
whiteList['figure'] = []
// allow figcaption tag
whiteList['figcaption'] = []

var filterXSSOptions = {
  allowCommentTag: true,
  whiteList: whiteList,
  escapeHtml: function (html) {
    // allow html comment in multiple lines
    return html.replace(/<(?!!--)/g, '<').replace(/-->/g, '__HTML_COMMENT_END__').replace(/>/g, '>').replace(/__HTML_COMMENT_END__/g, '-->')
  },
  onIgnoreTag: function (tag, html, options) {
    // allow comment tag
    if (tag === '!--') {
            // do not filter its attributes
      return html
    }
  },
  onTagAttr: function (tag, name, value, isWhiteAttr) {
    // allow href and src that match linkRegex
    if (isWhiteAttr && (name === 'href' || name === 'src') && linkRegex.test(value)) {
      return name + '="' + filterXSS.escapeAttrValue(value) + '"'
    }
    // allow data uri in img src
    if (isWhiteAttr && (tag === 'img' && name === 'src') && dataUriRegex.test(value)) {
      return name + '="' + filterXSS.escapeAttrValue(value) + '"'
    }
  },
  onIgnoreTagAttr: function (tag, name, value, isWhiteAttr) {
    // allow attr start with 'data-' or in the whiteListAttr
    if (name.substr(0, 5) === 'data-' || window.whiteListAttr.indexOf(name) !== -1) {
      // escape its value using built-in escapeAttrValue function
      return name + '="' + filterXSS.escapeAttrValue(value) + '"'
    }
  }
}

function preventXSS (html) {
  return filterXSS(html, filterXSSOptions)
}
window.preventXSS = preventXSS

module.exports = {
  preventXSS: preventXSS
}
<commit_msg>Remove manual allow details tag since default already allow it<commit_after>/* eslint-env browser, jquery */
/* global filterXSS */
// allow some attributes
var whiteListAttr = ['id', 'class', 'style']
window.whiteListAttr = whiteListAttr
// allow link starts with '.', '/' and custom protocol with '://', exclude link starts with javascript://
var linkRegex = /^(?!javascript:\/\/)([\w|-]+:\/\/)|^([.|/])+/i
// allow data uri, from https://gist.github.com/bgrins/6194623
var dataUriRegex = /^\s*data:([a-z]+\/[a-z0-9-+.]+(;[a-z-]+=[a-z0-9-]+)?)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@/?%\s]*)\s*$/i
// custom white list
var whiteList = filterXSS.whiteList
// allow ol specify start number
whiteList['ol'] = ['start']
// allow li specify value number
whiteList['li'] = ['value']
// allow style tag
whiteList['style'] = []
// allow kbd tag
whiteList['kbd'] = []
// allow ifram tag with some safe attributes
whiteList['iframe'] = ['allowfullscreen', 'name', 'referrerpolicy', 'sandbox', 'src', 'width', 'height']
// allow summary tag
whiteList['summary'] = []
// allow ruby tag
whiteList['ruby'] = []
// allow rt tag for ruby
whiteList['rt'] = []
// allow figure tag
whiteList['figure'] = []
// allow figcaption tag
whiteList['figcaption'] = []

var filterXSSOptions = {
  allowCommentTag: true,
  whiteList: whiteList,
  escapeHtml: function (html) {
    // allow html comment in multiple lines
    return html.replace(/<(?!!--)/g, '<').replace(/-->/g, '__HTML_COMMENT_END__').replace(/>/g, '>').replace(/__HTML_COMMENT_END__/g, '-->')
  },
  onIgnoreTag: function (tag, html, options) {
    // allow comment tag
    if (tag === '!--') {
            // do not filter its attributes
      return html
    }
  },
  onTagAttr: function (tag, name, value, isWhiteAttr) {
    // allow href and src that match linkRegex
    if (isWhiteAttr && (name === 'href' || name === 'src') && linkRegex.test(value)) {
      return name + '="' + filterXSS.escapeAttrValue(value) + '"'
    }
    // allow data uri in img src
    if (isWhiteAttr && (tag === 'img' && name === 'src') && dataUriRegex.test(value)) {
      return name + '="' + filterXSS.escapeAttrValue(value) + '"'
    }
  },
  onIgnoreTagAttr: function (tag, name, value, isWhiteAttr) {
    // allow attr start with 'data-' or in the whiteListAttr
    if (name.substr(0, 5) === 'data-' || window.whiteListAttr.indexOf(name) !== -1) {
      // escape its value using built-in escapeAttrValue function
      return name + '="' + filterXSS.escapeAttrValue(value) + '"'
    }
  }
}

function preventXSS (html) {
  return filterXSS(html, filterXSSOptions)
}
window.preventXSS = preventXSS

module.exports = {
  preventXSS: preventXSS
}
<|endoftext|>


<commit_before>(function($, ns) {
    ns.Router = Backbone.Router.extend({
        routes: {
            ""    :   "dashboard",
            "/"    :   "dashboard",
            "/login"        :   "login",
            "/users"        :   "users",
            "/users/new"        :   "userNew"
        },

        dashboard : function() {
            page("Dashboard");
        },

        login : function() {
            page("Login");
        },

        users : function () {
            page("UserIndex");
        },

        userNew : function () {
            page("UserNew");
        }
    });

    function page(className){
        $("#content").html(new chorus.pages[className + "Page"]().render().el);
    }
})(jQuery, chorus);
<commit_msg>Further meta/refactoring on Router<commit_after>(function($, ns) {
    ns.Router = Backbone.Router.extend({
        initialize : function(){
            this.route("", "dashboard", makePage("Dashboard"));
            this.route("/", "dashboard", makePage("Dashboard"));
            this.route("/login", "login", makePage("Login"));
            this.route("/users", "users", makePage("UserIndex"));
            this.route("/users/new", "userNew", makePage("UserNew"));
        }
    });

    function page(className){
        $("#content").html(new chorus.pages[className + "Page"]().render().el);
    }
    function makePage(className) {
        return function() { page(className); }
    }
})(jQuery, chorus);<|endoftext|>


<commit_before>var RoomController = function() {
    this.players = [];
}

RoomController.prototype.init = function() {
    client.socket.on("roomUpdated", this.roomUpdated.bind(this));
    client.socket.on("welcome", this.handleWelcome.bind(this));
    client.socket.on("updateHost", this.updateHost.bind(this));
    client.socket.on("play", this.handlePlay.bind(this));

    client.socket.emit("welcome", {playerName: client.playerName, playerId: client.socket.io.engine.id});

    $("#startGame").on("click", function() {
        client.socket.emit("play");
    });
}

RoomController.prototype.handleWelcome = function(data) {
    client.isHost = data.isHost;
    this.renderHost();
}

RoomController.prototype.updateHost = function(data) {
    client.isHost = data.isHost;
    this.renderHost();
}

RoomController.prototype.handlePlay = function() {
    $("#content").remove();
    $("body").append('<canvas id="game-canvas" width="800px" height="800px">Your browser does not support the canvas element. Consider upgrading your IE6.</canvas>');

    startAll();
}

RoomController.prototype.roomUpdated = function(data) {
    var displayPlayers = "";
    var players = data.players;

    for(var i = 0; i < players.length; i++) {
        displayPlayers += "
" +
            "" +
            "
" +
                players[i].name
            + "

";

    }

    $(".players").html(displayPlayers);
}

RoomController.prototype.renderHost = function() {
    if(client.isHost) {
        $("#startGame").removeClass("disabled");
        $("#startGame").addClass("active");
    } else {
        $("#startGame").removeClass("active");
        $("#startGame").addClass("disabled");
    }

}

var roomController = new RoomController();
roomController.init();

<commit_msg>Every player has different image for a hero.<commit_after>var RoomController = function() {
    this.players = [];
    this.avatar_images = ["archer.png", "knight.png", "mage.png", "monk.png",
     "necro.png", "orc.png", "queen.png", "rogue.png"];
}

RoomController.prototype.init = function() {
    client.socket.on("roomUpdated", this.roomUpdated.bind(this));
    client.socket.on("welcome", this.handleWelcome.bind(this));
    client.socket.on("updateHost", this.updateHost.bind(this));
    client.socket.on("play", this.handlePlay.bind(this));

    client.socket.emit("welcome", {playerName: client.playerName, playerId: client.socket.io.engine.id});

    $("#startGame").on("click", function() {
        client.socket.emit("play");
    });
}

RoomController.prototype.handleWelcome = function(data) {
    client.isHost = data.isHost;
    this.renderHost();
}

RoomController.prototype.updateHost = function(data) {
    client.isHost = data.isHost;
    this.renderHost();
}

RoomController.prototype.handlePlay = function() {
    $("#content").remove();
    $("body").append('<canvas id="game-canvas" width="800px" height="800px">Your browser does not support the canvas element. Consider upgrading your IE6.</canvas>');

    startAll();
}

RoomController.prototype.roomUpdated = function(data) {
    var displayPlayers = "";
    var players = data.players;

    for(var i = 0; i < players.length; i++) {
        displayPlayers += "
" +
            "" +
            "
" +
                players[i].name
            + "

";

    }

    $(".players").html(displayPlayers);
}

RoomController.prototype.renderHost = function() {
    if(client.isHost) {
        $("#startGame").removeClass("disabled");
        $("#startGame").addClass("active");
    } else {
        $("#startGame").removeClass("active");
        $("#startGame").addClass("disabled");
    }

}

var roomController = new RoomController();
roomController.init();

<|endoftext|>


<commit_before>let camera = null;
let scene = null, cssScene = null;
let sceneRenderer = null;
let cssRenderer = null;
let container = null;
const target = new THREE.Vector3();
let movingCamera = false;
let timer = 3600; // 60 minutes in seconds

document.addEventListener('DOMContentLoaded', () => {

    loadScene();

    loadInteractionEvents();
});

function loadScene() {

    container = document.getElementById('render');

    scene = new THREE.Scene();
    cssScene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 1000 );

    camera.target = new THREE.Vector3(1000, 0, 0);
    camera.position.set(0, 0, 0);
    camera.lookAt(camera.target);

    const loader = new THREE.CubeTextureLoader();
    loader.setPath( 'images/' );

    const textureCube = loader.load( [
        'cube.left.png', 'cube.right.png',
        'cube.bottom.png', 'cube.top.png',
        'cube.front.png', 'cube.back.png'
    ] );

    const cube = new THREE.Mesh(new THREE.BoxGeometry(1024, 1024, 1024, 7, 7, 7), new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } ));

    cube.scale.x = -1;
    cube.name = "cube";
    cube.x = 0;
    cube.y = 0;
    cube.z = 0;
    scene.add(cube);

    cssRenderer = new THREE.CSS3DRenderer();
    cssRenderer.setSize(window.innerWidth, window.innerHeight);
    cssRenderer.domElement.style.position = "absolute";
    cssRenderer.domElement.style.top = 0;
    container.appendChild(cssRenderer.domElement);

    sceneRenderer = new THREE.WebGLRenderer();
    sceneRenderer.setSize( window.innerWidth, window.innerHeight );

    container.appendChild( sceneRenderer.domElement );

    window.addEventListener("resize", onWindowResize, !1);

    moveCamera();
    render();

    createElement(100, 0, 100, "link1", "Link", "#");

    // Require a delay so that CSS elements are rendered before assigning event handlers
    setTimeout(() => {

        for (const el of document.querySelectorAll('.anchor')) {

            el.addEventListener('click', () => {

                // Variable el.dataset.link now holds the element to highlight in a pane
            });
        }
    }, 100);
}

function startTimer() {

    // Check if timer not already going
    if (timer !== 3600) {
        return;
    }

    setInterval(() => {

        const minutes = timer / 60;
        let seconds = timer % 60;

        if (seconds < 10) {
            seconds = "0" + seconds;
        }

        document.getElementsByClassName('timer')[0].innerHTML = `${Math.floor(minutes)}:${seconds}`;

        timer -= 1;

        if (timer <= 0) {

            timer = 3600;
        }
    }, 1000);
}

function createElement(x, y, z, className, label, link) {

    const element = document.createElement("div");
    element.dataset.link = link;
    element.innerHTML = "" + label + "";
    element.className = "anchor " + className;

    const div = new THREE.CSS3DSprite(element);
    div.position.x = x;
    div.position.y = y;
    div.position.z = z;
    div.scale.x = div.scale.y = .4;

    cssScene.add(div);
}

function onWindowResize(ev) {

}

function touchpointAction(ev) {

}

let lon = 1000, lat = 0, onPointerDownLat = 0, onPointerDownLon = 0, onPointerDownPointerX = 0, onPointerDownPointerY = 0;

function render() {
	requestAnimationFrame( render );

	lat = Math.max( - 85, Math.min( 85, lat ) );
    phi = THREE.Math.degToRad( 90 - lat );
	theta = THREE.Math.degToRad( lon );

    target.x = Math.sin( phi ) * Math.cos( theta );
    target.y = Math.cos( phi );
    target.z = Math.sin( phi ) * Math.sin( theta );

    camera.lookAt( target );

    cssRenderer.render( cssScene, camera );

	sceneRenderer.render( scene, camera );
}

function onDocumentMouseMove(event) {

    if (!movingCamera) {
        return;
    }

    lon = .12 * (onPointerDownPointerX - event.clientX) + onPointerDownLon;
    lat = .12 * (event.clientY - onPointerDownPointerY) + onPointerDownLat;
}

function onDocumentMouseDown(event) {

    event.preventDefault();
    onPointerDownPointerX = event.clientX;
    onPointerDownPointerY = event.clientY;
    onPointerDownLon = lon;
    onPointerDownLat = lat;

    movingCamera = true;
}

function onDocumentMouseUp() {

    event.preventDefault();

    movingCamera = false;
}

function moveCamera() {

    container.addEventListener("mousedown", onDocumentMouseDown);
    container.addEventListener("mousemove", onDocumentMouseMove);
    container.addEventListener("mouseup", onDocumentMouseUp);

    camera.updateProjectionMatrix();
}

function loadInteractionEvents() {

    const streamToggle = document.getElementById('toggle-streaming');
    const skipToggle = document.getElementById('toggle-skip');
    const backButton = document.getElementById('menu-back');

    streamToggle.addEventListener('click', (ev) => {

        streamToggle.classList.toggle('active');
    });

    skipToggle.addEventListener('click', (ev) => {

        skipToggle.classList.toggle('active');
    });

    document.getElementById('menu-gameplay').addEventListener('click', () => {

        for (const el of document.getElementsByClassName('main-menu')) {

            el.classList.add('hidden');
        }

        for (const el of document.getElementsByClassName('gameplay-menu')) {

            el.classList.remove('hidden');
        }

        backButton.classList.remove('hidden');
    });

    document.getElementById('menu-options').addEventListener('click', () => {

        for (const el of document.getElementsByClassName('main-menu')) {

            el.classList.add('hidden');
        }

        for (const el of document.getElementsByClassName('options-menu')) {

            el.classList.remove('hidden');
        }

        backButton.classList.remove('hidden');
    });

    document.getElementById('menu-stats').addEventListener('click', () => {

        for (const el of document.getElementsByClassName('main-menu')) {

            el.classList.add('hidden');
        }

        for (const el of document.getElementsByClassName('stats-menu')) {

            el.classList.remove('hidden');
        }

        backButton.classList.remove('hidden');
    });

    backButton.addEventListener('click', () => {

        resetMenus();
    })

    addPageHandler('menu-storymode', 'page-storymode');
    addPageHandler('menu-puzzlemode', 'page-puzzlemode');
    addPageHandler('menu-tutorial', 'page-tutorial');
    addPageHandler('menu-share', 'page-share');
    addPageHandler('menu-leaderboards', 'page-leaderboards');
    addPageHandler('timer', 'page-timer');

    for (const el of document.getElementsByClassName('page-close')) {

        el.addEventListener('click', hidePages);
    }

    for (const el of document.getElementsByClassName('start-game')) {

         el.addEventListener('click', startGame);
    }
}

function resetMenus() {

    for (const el of document.getElementsByClassName('main-menu')) {

        el.classList.remove('hidden');
    }

    for (const el of document.getElementsByClassName('gameplay-menu')) {

        el.classList.add('hidden');
    }

    for (const el of document.getElementsByClassName('options-menu')) {

        el.classList.add('hidden');
    }

    for (const el of document.getElementsByClassName('stats-menu')) {

        el.classList.add('hidden');
    }

    document.getElementById('menu-back').classList.add('hidden');
}

function hidePages() {

    for (const el of document.getElementsByClassName('page')) {

        el.classList.remove('active');
    }
}

function hideMenus() {

    resetMenus();

    for (const el of document.getElementsByClassName('menu_box')) {

        el.classList.add('hidden');
    }
}

function addPageHandler(menuClass, pageClass) {

    document.getElementById(menuClass).addEventListener('click', () => {

        hidePages();

        setTimeout(() => {

            document.getElementById(pageClass).classList.add('active');
        }, 450);
    });
}

function startGame() {

    document.getElementById('render').classList.remove('blur');

    hidePages();

    hideMenus();

    startTimer();
}<commit_msg>Adjust room file names<commit_after>let camera = null;
let scene = null, cssScene = null;
let sceneRenderer = null;
let cssRenderer = null;
let container = null;
const target = new THREE.Vector3();
let movingCamera = false;
let timer = 3600; // 60 minutes in seconds

document.addEventListener('DOMContentLoaded', () => {

    loadScene();

    loadInteractionEvents();
});

function loadScene() {

    container = document.getElementById('render');

    scene = new THREE.Scene();
    cssScene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 1000 );

    camera.target = new THREE.Vector3(1000, 0, 0);
    camera.position.set(0, 0, 0);
    camera.lookAt(camera.target);

    const loader = new THREE.CubeTextureLoader();
    loader.setPath( 'images/' );

    const textureCube = loader.load( [
        'room.left.jpg', 'room.right.jpg',
        'room.bottom.jpg', 'room.top.jpg',
        'room.front.jpg', 'room.back.jpg'
    ] );

    const cube = new THREE.Mesh(new THREE.BoxGeometry(1024, 1024, 1024, 7, 7, 7), new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } ));

    cube.scale.x = -1;
    cube.name = "cube";
    cube.x = 0;
    cube.y = 0;
    cube.z = 0;
    scene.add(cube);

    cssRenderer = new THREE.CSS3DRenderer();
    cssRenderer.setSize(window.innerWidth, window.innerHeight);
    cssRenderer.domElement.style.position = "absolute";
    cssRenderer.domElement.style.top = 0;
    container.appendChild(cssRenderer.domElement);

    sceneRenderer = new THREE.WebGLRenderer();
    sceneRenderer.setSize( window.innerWidth, window.innerHeight );

    container.appendChild( sceneRenderer.domElement );

    window.addEventListener("resize", onWindowResize, !1);

    moveCamera();
    render();

    createElement(100, 0, 100, "link1", "Link", "#");

    // Require a delay so that CSS elements are rendered before assigning event handlers
    setTimeout(() => {

        for (const el of document.querySelectorAll('.anchor')) {

            el.addEventListener('click', () => {

                // Variable el.dataset.link now holds the element to highlight in a pane
            });
        }
    }, 100);
}

function startTimer() {

    // Check if timer not already going
    if (timer !== 3600) {
        return;
    }

    setInterval(() => {

        const minutes = timer / 60;
        let seconds = timer % 60;

        if (seconds < 10) {
            seconds = "0" + seconds;
        }

        document.getElementsByClassName('timer')[0].innerHTML = `${Math.floor(minutes)}:${seconds}`;

        timer -= 1;

        if (timer <= 0) {

            timer = 3600;
        }
    }, 1000);
}

function createElement(x, y, z, className, label, link) {

    const element = document.createElement("div");
    element.dataset.link = link;
    element.innerHTML = "" + label + "";
    element.className = "anchor " + className;

    const div = new THREE.CSS3DSprite(element);
    div.position.x = x;
    div.position.y = y;
    div.position.z = z;
    div.scale.x = div.scale.y = .4;

    cssScene.add(div);
}

function onWindowResize(ev) {

}

function touchpointAction(ev) {

}

let lon = 1000, lat = 0, onPointerDownLat = 0, onPointerDownLon = 0, onPointerDownPointerX = 0, onPointerDownPointerY = 0;

function render() {
	requestAnimationFrame( render );

	lat = Math.max( - 85, Math.min( 85, lat ) );
    phi = THREE.Math.degToRad( 90 - lat );
	theta = THREE.Math.degToRad( lon );

    target.x = Math.sin( phi ) * Math.cos( theta );
    target.y = Math.cos( phi );
    target.z = Math.sin( phi ) * Math.sin( theta );

    camera.lookAt( target );

    cssRenderer.render( cssScene, camera );

	sceneRenderer.render( scene, camera );
}

function onDocumentMouseMove(event) {

    if (!movingCamera) {
        return;
    }

    lon = .12 * (onPointerDownPointerX - event.clientX) + onPointerDownLon;
    lat = .12 * (event.clientY - onPointerDownPointerY) + onPointerDownLat;
}

function onDocumentMouseDown(event) {

    event.preventDefault();
    onPointerDownPointerX = event.clientX;
    onPointerDownPointerY = event.clientY;
    onPointerDownLon = lon;
    onPointerDownLat = lat;

    movingCamera = true;
}

function onDocumentMouseUp() {

    event.preventDefault();

    movingCamera = false;
}

function moveCamera() {

    container.addEventListener("mousedown", onDocumentMouseDown);
    container.addEventListener("mousemove", onDocumentMouseMove);
    container.addEventListener("mouseup", onDocumentMouseUp);

    camera.updateProjectionMatrix();
}

function loadInteractionEvents() {

    const streamToggle = document.getElementById('toggle-streaming');
    const skipToggle = document.getElementById('toggle-skip');
    const backButton = document.getElementById('menu-back');

    streamToggle.addEventListener('click', (ev) => {

        streamToggle.classList.toggle('active');
    });

    skipToggle.addEventListener('click', (ev) => {

        skipToggle.classList.toggle('active');
    });

    document.getElementById('menu-gameplay').addEventListener('click', () => {

        for (const el of document.getElementsByClassName('main-menu')) {

            el.classList.add('hidden');
        }

        for (const el of document.getElementsByClassName('gameplay-menu')) {

            el.classList.remove('hidden');
        }

        backButton.classList.remove('hidden');
    });

    document.getElementById('menu-options').addEventListener('click', () => {

        for (const el of document.getElementsByClassName('main-menu')) {

            el.classList.add('hidden');
        }

        for (const el of document.getElementsByClassName('options-menu')) {

            el.classList.remove('hidden');
        }

        backButton.classList.remove('hidden');
    });

    document.getElementById('menu-stats').addEventListener('click', () => {

        for (const el of document.getElementsByClassName('main-menu')) {

            el.classList.add('hidden');
        }

        for (const el of document.getElementsByClassName('stats-menu')) {

            el.classList.remove('hidden');
        }

        backButton.classList.remove('hidden');
    });

    backButton.addEventListener('click', () => {

        resetMenus();
    })

    addPageHandler('menu-storymode', 'page-storymode');
    addPageHandler('menu-puzzlemode', 'page-puzzlemode');
    addPageHandler('menu-tutorial', 'page-tutorial');
    addPageHandler('menu-share', 'page-share');
    addPageHandler('menu-leaderboards', 'page-leaderboards');
    addPageHandler('timer', 'page-timer');

    for (const el of document.getElementsByClassName('page-close')) {

        el.addEventListener('click', hidePages);
    }

    for (const el of document.getElementsByClassName('start-game')) {

         el.addEventListener('click', startGame);
    }
}

function resetMenus() {

    for (const el of document.getElementsByClassName('main-menu')) {

        el.classList.remove('hidden');
    }

    for (const el of document.getElementsByClassName('gameplay-menu')) {

        el.classList.add('hidden');
    }

    for (const el of document.getElementsByClassName('options-menu')) {

        el.classList.add('hidden');
    }

    for (const el of document.getElementsByClassName('stats-menu')) {

        el.classList.add('hidden');
    }

    document.getElementById('menu-back').classList.add('hidden');
}

function hidePages() {

    for (const el of document.getElementsByClassName('page')) {

        el.classList.remove('active');
    }
}

function hideMenus() {

    resetMenus();

    for (const el of document.getElementsByClassName('menu_box')) {

        el.classList.add('hidden');
    }
}

function addPageHandler(menuClass, pageClass) {

    document.getElementById(menuClass).addEventListener('click', () => {

        hidePages();

        setTimeout(() => {

            document.getElementById(pageClass).classList.add('active');
        }, 450);
    });
}

function startGame() {

    document.getElementById('render').classList.remove('blur');

    hidePages();

    hideMenus();

    startTimer();
}<|endoftext|>


<commit_before>var pathNameUrl = $(location).attr('pathname').split('/');
var pathUrl = (pathNameUrl[1] == 'admin') ? '/admin' : '';

/* ------------------- Get the query in database searching -------------------*/
var requestBooksSearch = function() {
    var text = $('#search').val();
    text = text.replace(/(^\s+|\s+$)/g, '');
    var textEncode = encodeURIComponent(text); // shielding request
    doAjaxQuery('GET', '' + pathUrl + '/api/v1/books?search=' + textEncode + '', null,
        function(res) {
            if (res.data.total.amount > 0) {
                (pathUrl === '') ? view.addBooksItems(res.data.books): view.addBooksList(res.data.books);
            } else {
                console.log("zero");
                view.showNot_found(text, pathUrl);
            }
        });
};

/* ---------- Live search if the search did not introduced n time ----------- */
$('#search').keydown(function(event) {
    if (event.keyCode === 13) {
        event.preventDefault();
        requestBooksSearch();
    }
    var text = $(this).val();
    if (text.length > 0) {
        if (!(event.keyCode >= 33 && event.keyCode <= 40) &&
            !(event.keyCode >= 16 && event.keyCode <= 20) &&
            (event.keyCode !== 27) &&
            (event.keyCode !== 13)) {
            var task = setTimeout(requestBooksSearch, 1000);
        }

        $('#search').keydown(function(event) {
            if (!(event.keyCode >= 33 && event.keyCode <= 40) &&
                !(event.keyCode >= 16 && event.keyCode <= 20)) {
                clearTimeout(task);
            }
        });
    }
});
<commit_msg>clear area before display search result<commit_after>var pathNameUrl = $(location).attr('pathname').split('/');
var pathUrl = (pathNameUrl[1] == 'admin') ? '/admin' : '';

/* ------------------- Get the query in database searching -------------------*/
var requestBooksSearch = function() {
    var text = $('#search').val();
    text = text.replace(/(^\s+|\s+$)/g, '');
    var textEncode = encodeURIComponent(text); // shielding request
    doAjaxQuery('GET', '' + pathUrl + '/api/v1/books?search=' + textEncode + '', null,
        function(res) {
            if (res.data.total.amount > 0) {
                $('#content').empty();
                (pathUrl === '') ? view.addBooksItems(res.data.books): view.addBooksList(res.data.books);
            } else {
                view.showNot_found(text, pathUrl);
            }
        });
};

/* ---------- Live search if the search did not introduced n time ----------- */
$('#search').keydown(function(event) {
    if (event.keyCode === 13) {
        event.preventDefault();
        requestBooksSearch();
    }
    var text = $(this).val();
    if (text.length > 0) {
        if (!(event.keyCode >= 33 && event.keyCode <= 40) &&
            !(event.keyCode >= 16 && event.keyCode <= 20) &&
            (event.keyCode !== 27) &&
            (event.keyCode !== 13)) {
            var task = setTimeout(requestBooksSearch, 1000);
        }

        $('#search').keydown(function(event) {
            if (!(event.keyCode >= 33 && event.keyCode <= 40) &&
                !(event.keyCode >= 16 && event.keyCode <= 20)) {
                clearTimeout(task);
            }
        });
    }
});
<|endoftext|>


<commit_before>var v = "20150930"
// scroll the chat as messages are added
var scrollChat = function () {
  var chat = $("#chat")
  chat.animate({ scrollTop: chat.prop("scrollHeight") }, 2000)
}

// handle user queries
var processRequest = function (query) {
  var request = $.ajax({
    data: { "query": query, "v": v },
    dataType: "json",
    type: "POST",
    url: "/message"
  })
  request.done(function (message) {
    if (message.result.fulfillment.speech !== "")
      writeBotMessage(message)
    if (message.result.action === "getBitcoinPrice")
      setTimeout(getBitcoinPrice, 1000)
    else if (message.result.action === "getCurrentAge")
      setTimeout(getCurrentAge, 1000)
  })
}

// calculate Phaedrus's current age
var getCurrentAge = function () {
  var birthday = new Date("08/30/1992")
  var today = new Date()
  var age = Math.floor((today - birthday) / (365.25 * 24 * 60 * 60 * 1000))
  var nextAge = age + 1
  var monthsTillBirthday = birthday.getMonth() - today.getMonth()
  var ageMessage = "He is " + age
  if (monthsTillBirthday >= 0 && monthsTillBirthday < 4) {
    ageMessage += ", turning " + nextAge + " on August 30"
  }
  if (monthsTillBirthday === 0) {
    ageMessage += " (so soon!)"
  }
  ageMessage += "."
  writeMessage(ageMessage, false)
}

// welcome logic
var howdy = function () {
  var request = $.ajax({
    data: { "e": "WELCOME", "v": v },
    dataType: "json",
    type: "POST",
    url: "/welcome"
  })
  request.done(function (message) {
    writeBotMessage(message)
  })
}

// fetch the current Bitcoin price from the CoinDesk API
var getBitcoinPrice = function () {
  var btcRequest = $.ajax({
    type: "GET",
    url: "http://api.coindesk.com/v1/bpi/currentprice.json",
    error: function (data, textStatus, jqXHR) {
      console.log("Error! Could not fetch access token.")
    }
  })
  btcRequest.done(function (message) {
    var btcMsg = "$" + JSON.parse(message).bpi.USD.rate
    writeMessage(btcMsg, false)
  })
}

// is Phaedbot writing one message or a chain?
var writeBotMessage = function (message) {
  var response = message.result.fulfillment
  if (response.messages.length === 1)
    writeMessage(response.speech, false)
  else {
    for (var i = 0; i < response.messages.length; i++) {
      setTimeout(writeMessage, 1500 * i+1, response.messages[i].speech, false)
    }
  }
}

// write a message to the chat
var writeMessage = function (message, fromUser) {
  var wrapperDiv = document.createElement("div")
  wrapperDiv.className = fromUser ? "request row" : "response row"
  var authorDiv = document.createElement("div")
  authorDiv.className = "col-xs-3 col-sm-2 col-sm-offset-3 col-md-1 col-md-offset-4"
  var authorSpan = document.createElement("span")
  authorSpan.className = "author"
  var author = document.createTextNode(fromUser ? "You" : "Phaedbot")
  authorSpan.appendChild(author)
  authorDiv.appendChild(authorSpan)
  var messageDiv = document.createElement("div")
  messageDiv.className = "col-xs-9 col-sm-6 col-md-5"
  var messageP = document.createElement("p")
  messageP.className = "message"
  var messageText = document.createTextNode(message)
  messageP.appendChild(messageText)
  messageDiv.appendChild(messageP)
  wrapperDiv.appendChild(authorDiv)
  wrapperDiv.appendChild(messageDiv)
  $("#chat").append(wrapperDiv)
  if (fromUser) {
    $("#message-contents").val("")
  } else {
    $("#chat div.response").last()
      .css("opacity", 0)
      .slideDown(500)
      .animate({ opacity: 1 }, { queue: false }, { duration: 2000 })
    setTimeout(scrollChat, 500)
  }
}

// page lifecycle
$(document).ready(function () {
  // focus on user input element
  $("#message-contents").focus()
  // Phaedbot starts the conversation
  howdy()
  // process messages on form submit
  $("#message-form").submit(function (e) {
    e.preventDefault()
    var query = $("#message-contents").val()
    writeMessage(query, true)
    processRequest(query)
  })
})
<commit_msg>Tighter fullscreen style<commit_after>var v = "20150930"
// scroll the chat as messages are added
var scrollChat = function () {
  var chat = $("#chat")
  chat.animate({ scrollTop: chat.prop("scrollHeight") }, 2000)
}

// handle user queries
var processRequest = function (query) {
  var request = $.ajax({
    data: { "query": query, "v": v },
    dataType: "json",
    type: "POST",
    url: "/message"
  })
  request.done(function (message) {
    if (message.result.fulfillment.speech !== "")
      writeBotMessage(message)
    if (message.result.action === "getBitcoinPrice")
      setTimeout(getBitcoinPrice, 1500)
    else if (message.result.action === "getCurrentAge")
      setTimeout(getCurrentAge, 1500)
  })
}

// calculate Phaedrus's current age
var getCurrentAge = function () {
  var birthday = new Date("08/30/1992")
  var today = new Date()
  var age = Math.floor((today - birthday) / (365.25 * 24 * 60 * 60 * 1000))
  var nextAge = age + 1
  var monthsTillBirthday = birthday.getMonth() - today.getMonth()
  var ageMessage = "He is " + age
  if (monthsTillBirthday >= 0 && monthsTillBirthday < 4) {
    ageMessage += ", turning " + nextAge + " on August 30"
  }
  if (monthsTillBirthday === 0) {
    ageMessage += " (so soon!)"
  }
  ageMessage += "."
  writeMessage(ageMessage, false)
}

// welcome logic
var howdy = function () {
  var request = $.ajax({
    data: { "e": "WELCOME", "v": v },
    dataType: "json",
    type: "POST",
    url: "/welcome"
  })
  request.done(function (message) {
    writeBotMessage(message)
  })
}

// fetch the current Bitcoin price from the CoinDesk API
var getBitcoinPrice = function () {
  var btcRequest = $.ajax({
    type: "GET",
    url: "http://api.coindesk.com/v1/bpi/currentprice.json",
    error: function (data, textStatus, jqXHR) {
      console.log("Error! Could not fetch access token.")
    }
  })
  btcRequest.done(function (message) {
    var btcMsg = "$" + JSON.parse(message).bpi.USD.rate
    writeMessage(btcMsg, false)
  })
}

// is Phaedbot writing one message or a chain?
var writeBotMessage = function (message) {
  var response = message.result.fulfillment
  if (response.messages.length === 1)
    writeMessage(response.speech, false)
  else {
    for (var i = 0; i < response.messages.length; i++) {
      setTimeout(writeMessage, 2500 * i+1, response.messages[i].speech, false)
    }
  }
}

// write a message to the chat
var writeMessage = function (message, fromUser) {
  var wrapperDiv = document.createElement("div")
  wrapperDiv.className = fromUser ? "request row" : "response row"
  var authorDiv = document.createElement("div")
  authorDiv.className = "col-xs-3 col-sm-2 col-sm-offset-3 col-md-1 col-md-offset-4"
  var authorSpan = document.createElement("span")
  authorSpan.className = "author"
  var author = document.createTextNode(fromUser ? "You" : "Phaedbot")
  authorSpan.appendChild(author)
  authorDiv.appendChild(authorSpan)
  var messageDiv = document.createElement("div")
  messageDiv.className = "col-xs-9 col-sm-6 col-md-4"
  var messageP = document.createElement("p")
  messageP.className = "message"
  var messageText = document.createTextNode(message)
  messageP.appendChild(messageText)
  messageDiv.appendChild(messageP)
  wrapperDiv.appendChild(authorDiv)
  wrapperDiv.appendChild(messageDiv)
  $("#chat").append(wrapperDiv)
  if (fromUser) {
    $("#message-contents").val("")
  } else {
    $("#chat div.response").last()
      .css("opacity", 0)
      .slideDown(500)
      .animate({ opacity: 1 }, { queue: false }, { duration: 1500 })
    setTimeout(scrollChat, 1000)
  }
}

// page lifecycle
$(document).ready(function () {
  // focus on user input element
  $("#message-contents").focus()
  // Phaedbot starts the conversation
  howdy()
  // process messages on form submit
  $("#message-form").submit(function (e) {
    e.preventDefault()
    var query = $("#message-contents").val()
    writeMessage(query, true)
    processRequest(query)
  })
})
<|endoftext|>


<commit_before>'use strict';
var logger = require('log4js').getLogger('blueprints_spec');
var components = require('../../src/components/index');
var hotkeys = components.ui.hotkeys;
var config = components.config.tests.sanity.hotkeys_spec;

describe('Website hotkeys', function(){

    beforeEach(function(){ logger.info('running from ' + __filename); });

    //TODO Phantomjs doesn't seem to send thoes keys so it doesn't work while it does on chrome :/ https://cloudifysource.atlassian.net/browse/CFY-4962
    //describe('Navigation hotkeys', function(){
    //    var isPage = function(pageName){
    //        return browser.getCurrentUrl().then(function(currentUrl) {
    //            return currentUrl.indexOf('/'+pageName) !== -1;
    //        });
    //    };
    //
    //    beforeEach(function(){
    //        browser.get('/#/blueprints');
    //        browser.waitForAngular();
    //    });
    //
    //    it('should navigate to blueprints', function(){
    //        browser.get('/#/deployments');
    //        browser.waitForAngular();
    //
    //        hotkeys.Navigations.blueprints();
    //        expect(isPage('blueprints')).toBe(true);
    //    });
    //
    //    it('should navigate to deployments', function(){
    //        hotkeys.Navigations.deployments();
    //        expect(isPage('deployments')).toBe(true);
    //    });
    //
    //    it('should navigate to logs & events', function(){
    //        hotkeys.Navigations.logs();
    //        expect(isPage('logs')).toBe(true);
    //    });
    //
    //    it('should navigate to nodes', function(){
    //        hotkeys.Navigations.nodes();
    //        expect(isPage('nodes')).toBe(true);
    //    });
    //});

    describe('Upload blueprint', function(){
        describe('blueprint index', function(){
            beforeEach(function(){
                browser.get('/#/blueprints');
                browser.waitForAngular();
            });

            it('should open upload blueprint dialog', function(){
                hotkeys.UploadBlueprint();

                expect($('#uploadForm').isPresent()).toBe(true);
            });
        });

        describe('not found blueprint at blueprint page', function(){
            beforeEach(function(){
                browser.get('/#/blueprint/'+config.notExistingBlueprint+'/topology');
                browser.waitForAngular();
            });

            it('should open upload blueprint dialog', function(){
                hotkeys.UploadBlueprint();

                expect($('#uploadForm').isPresent()).toBe(true);
            });
        });
    });

    describe('Blueprint actions hotkeys', function(){
        describe('Bluprints index', function(){
            beforeEach(function(){
                browser.get('/#/blueprints');
                browser.waitForAngular();
            });

            it('should open deploy dialog', function(){
                components.ui.blueprints.IndexPage.selectBlueprint(0);
                hotkeys.BlueprintActions.deploy();

                expect($('.deploy-dialog').isPresent()).toBe(true);
            });

            it('should open delete dialog', function(){
                components.ui.blueprints.IndexPage.selectBlueprint(0);
                hotkeys.BlueprintActions.delete();

                expect($('.delete-dialog').isPresent()).toBe(true);
            });
        });

        describe('Bluprint page', function(){
            beforeEach(function(){
                browser.get('/#/blueprint/'+config.anyBlueprint+'/topology');
                browser.waitForAngular();
            });

            it('should open deploy dialog', function(){
                hotkeys.BlueprintActions.deploy();

                expect($('.deploy-dialog').isPresent()).toBe(true);
            });

            it('should open delete dialog', function(){
                hotkeys.BlueprintActions.delete();

                expect($('.delete-dialog').isPresent()).toBe(true);
            });
        });
    });

    describe('Deployment actions hotkeys', function(){
        describe('Not executing deployment', function(){
            describe('Deployments index', function(){
                beforeEach(function(){
                    browser.get('/#/deployments');
                    browser.waitForAngular();
                });

                it('should open execute dialog', function(){
                    components.ui.deployments.IndexPage.selectDeployment(0);
                    hotkeys.DeploymentActions.execute();

                    expect($('.start-execution-dialog').isPresent()).toBe(true);
                });

                it('should open delete dialog', function(){
                    components.ui.deployments.IndexPage.selectDeployment(0);
                    hotkeys.DeploymentActions.delete();

                    expect($('.delete-dialog').isPresent()).toBe(true);
                });
            });

            describe('Deployment page', function(){
                beforeEach(function(){
                    browser.get('/#/deployment/'+config.notExecutingDeployment+'/topology');
                    browser.waitForAngular();
                });

                it('should open execute dialog', function(){
                    hotkeys.DeploymentActions.execute();
                    expect($('.start-execution-dialog').isPresent()).toBe(true);
                });

                it('should open delete dialog', function(){
                    hotkeys.DeploymentActions.delete();

                    expect($('.delete-dialog').isPresent()).toBe(true);
                });
            });
        });

        describe('Executing deployment', function(){
            //TODO: Replace it with beforeAll when upgrading to jasmine 2
            it('should setup env because we can"t use beforeAll',function(){
                browser.get('/#/deployments');
                browser.waitForAngular();

                (function installDeployment (){
                    components.ui.deployments.IndexPage.executeWorkflowWithoutWaitingUntilDone({
                        deployment: {
                            id: config.executingDeployment
                        },
                        workflow: 'install'
                    });
                })();
            });

            describe('Deployments index', function(){
                beforeEach(function(){
                    browser.get('/#/deployments');
                    browser.waitForAngular();
                });

                it('should open cancel execution dialog', function(){
                    components.ui.deployments.IndexPage.selectDeployment(config.executingDeployment);
                    hotkeys.DeploymentActions.cancelExecution();

                    expect($('[ng-click="cancelWorkflow()"]').isPresent()).toBe(true);
                });
            });

            describe('Deployment page', function(){
                beforeEach(function(){
                    browser.get('/#/deployment/'+config.executingDeployment+'/topology');
                    browser.waitForAngular();
                });

                it('should open cancel execution dialog', function(){
                    hotkeys.DeploymentActions.cancelExecution();

                    expect($('[ng-click="cancelWorkflow()"]').isPresent()).toBe(true);
                });
            });
        });
    });
});<commit_msg>fix(hotkeys) fixing failing tests<commit_after>'use strict';
var logger = require('log4js').getLogger('blueprints_spec');
var components = require('../../src/components/index');
var hotkeys = components.ui.hotkeys;
var config = components.config.tests.sanity.hotkeys_spec;

describe('Website hotkeys', function(){

    beforeEach(function(){ logger.info('running from ' + __filename); });

    //TODO Phantomjs doesn't seem to send thoes keys so it doesn't work while it does on chrome :/ https://cloudifysource.atlassian.net/browse/CFY-4962
    //describe('Navigation hotkeys', function(){
    //    var isPage = function(pageName){
    //        return browser.getCurrentUrl().then(function(currentUrl) {
    //            return currentUrl.indexOf('/'+pageName) !== -1;
    //        });
    //    };
    //
    //    beforeEach(function(){
    //        browser.get('/#/blueprints');
    //        browser.waitForAngular();
    //    });
    //
    //    it('should navigate to blueprints', function(){
    //        browser.get('/#/deployments');
    //        browser.waitForAngular();
    //
    //        hotkeys.Navigations.blueprints();
    //        expect(isPage('blueprints')).toBe(true);
    //    });
    //
    //    it('should navigate to deployments', function(){
    //        hotkeys.Navigations.deployments();
    //        expect(isPage('deployments')).toBe(true);
    //    });
    //
    //    it('should navigate to logs & events', function(){
    //        hotkeys.Navigations.logs();
    //        expect(isPage('logs')).toBe(true);
    //    });
    //
    //    it('should navigate to nodes', function(){
    //        hotkeys.Navigations.nodes();
    //        expect(isPage('nodes')).toBe(true);
    //    });
    //});

    describe('Upload blueprint', function(){
        describe('blueprint index', function(){
            beforeEach(function(){
                browser.get('/#/blueprints');
                browser.waitForAngular();
            });

            it('should open upload blueprint dialog', function(){
                hotkeys.UploadBlueprint();

                expect($('#uploadForm').isPresent()).toBe(true);
            });
        });

        describe('not found blueprint at blueprint page', function(){
            beforeEach(function(){
                browser.get('/#/blueprint/'+config.notExistingBlueprint+'/topology');
                browser.waitForAngular();
            });

            it('should open upload blueprint dialog', function(){
                hotkeys.UploadBlueprint();

                expect($('#uploadForm').isPresent()).toBe(true);
            });
        });
    });

    describe('Blueprint actions hotkeys', function(){
        describe('Bluprints index', function(){
            beforeEach(function(){
                browser.get('/#/blueprints');
                browser.waitForAngular();
            });

            it('should open deploy dialog', function(){
                components.ui.blueprints.IndexPage.selectBlueprint(0);
                hotkeys.BlueprintActions.deploy();

                expect($('.deploy-dialog').isPresent()).toBe(true);
            });

            it('should open delete dialog', function(){
                components.ui.blueprints.IndexPage.selectBlueprint(0);
                hotkeys.BlueprintActions.delete();

                expect($('.delete-dialog').isPresent()).toBe(true);
            });
        });

        describe('Bluprint page', function(){
            beforeEach(function(){
                browser.get('/#/blueprint/'+config.anyBlueprint+'/topology');
                browser.waitForAngular();
            });

            it('should open deploy dialog', function(){
                hotkeys.BlueprintActions.deploy();

                expect($('.deploy-dialog').isPresent()).toBe(true);
            });

            it('should open delete dialog', function(){
                hotkeys.BlueprintActions.delete();

                expect($('.delete-dialog').isPresent()).toBe(true);
            });
        });
    });

    describe('Deployment actions hotkeys', function(){
        describe('Not executing deployment', function(){
            describe('Deployments index', function(){
                beforeEach(function(){
                    browser.get('/#/deployments');
                    browser.waitForAngular();
                });

                it('should open execute dialog', function(){
                    components.ui.deployments.IndexPage.selectDeployment(0);
                    hotkeys.DeploymentActions.execute();

                    expect($('#startExecutionDialog').isPresent()).toBe(true);
                });

                it('should open delete dialog', function(){
                    components.ui.deployments.IndexPage.selectDeployment(0);
                    hotkeys.DeploymentActions.delete();

                    expect($('.delete-dialog').isPresent()).toBe(true);
                });
            });

            describe('Deployment page', function(){
                beforeEach(function(){
                    browser.get('/#/deployment/'+config.notExecutingDeployment+'/topology');
                    browser.waitForAngular();
                });

                it('should open execute dialog', function(){
                    hotkeys.DeploymentActions.execute();
                    expect($('#startExecutionDialog').isPresent()).toBe(true);
                });

                it('should open delete dialog', function(){
                    hotkeys.DeploymentActions.delete();

                    expect($('.delete-dialog').isPresent()).toBe(true);
                });
            });
        });

        describe('Executing deployment', function(){
            //TODO: Replace it with beforeAll when upgrading to jasmine 2
            it('should setup env because we can"t use beforeAll',function(){
                browser.get('/#/deployments');
                browser.waitForAngular();

                (function installDeployment (){
                    components.ui.deployments.IndexPage.executeWorkflowWithoutWaitingUntilDone({
                        deployment: {
                            id: config.executingDeployment
                        },
                        workflow: 'install'
                    });
                })();
            });

            describe('Deployments index', function(){
                beforeEach(function(){
                    browser.get('/#/deployments');
                    browser.waitForAngular();
                });

                it('should open cancel execution dialog', function(){
                    components.ui.deployments.IndexPage.selectDeployment(config.executingDeployment);
                    hotkeys.DeploymentActions.cancelExecution();

                    expect($('[ng-click="cancelWorkflow()"]').isPresent()).toBe(true);
                });
            });

            describe('Deployment page', function(){
                beforeEach(function(){
                    browser.get('/#/deployment/'+config.executingDeployment+'/topology');
                    browser.waitForAngular();
                });

                it('should open cancel execution dialog', function(){
                    hotkeys.DeploymentActions.cancelExecution();

                    expect($('[ng-click="cancelWorkflow()"]').isPresent()).toBe(true);
                });
            });
        });
    });
});<|endoftext|>


<commit_before>import addElOrigin from "./addElOrigin"
import $ from "jquery"
import tagTypeHasClosingTag from "./tagTypeHasClosingTag"

// tries to describe the relationship between an assigned innerHTML value
// and the value you get back when reading el.innerHTML.
// e.g. you could assign "<input type='checkbox' checked>" and get back
// "<input type='checkbox' checked=''>"
export default function mapInnerHTMLAssignment(el, assignedInnerHTML, actionName, initialExtraCharsValue){
    var innerHTMLAfterAssignment = nativeInnerHTMLDescriptor.get.call(el)
    var forDebuggingProcessedHtml = ""
    var charOffset = 0;
    var extraCharsAdded = 0;
    if (initialExtraCharsValue !== undefined){
        extraCharsAdded = initialExtraCharsValue
    }
    processNewInnerHtml(el)

    function processNewInnerHtml(el){
        var children = Array.prototype.slice.apply(el.childNodes, [])
        addElOrigin(el, "replaceContents", {
            action: actionName,
            children: children
        })

        $(el).contents().each(function(i, child){
            var isTextNode = child.nodeType === 3
            if (isTextNode) {
                addElOrigin(child, "textValue", {
                    "action": actionName,
                    inputValues: [assignedInnerHTML],
                    value: innerHTMLAfterAssignment,
                    inputValuesCharacterIndex: [charOffset],
                    extraCharsAdded: extraCharsAdded
                })

                charOffset += child.textContent.length
                forDebuggingProcessedHtml += child.textContent
            } else {

                addElOrigin(child, "openingTagStart", {
                    action: actionName,
                    inputValues: [assignedInnerHTML],
                    inputValuesCharacterIndex: [charOffset],
                    value: innerHTMLAfterAssignment,
                    extraCharsAdded: extraCharsAdded
                })
                var openingTagStart = "<" + child.tagName
                charOffset += openingTagStart.length
                forDebuggingProcessedHtml += openingTagStart

                for (var i = 0;i<child.attributes.length;i++) {
                    var attr = child.attributes[i]

                    var charOffsetBefore = charOffset

                    var attrStr = " " + attr.name
                    attrStr += "='" + attr.textContent +  "'"

                    charOffset += attrStr.length
                    var offsetAtCharIndex = null
                    var extraCharsAddedHere = 0;
                    if (attr.textContent === ""){
                        //charOffset += "'='".length
                        extraCharsAddedHere = "=''".length

                        offsetAtCharIndex = []
                        for (var charIndex in attrStr){
                            if (charIndex >= attrStr.length - '=""'.length){
                                offsetAtCharIndex.push(attrStr.length - "=''".length - charIndex - 1)
                            } else {
                                offsetAtCharIndex.push(0)
                            }
                        }
                    }

                    addElOrigin(child, "attribute_" + attr.name, {
                        action: actionName,
                        inputValues: [assignedInnerHTML],
                        value: innerHTMLAfterAssignment,
                        inputValuesCharacterIndex: [charOffsetBefore],
                        extraCharsAdded: extraCharsAdded,
                        offsetAtCharIndex: offsetAtCharIndex
                    })

                    extraCharsAdded += extraCharsAddedHere

                    forDebuggingProcessedHtml += attrStr
                }

                // console.log("extraCharsAdded", extraCharsAdded)

                var openingTagEnd = ">"
                if (assignedInnerHTML.toString()[charOffset] === " ") {
                    // something like <div > (with extra space)
                    // this char will not show up in the re-serialized innerHTML
                    extraCharsAdded -= 1;
                }
                addElOrigin(child, "openingTagEnd", {
                    action: actionName,
                    inputValues: [assignedInnerHTML],
                    inputValuesCharacterIndex: [charOffset],
                    value: innerHTMLAfterAssignment,
                    extraCharsAdded: extraCharsAdded
                })
                charOffset += openingTagEnd.length
                forDebuggingProcessedHtml += openingTagEnd

                processNewInnerHtml(child)

                if (tagTypeHasClosingTag(child.tagName)) {
                    addElOrigin(child, "closingTag", {
                        action: actionName,
                        inputValues: [assignedInnerHTML],
                        inputValuesCharacterIndex: [charOffset],
                        value: innerHTMLAfterAssignment,
                        extraCharsAdded: extraCharsAdded
                    })
                    var closingTag = "</" + child.tagName + ">"
                    charOffset += closingTag.length
                    forDebuggingProcessedHtml += closingTag
                }

            }
            // console.log("processed", forDebuggingProcessedHtml, assignedInnerHTML.toString().toLowerCase().replace(/\"/g, "'") === forDebuggingProcessedHtml.toLowerCase())

        })
    }
}
<commit_msg>Handle comment nodes better rather than throwing exception.<commit_after>import addElOrigin from "./addElOrigin"
import $ from "jquery"
import tagTypeHasClosingTag from "./tagTypeHasClosingTag"

// tries to describe the relationship between an assigned innerHTML value
// and the value you get back when reading el.innerHTML.
// e.g. you could assign "<input type='checkbox' checked>" and get back
// "<input type='checkbox' checked=''>"
export default function mapInnerHTMLAssignment(el, assignedInnerHTML, actionName, initialExtraCharsValue){
    var innerHTMLAfterAssignment = nativeInnerHTMLDescriptor.get.call(el)
    var forDebuggingProcessedHtml = ""
    var charOffset = 0;
    var extraCharsAdded = 0;
    if (initialExtraCharsValue !== undefined){
        extraCharsAdded = initialExtraCharsValue
    }
    processNewInnerHtml(el)

    function processNewInnerHtml(el){
        var children = Array.prototype.slice.apply(el.childNodes, [])
        addElOrigin(el, "replaceContents", {
            action: actionName,
            children: children
        })

        $(el).contents().each(function(i, child){
            var isTextNode = child.nodeType === 3
            var isCommentNode = child.nodeType === 8
            var isElementNode = child.nodeType === 1
            if (isTextNode) {
                addElOrigin(child, "textValue", {
                    "action": actionName,
                    inputValues: [assignedInnerHTML],
                    value: innerHTMLAfterAssignment,
                    inputValuesCharacterIndex: [charOffset],
                    extraCharsAdded: extraCharsAdded
                })

                charOffset += child.textContent.length
                forDebuggingProcessedHtml += child.textContent
            } else if (isCommentNode) {
                // do nothing?
            } else if (isElementNode) {

                addElOrigin(child, "openingTagStart", {
                    action: actionName,
                    inputValues: [assignedInnerHTML],
                    inputValuesCharacterIndex: [charOffset],
                    value: innerHTMLAfterAssignment,
                    extraCharsAdded: extraCharsAdded
                })
                var openingTagStart = "<" + child.tagName
                charOffset += openingTagStart.length
                forDebuggingProcessedHtml += openingTagStart

                for (var i = 0;i<child.attributes.length;i++) {
                    var attr = child.attributes[i]

                    var charOffsetBefore = charOffset

                    var attrStr = " " + attr.name
                    attrStr += "='" + attr.textContent +  "'"

                    charOffset += attrStr.length
                    var offsetAtCharIndex = null
                    var extraCharsAddedHere = 0;
                    if (attr.textContent === ""){
                        //charOffset += "'='".length
                        extraCharsAddedHere = "=''".length

                        offsetAtCharIndex = []
                        for (var charIndex in attrStr){
                            if (charIndex >= attrStr.length - '=""'.length){
                                offsetAtCharIndex.push(attrStr.length - "=''".length - charIndex - 1)
                            } else {
                                offsetAtCharIndex.push(0)
                            }
                        }
                    }

                    addElOrigin(child, "attribute_" + attr.name, {
                        action: actionName,
                        inputValues: [assignedInnerHTML],
                        value: innerHTMLAfterAssignment,
                        inputValuesCharacterIndex: [charOffsetBefore],
                        extraCharsAdded: extraCharsAdded,
                        offsetAtCharIndex: offsetAtCharIndex
                    })

                    extraCharsAdded += extraCharsAddedHere

                    forDebuggingProcessedHtml += attrStr
                }

                var openingTagEnd = ">"
                if (assignedInnerHTML.toString()[charOffset] === " ") {
                    // something like <div > (with extra space)
                    // this char will not show up in the re-serialized innerHTML
                    extraCharsAdded -= 1;
                }
                addElOrigin(child, "openingTagEnd", {
                    action: actionName,
                    inputValues: [assignedInnerHTML],
                    inputValuesCharacterIndex: [charOffset],
                    value: innerHTMLAfterAssignment,
                    extraCharsAdded: extraCharsAdded
                })
                charOffset += openingTagEnd.length
                forDebuggingProcessedHtml += openingTagEnd

                processNewInnerHtml(child)

                if (tagTypeHasClosingTag(child.tagName)) {
                    addElOrigin(child, "closingTag", {
                        action: actionName,
                        inputValues: [assignedInnerHTML],
                        inputValuesCharacterIndex: [charOffset],
                        value: innerHTMLAfterAssignment,
                        extraCharsAdded: extraCharsAdded
                    })
                    var closingTag = "</" + child.tagName + ">"
                    charOffset += closingTag.length
                    forDebuggingProcessedHtml += closingTag
                }

            } else {
                throw "not handled"
            }
            // console.log("processed", forDebuggingProcessedHtml, assignedInnerHTML.toString().toLowerCase().replace(/\"/g, "'") === forDebuggingProcessedHtml.toLowerCase())

        })
    }
}
<|endoftext|>


<commit_before>describe("Traverser Service", function () {

  var Traverser;

  beforeEach(module('traverser'));

  beforeEach(inject(function (_Traverser_) {
    Traverser = _Traverser_;
  }));

  describe("Making a view map", function () {

    it("should make a viewMap", function () {
      var states = [
        {name: 'folderview',
          viewConfig: {resourceType: 'folder', name: 'default'}},
        {name: 'some.route'}
      ];
      Traverser.makeViewMap(states);
      var viewConfig = Traverser.viewMap.default[0];
      expect(viewConfig.resourceType).toBe('folder');
    });

    it("should make a viewMap (best match ordering)", function () {
      var states = [
        {name: 'folderview',
          viewConfig: {resourceType: 'folder', name: 'default'}},
        {name: 'folderview',
          viewConfig: {resourceType: 'folder', name: 'default', marker: 'somemarker'}},
        {name: 'some.route'}
      ];
      Traverser.makeViewMap(states);
      var viewConfig = Traverser.viewMap.default[0];
      expect(viewConfig.resourceType).toBe('folder');
      expect(viewConfig.marker).toBe('somemarker');
    });

  });

  describe("Resolve states", function () {

    var toState;

    it("should choose the highest precedence", function () {
      var states = [
        {name: 'some-state', viewConfig: {name: 'default'}
        }
      ];
      Traverser.makeViewMap(states);
      var args = {title: 'Context 1', viewName: 'default'};
      toState = Traverser.resolveState(args);
      expect(toState).toBe('folder');
    });

    it("should choose the highest precedence", function () {
      var states = [
        {name: 'view1',
          viewConfig: {name: 'default',
            resourceType: 'folder'}
        }
      ];
      Traverser.makeViewMap(states);

      var viewConfig = Traverser.viewMap.default[0];
      expect(viewConfig.resourceType).toBe('folder');
    });

  });

});

<commit_msg>fixed test<commit_after>describe("Traverser Service", function () {

  var Traverser;

  beforeEach(module('traverser'));

  beforeEach(inject(function (_Traverser_) {
    Traverser = _Traverser_;
  }));

  describe("Making a view map", function () {

    it("should make a viewMap", function () {
      var states = [
        {name: 'folderview',
          viewConfig: {resourceType: 'folder', name: 'default'}},
        {name: 'some.route'}
      ];
      Traverser.makeViewMap(states);
      var viewConfig = Traverser.viewMap.default[0];
      expect(viewConfig.resourceType).toBe('folder');
    });

    it("should make a viewMap (best match ordering)", function () {
      var states = [
        {name: 'folderview',
          viewConfig: {resourceType: 'folder', name: 'default'}},
        {name: 'folderview-marker',
          viewConfig: {resourceType: 'folder', name: 'default', marker: 'somemarker'}},
        {name: 'some.route'}
      ];
      Traverser.makeViewMap(states);
      var viewConfig = Traverser.viewMap.default[0];
      expect(viewConfig.marker).toBe('somemarker');
    });

  });

  describe("Resolve states", function () {

    var toState;

    it("should choose the highest precedence", function () {
      var states = [
        {name: 'some-state', viewConfig: {name: 'default'}
        }
      ];
      Traverser.makeViewMap(states);
      var args = {title: 'Context 1', viewName: 'default'};
      toState = Traverser.resolveState(args);
      expect(toState).toBe('folder');
    });

    it("should choose the highest precedence", function () {
      var states = [
        {name: 'view1',
          viewConfig: {name: 'default',
            resourceType: 'folder'}
        }
      ];
      Traverser.makeViewMap(states);

      var viewConfig = Traverser.viewMap.default[0];
      expect(viewConfig.resourceType).toBe('folder');
    });

  });

});

<|endoftext|>