<commit_before>import {
  COLOR,
  BORDER_WIDTH,
  FONT_FAMILY,
  FONT_SIZE,
  FONT_WEIGHT,
  SPACING
} from "../../consts/types";

export default {
  // General
  "tabs.general.borderBottomColor": {
    type: COLOR,
    value: { ref: "colorScheme.baseColor" }
  },
  "tabs.general.borderBottomWidth": {
    type: BORDER_WIDTH,
    value: { ref: "basics.borderWidths.medium" }
  },
  "tabs.general.gutter": {
    type: SPACING,
    value: { ref: "density.spacings.extraSmall" }
  },

  // General - Tab
  "tabs.general.tab.fontFamily": {
    type: FONT_FAMILY,
    value: { ref: "basics.fontFamilies.main" }
  },
  "tabs.general.tab.fontSize": {
    type: FONT_SIZE,
    value: { ref: "density.fontSizes.medium" }
  },
  "tabs.general.tab.fontWeight": {
    type: FONT_WEIGHT,
    value: { ref: "basics.fontWeights.regular" }
  },

  // General - Tab - Selected
  "tabs.general.tab.selected.borderBottomColor": {
    type: COLOR,
    value: { ref: "colorScheme.accentColor" }
  },
  "tabs.general.tab.selected.borderBottomWidth": {
    type: BORDER_WIDTH,
    value: { ref: "basics.borderWidths.large" }
  },
  "tabs.general.tab.selected.fontWeight": {
    type: FONT_WEIGHT,
    value: { ref: "basics.fontWeights.bold" }
  },

  // General - Tab - Disabled
  "tabs.general.tab.disabled.fontColor": {
    type: COLOR,
    value: { ref: "colorScheme.textColor" },
    transform: { alpha: 0.5 }
  },

  // General - Tab - Hover
  "tabs.general.tab.hover.borderBottomColor": {
    type: COLOR,
    value: { ref: "colorScheme.baseColor" },
    transform: { alpha: 0.5 }
  },
  "tabs.general.tab.hover.borderBottomWidth": {
    type: BORDER_WIDTH,
    value: { ref: "basics.borderWidths.medium" }
  },

  // General - Tab - Focus
  "tabs.general.tab.focus.halo.color": {
    type: COLOR,
    value: { ref: "colorScheme.accentColor" },
    transform: { alpha: 0.5 }
  },
  "tabs.general.tab.focus.halo.width": {
    type: BORDER_WIDTH,
    value: { ref: "basics.borderWidths.large" }
  }
};
<commit_msg>feat: update Tab theme data<commit_after>import {
  COLOR,
  BORDER_WIDTH,
  FONT_FAMILY,
  FONT_SIZE,
  FONT_WEIGHT,
  SPACING
} from "../../consts/types";

export default {
  // General
  "tabs.general.borderBottomColor": {
    type: COLOR,
    value: { ref: "colorScheme.baseColor" },
    transform: { alpha: 0.1 }
  },
  "tabs.general.borderBottomWidth": {
    type: BORDER_WIDTH,
    value: { ref: "basics.borderWidths.small" }
  },
  "tabs.general.gutter": {
    type: SPACING,
    value: { ref: "density.spacings.extraSmall" }
  },

  // General - Tab
  "tabs.general.tab.fontFamily": {
    type: FONT_FAMILY,
    value: { ref: "basics.fontFamilies.main" }
  },
  "tabs.general.tab.fontSize": {
    type: FONT_SIZE,
    value: { ref: "typography.h3.fontSize" }
  },
  "tabs.general.tab.fontWeight": {
    type: FONT_WEIGHT,
    value: { ref: "basics.fontWeights.regular" }
  },

  // General - Tab - Selected
  "tabs.general.tab.selected.borderBottomColor": {
    type: COLOR,
    value: { ref: "colorScheme.accentColor" }
  },
  "tabs.general.tab.selected.borderBottomWidth": {
    type: BORDER_WIDTH,
    value: { ref: "basics.borderWidths.medium" }
  },
  "tabs.general.tab.selected.fontWeight": {
    type: FONT_WEIGHT,
    value: { ref: "basics.fontWeights.bold" }
  },

  // General - Tab - Disabled
  "tabs.general.tab.disabled.fontColor": {
    type: COLOR,
    value: { ref: "colorScheme.textColor" },
    transform: { alpha: 0.5 }
  },

  // General - Tab - Hover
  "tabs.general.tab.hover.borderBottomColor": {
    type: COLOR,
    value: { ref: "colorScheme.baseColor" },
    transform: { alpha: 0.5 }
  },
  "tabs.general.tab.hover.borderBottomWidth": {
    type: BORDER_WIDTH,
    value: { ref: "basics.borderWidths.medium" }
  },

  // General - Tab - Focus
  "tabs.general.tab.focus.halo.color": {
    type: COLOR,
    value: { ref: "colorScheme.accentColor" },
    transform: { alpha: 0.5 }
  },
  "tabs.general.tab.focus.halo.width": {
    type: BORDER_WIDTH,
    value: { ref: "basics.borderWidths.large" }
  }
};
<|endoftext|>


<commit_before>var statusElement;

var wsClient;

var Module = {
	preRun: [function() {
		Module.canvas = document.getElementById("canvas");
	}],
	postRun: [],
	print: function(text) {
		console.log(text);
	},
	printErr: function(text) {
		console.error(text);
	},
	setStatus: function(text) {
		if(!text) {
			// ugly hack to prevent the status set
			// in the RenderedMatch constructor to
			// be removed by some initialization code
			if(statusElement.html() == "Setup")
				return;
		}

		statusElement.html(text);
	},
	totalDependencies: 0,
	monitorRunDependencies: function(left) {
		this.totalDependencies = Math.max(this.totalDependencies, left);
		Module.setStatus(left ? "Preparing... (" + (this.totalDependencies-left) + "/" + this.totalDependencies + ")"
			: "All downloads complete.");
	},
	filePackagePrefixURL: "/",
	doNotCaptureKeyboard: true
};

// for type checks
function isString(object) {
	return typeof(object) === "string" || object instanceof String;
}

// tiny jQuery extension from somewhere off the net
$.fn.exists = function () {
	// int-to-bool conversion through twice applying the ! operator
    return !!this.length;
};

// another thingy from teh internetz, this time really ugly...
// but it works, and I'm not particularily intersted in doing it better
function htmlEncode(value) {
  // create a in-memory div, set it's inner text(which jQuery automatically encodes)
  // then grab the encoded contents back out. The div never exists on the page.
  return $("
").text(value).html();
}

function htmlDecode(value) {
  return $("
").html(value).text();
}

// own stuff again

function loadPage(url, success, pushState, replaceRoot, getData) {
	if(!isString(url))
		throw new TypeError("url has to be a string");

	if(pushState === undefined)
		pushState = true;
	else if(typeof(pushState) !== "boolean")
		throw new TypeError("pushState has to be a bool");

	if(replaceRoot === undefined)
		replaceRoot = "#page-wrap";
	else if(!isString(replaceRoot))
		throw new TypeError("replaceRoot has to be a string");

	var realUrl = url;
	if(realUrl.substr(-1) == "/")
		realUrl = realUrl + "index";

	$.getJSON(realUrl + ".json", getData, function(reply) {
		if(pushState) {
			document.title = reply.title;
			history.pushState(null, reply.title, url);
		}

		$(replaceRoot).fadeOut(300, function() {
			$(replaceRoot).html(reply.content);

			if(typeof(success) === "function")
				success();

			$(replaceRoot).fadeIn(300);
		});
	});
}

function loadRuleSetDoc(ruleSet) {
	var pageContent = $("#page-content");

	if(ruleSet) {
		$("#option-extras").show();

		pageContent.html("Loading
.
");
		// TODO: replace with loadPage
		$.get("/rule_sets/" + ruleSet + ".html", function(reply) {
			pageContent.html(reply);
		});

		$(".rule-set-new-tab-box").show();
		$(".rule-set-new-tab").attr("href", "/rule_sets/" + ruleSet);
	}
	else {
		$("#option-extras").hide();
		pageContent.html("Click a rule set to get the corresponding documentation here.");

		$(".rule-set-new-tab-box").show();
		$(".rule-set-new-tab").attr("href", "#");
	}
}

function initializeWSClient() {
	if(wsClient) // already initialized
		throw new Error("WebSocket client already initialized!");

	wsClient = new CyvasseWSClient(new WebSocket("ws://" + window.location.hostname + ":2516/"), loadPage);
	Module.wsClient = wsClient;
	Module.gameMetaData = {};

	Module.setStatus("Downloading.");
	window.onerror = function() {
		Module.setStatus("Exception thrown, see JavaScript console");
		Module.setStatus = function(text) {
			if(text) Module.printErr("[post-exception status] " + text);
		};
	};
}

function createGameParamValid(metaData) {
	return !!metaData.ruleSet
		&& !!metaData.color
		&& !!metaData.gameMode;
}

function updateGameOptions()
{
	var gameOptions = $("#game-options");

	var showOptions = function() {
		switch($("input[name='create-join']:checked").val())
		{
			// TODO: remove disabled attribute stuff when filters are implemented
			case "create-game":
				$("#game-options input").prop("checked", false).attr("type", "radio").attr("disabled", false);

				// TODO
				$("#game-mode-bot, #game-mode-local").attr("disabled", true);

				$("#create-game-button").attr("disabled", true);
				$("#create-game-only").show();
				break;
			case "join-game":
				$("#game-options input").prop("checked", false).attr("type", "checkbox").attr("disabled", true);
				$("#create-game-only").hide();
				break;
			default:
				throw new Error("This function should only be called when either" +
					"'Create game' or 'Join game' was clicked.");
		}

		gameOptions.fadeIn(300);
	};

	if(gameOptions.is(":visible"))
		gameOptions.fadeOut(300, showOptions);
	else
		showOptions();
}

function setupSidePaneEventHandlers() {
	$("input[name='ruleSet']").change(function() {
		if($("input[name='create-join']:checked").val() == "create-game")
			loadRuleSetDoc($("input[name='ruleSet']:checked").val());
	});

	$("input[name='create-join']").change(function() {
		var action = $("input[name='create-join']:checked").val();

		var hideRuleSetNewTabBox = function() {
			$(".rule-set-new-tab-box").fadeOut(300);
		};

		if(document.location.pathname == "/") {
			var pageOuterWrap     = $("#page-outer-wrap");
			var oldPageContentDiv = $("#page-content");
			var newPageContentDiv = $("
");

			newPageContentDiv.html("
Loading.
");

			// dirty hack...
			oldPageContentDiv.width(oldPageContentDiv.width());
			newPageContentDiv.width(newPageContentDiv.width());

			pageOuterWrap.width("170%");
			newPageContentDiv.appendTo("#page-wrap");

			pageOuterWrap.animate({"margin-left": -oldPageContentDiv.width()}, 600, function() {
				// after animation...
				oldPageContentDiv.remove();

				pageOuterWrap.css("margin-left", "");
				pageOuterWrap.width("");
				newPageContentDiv.width("");

				newPageContentDiv.attr("id", "page-content");

				hideRuleSetNewTabBox();
				loadPage("/" + action, null, true, "#page-content", "pageContent=true");

				updateGameOptions();
			});
		}
		else if(document.location.pathname.substr(1) !== action) {
			updateGameOptions();
			hideRuleSetNewTabBox();
			loadPage("/" + action, null, true, "#page-content", "pageContent=true");
		}
	});

	$("#game-options input").change(function() {
		switch($("input[name='create-join']:checked").val())
		{
			case "create-game":
				$("#create-game-button").attr("disabled", !createGameParamValid({
					ruleSet:  $("input:radio[name='ruleSet']:checked").val(),
					color:    $("input:radio[name='color']:checked").val(),
					gameMode: $("input:radio[name='gameMode']:checked").val()
				}));
				break;
			case "join-game":
				// TODO
				break;
			default:
				throw new Error("Congratiulations! You found a bug. What you just clicked should not be visible...");
		}
	});

	$("#create-game-button").click(function() {
		var metaData = {
			ruleSet:  $("input:radio[name='ruleSet']:checked").val(),
			color:    $("input:radio[name='color']:checked").val(),
			gameMode: $("input:radio[name='gameMode']:checked").val()
		};

		if(!createGameParamValid(metaData))
			throw new Error("#create-game-button should be disabled if the given parameters are not valid.");

		$("#side-pane :input").attr("disabled", true);
		$("#create-game-button").attr("disabled", true);
		$("#create-game-button").css("color", "#000");
		$("#create-game-button").html("Creating game.");

		initializeWSClient();

		// TODO: might not be the best to overwrite conn.onopen
		wsClient.conn.onopen = function() {
			wsClient.createGame(metaData);
		};
	});
}

function getMatchID(url) {
	return url.substr(-4);
}

$(document).ready(function() {
	statusElement = $("#status");
	//progressElement = $("#progress");

	$("a[href^='/']").click(function(event) {
		if(event.button === 0) {
			// left mouse click
			event.preventDefault();
			loadPage(this.href);
		}
	});

	window.onpopstate = function() {
		loadPage(document.location.pathname, null, false);
	};
});
<commit_msg>Added Module.memoryInitializerPrefixURL<commit_after>var statusElement;

var wsClient;

var Module = {
	preRun: [function() {
		Module.canvas = document.getElementById("canvas");
	}],
	postRun: [],
	print: function(text) {
		console.log(text);
	},
	printErr: function(text) {
		console.error(text);
	},
	setStatus: function(text) {
		if(!text) {
			// ugly hack to prevent the status set
			// in the RenderedMatch constructor to
			// be removed by some initialization code
			if(statusElement.html() == "Setup")
				return;
		}

		statusElement.html(text);
	},
	totalDependencies: 0,
	monitorRunDependencies: function(left) {
		this.totalDependencies = Math.max(this.totalDependencies, left);
		Module.setStatus(left ? "Preparing... (" + (this.totalDependencies-left) + "/" + this.totalDependencies + ")"
			: "All downloads complete.");
	},
	filePackagePrefixURL: "/",
	memoryInitializerPrefixURL: "/",
	doNotCaptureKeyboard: true
};

// for type checks
function isString(object) {
	return typeof(object) === "string" || object instanceof String;
}

// tiny jQuery extension from somewhere off the net
$.fn.exists = function () {
	// int-to-bool conversion through twice applying the ! operator
    return !!this.length;
};

// another thingy from teh internetz, this time really ugly...
// but it works, and I'm not particularily intersted in doing it better
function htmlEncode(value) {
  // create a in-memory div, set it's inner text(which jQuery automatically encodes)
  // then grab the encoded contents back out. The div never exists on the page.
  return $("
").text(value).html();
}

function htmlDecode(value) {
  return $("
").html(value).text();
}

// own stuff again

function loadPage(url, success, pushState, replaceRoot, getData) {
	if(!isString(url))
		throw new TypeError("url has to be a string");

	if(pushState === undefined)
		pushState = true;
	else if(typeof(pushState) !== "boolean")
		throw new TypeError("pushState has to be a bool");

	if(replaceRoot === undefined)
		replaceRoot = "#page-wrap";
	else if(!isString(replaceRoot))
		throw new TypeError("replaceRoot has to be a string");

	var realUrl = url;
	if(realUrl.substr(-1) == "/")
		realUrl = realUrl + "index";

	$.getJSON(realUrl + ".json", getData, function(reply) {
		if(pushState) {
			document.title = reply.title;
			history.pushState(null, reply.title, url);
		}

		$(replaceRoot).fadeOut(300, function() {
			$(replaceRoot).html(reply.content);

			if(typeof(success) === "function")
				success();

			$(replaceRoot).fadeIn(300);
		});
	});
}

function loadRuleSetDoc(ruleSet) {
	var pageContent = $("#page-content");

	if(ruleSet) {
		$("#option-extras").show();

		pageContent.html("Loading
.
");
		// TODO: replace with loadPage
		$.get("/rule_sets/" + ruleSet + ".html", function(reply) {
			pageContent.html(reply);
		});

		$(".rule-set-new-tab-box").show();
		$(".rule-set-new-tab").attr("href", "/rule_sets/" + ruleSet);
	}
	else {
		$("#option-extras").hide();
		pageContent.html("Click a rule set to get the corresponding documentation here.");

		$(".rule-set-new-tab-box").show();
		$(".rule-set-new-tab").attr("href", "#");
	}
}

function initializeWSClient() {
	if(wsClient) // already initialized
		throw new Error("WebSocket client already initialized!");

	wsClient = new CyvasseWSClient(new WebSocket("ws://" + window.location.hostname + ":2516/"), loadPage);
	Module.wsClient = wsClient;
	Module.gameMetaData = {};

	Module.setStatus("Downloading.");
	window.onerror = function() {
		Module.setStatus("Exception thrown, see JavaScript console");
		Module.setStatus = function(text) {
			if(text) Module.printErr("[post-exception status] " + text);
		};
	};
}

function createGameParamValid(metaData) {
	return !!metaData.ruleSet
		&& !!metaData.color
		&& !!metaData.gameMode;
}

function updateGameOptions()
{
	var gameOptions = $("#game-options");

	var showOptions = function() {
		switch($("input[name='create-join']:checked").val())
		{
			// TODO: remove disabled attribute stuff when filters are implemented
			case "create-game":
				$("#game-options input").prop("checked", false).attr("type", "radio").attr("disabled", false);

				// TODO
				$("#game-mode-bot, #game-mode-local").attr("disabled", true);

				$("#create-game-button").attr("disabled", true);
				$("#create-game-only").show();
				break;
			case "join-game":
				$("#game-options input").prop("checked", false).attr("type", "checkbox").attr("disabled", true);
				$("#create-game-only").hide();
				break;
			default:
				throw new Error("This function should only be called when either" +
					"'Create game' or 'Join game' was clicked.");
		}

		gameOptions.fadeIn(300);
	};

	if(gameOptions.is(":visible"))
		gameOptions.fadeOut(300, showOptions);
	else
		showOptions();
}

function setupSidePaneEventHandlers() {
	$("input[name='ruleSet']").change(function() {
		if($("input[name='create-join']:checked").val() == "create-game")
			loadRuleSetDoc($("input[name='ruleSet']:checked").val());
	});

	$("input[name='create-join']").change(function() {
		var action = $("input[name='create-join']:checked").val();

		var hideRuleSetNewTabBox = function() {
			$(".rule-set-new-tab-box").fadeOut(300);
		};

		if(document.location.pathname == "/") {
			var pageOuterWrap     = $("#page-outer-wrap");
			var oldPageContentDiv = $("#page-content");
			var newPageContentDiv = $("
");

			newPageContentDiv.html("
Loading.
");

			// dirty hack...
			oldPageContentDiv.width(oldPageContentDiv.width());
			newPageContentDiv.width(newPageContentDiv.width());

			pageOuterWrap.width("170%");
			newPageContentDiv.appendTo("#page-wrap");

			pageOuterWrap.animate({"margin-left": -oldPageContentDiv.width()}, 600, function() {
				// after animation...
				oldPageContentDiv.remove();

				pageOuterWrap.css("margin-left", "");
				pageOuterWrap.width("");
				newPageContentDiv.width("");

				newPageContentDiv.attr("id", "page-content");

				hideRuleSetNewTabBox();
				loadPage("/" + action, null, true, "#page-content", "pageContent=true");

				updateGameOptions();
			});
		}
		else if(document.location.pathname.substr(1) !== action) {
			updateGameOptions();
			hideRuleSetNewTabBox();
			loadPage("/" + action, null, true, "#page-content", "pageContent=true");
		}
	});

	$("#game-options input").change(function() {
		switch($("input[name='create-join']:checked").val())
		{
			case "create-game":
				$("#create-game-button").attr("disabled", !createGameParamValid({
					ruleSet:  $("input:radio[name='ruleSet']:checked").val(),
					color:    $("input:radio[name='color']:checked").val(),
					gameMode: $("input:radio[name='gameMode']:checked").val()
				}));
				break;
			case "join-game":
				// TODO
				break;
			default:
				throw new Error("Congratiulations! You found a bug. What you just clicked should not be visible...");
		}
	});

	$("#create-game-button").click(function() {
		var metaData = {
			ruleSet:  $("input:radio[name='ruleSet']:checked").val(),
			color:    $("input:radio[name='color']:checked").val(),
			gameMode: $("input:radio[name='gameMode']:checked").val()
		};

		if(!createGameParamValid(metaData))
			throw new Error("#create-game-button should be disabled if the given parameters are not valid.");

		$("#side-pane :input").attr("disabled", true);
		$("#create-game-button").attr("disabled", true);
		$("#create-game-button").css("color", "#000");
		$("#create-game-button").html("Creating game.");

		initializeWSClient();

		// TODO: might not be the best to overwrite conn.onopen
		wsClient.conn.onopen = function() {
			wsClient.createGame(metaData);
		};
	});
}

function getMatchID(url) {
	return url.substr(-4);
}

$(document).ready(function() {
	statusElement = $("#status");
	//progressElement = $("#progress");

	$("a[href^='/']").click(function(event) {
		if(event.button === 0) {
			// left mouse click
			event.preventDefault();
			loadPage(this.href);
		}
	});

	window.onpopstate = function() {
		loadPage(document.location.pathname, null, false);
	};
});
<|endoftext|>


<commit_before>// from https://www.shadertoy.com/view/XsfXWX

export default function({
  map = `
  vec3 metalRayPick(vec3 p) {
    return vec3(0.);
  }
  `
} = {}) {
  return `
struct Light
{
  vec3 color;
  vec3 direction;
};

float G1V ( float dotNV, float k ) {
	return 1.0 / (dotNV*(1.0 - k) + k);
}

float GGX(vec3 N, vec3 V, vec3 L, float roughness, float F0) {
  float alpha = roughness*roughness;
	vec3 H = normalize (V + L);

	float dotNL = clamp (dot (N, L), 0.0, 1.0);
	float dotNV = clamp (dot (N, V), 0.0, 1.0);
	float dotNH = clamp (dot (N, H), 0.0, 1.0);
	float dotLH = clamp (dot (L, H), 0.0, 1.0);

	float D, vis;
	float F;

	// NDF : GGX
	float alphaSqr = alpha*alpha;
	float pi = 3.1415926535;
	float denom = dotNH * dotNH *(alphaSqr - 1.0) + 1.0;
	D = alphaSqr / (pi * denom * denom);

	// Fresnel (Schlick)
	float dotLH5 = pow (1.0 - dotLH, 5.0);
	F = F0 + (1.0 - F0)*(dotLH5);

	// Visibility term (G) : Smith with Schlick's approximation
	float k = alpha / 2.0;
	vis = G1V (dotNL, k) * G1V (dotNV, k);

	return /*dotNL */ D * F * vis;
}

vec3 computePBRLighting (
  Light light,
  Ray ray,
  vec3 position,
  vec3 normal,
  vec3 albedo,
  float metalness,
  float roughness,
  samplerCube reflectionTexture
) {

  // material
  float fresnel_pow = 1.5;
  light.color *= textureCube(reflectionTexture, vec3(1.0,0.0,0.0)).xyz * 1.2;

  // IBL
  vec3 ibl_diffuse = textureCube(reflectionTexture, normalize(normal + vec3(rand(position.x * 2. - 1.), rand(position.y * 2. - 1.), rand(position.z * 2. - 1.)) * .5)).xyz;
  float blurRatio = (ibl_diffuse.r + ibl_diffuse.g + ibl_diffuse.b) / 3.;
  ibl_diffuse = ibl_diffuse * blurRatio + (1. - blurRatio);
  vec3 ibl_reflection = textureCube(reflectionTexture, normalize(reflect(ray.direction, normal) + vec3(rand(position.x * 2. - 1.), rand(position.y * 2. - 1.), rand(position.z * 2. - 1.)) * .5)).xyz;
  blurRatio = (ibl_reflection.r + ibl_reflection.g + ibl_reflection.b) / 3.;
  ibl_reflection = ibl_reflection * blurRatio + (1. - blurRatio);

  // fresnel
  float fresnel = max(1.0 - dot(normal, -ray.direction), 0.0);
  fresnel = pow(fresnel, fresnel_pow);

  // reflection
  vec3 refl = textureCube(reflectionTexture, reflect(ray.direction,normal)).xyz;
  refl = mix(refl, ibl_reflection, (1.0-fresnel)*roughness);
  refl = mix(refl, ibl_reflection, roughness);

  // specular
  float power = 1.0 / max(roughness * 0.4,0.01);
  vec3 spec = light.color * GGX(normal, -ray.direction, -light.direction, roughness, 0.2);
  refl -= spec;

  // diffuse
  vec3 diff = ibl_diffuse * albedo;
  diff = mix(diff, refl, fresnel * (1. - roughness));

  vec3 color = mix(diff, refl, metalness) + spec;
  return color;
}
`};
<commit_msg>more pbr fixes<commit_after>// from https://www.shadertoy.com/view/XsfXWX

export default function({
  map = `
  vec3 metalRayPick(vec3 p) {
    return vec3(0.);
  }
  `
} = {}) {
  return `
struct Light
{
  vec3 color;
  vec3 direction;
};

float G1V ( float dotNV, float k ) {
	return 1.0 / (dotNV*(1.0 - k) + k);
}

float GGX(vec3 N, vec3 V, vec3 L, float roughness, float F0) {
  float alpha = roughness*roughness;
	vec3 H = normalize (V + L);

	float dotNL = clamp (dot (N, L), 0.0, 1.0);
	float dotNV = clamp (dot (N, V), 0.0, 1.0);
	float dotNH = clamp (dot (N, H), 0.0, 1.0);
	float dotLH = clamp (dot (L, H), 0.0, 1.0);

	float D, vis;
	float F;

	// NDF : GGX
	float alphaSqr = alpha*alpha;
	float pi = 3.1415926535;
	float denom = dotNH * dotNH *(alphaSqr - 1.0) + 1.0;
	D = alphaSqr / (pi * denom * denom);

	// Fresnel (Schlick)
	float dotLH5 = pow (1.0 - dotLH, 5.0);
	F = F0 + (1.0 - F0)*(dotLH5);

	// Visibility term (G) : Smith with Schlick's approximation
	float k = alpha / 2.0;
	vis = G1V (dotNL, k) * G1V (dotNV, k);

	return /*dotNL */ D * F * vis;
}

vec3 computePBRLighting (
  Light light,
  Ray ray,
  vec3 position,
  vec3 normal,
  vec3 albedo,
  float metalness,
  float roughness,
  samplerCube reflectionTexture
) {

  // material
  float fresnel_pow = 2.5;
  light.color *= textureCube(reflectionTexture, vec3(1.0,0.0,0.0)).xyz * 1.2;

  // IBL
  vec3 randomRay = vec3(rand(position.x) * 2. - 1., rand(position.y) * 2. - 1., rand(position.z) * 2. - 1.) * (.2 * roughness);
  vec3 diffuseRayDirection = normalize(normal + randomRay);
  vec3 reflectionRayDirection = normalize(reflect(ray.direction, normal) + randomRay);
  vec3 ibl_diffuse = textureCube(reflectionTexture, diffuseRayDirection).xyz;
  // float blurRatio = (ibl_diffuse.r + ibl_diffuse.g + ibl_diffuse.b) / 3.;
  // ibl_diffuse = ibl_diffuse * blurRatio + (1. - blurRatio);
  vec3 ibl_reflection = textureCube(reflectionTexture, reflectionRayDirection).xyz;
  // blurRatio = (ibl_reflection.r + ibl_reflection.g + ibl_reflection.b) / 3.;
  // ibl_reflection = ibl_reflection * blurRatio + (1. - blurRatio);

  // fresnel
  float fresnel = max(1.0 - dot(normal, -ray.direction), 0.0);
  fresnel = pow(fresnel, fresnel_pow);

  // reflection
  vec3 refl = textureCube(reflectionTexture, reflect(ray.direction,normal)).xyz;
  refl = mix(refl, ibl_reflection, roughness);

  // specular
  vec3 spec = light.color * GGX(normal, -ray.direction, -light.direction, roughness, .2);
  // refl -= spec;

  // diffuse
  vec3 diff = albedo;
  diff = mix(diff, refl, fresnel * (1. - roughness));

  vec3 color = mix(diff, refl, metalness * (1. - roughness));
  //  + spec;
  return color;
}
`};
<|endoftext|>


<commit_before>'use strict';

const BackendCommunicator = require('./backendCommunicator');

module.exports = Game;

function Game(GameBase) {
    let self = this;

    this.GameBase = GameBase;

    this.backendCommunicator = null;

    this.settings = null;

    this.init = function(callback) {
        this.backendCommunicator = new BackendCommunicator('127.0.0.1', 3702);

        this.backendCommunicator.eventEmitter.on('match.auth', function() {
            self.backendCommunicator.sendCommand('match.auth', process.argv[2]);
        });
        this.backendCommunicator.eventEmitter.on('authed', function(settings, players) {
            self.settings = settings;
            self.GameBase.Players.players = players;

            callback();
        });
        this.backendCommunicator.eventEmitter.on('socketError', function(error) {
            console.log('socketError', error);
        });
        this.backendCommunicator.eventEmitter.on('invalidRequest', function(error) {
            console.log('invalidRequest', error);
        });
        this.backendCommunicator.eventEmitter.on('match.error', function(error) {
            console.error('Got error from backend:', error);
            process.exit();
        });

        this.backendCommunicator.eventEmitter.on('terminateGame', function() {
            process.exit();
        });
    };

    this.finish = function() {
        this.backendCommunicator.sendCommand('finish', {players: this.GameBase.Players.getAll()})
    };
};<commit_msg>Renamed the auth handshake for clearer understanding.<commit_after>'use strict';

const BackendCommunicator = require('./backendCommunicator');

module.exports = Game;

function Game(GameBase) {
    let self = this;

    this.GameBase = GameBase;

    this.backendCommunicator = null;

    this.settings = null;

    this.init = function(callback) {
        this.backendCommunicator = new BackendCommunicator('127.0.0.1', 3702);

        this.backendCommunicator.eventEmitter.on('match.requestingAuth', function() {
            self.backendCommunicator.sendCommand('match.auth', process.argv[2]);
        });
        this.backendCommunicator.eventEmitter.on('authed', function(settings, players) {
            self.settings = settings;
            self.GameBase.Players.players = players;

            callback();
        });
        this.backendCommunicator.eventEmitter.on('socketError', function(error) {
            console.log('socketError', error);
        });
        this.backendCommunicator.eventEmitter.on('invalidRequest', function(error) {
            console.log('invalidRequest', error);
        });
        this.backendCommunicator.eventEmitter.on('match.error', function(error) {
            console.error('Got error from backend:', error);
            process.exit();
        });

        this.backendCommunicator.eventEmitter.on('terminateGame', function() {
            process.exit();
        });
    };

    this.finish = function() {
        this.backendCommunicator.sendCommand('finish', {players: this.GameBase.Players.getAll()})
    };
};<|endoftext|>


<commit_before>var fs = require("fs");
var yaml = require("js-yaml");
var _ = require("underscore");
var path = require("path");
var marked = require("marked");

marked.setOptions({
  gfm: true,
  tables: true,
  breaks: true,
  highlight: function (code) {
    return require('highlight.js').highlightAuto(code).value;
  }
})

/**
 * Defaults object
 *
 */
var defaults = {
  optionsCheck: true,
  optionsDelimiter: "---",
  optionsParse: function (string) {
    return yaml.safeLoad(string);
  },
  contentParse: function (string) {
    return marked(string);
  },
  templatesDir: path.join(process.cwd(), "src", "layouts"),
  templateCompile: function (string) {
    return _.template(string);
  },
  templateData: {}
};

/**
 * Constructor for the Pagemaki class
 *
 * @param {[type]} config [description]
 */
var Pagemaki = function (config) {
  this.templates = {};
  this.config = _.extend({}, defaults, config);
  this.config.optionsRegex = new RegExp("^" + this.config.optionsDelimiter + "([\\S\\s]+)" + this.config.optionsDelimiter + "([\\S\\s]+)");
};

/**
 * Find and return the template string to be compiled
 *
 * Note: this can be overridden by passing a 'getTemplateString'
 * function to the Pagemaki constructor, esp for testing
 *
 * @param  {[type]} name [description]
 * @return {[type]}      [description]
 */
Pagemaki.prototype.getTemplateString = function (name) {
  return fs.readFileSync(path.join(this.config.templatesDir, name + ".html")).toString();
}

/**
 * Get a cached template by name, or from disk and then cache for later
 *
 * @param  {[type]} name [description]
 * @return {[type]}      [description]
 */
Pagemaki.prototype.getTemplate = function (name) {

  var getTemplateString = (this.config.getTemplateString || this.getTemplateString).bind(this);

  if (!this.templates[name]) {
    this.templates[name] = this.config.templateCompile(getTemplateString(name).trim());
  }

  return this.templates[name];

};

/**
 * Parse out the string and look for options, content
 *
 * @param  {[type]}   string   [description]
 * @param  {Function} callback [description]
 * @return {[type]}            [description]
 */
Pagemaki.prototype.parse = function (string, callback) {

  var data = {};
  var matches = this.config.optionsCheck && this.config.optionsRegex.exec(string);

  if (matches) {
    data.options = this.config.optionsParse(matches[1]);
    data.content = this.config.contentParse(matches[2].trim());
  } else {
    data.options = false;
    data.content = this.config.contentParse(string.trim());
  }

  callback(null, data);

};

/**
 * Use the rendering function to create static string
 *
 * @param  {[type]}   err      [description]
 * @param  {[type]}   parsed   [description]
 * @param  {Function} callback [description]
 * @return {[type]}            [description]
 */
Pagemaki.prototype.render = function (err, parsed, callback) {

  if (err) {
    callback(err);
    return;
  }

  var layout = (parsed.options && parsed.options.layout) || "default";
  var render = this.getTemplate(layout);

  this.config.templateData.page = parsed;

  callback(null, render(this.config.templateData).trim());

};

/**
 * Putting it all together using the parsed options, content,
 * and templates to compile static HTML
 *
 * @param  {[type]}   string   [description]
 * @param  {Function} callback [description]
 * @return {[type]}            [description]
 */
Pagemaki.prototype.make = function (string, callback) {

  var self = this;

  this.parse(string, function (err, parsed) {

    self.render(err, parsed, callback);

  });

};

module.exports = Pagemaki;
<commit_msg>Fix broken underscore dependency, now lodash<commit_after>var fs = require("fs");
var yaml = require("js-yaml");
var _ = require("lodash");
var path = require("path");
var marked = require("marked");

marked.setOptions({
  gfm: true,
  tables: true,
  breaks: true,
  highlight: function (code) {
    return require('highlight.js').highlightAuto(code).value;
  }
})

/**
 * Defaults object
 *
 */
var defaults = {
  optionsCheck: true,
  optionsDelimiter: "---",
  optionsParse: function (string) {
    return yaml.safeLoad(string);
  },
  contentParse: function (string) {
    return marked(string);
  },
  templatesDir: path.join(process.cwd(), "src", "layouts"),
  templateCompile: function (string) {
    return _.template(string);
  },
  templateData: {}
};

/**
 * Constructor for the Pagemaki class
 *
 * @param {[type]} config [description]
 */
var Pagemaki = function (config) {
  this.templates = {};
  this.config = _.extend({}, defaults, config);
  this.config.optionsRegex = new RegExp("^" + this.config.optionsDelimiter + "([\\S\\s]+)" + this.config.optionsDelimiter + "([\\S\\s]+)");
};

/**
 * Find and return the template string to be compiled
 *
 * Note: this can be overridden by passing a 'getTemplateString'
 * function to the Pagemaki constructor, esp for testing
 *
 * @param  {[type]} name [description]
 * @return {[type]}      [description]
 */
Pagemaki.prototype.getTemplateString = function (name) {
  return fs.readFileSync(path.join(this.config.templatesDir, name + ".html")).toString();
}

/**
 * Get a cached template by name, or from disk and then cache for later
 *
 * @param  {[type]} name [description]
 * @return {[type]}      [description]
 */
Pagemaki.prototype.getTemplate = function (name) {

  var getTemplateString = (this.config.getTemplateString || this.getTemplateString).bind(this);

  if (!this.templates[name]) {
    this.templates[name] = this.config.templateCompile(getTemplateString(name).trim());
  }

  return this.templates[name];

};

/**
 * Parse out the string and look for options, content
 *
 * @param  {[type]}   string   [description]
 * @param  {Function} callback [description]
 * @return {[type]}            [description]
 */
Pagemaki.prototype.parse = function (string, callback) {

  var data = {};
  var matches = this.config.optionsCheck && this.config.optionsRegex.exec(string);

  if (matches) {
    data.options = this.config.optionsParse(matches[1]);
    data.content = this.config.contentParse(matches[2].trim());
  } else {
    data.options = false;
    data.content = this.config.contentParse(string.trim());
  }

  callback(null, data);

};

/**
 * Use the rendering function to create static string
 *
 * @param  {[type]}   err      [description]
 * @param  {[type]}   parsed   [description]
 * @param  {Function} callback [description]
 * @return {[type]}            [description]
 */
Pagemaki.prototype.render = function (err, parsed, callback) {

  if (err) {
    callback(err);
    return;
  }

  var layout = (parsed.options && parsed.options.layout) || "default";
  var render = this.getTemplate(layout);

  this.config.templateData.page = parsed;

  callback(null, render(this.config.templateData).trim());

};

/**
 * Putting it all together using the parsed options, content,
 * and templates to compile static HTML
 *
 * @param  {[type]}   string   [description]
 * @param  {Function} callback [description]
 * @return {[type]}            [description]
 */
Pagemaki.prototype.make = function (string, callback) {

  var self = this;

  this.parse(string, function (err, parsed) {

    self.render(err, parsed, callback);

  });

};

module.exports = Pagemaki;
<|endoftext|>


<commit_before>'use strict';

let config = require('../config'),
    ignoreURLs = [
        'whatsapp'
    ];

const Pageres = require('pageres');

class URLtoImage {
    constructor(message) {
        this.action = 'IMAGE';
        this.type = 'all';
        this.url = [
            message[1], // protocol: http or https
            message[2]  // url: c9.io/example.html
        ].join('');
    }

    execute(callback) {
        let tmp = config.tmp.dir,
            url = this.url,
            ignorePattern;

        for (let i = 0, len = ignoreURLs.length; i < len; i++) {
            ignorePattern = new RegExp(ignoreURLs[i], 'i');

            if (url.match(ignorePattern)) {
                console.log('Ignore url found ' + url);
                return;
            }
        }

        // TODO, handle diffrently images, .jpg, .png wget them directly instead of using web browser.

        console.log('Downloading url... ' + url);

        let pageres = new Pageres({delay: 2})
            .src(url, ['750x1334'])
            .dest(tmp)
            .run()
            .then((stream) => {
                let fileName = stream[0].filename;
                console.log('Downloading complete... ' + url + ' Sending back '+ fileName);

                callback(tmp +'/'+ fileName);
            });
    }
}

module.exports = URLtoImage;<commit_msg>spacing<commit_after>'use strict';

let config = require('../config'),
    ignoreURLs = [
        'whatsapp'
    ];

const Pageres = require('pageres');

class URLtoImage {
    constructor(message) {
        this.action = 'IMAGE';
        this.type = 'all';
        this.url = [
            message[1], // protocol: http or https
            message[2]  // url: c9.io/example.html
        ].join('');
    }

    execute(callback) {
        let tmp = config.tmp.dir,
            url = this.url,
            ignorePattern;

        for (let i = 0, len = ignoreURLs.length; i < len; i++) {
            ignorePattern = new RegExp(ignoreURLs[i], 'i');

            if (url.match(ignorePattern)) {
                console.log('Ignore url found ' + url);
                return;
            }
        }

        // TODO, handle diffrently images, .jpg, .png wget them directly instead of using web browser.

        console.log('Downloading url... ' + url);

        let pageres = new Pageres({delay: 2})
            .src(url, ['750x1334'])
            .dest(tmp)
            .run()
            .then((stream) => {
                let fileName = stream[0].filename;
                console.log('Downloading complete... ' + url + ' Sending back '+ fileName);

                callback(tmp +'/'+ fileName);
            });
    }
}

module.exports = URLtoImage;<|endoftext|>


<commit_before>'use strict';

Connector.artistTrackSelector = '#np';

Connector.playButtonSelector = '#stream-play';

Connector.playerSelector = '.dynamic-row > .col-md-6';

Connector.durationSelector = '#progress-length';

Connector.currentTimeSelector = '#progress-current';
<commit_msg>Fix r-a-d.io connector<commit_after>'use strict';

const playPauseButtonSelector = '#stream-play';

Connector.artistTrackSelector = '#np';

Connector.playerSelector = '.dynamic-row > .col-md-6';

Connector.durationSelector = '#progress-length';

Connector.currentTimeSelector = '#progress-current';

Connector.isPlaying = () =>
	Util.getTextFromSelectors(playPauseButtonSelector) === 'Stop Stream';
<|endoftext|>


<commit_before>(function($){

    var data = {
        state : {
            isOverWorld: function(){
                return $('.overworld-locations').is(':visible');
            },
            isChooseParty: function(){
                return $('.page-dungeon-chooseparty').is(':visible');
            },
            isAdventure: function(){
                return $('.dungeon-map-inner').is(':visible') && !$('.modal-window').is(':visible');
            },
            isSelectCompanion: function(){
                return $('.encounter-party-list').is(':visible');
            },
            isEncounter: function(){
                return $('.page-dungeon-combat').is(':visible') &&
                        (!$('.modal-window').is(':visible') ||
                          $('.modal-confirm.combat-wild > h3:contains(' + data.text.criticalHit + ')').is(':visible'));
            },
            isDiceRoller: function(){
                return $('.combatDiceBox').is(':visible') && !$('.modal-window').is(':visible');
            },
            isModal: function(){
                return $('.modal-window').is(':visible');
            }
        },
        text:{
            chooseYourParty: 'Choose Your Party',
            ok: 'OK',
            d20: 'D20',
            criticalHit: 'Critical Hit!'
        }
    };

    var Adventure = function(character, dicePickerBrain){

        var _adv = [
            {
                tier: "tier-[1|2|3|4|5|6]",
                companions: [
                    {
                        "name":"cleric",
                        "required":true||false,
                    },
                    {
                        "name":"guy",
                        "required":true||false,
                    }
                ]
            },
            {
                tier: "tier-1",
                companions: [
                    {
                        "name":"lowbies",
                        "required":true||false,
                    }
                ]
            },

        ];

        this.character = character;
        this.changeCharacter = $.nwg.changeCharacter.create(this.character);
        this.adventures = this.character.adv;
        this.dicePicker = $.nwg.dicePicker.create(this.character,
            !dicePickerBrain ? $.nwg.dicePickerBrain.create() : dicePickerBrain);
    };

    Adventure.prototype.make_adventure_active = function(task) {
        $('.nav-dungeons').trigger('click');
        return {
            error: false,
            delay: 3000
        };
    };

    Adventure.prototype.check_adventure_state = function(task) {
        //var task = self.crete_base_task();
        /*
            Should only be called from the crate_base_task method
        */

        if(data.state.isOverWorld()){
            console.log("isOverWorld");
            task.then(this.start_adventure.bind(this))
            task.then(this.confirm_adventure.bind(this));
            task.then(this.clear_adventure_party.bind(this));
            task.then(this.select_adventure_party.bind(this));
        }
        else if(data.state.isSelectCompanion()){
            console.log("isSelectCompanion");
            task.then(this.clear_adventure_party.bind(this));
            task.then(this.select_adventure_party.bind(this));
        }
        else if(data.state.isAdventure()){
            console.log("isAdventure");
            task.then(this.select_encounter.bind(this));
        }
        else if(data.state.isEncounter()){
            console.log("isEncounter");
            task.then(this.dicePicker.pick_die.bind(this.dicePicker));
        }
        //isAdventure
            //select encounter
        //isSelectCompanion
            //choose encounter companion
        //isEncounter || isCritical
            //select die
        //isDiceRoller
            //wait
        //isModal
            //clear
        else if (data.state.isModal){
            task.then(this.clear_modal.bind(this));
        }
        //else

        return {error:false, delay: 3000};
    };

    Adventure.prototype.start_adventure = function(task) {
        console.log("start_adventure");
        $('a.' + 'tier-1').trigger('click');

        return {
            error: false,
            delay: 1000
        };
    };

    Adventure.prototype.confirm_adventure = function(task) {
        console.log("confirm_adventure");
        $('.choosePartyButton > button:contains(' + data.text.chooseYourParty + ')').trigger('click');

        return {
            error: false,
            delay: 1000
        };
    };

    Adventure.prototype.select_adventure_party = function(old_task) {
        console.log("select_adventure_party");
        //select adventure party member (which attemps to cancel the confirm if up THEN clears THEN selects)
        var PARTY_SIZE = 4;
        var adventures = this.adventures;
        var self = this;
        var companionsToSelect = [];

        $(adventures).each(function(indx, adventure){

            var tier = adventure.tier;
            var adventureCompanions = adventure.companions;
            var requiredCompanions = [];
            var optionalCompanions = [];
            var totalCompanionCount = $('.party-entry.full-sheet:not(.promo)').length;
            var disabledCount = $('.party-entry.full-sheet.disabled').length;
            var maxAvailableCount = totalCompanionCount - disabledCount;
            var availableCompanions = $('.party-entry.full-sheet.available:not(.promo)>a:not(.selected)');

            if(adventureCompanions && adventureCompanions.length > 0 &&
                totalCompanionCount > PARTY_SIZE && maxAvailableCount > PARTY_SIZE){

                $(availableCompanions).each(function(indx, aCmp){
                    var aComp = $(aCmp);
                    var matched = false;
                    $(adventureCompanions).each(function(indx, cmp){
                        var companion = aComp.has(':contains(' + cmp.name + ')');
                        if(companion.length === 1){
                            matched = true;
                            if(cmp.required){
                                requiredCompanions.push(companion);
                            }
                            else if(!cmp.excluded){
                                optionalCompanions.push(companion);
                            }
                        }
                    });
                    if(!matched){
                        optionalCompanions.push(aComp);
                    }
                    //console.log("rC=" + requiredCompanions.length + " | oC=" + optionalCompanions.length);
                });

                if(requiredCompanions.length + optionalCompanions.length >= PARTY_SIZE){

                    for(var i = 0; i < requiredCompanions.length && i < PARTY_SIZE; i++){
                        companionsToSelect.push($(requiredCompanions[i]));
                    }

                    for(var ii = 0; ii < optionalCompanions.length && ii < PARTY_SIZE && ii < PARTY_SIZE - requiredCompanions.length; ii++){
                        companionsToSelect.push($(optionalCompanions[ii]));
                    }

                    return false;
                }
            }
            else if(totalCompanionCount <= PARTY_SIZE && disabledCount === 0){
                companionsToSelect = availableCompanions;
                return false;
            }
        });

        if(companionsToSelect.length > 0){
            for(var i = 0; i < companionsToSelect.length && i < PARTY_SIZE; i++){
                $(companionsToSelect[i]).trigger('click');
            }

            var task = self.create_base_task();
            task.then(self.comfirm_adventure_party.bind(self));
            task.then(self.select_encounter.bind(self));
            task.then(self.select_encoutner_companion.bind(self));
            task.then(self.select_die.bind(self));

            task.start_in(1500);
        }

        old_task.finish();
    };

    Adventure.prototype.clear_adventure_party = function(task){
        console.log("clear_adventure_party");
        var partyCloseButtons = $('.party-entry > button.close-button');
        partyCloseButtons.each(function(idx, btn) {
            $(btn).trigger('click');
        });

        return {
            error: false,
            delay: 3000
        };
    };

    Adventure.prototype.comfirm_adventure_party = function(task) {
        console.log("comfirm_adventure_party");
        $('.modal-window  button:contains(' + data.text.ok + ')').trigger('click');

        return {
            error: false,
            delay: 1000
        };
    };

    Adventure.prototype.select_encounter = function(task) {
        console.log("select_encounter");
        if($('.dungeon-map-inner').length === 0){
            //console.log("Dungeon not ready");
            return {
                error: false,
                delay: 1000
            };
        }
        var encounters = $('.overlay.button:not(.complete, .exit, .boss)');
        var boss = $('.overlay.button.boss');

        //console.log("[encounters=" + encounters.length + "]");
        if(encounters.length > 0){
            encounters.eq(0).trigger('click');
        }
        else if(boss.length > 0){
            boss.eq(0).trigger('click');
        }

        return {
            error: false,
            delay: 1000
        };
    };

    Adventure.prototype.select_encoutner_companion = function(task) {
        console.log("select_encoutner_companion");
        var companions = $('a.selectable');
        if(!companions.length){
            //console.log("companions not found");
            return {
                error: false,
                delay: 1000
            };
        };
        $('a.selectable').eq(0).trigger('click');
        return {
            error: false,
            delay: 1000
        };
    };

    Adventure.prototype.clear_modal = function(task) {
        var m = $('.modal-window');

        var okBtn = m.find('button:contains(' + data.text.ok + ')')
        var d20Btn = m.find('button:contains('+ data.text.d20+')');

        if(okBtn.length === 1){
            okBtn.trigger('click');
        }
        if(d20Btn.l === 1){
            d20Btn.trigger('click');
        }

        return {
            error:false,
            delay: 3000
        }
    };

    Adventure.prototype.create_base_task = function create_base_task() {
        var self = this;
        var task = $.task.create(this.changeCharacter.activate.bind(this.changeCharacter));
        task.then(this.make_adventure_active.bind(this));
        task.then(this.check_adventure_state.bind(this));

        return task;
    };

    $.extend(true, $.nwg, {
        adventure: {
            create:function(character){
                return new Adventure(character);
            }
        }
    });

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

    var data = {
        state : {
            isOverWorld: function(){
                return $('.overworld-locations').is(':visible');
            },
            isChooseParty: function(){
                return $('.page-dungeon-chooseparty').is(':visible');
            },
            isAdventure: function(){
                return $('.dungeon-map-inner').is(':visible') && !$('.modal-window').is(':visible');
            },
            isSelectCompanion: function(){
                return $('.encounter-party-list').is(':visible');
            },
            isEncounter: function(){
                return $('.page-dungeon-combat').is(':visible') &&
                        (!$('.modal-window').is(':visible') ||
                          $('.modal-confirm.combat-wild > h3:contains(' + data.text.criticalHit + ')').is(':visible'));
            },
            isDiceRoller: function(){
                return $('.combatDiceBox').is(':visible') && !$('.modal-window').is(':visible');
            },
            isModal: function(){
                return $('.modal-window').is(':visible');
            }
        },
        text:{
            chooseYourParty: 'Choose Your Party',
            ok: 'OK',
            d20: 'D20',
            criticalHit: 'Critical Hit!'
        }
    };

    var Adventure = function(character, dicePickerBrain){

        var _adv = [
            {
                tier: "tier-[1|2|3|4|5|6]",
                companions: [
                    {
                        "name":"cleric",
                        "required":true||false,
                    },
                    {
                        "name":"guy",
                        "required":true||false,
                    }
                ]
            },
            {
                tier: "tier-1",
                companions: [
                    {
                        "name":"lowbies",
                        "required":true||false,
                    }
                ]
            },

        ];

        this.character = character;
        this.changeCharacter = $.nwg.changeCharacter.create(this.character);
        this.adventures = this.character.adv;
        this.dicePicker = $.nwg.dicePicker.create(this.character,
            !dicePickerBrain ? $.nwg.dicePickerBrain.create() : dicePickerBrain);
    };

    Adventure.prototype.make_adventure_active = function(task) {
        $('.nav-dungeons').trigger('click');
        return {
            error: false,
            delay: 3000
        };
    };

    Adventure.prototype.check_adventure_state = function(task) {
        //var task = self.crete_base_task();
        /*
            Should only be called from the crate_base_task method
        */

        if(data.state.isOverWorld()){
            console.log("isOverWorld");
            task.then(this.start_adventure.bind(this))
            task.then(this.confirm_adventure.bind(this));
            task.then(this.clear_adventure_party.bind(this));
            task.then(this.select_adventure_party.bind(this));
        }
        else if(data.state.isSelectCompanion()){
            console.log("isSelectCompanion");
            task.then(this.clear_adventure_party.bind(this));
            task.then(this.select_adventure_party.bind(this));
        }
        else if(data.state.isAdventure()){
            console.log("isAdventure");
            task.then(this.select_encounter.bind(this));
            task.then(this.select_encounter_companion.bind(this));
        }
        else if(data.state.isSelectCompanion()){
            console.log("isSelectCompanion");
            task.then(this.select_encounter_companion.bind(this));
        }
        else if(data.state.isEncounter()){
            console.log("isEncounter");
            task.then(this.dicePicker.pick_die.bind(this.dicePicker));
        }
        //isAdventure
            //select encounter
        //isSelectCompanion
            //choose encounter companion
        //isEncounter || isCritical
            //select die
        //isDiceRoller
            //wait
        //isModal
            //clear
        else if (data.state.isModal){
            task.then(this.clear_modal.bind(this));
        }
        //else

        return {error:false, delay: 3000};
    };

    Adventure.prototype.start_adventure = function(task) {
        console.log("start_adventure");
        $('a.' + 'tier-1').trigger('click');

        return {
            error: false,
            delay: 1000
        };
    };

    Adventure.prototype.confirm_adventure = function(task) {
        console.log("confirm_adventure");
        $('.choosePartyButton > button:contains(' + data.text.chooseYourParty + ')').trigger('click');

        return {
            error: false,
            delay: 1000
        };
    };

    Adventure.prototype.select_adventure_party = function(old_task) {
        console.log("select_adventure_party");
        //select adventure party member (which attemps to cancel the confirm if up THEN clears THEN selects)
        var PARTY_SIZE = 4;
        var adventures = this.adventures;
        var self = this;
        var companionsToSelect = [];

        $(adventures).each(function(indx, adventure){

            var tier = adventure.tier;
            var adventureCompanions = adventure.companions;
            var requiredCompanions = [];
            var optionalCompanions = [];
            var totalCompanionCount = $('.party-entry.full-sheet:not(.promo)').length;
            var disabledCount = $('.party-entry.full-sheet.disabled').length;
            var maxAvailableCount = totalCompanionCount - disabledCount;
            var availableCompanions = $('.party-entry.full-sheet.available:not(.promo)>a:not(.selected)');

            if(adventureCompanions && adventureCompanions.length > 0 &&
                totalCompanionCount > PARTY_SIZE && maxAvailableCount > PARTY_SIZE){

                $(availableCompanions).each(function(indx, aCmp){
                    var aComp = $(aCmp);
                    var matched = false;
                    $(adventureCompanions).each(function(indx, cmp){
                        var companion = aComp.has(':contains(' + cmp.name + ')');
                        if(companion.length === 1){
                            matched = true;
                            if(cmp.required){
                                requiredCompanions.push(companion);
                            }
                            else if(!cmp.excluded){
                                optionalCompanions.push(companion);
                            }
                        }
                    });
                    if(!matched){
                        optionalCompanions.push(aComp);
                    }
                    //console.log("rC=" + requiredCompanions.length + " | oC=" + optionalCompanions.length);
                });

                if(requiredCompanions.length + optionalCompanions.length >= PARTY_SIZE){

                    for(var i = 0; i < requiredCompanions.length && i < PARTY_SIZE; i++){
                        companionsToSelect.push($(requiredCompanions[i]));
                    }

                    for(var ii = 0; ii < optionalCompanions.length && ii < PARTY_SIZE && ii < PARTY_SIZE - requiredCompanions.length; ii++){
                        companionsToSelect.push($(optionalCompanions[ii]));
                    }

                    return false;
                }
            }
            else if(totalCompanionCount <= PARTY_SIZE && disabledCount === 0){
                companionsToSelect = availableCompanions;
                return false;
            }
        });

        if(companionsToSelect.length > 0){
            for(var i = 0; i < companionsToSelect.length && i < PARTY_SIZE; i++){
                $(companionsToSelect[i]).trigger('click');
            }

            var task = self.create_base_task();
            task.then(self.comfirm_adventure_party.bind(self));
            task.then(self.select_encounter.bind(self));
            task.then(self.select_encounter_companion.bind(self));
            task.then(self.select_die.bind(self));

            task.start_in(1500);
        }

        old_task.finish();
    };

    Adventure.prototype.clear_adventure_party = function(task){
        console.log("clear_adventure_party");
        var partyCloseButtons = $('.party-entry > button.close-button');
        partyCloseButtons.each(function(idx, btn) {
            $(btn).trigger('click');
        });

        return {
            error: false,
            delay: 3000
        };
    };

    Adventure.prototype.comfirm_adventure_party = function(task) {
        console.log("comfirm_adventure_party");
        $('.modal-window  button:contains(' + data.text.ok + ')').trigger('click');

        return {
            error: false,
            delay: 1000
        };
    };

    Adventure.prototype.select_encounter = function(task) {
        console.log("select_encounter");
        if($('.dungeon-map-inner').length === 0){
            //console.log("Dungeon not ready");
            return {
                error: false,
                delay: 1000
            };
        }
        var encounters = $('.overlay.button:not(.complete, .exit, .boss)');
        var boss = $('.overlay.button.boss');

        //console.log("[encounters=" + encounters.length + "]");
        if(encounters.length > 0){
            encounters.eq(0).trigger('click');
        }
        else if(boss.length > 0){
            boss.eq(0).trigger('click');
        }

        return {
            error: false,
            delay: 1000
        };
    };

    Adventure.prototype.select_encounter_companion = function(task) {
        console.log("select_encounter_companion");
        var companions = $('a.selectable');
        if(!companions.length){
            //console.log("companions not found");
            return {
                error: false,
                delay: 1000
            };
        };
        $('a.selectable').eq(0).trigger('click');
        return {
            error: false,
            delay: 1000
        };
    };

    Adventure.prototype.clear_modal = function(task) {
        var m = $('.modal-window');

        var okBtn = m.find('button:contains(' + data.text.ok + ')')
        var d20Btn = m.find('button:contains('+ data.text.d20+')');

        if(okBtn.length === 1){
            okBtn.trigger('click');
        }
        if(d20Btn.l === 1){
            d20Btn.trigger('click');
        }

        return {
            error:false,
            delay: 3000
        }
    };

    Adventure.prototype.create_base_task = function create_base_task() {
        var self = this;
        var task = $.task.create(this.changeCharacter.activate.bind(this.changeCharacter));
        task.then(this.make_adventure_active.bind(this));
        task.then(this.check_adventure_state.bind(this));

        return task;
    };

    $.extend(true, $.nwg, {
        adventure: {
            create:function(character){
                return new Adventure(character);
            }
        }
    });

}(jQuery));<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Joyride from 'react-joyride';
import isEmpty from 'lodash/isEmpty';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Link } from 'react-router';
import currentUserProps from '../prop-types/current_user_props';
import NotificationDropdown from '../containers/NotificationDropdown';
import NotificationMenu from '../components/NotificationMenu';
import { fetchNotifications } from '../actions/notification_actions';

let LoginMenu = ({disableUserRegistration, logInOpener, signUpOpener, currentUser}) => {
  let loggedIn = ! isEmpty(currentUser);
  if(!loggedIn) {
    if(disableUserRegistration) {
      return (

            Login

      );
    }
    return (

           {
            logInOpener();
            return false;
          }}>Login

           {
            signUpOpener();
            return false;
          }}> Register

    );
  }
  return null;

};

LoginMenu.propTypes = {
  currentUser: currentUserProps,
  logInOpener: PropTypes.func.isRequired,
  signUpOpener: PropTypes.func.isRequired,
  disableUserRegistration: PropTypes.bool.isRequired
};

let ContentMenu = ({settingsOpener, currentUser}) => {
  let loggedIn = ! isEmpty(currentUser);
  if(loggedIn) {
    let {email} = currentUser;
    return(

        {email}

 {
            e.preventDefault();
            settingsOpener();
            return false;
          }}>Settings

          {currentUser.admin &&
<Link to="/admin" tabIndex="2"><text className="sr-only">Click link to visit </text>Admin Panel</Link>
}

            Logout

    );
  }
  return false;
};
ContentMenu.propTypes = {
  currentUser: currentUserProps,
  settingsOpener: PropTypes.func.isRequired
};

let SignedInMenu = ({currentUser, location, notifications, notificationCount}) => {
  let loggedIn = ! isEmpty(currentUser);
  if(loggedIn) {
    return (

Dashboard

        {!location.pathname.includes("revise") && !location.pathname.includes("edit") && !location.pathname.includes("extend") && !location.pathname.includes("new") && (currentUser.publisher || currentUser.author) &&

            Create

<Link to="/responseSets/new" tabIndex="2"><text className="sr-only">Click link to create new </text>Response Sets</Link>

<Link to="/questions/new" tabIndex="2"><text className="sr-only">Click link to create new </text>Questions</Link>

<Link to="/sections/new" tabIndex="2"><text className="sr-only">Click link to create new </text>Sections</Link>

<Link to="/surveys/new" tabIndex="2"><text className="sr-only">Click link to create new </text>Surveys</Link>

<Link to="/surveys/import" tabIndex="2"><text className="sr-only">Click link to </text>Import Spreadsheet</Link>

        }

          <NotificationDropdown notifications={notifications} notificationCount={notificationCount} />
          { notificationCount > 0 ? (
            <NotificationMenu notifications={notifications} />
          ) : (

No new notifications

          )}

    );
  }
  return null;
};
SignedInMenu.propTypes = {
  currentUser: currentUserProps,
  location: PropTypes.object,
  notifications: PropTypes.arrayOf(PropTypes.object),
  notificationCount: PropTypes.number
};

class Header extends Component {
  constructor(props){
    super(props);
    this.state={
      joyrideOverlay: false,
      joyrideType: 'continuous',
      isReady: false,
      isRunning: false,
      stepIndex: 0,
      steps: [],
      selector: ''
    };
    this.renderJoyride = this.renderJoyride.bind(this);
    this.addSteps = this.addSteps.bind(this);
  }

  componentWillMount() {
    this.props.fetchNotifications();
  }

  componentDidMount() {
    this.addSteps(this.props.steps);
    setTimeout(() => {
      this.setState({
        isReady: true,
        isRunning: false,
      });
    }, 1000);
  }

  addSteps(steps) {
    let newSteps = steps;
    if (!Array.isArray(newSteps)) {
      newSteps = [newSteps];
    }
    if (!newSteps.length) {
      return;
    }

    this.setState(currentState => {
      currentState.steps = currentState.steps.concat(newSteps);
      return currentState;
    });
  }

  renderJoyride(isReady, isRunning, joyrideOverlay, joyrideType, selector, stepIndex) {
    return (
      <Joyride
        ref={c => (this.joyride = c)}
        debug={false}
        locale={{
          back: (Back),
          close: (Close),
          last: (End),
          next: (Next),
          skip: (Exit Tutorial),
        }}
        autoStart={true}
        run={isRunning}
        showOverlay={joyrideOverlay}
        showSkipButton={true}
        showStepsProgress={true}
        stepIndex={stepIndex}
        steps={this.props.steps}
        type={joyrideType}
        tooltipOffset={0}
        keyboardNavigation={false}
      />
    );
  }

  render() {
    const {
      isReady,
      isRunning,
      joyrideOverlay,
      joyrideType,
      selector,
      stepIndex,
    } = this.state;

    return (

          {isReady &&
{this.renderJoyride(isReady, isRunning, joyrideOverlay, joyrideType, selector, stepIndex)}
}

            <button type="button" className="cdc-navbar-toggle collapsed" data-toggle="collapse" data-target="#cdcnav" aria-expanded="false" tabIndex="2">
              Toggle navigation
              Toggle navigation
            </button>
            <Link to="/" className="cdc-brand" tabIndex="2">CDC Vocabulary Service</Link>

            <SignedInMenu currentUser={this.props.currentUser} location={this.props.location} notifications={this.props.notifications} notificationCount={this.props.notificationCount} />

              <ContentMenu currentUser={this.props.currentUser} settingsOpener={this.props.settingsOpener} />
              <LoginMenu currentUser={this.props.currentUser} logInOpener={this.props.logInOpener} signUpOpener={this.props.signUpOpener} disableUserRegistration={this.props.disableUserRegistration}/>

                Help

<Link to='/Help' tabIndex="2">Help Documentation</Link>

                  {isReady && this.props.steps.length > 0 &&

 {
                      e.preventDefault();
                      return this.joyride.reset(true);
                    }}>Step-by-Step Walkthrough

                  }

Swagger API

<Link to="/fhirDoc" tabIndex="2">FHIR Documentation</Link>

<Link to={{ pathname: '/Help', state: {selectedTab: 'whatsnew'} }}>What‘s New</Link>

Contact Us

Release: v{this.props.appVersion}

    );
  }
}

function mapStateToProps(state) {
  return {
    notifications: state.notifications,
    currentUser: state.currentUser,
    steps: state.tutorialSteps,
    notificationCount: state.notifications.length
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({fetchNotifications}, dispatch);
}

Header.propTypes = {
  currentUser: currentUserProps,
  steps: PropTypes.array,
  location: PropTypes.object,
  appVersion: PropTypes.string,
  notifications: PropTypes.arrayOf(PropTypes.object),
  notificationCount: PropTypes.number,
  fetchNotifications: PropTypes.func,
  logInOpener: PropTypes.func.isRequired,
  signUpOpener: PropTypes.func.isRequired,
  settingsOpener: PropTypes.func.isRequired,
  disableUserRegistration: PropTypes.bool.isRequired
};

export default connect(mapStateToProps, mapDispatchToProps)(Header);
<commit_msg>updated tags for help menu items<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Joyride from 'react-joyride';
import isEmpty from 'lodash/isEmpty';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Link } from 'react-router';
import currentUserProps from '../prop-types/current_user_props';
import NotificationDropdown from '../containers/NotificationDropdown';
import NotificationMenu from '../components/NotificationMenu';
import { fetchNotifications } from '../actions/notification_actions';
import { gaSend } from '../utilities/GoogleAnalytics';

let LoginMenu = ({disableUserRegistration, logInOpener, signUpOpener, currentUser}) => {
  let loggedIn = ! isEmpty(currentUser);
  if(!loggedIn) {
    if(disableUserRegistration) {
      return (

            Login

      );
    }
    return (

           {
            logInOpener();
            return false;
          }}>Login

           {
            signUpOpener();
            return false;
          }}> Register

    );
  }
  return null;

};

LoginMenu.propTypes = {
  currentUser: currentUserProps,
  logInOpener: PropTypes.func.isRequired,
  signUpOpener: PropTypes.func.isRequired,
  disableUserRegistration: PropTypes.bool.isRequired
};

let ContentMenu = ({settingsOpener, currentUser}) => {
  let loggedIn = ! isEmpty(currentUser);
  if(loggedIn) {
    let {email} = currentUser;
    return(

        {email}

 {
            e.preventDefault();
            settingsOpener();
            return false;
          }}>Settings

          {currentUser.admin &&
<Link to="/admin" tabIndex="2"><text className="sr-only">Click link to visit </text>Admin Panel</Link>
}

            Logout

    );
  }
  return false;
};
ContentMenu.propTypes = {
  currentUser: currentUserProps,
  settingsOpener: PropTypes.func.isRequired
};

let SignedInMenu = ({currentUser, location, notifications, notificationCount}) => {
  let loggedIn = ! isEmpty(currentUser);
  if(loggedIn) {
    return (

Dashboard

        {!location.pathname.includes("revise") && !location.pathname.includes("edit") && !location.pathname.includes("extend") && !location.pathname.includes("new") && (currentUser.publisher || currentUser.author) &&

            Create

<Link to="/responseSets/new" tabIndex="2"><text className="sr-only">Click link to create new </text>Response Sets</Link>

<Link to="/questions/new" tabIndex="2"><text className="sr-only">Click link to create new </text>Questions</Link>

<Link to="/sections/new" tabIndex="2"><text className="sr-only">Click link to create new </text>Sections</Link>

<Link to="/surveys/new" tabIndex="2"><text className="sr-only">Click link to create new </text>Surveys</Link>

<Link to="/surveys/import" tabIndex="2"><text className="sr-only">Click link to </text>Import Spreadsheet</Link>

        }

          <NotificationDropdown notifications={notifications} notificationCount={notificationCount} />
          { notificationCount > 0 ? (
            <NotificationMenu notifications={notifications} />
          ) : (

No new notifications

          )}

    );
  }
  return null;
};
SignedInMenu.propTypes = {
  currentUser: currentUserProps,
  location: PropTypes.object,
  notifications: PropTypes.arrayOf(PropTypes.object),
  notificationCount: PropTypes.number
};

class Header extends Component {
  constructor(props){
    super(props);
    this.state={
      joyrideOverlay: false,
      joyrideType: 'continuous',
      isReady: false,
      isRunning: false,
      stepIndex: 0,
      steps: [],
      selector: ''
    };
    this.renderJoyride = this.renderJoyride.bind(this);
    this.addSteps = this.addSteps.bind(this);
  }

  componentWillMount() {
    this.props.fetchNotifications();
  }

  componentDidMount() {
    this.addSteps(this.props.steps);
    setTimeout(() => {
      this.setState({
        isReady: true,
        isRunning: false,
      });
    }, 1000);
  }

  addSteps(steps) {
    let newSteps = steps;
    if (!Array.isArray(newSteps)) {
      newSteps = [newSteps];
    }
    if (!newSteps.length) {
      return;
    }

    this.setState(currentState => {
      currentState.steps = currentState.steps.concat(newSteps);
      return currentState;
    });
  }

  renderJoyride(isReady, isRunning, joyrideOverlay, joyrideType, selector, stepIndex) {
    return (
      <Joyride
        ref={c => (this.joyride = c)}
        debug={false}
        locale={{
          back: (Back),
          close: (Close),
          last: (End),
          next: (Next),
          skip: (Exit Tutorial),
        }}
        autoStart={true}
        run={isRunning}
        showOverlay={joyrideOverlay}
        showSkipButton={true}
        showStepsProgress={true}
        stepIndex={stepIndex}
        steps={this.props.steps}
        type={joyrideType}
        tooltipOffset={0}
        keyboardNavigation={false}
      />
    );
  }

  render() {
    const {
      isReady,
      isRunning,
      joyrideOverlay,
      joyrideType,
      selector,
      stepIndex,
    } = this.state;

    return (

          {isReady &&
{this.renderJoyride(isReady, isRunning, joyrideOverlay, joyrideType, selector, stepIndex)}
}

            <button type="button" className="cdc-navbar-toggle collapsed" data-toggle="collapse" data-target="#cdcnav" aria-expanded="false" tabIndex="2">
              Toggle navigation
              Toggle navigation
            </button>
            <Link to="/" className="cdc-brand" tabIndex="2">CDC Vocabulary Service</Link>

            <SignedInMenu currentUser={this.props.currentUser} location={this.props.location} notifications={this.props.notifications} notificationCount={this.props.notificationCount} />

              <ContentMenu currentUser={this.props.currentUser} settingsOpener={this.props.settingsOpener} />
              <LoginMenu currentUser={this.props.currentUser} logInOpener={this.props.logInOpener} signUpOpener={this.props.signUpOpener} disableUserRegistration={this.props.disableUserRegistration}/>

                Help

<Link to='/Help' tabIndex="2">Help Documentation</Link>

                  {isReady && this.props.steps.length > 0 &&

 {
                      e.preventDefault();
                      return this.joyride.reset(true);
                    }}>Step-by-Step Walkthrough

                  }

 gaSend('send', 'pageview', window.location.toString() + '/Swagger API')}>Swagger API

<Link to="/fhirDoc" tabIndex="2" onClick={() => gaSend('send', 'pageview', window.location.toString() + '/FHIR Documentation')}>FHIR Documentation</Link>

<Link to={{ pathname: '/Help', state: {selectedTab: 'whatsnew'} }}  onClick={() => gaSend('send', 'pageview', window.location.toString() + '/whats New')}>What‘s New</Link>

 gaSend('send', 'pageview', window.location.toString() + '/Contact Us')}>Contact Us

Release: v{this.props.appVersion}

    );
  }
}

function mapStateToProps(state) {
  return {
    notifications: state.notifications,
    currentUser: state.currentUser,
    steps: state.tutorialSteps,
    notificationCount: state.notifications.length
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({fetchNotifications}, dispatch);
}

Header.propTypes = {
  currentUser: currentUserProps,
  steps: PropTypes.array,
  location: PropTypes.object,
  appVersion: PropTypes.string,
  notifications: PropTypes.arrayOf(PropTypes.object),
  notificationCount: PropTypes.number,
  fetchNotifications: PropTypes.func,
  logInOpener: PropTypes.func.isRequired,
  signUpOpener: PropTypes.func.isRequired,
  settingsOpener: PropTypes.func.isRequired,
  disableUserRegistration: PropTypes.bool.isRequired
};

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


<commit_before>import React, { Component } from "react";
import { connect } from "react-redux";

import { setValue, clearValues } from "@appbaseio/reactivecore/lib/actions";
import types from "@appbaseio/reactivecore/lib/utils/types";
import Button, { filters } from "../../styles/Button";

class SelectedFilters extends Component {
	remove = (component) => {
		this.props.setValue(component, null);
	};

	renderValue = (value, isArray) => {
		if (isArray) {
			return value.join(", ");
		}
		return value;
	}

	render() {
		const { selectedValues } = this.props;
		let hasValues = false;

		return (

			{
				Object.keys(selectedValues)
					.filter(id => this.props.components.includes(id) && selectedValues[id].showFilter)
					.map((component, index) => {
						const { label, value } = selectedValues[component];
						const isArray = Array.isArray(value);

						if (label && (isArray && value.length) || (!isArray && value)) {
							hasValues = true;
							return (<Button key={`${component}-${index}`} onClick={() => this.remove(component)}>
								{selectedValues[component].label}: {this.renderValue(value, isArray)}
								✕
							</Button>);
						}
						return null;
					})
			}
			{
				hasValues
					? <Button onClick={this.props.clearValues}>Clear all filters</Button>
					: null
			}

)
	}
}

SelectedFilters.propTypes = {
	selectedValues: types.selectedValues,
	setValue: types.setValue,
	clearValues: types.clearValues,
	components: types.components
};

const mapStateToProps = state => ({
	selectedValues: state.selectedValues,
	components: state.components
});

const mapDispatchtoProps = dispatch => ({
	setValue: (component, value) => dispatch(setValue(component, value)),
	clearValues: () => (dispatch(clearValues()))
});

export default connect(mapStateToProps, mapDispatchtoProps)(SelectedFilters);
<commit_msg>upgrade SelectedFilters to support arbitrary value types<commit_after>import React, { Component } from "react";
import { connect } from "react-redux";

import { setValue, clearValues } from "@appbaseio/reactivecore/lib/actions";
import types from "@appbaseio/reactivecore/lib/utils/types";
import Button, { filters } from "../../styles/Button";

class SelectedFilters extends Component {
	remove = (component) => {
		this.props.setValue(component, null);
	};

	renderValue = (value, isArray) => {
		if (isArray && value.length) {
			const arrayToRender = value.map(item => this.renderValue(item));
			return arrayToRender.join(", ");
		} else if (typeof value === "object") {
			// TODO: support for NestedList
			if (value.label || value.key) {
				return value.label || value.key;
			}
			return null;
		}
		return value;
	}

	render() {
		const { selectedValues } = this.props;
		let hasValues = false;

		return (

			{
				Object.keys(selectedValues)
					.filter(id => this.props.components.includes(id) && selectedValues[id].showFilter)
					.map((component, index) => {
						const { label, value } = selectedValues[component];
						const isArray = Array.isArray(value);

						if (label && (isArray && value.length) || (!isArray && value)) {
							hasValues = true;
							return (<Button key={`${component}-${index}`} onClick={() => this.remove(component)}>
								{selectedValues[component].label}: {this.renderValue(value, isArray)}
								✕
							</Button>);
						}
						return null;
					})
			}
			{
				hasValues
					? <Button onClick={this.props.clearValues}>Clear all filters</Button>
					: null
			}

)
	}
}

SelectedFilters.propTypes = {
	selectedValues: types.selectedValues,
	setValue: types.setValue,
	clearValues: types.clearValues,
	components: types.components
};

const mapStateToProps = state => ({
	selectedValues: state.selectedValues,
	components: state.components
});

const mapDispatchtoProps = dispatch => ({
	setValue: (component, value) => dispatch(setValue(component, value)),
	clearValues: () => (dispatch(clearValues()))
});

export default connect(mapStateToProps, mapDispatchtoProps)(SelectedFilters);
<|endoftext|>


<commit_before>var plugins = require("ep_etherpad-lite/static/js/pluginfw/plugins");
var _;

/* FIXME: Ugly hack, in the future, use same code for server & client */
if (plugins.isClient) {
  var async = require("ep_etherpad-lite/static/js/pluginfw/async");
  _ = require("ep_etherpad-lite/static/js/underscore");
} else {
  var async = require("async");
  _ = require("underscore");
}

exports.bubbleExceptions = true

var hookCallWrapper = function (hook, hook_name, args, cb) {
  if (cb === undefined) cb = function (x) { return x; };
  if (exports.bubbleExceptions) {
    return hook.hook_fn(hook_name, args, cb);
  } else {
    try {
      return hook.hook_fn(hook_name, args, cb);
    } catch (ex) {
      console.error([hook_name, hook.part.full_name, ex.stack || ex]);
    }
  }
}

/* Don't use Array.concat as it flatterns arrays within the array */
exports.flatten = function (lst) {
  var res = [];
  if (lst != undefined && lst != null) {
    for (var i = 0; i < lst.length; i++) {
      if (lst[i] != undefined && lst[i] != null) {
        for (var j = 0; j < lst[i].length; j++) {
          res.push(lst[i][j]);
	}
      }
    }
  }
  return res;
}

exports.callAll = function (hook_name, args) {
  if (!args) args = {};
  if (plugins.hooks[hook_name] === undefined) return [];
  return exports.flatten(_.map(plugins.hooks[hook_name], function (hook) {
    return hookCallWrapper(hook, hook_name, args);
  }));
}

exports.aCallAll = function (hook_name, args, cb) {
  if (!args) args = {};
  if (!cb) cb = function () {};
  if (plugins.hooks[hook_name] === undefined) return cb(null, []);
  async.map(
    plugins.hooks[hook_name],
    function (hook, cb) {
      hookCallWrapper(hook, hook_name, args, function (res) { cb(null, res); });
    },
    function (err, res) {
      cb(null, exports.flatten(res));
    }
  );
}

exports.callFirst = function (hook_name, args) {
  if (!args) args = {};
  if (plugins.hooks[hook_name][0] === undefined) return [];
  return exports.flatten(hookCallWrapper(plugins.hooks[hook_name][0], hook_name, args));
}

exports.aCallFirst = function (hook_name, args, cb) {
  if (!args) args = {};
  if (!cb) cb = function () {};
  if (plugins.hooks[hook_name][0] === undefined) return cb(null, []);
    hookCallWrapper(plugins.hooks[hook_name][0], hook_name, args, function (res) { cb(null, exports.flatten(res)); });
}

exports.callAllStr = function(hook_name, args, sep, pre, post) {
  if (sep == undefined) sep = '';
  if (pre == undefined) pre = '';
  if (post == undefined) post = '';
  var newCallhooks = [];
  var callhooks = exports.callAll(hook_name, args);
  for (var i = 0, ii = callhooks.length; i < ii; i++) {
    newCallhooks[i] = pre + callhooks[i] + post;
  }
  return newCallhooks.join(sep || "");
}
<commit_msg>Bugfix for callFirst to actually call call hooks until it finds one that returns non-empty, which is actually usefull, as opposed to just calling one hook.<commit_after>var plugins = require("ep_etherpad-lite/static/js/pluginfw/plugins");
var _;

/* FIXME: Ugly hack, in the future, use same code for server & client */
if (plugins.isClient) {
  var async = require("ep_etherpad-lite/static/js/pluginfw/async");
  var _ = require("ep_etherpad-lite/static/js/underscore");
} else {
  var async = require("async");
  var _ = require("underscore");
}

exports.bubbleExceptions = true

var hookCallWrapper = function (hook, hook_name, args, cb) {
  if (cb === undefined) cb = function (x) { return x; };

  // Normalize output to list for both sync and async cases
  var normalize = function(x) {
    if (x == undefined) return [];
    return x;
  }
  var normalizedhook = function () {
    return normalize(hook.hook_fn(hook_name, args, function (x) {
      return cb(normalize(x));
    }));
  }

  if (exports.bubbleExceptions) {
      return normalizedhook();
  } else {
    try {
      return normalizedhook();
    } catch (ex) {
      console.error([hook_name, hook.part.full_name, ex.stack || ex]);
    }
  }
}

exports.syncMapFirst = function (lst, fn) {
  var i;
  var result;
  for (i = 0; i < lst.length; i++) {
    result = fn(lst[i])
    if (result.length) return result;
  }
  return undefined;
}

exports.mapFirst = function (lst, fn, cb) {
  var i = 0;

  next = function () {
    if (i >= lst.length) return cb(undefined);
    fn(lst[i++], function (err, result) {
      if (err) return cb(err);
      if (result.length) return cb(null, result);
      next();
    });
  }
  next();
}

/* Don't use Array.concat as it flatterns arrays within the array */
exports.flatten = function (lst) {
  var res = [];
  if (lst != undefined && lst != null) {
    for (var i = 0; i < lst.length; i++) {
      if (lst[i] != undefined && lst[i] != null) {
        for (var j = 0; j < lst[i].length; j++) {
          res.push(lst[i][j]);
	}
      }
    }
  }
  return res;
}

exports.callAll = function (hook_name, args) {
  if (!args) args = {};
  if (plugins.hooks[hook_name] === undefined) return [];
  return _.flatten(_.map(plugins.hooks[hook_name], function (hook) {
    return hookCallWrapper(hook, hook_name, args);
  }), true);
}

exports.aCallAll = function (hook_name, args, cb) {
  if (!args) args = {};
  if (!cb) cb = function () {};
  if (plugins.hooks[hook_name] === undefined) return cb(null, []);
  async.map(
    plugins.hooks[hook_name],
    function (hook, cb) {
      hookCallWrapper(hook, hook_name, args, function (res) { cb(null, res); });
    },
    function (err, res) {
        cb(null, _.flatten(res, true));
    }
  );
}

exports.callFirst = function (hook_name, args) {
  if (!args) args = {};
  if (plugins.hooks[hook_name][0] === undefined) return [];
  return exports.syncMapFirst(plugins.hooks[hook_name], function (hook) {
    return hookCallWrapper(hook, hook_name, args);
  });
}

exports.aCallFirst = function (hook_name, args, cb) {
  if (!args) args = {};
  if (!cb) cb = function () {};
  if (plugins.hooks[hook_name] === undefined) return cb(null, []);
  exports.mapFirst(
    plugins.hooks[hook_name],
    function (hook, cb) {
      hookCallWrapper(hook, hook_name, args, function (res) { cb(null, res); });
    },
    cb
  );
}

exports.callAllStr = function(hook_name, args, sep, pre, post) {
  if (sep == undefined) sep = '';
  if (pre == undefined) pre = '';
  if (post == undefined) post = '';
  var newCallhooks = [];
  var callhooks = exports.callAll(hook_name, args);
  for (var i = 0, ii = callhooks.length; i < ii; i++) {
    newCallhooks[i] = pre + callhooks[i] + post;
  }
  return newCallhooks.join(sep || "");
}
<|endoftext|>


<commit_before>(function(doc) {
    window.addEventListener("load", function apiOnDomReady() {

        var loading = doc.querySelector(".loading")
          , errorDiv = doc.querySelector(".error")
          , errorMessage = errorDiv.querySelector(".message")
          , input = location.search.replace(/^\?@?/g, "")
          ;

        if (!input) {
            return;
        }

        loading.classList.add("visible");

        var polyglot = new GitHubPolyglot(input)
          , func = polyglot.userStats
          ;

        if (polyglot.repo) {
            func = polyglot.repoStats
        }

        func.call(polyglot, function (err, stats) {
            loading.classList.remove("visible");
            if (err) {
                errorDiv.classList.add("visible");
                return errorMessage.textContent = err || "This user doesn't have any repositories.";
            }
            stats.sort(function (a, b) {
                return a.value < b.value ? 1 : -1;
            }).forEach(function (c) {
                c.title = c.label;
                delete c.label;
            });
            drawPieChart.call(doc.querySelector("#pieChart"), stats, {
                legend: true
            });
        });
    });
})(document);
<commit_msg>Added localstorage caching<commit_after>(function(doc) {
    window.addEventListener("load", function apiOnDomReady() {

        var loading = doc.querySelector(".loading")
          , errorDiv = doc.querySelector(".error")
          , errorMessage = errorDiv.querySelector(".message")
          , input = location.search.replace(/^\?@?/g, "")
          ;

        if (!input) {
            return;
        }

        loading.classList.add("visible");

        function getStats(input, callback) {

            var fromLocalStorage = localStorage[input];
            try {
                fromLocalStorage = JSON.parse(fromLocalStorage);
            } catch (e) {
                fromLocalStorage = null;
            }

            if (Array.isArray(fromLocalStorage)) {
                return callback(null, fromLocalStorage);
            }

            var polyglot = new GitHubPolyglot(input)
              , func = polyglot.userStats
              ;

            if (localStorage[input]) { return callback(null, localStorage[input]); }

            if (polyglot.repo) {
                func = polyglot.repoStats
            }

            func.call(polyglot, function (err, stats) {
                if (err) {
                    return callback(err);
                }

                try {
                    localStorage[input] = JSON.stringify(stats);
                } catch (e) {
                    localStorage.clear();
                }

                callback(null, stats);
            });
        }

        getStats(input, function (err, stats) {
            loading.classList.remove("visible");
            if (err) {
                errorDiv.classList.add("visible");
                return errorMessage.textContent = err || "This user doesn't have any repositories.";
            }
            stats.sort(function (a, b) {
                return a.value < b.value ? 1 : -1;
            }).forEach(function (c) {
                c.title = c.label;
                delete c.label;
            });
            drawPieChart.call(doc.querySelector("#pieChart"), stats, {
                legend: true
            });
        });
    });
})(document);
<|endoftext|>


<commit_before>var ServiceManager  = require('rotor-service-manager');
var Entity          = require('rotor-entity');
var _               = require('lodash');
var createCamera    = require('canvas-orbit-camera');

/**
 * Game skeleton, basic element in rotor-web engine.
 * @param {object} param
 * @constructor
 */
function Game(param) {
  if (Game._instance === null) {
    Game.prototype.init.apply(this, arguments);
    Game._instance = this;
  } else {
    return Game._instance;
  }
}

var proto = Game.prototype;

proto.init = function(param) {
  param = param || {};

  this.running = false;
  this.tabstop = param.tabstop;

  this._services = new ServiceManager(this);

  //The root of entities
  this._entities = new Entity({
    name: 'Root'
  });
  this._entities._game = this;

};

/**
 * Add entity to the game
 * @param entity
 */
proto.addEntity = function(entity) {
  this._entities.addChild(entity);
};

proto.removeEntity = function(entity) {
  this._entities.removeChild(entity);
};

proto.updateEntities = function() {
  this._entities.update();
};

proto.registerServices = function(serviceConfigs) {
  _.each(serviceConfigs, function(service) {
    this._services.registerService(service.type, service.constructor, service.config);
  }.bind(this));
};

proto.initializeServices = function(serviceList) {
  this._services.initializeServices(serviceList);

  //TODO: remove camera initialization from there
  var graphics = this.getServiceByType('Graphics');
  this.camera = createCamera(graphics._canvas);
};

proto.getServiceByType = function(type) {
  return this._services.getServiceByType(type);
};

proto.run = function() {
  this._entities.realize();
  this.running = true;
  this.loop();
};

proto.loop = function(time) {
  requestAnimationFrame(this.loop.bind(this));
  this.ServiceManager.update();
  this.camera.tick();
};

//static
Game._instance = null;
Game.getInstance = function() {
  return Game._instance;
};

module.exports = Game;
<commit_msg>Fix loop<commit_after>var ServiceManager  = require('rotor-service-manager');
var Entity          = require('rotor-entity');
var _               = require('lodash');
var createCamera    = require('canvas-orbit-camera');

/**
 * Game skeleton, basic element in rotor-web engine.
 * @param {object} param
 * @constructor
 */
function Game(param) {
  if (Game._instance === null) {
    Game.prototype.init.apply(this, arguments);
    Game._instance = this;
  } else {
    return Game._instance;
  }
}

var proto = Game.prototype;

proto.init = function(param) {
  param = param || {};

  this.running = false;
  this.tabstop = param.tabstop;

  this._services = new ServiceManager(this);

  //The root of entities
  this._entities = new Entity({
    name: 'Root'
  });
  this._entities._game = this;

};

/**
 * Add entity to the game
 * @param entity
 */
proto.addEntity = function(entity) {
  this._entities.addChild(entity);
};

proto.removeEntity = function(entity) {
  this._entities.removeChild(entity);
};

proto.updateEntities = function() {
  this._entities.update();
};

proto.registerServices = function(serviceConfigs) {
  _.each(serviceConfigs, function(service) {
    this._services.registerService(service.type, service.constructor, service.config);
  }.bind(this));
};

proto.initializeServices = function(serviceList) {
  this._services.initializeServices(serviceList);

  //TODO: remove camera initialization from there
  var graphics = this.getServiceByType('Graphics');
  this.camera = createCamera(graphics._canvas);
};

proto.getServiceByType = function(type) {
  return this._services.getServiceByType(type);
};

proto.run = function() {
  this._entities.realize();
  this.running = true;
  this.loop();
};

proto.loop = function(time) {
  requestAnimationFrame(this.loop.bind(this));
  this._services.update();
  this.camera.tick();
};

//static
Game._instance = null;
Game.getInstance = function() {
  return Game._instance;
};

module.exports = Game;
<|endoftext|>


<commit_before>goog.module('measurementLibrary.storage.CookiesStorage');

/**
 * An implementation of StorageInterface that uses cookies for storage.
 * @implements {StorageInterface}
 */
class CookiesStorage {
  /** @param {!Object.<string, string|number|boolean>} settings an object
   *      holding the settings to be set on this instance of CookiesStorage.
   */
  constructor(settings) {
    /** @private @const {!Object.<string, string|number|boolean>}*/
    this.settings_ = settings;

    this.setDefaults_();
  }

  /**
   * Helps the constructor set the default for any omitted settings.
   * @private
   */
  setDefaults_() {
    if (!this.settings_['domain']) {
      this.settings_['domain'] = this.findAutoDomain_(document);
    }
    if (this.settings_['expires'] == undefined) {
      // 28 days in seconds, default expiry time.
      const defaultTime = 28 * 24 * 60 * 60;
      this.settings_['expires'] = defaultTime;
    }
    if (!this.settings_['prefix']) {
      // ml for measurement library. should be discussed.
      const defaultPrefix = 'ml_';
      this.settings_['prefix'] = defaultPrefix;
    }
    if (!this.settings_['update']) {
      const defaultUpdate = true;
      this.settings_['update'] = defaultUpdate;
    }
    if (!this.settings_['flags']) {
      const defaultFlags = '';
      this.settings_['flags'] = defaultFlags;
    }
  }

  /**
   * Finds the registrable domain of current URL and sets it as the default
   *    domain for cookies
   * @param {!document} document the document whose cookies are to be set.
   * @return {?string} the registrable domain of docDomain
   * @private
   */
  findAutoDomain_(document) {
    const oldCookies = document.cookie;
    const domainArray = document.domain.split('.');
    let domain = domainArray.pop();
    const newCookie = `registrable_domain=${domain};domain=${domain}`;
    document.cookie = newCookie;

    while (document.cookie === oldCookies && domainArray.length > 0) {
      domain = `${domainArray.pop() }.${ domain }`;
      const newCookie = `registrable_domain=${ domain };domain=${ domain }`;
      document.cookie = newCookie;
    }

    if (document.cookie === oldCookies) {
      return null;
    }

    // Since the cookie was updated with a dummy value, remove it by setting
    // expiry to a date in the past.
    const pastDate = "Thu, 01 Jan 1970 00:00:00 GMT";
    document.cookie =
      `registrable_domain=;domain=${domain};expires=${pastDate}`;

    return domain;
  }

  /** @override */
  save(key, value, secondsToLive) {}

  /** @override */
  load(key, defaultValue) {}
}

exports = CookiesStorage;
<commit_msg>Update CookiesInterface.js<commit_after>goog.module('measurementLibrary.storage.CookiesStorage');

/**
 * An implementation of StorageInterface that uses cookies for storage.
 * @implements {StorageInterface}
 */
class CookiesStorage {
  /**
   * @param {!Object.<string, string|number|boolean>} settings an object
   *     holding the settings to be set on this instance of CookiesStorage.
   */
  constructor(settings) {
    /** @private @const {!Object.<string, string|number|boolean>}*/
    this.settings_ = settings;

    this.setDefaults_();
  }

  /**
   * Helps the constructor set the default for any omitted settings.
   * @private
   */
  setDefaults_() {
    if (!this.settings_['domain']) {
      this.settings_['domain'] = this.findAutoDomain_(document);
    }
    if (this.settings_['expires'] == undefined) {
      // 28 days in seconds, default expiry time.
      const defaultTime = 28 * 24 * 60 * 60;
      this.settings_['expires'] = defaultTime;
    }
    if (!this.settings_['prefix']) {
      // ml for measurement library. should be discussed.
      const defaultPrefix = 'ml_';
      this.settings_['prefix'] = defaultPrefix;
    }
    if (!this.settings_['update']) {
      const defaultUpdate = true;
      this.settings_['update'] = defaultUpdate;
    }
    if (!this.settings_['flags']) {
      const defaultFlags = '';
      this.settings_['flags'] = defaultFlags;
    }
  }

  /**
   * Finds the registrable domain of current URL and sets it as the default
   *    domain for cookies
   * @param {!document} document the document whose cookies are to be set.
   * @return {?string} the registrable domain of docDomain
   * @private
   */
  findAutoDomain_(document) {
    const oldCookies = document.cookie;
    const domainArray = document.domain.split('.');
    let domain = domainArray.pop();
    const newCookie = `registrable_domain=${domain};domain=${domain}`;
    document.cookie = newCookie;

    while (document.cookie === oldCookies && domainArray.length > 0) {
      domain = `${domainArray.pop() }.${ domain }`;
      const newCookie = `registrable_domain=${ domain };domain=${ domain }`;
      document.cookie = newCookie;
    }

    if (document.cookie === oldCookies) {
      return null;
    }

    // Since the cookie was updated with a dummy value, remove it by setting
    // expiry to a date in the past.
    const pastDate = "Thu, 01 Jan 1970 00:00:00 GMT";
    document.cookie =
      `registrable_domain=;domain=${domain};expires=${pastDate}`;

    return domain;
  }

  /** @override */
  save(key, value, secondsToLive) {}

  /** @override */
  load(key, defaultValue) {}
}

exports = CookiesStorage;
<|endoftext|>