<commit_before>fullscreen = function() {
	screenfull.toggle();
}

Polymer('character-card', {
	response: "",
	character: {
		"Might":"",
		"Speed":"",
		"Knowledge":"",
		"Sanity":"",
		"MightIndex":"",
		"SpeedIndex":"",
		"KnowledgeIndex":"",
		"SanityIndex":""
	},

	updateStat: function(attribute, direction) {
		switch(attribute) {
			case "might":
				switch(direction) {
					case "up":
						console.log("up");
						if(this.character.MightIndex < 8) {
							document.querySelector("character-card::shadow #might-score").innerHTML = this.character.Might[++this.character.MightIndex];
						}
						break;
					case "down":
						console.log("down");
						if(this.character.MightIndex > 0) {
							document.querySelector("character-card::shadow #might-score").innerHTML = this.character.Might[--this.character.MightIndex];
						}
						break;
				}
				document.querySelector("character-card::shadow #might-index").innerHTML = this.character.MightIndex;
				if(!this.character.MightIndex) {
					alert("You've died.");
				}
				break;
			case "speed":
				switch(direction) {
					case "up":
						console.log("up");
						if(this.character.SpeedIndex < 8) {
							document.querySelector("character-card::shadow #speed-score").innerHTML = this.character.Speed[++this.character.SpeedIndex];
						}
						break;
					case "down":
						console.log("down");
						if(this.character.SpeedIndex > 0) {
							document.querySelector("character-card::shadow #speed-score").innerHTML = this.character.Speed[--this.character.SpeedIndex];
						}
						break;
				}
				document.querySelector("character-card::shadow #speed-index").innerHTML = this.character.SpeedIndex;
				if(!this.character.SpeedIndex) {
					alert("You've died.");
				}
				break;
			case "knowledge":
				switch(direction) {
					case "up":
						console.log("up");
						if(this.character.KnowledgeIndex < 8) {
							document.querySelector("character-card::shadow #knowledge-score").innerHTML = this.character.Knowledge[++this.character.KnowledgeIndex];
						}
						break;
					case "down":
						console.log("down");
						if(this.character.KnowledgeIndex > 0) {
							document.querySelector("character-card::shadow #knowledge-score").innerHTML = this.character.Knowledge[--this.character.KnowledgeIndex];
						}
						break;
				}
				document.querySelector("character-card::shadow #knowledge-index").innerHTML = this.character.KnowledgeIndex;
				if(!this.character.KnowledgeIndex) {
					alert("You've died.");
				}
				break;
			case "sanity":
				switch(direction) {
					case "up":
						console.log("up");
						if(this.character.SanityIndex < 8) {
							document.querySelector("character-card::shadow #sanity-score").innerHTML = this.character.Sanity[++this.character.SanityIndex];
						}
						break;
					case "down":
						console.log("down");
						if(this.character.SanityIndex > 0) {
							document.querySelector("character-card::shadow #sanity-score").innerHTML = this.character.Sanity[--this.character.SanityIndex];
						}
						break;
				}
				document.querySelector("character-card::shadow #sanity-index").innerHTML = this.character.SanityIndex;
				if(!this.character.SanityIndex) {
					alert("You've died.");
				}
				break;
		}
	},

	clickHandler: function(event) {
		event.stopPropogation();
		attribute = event.target.attributes['name'].value;
		direction = event.target.attributes['class'].value;
		self.updateStat(attribute, direction);
	},

	setHeader: function(character) {
		switch(character) {
			case "ox-bellows":
			case "darrin-flash-williams":
				color = "#F44336";
				break;
			case "father-rhinehardt":
			case "professor-longfellow":
				color = "#9E9E9E";
				break;
			case "vivian-lopez":
			case "madame-zostra":
				color = "#3F51B5";
				break;
			case "peter-akimoto":
			case "brandon-jaspers":
				color = "#8BC34A";
				break;
			case "missy-dobourde":
			case "zoe-ingstrom":
				color = "#FFC107";
				break;
			case "jenny-leclerc":
			case "heather-granville":
				color = "#9C27B0";
				break;
			default:
				color = "#000000";
		}

		document.querySelector("character-card::shadow #character-name").style.backgroundColor = color;
	},

	setCardValues: function(character) {
		characters = [
				"ox-bellows",
				"father-rhinehardt",
				"vivian-lopez",
				"peter-akimoto",
				"missy-dobourde",
				"jenny-leclerc",
				"darrin-flash-williams",
				"professor-longfellow",
				"madame-zostra",
				"brandon-jaspers",
				"zoe-ingstrom",
				"heather-granville"
		]

		selection = this.response.Characters[characters.indexOf(character)];

		document.querySelector("character-card::shadow #character-name").innerHTML = selection.Name;
		document.querySelector("character-card::shadow #age").innerHTML = selection.Age;
		document.querySelector("character-card::shadow #height").innerHTML = selection.Height;
		document.querySelector("character-card::shadow #weight").innerHTML = selection.Weight;
		document.querySelector("character-card::shadow #birthday").innerHTML = selection.Birthday;
		document.querySelector("character-card::shadow #hobbies").innerHTML = selection.Hobbies;
		document.querySelector("character-card::shadow #might-score").innerHTML = selection.Might[selection.BaseMightIndex];
		document.querySelector("character-card::shadow #speed-score").innerHTML = selection.Speed[selection.BaseSpeedIndex];
		document.querySelector("character-card::shadow #knowledge-score").innerHTML = selection.Knowledge[selection.BaseKnowledgeIndex];
		document.querySelector("character-card::shadow #sanity-score").innerHTML = selection.Sanity[selection.BaseSanityIndex];
		document.querySelector("character-card::shadow #might-index").innerHTML = selection.BaseMightIndex;
		document.querySelector("character-card::shadow #speed-index").innerHTML = selection.BaseSpeedIndex;
		document.querySelector("character-card::shadow #knowledge-index").innerHTML = selection.BaseKnowledgeIndex;
		document.querySelector("character-card::shadow #sanity-index").innerHTML = selection.BaseSanityIndex;

		this.character.Might = selection.Might;
		this.character.Speed = selection.Speed;
		this.character.Knowledge = selection.Knowledge;
		this.character.Sanity = selection.Sanity;
		this.character.MightIndex = selection.BaseMightIndex
		this.character.SpeedIndex = selection.BaseSpeedIndex
		this.character.KnowledgeIndex = selection.BaseKnowledgeIndex
		this.character.SanityIndex = selection.BaseSanityIndex
	},

	getCharacter: function(character) {
		self = this;

		this.setHeader(character);

		request = new XMLHttpRequest();
		request.open("GET", "/polymer-character-card/elements/character-card/characters.json", true);

		response = "";
		request.onreadystatechange = function() {
			if(request.readyState === request.DONE) {
				status = request.status;

				if((status >= 200 && status < 300) || status === 304 || status === 0) {
					self.response = JSON.parse(request.responseText);
					self.setCardValues(character);
				}
			}
		};
		request.send();
	},

	domReady: function() {
		self = this;

		ups = document.querySelectorAll("character-card::shadow .up");

		for (var i = ups.length - 1; i >= 0; i--) {
			ups[i].addEventListener("click", this.clickHandler);
		};

		downs = document.querySelectorAll("character-card::shadow .down");

		for (var j = downs.length - 1; j >= 0; j--) {
			downs[j].addEventListener("click", this.clickHandler);
		};

		//this.getCharacter("darrin-flash-williams");
	},
});
<commit_msg>Update character-card.js<commit_after>fullscreen = function() {
	screenfull.toggle();
}

Polymer('character-card', {
	response: "",
	character: {
		"Might":"",
		"Speed":"",
		"Knowledge":"",
		"Sanity":"",
		"MightIndex":"",
		"SpeedIndex":"",
		"KnowledgeIndex":"",
		"SanityIndex":""
	},

	updateStat: function(attribute, direction) {
		switch(attribute) {
			case "might":
				switch(direction) {
					case "up":
						console.log("up");
						if(this.character.MightIndex < 8) {
							document.querySelector("character-card::shadow #might-score").innerHTML = this.character.Might[++this.character.MightIndex];
						}
						break;
					case "down":
						console.log("down");
						if(this.character.MightIndex > 0) {
							document.querySelector("character-card::shadow #might-score").innerHTML = this.character.Might[--this.character.MightIndex];
						}
						break;
				}
				document.querySelector("character-card::shadow #might-index").innerHTML = this.character.MightIndex;
				if(!this.character.MightIndex) {
					alert("You've died.");
				}
				break;
			case "speed":
				switch(direction) {
					case "up":
						console.log("up");
						if(this.character.SpeedIndex < 8) {
							document.querySelector("character-card::shadow #speed-score").innerHTML = this.character.Speed[++this.character.SpeedIndex];
						}
						break;
					case "down":
						console.log("down");
						if(this.character.SpeedIndex > 0) {
							document.querySelector("character-card::shadow #speed-score").innerHTML = this.character.Speed[--this.character.SpeedIndex];
						}
						break;
				}
				document.querySelector("character-card::shadow #speed-index").innerHTML = this.character.SpeedIndex;
				if(!this.character.SpeedIndex) {
					alert("You've died.");
				}
				break;
			case "knowledge":
				switch(direction) {
					case "up":
						console.log("up");
						if(this.character.KnowledgeIndex < 8) {
							document.querySelector("character-card::shadow #knowledge-score").innerHTML = this.character.Knowledge[++this.character.KnowledgeIndex];
						}
						break;
					case "down":
						console.log("down");
						if(this.character.KnowledgeIndex > 0) {
							document.querySelector("character-card::shadow #knowledge-score").innerHTML = this.character.Knowledge[--this.character.KnowledgeIndex];
						}
						break;
				}
				document.querySelector("character-card::shadow #knowledge-index").innerHTML = this.character.KnowledgeIndex;
				if(!this.character.KnowledgeIndex) {
					alert("You've died.");
				}
				break;
			case "sanity":
				switch(direction) {
					case "up":
						console.log("up");
						if(this.character.SanityIndex < 8) {
							document.querySelector("character-card::shadow #sanity-score").innerHTML = this.character.Sanity[++this.character.SanityIndex];
						}
						break;
					case "down":
						console.log("down");
						if(this.character.SanityIndex > 0) {
							document.querySelector("character-card::shadow #sanity-score").innerHTML = this.character.Sanity[--this.character.SanityIndex];
						}
						break;
				}
				document.querySelector("character-card::shadow #sanity-index").innerHTML = this.character.SanityIndex;
				if(!this.character.SanityIndex) {
					alert("You've died.");
				}
				break;
		}
	},

	clickHandler: function(event) {
		event.stopPropogation();
		attribute = event.target.attributes['name'].value;
		direction = event.target.attributes['class'].value;
		self.updateStat(attribute, direction);
	},

	setHeader: function(character) {
		switch(character) {
			case "ox-bellows":
			case "darrin-flash-williams":
				color = "#F44336";
				break;
			case "father-rhinehardt":
			case "professor-longfellow":
				color = "#9E9E9E";
				break;
			case "vivian-lopez":
			case "madame-zostra":
				color = "#3F51B5";
				break;
			case "peter-akimoto":
			case "brandon-jaspers":
				color = "#8BC34A";
				break;
			case "missy-dobourde":
			case "zoe-ingstrom":
				color = "#FFC107";
				break;
			case "jenny-leclerc":
			case "heather-granville":
				color = "#9C27B0";
				break;
			default:
				color = "#000000";
		}

		document.querySelector("character-card::shadow #character-name").style.backgroundColor = color;
	},

	setCardValues: function(character) {
		characters = [
				"ox-bellows",
				"father-rhinehardt",
				"vivian-lopez",
				"peter-akimoto",
				"missy-dobourde",
				"jenny-leclerc",
				"darrin-flash-williams",
				"professor-longfellow",
				"madame-zostra",
				"brandon-jaspers",
				"zoe-ingstrom",
				"heather-granville"
		]

		selection = this.response.Characters[characters.indexOf(character)];

		document.querySelector("character-card::shadow #character-name").innerHTML = selection.Name;
		document.querySelector("character-card::shadow #age").innerHTML = selection.Age;
		document.querySelector("character-card::shadow #height").innerHTML = selection.Height;
		document.querySelector("character-card::shadow #weight").innerHTML = selection.Weight;
		document.querySelector("character-card::shadow #birthday").innerHTML = selection.Birthday;
		document.querySelector("character-card::shadow #hobbies").innerHTML = selection.Hobbies;
		document.querySelector("character-card::shadow #might-score").innerHTML = selection.Might[selection.BaseMightIndex];
		document.querySelector("character-card::shadow #speed-score").innerHTML = selection.Speed[selection.BaseSpeedIndex];
		document.querySelector("character-card::shadow #knowledge-score").innerHTML = selection.Knowledge[selection.BaseKnowledgeIndex];
		document.querySelector("character-card::shadow #sanity-score").innerHTML = selection.Sanity[selection.BaseSanityIndex];
		document.querySelector("character-card::shadow #might-index").innerHTML = selection.BaseMightIndex;
		document.querySelector("character-card::shadow #speed-index").innerHTML = selection.BaseSpeedIndex;
		document.querySelector("character-card::shadow #knowledge-index").innerHTML = selection.BaseKnowledgeIndex;
		document.querySelector("character-card::shadow #sanity-index").innerHTML = selection.BaseSanityIndex;

		this.character.Might = selection.Might;
		this.character.Speed = selection.Speed;
		this.character.Knowledge = selection.Knowledge;
		this.character.Sanity = selection.Sanity;
		this.character.MightIndex = selection.BaseMightIndex
		this.character.SpeedIndex = selection.BaseSpeedIndex
		this.character.KnowledgeIndex = selection.BaseKnowledgeIndex
		this.character.SanityIndex = selection.BaseSanityIndex
	},

	getCharacter: function(character) {
		self = this;

		this.setHeader(character);

		request = new XMLHttpRequest();
		request.open("GET", "/polymer-character-card/elements/character-card/characters.json", true);

		response = "";
		request.onreadystatechange = function() {
			if(request.readyState === request.DONE) {
				status = request.status;

				if((status >= 200 && status < 300) || status === 304 || status === 0) {
					self.response = JSON.parse(request.responseText);
					self.setCardValues(character);
				}
			}
		};
		request.send();
	},

	ready: function() {
		self = this;

		ups = document.querySelectorAll("character-card::shadow .up");

		for (var i = ups.length - 1; i >= 0; i--) {
			ups[i].addEventListener("click", this.clickHandler);
		};

		downs = document.querySelectorAll("character-card::shadow .down");

		for (var j = downs.length - 1; j >= 0; j--) {
			downs[j].addEventListener("click", this.clickHandler);
		};

		//this.getCharacter("darrin-flash-williams");
	},
});
<|endoftext|>


<commit_before>import React from 'react'

const Details = React.createClass({

   render () {

      console.log(this.props)
      return (

test

      )
   }
})

export default Details
<commit_msg>update 'Details' component to display show<commit_after>import React from 'react'
const { shape, string } = React.PropTypes

const Details = React.createClass({
   propsTypes: {
      show: shape({
         title: string,
         year: string,
         poster: string,
         description: string,
         trailer: string
      })

   },

   render () {

      const { poster, title, year, description, trailer } = this.props.show
      console.log(this.props)

      return (

svideo

{title}

({year})

            <img src={`/public/img/posters/${poster}`} />

{description}

            <iframe src={`https://www.youtube-nocookie.com/embed/${trailer}?rel=0&controls=0&showinfo=0`} frameBorder='0' allowFullScreen />

      )
   }
})

// stateless compponent can take props -> query params property

// const Details = (props) => {
//   return
stateless component

// }

export default Details

<|endoftext|>


<commit_before>function inject(fn) {
    var script = document.createElement('script');
    script.setAttribute("type", "application/javascript");
    script.textContent = '(' + fn + ')();';
    document.body.appendChild(script);
    document.body.removeChild(script);
}

function change_keymap () {

    var codemirror = document.getElementsByClassName('CodeMirror')[0];
    var code_editor = codemirror.CodeMirror;
    var keymap_mode;

    if (document.all) {
        keymap_mode = document.getElementById('keymap_btn').firstElementChild.innerText;
    } else {
        keymap_mode = document.getElementById('keymap_btn').firstElementChild.textContent;
    }

    if (keymap_mode === 'VIM') {

        code_editor.setOption('keyMap', 'vim');
        code_editor.setOption('extraKeys', {"':'": function (cm) {
            var state = cm.getOption('keyMap')
            if (state === 'vim-insert') {
               cm.replaceSelection(':', "end");
            }
        }});
        code_editor.setOption('onKeyEvent', function (instance, key_event) {

                function changeCursor(state) {
                     var cm_div = document.getElementsByClassName('CodeMirror')[0];
                     var current_class = cm_div.className;
                     var focus = current_class.search('CodeMirror-focused');
                     var new_class;
                     if (state === 'normal') {
                         new_class = 'CodeMirror cm-s-codacity cm-keymap-fat-cursor';
                     }
                     else if (state === 'insert') {
                         new_class = 'CodeMirror cm-s-codacity';
                     }
                     if (focus) {
                         new_class = new_class + ' CodeMirror-focused';
                     }
                     cm_div.className = new_class;
                 }

                 // ESC
                 if (key_event.keyCode === 27) {
                     changeCursor('normal');
                 }
                 // C-[
                 else if (key_event.keyCode === 219 && key_event.ctrlKey) {
                     changeCursor('normal');
                 }

                 // C-c
                 else if (key_event.keyCode === 67 && key_event.ctrlKey) {
                     changeCursor('normal');
                 }

                 // a
                 else if (key_event.keyCode === 65) {
                     changeCursor('insert');
                 }

                 // i
                 else if (key_event.keyCode === 73) {
                     changeCursor('insert');
                 }

                 // s
                 else if (key_event.keyCode === 83) {
                     changeCursor('insert');
                 }

                 // o
                 else if (key_event.keyCode === 79) {
                     changeCursor('insert');
                 }
        });
    }

    else if (keymap_mode === 'DEFAULT') {
        code_editor.setOption('keyMap', 'default');
        code_editor.setOption('extraKeys', null);

    }

    else if (keymap_mode === 'EMACS') {
        code_editor.setOption('keyMap', 'emacs');
        code_editor.setOption('extraKeys', null);
        code_editor.setOption('onKeyEvent', function () {});
    }
}

function load_bindings () {

        var cursor_style = ['.CodeMirror.cm-keymap-fat-cursor pre.CodeMirror-cursor {',
                           '    z-index: 10;',
                           '    width: auto;',
                           '    border: 0;',
                           '    background: transparent;',
                           '    background: rgba(0, 200, 0, .4);',
                           '}'].join('\n');

        var new_css = document.createElement('style');
        new_css.type = 'text/css';
        new_css.innerHTML = cursor_style;
        document.head.appendChild(new_css);
}

function load_keymap_btn () {

    function toggle_mode (btn) {
        var binding_titles = ["DEFAULT", "VIM", "EMACS"];
        var btn_state = btn.getAttribute('state');
        var i = parseInt(btn_state, 10);
        i = (i + 1) % binding_titles.length;
        btn.setAttribute("state", i);
        var keymap_mode = binding_titles[i];
        if (document.all) {
            btn.firstElementChild.innerText = keymap_mode;
        } else {
            btn.firstElementChild.textContent = keymap_mode;
        }
        return keymap_mode;
    }

    function reset_mode (btn) {
        btn.setAttribute("state", 0);
        if (document.all) {
            btn.firstElementChild.innerText = "DEFAULT";
        } else {
            btn.firstElementChild.textContent = "DEFAULT";
        }
    }

    function try_append () {
        var test_run = document.getElementsByClassName('test-run')[0];
        if (test_run) {
          quiz_controls.appendChild(keymap_btn);
        } else {
            setTimeout(try_append, 500);
        }
    }

    var quiz_controls = document.getElementsByClassName('programming-quiz-controls')[0];

    var keymap_btn = document.createElement('div');
    keymap_btn.setAttribute("class", "btn");
    keymap_btn.setAttribute("id", "keymap_btn");
    if (document.all) {
        keymap_btn.innerText = " Key bindings: ";
    } else {
        keymap_btn.textContent = " Key bindings: ";
    }
    var strong_state = document.createElement('strong');
    if (document.all) {
        strong_state.innerText = "DEFAULT";
    } else {
        strong_state.textContent = "DEFAULT";
    }
    keymap_btn.appendChild(strong_state);

    var keymap_btn_style = ['#keymap_btn {',
                             '  margin-right: 10px;',
                             '  line-height: 18px;',
                             '}'].join('\n');

    var keymap_btn_css = document.createElement('style');
        keymap_btn_css.type = 'text/css';
        keymap_btn_css.innerHTML = keymap_btn_style;
        document.head.appendChild(keymap_btn_css);

    keymap_btn.setAttribute("state", 0);

    keymap_btn.addEventListener('click', function () {
        var keymap_mode = toggle_mode(this);
        inject(change_keymap);
    });

    window.addEventListener('hashchange', function () {
        reset_mode(keymap_btn);
    });

    inject(load_bindings);
    try_append();

}

load_keymap_btn();
<commit_msg>Update quiz_controls to get correct class name and move it so that we query when it's loaded.<commit_after>function inject(fn) {
    var script = document.createElement('script');
    script.setAttribute("type", "application/javascript");
    script.textContent = '(' + fn + ')();';
    document.body.appendChild(script);
    document.body.removeChild(script);
}

function change_keymap () {

    var codemirror = document.getElementsByClassName('CodeMirror')[0];
    var code_editor = codemirror.CodeMirror;
    var keymap_mode;

    if (document.all) {
        keymap_mode = document.getElementById('keymap_btn').firstElementChild.innerText;
    } else {
        keymap_mode = document.getElementById('keymap_btn').firstElementChild.textContent;
    }

    if (keymap_mode === 'VIM') {

        code_editor.setOption('keyMap', 'vim');
        code_editor.setOption('extraKeys', {"':'": function (cm) {
            var state = cm.getOption('keyMap')
            if (state === 'vim-insert') {
               cm.replaceSelection(':', "end");
            }
        }});
        code_editor.setOption('onKeyEvent', function (instance, key_event) {

                function changeCursor(state) {
                     var cm_div = document.getElementsByClassName('CodeMirror')[0];
                     var current_class = cm_div.className;
                     var focus = current_class.search('CodeMirror-focused');
                     var new_class;
                     if (state === 'normal') {
                         new_class = 'CodeMirror cm-s-codacity cm-keymap-fat-cursor';
                     }
                     else if (state === 'insert') {
                         new_class = 'CodeMirror cm-s-codacity';
                     }
                     if (focus) {
                         new_class = new_class + ' CodeMirror-focused';
                     }
                     cm_div.className = new_class;
                 }

                 // ESC
                 if (key_event.keyCode === 27) {
                     changeCursor('normal');
                 }
                 // C-[
                 else if (key_event.keyCode === 219 && key_event.ctrlKey) {
                     changeCursor('normal');
                 }

                 // C-c
                 else if (key_event.keyCode === 67 && key_event.ctrlKey) {
                     changeCursor('normal');
                 }

                 // a
                 else if (key_event.keyCode === 65) {
                     changeCursor('insert');
                 }

                 // i
                 else if (key_event.keyCode === 73) {
                     changeCursor('insert');
                 }

                 // s
                 else if (key_event.keyCode === 83) {
                     changeCursor('insert');
                 }

                 // o
                 else if (key_event.keyCode === 79) {
                     changeCursor('insert');
                 }
        });
    }

    else if (keymap_mode === 'DEFAULT') {
        code_editor.setOption('keyMap', 'default');
        code_editor.setOption('extraKeys', null);

    }

    else if (keymap_mode === 'EMACS') {
        code_editor.setOption('keyMap', 'emacs');
        code_editor.setOption('extraKeys', null);
        code_editor.setOption('onKeyEvent', function () {});
    }
}

function load_bindings () {

        var cursor_style = ['.CodeMirror.cm-keymap-fat-cursor pre.CodeMirror-cursor {',
                           '    z-index: 10;',
                           '    width: auto;',
                           '    border: 0;',
                           '    background: transparent;',
                           '    background: rgba(0, 200, 0, .4);',
                           '}'].join('\n');

        var new_css = document.createElement('style');
        new_css.type = 'text/css';
        new_css.innerHTML = cursor_style;
        document.head.appendChild(new_css);
}

function load_keymap_btn () {

    function toggle_mode (btn) {
        var binding_titles = ["DEFAULT", "VIM", "EMACS"];
        var btn_state = btn.getAttribute('state');
        var i = parseInt(btn_state, 10);
        i = (i + 1) % binding_titles.length;
        btn.setAttribute("state", i);
        var keymap_mode = binding_titles[i];
        if (document.all) {
            btn.firstElementChild.innerText = keymap_mode;
        } else {
            btn.firstElementChild.textContent = keymap_mode;
        }
        return keymap_mode;
    }

    function reset_mode (btn) {
        btn.setAttribute("state", 0);
        if (document.all) {
            btn.firstElementChild.innerText = "DEFAULT";
        } else {
            btn.firstElementChild.textContent = "DEFAULT";
        }
    }

    function try_append () {
        var test_run = document.getElementsByClassName('test-run')[0];
        if (test_run) {
          var quiz_controls = document.getElementsByClassName('viewer-button-bar')[0];
          quiz_controls.appendChild(keymap_btn);
        } else {
            setTimeout(try_append, 500);
        }
    }

    var keymap_btn = document.createElement('div');
    keymap_btn.setAttribute("class", "btn");
    keymap_btn.setAttribute("id", "keymap_btn");
    if (document.all) {
        keymap_btn.innerText = " Key bindings: ";
    } else {
        keymap_btn.textContent = " Key bindings: ";
    }
    var strong_state = document.createElement('strong');
    if (document.all) {
        strong_state.innerText = "DEFAULT";
    } else {
        strong_state.textContent = "DEFAULT";
    }
    keymap_btn.appendChild(strong_state);

    var keymap_btn_style = ['#keymap_btn {',
                             '  margin-right: 10px;',
                             '  line-height: 18px;',
                             '}'].join('\n');

    var keymap_btn_css = document.createElement('style');
        keymap_btn_css.type = 'text/css';
        keymap_btn_css.innerHTML = keymap_btn_style;
        document.head.appendChild(keymap_btn_css);

    keymap_btn.setAttribute("state", 0);

    keymap_btn.addEventListener('click', function () {
        var keymap_mode = toggle_mode(this);
        inject(change_keymap);
    });

    window.addEventListener('hashchange', function () {
        reset_mode(keymap_btn);
    });

    inject(load_bindings);
    try_append();

}

load_keymap_btn();
<|endoftext|>


<commit_before>/* ==========================================================================
   Settings for webpack JavaScript bundling system.
   ========================================================================== */

const BROWSER_LIST = require( './browser-list-config' );
const webpack = require( 'webpack' );
const TerserPlugin = require( 'terser-webpack-plugin' );

/* Commmon webpack 'module' option used in each configuration.
   Runs code through Babel and uses global supported browser list. */
const COMMON_MODULE_CONFIG = {
  rules: [ {
    use: {
      loader: 'babel-loader?cacheDirectory=true',
      options: {
        presets: [ [ '@babel/preset-env', {
          targets: {
            browsers: BROWSER_LIST.LAST_2_PLUS_IE_9_AND_UP
          },
          debug: false
        } ] ]
      }
    }
  } ]
};

/* Set warnings to true to show linter-style warnings.
   Set mangle to false and beautify to true to debug the output code. */
const COMMON_UGLIFY_CONFIG = new TerserPlugin( {
  cache: true,
  parallel: true,
  terserOptions: {
    ie8: false,
    ecma: 5,
    warnings: true,
    mangle: true,
    output: {
      comments: false,
      beautify: false
    }
  }
} );

const commonConf = {
  cache: true,
  module: COMMON_MODULE_CONFIG,
  mode: 'production',
  optimization: {
    minimizer: [
      COMMON_UGLIFY_CONFIG
    ],
  }
};

module.exports = { commonConf };
<commit_msg>Change minification config variable name<commit_after>/* ==========================================================================
   Settings for webpack JavaScript bundling system.
   ========================================================================== */

const BROWSER_LIST = require( './browser-list-config' );
const webpack = require( 'webpack' );
const TerserPlugin = require( 'terser-webpack-plugin' );

/* Commmon webpack 'module' option used in each configuration.
   Runs code through Babel and uses global supported browser list. */
const COMMON_MODULE_CONFIG = {
  rules: [ {
    use: {
      loader: 'babel-loader?cacheDirectory=true',
      options: {
        presets: [ [ '@babel/preset-env', {
          targets: {
            browsers: BROWSER_LIST.LAST_2_PLUS_IE_9_AND_UP
          },
          debug: false
        } ] ]
      }
    }
  } ]
};

/* Set warnings to true to show linter-style warnings.
   Set mangle to false and beautify to true to debug the output code. */
const COMMON_MINIFICATION_CONFIG = new TerserPlugin( {
  cache: true,
  parallel: true,
  terserOptions: {
    ie8: false,
    ecma: 5,
    warnings: true,
    mangle: true,
    output: {
      comments: false,
      beautify: false
    }
  }
} );

const commonConf = {
  cache: true,
  module: COMMON_MODULE_CONFIG,
  mode: 'production',
  optimization: {
    minimizer: [
      COMMON_MINIFICATION_CONFIG
    ],
  }
};

module.exports = { commonConf };
<|endoftext|>


<commit_before>// ```
// @datatype_void
// david.r.niciforovic@gmail.com
// webpack.common.js may be freely distributed under the MIT license
// ```

var webpack = require('webpack');
var helpers = require('./helpers');

//# Webpack Plugins
var CopyWebpackPlugin = require('copy-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;

//# Webpack Constants
const ENV = process.env.ENV = process.env.NODE_ENV = 'development';
const HMR = helpers.hasProcessFlag('hot');
const METADATA = {
  title: 'Angular 2 MEAN Webpack Starter Kit by @datatype_void',
  baseUrl: '/',
  host: process.env.HOST || '0.0.0.0',
  port: process.env.PORT || 8080,
  ENV: ENV,
  HMR: HMR
};

//# Webpack Configuration
//
// See: http://webpack.github.io/docs/configuration.html#cli
module.exports = {

  // Static metadata for index.html
  //
  // See: (custom attribute)
  metadata: METADATA,

  // Cache generated modules and chunks to improve performance for multiple incremental builds.
  // This is enabled by default in watch mode.
  // You can pass false to disable it.
  //
  // See: http://webpack.github.io/docs/configuration.html#cache
  // cache: false,

  // The entry point for the bundle
  // Our Angular.js app
  //
  // See: http://webpack.github.io/docs/configuration.html#entry
  entry: {

    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    // Our primary Angular 2 application
    'main': './src/main.browser.ts',

  },

  // Options affecting the resolving of modules.
  //
  // See: http://webpack.github.io/docs/configuration.html#resolve
  resolve: {

    // An array of extensions that should be used to resolve modules.
    //
    // See: http://webpack.github.io/docs/configuration.html#resolve-extensions
    extensions: ['', '.ts', '.js', '.scss'],

    // Ensure that root is `src`
    root: helpers.root('src'),

    // remove other default values
    modulesDirectories: ['node_modules']
  },

  // Options affecting the normal modules.
  //
  // See: http://webpack.github.io/docs/configuration.html#module
  module: {

    // An array of applied pre and post loaders.
    //
    // See: http://webpack.github.io/docs/configuration.html#module-preloaders-module-postloaders
    preLoaders: [

      // Tslint loader support for *.ts files
      //
      // See: https://github.com/wbuchwalter/tslint-loader
      // { test: /\.ts$/, loader: 'tslint-loader', exclude: [ helpers.root('node_modules') ] },

      // Source map loader support for *.js files
      // Extracts SourceMaps for source files that as added as sourceMappingURL comment.
      //
      // See: https://github.com/webpack/source-map-loader
      {
        test: /\.js$/,
        loader: 'source-map-loader',
        exclude: [
          // these packages have problems with their sourcemaps
          helpers.root('node_modules/rxjs'),
          helpers.root('node_modules/@angular2-material')
        ]
      }

    ],

    // An array of automatically applied loaders.
    //
    // IMPORTANT: The loaders here are resolved relative to the resource which they are applied to.
    // This means they are not resolved relative to the configuration file.
    //
    // See: http://webpack.github.io/docs/configuration.html#module-loaders
    loaders: [

      // Typescript loader support for .ts and Angular 2 async routes via .async.ts
      //
      // See: https://github.com/s-panferov/awesome-typescript-loader
      {
        test: /\.ts$/,
        loader: 'awesome-typescript-loader',
        exclude: [/\.(spec|e2e)\.ts$/]
      },

      // Json loader support for *.json files.
      //
      // See: https://github.com/webpack/json-loader
      {
        test: /\.json$/,
        loader: 'json-loader'
      },

      // Raw loader support for *.css files
      // Returns file content as string
      //
      // See: https://github.com/webpack/raw-loader
      {
        test: /\.css$/,
        loader: 'raw-loader'
      },

      // Raw loader support for *.html
      // Returns file content as string
      //
      // See: https://github.com/webpack/raw-loader
      {
        test: /\.html$/,
        loader: 'raw-loader',
        exclude: [helpers.root('src/index.html')]
      },

      // Support for sass imports
      // Add CSS rules to your document:
      // `require("!style!css!sass!./file.scss");`
      {
        test: /\.scss$/,
        loader: 'style!css!autoprefixer-loader?browsers=last 2 versions!sass',
        exclude: [ helpers.root('node_modules') ]
      }

    ]

  },

  // Add additional plugins to the compiler.
  //
  // See: http://webpack.github.io/docs/configuration.html#plugins
  plugins: [

    // Plugin: ForkCheckerPlugin
    // Description: Do type checking in a separate process, so webpack don't need to wait.
    //
    // See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
    new ForkCheckerPlugin(),

    // Plugin: OccurenceOrderPlugin
    // Description: Varies the distribution of the ids to get the smallest id length
    // for often used ids.
    //
    // See: https://webpack.github.io/docs/list-of-plugins.html#occurrenceorderplugin
    // See: https://github.com/webpack/docs/wiki/optimization#minimize
    new webpack.optimize.OccurenceOrderPlugin(true),

    // Plugin: CommonsChunkPlugin
    // Description: Shares common code between the pages.
    // It identifies common modules and put them into a commons chunk.
    //
    // See: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
    // See: https://github.com/webpack/docs/wiki/optimization#multi-page-app
    new webpack.optimize.CommonsChunkPlugin({
      helpers.reverse(['polyfills', 'vendor', 'main']),
      minChunks: Infinity
    }),

    // Plugin: CopyWebpackPlugin
    // Description: Copy files and directories in webpack.
    //
    // Copies project static assets.
    //
    // See: https://www.npmjs.com/package/copy-webpack-plugin
    new CopyWebpackPlugin([{
      from: 'src/assets',
      to: 'assets'
    }]),

    // Plugin: HtmlWebpackPlugin
    // Description: Simplifies creation of HTML files to serve your webpack bundles.
    // This is especially useful for webpack bundles that include a hash in the filename
    // which changes every compilation.
    //
    // See: https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      template: 'src/index.html',
      chunksSortMode: helpers.packageSort(['polyfills', 'vendor', 'main'])
    }),

    // Plugin: DefinePlugin
    // Description: Define free variables.
    // Useful for having development builds with debug logging or adding global constants.
    //
    // Environment helpers
    //
    // See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
    // NOTE: when adding more properties make sure you include them in custom-typings.d.ts
    new webpack.DefinePlugin({
      'ENV': JSON.stringify(METADATA.ENV),
      'HMR': HMR
    })

  ],

  // Include polyfills or mocks for various node stuff
  // Description: Node configuration
  //
  // See: https://webpack.github.io/docs/configuration.html#node
  node: {
    global: 'window',
    crypto: 'empty',
    module: false,
    clearImmediate: false,
    setImmediate: false
  }
};
<commit_msg>chore(webpack.common): fix casing<commit_after>// ```
// @datatype_void
// david.r.niciforovic@gmail.com
// webpack.common.js may be freely distributed under the MIT license
// ```

var webpack = require('webpack');
var helpers = require('./helpers');

//# Webpack Plugins
var CopyWebpackPlugin = require('copy-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;

//# Webpack Constants
const ENV = process.env.ENV = process.env.NODE_ENV = 'development';
const HMR = helpers.hasProcessFlag('hot');
const METADATA = {
  title: 'Angular 2 MEAN Webpack Starter Kit by @datatype_void',
  baseUrl: '/',
  host: process.env.HOST || '0.0.0.0',
  port: process.env.PORT || 8080,
  ENV: ENV,
  HMR: HMR
};

//# Webpack Configuration
//
// See: http://webpack.github.io/docs/configuration.html#cli
module.exports = {

  // Static metadata for index.html
  //
  // See: (custom attribute)
  metadata: METADATA,

  // Cache generated modules and chunks to improve performance for multiple incremental builds.
  // This is enabled by default in watch mode.
  // You can pass false to disable it.
  //
  // See: http://webpack.github.io/docs/configuration.html#cache
  // cache: false,

  // The entry point for the bundle
  // Our Angular.js app
  //
  // See: http://webpack.github.io/docs/configuration.html#entry
  entry: {

    'polyfills': './src/polyfills.ts',
    'vendor': './src/vendor.ts',
    // Our primary Angular 2 application
    'main': './src/main.browser.ts',

  },

  // Options affecting the resolving of modules.
  //
  // See: http://webpack.github.io/docs/configuration.html#resolve
  resolve: {

    // An array of extensions that should be used to resolve modules.
    //
    // See: http://webpack.github.io/docs/configuration.html#resolve-extensions
    extensions: ['', '.ts', '.js', '.scss'],

    // Ensure that root is `src`
    root: helpers.root('src'),

    // Remove other default values
    modulesDirectories: ['node_modules']
  },

  // Options affecting the normal modules.
  //
  // See: http://webpack.github.io/docs/configuration.html#module
  module: {

    // An array of applied pre and post loaders.
    //
    // See: http://webpack.github.io/docs/configuration.html#module-preloaders-module-postloaders
    preLoaders: [

      // Tslint loader support for *.ts files
      //
      // See: https://github.com/wbuchwalter/tslint-loader
      // { test: /\.ts$/, loader: 'tslint-loader', exclude: [ helpers.root('node_modules') ] },

      // Source map loader support for *.js files
      // Extracts SourceMaps for source files that as added as sourceMappingURL comment.
      //
      // See: https://github.com/webpack/source-map-loader
      {
        test: /\.js$/,
        loader: 'source-map-loader',
        exclude: [
          // these packages have problems with their sourcemaps
          helpers.root('node_modules/rxjs'),
          helpers.root('node_modules/@angular2-material')
        ]
      }

    ],

    // An array of automatically applied loaders.
    //
    // IMPORTANT: The loaders here are resolved relative to the resource which they are applied to.
    // This means they are not resolved relative to the configuration file.
    //
    // See: http://webpack.github.io/docs/configuration.html#module-loaders
    loaders: [

      // Typescript loader support for .ts and Angular 2 async routes via .async.ts
      //
      // See: https://github.com/s-panferov/awesome-typescript-loader
      {
        test: /\.ts$/,
        loader: 'awesome-typescript-loader',
        exclude: [/\.(spec|e2e)\.ts$/]
      },

      // Json loader support for *.json files.
      //
      // See: https://github.com/webpack/json-loader
      {
        test: /\.json$/,
        loader: 'json-loader'
      },

      // Raw loader support for *.css files
      // Returns file content as string
      //
      // See: https://github.com/webpack/raw-loader
      {
        test: /\.css$/,
        loader: 'raw-loader'
      },

      // Raw loader support for *.html
      // Returns file content as string
      //
      // See: https://github.com/webpack/raw-loader
      {
        test: /\.html$/,
        loader: 'raw-loader',
        exclude: [helpers.root('src/index.html')]
      },

      // Support for sass imports
      // Add CSS rules to your document:
      // `require("!style!css!sass!./file.scss");`
      {
        test: /\.scss$/,
        loader: 'style!css!autoprefixer-loader?browsers=last 2 versions!sass',
        exclude: [ helpers.root('node_modules') ]
      }

    ]

  },

  // Add additional plugins to the compiler.
  //
  // See: http://webpack.github.io/docs/configuration.html#plugins
  plugins: [

    // Plugin: ForkCheckerPlugin
    // Description: Do type checking in a separate process, so webpack don't need to wait.
    //
    // See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
    new ForkCheckerPlugin(),

    // Plugin: OccurenceOrderPlugin
    // Description: Varies the distribution of the ids to get the smallest id length
    // for often used ids.
    //
    // See: https://webpack.github.io/docs/list-of-plugins.html#occurrenceorderplugin
    // See: https://github.com/webpack/docs/wiki/optimization#minimize
    new webpack.optimize.OccurenceOrderPlugin(true),

    // Plugin: CommonsChunkPlugin
    // Description: Shares common code between the pages.
    // It identifies common modules and put them into a commons chunk.
    //
    // See: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
    // See: https://github.com/webpack/docs/wiki/optimization#multi-page-app
    new webpack.optimize.CommonsChunkPlugin({
      helpers.reverse(['polyfills', 'vendor', 'main']),
      minChunks: Infinity
    }),

    // Plugin: CopyWebpackPlugin
    // Description: Copy files and directories in webpack.
    //
    // Copies project static assets.
    //
    // See: https://www.npmjs.com/package/copy-webpack-plugin
    new CopyWebpackPlugin([{
      from: 'src/assets',
      to: 'assets'
    }]),

    // Plugin: HtmlWebpackPlugin
    // Description: Simplifies creation of HTML files to serve your webpack bundles.
    // This is especially useful for webpack bundles that include a hash in the filename
    // which changes every compilation.
    //
    // See: https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      template: 'src/index.html',
      chunksSortMode: helpers.packageSort(['polyfills', 'vendor', 'main'])
    }),

    // Plugin: DefinePlugin
    // Description: Define free variables.
    // Useful for having development builds with debug logging or adding global constants.
    //
    // Environment helpers
    //
    // See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
    // NOTE: when adding more properties make sure you include them in custom-typings.d.ts
    new webpack.DefinePlugin({
      'ENV': JSON.stringify(METADATA.ENV),
      'HMR': HMR
    })

  ],

  // Include polyfills or mocks for various node stuff
  // Description: Node configuration
  //
  // See: https://webpack.github.io/docs/configuration.html#node
  node: {
    global: 'window',
    crypto: 'empty',
    module: false,
    clearImmediate: false,
    setImmediate: false
  }
};
<|endoftext|>


<commit_before>const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

// const version = process.env.npm_package_version;

module.exports = function (options) {
  return {
    entry: {
      app: ['./src/app.ts', './src/app.scss'],
      background: './src/background.ts'
    },
    resolve: {
      extensions: ['.ts', '.js', '.json']
    },
    output: {
      publicPath: '.',
      path: path.resolve(__dirname, '../dist'),
      filename: '[name].[contenthash].bundle.js',
      libraryTarget: 'umd'
    },
    module: {
      rules: [
        {
          test: /\.ts$/,
          loader: 'awesome-typescript-loader'
        },
        {
          test: /\.s?css$/,
          use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
        }
      ]
    },
    plugins: [
      // new webpack.ProvidePlugin({
      //   Promise: 'es6-promise',
      //   fetch: 'exports-loader?self.fetch!whatwg-fetch/dist/fetch.umd',
      // }),
      new MiniCssExtractPlugin({
        filename: '[name].css',
        chunkFilename: '[id].css'
      }),
      new CopyPlugin({
        patterns: [
          // {
          //   from: 'src/manifest-common.json',
          //   to: 'manifest.json',
          //   transform: function (content, path) {
          //     var manifest = JSON.parse(content.toString());
          //     manifest.version = version;
          //     return JSON.stringify(manifest, null, 2);
          //   }
          // },
          { from: 'src/_locales/', to: '_locales' },
          { from: 'src/images/', to: 'images' }
        ]
      })
    ]
  };
};
<commit_msg>fix(build): do not use random hash to match manifest<commit_after>const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

// const version = process.env.npm_package_version;

module.exports = function (options) {
  return {
    entry: {
      app: ['./src/app.ts', './src/app.scss'],
      background: './src/background.ts'
    },
    resolve: {
      extensions: ['.ts', '.js', '.json']
    },
    output: {
      publicPath: '.',
      path: path.resolve(__dirname, '../dist'),
      filename: '[name].bundle.js',
      libraryTarget: 'umd'
    },
    module: {
      rules: [
        {
          test: /\.ts$/,
          loader: 'awesome-typescript-loader'
        },
        {
          test: /\.s?css$/,
          use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
        }
      ]
    },
    plugins: [
      // new webpack.ProvidePlugin({
      //   Promise: 'es6-promise',
      //   fetch: 'exports-loader?self.fetch!whatwg-fetch/dist/fetch.umd',
      // }),
      new MiniCssExtractPlugin({
        filename: '[name].css',
        chunkFilename: '[id].css'
      }),
      new CopyPlugin({
        patterns: [
          // {
          //   from: 'src/manifest-common.json',
          //   to: 'manifest.json',
          //   transform: function (content, path) {
          //     var manifest = JSON.parse(content.toString());
          //     manifest.version = version;
          //     return JSON.stringify(manifest, null, 2);
          //   }
          // },
          { from: 'src/_locales/', to: '_locales' },
          { from: 'src/images/', to: 'images' }
        ]
      })
    ]
  };
};
<|endoftext|>


<commit_before>function Network() {
    // To server functions and constants
    function sendGameRequest(numPlayers) {
        var message = {"NumPlayers": numPlayers}
        sendMessage(NEW_GAME_CMD, message)
    }

    function sendClientInfo(playerId) {
        var message = {"Id": playerId}
        sendMessage(CLIENT_INFO_CMD, message);
    }

    function sendViewWorld() {
        sendMessage(VIEW_WORLD_CMD, {});
    }

    function sendUnitMove(unit, move) {
        var message = {move: []};
        for (var i = 0; i < move.length; i++) {
            message.move.push(move[i].position);
        };

        sendMessage(MOVE_UNIT_CMD, message);
    }

    CLIENT_INFO_CMD = "clientInfo";
    NEW_GAME_CMD = "newGame";
    VIEW_WORLD_CMD = "view";
    MOVE_UNIT_CMD = "move";

    host = window.location.host.split(":")[0];
    port = getPortNum();
    ws_addr = "ws://" + host + ":" + port + "/ws";
    conn = new WebSocket(ws_addr);
    DELIM = ":";

    // This function expects the message as a javascript object
    function sendMessage(command, messageObj) {
        var jsonified = JSON.stringify(messageObj)
        packet = command + DELIM + jsonified;
        conn.send(packet)
    }

    // From server functions and constants
    this.packetHandlers = {
        "view": parseViewWorld.bind(this),
        "clientinfo": parseClientInfo.bind(this),
        "new": parseGameRequestSuccess.bind(this),
        "move": parseMoveResponse.bind(this)
    }

    function parseViewWorld(status, viewWorld) {
        var terrain = viewWorld.terrain;
        if (game.world == null) {
            // TODO check if the terrain actually exists first
            game.world = new World(terrain.length, terrain[0].length);
            game.currentState = "CAMERA_CONTROL";
        }
        for (var x = 0; x < terrain.length; x++) {
            for (var y = 0; y < terrain[x].length; y++) {
                // TODO terrain cells may someday be the actual JSON
                terrain[x][y] = terrainLookup(terrain[x][y], x, y);
            }
        }
        game.world.initialize(terrain);

        var units = viewWorld.units;
        for (var i = units.length - 1; i >= 0; i--) {
            // this should be tank, but I've only got wizards right now
            // not sent movementType right now
            var unit = units[i];
            var position = unit.position;
            var movement = unit.movement;
            var unitnation = parseInt(unit.nation) + unit.name;
            var spriteName = UnitNationSprite[unitnation];
            if (!game.world.findUnit(position.x, position.y)) {
                game.world.addUnit(unit.nation, spriteName, position,
                                   unit.distance, movement.name,
                                   movement.speeds, unit.health,
                                   unit.nation, unit.name);
            } else {
                console.log("Verifing the unit could be useful here");
            }
        }
    }

    function parseClientInfo(status) {
        console.log("Your client info has been received, sending game request");
        this.sendGameRequest(parseInt(desiredPlayers));
    }

    function parseGameRequestSuccess(status) {
        console.log("Congratulations, you've been matched to a game!");
        this.sendViewWorld();
    }

    function parseMoveResponse(status) {
        if (status == "success") {
            var unit = unitControlState.unit;
            var path = unitControlState.path;
            if (path) {
                // tell the renderer about the move
                var unitSprite = assets.spriteManager.getSprite(unit.spriteName);
                // unitSprite.movements = unitSprite.movements.concat(translatePathToMoves(path));
                var goal = path[path.length - 1];
                unit.pos.x = goal.position.x;
                unit.pos.y = goal.position.y;
                // shim, while the mac tab crash bug is still happening
                unitSprite.drawPos = goal.position;
                unitControlState.reset();
            } else {
                console.log("Your path is null, man");
            }
        } else {
            console.log("Go a bad status from server:", status);
        }
    }

    conn.onopen = function () {
        this.sendClientInfo(getPlayerId());
    }.bind(this);

    // Log errors
    conn.onerror = function (error) {
        console.log('WebSocket Error ' + error);
    };

    // Log messages from the server
    conn.onmessage = function (e) {
        var cmds = trimSocketChars(e.data.actualSplit(DELIM, 3));
        if (cmds.length >= 2) {
            var pkt_type = cmds[0];
            var status = cmds[1];
            var dataObj;
            if (status != "failure") {
                if (cmds.length > 2) {
                    dataObj = JSON.parse(cmds[2]);
                }
                var handler = this.packetHandlers[pkt_type];
                if (handler != null) {
                    handler(status, dataObj);
                } else {
                    console.log("Recieved unknown command:", pkt_type);
                }
            } else {
                console.log("Received failure from server:", cmds);
            }
        } else {
            console.log("Received malformed command:", cmds);
        }
    }.bind(this);

    this.sendGameRequest = function(numPlayers) {
        sendGameRequest(numPlayers);
    }

    this.sendClientInfo = function(playerId) {
        sendClientInfo(playerId);
    }

    this.sendViewWorld = function() {
        sendViewWorld();
    }

    this.sendUnitMove = function(unit, move) {
        sendUnitMove(unit, move);
    }
}

function trimSocketChars(cmds) {
    cmds[cmds.length - 1] = cmds[cmds.length - 1].replace(/\x00/gi, "");
    return cmds;
}

String.prototype.actualSplit = function(sep, maxsplit) {
    var split = this.split(sep);
    var excess = split.slice(maxsplit - 1, split.length).join(":");
    if (excess.length > 0) {
        return maxsplit ? split.slice(0, maxsplit - 1).concat(excess) : split;
    } else {
        return maxsplit ? split.slice(0, maxsplit - 1) : split;
    }
}
<commit_msg>Compare and log disparities in viewWorld template<commit_after>function Network() {
    // To server functions and constants
    function sendGameRequest(numPlayers) {
        var message = {"NumPlayers": numPlayers}
        sendMessage(NEW_GAME_CMD, message)
    }

    function sendClientInfo(playerId) {
        var message = {"Id": playerId}
        sendMessage(CLIENT_INFO_CMD, message);
    }

    function sendViewWorld() {
        sendMessage(VIEW_WORLD_CMD, {});
    }

    function sendUnitMove(unit, move) {
        var message = {move: []};
        for (var i = 0; i < move.length; i++) {
            message.move.push(move[i].position);
        };

        sendMessage(MOVE_UNIT_CMD, message);
    }

    CLIENT_INFO_CMD = "clientInfo";
    NEW_GAME_CMD = "newGame";
    VIEW_WORLD_CMD = "view";
    MOVE_UNIT_CMD = "move";

    host = window.location.host.split(":")[0];
    port = getPortNum();
    ws_addr = "ws://" + host + ":" + port + "/ws";
    conn = new WebSocket(ws_addr);
    DELIM = ":";

    // This function expects the message as a javascript object
    function sendMessage(command, messageObj) {
        var jsonified = JSON.stringify(messageObj)
        packet = command + DELIM + jsonified;
        conn.send(packet)
    }

    // From server functions and constants
    this.packetHandlers = {
        "view": parseViewWorld.bind(this),
        "clientinfo": parseClientInfo.bind(this),
        "new": parseGameRequestSuccess.bind(this),
        "move": parseMoveResponse.bind(this)
    }

    function logTemplateComp(name, realResponse) {
        if (!verifyStructure(responseTemplates[name], realResponse)) {
            console.log("The", name, "template does not match. Proceed with caution");
        }
    }

    function parseViewWorld(status, viewWorld) {
        this.logTemplateComp("viewWorld", viewWorld);
        var terrain = viewWorld.terrain;
        if (game.world == null) {
            // TODO check if the terrain actually exists first
            game.world = new World(terrain.length, terrain[0].length);
            game.currentState = "CAMERA_CONTROL";
        }
        for (var x = 0; x < terrain.length; x++) {
            for (var y = 0; y < terrain[x].length; y++) {
                // TODO terrain cells may someday be the actual JSON
                terrain[x][y] = terrainLookup(terrain[x][y], x, y);
            }
        }
        game.world.initialize(terrain);

        var units = viewWorld.units;
        for (var i = units.length - 1; i >= 0; i--) {
            // this should be tank, but I've only got wizards right now
            // not sent movementType right now
            var unit = units[i];
            var position = unit.position;
            var movement = unit.movement;
            var unitnation = parseInt(unit.nation) + unit.name;
            var spriteName = UnitNationSprite[unitnation];
            if (!game.world.findUnit(position.x, position.y)) {
                game.world.addUnit(unit.nation, spriteName, position,
                                   unit.distance, movement.name,
                                   movement.speeds, unit.health,
                                   unit.nation, unit.name);
            } else {
                console.log("Verifing the unit could be useful here");
            }
        }
    }

    function parseClientInfo(status) {
        console.log("Your client info has been received, sending game request");
        this.sendGameRequest(parseInt(desiredPlayers));
    }

    function parseGameRequestSuccess(status) {
        console.log("Congratulations, you've been matched to a game!");
        this.sendViewWorld();
    }

    function parseMoveResponse(status) {
        if (status == "success") {
            var unit = unitControlState.unit;
            var path = unitControlState.path;
            if (path) {
                // tell the renderer about the move
                var unitSprite = assets.spriteManager.getSprite(unit.spriteName);
                // unitSprite.movements = unitSprite.movements.concat(translatePathToMoves(path));
                var goal = path[path.length - 1];
                unit.pos.x = goal.position.x;
                unit.pos.y = goal.position.y;
                // shim, while the mac tab crash bug is still happening
                unitSprite.drawPos = goal.position;
                unitControlState.reset();
            } else {
                console.log("Your path is null, man");
            }
        } else {
            console.log("Go a bad status from server:", status);
        }
    }

    conn.onopen = function () {
        this.sendClientInfo(getPlayerId());
    }.bind(this);

    // Log errors
    conn.onerror = function (error) {
        console.log('WebSocket Error ' + error);
    };

    // Log messages from the server
    conn.onmessage = function (e) {
        var cmds = trimSocketChars(e.data.actualSplit(DELIM, 3));
        if (cmds.length >= 2) {
            var pkt_type = cmds[0];
            var status = cmds[1];
            var dataObj;
            if (status != "failure") {
                if (cmds.length > 2) {
                    dataObj = JSON.parse(cmds[2]);
                }
                var handler = this.packetHandlers[pkt_type];
                if (handler != null) {
                    handler(status, dataObj);
                } else {
                    console.log("Recieved unknown command:", pkt_type);
                }
            } else {
                console.log("Received failure from server:", cmds);
            }
        } else {
            console.log("Received malformed command:", cmds);
        }
    }.bind(this);

    this.sendGameRequest = function(numPlayers) {
        sendGameRequest(numPlayers);
    }

    this.sendClientInfo = function(playerId) {
        sendClientInfo(playerId);
    }

    this.sendViewWorld = function() {
        sendViewWorld();
    }

    this.sendUnitMove = function(unit, move) {
        sendUnitMove(unit, move);
    }

    this.logTemplateComp = function(name, realResponse) {
        logTemplateComp(name, realResponse);
    }
}

function trimSocketChars(cmds) {
    cmds[cmds.length - 1] = cmds[cmds.length - 1].replace(/\x00/gi, "");
    return cmds;
}

String.prototype.actualSplit = function(sep, maxsplit) {
    var split = this.split(sep);
    var excess = split.slice(maxsplit - 1, split.length).join(":");
    if (excess.length > 0) {
        return maxsplit ? split.slice(0, maxsplit - 1).concat(excess) : split;
    } else {
        return maxsplit ? split.slice(0, maxsplit - 1) : split;
    }
}
<|endoftext|>


<commit_before>/**
 * @author: @AngularClass
 */

const webpack = require('webpack');
const helpers = require('./helpers');

/*
 * Webpack Plugins
 */
// problem with copy-webpack-plugin
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;
const HtmlElementsPlugin = require('./html-elements-plugin');
const AssetsPlugin = require('assets-webpack-plugin');
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');

/*
 * Webpack Constants
 */
const HMR = helpers.hasProcessFlag('hot');
const METADATA = {
  title: 'Angular2 Webpack Starter by @gdi2290 from @AngularClass',
  baseUrl: '/',
  isDevServer: helpers.isWebpackDevServer()
};

/*
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = function(options) {
  isProd = options.env === 'production';
  return {

    /*
     * Static metadata for index.html
     *
     * See: (custom attribute)
     */
    metadata: METADATA,

    /*
     * Cache generated modules and chunks to improve performance for multiple incremental builds.
     * This is enabled by default in watch mode.
     * You can pass false to disable it.
     *
     * See: http://webpack.github.io/docs/configuration.html#cache
     */
     //cache: false,

    /*
     * The entry point for the bundle
     * Our Angular.js app
     *
     * See: http://webpack.github.io/docs/configuration.html#entry
     */
    entry: {

      'polyfills': './src/polyfills.browser.ts',
      'vendor':    './src/vendor.browser.ts',
      'main':      './src/main.browser.ts'

    },

    /*
     * Options affecting the resolving of modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#resolve
     */
    resolve: {

      /*
       * An array of extensions that should be used to resolve modules.
       *
       * See: http://webpack.github.io/docs/configuration.html#resolve-extensions
       */
      extensions: ['', '.ts', '.js', '.json'],

      // An array of directory names to be resolved to the current directory
      modules: [helpers.root('src'), 'node_modules'],

    },

    /*
     * Options affecting the normal modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#module
     */
    module: {

      /*
       * An array of applied pre and post loaders.
       *
       * See: http://webpack.github.io/docs/configuration.html#module-preloaders-module-postloaders
       */
      preLoaders: [
        {
          test: /\.ts$/,
          loader: 'string-replace-loader',
          query: {
            search: '(System|SystemJS)(.*[\\n\\r]\\s*\\.|\\.)import\\((.+)\\)',
            replace: '$1.import($3).then(mod => (mod.__esModule && mod.default) ? mod.default : mod)',
            flags: 'g'
          },
          include: [helpers.root('src')]
        },

      ],

      /*
       * An array of automatically applied loaders.
       *
       * IMPORTANT: The loaders here are resolved relative to the resource which they are applied to.
       * This means they are not resolved relative to the configuration file.
       *
       * See: http://webpack.github.io/docs/configuration.html#module-loaders
       */
      loaders: [

        /*
         * Typescript loader support for .ts and Angular 2 async routes via .async.ts
         * Replace templateUrl and stylesUrl with require()
         *
         * See: https://github.com/s-panferov/awesome-typescript-loader
         * See: https://github.com/TheLarkInn/angular2-template-loader
         */
        {
          test: /\.ts$/,
          loaders: [
            '@angularclass/hmr-loader?pretty=' + !isProd + '&prod=' + isProd,
            'awesome-typescript-loader',
            'angular2-template-loader'
          ],
          exclude: [/\.(spec|e2e)\.ts$/]
        },

        /*
         * Json loader support for *.json files.
         *
         * See: https://github.com/webpack/json-loader
         */
        {
          test: /\.json$/,
          loader: 'json-loader'
        },

        /*
         * to string and css loader support for *.css files
         * Returns file content as string
         *
         */
        {
          test: /\.css$/,
          loaders: ['to-string-loader', 'css-loader']
        },

        /* Raw loader support for *.html
         * Returns file content as string
         *
         * See: https://github.com/webpack/raw-loader
         */
        {
          test: /\.html$/,
          loader: 'raw-loader',
          exclude: [helpers.root('src/index.html')]
        },

        /* File loader for supporting images, for example, in CSS files.
        */
        {
          test: /\.(jpg|png|gif)$/,
          loader: 'file'
        }
      ],

      postLoaders: [
        {
          test: /\.js$/,
          loader: 'string-replace-loader',
          query: {
            search: 'var sourceMappingUrl = extractSourceMappingUrl\\(cssText\\);',
            replace: 'var sourceMappingUrl = "";',
            flags: 'g'
          }
        }
      ]
    },

    /*
     * Add additional plugins to the compiler.
     *
     * See: http://webpack.github.io/docs/configuration.html#plugins
     */
    plugins: [
      new AssetsPlugin({
        path: helpers.root('dist'),
        filename: 'webpack-assets.json',
        prettyPrint: true
      }),

      /*
       * Plugin: ForkCheckerPlugin
       * Description: Do type checking in a separate process, so webpack don't need to wait.
       *
       * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
       */
      new ForkCheckerPlugin(),
      /*
       * Plugin: CommonsChunkPlugin
       * Description: Shares common code between the pages.
       * It identifies common modules and put them into a commons chunk.
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
       * See: https://github.com/webpack/docs/wiki/optimization#multi-page-app
       */
      new webpack.optimize.CommonsChunkPlugin({
        name: ['polyfills', 'vendor'].reverse()
      }),

      /**
       * Plugin: ContextReplacementPlugin
       * Description: Provides context to Angular's use of System.import
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#contextreplacementplugin
       * See: https://github.com/angular/angular/issues/11580
       */
      new ContextReplacementPlugin(
        // The (\\|\/) piece accounts for path separators in *nix and Windows
        /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
        helpers.root('src') // location of your src
      ),

      /*
       * Plugin: CopyWebpackPlugin
       * Description: Copy files and directories in webpack.
       *
       * Copies project static assets.
       *
       * See: https://www.npmjs.com/package/copy-webpack-plugin
       */
      new CopyWebpackPlugin([{
        from: 'src/assets',
        to: 'assets'
      }]),

      /*
       * Plugin: HtmlWebpackPlugin
       * Description: Simplifies creation of HTML files to serve your webpack bundles.
       * This is especially useful for webpack bundles that include a hash in the filename
       * which changes every compilation.
       *
       * See: https://github.com/ampedandwired/html-webpack-plugin
       */
      new HtmlWebpackPlugin({
        template: 'src/index.html',
        chunksSortMode: 'dependency'
      }),

      /*
       * Plugin: HtmlHeadConfigPlugin
       * Description: Generate html tags based on javascript maps.
       *
       * If a publicPath is set in the webpack output configuration, it will be automatically added to
       * href attributes, you can disable that by adding a "=href": false property.
       * You can also enable it to other attribute by settings "=attName": true.
       *
       * The configuration supplied is map between a location (key) and an element definition object (value)
       * The location (key) is then exported to the template under then htmlElements property in webpack configuration.
       *
       * Example:
       *  Adding this plugin configuration
       *  new HtmlElementsPlugin({
       *    headTags: { ... }
       *  })
       *
       *  Means we can use it in the template like this:
       *  <%= webpackConfig.htmlElements.headTags %>
       *
       * Dependencies: HtmlWebpackPlugin
       */
      new HtmlElementsPlugin({
        headTags: require('./head-config.common')
      }),

    ],

    /*
     * Include polyfills or mocks for various node stuff
     * Description: Node configuration
     *
     * See: https://webpack.github.io/docs/configuration.html#node
     */
    node: {
      global: 'window',
      crypto: 'empty',
      process: true,
      module: false,
      clearImmediate: false,
      setImmediate: false
    }

  };
}
<commit_msg>update base<commit_after>/**
 * @author: @AngularClass
 */

const webpack = require('webpack');
const helpers = require('./helpers');

/*
 * Webpack Plugins
 */
// problem with copy-webpack-plugin
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;
const HtmlElementsPlugin = require('./html-elements-plugin');
const AssetsPlugin = require('assets-webpack-plugin');
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');

/*
 * Webpack Constants
 */
const HMR = helpers.hasProcessFlag('hot');
const METADATA = {
  title: 'Angular2 Webpack Starter by @gdi2290 from @AngularClass',
  baseUrl: '/',
  isDevServer: helpers.isWebpackDevServer()
};

/*
 * Webpack configuration
 *
 * See: http://webpack.github.io/docs/configuration.html#cli
 */
module.exports = function(options) {
  isProd = options.env === 'production';
  return {

    /*
     * Static metadata for index.html
     *
     * See: (custom attribute)
     */
    metadata: METADATA,

    /*
     * Cache generated modules and chunks to improve performance for multiple incremental builds.
     * This is enabled by default in watch mode.
     * You can pass false to disable it.
     *
     * See: http://webpack.github.io/docs/configuration.html#cache
     */
     //cache: false,

    /*
     * The entry point for the bundle
     * Our Angular.js app
     *
     * See: http://webpack.github.io/docs/configuration.html#entry
     */
    entry: {

      'polyfills': './src/polyfills.browser.ts',
      'vendor':    './src/vendor.browser.ts',
      'main':      './src/main.browser.ts'

    },

    /*
     * Options affecting the resolving of modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#resolve
     */
    resolve: {

      /*
       * An array of extensions that should be used to resolve modules.
       *
       * See: http://webpack.github.io/docs/configuration.html#resolve-extensions
       */
      extensions: ['', '.ts', '.js', '.json'],

      // An array of directory names to be resolved to the current directory
      modules: [helpers.root('src'), 'node_modules'],

    },

    /*
     * Options affecting the normal modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#module
     */
    module: {

      /*
       * An array of applied pre and post loaders.
       *
       * See: http://webpack.github.io/docs/configuration.html#module-preloaders-module-postloaders
       */
      preLoaders: [
        {
          test: /\.ts$/,
          loader: 'string-replace-loader',
          query: {
            search: '(System|SystemJS)(.*[\\n\\r]\\s*\\.|\\.)import\\((.+)\\)',
            replace: '$1.import($3).then(mod => (mod.__esModule && mod.default) ? mod.default : mod)',
            flags: 'g'
          },
          include: [helpers.root('src')]
        },

      ],

      /*
       * An array of automatically applied loaders.
       *
       * IMPORTANT: The loaders here are resolved relative to the resource which they are applied to.
       * This means they are not resolved relative to the configuration file.
       *
       * See: http://webpack.github.io/docs/configuration.html#module-loaders
       */
      loaders: [

        /*
         * Typescript loader support for .ts and Angular 2 async routes via .async.ts
         * Replace templateUrl and stylesUrl with require()
         *
         * See: https://github.com/s-panferov/awesome-typescript-loader
         * See: https://github.com/TheLarkInn/angular2-template-loader
         */
        {
          test: /\.ts$/,
          loaders: [
            '@angularclass/hmr-loader?pretty=' + !isProd + '&prod=' + isProd,
            'awesome-typescript-loader',
            'angular2-template-loader'
          ],
          exclude: [/\.(spec|e2e)\.ts$/]
        },

        /*
         * Json loader support for *.json files.
         *
         * See: https://github.com/webpack/json-loader
         */
        {
          test: /\.json$/,
          loader: 'json-loader'
        },

        /*
         * to string and css loader support for *.css files
         * Returns file content as string
         *
         */
        {
          test: /\.css$/,
          loaders: ['to-string-loader', 'css-loader']
        },

        /* Raw loader support for *.html
         * Returns file content as string
         *
         * See: https://github.com/webpack/raw-loader
         */
        {
          test: /\.html$/,
          loader: 'raw-loader',
          exclude: [helpers.root('src/index.html')]
        },

        /* File loader for supporting images, for example, in CSS files.
        */
        {
          test: /\.(jpg|png|gif)$/,
          loader: 'file'
        }
      ],

      postLoaders: [
        {
          test: /\.js$/,
          loader: 'string-replace-loader',
          query: {
            search: 'var sourceMappingUrl = extractSourceMappingUrl\\(cssText\\);',
            replace: 'var sourceMappingUrl = "";',
            flags: 'g'
          }
        }
      ]
    },

    /*
     * Add additional plugins to the compiler.
     *
     * See: http://webpack.github.io/docs/configuration.html#plugins
     */
    plugins: [
      new AssetsPlugin({
        path: helpers.root('dist'),
        filename: 'webpack-assets.json',
        prettyPrint: true
      }),

      /*
       * Plugin: ForkCheckerPlugin
       * Description: Do type checking in a separate process, so webpack don't need to wait.
       *
       * See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
       */
      new ForkCheckerPlugin(),
      /*
       * Plugin: CommonsChunkPlugin
       * Description: Shares common code between the pages.
       * It identifies common modules and put them into a commons chunk.
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
       * See: https://github.com/webpack/docs/wiki/optimization#multi-page-app
       */
      new webpack.optimize.CommonsChunkPlugin({
        name: ['polyfills', 'vendor'].reverse()
      }),

      /**
       * Plugin: ContextReplacementPlugin
       * Description: Provides context to Angular's use of System.import
       *
       * See: https://webpack.github.io/docs/list-of-plugins.html#contextreplacementplugin
       * See: https://github.com/angular/angular/issues/11580
       */
      new ContextReplacementPlugin(
        // The (\\|\/) piece accounts for path separators in *nix and Windows
        /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
        helpers.root('src') // location of your src
      ),

      /*
       * Plugin: CopyWebpackPlugin
       * Description: Copy files and directories in webpack.
       *
       * Copies project static assets.
       *
       * See: https://www.npmjs.com/package/copy-webpack-plugin
       */
      new CopyWebpackPlugin([{
        from: 'src/assets',
        to: 'assets'
      }], {
        ignore: [
          'humans.txt',
          'robots.txt'
        ]
      }),
      new CopyWebpackPlugin([{
        from: 'src/assets/robots.txt'
      }, {
        from: 'src/assets/humans.txt'
      }]),

      /*
       * Plugin: HtmlWebpackPlugin
       * Description: Simplifies creation of HTML files to serve your webpack bundles.
       * This is especially useful for webpack bundles that include a hash in the filename
       * which changes every compilation.
       *
       * See: https://github.com/ampedandwired/html-webpack-plugin
       */
      new HtmlWebpackPlugin({
        template: 'src/index.html',
        chunksSortMode: 'dependency'
      }),

      /*
       * Plugin: HtmlHeadConfigPlugin
       * Description: Generate html tags based on javascript maps.
       *
       * If a publicPath is set in the webpack output configuration, it will be automatically added to
       * href attributes, you can disable that by adding a "=href": false property.
       * You can also enable it to other attribute by settings "=attName": true.
       *
       * The configuration supplied is map between a location (key) and an element definition object (value)
       * The location (key) is then exported to the template under then htmlElements property in webpack configuration.
       *
       * Example:
       *  Adding this plugin configuration
       *  new HtmlElementsPlugin({
       *    headTags: { ... }
       *  })
       *
       *  Means we can use it in the template like this:
       *  <%= webpackConfig.htmlElements.headTags %>
       *
       * Dependencies: HtmlWebpackPlugin
       */
      new HtmlElementsPlugin({
        headTags: require('./head-config.common')
      }),

    ],

    /*
     * Include polyfills or mocks for various node stuff
     * Description: Node configuration
     *
     * See: https://webpack.github.io/docs/configuration.html#node
     */
    node: {
      global: 'window',
      crypto: 'empty',
      process: true,
      module: false,
      clearImmediate: false,
      setImmediate: false
    }

  };
}
<|endoftext|>


<commit_before>// This is particular to the sequence below:
// - Colliding bunch crossings
// - Zoom into position inside detector
// - Rotate around, turning off tracks halfway through rotation
// It will be nice to generalize all this but it's good-enough for now.
// This is reaching the limit of complexity with this setup. Use key frames!

ispy.animation_script = {
    "collision": {
      "proton1": {
        "pi" : {x:0, y:0, z:200.0},
        "pf" : {x:0, y:0, z:-200.0}
      },
      "proton2": {
        "pi": {x:0, y:0, z:-200.0},
        "pf": {x:0, y:0, z:200.0}
      },
      "time": 2500,
      "objects": [
        {"group":"Tracking", "key":"Tracks_V2"},
        {"group":"ECAL", "key":"EBRecHits_V2"},
        {"group":"ECAL", "key":"EERecHits_V2"},
        {"group":"HCAL", "key":"HBRecHits_V2"},
        {"group":"HCAL", "key":"HERecHits_V2"}
      ]
    },
    "zoom": {
      "time": 2000
    },
    // This rotation is actually split into two halves and the toggle
    // on objects happens at PI
    "rotation": {
      "radius": 2.0,
      "angle": 2*Math.PI,
      "nsteps": 24,
      "time": 5000,
      "objects": [
        {"group":"Tracking", "key":"Tracks_V2"},
        {"group":"HCAL", "key":"HBRecHits_V2"},
        {"group":"HCAL", "key":"HERecHits_V2"},
        {"group":"PhysicsObjects", "key":"GsfElectrons_V1"}
      ]
    }
}

ispy.toggleAnimation = function() {
  ispy.animating = !ispy.animating;

  $('#animate').toggleClass('active');

  if ( ispy.animating ) {
    var animation = ispy.animation_script;

    var length = ispy.camera.position.length();
    var xs = [ispy.camera.position.x, 0];
    var ys = [0, 0];
    var zs = [ispy.camera.position.z, length];

    var tw1 = new TWEEN.Tween(ispy.camera.position)
      .to({x:xs, y:ys, z:zs}, animation.zoom.time)
      .easing(TWEEN.Easing.Sinusoidal.In);

    var r = animation.rotation.radius;

    var tw2 = new TWEEN.Tween(ispy.camera.position)
      .to({x:0, y:0, z:r}, animation.zoom.time)
      .easing(TWEEN.Easing.Sinusoidal.In);

    var ns = animation.rotation.nsteps;
    var s = animation.rotation.angle/ns;
    var cx = [];
    var cy = [];
    var cz = [];
    for ( var i = 1; i <= ns; i++ ) {
      cx.push(r*Math.sin(s*i));
      cy.push(0.0);
      cz.push(r*Math.cos(s*i));
    }

    var bs = 0;
    var es = ns/2;

    var c1x = cx.slice(0,es);
    var c1y = cy.slice(0,es);
    var c1z = cz.slice(0,es);

    var tw3 = new TWEEN.Tween(ispy.camera.position)
      .to({x:c1x, y:c1y, z:c1z}, animation.rotation.time);

    // Split the rotation in half and
    // turn off tracks and turn on electrons

    bs = ns/2 + 1;
    es = ns;

    var c2x = cx.slice(bs, es);
    var c2y = cy.slice(bs, es);
    var c2z = cz.slice(bs, es);

    var tw4 = new TWEEN.Tween(ispy.camera.position)
      .to({x:c2x, y:c2y, z:c2z}, animation.rotation.time)
      .onStart(function(){
        animation.rotation.objects.forEach(function(o) {
          ispy.toggle(o.group, o.key);
        });
      });

    var pgeometry = new THREE.SphereGeometry(0.25,32,32);
    var pmaterial = new THREE.MeshBasicMaterial({color: 0xffff00});

    var proton1 = new THREE.Mesh(pgeometry, pmaterial);
    proton1.position.x = animation.collision.proton1.pi.x;
    proton1.position.y = animation.collision.proton1.pi.y;
    proton1.position.z = animation.collision.proton1.pi.z;

    var proton2 = new THREE.Mesh(pgeometry, pmaterial);
    proton2.position.x = animation.collision.proton2.pi.x;
    proton2.position.y = animation.collision.proton2.pi.y;
    proton2.position.z = animation.collision.proton2.pi.z;

    ispy.scene.add(proton1);
    ispy.scene.add(proton2);

    var c1 = new TWEEN.Tween(proton1.position)
      .to({z:0.0}, animation.collision.time)
      .easing(TWEEN.Easing.Back.In);

    var c2 = new TWEEN.Tween(proton2.position)
      .to({z:0.0}, animation.collision.time)
      .onComplete(function(){
        tw1.start();
        animation.collision.objects.forEach(function(o) {
          ispy.toggle(o.group, o.key);
        });
      })
      .easing(TWEEN.Easing.Back.In);

    var c3 = new TWEEN.Tween(proton1.position)
      .to({z:animation.collision.proton1.pf.z}, animation.collision.time)
      .onComplete(function(){
        ispy.scene.remove(proton1);
      }).easing(TWEEN.Easing.Back.Out);

    var c4 = new TWEEN.Tween(proton2.position)
      .to({z:animation.collision.proton2.pf.z}, animation.collision.time)
      .onComplete(function(){
        ispy.scene.remove(proton2);
      }).easing(TWEEN.Easing.Back.Out);

    c1.chain(c3);
    c2.chain(c4);

    tw1.chain(tw2);
    tw2.chain(tw3);
    tw3.chain(tw4);

    c1.start();
    c2.start();
  }
}
<commit_msg>return to home at end of animation sequence<commit_after>// This is particular to the sequence below:
// - Colliding bunch crossings
// - Zoom into position inside detector
// - Rotate around, turning off tracks halfway through rotation
// It will be nice to generalize all this but it's good-enough for now.
// This is reaching the limit of complexity with this setup. Use key frames!

ispy.animation_script = {
    "collision": {
      "proton1": {
        "pi" : {x:0, y:0, z:200.0},
        "pf" : {x:0, y:0, z:-200.0}
      },
      "proton2": {
        "pi": {x:0, y:0, z:-200.0},
        "pf": {x:0, y:0, z:200.0}
      },
      "time": 2500,
      "objects": [
        {"group":"Tracking", "key":"Tracks_V2"},
        {"group":"ECAL", "key":"EBRecHits_V2"},
        {"group":"ECAL", "key":"EERecHits_V2"},
        {"group":"HCAL", "key":"HBRecHits_V2"},
        {"group":"HCAL", "key":"HERecHits_V2"}
      ]
    },
    "zoom": {
      "time": 2000
    },
    // This rotation is actually split into two halves and the toggle
    // on objects happens at PI
    "rotation": {
      "radius": 2.0,
      "angle": 2*Math.PI,
      "nsteps": 24,
      "time": 5000,
      "objects": [
        {"group":"Tracking", "key":"Tracks_V2"},
        {"group":"HCAL", "key":"HBRecHits_V2"},
        {"group":"HCAL", "key":"HERecHits_V2"},
        {"group":"PhysicsObjects", "key":"GsfElectrons_V1"}
      ]
    }
}

ispy.toggleAnimation = function() {
  ispy.animating = !ispy.animating;

  $('#animate').toggleClass('active');

  if ( ispy.animating ) {
    var animation = ispy.animation_script;
    var home = ispy.camera.position;

    var length = ispy.camera.position.length();
    var xs = [ispy.camera.position.x, 0];
    var ys = [0, 0];
    var zs = [ispy.camera.position.z, length];

    var tw1 = new TWEEN.Tween(ispy.camera.position)
      .to({x:xs, y:ys, z:zs}, animation.zoom.time)
      .easing(TWEEN.Easing.Sinusoidal.In);

    var r = animation.rotation.radius;

    var tw2 = new TWEEN.Tween(ispy.camera.position)
      .to({x:0, y:0, z:r}, animation.zoom.time)
      .easing(TWEEN.Easing.Sinusoidal.In);

    var ns = animation.rotation.nsteps;
    var s = animation.rotation.angle/ns;
    var cx = [];
    var cy = [];
    var cz = [];
    for ( var i = 1; i <= ns; i++ ) {
      cx.push(r*Math.sin(s*i));
      cy.push(0.0);
      cz.push(r*Math.cos(s*i));
    }

    var bs = 0;
    var es = ns/2;

    var c1x = cx.slice(0,es);
    var c1y = cy.slice(0,es);
    var c1z = cz.slice(0,es);

    var tw3 = new TWEEN.Tween(ispy.camera.position)
      .to({x:c1x, y:c1y, z:c1z}, animation.rotation.time);

    // Split the rotation in half and
    // turn off tracks and turn on electrons

    bs = ns/2 + 1;
    es = ns;

    var c2x = cx.slice(bs, es);
    var c2y = cy.slice(bs, es);
    var c2z = cz.slice(bs, es);

    var tw4 = new TWEEN.Tween(ispy.camera.position)
      .to({x:c2x, y:c2y, z:c2z}, animation.rotation.time)
      .onStart(function(){
        animation.rotation.objects.forEach(function(o) {
          ispy.toggle(o.group, o.key);
        });
      });

    var tw5 = new TWEEN.Tween(ispy.camera.position)
      .to({x:home.x, y:home.y, z:home.z}, 5000)
      .easing(TWEEN.Easing.Sinusoidal.In);

    tw5.delay(1000);

    var pgeometry = new THREE.SphereGeometry(0.25,32,32);
    var pmaterial = new THREE.MeshBasicMaterial({color: 0xffff00});

    var proton1 = new THREE.Mesh(pgeometry, pmaterial);
    proton1.position.x = animation.collision.proton1.pi.x;
    proton1.position.y = animation.collision.proton1.pi.y;
    proton1.position.z = animation.collision.proton1.pi.z;

    var proton2 = new THREE.Mesh(pgeometry, pmaterial);
    proton2.position.x = animation.collision.proton2.pi.x;
    proton2.position.y = animation.collision.proton2.pi.y;
    proton2.position.z = animation.collision.proton2.pi.z;

    ispy.scene.add(proton1);
    ispy.scene.add(proton2);

    var c1 = new TWEEN.Tween(proton1.position)
      .to({z:0.0}, animation.collision.time)
      .easing(TWEEN.Easing.Back.In);

    var c2 = new TWEEN.Tween(proton2.position)
      .to({z:0.0}, animation.collision.time)
      .onComplete(function(){
        tw1.start();
        animation.collision.objects.forEach(function(o) {
          ispy.toggle(o.group, o.key);
        });
      })
      .easing(TWEEN.Easing.Back.In);

    var c3 = new TWEEN.Tween(proton1.position)
      .to({z:animation.collision.proton1.pf.z}, animation.collision.time)
      .onComplete(function(){
        ispy.scene.remove(proton1);
      }).easing(TWEEN.Easing.Back.Out);

    var c4 = new TWEEN.Tween(proton2.position)
      .to({z:animation.collision.proton2.pf.z}, animation.collision.time)
      .onComplete(function(){
        ispy.scene.remove(proton2);
      }).easing(TWEEN.Easing.Back.Out);

    c1.chain(c3);
    c2.chain(c4);

    tw1.chain(tw2);
    tw2.chain(tw3);
    tw3.chain(tw4);
    tw4.chain(tw5);

    c1.start();
    c2.start();
  }
}
<|endoftext|>