<commit_before>/*
 * xWeb (v1.0) by EvolSoft
 * Developer: EvolSoft (Flavius12)
 * Website: http://www.evolsoft.tk
 * Date: 11/05/2015 06:15 PM (UTC)
 * Copyright & License: (C) 2015 EvolSoft
 * Licensed under MIT (https://github.com/EvolSoft/xWeb/blob/master/LICENSE)
 */

function changeTitle(e){checkElement("title")?$("title").text(e):$("head").append("<title>"+e+"</title>")}function checkElement(e){return $(e).length}function getVersion(){return XWEB_VERSION}function pxtoint(e){return parseInt(e.replace("px",""))}function initializeImageSlider(e){$(e).hasClass("image-slider")&&(ImageItem=$(e).find(".image-slider-images").children(".image-slider-item"),activeImageItem=$(e).find(".image-slider-images").children(".image-slider-item.active"),$(e).trigger("image-slider.initialize"),activeImageItem.length>0?(activeImageItem.css("margin-left","0%"),activeImageItem.prevAll().css("margin-left","-100%"),activeImageItem.nextAll().css("margin-left","100%"),$(e).find(".image-slider-navigation").find("[img-id='"+activeImageItem.attr("img-item")+"']").addClass("active")):(ImageItem.first().addClass("active"),ImageItem.nextAll().css("margin-left","100%"),$(e).find(".image-slider-navigation").find("[img-id='"+ImageItem.attr("img-item")+"']").addClass("active")))}function slideLeft(e){$(e).hasClass("image-slider")&&(parent=$(e).find(".image-slider-images").children(".image-slider-item"),activeParent=$(e).find(".image-slider-images").children(".image-slider-item.active"),$(e).trigger("image-slider.slide"),activeParent.prev().length>0?(parent.removeClass("active"),activeParent.prev().addClass("active"),activeParent.css("margin-left","0%"),activeParent.prev().css("margin-left","-100%"),activeParent.animate({"margin-left":"100%"},200),activeParent.prev().animate({"margin-left":"0%"},200),$(e).find(".image-slider-navigation").children("li").removeClass("active"),$(e).find(".image-slider-navigation").find("[img-id='"+activeParent.prev().attr("img-item")+"']").addClass("active")):(parent.removeClass("active"),parent.last().addClass("active"),activeParent.css("margin-left","0%"),parent.last().css("margin-left","-100%"),activeParent.animate({"margin-left":"100%"},200),parent.last().animate({"margin-left":"0%"},200),$(e).find(".image-slider-navigation").children("li").removeClass("active"),$(e).find(".image-slider-navigation").find("[img-id='"+parent.last().attr("img-item")+"']").addClass("active")))}function slideLeftPos(e,t){$(e).hasClass("image-slider")&&$(e).find(".image-slider-images").children("[img-item='"+t+"']")&&(parent=$(e).find(".image-slider-images").children(".image-slider-item"),parent.removeClass("active"),$(e).find(".image-slider-images").children("[img-item='"+t+"']").addClass("active"),initializeImageSlider(e),activeParent=$(e).find(".image-slider-images").children(".image-slider-item.active"),$(e).trigger("image-slider.slide"),activeParent.prev().length>0?(activeParent.prev().css("margin-left","0%"),activeParent.css("margin-left","100%"),activeParent.animate({"margin-left":"0%"},200),activeParent.prev().animate({"margin-left":"-100%"},200),$(e).find(".image-slider-navigation").children("li").removeClass("active"),$(e).find(".image-slider-navigation").find("[img-id='"+activeParent.attr("img-item")+"']").addClass("active")):(activeParent.css("margin-left","100%"),parent.last().css("margin-left","0%"),activeParent.animate({"margin-left":"0%"},200),parent.last().animate({"margin-left":"-100%"},200),$(e).find(".image-slider-navigation").children("li").removeClass("active"),$(e).find(".image-slider-navigation").find("[img-id='"+activeParent.attr("img-item")+"']").addClass("active")))}function slideRight(e){$(e).hasClass("image-slider")&&(parent=$(e).find(".image-slider-images").children(".image-slider-item"),activeParent=$(e).find(".image-slider-images").children(".image-slider-item.active"),$(e).trigger("image-slider.slide"),activeParent.next().length>0?(parent.removeClass("active"),activeParent.next().addClass("active"),activeParent.css("margin-left","0%"),activeParent.next().css("margin-left","100%"),activeParent.animate({"margin-left":"-100%"},200),activeParent.next().animate({"margin-left":"0%"},200),$(e).find(".image-slider-navigation").children("li").removeClass("active"),$(e).find(".image-slider-navigation").find("[img-id='"+activeParent.next().attr("img-item")+"']").addClass("active")):(parent.removeClass("active"),parent.first().addClass("active"),activeParent.css("margin-left","0%"),parent.first().css("margin-left","100%"),activeParent.animate({"margin-left":"-100%"},200),parent.first().animate({"margin-left":"0%"},200),$(e).find(".image-slider-navigation").children("li").removeClass("active"),$(e).find(".image-slider-navigation").find("[img-id='"+parent.first().attr("img-item")+"']").addClass("active")))}function slideRightPos(e,t){$(e).hasClass("image-slider")&&$(e).find(".image-slider-images").children("[img-item='"+t+"']")&&(parent=$(e).find(".image-slider-images").children(".image-slider-item"),parent.removeClass("active"),$(e).find(".image-slider-images").children("[img-item='"+t+"']").addClass("active"),initializeImageSlider(e),activeParent=$(e).find(".image-slider-images").children(".image-slider-item.active"),$(e).trigger("image-slider.slide"),activeParent.next().length>0?(activeParent.next().css("margin-left","0%"),activeParent.css("margin-left","-100%"),activeParent.animate({"margin-left":"0%"},200),activeParent.next().animate({"margin-left":"100%"},200),$(e).find(".image-slider-navigation").children("li").removeClass("active"),$(e).find(".image-slider-navigation").find("[img-id='"+activeParent.attr("img-item")+"']").addClass("active")):(activeParent.css("margin-left","-100%"),parent.first().css("margin-left","0%"),activeParent.animate({"margin-left":"0%"},200),parent.first().animate({"margin-left":"100%"},200),$(e).find(".image-slider-navigation").children("li").removeClass("active"),$(e).find(".image-slider-navigation").find("[img-id='"+activeParent.attr("img-item")+"']").addClass("active")))}function toggleModal(e){$(e).hasClass("modal")&&($(e).toggleClass("modal-open"),$(e).trigger($(e).hasClass("modal-open")?"modal.open":"modal.close"))}function closeModal(e){$(e).hasClass("modal")&&($(e).trigger("modal.close"),$(e).removeClass("modal-open"),$(e).addClass("closing"),$(e).on("transitionend",function(){$(this).removeClass("closing")}))}function getRSliderVal(e){return $(e).hasClass("slider")?(percentage=percent=Math.round(100*pxtoint($(e).find(".slider-handle").css("left"))/pxtoint($(e).css("width"))),percentage):null}var XWEB_VERSION="1.0";$(document).on("click",".close",function(){$(this).parent().hasClass("alert")&&($(this).parent().trigger("alert.close"),$(this).parent().remove())}),$(document).on("click","[alert-close]",function(){$(this).parent().hasClass("alert")&&($(this).parent().trigger("alert.close"),$(this).parent().remove())}),$(document).ready(function(){$(".image-slider").each(function(){initializeImageSlider(this)}),setInterval(function(){$("[auto-scroll]").each(function(){$(this).hasClass("image-slider")&&slideRight(this)})},4e3)}),$(document).on("click",".image-slider-control-left",function(){slideLeft($(event.target).parent())}),$(document).on("click",".image-slider-control-right",function(){slideRight($(event.target).parent())}),$(document).on("click",".image-slider > .image-slider-navigation > li",function(){$(event.target).hasClass("active")||($(event.target).nextAll().hasClass("active")?slideRightPos($(event.target).parent().parent(),$(this).attr("img-id")):slideLeftPos($(event.target).parent().parent(),$(this).attr("img-id")))}),$(document).on("click",function(){var e=event.target;$(e).parent().hasClass("open")&&$(e).parent().hasClass("menu-group")?($(".menu-group").removeClass("open"),$(e).parent().trigger("menu.close")):$(e).parent().hasClass("menu-group")&&""==$(e).attr("openmenu")?($(".menu-group").removeClass("open"),$(e).parent().toggleClass("open"),$(e).parent().trigger("menu.open")):($(".menu-group").each(function(){$(this).hasClass("open")&&$(this).trigger("menu.close")}),$(".menu-group").removeClass("open"))}),$(document).on("click",".close",function(){$(this).parent().parent().hasClass("modal")&&closeModal($(this).parent().parent())}),$(document).on("click",".modal-background",function(){$(this).parent().hasClass("modal")&&("false"==$(this).parent().attr("static")||"undefined"==typeof $(this).parent().attr("static"))&&closeModal($(this).parent())}),$(document).on("click",".navbar-toggle",function(){$(this).parent().hasClass("navbar")&&$(this).parent().find(".navbar-links").toggleClass("open")});var click=!1,current=null,pos=0;$(document).on("mousedown",function(){click=!0,current=event.target}),$(document).on("mouseup",function(){click=!1,current=null}),$(document).on("mousemove",function(e){click&&null!=current&&"slider-handle"==$(current).attr("class")&&(fixedpos=e.pageX-$(current).parent().offset().left,percent=Math.round(100*fixedpos/pxtoint($(current).parent().css("width"))),e.pageX>pos?fixedpos>=0&&fixedpos<=$(current).parent().width()&&($(current).css("left",+percent+"%"),$(current).parent().find(".slider-progress").css("width",percent+1+"%"),$(current).parent().trigger("slider.change")):fixedpos>=0&&fixedpos<=$(current).parent().width()&&($(current).css("left",+percent+"%"),$(current).parent().find(".slider-progress").css("width",percent+1+"%"),$(current).parent().trigger("slider.change"))),pos=e.pageX}),$(document).on("click","a",function(){$(this).parent().parent().hasClass("tabs")&&($(this).parent().parent().find("li").removeClass("active"),$(this).parent().addClass("active"),$(this).parent().parent().parent().find(".tab-content").css("display","none"),$(this).parent().parent().parent().find("[tab-id="+$(event.target).attr("open-tab")+"]").hasClass("tab-content")&&($(this).parent().parent().parent().find("[tab-id="+$(event.target).attr("open-tab")+"]").css("display","block"),$(this).parent().parent().parent().find("[tab-id="+$(event.target).attr("open-tab")+"]").trigger("tab.open")))}),$(document).on("mouseover",function(){$("[tooltip]").hover(function(){tooltip=$("[tooltip-id='"+$(event.target).attr("tooltip")+"']"),$(event.target).trigger("tooltip.show",[tooltip]),$(tooltip).css("visibility","visible"),$(tooltip).css("opacity","0.8"),$(tooltip).hasClass("tooltip-top")?($(tooltip).css("top",$(event.target).position().top-($(tooltip).outerHeight(!0)-pxtoint($(event.target).css("marginTop")))),$(tooltip).css("left",$(event.target).position().left+($(event.target).outerWidth(!0)/2-$(tooltip).outerWidth(!0)/2))):$(tooltip).hasClass("tooltip-bottom")?($(tooltip).css("top",$(event.target).position().top+($(event.target).outerHeight(!0)-pxtoint($(event.target).css("marginBottom")))),$(tooltip).css("left",$(event.target).position().left+($(event.target).outerWidth(!0)/2-$(tooltip).outerWidth(!0)/2))):$(tooltip).hasClass("tooltip-left")?($(tooltip).css("top",$(event.target).position().top+($(event.target).outerHeight(!0)/2-$(tooltip).outerHeight(!0)/2)),$(tooltip).css("left",$(event.target).position().left+pxtoint($(event.target).css("marginLeft"))-($(tooltip).outerWidth()+pxtoint($(tooltip).css("padding"))))):$(tooltip).hasClass("tooltip-right")&&($(tooltip).css("top",$(event.target).position().top+($(event.target).outerHeight(!0)/2-$(tooltip).outerHeight(!0)/2)),$(tooltip).css("left",$(event.target).position().left+$(event.target).outerWidth(!0)-pxtoint($(event.target).css("marginRight"))+pxtoint($(tooltip).css("padding"))))},function(){tooltip=$("[tooltip-id='"+$(event.target).attr("tooltip")+"']"),$(event.target).trigger("tooltip.hide",[tooltip]),$(tooltip).css("visibility","hidden"),$(tooltip).css("opacity","0")})});
<commit_msg>Update xWeb.min.js<commit_after>/*
 * xWeb (v1.0) by EvolSoft
 * Developer: EvolSoft (Flavius12)
 * Website: http://www.evolsoft.tk
 * Date: 24/06/2015 12:36 AM (UTC)
 * Copyright & License: (C) 2015 EvolSoft
 * Licensed under MIT (https://github.com/EvolSoft/xWeb/blob/master/LICENSE)
 */
function changeTitle(e){checkElement("title")?$("title").text(e):$("head").append("<title>"+e+"</title>")}function checkElement(e){return $(e).length}function getVersion(){return XWEB_VERSION}function pxtoint(e){return parseInt(e.replace("px",""))}function initializeImageSlider(e){if($(e).hasClass("image-slider")){var i=$(e).find(".image-slider-images").children(".image-slider-item"),t=$(e).find(".image-slider-images").children(".image-slider-item.active");$(e).trigger("image-slider.initialize"),t.length>0?(t.css("margin-left","0%"),t.prevAll().css("margin-left","-100%"),t.nextAll().css("margin-left","100%"),$(e).find(".image-slider-navigation").find("[img-id='"+t.attr("img-item")+"']").addClass("active")):(i.first().addClass("active"),i.nextAll().css("margin-left","100%"),$(e).find(".image-slider-navigation").find("[img-id='"+i.attr("img-item")+"']").addClass("active"))}}function slideLeft(e){if($(e).hasClass("image-slider")){var i=$(e).find(".image-slider-images").children(".image-slider-item"),t=$(e).find(".image-slider-images").children(".image-slider-item.active");$(e).trigger("image-slider.slide"),t.prev().length>0?(i.removeClass("active"),t.prev().addClass("active"),t.css("margin-left","0%"),t.prev().css("margin-left","-100%"),t.animate({"margin-left":"100%"},200),t.prev().animate({"margin-left":"0%"},200),$(e).find(".image-slider-navigation").children("li").removeClass("active"),$(e).find(".image-slider-navigation").find("[img-id='"+t.prev().attr("img-item")+"']").addClass("active")):(i.removeClass("active"),i.last().addClass("active"),t.css("margin-left","0%"),i.last().css("margin-left","-100%"),t.animate({"margin-left":"100%"},200),i.last().animate({"margin-left":"0%"},200),$(e).find(".image-slider-navigation").children("li").removeClass("active"),$(e).find(".image-slider-navigation").find("[img-id='"+i.last().attr("img-item")+"']").addClass("active"))}}function slideLeftPos(e,i){if($(e).hasClass("image-slider")&&$(e).find(".image-slider-images").children("[img-item='"+i+"']")){var t=$(e).find(".image-slider-images").children(".image-slider-item");t.removeClass("active"),$(e).find(".image-slider-images").children("[img-item='"+i+"']").addClass("active"),initializeImageSlider(e);var a=$(e).find(".image-slider-images").children(".image-slider-item.active");$(e).trigger("image-slider.slide"),a.prev().length>0?(a.prev().css("margin-left","0%"),a.css("margin-left","100%"),a.animate({"margin-left":"0%"},200),a.prev().animate({"margin-left":"-100%"},200),$(e).find(".image-slider-navigation").children("li").removeClass("active"),$(e).find(".image-slider-navigation").find("[img-id='"+a.attr("img-item")+"']").addClass("active")):(a.css("margin-left","100%"),t.last().css("margin-left","0%"),a.animate({"margin-left":"0%"},200),t.last().animate({"margin-left":"-100%"},200),$(e).find(".image-slider-navigation").children("li").removeClass("active"),$(e).find(".image-slider-navigation").find("[img-id='"+a.attr("img-item")+"']").addClass("active"))}}function slideRight(e){if($(e).hasClass("image-slider")){var i=$(e).find(".image-slider-images").children(".image-slider-item"),t=$(e).find(".image-slider-images").children(".image-slider-item.active");$(e).trigger("image-slider.slide"),t.next().length>0?(i.removeClass("active"),t.next().addClass("active"),t.css("margin-left","0%"),t.next().css("margin-left","100%"),t.animate({"margin-left":"-100%"},200),t.next().animate({"margin-left":"0%"},200),$(e).find(".image-slider-navigation").children("li").removeClass("active"),$(e).find(".image-slider-navigation").find("[img-id='"+t.next().attr("img-item")+"']").addClass("active")):(i.removeClass("active"),i.first().addClass("active"),t.css("margin-left","0%"),i.first().css("margin-left","100%"),t.animate({"margin-left":"-100%"},200),i.first().animate({"margin-left":"0%"},200),$(e).find(".image-slider-navigation").children("li").removeClass("active"),$(e).find(".image-slider-navigation").find("[img-id='"+i.first().attr("img-item")+"']").addClass("active"))}}function slideRightPos(e,i){if($(e).hasClass("image-slider")&&$(e).find(".image-slider-images").children("[img-item='"+i+"']")){var t=$(e).find(".image-slider-images").children(".image-slider-item");t.removeClass("active"),$(e).find(".image-slider-images").children("[img-item='"+i+"']").addClass("active"),initializeImageSlider(e);var a=$(e).find(".image-slider-images").children(".image-slider-item.active");$(e).trigger("image-slider.slide"),a.next().length>0?(a.next().css("margin-left","0%"),a.css("margin-left","-100%"),a.animate({"margin-left":"0%"},200),a.next().animate({"margin-left":"100%"},200),$(e).find(".image-slider-navigation").children("li").removeClass("active"),$(e).find(".image-slider-navigation").find("[img-id='"+a.attr("img-item")+"']").addClass("active")):(a.css("margin-left","-100%"),t.first().css("margin-left","0%"),a.animate({"margin-left":"0%"},200),t.first().animate({"margin-left":"100%"},200),$(e).find(".image-slider-navigation").children("li").removeClass("active"),$(e).find(".image-slider-navigation").find("[img-id='"+a.attr("img-item")+"']").addClass("active"))}}function toggleModal(e){$(e).hasClass("modal")&&($(e).toggleClass("modal-open"),$(e).trigger($(e).hasClass("modal-open")?"modal.open":"modal.close"))}function closeModal(e){$(e).hasClass("modal")&&($(e).trigger("modal.close"),$(e).removeClass("modal-open"),$(e).addClass("closing"),$(e).on("transitionend",function(){$(this).removeClass("closing")}))}function getRSliderVal(e){return $(e).hasClass("slider")?(percentage=percent=Math.round(100*pxtoint($(e).find(".slider-handle").css("left"))/pxtoint($(e).css("width"))),percentage):null}var XWEB_VERSION="1.0";$(document).on("click",".close",function(){$(this).parent().hasClass("alert")&&($(this).parent().trigger("alert.close"),$(this).parent().remove())}),$(document).on("click","[alert-close]",function(){$(this).parent().hasClass("alert")&&($(this).parent().trigger("alert.close"),$(this).parent().remove())}),$(document).ready(function(){$(".image-slider").each(function(){initializeImageSlider(this)}),setInterval(function(){$("[auto-scroll]").each(function(){$(this).hasClass("image-slider")&&slideRight(this)})},4e3)}),$(document).on("click",".image-slider-control-left",function(){var e=event.target||event.srcElement;slideLeft($(e).parent())}),$(document).on("click",".image-slider-control-right",function(){var e=event.target||event.srcElement;slideRight($(e).parent())}),$(document).on("click",".image-slider > .image-slider-navigation > li",function(){var e=event.target||event.srcElement;$(e).hasClass("active")||($(event.target).nextAll().hasClass("active")?slideRightPos($(e).parent().parent(),$(this).attr("img-id")):slideLeftPos($(e).parent().parent(),$(this).attr("img-id")))}),$(document).on("click",function(){var e=event.target||event.srcElement;$(e).is("[openmenu]")||(e=$(e).parent()),$(e).parent().hasClass("open")&&$(e).parent().hasClass("menu-group")?($(".menu-group").removeClass("open"),$(e).parent().trigger("menu.close")):$(e).parent().hasClass("menu-group")&&""==$(e).attr("openmenu")?($(".menu-group").removeClass("open"),$(e).parent().toggleClass("open"),$(e).parent().trigger("menu.open")):($(".menu-group").each(function(){$(this).hasClass("open")&&$(this).trigger("menu.close")}),$(".menu-group").removeClass("open"))}),$(document).on("click",".close",function(){$(this).parent().parent().hasClass("modal")&&closeModal($(this).parent().parent())}),$(document).on("click",".modal-background",function(){$(this).parent().hasClass("modal")&&("false"==$(this).parent().attr("static")||"undefined"==typeof $(this).parent().attr("static"))&&closeModal($(this).parent())}),$(document).on("click",".navbar-toggle",function(){$(this).parent().hasClass("navbar")&&$(this).parent().find(".navbar-links").toggleClass("open")});var click=!1,current=null,pos=0;$(document).on("mousedown",function(){click=!0,current=event.target||event.srcElement}),$(document).on("mouseup",function(){click=!1,current=null}),$(document).on("mousemove",function(e){click&&null!=current&&"slider-handle"==$(current).attr("class")&&(fixedpos=e.pageX-$(current).parent().offset().left,percent=Math.round(100*fixedpos/pxtoint($(current).parent().css("width"))),e.pageX>pos?fixedpos>=0&&fixedpos<=$(current).parent().width()&&($(current).css("left",+percent+"%"),$(current).parent().find(".slider-progress").css("width",percent+1+"%"),$(current).parent().trigger("slider.change")):fixedpos>=0&&fixedpos<=$(current).parent().width()&&($(current).css("left",+percent+"%"),$(current).parent().find(".slider-progress").css("width",percent+1+"%"),$(current).parent().trigger("slider.change"))),pos=e.pageX}),$(document).on("click","a",function(){var e=event.target||event.srcElement;$(this).parent().parent().hasClass("tabs")&&($(this).parent().parent().find("li").removeClass("active"),$(this).parent().addClass("active"),$(this).parent().parent().parent().find(".tab-content").css("display","none"),$(this).parent().parent().parent().find("[tab-id="+$(e).attr("open-tab")+"]").hasClass("tab-content")&&($(this).parent().parent().parent().find("[tab-id="+$(e).attr("open-tab")+"]").css("display","block"),$(this).parent().parent().parent().find("[tab-id="+$(e).attr("open-tab")+"]").trigger("tab.open")))}),$(document).on("mouseover",function(){$("[tooltip]").hover(function(){var e=event.target||event.srcElement;tooltip=$("[tooltip-id='"+$(e).attr("tooltip")+"']"),$(e).trigger("tooltip.show",[tooltip]),$(tooltip).css("visibility","visible"),$(tooltip).css("opacity","0.8"),$(tooltip).hasClass("tooltip-top")?($(tooltip).css("top",$(e).position().top-($(tooltip).outerHeight(!0)-pxtoint($(e).css("marginTop")))),$(tooltip).css("left",$(e).position().left+($(e).outerWidth(!0)/2-$(tooltip).outerWidth(!0)/2))):$(tooltip).hasClass("tooltip-bottom")?($(tooltip).css("top",$(e).position().top+($(e).outerHeight(!0)-pxtoint($(e).css("marginBottom")))),$(tooltip).css("left",$(e).position().left+($(e).outerWidth(!0)/2-$(tooltip).outerWidth(!0)/2))):$(tooltip).hasClass("tooltip-left")?($(tooltip).css("top",$(e).position().top+($(e).outerHeight(!0)/2-$(tooltip).outerHeight(!0)/2)),$(tooltip).css("left",$(e).position().left+pxtoint($(e).css("marginLeft"))-($(tooltip).outerWidth()+pxtoint($(tooltip).css("padding"))))):$(tooltip).hasClass("tooltip-right")&&($(tooltip).css("top",$(e).position().top+($(e).outerHeight(!0)/2-$(tooltip).outerHeight(!0)/2)),$(tooltip).css("left",$(e).position().left+$(e).outerWidth(!0)-pxtoint($(e).css("marginRight"))+pxtoint($(tooltip).css("padding"))))},function(){var e=event.target||event.srcElement;tooltip=$("[tooltip-id='"+$(e).attr("tooltip")+"']"),$(e).trigger("tooltip.hide",[tooltip]),$(tooltip).css("visibility","hidden"),$(tooltip).css("opacity","0")})});
<|endoftext|>


<commit_before>// @flow

import {Platform} from 'react-native'
import {
	createBottomTabNavigator,
	NavigationScreenRouteConfig,
} from 'react-navigation'
import {getTheme} from '@frogpond/app-theme'
import {createMaterialBottomTabNavigator} from 'react-navigation-material-bottom-tabs'

type ComponentType = (
	screens: {[key: string]: NavigationScreenRouteConfig},
	options: any, // I don't know how to type this better…
	// the package provides a bunch of types… but it doesn't even use some
	// of them??? and none seem to be the combination of args to the second
	// arg of TabNavigator.
) => typeof createTabNavigator

const createTabNavigator =
	Platform.OS === 'android'
		? createMaterialBottomTabNavigator
		: createBottomTabNavigator

export const TabNavigator: ComponentType = (screens, options = {}) => {
	let theme = getTheme()

	return createTabNavigator(screens, {
		defaultNavigationOptions: {
			backBehavior: 'none',
			lazy: true,
			theme: {
				colors: {
					primary: theme.androidTabBarBackground,
				},
			},
			activeTintColor: theme.androidTabBarForeground,
			...(options.defaultNavigationOptions || {}),
		},
		tabBarOptions: {
			activeTintColor: theme.iosTabBarActiveColor,
			...(options.tabBarOptions || {}),
			labelStyle: {
				...Platform.select({
					ios: {
						fontFamily: 'System',
					},
					android: {
						fontFamily: 'sans-serif-condensed',
						fontSize: 14,
					},
				}),
			},
		},
		...options,
	})
}
<commit_msg>adjust createTabNavigator invocation for android<commit_after>// @flow

import {Platform} from 'react-native'
import {
	createBottomTabNavigator,
	NavigationScreenRouteConfig,
} from 'react-navigation'
import {getTheme} from '@frogpond/app-theme'
import {createMaterialBottomTabNavigator} from 'react-navigation-material-bottom-tabs'

type ComponentType = (
	screens: {[key: string]: NavigationScreenRouteConfig},
	options: any, // I don't know how to type this better…
	// the package provides a bunch of types… but it doesn't even use some
	// of them??? and none seem to be the combination of args to the second
	// arg of TabNavigator.
) => typeof createTabNavigator

const createTabNavigator =
	Platform.OS === 'android'
		? createMaterialBottomTabNavigator
		: createBottomTabNavigator

export const TabNavigator: ComponentType = (screens, options = {}) => {
	let theme = getTheme()

	return createTabNavigator(screens, {
		// for react-native-material-bottom-tabs
		backBehavior: 'none',
		activeColor: theme.androidTabBarForeground,
		// for the <BottomNavigation/> that react-native-material-bottom-tabs wraps
		theme: {
			colors: {primary: theme.androidTabBarBackground},
		},
		...options,
		defaultNavigationOptions: {
			...(options.defaultNavigationOptions || {}),
		},
		tabBarOptions: {
			activeTintColor: theme.iosTabBarActiveColor,
			...(options.tabBarOptions || {}),
			labelStyle: {
				fontFamily: 'System',
			},
		},
	})
}
<|endoftext|>


<commit_before>const lwip = require('lwip');
const Pixel = require('../models/pixel');

const imageSize = 1000;

function PaintingHandler(app) {
    return {
        hasImage: false,
        imageHasChanged: false,
        image: null,
        outputImage: null,
        colours: [
            {r: 255, g: 255, b: 255},
            {r: 228, g: 228, b: 228},
            {r: 136, g: 136, b: 136},
            {r: 34, g: 34, b: 34},
            {r: 255, g: 167, b: 209},
            {r: 229, g: 0, b: 0},
            {r: 229, g: 149, b: 0},
            {r: 160, g: 106, b: 66},
            {r: 229, g: 217, b: 0},
            {r: 148, g: 224, b: 68},
            {r: 2, g: 190, b: 1},
            {r: 0, g: 211, b: 221},
            {r: 0, g: 131, b: 199},
            {r: 0, g: 0, b: 234},
            {r: 207, g: 110, b: 228},
            {r: 130, g: 0, b: 128},
        ],

        getBlankImage: function() {
            return new Promise((resolve, reject) => {
                lwip.create(imageSize, imageSize, "white", (err, image) => {
                    if (err) return reject(err);
                    resolve(image);
                });
            });
        },

        loadImageFromDatabase: function() {
            return new Promise((resolve, reject) => {
                let image = this.getBlankImage().then(image => {
                    Pixel.getAllPixels().then(pixels => {
                        let batch = image.batch();
                        pixels.forEach(pixel => {
                            let x = pixel.point.x, y = pixel.point.y;
                            if(x > 0 || y > 0 || x <= 1000 || y <= 1000) {
                                batch.setPixel(x, y, pixel.colour)
                            }
                        })
                        batch.exec((err, image) => {
                            if (err) return reject(err);
                            this.hasImage = true;
                            this.image = image;
                            this.imageBatch = this.image.batch();
                            resolve(image);
                        });
                    }).catch(err => reject(err));
                }).catch(err => {
                    reject(err);
                })
            });
        },

        getOutputImage: function() {
            return new Promise((resolve, reject) => {
                if (this.outputImage && !this.imageHasChanged) return resolve(this.outputImage);
                console.log("Generating new output image!");
                this.generateOutputImage().then((outputImage) => resolve(outputImage)).catch((err) => reject(err));
            })
        },

        generateOutputImage: function() {
            var a = this;
            return new Promise((resolve, reject) => {
                this.imageBatch.toBuffer("png", { compression: "fast", transparency: false }, (err, buffer) => {
                    if (err) return reject(err);
                    a.outputImage = buffer;
                    a.imageHasChanged = false;
                    resolve(buffer);
                })
            })
        },

        getColourRGB: function(colourID) {
            let colour = this.colours[colourID];
            if (!colour) return false;
            return colour;
        },

        doPaint: function(colour, x, y, user) {
            var a = this;
            return new Promise((resolve, reject) => {
                if(!this.hasImage) return reject({message: "Server not ready", code: "not_ready"});
                // Add to DB:
                user.addPixel(colour, x, y, (pixel, err) => {
                    if(err) return reject(err);
                    // Paint on live image:
                    a.imageBatch.setPixel(x, y, colour).exec((err, image) => {
                        if(image) {
                            a.imageHasChanged = true;
                            a.generateOutputImage();
                        }
                    });
                    // Send notice to all clients:
                    app.websocketServer.broadcast("tile_placed", {x: x, y: y, colour: colour});
                    resolve();
                });
            });
        }
    }
}

PaintingHandler.prototype = Object.create(PaintingHandler.prototype);

module.exports = PaintingHandler;<commit_msg>Work cunt<commit_after>const lwip = require('lwip');
const Pixel = require('../models/pixel');

const imageSize = 1000;

function PaintingHandler(app) {
    return {
        hasImage: false,
        imageHasChanged: false,
        image: null,
        outputImage: null,
        colours: [
            {r: 255, g: 255, b: 255},
            {r: 228, g: 228, b: 228},
            {r: 136, g: 136, b: 136},
            {r: 34, g: 34, b: 34},
            {r: 255, g: 167, b: 209},
            {r: 229, g: 0, b: 0},
            {r: 229, g: 149, b: 0},
            {r: 160, g: 106, b: 66},
            {r: 229, g: 217, b: 0},
            {r: 148, g: 224, b: 68},
            {r: 2, g: 190, b: 1},
            {r: 0, g: 211, b: 221},
            {r: 0, g: 131, b: 199},
            {r: 0, g: 0, b: 234},
            {r: 207, g: 110, b: 228},
            {r: 130, g: 0, b: 128},
        ],

        getBlankImage: function() {
            return new Promise((resolve, reject) => {
                lwip.create(imageSize, imageSize, "white", (err, image) => {
                    if (err) return reject(err);
                    resolve(image);
                });
            });
        },

        loadImageFromDatabase: function() {
            return new Promise((resolve, reject) => {
                let image = this.getBlankImage().then(image => {
                    Pixel.getAllPixels().then(pixels => {
                        let batch = image.batch();
                        pixels.forEach(pixel => {
                            let x = pixel.point.x, y = pixel.point.y;
                            if(x >= 0 || y >= 0 || x < 1000 || y < 1000) {
                                batch.setPixel(x, y, pixel.colour)
                            }
                        })
                        batch.exec((err, image) => {
                            if (err) return reject(err);
                            this.hasImage = true;
                            this.image = image;
                            this.imageBatch = this.image.batch();
                            resolve(image);
                        });
                    }).catch(err => reject(err));
                }).catch(err => {
                    reject(err);
                })
            });
        },

        getOutputImage: function() {
            return new Promise((resolve, reject) => {
                if (this.outputImage && !this.imageHasChanged) return resolve(this.outputImage);
                console.log("Generating new output image!");
                this.generateOutputImage().then((outputImage) => resolve(outputImage)).catch((err) => reject(err));
            })
        },

        generateOutputImage: function() {
            var a = this;
            return new Promise((resolve, reject) => {
                this.imageBatch.toBuffer("png", { compression: "fast", transparency: false }, (err, buffer) => {
                    if (err) return reject(err);
                    a.outputImage = buffer;
                    a.imageHasChanged = false;
                    resolve(buffer);
                })
            })
        },

        getColourRGB: function(colourID) {
            let colour = this.colours[colourID];
            if (!colour) return false;
            return colour;
        },

        doPaint: function(colour, x, y, user) {
            var a = this;
            return new Promise((resolve, reject) => {
                if(!this.hasImage) return reject({message: "Server not ready", code: "not_ready"});
                // Add to DB:
                user.addPixel(colour, x, y, (pixel, err) => {
                    if(err) return reject(err);
                    // Paint on live image:
                    a.imageBatch.setPixel(x, y, colour).exec((err, image) => {
                        if(image) {
                            a.imageHasChanged = true;
                            a.generateOutputImage();
                        }
                    });
                    // Send notice to all clients:
                    app.websocketServer.broadcast("tile_placed", {x: x, y: y, colour: colour});
                    resolve();
                });
            });
        }
    }
}

PaintingHandler.prototype = Object.create(PaintingHandler.prototype);

module.exports = PaintingHandler;<|endoftext|>


<commit_before>import { create_svg_url, normalize_svg, generate_svg } from './svg';

import list from './utils/list';
import random_func from './utils/random';

import { cell_id, is_letter, alias_for } from './utils/index';
import { lazy, clamp, sequence, get_value } from './utils/index';

import by_unit from './utils/by-unit';
import by_charcode from './utils/by-charcode';
import calc from './utils/calc';
import expand from './utils/expand';
import Stack from './utils/stack';
import memo from './utils/memo';

import { shapes, create_shape_points } from './shapes';
import parse_value_group from './parser/parse-value-group';
import parse_shape_commands from './parser/parse-shape-commands';
import parse_svg from './parser/parse-svg';
import parse_svg_path from './parser/parse-svg-path';

import { uniform_time } from './uniform';

function get_exposed(random) {
  const { shuffle } = list(random);
  const { pick, rand, nrand, unique_id } = random_func(random);

  const Expose = {

    index({ count }) {
      return _ => count;
    },

    row({ y }) {
      return _ => y;
    },

    col({ x }) {
      return _ => x;
    },

    depth({ z }) {
      return _ => z;
    },

    size({ grid }) {
      return _ => grid.count;
    },

    ['size-row']({ grid }) {
      return _ => grid.y;
    },

    ['size-col']({ grid }) {
      return _ => grid.x;
    },

    ['size-depth']({ grid }) {
      return _ => grid.z;
    },

    id({ x, y, z }) {
      return _ => cell_id(x, y, z);
    },

    n({ extra }) {
      return n => extra ? (extra[0] + (Number(n) || 0)) : '@n';
    },

    nx({ extra }) {
      return n => extra ? (extra[1] + (Number(n) || 0)) : '@nx';
    },

    ny({ extra }) {
      return n => extra ? (extra[2] + (Number(n) || 0)) : '@ny';
    },

    N({ extra }) {
      return n => extra ? (extra[3] + (Number(n) || 0)) : '@N';
    },

    repeat: (
      make_sequence('')
    ),

    multiple: (
      make_sequence(',')
    ),

    ['multiple-with-space']: (
      make_sequence(' ')
    ),

    pick({ context }) {
      return expand((...args) => {
        return push_stack(context, 'last_pick', pick(args));
      });
    },

    ['pick-n']({ context, extra, position }) {
      let counter = 'pn-counter' + position;
      return expand((...args) => {
        if (!context[counter]) context[counter] = 0;
        context[counter] += 1;
        let max = args.length;
        let [idx = context[counter]] = extra || [];
        let pos = (idx - 1) % max;
        let value = args[pos];
        return push_stack(context, 'last_pick', value);
      });
    },

    ['pick-d']({ context, extra, position }) {
      let counter = 'pd-counter' + position;
      let values = 'pd-values' + position;
      return expand((...args) => {
        if (!context[counter]) context[counter] = 0;
        context[counter] += 1;
        if (!context[values]) {
          context[values] = shuffle(args);
        }
        let max = args.length;
        let [idx = context[counter]] = extra || [];
        let pos = (idx - 1) % max;
        let value = context[values][pos];
        return push_stack(context, 'last_pick', value);
      });
    },

    ['last-pick']({ context }) {
      return (n = 1) => {
        let stack = context.last_pick;
        return stack ? stack.last(n) : '';
      };
    },

    rand({ context }) {
      return (...args) => {
        let transform_type = args.every(is_letter)
          ? by_charcode
          : by_unit;
        let value = transform_type(rand).apply(null, args);
        return push_stack(context, 'last_rand', value);
      };
    },

    nrand({ context }) {
      return (...args) => {
        let transform_type = args.every(is_letter)
          ? by_charcode
          : by_unit;
        let value = transform_type(nrand).apply(null, args);
        return push_stack(context, 'last_rand', value);
      };
    },

    ['rand-int']({ context }) {
      return (...args) => {
        let transform_type = args.every(is_letter)
          ? by_charcode
          : by_unit;
        let rand_int = (...args) => Math.round(rand(...args))
        let value = transform_type(rand_int).apply(null, args)
        return push_stack(context, 'last_rand', value);
      }
    },

    ['nrand-int']({ context }) {
      return (...args) => {
        let transform_type = args.every(is_letter)
          ? by_charcode
          : by_unit;
        let nrand_int = (...args) => Math.round(nrand(...args))
        let value = transform_type(nrand_int).apply(null, args)
        return push_stack(context, 'last_rand', value);
      }
    },

    ['last-rand']({ context }) {
      return (n = 1) => {
        let stack = context.last_rand;
        return stack ? stack.last(n) : '';
      };
    },

    stripe() {
      return (...input) => {
        let colors = input.map(get_value);
        let max = colors.length;
        let default_count = 0;
        let custom_sizes = [];
        let prev;
        if (!max) {
          return '';
        }
        colors.forEach(step => {
          let [_, size] = parse_value_group(step);
          if (size !== undefined) custom_sizes.push(size);
          else default_count += 1;
        });
        let default_size = custom_sizes.length
          ? `(100% - ${custom_sizes.join(' - ')}) / ${default_count}`
          : `100% / ${max}`
        return colors.map((step, i) => {
          if (custom_sizes.length) {
            let [color, size] = parse_value_group(step);
            let prefix = prev ? (prev + ' + ') : '';
            prev = prefix + (size !== undefined ? size : default_size);
            return `${color} 0 calc(${ prev })`
          }
          return `${step} 0 ${100 / max * (i + 1)}%`
        })
        .join(',');
      }
    },

    reflect() {
      return (...input) => {
        return [
          ...input,
          ...input.slice(0, -1).reverse()
        ].join(',');
      }
    },

    calc() {
      return value => calc(get_value(value));
    },

    hex() {
      return value => parseInt(get_value(value)).toString(16);
    },

    svg: lazy((...args) => {
      let value = args.map(input => get_value(input()).trim()).join(',');
      if (!value.startsWith('<')) {
        let parsed = parse_svg(value);
        value = generate_svg(parsed);
      }
      let svg = normalize_svg(value);
      return create_svg_url(svg);
    }),

    ['svg-filter']: lazy((...args) => {
      let value = args.map(input => get_value(input()).trim()).join(',');
      let id = unique_id('filter-');
      if (!value.startsWith('<')) {
        let parsed = parse_svg(value, {
          type: 'block',
          name: 'filter'
        });
        value = generate_svg(parsed);
      }
      let svg = normalize_svg(value).replace(
        /<filter([\s>])/,
        `<filter id="${ id }"$1`
      );
      return create_svg_url(svg, id);
    }),

    var() {
      return value => `var(${ get_value(value) })`;
    },

    t() {
      return value => `var(--${ uniform_time.name })`;
    },

    point({ count, context, extra, position, grid }) {
      let key = 'offset-points' + position;
      return commands => {
        let [idx = count, _, __, max = grid.count] = extra || [];
        if (!context[key]) {
          let config = parse_shape_commands(commands);
          config.points = max;
          context[key] = create_shape_points(config, {min: 1, max: 65536});
        }
        return context[key][idx - 1];
      };
    },

    Point({ count, context, extra, position, grid }) {
      let key = 'offset-points' + position;
      return commands => {
        let [idx = count, _, __, max = grid.count] = extra || [];
        if (!context[key]) {
          let config = parse_shape_commands(commands);
          config.points = max;
          config.absolute = true;
          context[key] = create_shape_points(config, {min: 1, max: 65536});
        }
        return context[key][idx - 1];
      };
    },

    shape() {
      return memo('shape-function', (type = '', ...args) => {
        type = String(type).trim();
        let points = [];
        if (type.length) {
          if (typeof shapes[type] === 'function') {
            points = shapes[type](args);
          } else {
            let commands = type;
            let rest = args.join(',');
            if (rest.length) {
              commands = type + ',' + rest;
            }
            let config = parse_shape_commands(commands);
            points = create_shape_points(config, {min: 3, max: 3600});
          }
        }
        return `polygon(${points.join(',')})`;
      });
    },

    doodle() {
      return value => value;
    },

    shaders() {
      return value => value;
    },

    path() {
      return value => value;
    },

    invert() {
      return commands => {
        let parsed = parse_svg_path(commands);
        if (!parsed.valid) return commands;
        return parsed.commands.map(({ name, value }) => {
          switch (name) {
            case 'v': return 'h' + value.join(' ');
            case 'V': return 'H' + value.join(' ');
            case 'h': return 'v' + value.join(' ');
            case 'H': return 'V' + value.join(' ');
            default:  return name + value.join(' ');
          }
        }).join(' ');
      };
    },

    flipH() {
      return commands => {
        let parsed = parse_svg_path(commands);
        if (!parsed.valid) return commands;
        return parsed.commands.map(({ name, value }) => {
          switch (name) {
            case 'h':
            case 'H': return name + value.map(flip_value).join(' ');
            default:  return name + value.join(' ');
          }
        }).join(' ');
      };
    },

    flipV() {
      return commands => {
        let parsed = parse_svg_path(commands);
        if (!parsed.valid) return commands;
        return parsed.commands.map(({ name, value }) => {
          switch (name) {
            case 'v':
            case 'V': return name + value.map(flip_value).join(' ');
            default:  return name + value.join(' ');
          }
        }).join(' ');
      };
    },

    flip(...args) {
      let flipH = Expose.flipH(...args);
      let flipV = Expose.flipV(...args);
      return commands => {
        return flipV(flipH(commands));
      }
    },

  };

  function make_sequence(c) {
    return lazy((n, ...actions) => {
      if (!actions || !n) return '';
      let count = get_value(n());
      let evaluated = calc(count);
      if (evaluated === 0) {
        evaluated = count;
      }
      return sequence(
        evaluated,
        (...args) => {
          return actions.map(action => {
            return get_value(action(...args))
          }).join(',');
        }
      ).join(c);
    });
  }

  function push_stack(context, name, value) {
    if (!context[name]) context[name] = new Stack();
    context[name].push(value);
    return value;
  }

  function flip_value(num) {
    return -1 * num;
  }

  return alias_for(Expose, {
    'm': 'multiple',
    'M': 'multiple-with-space',

    'r':    'rand',
    'rn':   'nrand',
    'ri':   'rand-int',
    'rni':  'nrand-int',
    'lr':   'last-rand',

    'p':  'pick',
    'pn': 'pick-n',
    'pd': 'pick-d',
    'lp': 'last-pick',

    'rep': 'repeat',

    'i': 'index',
    'x': 'col',
    'y': 'row',
    'z': 'depth',

    'I': 'size',
    'X': 'size-col',
    'Y': 'size-row',
    'Z': 'size-depth',

    // legacy names, keep them before 1.0
    'nr': 'rn',
    'nri': 'nri',
    'ms': 'multiple-with-space',
    's':  'size',
    'sx': 'size-col',
    'sy': 'size-row',
    'sz': 'size-depth',
    'size-x': 'size-col',
    'size-y': 'size-row',
    'size-z': 'size-depth',
    'multi': 'multiple',
    'pick-by-turn': 'pick-n',
    'max-row': 'size-row',
    'max-col': 'size-col',
    'offset': 'point',
    'Offset': 'Point',

    // error prone
    'stripes': 'stripe',
    'strip':   'stripe',
  });
}

export default get_exposed;
<commit_msg>Add lowercase aliases<commit_after>import { create_svg_url, normalize_svg, generate_svg } from './svg';

import list from './utils/list';
import random_func from './utils/random';

import { cell_id, is_letter, alias_for } from './utils/index';
import { lazy, clamp, sequence, get_value } from './utils/index';

import by_unit from './utils/by-unit';
import by_charcode from './utils/by-charcode';
import calc from './utils/calc';
import expand from './utils/expand';
import Stack from './utils/stack';
import memo from './utils/memo';

import { shapes, create_shape_points } from './shapes';
import parse_value_group from './parser/parse-value-group';
import parse_shape_commands from './parser/parse-shape-commands';
import parse_svg from './parser/parse-svg';
import parse_svg_path from './parser/parse-svg-path';

import { uniform_time } from './uniform';

function get_exposed(random) {
  const { shuffle } = list(random);
  const { pick, rand, nrand, unique_id } = random_func(random);

  const Expose = {

    index({ count }) {
      return _ => count;
    },

    row({ y }) {
      return _ => y;
    },

    col({ x }) {
      return _ => x;
    },

    depth({ z }) {
      return _ => z;
    },

    size({ grid }) {
      return _ => grid.count;
    },

    ['size-row']({ grid }) {
      return _ => grid.y;
    },

    ['size-col']({ grid }) {
      return _ => grid.x;
    },

    ['size-depth']({ grid }) {
      return _ => grid.z;
    },

    id({ x, y, z }) {
      return _ => cell_id(x, y, z);
    },

    n({ extra }) {
      return n => extra ? (extra[0] + (Number(n) || 0)) : '@n';
    },

    nx({ extra }) {
      return n => extra ? (extra[1] + (Number(n) || 0)) : '@nx';
    },

    ny({ extra }) {
      return n => extra ? (extra[2] + (Number(n) || 0)) : '@ny';
    },

    N({ extra }) {
      return n => extra ? (extra[3] + (Number(n) || 0)) : '@N';
    },

    repeat: (
      make_sequence('')
    ),

    multiple: (
      make_sequence(',')
    ),

    ['multiple-with-space']: (
      make_sequence(' ')
    ),

    pick({ context }) {
      return expand((...args) => {
        return push_stack(context, 'last_pick', pick(args));
      });
    },

    ['pick-n']({ context, extra, position }) {
      let counter = 'pn-counter' + position;
      return expand((...args) => {
        if (!context[counter]) context[counter] = 0;
        context[counter] += 1;
        let max = args.length;
        let [idx = context[counter]] = extra || [];
        let pos = (idx - 1) % max;
        let value = args[pos];
        return push_stack(context, 'last_pick', value);
      });
    },

    ['pick-d']({ context, extra, position }) {
      let counter = 'pd-counter' + position;
      let values = 'pd-values' + position;
      return expand((...args) => {
        if (!context[counter]) context[counter] = 0;
        context[counter] += 1;
        if (!context[values]) {
          context[values] = shuffle(args);
        }
        let max = args.length;
        let [idx = context[counter]] = extra || [];
        let pos = (idx - 1) % max;
        let value = context[values][pos];
        return push_stack(context, 'last_pick', value);
      });
    },

    ['last-pick']({ context }) {
      return (n = 1) => {
        let stack = context.last_pick;
        return stack ? stack.last(n) : '';
      };
    },

    rand({ context }) {
      return (...args) => {
        let transform_type = args.every(is_letter)
          ? by_charcode
          : by_unit;
        let value = transform_type(rand).apply(null, args);
        return push_stack(context, 'last_rand', value);
      };
    },

    nrand({ context }) {
      return (...args) => {
        let transform_type = args.every(is_letter)
          ? by_charcode
          : by_unit;
        let value = transform_type(nrand).apply(null, args);
        return push_stack(context, 'last_rand', value);
      };
    },

    ['rand-int']({ context }) {
      return (...args) => {
        let transform_type = args.every(is_letter)
          ? by_charcode
          : by_unit;
        let rand_int = (...args) => Math.round(rand(...args))
        let value = transform_type(rand_int).apply(null, args)
        return push_stack(context, 'last_rand', value);
      }
    },

    ['nrand-int']({ context }) {
      return (...args) => {
        let transform_type = args.every(is_letter)
          ? by_charcode
          : by_unit;
        let nrand_int = (...args) => Math.round(nrand(...args))
        let value = transform_type(nrand_int).apply(null, args)
        return push_stack(context, 'last_rand', value);
      }
    },

    ['last-rand']({ context }) {
      return (n = 1) => {
        let stack = context.last_rand;
        return stack ? stack.last(n) : '';
      };
    },

    stripe() {
      return (...input) => {
        let colors = input.map(get_value);
        let max = colors.length;
        let default_count = 0;
        let custom_sizes = [];
        let prev;
        if (!max) {
          return '';
        }
        colors.forEach(step => {
          let [_, size] = parse_value_group(step);
          if (size !== undefined) custom_sizes.push(size);
          else default_count += 1;
        });
        let default_size = custom_sizes.length
          ? `(100% - ${custom_sizes.join(' - ')}) / ${default_count}`
          : `100% / ${max}`
        return colors.map((step, i) => {
          if (custom_sizes.length) {
            let [color, size] = parse_value_group(step);
            let prefix = prev ? (prev + ' + ') : '';
            prev = prefix + (size !== undefined ? size : default_size);
            return `${color} 0 calc(${ prev })`
          }
          return `${step} 0 ${100 / max * (i + 1)}%`
        })
        .join(',');
      }
    },

    reflect() {
      return (...input) => {
        return [
          ...input,
          ...input.slice(0, -1).reverse()
        ].join(',');
      }
    },

    calc() {
      return value => calc(get_value(value));
    },

    hex() {
      return value => parseInt(get_value(value)).toString(16);
    },

    svg: lazy((...args) => {
      let value = args.map(input => get_value(input()).trim()).join(',');
      if (!value.startsWith('<')) {
        let parsed = parse_svg(value);
        value = generate_svg(parsed);
      }
      let svg = normalize_svg(value);
      return create_svg_url(svg);
    }),

    ['svg-filter']: lazy((...args) => {
      let value = args.map(input => get_value(input()).trim()).join(',');
      let id = unique_id('filter-');
      if (!value.startsWith('<')) {
        let parsed = parse_svg(value, {
          type: 'block',
          name: 'filter'
        });
        value = generate_svg(parsed);
      }
      let svg = normalize_svg(value).replace(
        /<filter([\s>])/,
        `<filter id="${ id }"$1`
      );
      return create_svg_url(svg, id);
    }),

    var() {
      return value => `var(${ get_value(value) })`;
    },

    t() {
      return value => `var(--${ uniform_time.name })`;
    },

    point({ count, context, extra, position, grid }) {
      let key = 'offset-points' + position;
      return commands => {
        let [idx = count, _, __, max = grid.count] = extra || [];
        if (!context[key]) {
          let config = parse_shape_commands(commands);
          config.points = max;
          context[key] = create_shape_points(config, {min: 1, max: 65536});
        }
        return context[key][idx - 1];
      };
    },

    Point({ count, context, extra, position, grid }) {
      let key = 'offset-points' + position;
      return commands => {
        let [idx = count, _, __, max = grid.count] = extra || [];
        if (!context[key]) {
          let config = parse_shape_commands(commands);
          config.points = max;
          config.absolute = true;
          context[key] = create_shape_points(config, {min: 1, max: 65536});
        }
        return context[key][idx - 1];
      };
    },

    shape() {
      return memo('shape-function', (type = '', ...args) => {
        type = String(type).trim();
        let points = [];
        if (type.length) {
          if (typeof shapes[type] === 'function') {
            points = shapes[type](args);
          } else {
            let commands = type;
            let rest = args.join(',');
            if (rest.length) {
              commands = type + ',' + rest;
            }
            let config = parse_shape_commands(commands);
            points = create_shape_points(config, {min: 3, max: 3600});
          }
        }
        return `polygon(${points.join(',')})`;
      });
    },

    doodle() {
      return value => value;
    },

    shaders() {
      return value => value;
    },

    path() {
      return value => value;
    },

    invert() {
      return commands => {
        let parsed = parse_svg_path(commands);
        if (!parsed.valid) return commands;
        return parsed.commands.map(({ name, value }) => {
          switch (name) {
            case 'v': return 'h' + value.join(' ');
            case 'V': return 'H' + value.join(' ');
            case 'h': return 'v' + value.join(' ');
            case 'H': return 'V' + value.join(' ');
            default:  return name + value.join(' ');
          }
        }).join(' ');
      };
    },

    flipH() {
      return commands => {
        let parsed = parse_svg_path(commands);
        if (!parsed.valid) return commands;
        return parsed.commands.map(({ name, value }) => {
          switch (name) {
            case 'h':
            case 'H': return name + value.map(flip_value).join(' ');
            default:  return name + value.join(' ');
          }
        }).join(' ');
      };
    },

    flipV() {
      return commands => {
        let parsed = parse_svg_path(commands);
        if (!parsed.valid) return commands;
        return parsed.commands.map(({ name, value }) => {
          switch (name) {
            case 'v':
            case 'V': return name + value.map(flip_value).join(' ');
            default:  return name + value.join(' ');
          }
        }).join(' ');
      };
    },

    flip(...args) {
      let flipH = Expose.flipH(...args);
      let flipV = Expose.flipV(...args);
      return commands => {
        return flipV(flipH(commands));
      }
    },

  };

  function make_sequence(c) {
    return lazy((n, ...actions) => {
      if (!actions || !n) return '';
      let count = get_value(n());
      let evaluated = calc(count);
      if (evaluated === 0) {
        evaluated = count;
      }
      return sequence(
        evaluated,
        (...args) => {
          return actions.map(action => {
            return get_value(action(...args))
          }).join(',');
        }
      ).join(c);
    });
  }

  function push_stack(context, name, value) {
    if (!context[name]) context[name] = new Stack();
    context[name].push(value);
    return value;
  }

  function flip_value(num) {
    return -1 * num;
  }

  return alias_for(Expose, {
    'm': 'multiple',
    'M': 'multiple-with-space',

    'r':    'rand',
    'rn':   'nrand',
    'ri':   'rand-int',
    'rni':  'nrand-int',
    'lr':   'last-rand',

    'p':  'pick',
    'pn': 'pick-n',
    'pd': 'pick-d',
    'lp': 'last-pick',

    'rep': 'repeat',

    'i': 'index',
    'x': 'col',
    'y': 'row',
    'z': 'depth',

    'I': 'size',
    'X': 'size-col',
    'Y': 'size-row',
    'Z': 'size-depth',

    'flipv': 'flipV',
    'fliph': 'flipH',

    // legacy names, keep them before 1.0
    'nr': 'rn',
    'nri': 'nri',
    'ms': 'multiple-with-space',
    's':  'size',
    'sx': 'size-col',
    'sy': 'size-row',
    'sz': 'size-depth',
    'size-x': 'size-col',
    'size-y': 'size-row',
    'size-z': 'size-depth',
    'multi': 'multiple',
    'pick-by-turn': 'pick-n',
    'max-row': 'size-row',
    'max-col': 'size-col',
    'offset': 'point',
    'Offset': 'Point',

    // error prone
    'stripes': 'stripe',
    'strip':   'stripe',
  });
}

export default get_exposed;
<|endoftext|>


<commit_before>Vps.Auto.AssignGridPanel = Ext.extend(Vps.Binding.ProxyPanel, {

    gridAssignedControllerUrl: '',
    gridDataControllerUrl: '',
    textAssignActionUrl: null,

    gridDataHeight: 410,

    assignActionUrl: '',
    gridDataParamName: 'foreign_keys',

    initComponent: function()
    {
        this.actions.assign = new Ext.Action({
            text    : trlVps('Assign'),
            icon    : '/assets/silkicons/table_relationship.png',
            cls     : 'x-btn-text-icon',
            disabled: true,
            handler : this.onAssign,
            scope   : this
        });

        if (this.assignActionUrl == '') {
            this.assignActionUrl = this.gridAssignedControllerUrl + '/json-assign';
        }

        this.gridAssigned = new Vps.Auto.AssignedGridPanel({
            controllerUrl: this.gridAssignedControllerUrl,
            textAssignActionUrl: this.textAssignActionUrl,
            region: 'center',
            gridConfig: {
                selModel: new Ext.grid.CheckboxSelectionModel()
            }
        });
        this.proxyItem = this.gridAssigned;

        this.gridData = new Vps.Auto.GridPanel({
            region: 'south',
            split: true,
            height: this.gridDataHeight,
            controllerUrl: this.gridDataControllerUrl,
            gridConfig: {
                tbar: [ this.getAction('assign'), '-' ],
                selModel: new Ext.grid.CheckboxSelectionModel()
            },
            autoLoad: this.autoLoad
        });

        this.gridAssigned.on('datachange', function() {
            this.gridData.reload();
        }, this);

        this.relayEvents(this.gridAssigned, ['datachange']);

        this.gridData.on('selectionchange', function() {
            if (this.gridData.getSelectionModel().getSelections()[0]) {
                this.getAction('assign').enable();
            } else {
                this.getAction('assign').disable();
            }
        }, this);

        this.gridData.on('deleterow', function() {
            this.gridAssigned.reload();
        }, this);

        this.gridData.on('datachange', function() {
            this.gridAssigned.reload();
        }, this);

        this.layout = 'border';

        this.items = [this.gridAssigned, this.gridData];

        Vps.Auto.AssignGridPanel.superclass.initComponent.call(this);
    },

    onAssign : function()
    {
        if (!this.gridData.getSelectionModel().getSelections()) return;
        var params = this.gridAssigned.getBaseParams();
        params[this.gridDataParamName] = [];

        var selections = this.gridData.getSelectionModel().getSelections();
        for (var i in selections) {
            if (selections[i].id) {
                params[this.gridDataParamName].push(selections[i].id);
            }
        }
        params[this.gridDataParamName] = Ext.encode(params[this.gridDataParamName]);

        Ext.Ajax.request({
            url: this.assignActionUrl,
            params: params,
            success: function() {
                this.gridAssigned.reload();
                this.gridData.reload();
            },
            scope: this
        });
    },

    reloadDataGrid: function() {
        return this.gridData.reload.apply(this.gridData, arguments);
    },

    setAutoLoad: function(v) {
        Vps.Auto.AssignGridPanel.superclass.setAutoLoad.apply(this, arguments);
        this.gridData.setAutoLoad(v);
    },
    load: function() {
        Vps.Auto.AssignGridPanel.superclass.load.apply(this, arguments);

        //wenn autoLoad=false
        if (!this.gridData.getStore()) {
            this.gridData.load();
        }
    },

    setBaseParams: function(bp) {
        this.gridAssigned.setBaseParams(bp);
        this.gridData.setBaseParams(bp);
        return Vps.Auto.AssignGridPanel.superclass.setBaseParams.call(this, bp);
    },

    applyBaseParams: function(bp) {
        this.gridAssigned.applyBaseParams(bp);
        this.gridData.applyBaseParams(bp);
        return Vps.Auto.AssignGridPanel.superclass.applyBaseParams.call(this, bp);
    }

});

Ext.reg('vps.assigngrid', Vps.Auto.AssignGridPanel);<commit_msg>assigned event zu assignedGrid hinzugefuegt<commit_after>Vps.Auto.AssignGridPanel = Ext.extend(Vps.Binding.ProxyPanel, {

    gridAssignedControllerUrl: '',
    gridDataControllerUrl: '',
    textAssignActionUrl: null,

    gridDataHeight: 410,

    assignActionUrl: '',
    gridDataParamName: 'foreign_keys',

    initComponent: function()
    {
        this.addEvents({
            'assigned': true
        });

        this.actions.assign = new Ext.Action({
            text    : trlVps('Assign'),
            icon    : '/assets/silkicons/table_relationship.png',
            cls     : 'x-btn-text-icon',
            disabled: true,
            handler : this.onAssign,
            scope   : this
        });

        if (this.assignActionUrl == '') {
            this.assignActionUrl = this.gridAssignedControllerUrl + '/json-assign';
        }

        this.gridAssigned = new Vps.Auto.AssignedGridPanel({
            controllerUrl: this.gridAssignedControllerUrl,
            textAssignActionUrl: this.textAssignActionUrl,
            region: 'center',
            gridConfig: {
                selModel: new Ext.grid.CheckboxSelectionModel()
            }
        });
        this.proxyItem = this.gridAssigned;

        this.gridData = new Vps.Auto.GridPanel({
            region: 'south',
            split: true,
            height: this.gridDataHeight,
            controllerUrl: this.gridDataControllerUrl,
            gridConfig: {
                tbar: [ this.getAction('assign'), '-' ],
                selModel: new Ext.grid.CheckboxSelectionModel()
            },
            autoLoad: this.autoLoad
        });

        this.gridAssigned.on('datachange', function() {
            this.gridData.reload();
        }, this);

        this.relayEvents(this.gridAssigned, ['datachange']);

        this.gridData.on('selectionchange', function() {
            if (this.gridData.getSelectionModel().getSelections()[0]) {
                this.getAction('assign').enable();
            } else {
                this.getAction('assign').disable();
            }
        }, this);

        this.gridData.on('deleterow', function() {
            this.gridAssigned.reload();
        }, this);

        this.gridData.on('datachange', function() {
            this.gridAssigned.reload();
        }, this);

        this.layout = 'border';

        this.items = [this.gridAssigned, this.gridData];

        Vps.Auto.AssignGridPanel.superclass.initComponent.call(this);
    },

    onAssign : function()
    {
        if (!this.gridData.getSelectionModel().getSelections()) return;
        var params = this.gridAssigned.getBaseParams();
        params[this.gridDataParamName] = [];

        var selections = this.gridData.getSelectionModel().getSelections();
        for (var i in selections) {
            if (selections[i].id) {
                params[this.gridDataParamName].push(selections[i].id);
            }
        }
        params[this.gridDataParamName] = Ext.encode(params[this.gridDataParamName]);

        Ext.Ajax.request({
            url: this.assignActionUrl,
            params: params,
            success: function() {
                this.gridAssigned.reload();
                this.gridData.reload();
                this.fireEvent('assigned', this);
            },
            scope: this
        });
    },

    reloadDataGrid: function() {
        return this.gridData.reload.apply(this.gridData, arguments);
    },

    setAutoLoad: function(v) {
        Vps.Auto.AssignGridPanel.superclass.setAutoLoad.apply(this, arguments);
        this.gridData.setAutoLoad(v);
    },
    load: function() {
        Vps.Auto.AssignGridPanel.superclass.load.apply(this, arguments);

        //wenn autoLoad=false
        if (!this.gridData.getStore()) {
            this.gridData.load();
        }
    },

    setBaseParams: function(bp) {
        this.gridAssigned.setBaseParams(bp);
        this.gridData.setBaseParams(bp);
        return Vps.Auto.AssignGridPanel.superclass.setBaseParams.call(this, bp);
    },

    applyBaseParams: function(bp) {
        this.gridAssigned.applyBaseParams(bp);
        this.gridData.applyBaseParams(bp);
        return Vps.Auto.AssignGridPanel.superclass.applyBaseParams.call(this, bp);
    }

});

Ext.reg('vps.assigngrid', Vps.Auto.AssignGridPanel);<|endoftext|>


<commit_before>/*****************************************************************************************************************
 *    Attributes for tabbing, keyup/down and page up/down
 *    Created by vegar ringdal
 *
 ****************************************************************************************************************/
import {inject, customAttribute} from 'aurelia-framework';
import {VGrid} from './v-grid';

@customAttribute('v-key-move')
@inject(Element, VGrid)
export class vGridAttributesSort {

  constructor(element, vGrid) {
    this.vGrid = vGrid;
    this.element = element;
    this.classname = "v-grid-key-move";
  }

  bind(bindingContext, overrideContext) {
    this.bindingContext = bindingContext;
    this.overrideContext = overrideContext;

  }

  attached() {
    this.element.classList.add(this.classname);
    this.addGridKeyListner();

    this.element.addEventListener('tabbing', (e)=> {
      this.element.focus();
    })

  }

  /***************************************************************************************
   * for setting next cell ny similating a mouse click, used for tabbing etc
   ***************************************************************************************/
  dispatchCellClick(index) {
    var e = document.createEvent('Event');
    e.initEvent("tabbing", true, true);

    if (this.cells[index]) {
      this.cells[index].dispatchEvent(e);
    }

    var e = document.createEvent('Event');
    e.initEvent("click", true, true);

    if (this.cells[index]) {
      this.cells[index].offsetParent.dispatchEvent(e);
    }

  }

  /***************************************************************************************
   * sets "the cells" from  to direction asked for, so tabbing jumps to next row
   ***************************************************************************************/
  setCellsFromElement(node, direction) {
    var thisTop;
    var element;
    for (var i = 0; i < 10; i++) {
      try {
        if (node.classList.contains(this.vGrid.vGridConfig.css.row)) {
          var row = parseInt(node.getAttribute("row"));
          for (var y = 0; y < this.vGrid.vGridGenerator.rowElementArray.length; y++) {
            if (row === parseInt((this.vGrid.vGridGenerator.rowElementArray[y].top / this.vGrid.vGridConfig.attRowHeight))) {
              this.row = row;
              thisTop = this.vGrid.vGridGenerator.rowElementArray[y + direction].top;
              element = this.vGrid.vGridGenerator.rowElementArray[y + direction].div;
            }
          }
        }
        node = node.parentNode;
      } catch (err) {
        console.warn("tabbing failure")
      }
    }
    if (element) {
      this.cells = element.querySelectorAll("." + this.classname);
    }
    return thisTop;
  };

  /***************************************************************************************
   * sets "the cells" from a top value, used for page up/down
   ***************************************************************************************/
  setCellsFromTopValue(top) {
    var element = 0;
    for (var i = 0; i < this.vGrid.vGridGenerator.rowElementArray.length; i++) {
      if (this.vGrid.vGridGenerator.rowElementArray[i].top === top) {
        element = this.vGrid.vGridGenerator.rowElementArray[i].div;
      }
    }
    if (element) {
      this.cells = element.querySelectorAll("." + this.classname);
    }

  }

  /***************************************************************************************
   * simple delay for the keydown events, like tabbing etc, so I cantrol the speed of it
   ***************************************************************************************/
  keyDownDelay(callback) {
    if (!this.timer) {
      this.timer = setTimeout(()=> {
        this.timer = null;
        callback();
      }, 150)
    }
  }

  /***************************************************************************************
   * get the index
   ***************************************************************************************/
  getIndex() {
    for (var i = 0; i < this.cells.length; i++) {
      if (this.element === this.cells[i]) {
        this.index = i;
        if (i === 0) {
          this.first = true;
          this.last = false;
        }
        if (i === this.cells.length - 1) {
          this.first = false;
          this.last = true;
        }
      }
    }
  }

  /***************************************************************************************
   * adds main keys, like arrow keys, tab, and page up/down
   ***************************************************************************************/
  addGridKeyListner() {

    this.element.onkeydown = function (e) {

      this.setCellsFromElement(this.element, 0);
      this.getIndex();

      //page up
      if (e.keyCode === 33) {
        e.preventDefault();
        this.keyDownDelay(() => {

          //get scrolltop
          var currentscrolltop = this.vGrid.vGridClientCtx.getScrollTop();

          //get content height/rows
          var rowHeight = this.vGrid.vGridConfig.attRowHeight;
          var containerHeight = this.vGrid.vGridGenerator.contentElement.clientHeight;
          var containerRows = parseInt(containerHeight / rowHeight, 10);
          this.top = this.setCellsFromElement(this.element, 0);

          var newTop = this.top - (containerRows * rowHeight);
          if ((newTop / rowHeight) <= 0) {
            newTop = 0;
          }

          //if last scroll was up then we need to reverse the buffer
          if (this.vGrid.vGridScrollEvents.lastScrollType === "down") {
            this.vGrid.vGridScrollEvents.onSmallScroll(false)
          }

          this.setCellsFromTopValue(newTop);
          this.dispatchCellClick(this.index);

          var setTop = newTop - parseInt((containerRows * rowHeight) / 2);
          this.vGrid.vGridClientCtx.setScrollTop(setTop);

        });
      }

      //page down
      if (e.keyCode === 34) {
        e.preventDefault();
        this.keyDownDelay(() => {

          //get scrolltop
          var currentscrolltop = this.vGrid.vGridClientCtx.getScrollTop();

          //get content height/rows
          var rowHeight = this.vGrid.vGridConfig.attRowHeight;
          var containerHeight = this.vGrid.vGridGenerator.contentElement.clientHeight;
          var containerRows = parseInt(containerHeight / rowHeight, 10);
          this.top = this.setCellsFromElement(this.element, 0);

          var newTop = this.top + (containerRows * rowHeight);
          if ((newTop / rowHeight) >= this.vGrid.vGridConfig.getCollectionLength()) {
            newTop = this.vGrid.vGridConfig.getCollectionLength() * rowHeight;
            newTop = newTop - rowHeight
          }

          //if last scroll was up then we need to reverse the buffer
          if (this.vGrid.vGridScrollEvents.lastScrollType === "up") {
            this.vGrid.vGridScrollEvents.onSmallScroll(true);
          }

          this.setCellsFromTopValue(newTop);
          this.dispatchCellClick(this.index);

          var setTop = newTop - parseInt((containerRows * rowHeight) / 2);
          this.vGrid.vGridClientCtx.setScrollTop(setTop);
        });
      }

      //arrow down
      if (e.keyCode === 40) {
        e.preventDefault();
        this.keyDownDelay(() => {
          if (this.vGrid.vGridScrollEvents.lastScrollType === "up") {
            this.vGrid.vGridScrollEvents.onSmallScroll(true);
          }
          this.top = this.setCellsFromElement(this.element, +1);
          this.dispatchCellClick(this.index)
        });
      }

      //arrow up
      if (e.keyCode === 38) {
        e.preventDefault();
        this.keyDownDelay(() => {
          if (this.vGrid.vGridScrollEvents.lastScrollType === "down") {
            this.vGrid.vGridScrollEvents.onSmallScroll(false);
          }
          this.top = this.setCellsFromElement(this.element, -1);
          this.dispatchCellClick(this.index)
        });
      }

      //tab and shift key for tabing in other direction
      if (e.keyCode === 9 && e.shiftKey === true) {
        if (this.row !== 0 && this.first) {
          e.preventDefault();
          this.keyDownDelay(() => {
            this.index = this.index - 1;
            if (this.first) {
              if (this.vGrid.vGridScrollEvents.lastScrollType === "down") {
                this.vGrid.vGridScrollEvents.onSmallScroll(false);
              }
              this.index = this.cells.length - 1;
              this.top = this.setCellsFromElement(this.element, -1)
            }
            this.dispatchCellClick(this.index)

          });
        }
      }

      //normal tabbing
      if (e.keyCode === 9 && e.shiftKey === false) {
        e.preventDefault();
        this.keyDownDelay(() => {
          this.index = this.index + 1;
          if (this.last) {
            if (this.vGrid.vGridScrollEvents.lastScrollType === "up") {
              this.vGrid.vGridScrollEvents.onSmallScroll(true);
            }
            this.index = 0;
            this.top = this.setCellsFromElement(this.element, 1)
          }
          this.dispatchCellClick(this.index)
        });

      }

    }.bind(this)
  }

}
<commit_msg>update/fix to v-key-move attribute<commit_after>/*****************************************************************************************************************
 *    Attributes for tabbing, keyup/down and page up/down
 *    Created by vegar ringdal
 *
 ****************************************************************************************************************/
import {inject, customAttribute} from 'aurelia-framework';
import {VGrid} from './v-grid';

@customAttribute('v-key-move')
@inject(Element, VGrid)
export class vGridAttributesKeyMove {

  constructor(element, vGrid) {
    this.vGrid = vGrid;
    this.element = element;
    this.classname = "v-grid-key-move";
  }

  bind(bindingContext, overrideContext) {
    this.bindingContext = bindingContext;
    this.overrideContext = overrideContext;

  }

  attached() {
    this.element.classList.add(this.classname);
    this.addGridKeyListner();

    this.element.addEventListener('tabbing', (e)=> {
      this.element.focus();

      let ev = document.createEvent('Event');
      ev.initEvent("click", true, true);
      this.element.offsetParent.dispatchEvent(ev);

    });

    this.element.addEventListener('focus', (e)=> {

      if (this.vGrid.vGridCurrentEntityRef === null) {
        let ev = document.createEvent('Event');
        ev.initEvent("click", true, true);
        this.element.offsetParent.dispatchEvent(ev);
      }

    });

  }

  /***************************************************************************************
   * for setting next cell ny similating a mouse click, used for tabbing etc
   ***************************************************************************************/
  dispatchCellClick(index) {
    var e = document.createEvent('Event');
    e.initEvent("tabbing", true, true);

    if (this.cells[index]) {
      this.cells[index].dispatchEvent(e);
    }
  }

  /***************************************************************************************
   * sets "the cells" from  to direction asked for, so tabbing jumps to next row
   ***************************************************************************************/
  setCellsFromElement(node, direction) {
    var thisTop;
    var element;
    for (var i = 0; i < 10; i++) {
      try {
        if (node.classList.contains(this.vGrid.vGridConfig.css.row)) {
          var row = parseInt(node.getAttribute("row"));
          for (var y = 0; y < this.vGrid.vGridGenerator.rowElementArray.length; y++) {
            if (row === parseInt((this.vGrid.vGridGenerator.rowElementArray[y].top / this.vGrid.vGridConfig.attRowHeight))) {
              this.row = row;
              thisTop = this.vGrid.vGridGenerator.rowElementArray[y + direction].top;
              element = this.vGrid.vGridGenerator.rowElementArray[y + direction].div;
            }
          }
        }
        node = node.parentNode;
      } catch (err) {
        //nothing for now
      }
    }
    if (element) {
      this.cells = element.querySelectorAll("." + this.classname);
    }
    return thisTop;
  };

  /***************************************************************************************
   * sets "the cells" from a top value, used for page up/down
   ***************************************************************************************/
  setCellsFromTopValue(top) {
    var element = 0;
    for (var i = 0; i < this.vGrid.vGridGenerator.rowElementArray.length; i++) {
      if (this.vGrid.vGridGenerator.rowElementArray[i].top === top) {
        element = this.vGrid.vGridGenerator.rowElementArray[i].div;
      }
    }
    if (element) {
      this.cells = element.querySelectorAll("." + this.classname);
    }

  }

  /***************************************************************************************
   * simple delay for the keydown events, like tabbing etc, so I cantrol the speed of it
   ***************************************************************************************/
  keyDownDelay(callback) {
    if (!this.timer) {
      this.timer = setTimeout(()=> {
        this.timer = null;
        callback();
      }, 150)
    }
  }

  /***************************************************************************************
   * get the index
   ***************************************************************************************/
  getIndex() {
    for (var i = 0; i < this.cells.length; i++) {
      if (this.element === this.cells[i]) {
        this.index = i;
        if (i === 0) {
          this.first = true;
          this.last = false;
        }
        if (i === this.cells.length - 1) {
          this.first = false;
          this.last = true;
        }
      }
    }
  }

  /***************************************************************************************
   * adds main keys, like arrow keys, tab, and page up/down
   ***************************************************************************************/
  addGridKeyListner() {

    this.element.onkeydown = (e) => {

      this.setCellsFromElement(this.element, 0);
      this.getIndex();

      //page up
      if (e.keyCode === 33) {
        e.preventDefault();
        this.keyDownDelay(() => {

          //get scrolltop
          var currentscrolltop = this.vGrid.vGridClientCtx.getScrollTop();

          //get content height/rows
          var rowHeight = this.vGrid.vGridConfig.attRowHeight;
          var containerHeight = this.vGrid.vGridGenerator.contentElement.clientHeight;
          var containerRows = parseInt(containerHeight / rowHeight, 10);
          this.top = this.setCellsFromElement(this.element, 0);

          var newTop = this.top - (containerRows * rowHeight);
          if ((newTop / rowHeight) <= 0) {
            newTop = 0;
          }

          //if last scroll was up then we need to reverse the buffer
          if (this.vGrid.vGridScrollEvents.lastScrollType === "down") {
            this.vGrid.vGridScrollEvents.onSmallScroll(false);
          }

          this.setCellsFromTopValue(newTop);
          this.dispatchCellClick(this.index);

          var setTop = newTop - parseInt((containerRows * rowHeight) / 2);
          this.vGrid.vGridClientCtx.setScrollTop(setTop);

        });
      }

      //page down
      if (e.keyCode === 34) {
        e.preventDefault();
        this.keyDownDelay(() => {

          //get scrolltop
          var currentscrolltop = this.vGrid.vGridClientCtx.getScrollTop();

          //get content height/rows
          var rowHeight = this.vGrid.vGridConfig.attRowHeight;
          var containerHeight = this.vGrid.vGridGenerator.contentElement.clientHeight;
          var containerRows = parseInt(containerHeight / rowHeight, 10);
          this.top = this.setCellsFromElement(this.element, 0);

          var newTop = this.top + (containerRows * rowHeight);
          if ((newTop / rowHeight) >= this.vGrid.vGridConfig.getCollectionLength()) {
            newTop = this.vGrid.vGridConfig.getCollectionLength() * rowHeight;
            newTop = newTop - rowHeight
          }

          //if last scroll was up then we need to reverse the buffer
          if (this.vGrid.vGridScrollEvents.lastScrollType === "up") {
            this.vGrid.vGridScrollEvents.onSmallScroll(true);
          }

          this.setCellsFromTopValue(newTop);
          this.dispatchCellClick(this.index);

          var setTop = newTop - parseInt((containerRows * rowHeight) / 2);
          this.vGrid.vGridClientCtx.setScrollTop(setTop);
        });
      }

      //arrow down
      if (e.keyCode === 40) {
        e.preventDefault();
        this.keyDownDelay(() => {
          if (this.vGrid.vGridScrollEvents.lastScrollType === "up") {
            this.vGrid.vGridScrollEvents.onSmallScroll(true);
          }
          this.top = this.setCellsFromElement(this.element, +1);
          this.dispatchCellClick(this.index)
        });
      }

      //arrow up
      if (e.keyCode === 38) {
        e.preventDefault();
        this.keyDownDelay(() => {
          if (this.vGrid.vGridScrollEvents.lastScrollType === "down") {
            this.vGrid.vGridScrollEvents.onSmallScroll(false);
          }
          this.top = this.setCellsFromElement(this.element, -1);
          this.dispatchCellClick(this.index)
        });
      }

      //tab and shift key for tabing in other direction
      if (e.keyCode === 9 && e.shiftKey === true) {
        if (this.row !== 0 && this.first) {
          e.preventDefault();
          this.keyDownDelay(() => {
            this.index = this.index - 1;
            if (this.first) {
              if (this.vGrid.vGridScrollEvents.lastScrollType === "down") {
                this.vGrid.vGridScrollEvents.onSmallScroll(false);
              }
              this.index = this.cells.length - 1;
              this.top = this.setCellsFromElement(this.element, -1)
            }
            this.dispatchCellClick(this.index)

          });
        }
      }

      //normal tabbing
      if (e.keyCode === 9 && e.shiftKey === false) {

        e.preventDefault();
        this.keyDownDelay(() => {
          this.index = this.index + 1;
          if (this.last) {
            if (this.vGrid.vGridScrollEvents.lastScrollType === "up") {
              this.vGrid.vGridScrollEvents.onSmallScroll(true);
            }
            this.index = 0;
            this.top = this.setCellsFromElement(this.element, 1)
          }
          this.dispatchCellClick(this.index)
        });

      }

    }
  }

}
<|endoftext|>