<commit_before>//requires jQuery
(function(window, $) {

	if(!window.ImgLoader) {
		window.ImgLoader = {};
	}

	var settings = ImgLoader.settings = {
		loadImgTags : true,
		loadBackgroundImages : false,

		loadContext : null,

		loadItems : null,

		itemLoaded : null,
		itemError : null,
		itemsCompleted : null,
	};

	ImgLoader.loadImages = function(options) {
		var itemsLoadedCount = 0,
			itemsCount = 0;

		$.extend(settings, options);

		var onImageLoad = function() {
			itemsLoadedCount++;
			if(settings.itemLoaded !== null && typeof settings.itemLoaded === 'function') {
				settings.itemLoaded(itemsLoadedCount / itemsCount);
			}

			if(itemsLoadedCount === itemsCount) {
				if(settings.itemsCompleted !== null && typeof settings.itemsCompleted === 'function') {
					settings.itemsCompleted();
				}
			}
		}

		var onImageError = function() {
			itemsLoadedCount++;
			if(settings.itemError !== null && typeof settings.itemError === 'function') {
				settings.itemError(itemsLoadedCount / itemsCount);
			}

			if(itemsLoadedCount === itemsCount) {
				if(settings.itemsCompleted !== null && typeof settings.itemsCompleted === 'function') {
					settings.itemsCompleted();
				}
			}
		};

		var toLoad = this.getImages();

		itemsCount = toLoad.length;

		for(var i=0; i<itemsCount; i++) {
			$("<img/>")
				.load(onImageLoad)
				.error(onImageError)
				.attr("src", toLoad[i]);
		}
	};

	ImgLoader.getImages = function() {
		var images = [];

		//Load <img> tags from the page
		if(settings.loadImgTags) {
			$('img[src]', settings.loadContext).each(function() {
				images.push($(this).attr('src'));
			});
		}

		//Load background images when there are some
		//TODO: Multiple backgrounds
		if(settings.loadBackgroundImages) {
			$('*', settings.loadContext).each(function() {
				var elmBg = $(this).css('background-image'),
					bgUrl;
				if(elmBg !== '' && elmBg !== 'none') {
					bgUrl = elmBg.replace(/^url\(["']?/, '').replace(/["']?\)$/, '');
					images.push(bgUrl);
				}
			});
		}

		//Load extra items passed by the user. Should be an array but accept a single string too
		if(settings.loadItems) {
			var extraItems = settings.loadItems;
			if (typeof extraItems == 'string' || extraItems instanceof String) {
				extraItems = [ extraItems ];
			}
			if (extraItems instanceof Array) {
				for(var i=0; i<extraItems.length; i++) {
					images.push(extraItems[i]);
				}
			}
		}

		return images;
	};

})(window, jQuery, undefined);<commit_msg>- Now dealing with duplicate images (They only trigger an event once) - Added a quick polyfill for IE < 9 that doesn't have Object.keys - Regex matching now deals with multiple backgrounds properly.<commit_after>//requires jQuery
(function(window, $) {
    'use strict';

    //Quick polyfill for Object.keys in IE < 9
    if (!Object.keys) {
        Object.keys = function (obj) {
            var keys = [],
                k;
            for (k in obj) {
                if (Object.prototype.hasOwnProperty.call(obj, k)) {
                    keys.push(k);
                }
            }
            return keys;
        };
    }

    if(!window.ImgLoader) {
        window.ImgLoader = {};
    }

    //Options
    var settings = ImgLoader.settings = {

        //Decides if <img> tags are loaded automatically
        loadImgTags : true,

        //Decides if elements that have background images are loaded automatically
        loadBackgroundImages : true,

        //Array of images that need to be loaded
        loadItems : null,

        //Selector or DOM element that decides the context in which the images are loaded
        //Ignored if loadImgTags and loadBackgroundImages are both set to false
        loadContext : null,

        //Callback for when an image is loaded (whether it fails or succeeds)
        itemCompletedCallback : null,

        //Callback for when all the items have been loaded.
        itemsCompletedCallback : null,
    };

    ImgLoader.loadImages = function(options) {
        $.extend(settings, options);

        var itemsLoaded = 0,
            allItemsCount,
            singleItemCallback,
            allItemsCallback;

        var imagesToLoad = Object.keys(this.getImages());

        allItemsCount = imagesToLoad.length;

        singleItemCallback = settings.itemCompletedCallback || $.noop;
        allItemsCallback = settings.itemsCompletedCallback || $.noop;

        for(var i=0; i<allItemsCount; i++) {

            //Create the image object in memory to make sure the event hasn't already happened.
            $("<img/>")
                .on("load.imgLoader error.imgLoader", function(event) {
                    itemsLoadedCount++;

                    singleItemCallback(itemsLoadedCount / allItemsCount, imagesToLoad[i], event.type === 'load');

                    if(itemsLoadedCount === allItemsCount) {
                        allItemsCallback();
                    }
                })
                .attr("src", imagesToLoad[i]);
        }
    };

    ImgLoader.getImages = function() {

        //Use as a hash to make sure an image with the same URL is not added twice
        var images = {};

        //Load <img> tags from the page
        if(settings.loadImgTags) {
            $('img[src!=""]', settings.loadContext).each(function() {
                images[$(this).attr('src')] = '';
            });
        }

        //Load background images from css when there are some
        if(settings.loadBackgroundImages) {

            //Regex pattern to match url('...')
            var matchUrl = /url\(\s*(['"]?)(.*?)\1\s*\)/g;

			$('*', settings.loadContext).each(function() {
                var elmBg = $(this).css('background-image'),
                    match,
                    bgUrl;

                if(elmBg === '' || elmBg === 'none') {
                    return;
                }

                //Needs to run in a loop for multiple backgrounds
                while (match = matchUrl.exec(elmBg)) {

                    //The first capturing group is only used for the \1 backreference (for the matching quotes)
                    //Discard the first group and only care about the second
                    bgUrl = match[2];

                    //Ignore inline data images
                    if(bgUrl.slice(0,5) !== 'data:') {
                        images[bgUrl] = '';
                    }
                }
			});
		}

		//Load extra items passed by the user.
		if(settings.loadItems) {

			var extraItems = settings.loadItems;

            //Should be an array but accept a single string too
			if (typeof extraItems == 'string' || extraItems instanceof String) {
				extraItems = [ extraItems ];
			}

			if (extraItems instanceof Array) {
				for(var i=0; i<extraItems.length; i++) {
					images[extraItems[i]] = '';
				}
			}
		}

		return images;
	};

})(window, jQuery, undefined);<|endoftext|>


<commit_before>var nav = require('./nav.js')
var analytics = require('./analytics')
import Svg4everybody from 'svg4everybody'

nav.init()
analytics.init()

var html = document.querySelector('html')
html.classList.remove('no-js')
html.classList.add('js')

// Check if we need fastclick
if ('touchAction' in document.body.style) {
  document.body.style.touchAction = 'manipulation'
} else {
  require.ensure(['fastclick'], (require) => {
    const FastClick = require('fastclick')

    window.addEventListener('load', () => {
      FastClick.attach(document.body)
    })
  }, 'fastclick')
}

// SVG support
Svg4everybody()

let pathName = window.location.pathname
let activePage = pathName.length > 1
  ? '/' + pathName.split('/')[1] + '/'
  : '/'

let navLinks = document.querySelectorAll('.nav__item a')
let activeNav = Array.from(navLinks).filter((l) => {
  return l.getAttribute('href') === activePage
})[0]

console.log(activePage)
activeNav.parentNode.classList.add('nav__item--active')
<commit_msg>tidy up common.js<commit_after>var nav = require('./nav.js')
var analytics = require('./analytics')
import Svg4everybody from 'svg4everybody'

let removeNoJS = () => {
  var html = document.querySelector('html')
  html.classList.remove('no-js')
  html.classList.add('js')
}

let fastClickCheck = () => {
  if ('touchAction' in document.body.style) {
    document.body.style.touchAction = 'manipulation'
  } else {
    require.ensure(['fastclick'], (require) => {
      const FastClick = require('fastclick')

      window.addEventListener('load', () => {
        FastClick.attach(document.body)
      })
    }, 'fastclick')
  }
}

let setActiveNav = () => {
  let pathName = window.location.pathname
  let activePage = pathName.length > 1
    ? '/' + pathName.split('/')[1] + '/'
    : '/'

  let navLinks = document.querySelectorAll('.nav__item a')
  let activeNav = Array.from(navLinks).filter((l) => {
    return l.getAttribute('href') === activePage
  })[0]

  console.log(activePage)
  activeNav.parentNode.classList.add('nav__item--active')
}

removeNoJS()
nav.init()
analytics.init()
fastClickCheck()
setActiveNav()
Svg4everybody() // SVG support
<|endoftext|>


<commit_before>// Parameters for the application

export default {
  queryURL: 'https://unece-stardog.ichec.ie/annex/classifications/sparql/query'
}
<commit_msg>Change backend to LOS GraphDB<commit_after>// Parameters for the application

export default {
  queryURL: 'http://graphdb.linked-open-statistics.org/repositories/classifications'
}
<|endoftext|>


<commit_before>import * as keys from './keys';
import createMenu from './createMenu';
import focusManager from './focusManager';

export default function createAriaMenuButton(React, classNames) {

  const Menu = createMenu(React, classNames);
  const CSSTransitionGroup = (React.addons) ? React.addons.CSSTransitionGroup : false;

  class AriaMenuButton extends React.Component {

    constructor(props) {
      super(props);
      this.state = { isOpen: !!props.isOpen };
      this.focusManager = focusManager();
    }

    shouldComponentUpdate(newProps, newState) {
      return (
        this.state.isOpen !== newState.isOpen
        || this.props.selectedValue !== newProps.selectedValue
      );
    }

    componentWillMount() {
      if (this.props.transition && !CSSTransitionGroup) {
        throw new Error(
          'If you want to use transitions with ariaMenuButton, you need to pass it ' +
          'React with addons'
        );
      }
    }

    componentDidMount() {
      this.focusManager.trigger = React.findDOMNode(this.refs.trigger);
    }

    openMenu(innerFocus=false) {
      this.setState({ isOpen: true, innerFocus: innerFocus });
    }

    closeMenu(focusTrigger=true) {
      this.setState({ isOpen: false, innerFocus: false }, () => {
        if (focusTrigger) this.focusManager.focusTrigger();
        this.focusManager.currentFocus = -1;
      });
    }

    toggleMenu() {
      if (this.state.isOpen) this.closeMenu();
      else this.openMenu();
    }

    handleAnywhereKey(e) {
      const key = e.key;
      const isLetterKey = isLetterKeyEvent(e);

      if (key !== keys.DOWN && !isLetterKey) return;
      e.preventDefault();

      if (key === keys.DOWN) {
        // "With focus on the button and the drop-down menu open,
        // pressing Down Arrow will move focus into the menu onto
        // the first menu item. [...]"
        // "With focus on the drop-down menu, the Up and Down Arrow
        // keys move focus within the menu items, "wrapping" at the top and bottom."
        if (this.state.isOpen) this.focusManager.moveDown();

        // "With focus on the button and no drop-down menu displayed,
        // pressing Down Arrow will open the drop-down menu and move focus
        // into the menu and onto the first menu item."
        else this.openMenu(true);
      }

      else if (isLetterKey && this.state.isOpen) this.checkLetterKeys(e.keyCode);
    }

    // "With focus on the button pressing Space or Enter will toggle
    // the display of the drop-down menu. Focus remains on the button."
    handleTriggerKey(e) {
      const key = e.key;
      if (key !== keys.ENTER && key !== keys.SPACE) return;
      e.preventDefault();
      this.toggleMenu();
    }

    handleMenuKey(e) {
      // "With focus on the drop-down menu, pressing Escape closes
      // the menu and returns focus to the button.
      if (e.key === keys.ESCAPE) this.closeMenu();

      // "With focus on the drop-down menu, the Up and Down Arrow
      // keys move focus within the menu items, "wrapping" at the top and bottom."
      else if (e.key === keys.UP && this.state.isOpen) {
        e.preventDefault();
        this.focusManager.moveUp();
      }
    }

    checkLetterKeys(kc) {
      // "Typing a letter (printable character) key moves focus to the next
      // instance of a visible node whose title begins with that printable letter."
      this.focusManager.moveToLetter(String.fromCharCode(kc));
    }

    handleBlur() {
      setTimeout(() => {
        const activeEl = document.activeElement;
        if (activeEl === this.focusManager.trigger) return;
        if (this.focusManager.focusables.some(f => f.node === activeEl)) return;
        this.closeMenu(false);
      }, 0);
    }

    handleSelection(v) {
      if (this.props.closeOnSelection) this.closeMenu();
      this.props.handleSelection(v);
    }

    render() {
      const props = this.props;
      const isOpen = this.state.isOpen;

      const menu = (isOpen) ? (
        <Menu {...props}
         handleSelection={this.handleSelection.bind(this)}
         receiveFocus={this.state.innerFocus}
         focusManager={this.focusManager} />
      ) : false;

      const menuWrapper = (props.transition) ? (
        <CSSTransitionGroup transitionName='is'
         component='div'
         className='AriaMenuButton-menuWrapper AriaMenuButton-menuWrapper--trans'
         onKeyDown={this.handleMenuKey.bind(this)}>
          {menu}
        </CSSTransitionGroup>
      ) : (

          {menu}

      );

      const triggerClasses = classNames({
        'AriaMenuButton-trigger': true,
        'is-open': isOpen
      });

      return (

          <div id={`${props.id}-trigger`}
           className={triggerClasses}
           onClick={this.toggleMenu.bind(this)}
           onKeyDown={this.handleTriggerKey.bind(this)}
           ref='trigger'
           aria-haspopup={true}
           aria-expanded={isOpen}
           role='button'
           tabIndex='0'>
            {props.triggerLabel}

          {menuWrapper}

      );
    }
  }

  const pt = React.PropTypes;
  AriaMenuButton.propTypes = {
    handleSelection: pt.func.isRequired,
    id: pt.string.isRequired,
    items: pt.arrayOf(pt.object).isRequired,
    triggerLabel: pt.string.isRequired,
    closeOnSelection: pt.bool,
    flushRight: pt.bool,
    isOpen: pt.bool,
    selectedValue: pt.oneOfType([pt.string, pt.number, pt.bool]),
    transition: pt.bool
  };

  return AriaMenuButton;
}

function isLetterKeyEvent(e) {
  return e.keyCode >= keys.LOWEST_LETTER_CODE && e.keyCode <= keys.HIGHEST_LETTER_CODE;
}
<commit_msg>clickOutside handling with mobile support; addresses #15<commit_after>import * as keys from './keys';
import createMenu from './createMenu';
import focusManager from './focusManager';

export default function createAriaMenuButton(React, classNames) {

  const Menu = createMenu(React, classNames);
  const CSSTransitionGroup = (React.addons) ? React.addons.CSSTransitionGroup : false;

  class AriaMenuButton extends React.Component {

    constructor(props) {
      super(props);
      this.state = { isOpen: !!props.isOpen };
      this.focusManager = focusManager();
    }

    shouldComponentUpdate(newProps, newState) {
      return (
        this.state.isOpen !== newState.isOpen
        || this.props.selectedValue !== newProps.selectedValue
      );
    }

    componentWillMount() {
      if (this.props.transition && !CSSTransitionGroup) {
        throw new Error(
          'If you want to use transitions with ariaMenuButton, you need to pass it ' +
          'React with addons'
        );
      }
    }

    componentDidMount() {
      this.focusManager.trigger = React.findDOMNode(this.refs.trigger);
    }

    openMenu(innerFocus=false) {
      this.setState({ isOpen: true, innerFocus: innerFocus });
    }

    closeMenu(focusTrigger=true) {
      console.log('trying to close');
      this.setState({ isOpen: false, innerFocus: false }, () => {
        if (focusTrigger) this.focusManager.focusTrigger();
        this.focusManager.currentFocus = -1;
      });
    }

    toggleMenu() {
      if (this.state.isOpen) this.closeMenu();
      else this.openMenu();
    }

    handleAnywhereKey(e) {
      const key = e.key;
      const isLetterKey = isLetterKeyEvent(e);

      if (key !== keys.DOWN && !isLetterKey) return;
      e.preventDefault();

      if (key === keys.DOWN) {
        // "With focus on the button and the drop-down menu open,
        // pressing Down Arrow will move focus into the menu onto
        // the first menu item. [...]"
        // "With focus on the drop-down menu, the Up and Down Arrow
        // keys move focus within the menu items, "wrapping" at the top and bottom."
        if (this.state.isOpen) this.focusManager.moveDown();

        // "With focus on the button and no drop-down menu displayed,
        // pressing Down Arrow will open the drop-down menu and move focus
        // into the menu and onto the first menu item."
        else this.openMenu(true);
      }

      else if (isLetterKey && this.state.isOpen) this.checkLetterKeys(e.keyCode);
    }

    // "With focus on the button pressing Space or Enter will toggle
    // the display of the drop-down menu. Focus remains on the button."
    handleTriggerKey(e) {
      const key = e.key;
      if (key !== keys.ENTER && key !== keys.SPACE) return;
      e.preventDefault();
      this.toggleMenu();
    }

    handleMenuKey(e) {
      // "With focus on the drop-down menu, pressing Escape closes
      // the menu and returns focus to the button.
      if (e.key === keys.ESCAPE) this.closeMenu();

      // "With focus on the drop-down menu, the Up and Down Arrow
      // keys move focus within the menu items, "wrapping" at the top and bottom."
      else if (e.key === keys.UP && this.state.isOpen) {
        e.preventDefault();
        this.focusManager.moveUp();
      }
    }

    checkLetterKeys(kc) {
      // "Typing a letter (printable character) key moves focus to the next
      // instance of a visible node whose title begins with that printable letter."
      this.focusManager.moveToLetter(String.fromCharCode(kc));
    }

    handleBlur() {
      setTimeout(() => {
        const activeEl = document.activeElement;
        if (activeEl === this.focusManager.trigger) return;
        if (this.focusManager.focusables.some(f => f.node === activeEl)) return;
        this.closeMenu(false);
      }, 0);
    }

    handleSelection(v) {
      if (this.props.closeOnSelection) this.closeMenu();
      this.props.handleSelection(v);
    }

    render() {
      const props = this.props;
      const isOpen = this.state.isOpen;

      const menu = (isOpen) ? (
        <Menu {...props}
         handleSelection={this.handleSelection.bind(this)}
         receiveFocus={this.state.innerFocus}
         focusManager={this.focusManager} />
      ) : false;

      const menuWrapper = (props.transition) ? (
        <CSSTransitionGroup transitionName='is'
         component='div'
         className='AriaMenuButton-menuWrapper AriaMenuButton-menuWrapper--trans'
         onKeyDown={this.handleMenuKey.bind(this)}>
          {menu}
        </CSSTransitionGroup>
      ) : (

          {menu}

      );

      const triggerClasses = classNames({
        'AriaMenuButton-trigger': true,
        'is-open': isOpen
      });

      const innerStyle = (!isOpen) ? {} : {
        display: 'inline-block',
        position: 'relative',
        zIndex: '100'
      };

      const outsideOverlay = (!isOpen) ? false : (
        <div id={`${props.id}-outside`}
         onClick={this.closeMenu.bind(this)}
         style={{
           cursor: 'pointer',
           position: 'fixed',
           top: 0, bottom: 0, left: 0, right: 0,
           zIndex: '99',
           '-webkit-tap-highlight-color': 'rgba(0, 0, 0, 0)'
         }} />
      );

      return (

          {outsideOverlay}

            <div id={`${props.id}-trigger`}
             className={triggerClasses}
             onClick={this.toggleMenu.bind(this)}
             onKeyDown={this.handleTriggerKey.bind(this)}
             ref='trigger'
             aria-haspopup={true}
             aria-expanded={isOpen}
             role='button'
             tabIndex='0'>
              {props.triggerLabel}

            {menuWrapper}

      );
    }
  }

  const pt = React.PropTypes;
  AriaMenuButton.propTypes = {
    handleSelection: pt.func.isRequired,
    id: pt.string.isRequired,
    items: pt.arrayOf(pt.object).isRequired,
    triggerLabel: pt.string.isRequired,
    closeOnSelection: pt.bool,
    flushRight: pt.bool,
    isOpen: pt.bool,
    selectedValue: pt.oneOfType([pt.string, pt.number, pt.bool]),
    transition: pt.bool
  };

  return AriaMenuButton;
}

function isLetterKeyEvent(e) {
  return e.keyCode >= keys.LOWEST_LETTER_CODE && e.keyCode <= keys.HIGHEST_LETTER_CODE;
}
<|endoftext|>


<commit_before>var RPi;

function RaspberryPi(model, stage3d)
{
    this.model = $( model );
    this.rotateX = 70;
    this.rotateY = 0;
    this.rotateZ = 40;

    this.traqball = new Traqball({
        stage: stage3d,
        //axis: [0.5,1,0,0.25],
        prespective: 1000
    });

    this.components = {
        ethernet:   new HWComponent("ethernet", this),
        usb:        new HWComponent("usb", this),
        cpu:        new HWComponent("cpu", this),
        ram:        new HWComponent("ram", this),
        sd:         new HWComponent("sd", this)
    }
    this.initSelf();
}

RaspberryPi.prototype.initSelf = function()
{
    var thisObj = this;

    $("#default_button").click(function(){
        thisObj.defaultPosition();
    });
};

RaspberryPi.prototype.defaultPosition = function()
{
    //this.traqball.disable();
    this.model.addClass( "picontainer_mover" );
    this.model.css( "-webkit-transform", "rotateX(58deg) rotateY(0deg) rotateZ(45deg)");
    this.model.css( "transform", "rotateX(58deg) rotateY(0deg) rotateZ(45deg)" );
    var thisObj = this;
    setTimeout(function(){
        thisObj.model.removeClass( "picontainer_mover" );
        //thisObj.traqball.activate();
    },500);

};

RaspberryPi.prototype.hideAll = function()
{
    for(var key in this.components)
    {
        var comp = this.components[key];
        if(comp.out)
        {
            comp.animateIn();
        }
    }
}

$(".sd").click(function(){
    this.addClass("sdout");
    alert("Hello");
});

function HWComponent( id, rpi )
{
    var thisObj = this;
    this.parentRPi = rpi;
    this.element = $("."+id );
    this.moverClassOut = id + "-mover-out";
    this.moverClassIn = id + "-mover-in";
    this.moverClassExt = id + "-ext";
    this.out = false;

    this.element.click(function ()
    {
        if (thisObj.out === false)
        {
            thisObj.parentRPi.traqball.disable();
            thisObj.parentRPi.defaultPosition();
            setTimeout(function() {
                thisObj.animateOut();
            }, 500);
        }
        else
        {
            thisObj.animateIn();
            setTimeout(function() {
                thisObj.parentRPi.traqball.activate();
                console.log("Activated")
            }, 500);
        }
    });
}

HWComponent.prototype.animateOut = function()
{
    var thisObj = this;
    this.element.addClass(this.moverClassOut);
    this.parentRPi.hideAll();
    this.element.bind("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){
        thisObj.element.addClass(thisObj.moverClassExt);
        thisObj.element.removeClass(thisObj.moverClassOut);
        thisObj.element.unbind("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd");
    });
    this.out = true;
};

HWComponent.prototype.animateIn = function()
{
    var thisObj = this;
    this.element.removeClass(this.moverClassExt);
    this.element.addClass(this.moverClassIn);

    this.element.bind("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){
        thisObj.element.removeClass(thisObj.moverClassIn);
        thisObj.element.unbind("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd");
    });
    this.out = false;
};

$(document).ready(function()
{
    RPi = new RaspberryPi(".pi", "stage");
});
<commit_msg>add strict<commit_after>var RPi;

function RaspberryPi(model, stage3d)
{
    'use strict'
    this.model = $( model );
    this.rotateX = 70;
    this.rotateY = 0;
    this.rotateZ = 40;

    this.traqball = new Traqball({
        stage: stage3d,
        //axis: [0.5,1,0,0.25],
        prespective: 1000
    });

    this.components = {
        ethernet:   new HWComponent("ethernet", this),
        usb:        new HWComponent("usb", this),
        cpu:        new HWComponent("cpu", this),
        ram:        new HWComponent("ram", this),
        sd:         new HWComponent("sd", this)
    };
    this.initSelf();
}

RaspberryPi.prototype.initSelf = function ()
{
    'use strict'
    var thisObj = this;

    $("#default_button").click(function (){
        thisObj.defaultPosition();
    });
};

RaspberryPi.prototype.defaultPosition = function ()
{
    'use strict'
    //this.traqball.disable();
    this.model.addClass( "picontainer_mover" );
    this.model.css( "-webkit-transform", "rotateX(58deg) rotateY(0deg) rotateZ(45deg)");
    this.model.css( "transform", "rotateX(58deg) rotateY(0deg) rotateZ(45deg)" );
    var thisObj = this;
    setTimeout(function(){
        thisObj.model.removeClass( "picontainer_mover" );
        //thisObj.traqball.activate();
    },500);

};

RaspberryPi.prototype.hideAll = function()
{
    'use strict'
    for(var key in this.components)
    {
        var comp = this.components[key];
        if(comp.out)
        {
            comp.animateIn();
        }
    }
}

function HWComponent( id, rpi )
{
    'use strict'
    var thisObj = this;
    this.parentRPi = rpi;
    this.element = $("."+id );
    this.moverClassOut = id + "-mover-out";
    this.moverClassIn = id + "-mover-in";
    this.moverClassExt = id + "-ext";
    this.out = false;

    this.element.click(function ()
    {
        if (thisObj.out === false)
        {
            thisObj.parentRPi.traqball.disable();
            thisObj.parentRPi.defaultPosition();
            setTimeout(function() {
                thisObj.animateOut();
            }, 500);
        }
        else
        {
            thisObj.animateIn();
            setTimeout(function() {
                thisObj.parentRPi.traqball.activate();
                console.log("Activated")
            }, 500);
        }
    });
}

HWComponent.prototype.animateOut = function()
{
    'use strict'
    var thisObj = this;
    this.element.addClass(this.moverClassOut);
    this.parentRPi.hideAll();
    this.element.bind("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){
        thisObj.element.addClass(thisObj.moverClassExt);
        thisObj.element.removeClass(thisObj.moverClassOut);
        thisObj.element.unbind("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd");
    });
    this.out = true;
};

HWComponent.prototype.animateIn = function()
{
    'use strict'
    var thisObj = this;
    this.element.removeClass(this.moverClassExt);
    this.element.addClass(this.moverClassIn);

    this.element.bind("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){
        thisObj.element.removeClass(thisObj.moverClassIn);
        thisObj.element.unbind("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd");
    });
    this.out = false;
};

$(document).ready(function()
{
    RPi = new RaspberryPi(".pi", "stage");
});
<|endoftext|>


<commit_before>var ticket_data = null;
var ticketTypes = null;
var earlyEntry = null;

function short_hash(data, type, row, meta)
{
    var short_hash = data.substring(0,7);
    return ''+short_hash+'';
}

function renderTicketType(data, type, row, meta)
{
    if(ticketTypes === null || ticketTypes[data] === undefined)
    {
        return data;
    }
    else
    {
        return ticketTypes[data];
    }
}

function get_ticket_by_selected()
{
    if(ticket_data.selected == -1)
    {
        return ticket_data.current;
    }
    return ticket_data.history[ticket_data.selected];
}

function show_ticket_from_data(data)
{
    var read_only = true;
    if(data.selected == -1)
    {
        ticket = data.current;
        $('#right_arrow').hide();
        if(data.history !== undefined && data.history.length > 0)
        {
            $('#left_arrow').show();
        }
        else
        {
            $('#left_arrow').hide();
        }
        read_only = false;
        $('#saveticket').removeAttr('disabled');
    }
    else
    {
        ticket = data.history[data.selected];
        if(data.selected == (data.history.length - 1))
        {
            $('#left_arrow').hide();
        }
        else
        {
            $('#left_arrow').show();
        }
        $('#right_arrow').show();
        $('#saveticket').attr('disabled', 'true');
    }
    $('#hash').val(ticket.hash);
    $('#year').val(ticket.year);
    $('#firstName').val(ticket.firstName);
    $('#lastName').val(ticket.lastName);
    $('#email').val(ticket.email);
    $('#request_id').val(ticket.request_id);
    $('#type').val(ticket.type);
    $('#guardian_first').val(ticket.guardian_first);
    $('#guardian_last').val(ticket.guardian_last);
    $('#earlyEntryWindow').val(ticket.earlyEntryWindow);
    if(ticket.sold == 1)
    {
        $('#sold').prop('checked', true);
    }
    else
    {
        $('#sold').prop('checked', false);
    }
    if(ticket.used == 1)
    {
        $('#used').prop('checked', true);
    }
    else
    {
        $('#used').prop('checked', false);
    }
    if(ticket.void == 1)
    {
        $('#void').prop('checked', true);
    }
    else
    {
        $('#void').prop('checked', false);
    }
    $('#comments').val(ticket.comments);
    if(read_only)
    {
        $('#firstName').prop('disabled', true);
        $('#lastName').prop('disabled', true);
        $('#email').prop('disabled', true);
        $('#request_id').prop('disabled', true);
        $('#type').prop('disabled', true);
        $('#guardian_first').prop('disabled', true);
        $('#guardian_last').prop('disabled', true);
        $('#sold').prop('disabled', true);
        $('#used').prop('disabled', true);
        $('#void').prop('disabled', true);
        $('#comments').prop('disabled', true);
    }
    else
    {
        $('#firstName').prop('disabled', false);
        $('#lastName').prop('disabled', false);
        $('#email').prop('disabled', false);
        $('#request_id').prop('disabled', false);
        $('#type').prop('disabled', false);
        $('#guardian_first').prop('disabled', false);
        $('#guardian_last').prop('disabled', false);
        $('#sold').prop('disabled', false);
        $('#used').prop('disabled', false);
        $('#void').prop('disabled', false);
        $('#comments').prop('disabled', false);
    }
    $('#ticket_modal').modal('show');
    console.log(data);
}

function ticket_data_done(data)
{
    var ticket = null;
    if(data.selected === undefined)
    {
        alert('Unable to retrieve ticket history data');
        console.log(data);
        return;
    }
    ticket_data = data;
    show_ticket_from_data(data);
}

function view_ticket(hash)
{
    $.ajax({
        url: '../api/v1/tickets/'+hash+'?with_history=1',
        type: 'get',
        dataType: 'json',
        success: ticket_data_done});
}

function prev_ticket()
{
    ticket_data.selected++;
    show_ticket_from_data(ticket_data);
}

function next_ticket()
{
    ticket_data.selected--;
    show_ticket_from_data(ticket_data);
}

function set_if_value_different(ticket, obj, inputname, fieldname)
{
    if(fieldname === undefined)
    {
        fieldname = inputname;
    }
    var input = $('#'+inputname);
    if(input.attr('type') === 'checkbox')
    {
         if(input.is(':checked'))
         {
             if(ticket[fieldname] == 0)
             {
                 obj[fieldname] = 1;
             }
         }
         else if(ticket[fieldname] == 1)
         {
             obj[fieldname] = 0;
         }
    }
    else
    {
        var val = $('#'+inputname).val();
        if(val != ticket[fieldname])
        {
            obj[fieldname] = val;
        }
    }
}

function save_ticket_done(jqXHR)
{
    if(jqXHR.status != 200)
    {
        alert("Unable to save ticket!");
    }
    else
    {
        $('#ticket_modal').modal('hide');
        yearChanged();
    }
}

function noChangeDone(jqXHR)
{
    if(jqXHR.status != 200)
    {
        alert("Error!");
    }
    else
    {
        $('#ticket_modal').modal('hide');
    }
}

function save_ticket()
{
    var ticket = get_ticket_by_selected();
    var obj = {};
    set_if_value_different(ticket, obj, 'email');
    set_if_value_different(ticket, obj, 'firstName');
    set_if_value_different(ticket, obj, 'lastName');
    set_if_value_different(ticket, obj, 'request_id');
    set_if_value_different(ticket, obj, 'type');
    set_if_value_different(ticket, obj, 'guardian_first');
    set_if_value_different(ticket, obj, 'guardian_last');
    set_if_value_different(ticket, obj, 'sold');
    set_if_value_different(ticket, obj, 'used');
    set_if_value_different(ticket, obj, 'void');
    set_if_value_different(ticket, obj, 'earlyEntryWindow');
    if(Object.keys(obj).length > 0)
    {
        $.ajax({
            url: '../api/v1/tickets/'+ticket.hash,
            contentType: 'application/json',
            data: JSON.stringify(obj),
            type: 'patch',
            dataType: 'json',
            complete: save_ticket_done});
    }
    else
    {
        $('#ticket_modal').modal('hide');
    }
}

function resendTicketEmail()
{
    var ticket = get_ticket_by_selected();
    $.ajax({
        url: '../api/v1/tickets/'+ticket.hash+'/Actions/Ticket.SendEmail',
        contentType: 'application/json',
        type: 'post',
        dataType: 'json',
        complete: noChangeDone});
}

function spinHash()
{
    var ticket = get_ticket_by_selected();
    $.ajax({
        url: '../api/v1/tickets/'+ticket.hash+'/Actions/Ticket.SpinHash',
        contentType: 'application/json',
        type: 'post',
        dataType: 'json',
        complete: save_ticket_done});
}

function backend_search_done(data)
{
    var tickets = data;
    var history = false;
    if(data.old_tickets !== undefined)
    {
        tickets = data.old_tickets;
        history = true;
    }
    view_ticket(tickets[0].hash);
}

function table_searched()
{
    var dt_api = $('#tickets').DataTable();
    if(dt_api.rows({'search':'applied'})[0].length == 0)
    {
        $.ajax({
            url: '../api/v1/tickets/search/'+dt_api.search(),
            type: 'get',
            dataType: 'json',
            success: backend_search_done
        });
    }
}

function yearChanged(e)
{
    var year;
    if(e === undefined)
    {
        year = $('#ticket_year').value;
    }
    else
    {
        year = e.currentTarget.value;
    }
    $('#tickets').DataTable().ajax.url('../api/v1/tickets?filter=year eq '+year+'&fmt=data-table').load();
}

function gotTicketYears(jqXHR)
{
    if(jqXHR.status !== 200)
    {
        alert('Unable to obtain valid ticket years!');
        console.log(jqXHR);
        return;
    }
    jqXHR.responseJSON.sort().reverse();
    for(var i = 0; i < jqXHR.responseJSON.length; i++)
    {
        $('#ticket_year').append($('<option/>').attr('value', jqXHR.responseJSON[i]).text(jqXHR.responseJSON[i]));
    }
    $('#ticket_year').on('change', yearChanged);
    var e = {};
    e.currentTarget = {};
    e.currentTarget.value = $('#ticket_year').val();
    yearChanged(e);
}

function gotTicketTypes(jqXHR)
{
    if(jqXHR.status !== 200 || jqXHR.responseJSON === undefined)
    {
        console.log(jqXHR);
        return;
    }
    var data = jqXHR.responseJSON;
    var options = '';
    ticketTypes = {};
    for(i = 0; i < data.length; i++)
    {
        options+='<option value="'+data[i].typeCode+'">'+data[i].description+'</option>';
        ticketTypes[data[i].typeCode] = data[i].description;
    }
    $('#type').replaceWith('<select id="type" name="type" class="form-control">'+options+'</select>');
}

function gotEarlyEntry(jqXHR)
{
    if(jqXHR.status !== 200 || jqXHR.responseJSON === undefined)
    {
        console.log(jqXHR);
        return;
    }
    var data = jqXHR.responseJSON;
    var options = '';
    earlyEntry = {};
    for(i = 0; i < data.length; i++)
    {
        options+='<option value="'+data[i].earlyEntrySetting+'">'+data[i].earlyEntryDescription+'</option>';
        earlyEntry[data[i].earlyEntrySetting] = data[i].earlyEntryDescription;
    }
    $('#earlyEntryWindow').replaceWith('<select id="earlyEntryWindow" name="earlyEntryWindow" class="form-control">'+options+'</select>');
}

function init_page()
{
    $('#tickets').dataTable({
        columns: [
            {'data': 'hash', 'render':short_hash},
            {'data': 'firstName'},
            {'data': 'lastName'},
            {'data': 'email'},
            {'data': 'type', 'render': renderTicketType}
        ]
    });
    $.ajax({
        url: '../api/v1/globals/years',
        type: 'get',
        dataType: 'json',
        complete: gotTicketYears});
    $.ajax({
        url: '../api/v1/globals/ticket_types',
        type: 'get',
        dataType: 'json',
        complete: gotTicketTypes});
    $.ajax({
        url: '../api/v1/earlyEntry',
        type: 'get',
        dataType: 'json',
        complete: gotEarlyEntry});

    $('#tickets').on('search.dt', table_searched);
}

$(init_page)
<commit_msg>Fix Comments on tickets<commit_after>var ticket_data = null;
var ticketTypes = null;
var earlyEntry = null;

function short_hash(data, type, row, meta)
{
    var short_hash = data.substring(0,7);
    return ''+short_hash+'';
}

function renderTicketType(data, type, row, meta)
{
    if(ticketTypes === null || ticketTypes[data] === undefined)
    {
        return data;
    }
    else
    {
        return ticketTypes[data];
    }
}

function get_ticket_by_selected()
{
    if(ticket_data.selected == -1)
    {
        return ticket_data.current;
    }
    return ticket_data.history[ticket_data.selected];
}

function show_ticket_from_data(data)
{
    var read_only = true;
    if(data.selected == -1)
    {
        ticket = data.current;
        $('#right_arrow').hide();
        if(data.history !== undefined && data.history.length > 0)
        {
            $('#left_arrow').show();
        }
        else
        {
            $('#left_arrow').hide();
        }
        read_only = false;
        $('#saveticket').removeAttr('disabled');
    }
    else
    {
        ticket = data.history[data.selected];
        if(data.selected == (data.history.length - 1))
        {
            $('#left_arrow').hide();
        }
        else
        {
            $('#left_arrow').show();
        }
        $('#right_arrow').show();
        $('#saveticket').attr('disabled', 'true');
    }
    $('#hash').val(ticket.hash);
    $('#year').val(ticket.year);
    $('#firstName').val(ticket.firstName);
    $('#lastName').val(ticket.lastName);
    $('#email').val(ticket.email);
    $('#request_id').val(ticket.request_id);
    $('#type').val(ticket.type);
    $('#guardian_first').val(ticket.guardian_first);
    $('#guardian_last').val(ticket.guardian_last);
    $('#earlyEntryWindow').val(ticket.earlyEntryWindow);
    if(ticket.sold == 1)
    {
        $('#sold').prop('checked', true);
    }
    else
    {
        $('#sold').prop('checked', false);
    }
    if(ticket.used == 1)
    {
        $('#used').prop('checked', true);
    }
    else
    {
        $('#used').prop('checked', false);
    }
    if(ticket.void == 1)
    {
        $('#void').prop('checked', true);
    }
    else
    {
        $('#void').prop('checked', false);
    }
    $('#comments').val(ticket.comments);
    if(read_only)
    {
        $('#firstName').prop('disabled', true);
        $('#lastName').prop('disabled', true);
        $('#email').prop('disabled', true);
        $('#request_id').prop('disabled', true);
        $('#type').prop('disabled', true);
        $('#guardian_first').prop('disabled', true);
        $('#guardian_last').prop('disabled', true);
        $('#sold').prop('disabled', true);
        $('#used').prop('disabled', true);
        $('#void').prop('disabled', true);
        $('#comments').prop('disabled', true);
    }
    else
    {
        $('#firstName').prop('disabled', false);
        $('#lastName').prop('disabled', false);
        $('#email').prop('disabled', false);
        $('#request_id').prop('disabled', false);
        $('#type').prop('disabled', false);
        $('#guardian_first').prop('disabled', false);
        $('#guardian_last').prop('disabled', false);
        $('#sold').prop('disabled', false);
        $('#used').prop('disabled', false);
        $('#void').prop('disabled', false);
        $('#comments').prop('disabled', false);
    }
    $('#ticket_modal').modal('show');
    console.log(data);
}

function ticket_data_done(data)
{
    var ticket = null;
    if(data.selected === undefined)
    {
        alert('Unable to retrieve ticket history data');
        console.log(data);
        return;
    }
    ticket_data = data;
    show_ticket_from_data(data);
}

function view_ticket(hash)
{
    $.ajax({
        url: '../api/v1/tickets/'+hash+'?with_history=1',
        type: 'get',
        dataType: 'json',
        success: ticket_data_done});
}

function prev_ticket()
{
    ticket_data.selected++;
    show_ticket_from_data(ticket_data);
}

function next_ticket()
{
    ticket_data.selected--;
    show_ticket_from_data(ticket_data);
}

function set_if_value_different(ticket, obj, inputname, fieldname)
{
    if(fieldname === undefined)
    {
        fieldname = inputname;
    }
    var input = $('#'+inputname);
    if(input.attr('type') === 'checkbox')
    {
         if(input.is(':checked'))
         {
             if(ticket[fieldname] == 0)
             {
                 obj[fieldname] = 1;
             }
         }
         else if(ticket[fieldname] == 1)
         {
             obj[fieldname] = 0;
         }
    }
    else
    {
        var val = $('#'+inputname).val();
        if(val != ticket[fieldname])
        {
            obj[fieldname] = val;
        }
    }
}

function save_ticket_done(jqXHR)
{
    if(jqXHR.status != 200)
    {
        alert("Unable to save ticket!");
    }
    else
    {
        $('#ticket_modal').modal('hide');
        yearChanged();
    }
}

function noChangeDone(jqXHR)
{
    if(jqXHR.status != 200)
    {
        alert("Error!");
    }
    else
    {
        $('#ticket_modal').modal('hide');
    }
}

function save_ticket()
{
    var ticket = get_ticket_by_selected();
    var obj = {};
    set_if_value_different(ticket, obj, 'email');
    set_if_value_different(ticket, obj, 'firstName');
    set_if_value_different(ticket, obj, 'lastName');
    set_if_value_different(ticket, obj, 'request_id');
    set_if_value_different(ticket, obj, 'type');
    set_if_value_different(ticket, obj, 'guardian_first');
    set_if_value_different(ticket, obj, 'guardian_last');
    set_if_value_different(ticket, obj, 'sold');
    set_if_value_different(ticket, obj, 'used');
    set_if_value_different(ticket, obj, 'void');
    set_if_value_different(ticket, obj, 'earlyEntryWindow');
    set_if_value_different(ticket, obj, 'comments');
    if(Object.keys(obj).length > 0)
    {
        $.ajax({
            url: '../api/v1/tickets/'+ticket.hash,
            contentType: 'application/json',
            data: JSON.stringify(obj),
            type: 'patch',
            dataType: 'json',
            complete: save_ticket_done});
    }
    else
    {
        $('#ticket_modal').modal('hide');
    }
}

function resendTicketEmail()
{
    var ticket = get_ticket_by_selected();
    $.ajax({
        url: '../api/v1/tickets/'+ticket.hash+'/Actions/Ticket.SendEmail',
        contentType: 'application/json',
        type: 'post',
        dataType: 'json',
        complete: noChangeDone});
}

function spinHash()
{
    var ticket = get_ticket_by_selected();
    $.ajax({
        url: '../api/v1/tickets/'+ticket.hash+'/Actions/Ticket.SpinHash',
        contentType: 'application/json',
        type: 'post',
        dataType: 'json',
        complete: save_ticket_done});
}

function backend_search_done(data)
{
    var tickets = data;
    var history = false;
    if(data.old_tickets !== undefined)
    {
        tickets = data.old_tickets;
        history = true;
    }
    view_ticket(tickets[0].hash);
}

function table_searched()
{
    var dt_api = $('#tickets').DataTable();
    if(dt_api.rows({'search':'applied'})[0].length == 0)
    {
        $.ajax({
            url: '../api/v1/tickets/search/'+dt_api.search(),
            type: 'get',
            dataType: 'json',
            success: backend_search_done
        });
    }
}

function yearChanged(e)
{
    var year;
    if(e === undefined)
    {
        year = $('#ticket_year').value;
    }
    else
    {
        year = e.currentTarget.value;
    }
    $('#tickets').DataTable().ajax.url('../api/v1/tickets?filter=year eq '+year+'&fmt=data-table').load();
}

function gotTicketYears(jqXHR)
{
    if(jqXHR.status !== 200)
    {
        alert('Unable to obtain valid ticket years!');
        console.log(jqXHR);
        return;
    }
    jqXHR.responseJSON.sort().reverse();
    for(var i = 0; i < jqXHR.responseJSON.length; i++)
    {
        $('#ticket_year').append($('<option/>').attr('value', jqXHR.responseJSON[i]).text(jqXHR.responseJSON[i]));
    }
    $('#ticket_year').on('change', yearChanged);
    var e = {};
    e.currentTarget = {};
    e.currentTarget.value = $('#ticket_year').val();
    yearChanged(e);
}

function gotTicketTypes(jqXHR)
{
    if(jqXHR.status !== 200 || jqXHR.responseJSON === undefined)
    {
        console.log(jqXHR);
        return;
    }
    var data = jqXHR.responseJSON;
    var options = '';
    ticketTypes = {};
    for(i = 0; i < data.length; i++)
    {
        options+='<option value="'+data[i].typeCode+'">'+data[i].description+'</option>';
        ticketTypes[data[i].typeCode] = data[i].description;
    }
    $('#type').replaceWith('<select id="type" name="type" class="form-control">'+options+'</select>');
}

function gotEarlyEntry(jqXHR)
{
    if(jqXHR.status !== 200 || jqXHR.responseJSON === undefined)
    {
        console.log(jqXHR);
        return;
    }
    var data = jqXHR.responseJSON;
    var options = '';
    earlyEntry = {};
    for(i = 0; i < data.length; i++)
    {
        options+='<option value="'+data[i].earlyEntrySetting+'">'+data[i].earlyEntryDescription+'</option>';
        earlyEntry[data[i].earlyEntrySetting] = data[i].earlyEntryDescription;
    }
    $('#earlyEntryWindow').replaceWith('<select id="earlyEntryWindow" name="earlyEntryWindow" class="form-control">'+options+'</select>');
}

function init_page()
{
    $('#tickets').dataTable({
        columns: [
            {'data': 'hash', 'render':short_hash},
            {'data': 'firstName'},
            {'data': 'lastName'},
            {'data': 'email'},
            {'data': 'type', 'render': renderTicketType}
        ]
    });
    $.ajax({
        url: '../api/v1/globals/years',
        type: 'get',
        dataType: 'json',
        complete: gotTicketYears});
    $.ajax({
        url: '../api/v1/globals/ticket_types',
        type: 'get',
        dataType: 'json',
        complete: gotTicketTypes});
    $.ajax({
        url: '../api/v1/earlyEntry',
        type: 'get',
        dataType: 'json',
        complete: gotEarlyEntry});

    $('#tickets').on('search.dt', table_searched);
}

$(init_page)
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Input } from 'semantic-ui-react';

class WriteRoute extends Component {

	render() {
		return (

일일장부 등록

주문자

<Input style={{width: '300px'}} />

		);
	}
};

export default WriteRoute;<commit_msg>글쓰기 폼 수정<commit_after>import React, { Component } from 'react';
import { Form } from 'semantic-ui-react';

class WriteRoute extends Component {

	render() {
		return (

일일장부 등록

				<Form>
					<Form.Dropdown
						label="주문자"
						placeholder="거래처를 입력 또는 선택하세요"
						search
						selection
						inline />
					<Form.Input label="연락처" placeholder="" />
				</Form>

		);
	}
};

export default WriteRoute;<|endoftext|>


<commit_before>/*
* sticky-header.js
* MIT licensed
*
* Created by Daniel Imms, http://www.growingwiththeweb.com
*/

(function() {
  'use strict';

  var tables = [];

  // Polyfills
  if (!window.getComputedStyle) {
    window.getComputedStyle = function(el) {
      this.el = el;
      this.getPropertyValue = function(prop) {
        return el.currentStyle[prop] || null;
      };
      return this;
    };
  }

  function getOffsetRelativeToDocument(element) {
    var x = 0;
    var y = 0;
    while (element && !isNaN(element.offsetLeft) && !isNaN(element.offsetTop)) {
      x += element.offsetLeft;
      y += element.offsetTop;
      element = element.offsetParent;
    }
    return { top: y, left: x };
  }

  function getScrollTop() {
    if (typeof window.pageYOffset !== 'undefined') {
      return window.pageYOffset;
    }
    var docElement = document.documentElement;
    if (!docElement.clientHeight) {
      docElement = document.body;
    }
    return docElement.scrollTop;
  }

  function listen(e, elem, func) {
    if (elem.addEventListener) {
      elem.addEventListener(e, func, false);
    } else if (elem.attachEvent) {
      elem.attachEvent('on' + e, func);
    }
  }

  function Table(element) {
    this.element = element;
    this.originalHeader = element.getElementsByTagName('thead')[0];
    this.floatingHeader = this.originalHeader.cloneNode(true);
    this.top = 0;
    this.bottom = 0;
    this.originalThs = this.originalHeader.getElementsByTagName('th');
    this.floatingThs = this.floatingHeader.getElementsByTagName('th');

    if (!this.element.style.position) {
      this.element.style.position = 'relative';
    }
    this.floatingHeader.setAttribute('aria-hidden', 'true');
    this.floatingHeader.style.position = 'absolute';
    this.floatingHeader.style.top = '0';

    this.refreshHeaderSize();
    this.attachFloatHeader();
  }

  Table.prototype.refreshHeaderSize = function () {
    var offset = getOffsetRelativeToDocument(this.element);
    var trs = this.element.getElementsByTagName('tr');
    var padding;
    this.top = offset.top;
    this.bottom = this.element.offsetHeight - trs[trs.length - 1].offsetHeight;
    for (var i = 0; i < this.originalThs.length; i++) {
      var th = this.originalThs[i];
      var style = window.getComputedStyle(th, null);
      var paddingLeft = style.getPropertyValue('padding-left')
          .replace('px', '');
      var paddingRight = style.getPropertyValue('padding-right')
          .replace('px', '');
      padding = parseFloat(paddingLeft, 10) + parseFloat(paddingRight, 10);
      this.floatingThs[i].style.width = (th.offsetWidth - padding) + 'px';
      this.floatingThs[i].style.height = (th.offsetHeight - padding) + 'px';
    }
  };

  Table.prototype.attachFloatHeader = function () {
    this.element.insertBefore(this.floatingHeader, this.element.firstChild);
  };

  function init() {
    var matches = document.querySelectorAll('table.sticky-header');
    for (var i = 0; i < matches.length; i++) {
      if (matches[i].tagName === 'TABLE') {
        tables[i] = new Table(matches[i]);
      }
    }
  }

  function windowScroll() {
    for (var i = 0; i < tables.length; i++) {
      var windowTop = getScrollTop();
      if (windowTop > tables[i].top) {
        tables[i].floatingHeader.style.top =
            Math.min(windowTop - tables[i].top, tables[i].bottom) + 'px';
      } else {
        tables[i].floatingHeader.style.top = '0';
      }
    }
  }

  function refreshHeaderSizes() {
    for (var i = 0; i < tables.length; i++) {
      tables[i].refreshHeaderSize();
    }
  }

  listen('load', window, function () {
    init();
    window.onscroll = windowScroll;
    window.onresize = refreshHeaderSizes;
  });
}());
<commit_msg>Fix incorrect variable<commit_after>/*
* sticky-header.js
* MIT licensed
*
* Created by Daniel Imms, http://www.growingwiththeweb.com
*/

(function() {
  'use strict';

  var tables = [];

  // Polyfills
  if (!window.getComputedStyle) {
    window.getComputedStyle = function(el) {
      this.el = el;
      this.getPropertyValue = function(prop) {
        return el.currentStyle[prop] || null;
      };
      return this;
    };
  }

  function getOffset(element) {
    var x = 0;
    var y = 0;
    while (element && !isNaN(element.offsetLeft) && !isNaN(element.offsetTop)) {
      x += element.offsetLeft - element.scrollLeft;
      y += element.offsetTop - element.scrollTop;
      element = element.offsetParent;
    }
    return { top: y, left: x };
  }

  function getScrollTop() {
    if (typeof window.pageYOffset !== 'undefined') {
      return window.pageYOffset;
    }
    var docElement = document.documentElement;
    if (!docElement.clientHeight) {
      docElement = document.body;
    }
    return docElement.scrollTop;
  }

  function listen(e, elem, func) {
    if (elem.addEventListener) {
      elem.addEventListener(e, func, false);
    } else if (elem.attachEvent) {
      elem.attachEvent('on' + e, func);
    }
  }

  function Table(element) {
    this.element = element;
    this.originalHeader = element.getElementsByTagName('thead')[0];
    this.floatingHeader = this.originalHeader.cloneNode(true);
    this.top = 0;
    this.bottom = 0;
    this.originalThs = this.originalHeader.getElementsByTagName('th');
    this.floatingThs = this.floatingHeader.getElementsByTagName('th');

    if (!this.element.style.position) {
      this.element.style.position = 'relative';
    }
    this.floatingHeader.setAttribute('aria-hidden', 'true');
    this.floatingHeader.style.position = 'absolute';
    this.floatingHeader.style.top = '0';

    this.refreshHeaderSize();
    this.attachFloatHeader();
  }

  Table.prototype.refreshHeaderSize = function () {
    var offset = getOffset(this.element);
    var trs = this.element.getElementsByTagName('tr');
    var padding;
    this.top = offset.top;
    this.bottom = this.element.offsetHeight - trs[trs.length - 1].offsetHeight;
    for (var i = 0; i < this.originalThs.length; i++) {
      var th = this.originalThs[i];
      var style = window.getComputedStyle(th, null);
      var paddingLeft = style.getPropertyValue('padding-left')
          .replace('px', '');
      var paddingRight = style.getPropertyValue('padding-right')
          .replace('px', '');
      padding = parseFloat(paddingLeft, 10) + parseFloat(paddingRight, 10);
      this.floatingThs[i].style.width = (th.offsetWidth - padding) + 'px';
      this.floatingThs[i].style.height = (th.offsetHeight - padding) + 'px';
    }
  };

  Table.prototype.attachFloatHeader = function () {
    this.element.insertBefore(this.floatingHeader, this.element.firstChild);
  };

  function init() {
    var matches = document.querySelectorAll('table.sticky-header');
    for (var i = 0; i < matches.length; i++) {
      if (matches[i].tagName === 'TABLE') {
        tables[i] = new Table(matches[i]);
      }
    }
  }

  function windowScroll() {
    for (var i = 0; i < tables.length; i++) {
      var windowTop = getScrollTop();
      if (windowTop > tables[i].top) {
        tables[i].floatingHeader.style.top =
            Math.min(windowTop - tables[i].top, tables[i].bottom) + 'px';
      } else {
        tables[i].floatingHeader.style.top = '0';
      }
    }
  }

  function refreshHeaderSizes() {
    for (var i = 0; i < tables.length; i++) {
      tables[i].refreshHeaderSize();
    }
  }

  listen('load', window, function () {
    init();
    window.onscroll = windowScroll;
    window.onresize = refreshHeaderSizes;
  });
}());
<|endoftext|>


<commit_before>// ECMAScript 5 strict mode
"use strict";

assert2(cr, "cr namespace not created");
assert2(cr.behaviors, "cr.behaviors not created");

cr.behaviors.CollisionAware = function(runtime)
{
    this.runtime = runtime;
};

(function ()
{
    var behaviorProto = cr.behaviors.CollisionAware.prototype;

    behaviorProto.Type = function(behavior, objtype)
    {
        this.behavior = behavior;
        this.objtype = objtype;
        this.runtime = behavior.runtime;
    };

    var behtypeProto = behaviorProto.Type.prototype;

    behtypeProto.onCreate = function()
    {
    };

    behaviorProto.Instance = function(type, inst)
    {
        this.type = type;
        this.behavior = type.behavior;
        this.inst = inst;
        this.runtime = type.runtime;
        this.stuckTracker = new simulatedTea.CollisionAware.StuckTracker(); // XXX this will break at minification
    };

    var toleratedNumericError = 2;

    var behinstProto = behaviorProto.Instance.prototype;

    behinstProto.onCreate = function()
    {
        this.enabled = this.properties[0];

        this.elasticity = 1;

        this.externDx = 0;
        this.externDy = 0;
        this.dx = 0;
        this.dy = 0;
        this.ticksToPush = 0;
        this.lastX = this.inst.x;
        this.lastY = this.inst.y;
        this.medianDt = 0.016; // 60 FPS
        this.lastDts = [0.016, 0.016, 0.016, 0.16, 0.16];
    };

    behinstProto.onDestroy = function ()
    {
    };

    behinstProto.saveToJSON = function ()
    {
        return {
            "enabled": this.enabled,
            "externDx": this.externDx,
            "externDy": this.externDy,
            "dx": this.dx,
            "dy": this.dy,
            "ticksToPush": this.ticksToPush,
            "lastX": this.lastX,
            "lastY": this.lastY,
            "medianDt": this.medianDt,
            "lastDts": this.lastDts
        };
    };

    behinstProto.loadFromJSON = function (o)
    {
        this.enabled = o["enabled"];
        this.externDx = o["externDx"];
        this.externDy = o["externDy"];
        this.dx = o["dx"];
        this.dy = o["dy"];
        this.ticksToPush = o["ticksToPush"];
        this.lastX = o["lastX"];
        this.lastY = o["lastY"];
        this.medianDt = o["medianDt"];
        this.lastDts = o["lastDts"];

        this.elasticity = 1;
    };

    behinstProto.tick = function ()
    {
        this.getLast5MedianDt();
        this.measureExternalImpuls();

        if (this.ticksToPush > 0)
        {
            this.inst.x += this.dx*this.medianDt;
            this.inst.y += this.dy*this.medianDt;
            this.ticksToPush -= 1;
        }
        else
        {
            this.dx = 0;
            this.dy = 0;
        }

        var diff = {
            x: this.inst.x - this.lastX,
            y: this.inst.y - this.lastY
        };

        if (!movementNegligible(diff) && this.enabled) // resolve collision & pickup counterspeed
        {
            if (this.isMovingSlow(diff))
            {
                this.oneStepOrCollision(diff);
            }
            // else should raycast. phew. --- or multisample !!
        }

        //if (movementNegligible(diff))
        //{
        //    this.stuckTracker.registerUnmoved(this.medianDt);
        //}
        //else
        //{
        //    this.stuckTracker.registerFreed();
        //}

        this.lastX = this.inst.x;
        this.lastY = this.inst.y;
    }

    behinstProto.getLast5MedianDt = function ()
    {
        var dt = this.runtime.getDt(this.inst);
        this.lastDts.pop();
        this.lastDts.unshift(dt);
        var sample = this.lastDts.slice().sort(function(a,b) {return a-b});
        this.medianDt = sample[2];
    }

    behinstProto.measureExternalImpuls = function ()
    {
        if (this.otherSourcesOfMovementExist())
        {
            var delta = this.getPositionDelta();
            this.externDx = (this.externDx + delta.x/this.medianDt)/2;
            this.externDy = (this.externDy + delta.y/this.medianDt)/2;
        }
    }

    behinstProto.otherSourcesOfMovementExist = function ()
    {
        return this.lastX !== this.inst.x || this.lastY !== this.inst.y
    }

    function movementNegligible (vector)
    {
        return (Math.abs(vector.x) < 0.1 && Math.abs(vector.y) < 0.1)
    }

    behinstProto.getPositionDelta = function ()
    {
        return {
            x: this.inst.x - this.lastX,
            y: this.inst.y - this.lastY
        }
    }

    behinstProto.isMovingSlow = function (diff)
    {
        return (Math.abs(diff.x) < this.inst.bbox.width()
            && Math.abs(diff.y) < this.inst.bbox.height())
    }

    behinstProto.oneStepOrCollision = function (diff)
    {
        this.inst.set_bbox_changed();
        var collobj = this.runtime.testOverlapSolid(this.inst);
        if (collobj)
        {
            this.runtime.pushOutSolidNearest(this.inst, Math.sqrt(diff.x*diff.x + diff.y*diff.y) + toleratedNumericError);
            this.runtime.registerCollision(this.inst, collobj);
            this.dx += this.elasticity*(this.inst.x - (this.lastX + diff.x))/this.medianDt;
            this.dy += this.elasticity*(this.inst.y - (this.lastY + diff.y))/this.medianDt;
            this.ticksToPush += 1;
        }
    }

    /**BEGIN-PREVIEWONLY**/
    behinstProto.getDebuggerValues = function (propsections)
    {
        propsections.push({
            "title": this.type.name,
            "properties": [
                {"name": "Velocity.x", "value": this.dx, "readonly": true},
                {"name": "Velocity.y", "value": this.dy, "readonly": true},
                {"name": "Enabled", "value": !! this.enabled},
            ]
        });
    };

    behinstProto.onDebugValueEdited = function (header, name, value)
    {
        if (name === "Enabled")
            this.enabled = value;
    };
    /**END-PREVIEWONLY**/

    function Cnds() {};

    Cnds.prototype.IsEnabled = function () { return this.enabled }

    behaviorProto.cnds = new Cnds();

    function Acts() {};

    Acts.prototype.setEnabled = function (en)
    {
        this.enabled = (en === 1);
        if (!this.enabled)
        {
            this.dx = 0;
            this.dy = 0;
        }
    };

    behaviorProto.acts = new Acts();

    function Exps() {};

    behaviorProto.exps = new Exps();

}());
<commit_msg>Disabling reflection, adding first steps of multisampling (still broken)<commit_after>// ECMAScript 5 strict mode
"use strict";

assert2(cr, "cr namespace not created");
assert2(cr.behaviors, "cr.behaviors not created");

cr.behaviors.CollisionAware = function(runtime)
{
    this.runtime = runtime;
};

(function ()
{
    var behaviorProto = cr.behaviors.CollisionAware.prototype;

    behaviorProto.Type = function(behavior, objtype)
    {
        this.behavior = behavior;
        this.objtype = objtype;
        this.runtime = behavior.runtime;
    };

    var behtypeProto = behaviorProto.Type.prototype;

    behtypeProto.onCreate = function()
    {
    };

    behaviorProto.Instance = function(type, inst)
    {
        this.type = type;
        this.behavior = type.behavior;
        this.inst = inst;
        this.runtime = type.runtime;
        this.stuckTracker = new simulatedTea.CollisionAware.StuckTracker(); // XXX this will break at minification
    };

    var toleratedNumericError = 2;

    var behinstProto = behaviorProto.Instance.prototype;

    behinstProto.onCreate = function()
    {
        this.enabled = this.properties[0];

        this.elasticity = 1;

        this.externDx = 0;
        this.externDy = 0;
        this.dx = 0;
        this.dy = 0;
        this.ticksToPush = 0;
        this.lastX = this.inst.x;
        this.lastY = this.inst.y;
        this.medianDt = 0.016; // 60 FPS
        this.lastDts = [0.016, 0.016, 0.016, 0.16, 0.16];
    };

    behinstProto.onDestroy = function ()
    {
    };

    behinstProto.saveToJSON = function ()
    {
        return {
            "enabled": this.enabled,
            "externDx": this.externDx,
            "externDy": this.externDy,
            "dx": this.dx,
            "dy": this.dy,
            "ticksToPush": this.ticksToPush,
            "lastX": this.lastX,
            "lastY": this.lastY,
            "medianDt": this.medianDt,
            "lastDts": this.lastDts
        };
    };

    behinstProto.loadFromJSON = function (o)
    {
        this.enabled = o["enabled"];
        this.externDx = o["externDx"];
        this.externDy = o["externDy"];
        this.dx = o["dx"];
        this.dy = o["dy"];
        this.ticksToPush = o["ticksToPush"];
        this.lastX = o["lastX"];
        this.lastY = o["lastY"];
        this.medianDt = o["medianDt"];
        this.lastDts = o["lastDts"];

        this.elasticity = 1;
    };

    behinstProto.tick = function ()
    {
        this.getLast5MedianDt();
        this.measureExternalImpuls();
        //this.applyReflectionSpeed();

        var diff = {
            x: this.inst.x - this.lastX,
            y: this.inst.y - this.lastY
        };

        if (!movementNegligible(diff) && this.enabled) // resolve collision & compute counterspeed
        {
            this.inst.update_bbox();
            if (this.isMovingSlow(diff))
            {
                this.lastCheckedStep(diff);
            }
            else
            {
                this.multiSamplePath(diff);
                // L> cannot recognize curvature
                //    gets very expensive for fast, small objects
                //    (would need a raycast-like check for that)
            }
            this.inst.set_bbox_changed(); // probably not needed
        }

        //if (movementNegligible(diff))
        //{
        //    this.stuckTracker.registerUnmoved(this.medianDt);
        //}
        //else
        //{
        //    this.stuckTracker.registerFreed();
        //}

        this.lastX = this.inst.x;
        this.lastY = this.inst.y;
    }

    behinstProto.applyReflectionSpeed = function ()
    {
        if (this.ticksToPush > 0)
        {
            this.inst.x += this.dx*this.medianDt;
            this.inst.y += this.dy*this.medianDt;
            this.ticksToPush -= 1;
        }
        else
        {
            this.dx = 0;
            this.dy = 0;
        }
    }

    behinstProto.isMovingSlow = function (diff)
    {
        return (Math.abs(diff.x) < this.inst.bbox.width()
            && Math.abs(diff.y) < this.inst.bbox.height())
    }

    behinstProto.lastCheckedStep = function (diff)
    {
        var collobj = this.runtime.testOverlapSolid(this.inst);
        if (collobj)
        {
            window.console.log('collision');
            this.resolveCollision(diff, collobj, Math.sqrt(diff.x*diff.x + diff.y*diff.y))
        }
    }

    behinstProto.multiSamplePath = function (diff)
    {
        var unit = 5,
            stepWidth = Math.max(Math.min(this.inst.bbox.width(), this.inst.bbox.height()) - unit, unit),
            // L> stupid workaround for missing raycast solution for small fast objects
            targetDistance = Math.sqrt(diff.x*diff.x + diff.y*diff.y);
        for (
            var stepDistance = unit;
            stepDistance + unit < targetDistance;
            stepDistance += stepWidth
        )
        {
            this.inst.x = this.lastX + stepDistance/targetDistance*diff.x;
            this.inst.y = this.lastY + stepDistance/targetDistance*diff.y;
            var collobj = this.runtime.testOverlapSolid(this.inst);
            if (collobj)
            {
                this.resolveCollision(diff, collobj, stepWidth);
                return;
            }
        }
        dot.x = this.inst.x;
        dot.y = this.inst.y;
        dot.set_bbox_changed();
        this.lastCheckedStep(diff);
    }

    behinstProto.resolveCollision = function (diff, collobj, maxDistance)
    {
        this.runtime.pushOutSolid(this.inst, -diff.x, -diff.y, maxDistance + toleratedNumericError);
        this.runtime.registerCollision(this.inst, collobj);
        var pushoutX = this.inst.x - (this.lastX + diff.x);
        var pushoutY = this.inst.y - (this.lastY + diff.y);
        // pushout direction is mostly off anglewise in positive direction
        // could try a workaround by manually continuing the pushout spiral (as circle, more likely)
        // this.testAndDecideReflectionSpeed(diff, pushoutX, pushoutY); // work postponed
    }

    behinstProto.testAndDecideReflectionSpeed = function (diff, pbx, pby)
    {
        this.dx += this.elasticity*(pbx)/this.medianDt;
        this.dy += this.elasticity*(pby)/this.medianDt;
        this.ticksToPush += 1;
    }

    behinstProto.getLast5MedianDt = function ()
    {
        var dt = this.runtime.getDt(this.inst);
        this.lastDts.pop();
        this.lastDts.unshift(dt);
        var sample = this.lastDts.slice().sort(function(a,b) {return a-b});
        this.medianDt = sample[2];
    }

    behinstProto.measureExternalImpuls = function ()
    {
        if (this.otherSourcesOfMovementExist())
        {
            var delta = this.getPositionDelta();
            this.externDx = (this.externDx + delta.x/this.medianDt)/2;
            this.externDy = (this.externDy + delta.y/this.medianDt)/2;
        }
    }

    behinstProto.otherSourcesOfMovementExist = function ()
    {
        return this.lastX !== this.inst.x || this.lastY !== this.inst.y
    }

    function movementNegligible (vector)
    {
        return (Math.abs(vector.x) < 0.1 && Math.abs(vector.y) < 0.1)
    }

    behinstProto.getPositionDelta = function ()
    {
        return {
            x: this.inst.x - this.lastX,
            y: this.inst.y - this.lastY
        }
    }

    /**BEGIN-PREVIEWONLY**/
    behinstProto.getDebuggerValues = function (propsections)
    {
        propsections.push({
            "title": this.type.name,
            "properties": [
                {"name": "Velocity.x", "value": this.dx, "readonly": true},
                {"name": "Velocity.y", "value": this.dy, "readonly": true},
                {"name": "Enabled", "value": !! this.enabled},
            ]
        });
    };

    behinstProto.onDebugValueEdited = function (header, name, value)
    {
        if (name === "Enabled")
            this.enabled = value;
    };
    /**END-PREVIEWONLY**/

    function Cnds() {};

    Cnds.prototype.IsEnabled = function () { return this.enabled }

    behaviorProto.cnds = new Cnds();

    function Acts() {};

    Acts.prototype.setEnabled = function (en)
    {
        this.enabled = (en === 1);
        if (!this.enabled)
        {
            this.dx = 0;
            this.dy = 0;
        }
    };

    behaviorProto.acts = new Acts();

    function Exps() {};

    behaviorProto.exps = new Exps();

}());
<|endoftext|>


<commit_before>import React from 'react';
import { storiesOf } from '@storybook/react';
import { boolean, number, select, text } from '@storybook/addon-knobs/react';
import { IconCalendarSmallOutline, IconInfoBadgedSmallFilled } from '@teamleader/ui-icons';
import {
  InputBase,
  Button,
  Checkbox,
  Counter,
  Icon,
  Input,
  Label,
  LoadingSpinner,
  NumericInput,
  Textarea,
  TextBody,
  TextSmall,
  Tooltip,
} from '../src';

const colors = ['aqua', 'gold', 'mint', 'neutral', 'ruby', 'teal', 'violet'];
const elements = ['input', 'textarea'];
const sizes = ['small', 'medium', 'large'];
const tints = ['lightest', 'light', 'normal', 'dark', 'darkest'];
const types = [
  'text',
  'button',
  'checkbox',
  'color',
  'date',
  'datetime-local',
  'email',
  'file',
  'hidden',
  'image',
  'month',
  'number',
  'password',
  'radio',
  'range',
  'reset',
  'search',
  'submit',
  'tel',
  'time',
  'url',
  'week',
];

const prefix = [
  <Icon color="neutral" tint="darkest">
    <IconCalendarSmallOutline />
  </Icon>,
  <TextBody color="neutral">€</TextBody>,
];

const suffix = [<TextSmall color="neutral">incl. BTW</TextSmall>, <Counter count={99} />, <LoadingSpinner />];

const props = {
  helpText: 'This is the fields help text',
  error: 'I am an error',
  placeholder: 'Placeholder',
  onChange: (event, value) => console.log('Changing to ', value),
};

const TooltippedIcon = Tooltip(Icon);

storiesOf('Form elements/Inputs', module)
  .add('Input base', () => (
    <InputBase
      bold={boolean('bold', false)}
      disabled={boolean('disabled', false)}
      element={select('element', elements)}
      inverse={boolean('inverse', false)}
      readOnly={boolean('readOnly', false)}
      size={select('size', sizes)}
      type={select('type', types)}
      value={text('value', undefined)}
    />
  ))
  .add('Text area', () => (
    <Textarea
      bold={boolean('bold', false)}
      disabled={boolean('disabled', false)}
      inverse={boolean('inverse', false)}
      readOnly={boolean('readOnly', false)}
      size={select('size', sizes) || undefined}
      value={text('value', undefined)}
    />
  ))
  .add('Input only', () => (
    <Input
      id="input1"
      bold={boolean('Bold', false)}
      disabled={boolean('Disabled', false)}
      readOnly={boolean('Read only', false)}
      {...props}
    />
  ))
  .add('text', () => (
    <Label htmlFor="input1" inverse={boolean('Inverse', false)} size={select('Size', sizes, 'medium')}>
      Input label
      <Input
        id="input1"
        bold={boolean('Bold', false)}
        disabled={boolean('Disabled', false)}
        readOnly={boolean('Read only', false)}
        {...props}
      />
    </Label>
  ))
  .add('password', () => (
    <Label htmlFor="input1" inverse={boolean('Inverse', false)} size={select('Size', sizes, 'medium')}>
      Input label
      <Input
        id="input1"
        type="password"
        bold={boolean('Bold', false)}
        disabled={boolean('Disabled', false)}
        readOnly={boolean('Read only', false)}
        {...props}
      />
    </Label>
  ))
  .add('Numeric', () => (
    <Label htmlFor="input1" inverse={boolean('Inverse', false)} size={select('Size', sizes, 'medium')}>
      Input label
      <NumericInput
        id="input1"
        bold={boolean('Bold', false)}
        disabled={boolean('Disabled', false)}
        readOnly={boolean('Read only', false)}
        min={number('Minimum', 0)}
        max={number('Maximum', 10)}
        spinner={boolean('Render spinner', true)}
        step={number('Step', 1)}
        {...props}
      />
    </Label>
  ))
  .add('with error', () => (
    <Label htmlFor="input1" inverse={boolean('Inverse', false)} size={select('Size', sizes, 'medium')}>
      Input label
      <Input
        error="This is an error message"
        id="input1"
        size="small"
        value="wrong value"
        bold={boolean('Bold', false)}
        disabled={boolean('Disabled', false)}
        readOnly={boolean('Read only', false)}
        {...props}
      />
    </Label>
  ))
  .add('with label tooltip', () => (
    <Label
      connectedRight={
        <TooltippedIcon
          color={select('Icon color', colors, 'teal')}
          tint={select('Icon tint', tints, 'dark')}
          tooltip={<TextSmall>This is the label tooltip text</TextSmall>}
          tooltipSize="small"
        >
          <IconInfoBadgedSmallFilled />
        </TooltippedIcon>
      }
      htmlFor="input1"
      inverse={boolean('Inverse', false)}
      size={select('Size', sizes, 'medium')}
    >
      Input label
      <Input
        id="input1"
        size="small"
        value="wrong value"
        bold={boolean('Bold', false)}
        disabled={boolean('Disabled', false)}
        readOnly={boolean('Read only', false)}
        {...props}
      />
    </Label>
  ))
  .add('with prefix or suffix', () => (
    <Label htmlFor="input1" inverse={boolean('Inverse', false)} size={select('Size', sizes, 'medium')}>
      Input label
      <Input
        id="input1"
        bold={boolean('Bold', false)}
        disabled={boolean('Disabled', false)}
        readOnly={boolean('Read only', false)}
        prefix={prefix}
        suffix={suffix}
        {...props}
      />
    </Label>
  ))
  .add('with connected elements', () => (
    <Label htmlFor="input1" inverse={boolean('Inverse', false)} size={select('Size', sizes, 'medium')}>
      Input label
      <Input
        id="input1"
        bold={boolean('Bold', false)}
        connectedLeft={<Button size={select('Size', sizes, 'medium')} label="€" />}
        connectedRight={
          <Button size={select('Size', sizes, 'medium')}>
            <Checkbox size="small">Discount</Checkbox>
          </Button>
        }
        disabled={boolean('Disabled', false)}
        type="number"
        min={number('Minimum', 0)}
        max={number('Maximum', 10)}
        step={number('Step', 1)}
        readOnly={boolean('Read only', false)}
        {...props}
      />
    </Label>
  ));
<commit_msg>Update & reduce the amount of Input stories<commit_after>import React from 'react';
import { storiesOf } from '@storybook/react';
import { boolean, number, select, text } from '@storybook/addon-knobs/react';
import { IconCalendarSmallOutline } from '@teamleader/ui-icons';
import {
  InputBase,
  Button,
  Checkbox,
  Counter,
  Icon,
  Input,
  LoadingSpinner,
  NumericInput,
  Textarea,
  TextBody,
  TextSmall,
} from '../src';

const sizes = ['small', 'medium', 'large'];
const types = [
  'text',
  'button',
  'checkbox',
  'color',
  'date',
  'datetime-local',
  'email',
  'file',
  'hidden',
  'image',
  'month',
  'number',
  'password',
  'radio',
  'range',
  'reset',
  'search',
  'submit',
  'tel',
  'time',
  'url',
  'week',
];
const placeholder = 'I am the placeholder';
const prefix = [
  <Icon color="neutral" tint="darkest">
    <IconCalendarSmallOutline />
  </Icon>,
  <TextBody color="neutral" tint="darkest">
    €
  </TextBody>,
];
const suffix = [
  <TextSmall color="neutral" tint="darkest">
    incl. BTW
  </TextSmall>,
  <Counter count={99} />,
  <LoadingSpinner />,
];

storiesOf('Form elements/Input', module)
  .addParameters({
    info: {
      propTables: [InputBase],
    },
  })
  .add('Input', () => (
    <Input
      bold={boolean('bold', false)}
      disabled={boolean('disabled', false)}
      error={text('error', '')}
      helpText={text('helpText', '')}
      id="input1"
      inverse={boolean('inverse', false)}
      placeholder={text('placeholder', placeholder)}
      readOnly={boolean('readOnly', false)}
      size={select('size', sizes) || undefined}
      type={select('type', types, 'text')}
      connectedLeft={
        boolean('Toggle connectedLeft', false) ? <Button size={select('size', sizes, 'medium')} label="€" /> : undefined
      }
      connectedRight={
        boolean('Toggle connectedRight', false) ? (
          <Button size={select('size', sizes, 'medium')}>
            <Checkbox size="small">Discount</Checkbox>
          </Button>
        ) : (
          undefined
        )
      }
      prefix={boolean('Toggle prefix', false) ? prefix : undefined}
      suffix={boolean('Toggle suffix', false) ? suffix : undefined}
    />
  ))
  .add('NumericInput', () => (
    <NumericInput
      bold={boolean('bold', false)}
      disabled={boolean('disabled', false)}
      error={text('error', '')}
      helpText={text('helpText', '')}
      id="input1"
      inverse={boolean('inverse', false)}
      max={number('max', 10)}
      min={number('min', 0)}
      placeholder={text('placeholder', placeholder)}
      readOnly={boolean('readOnly', false)}
      size={select('size', sizes) || undefined}
      spinner={boolean('spinner', true)}
      step={number('step', 1)}
      connectedLeft={
        boolean('Toggle connectedLeft', false) ? <Button size={select('size', sizes, 'medium')} label="€" /> : undefined
      }
      connectedRight={
        boolean('Toggle connectedRight', false) ? (
          <Button size={select('size', sizes, 'medium')}>
            <Checkbox size="small">Discount</Checkbox>
          </Button>
        ) : (
          undefined
        )
      }
      prefix={boolean('Toggle prefix', false) ? prefix : undefined}
      suffix={boolean('Toggle suffix', false) ? suffix : undefined}
    />
  ))
  .add('Textarea', () => (
    <Textarea
      bold={boolean('bold', false)}
      disabled={boolean('disabled', false)}
      error={text('error', '')}
      helpText={text('helpText', '')}
      id="input1"
      inverse={boolean('inverse', false)}
      placeholder={text('placeholder', placeholder)}
      readOnly={boolean('readOnly', false)}
      size={select('size', sizes) || undefined}
      value={text('value', undefined)}
    />
  ));
<|endoftext|>


<commit_before>const Command = require('../base/Command');
const moment = require('moment');

// To get the dates of any upcoming events if any (Adapted from shittybill#3024's Scorpio)
class CurrentEvents extends Command {
    constructor(client) {
        super(client, {
            name: 'currentevents',
            category: "SWGoH",
            aliases: ['cevents', 'ce'],
            permissions: ['EMBED_LINKS'],    // Starts with ['SEND_MESSAGES', 'VIEW_CHANNEL'] so don't need to add them
        });
    }

    async run(client, message, [num]) {
        const FLEET_CHALLENGES = ['shipevent_PRELUDE_ACKBAR', 'shipevent_PRELUDE_MACEWINDU', 'shipevent_PRELUDE_TARKIN', 'shipevent_SC01UPGRADE', 'shipevent_SC02TRAINING', 'shipevent_SC03TRAINING', 'shipevent_SC03ABILITY'];
        const MOD_CHALLENGES = ['restrictedmodbattle_set_1', 'restrictedmodbattle_set_2', 'restrictedmodbattle_set_3', 'restrictedmodbattle_set_4', 'restrictedmodbattle_set_5', 'restrictedmodbattle_set_6', 'restrictedmodbattle_set_7', 'restrictedmodbattle_set_8'];
        const DAILY_CHALLENGES = ['challenge_XP', 'challenge_CREDIT', 'challenge_ABILITYUPGRADEMATERIALS', 'challenge_EQUIPMENT_AGILITY', 'challenge_EQUIPMENT_INTELLIGENCE', 'challenge_EQUIPMENT_STRENGTH'];
        // const HEISTS = ['EVENT_CREDIT_HEIST_GETAWAY_V2'];

        const DEF_NUM = 10;
        // const lang = 'ger_de';
        // const lang = 'ita_it';
        // const lang = 'por_br';
        // const lang = 'jpn_jp';
        const lang = 'ENG_US';

        let botClient = null;
        try {
            botClient = await client.swgohAPI.getClient(lang);
        } catch (e) {
            console.error(e);
        }

        // Let them specify the max # of events to show
        let eNum = parseInt(num);
        if (isNaN(eNum)) {
            eNum = DEF_NUM;
        }

        const evOut = [];
        for (const event of botClient.events) {
            if (FLEET_CHALLENGES.includes(event.id) ||
                MOD_CHALLENGES.includes(event.id) ||
                DAILY_CHALLENGES.includes(event.id)) {
                delete botClient.event;
                continue;
            }

            // Filter out event dates from the past
            event.schedule = event.schedule.filter(p => {
                if (!moment().isBefore(moment(p.end))) return false;
                return true;
            });

            // Sort the dates in the event
            event.schedule = event.schedule.sort((p, c) => p.start - c.start);
            // console.log(`ID: ${event.id}, Name: ${event.name}`);
            evOut.push(event);
        }

        const fields = [];
        let desc = '`------------------------------`';
        let count = 0;
        const sortedEvents = evOut.sort((p, c) => parseInt(Math.min(...Array.from(p.schedule, t => t.start))) - parseInt(Math.min(...Array.from(c.schedule, t => t.start))));
        for (const event of sortedEvents) {

            if (count >= eNum) break;
            if (event.schedule.length) {
                count ++;
                // Expanded view
                // let enVal = '';
                // if (event.schedule.length) {
                //     if (fields.length >= eNum) break;
                //     event.schedule.forEach((d, ix) => {
                //         enVal += `${ix === 0 ? '' : '\n'}\`` + moment(d.start).format('DD/MM/YYYY') + '`';
                //     });
                //     fields.push({
                //         name: event.name,
                //         value: enVal + '\n`------------------------------`',
                //         inline: true
                //     });
                // }

                // Condensed view
                desc += `\n\`${moment(event.schedule[0].start).format('M-DD')} |\` **${event.name}**`;
            }
        }

        if (fields.length) {
            return message.channel.send({embed: {
                author: {
                    name: message.language.get('COMMAND_CURRENTEVENTS_HEADER')
                },
                color: 0x0f0f0f,
                description: message.language.get('COMMAND_CURRENTEVENTS_DESC', count),
                fields: fields
            }});
        } else if (desc.length) {
            return message.channel.send({embed: {
                author: {
                    name: message.language.get('COMMAND_CURRENTEVENTS_HEADER')
                },
                color: 0x0f0f0f,
                description: message.language.get('COMMAND_CURRENTEVENTS_DESC', count) + '\n' + desc + '\n`------------------------------`'
            }});
        } else {
            return message.send('No events at this time');
        }
    }
}

module.exports = CurrentEvents;

<commit_msg>Added event filters, and set the langhuage to the guild specific one<commit_after>const Command = require('../base/Command');
const moment = require('moment');

// To get the dates of any upcoming events if any (Adapted from shittybill#3024's Scorpio)
class CurrentEvents extends Command {
    constructor(client) {
        super(client, {
            name: 'currentevents',
            category: "SWGoH",
            aliases: ['cevents', 'ce'],
            permissions: ['EMBED_LINKS'],    // Starts with ['SEND_MESSAGES', 'VIEW_CHANNEL'] so don't need to add them
            flags: {
                heists: {
                    aliases: ['$', 'heist']
                },
                heroic: {
                    aliases: ['hero']
                }
            }
        });
    }

    async run(client, message, [num], options) {
        const FLEET_CHALLENGES = ['shipevent_PRELUDE_ACKBAR', 'shipevent_PRELUDE_MACEWINDU', 'shipevent_PRELUDE_TARKIN', 'shipevent_SC01UPGRADE', 'shipevent_SC02TRAINING', 'shipevent_SC03TRAINING', 'shipevent_SC03ABILITY'];
        const MOD_CHALLENGES = ['restrictedmodbattle_set_1', 'restrictedmodbattle_set_2', 'restrictedmodbattle_set_3', 'restrictedmodbattle_set_4', 'restrictedmodbattle_set_5', 'restrictedmodbattle_set_6', 'restrictedmodbattle_set_7', 'restrictedmodbattle_set_8'];
        const DAILY_CHALLENGES = ['challenge_XP', 'challenge_CREDIT', 'challenge_ABILITYUPGRADEMATERIALS', 'challenge_EQUIPMENT_AGILITY', 'challenge_EQUIPMENT_INTELLIGENCE', 'challenge_EQUIPMENT_STRENGTH'];
        const HEISTS = ['EVENT_CREDIT_HEIST_GETAWAY_V2', 'EVENT_TRAINING_DROID_SMUGGLING'];
        const HEROIC = ['progressionevent_PIECES_AND_PLANS', 'progressionevent_GRANDMASTERS_TRAINING', 'EVENT_HERO_SCAVENGERREY'];

        const DEF_NUM = 10;
        const lang = message.guildSettings.swgohLanguage;

        let botClient = null;
        try {
            botClient = await client.swgohAPI.getClient(lang);
        } catch (e) {
            console.error(e);
        }

        // Let them specify the max # of events to show
        let eNum = parseInt(num);
        if (isNaN(eNum)) {
            eNum = DEF_NUM;
        }

        let filter = [];
        const evOut = [];
        if (options.flags.heists) {
            filter = filter.concat(HEISTS);
        }
        if (options.flags.heroic) {
            filter = filter.concat(HEROIC);
        }
        for (const event of botClient.events) {
            if (FLEET_CHALLENGES.includes(event.id) ||
                MOD_CHALLENGES.includes(event.id) ||
                DAILY_CHALLENGES.includes(event.id)) {
                delete botClient.event;
                continue;
            }

            console.log(filter);

            if (filter.length) {
                if (filter.indexOf(event.id) < 0) {
                    delete botClient.event;
                    continue;
                }
            }

            // Filter out event dates from the past
            event.schedule = event.schedule.filter(p => {
                if (!moment().isBefore(moment(p.end))) return false;
                return true;
            });

            // Sort the dates in the event
            event.schedule = event.schedule.sort((p, c) => p.start - c.start);
            // console.log(`ID: ${event.id}, Name: ${event.name}`);
            evOut.push(event);
        }

        const fields = [];
        let desc = '`------------------------------`';
        let count = 0;
        const sortedEvents = evOut.sort((p, c) => parseInt(Math.min(...Array.from(p.schedule, t => t.start))) - parseInt(Math.min(...Array.from(c.schedule, t => t.start))));
        for (const event of sortedEvents) {

            if (count >= eNum) break;
            if (event.schedule.length) {
                count ++;
                // Expanded view
                // let enVal = '';
                // if (event.schedule.length) {
                //     if (fields.length >= eNum) break;
                //     event.schedule.forEach((d, ix) => {
                //         enVal += `${ix === 0 ? '' : '\n'}\`` + moment(d.start).format('DD/MM/YYYY') + '`';
                //     });
                //     fields.push({
                //         name: event.name,
                //         value: enVal + '\n`------------------------------`',
                //         inline: true
                //     });
                // }

                // Condensed view
                desc += `\n\`${moment(event.schedule[0].start).format('M-DD')} |\` **${event.name}**`;
            }
        }

        if (fields.length) {
            return message.channel.send({embed: {
                author: {
                    name: message.language.get('COMMAND_CURRENTEVENTS_HEADER')
                },
                color: 0x0f0f0f,
                description: message.language.get('COMMAND_CURRENTEVENTS_DESC', count),
                fields: fields
            }});
        } else if (count > 0) {
            return message.channel.send({embed: {
                author: {
                    name: message.language.get('COMMAND_CURRENTEVENTS_HEADER')
                },
                color: 0x0f0f0f,
                description: message.language.get('COMMAND_CURRENTEVENTS_DESC', count) + '\n' + desc + '\n`------------------------------`'
            }});
        } else {
            return message.send('No events at this time');
        }
    }
}

module.exports = CurrentEvents;

<|endoftext|>


<commit_before>/**
 * Created by julia on 07.11.2016.
 */
let Command = require('../../structures/command');
let moment = require('moment');
let UserManager = require('../../modules/userManager');
let winston = require('winston');
class UserInfo extends Command {
    constructor(t) {
        super();
        this.cmd = "uinfo";
        this.cat = "misc";
        this.needGuild = false;
        this.t = t;
        this.accessLevel = 0;
        this.u = new UserManager();
    }

    run(msg) {
        let user;
        let member;
        if (msg.mentions.length > 0) {
            user = msg.mentions[0];
            member = msg.guild ? msg.guild.members.find(u => u.id === user.id) : null;
            this.buildReply(msg, user, member);
        } else {
            user = msg.author;
            member = msg.guild ? msg.member : null;
            this.buildReply(msg, user, member);
        }
    }

    buildReply(msg, user, member) {
        let avatar = user.avatarURL ? user.avatarURL : user.defaultAvatarURL;
        this.u.loadUser(user, (err, dbUser) => {
            if (err) return winston.error(err);
            let reply = {
                embed: {
                    author: {
                        name: `${this.t('user-info.info', {lngs: msg.lang})}: ${user.username}#${user.discriminator}`,
                        icon_url: avatar
                    },
                    fields: this.buildUserInfo(msg, user, member, dbUser),
                    image: {url: avatar},
                    color: 0x00ADFF
                }
            };
            msg.channel.createMessage(reply);
        });
    }

    buildUserInfo(msg, user, member, dbUser) {
        let fields = [];
        fields.push({name: this.t('user-info.id', {lngs: msg.lang}), value: user.id, inline: true});
        fields.push({name: this.t('user-info.name', {lngs: msg.lang}), value: user.username, inline: true});
        fields.push({
            name: this.t('user-info.discriminator', {lngs: msg.lang}),
            value: user.discriminator,
            inline: true
        });
        fields.push({
            name: this.t('user-info.created', {lngs: msg.lang}),
            value: moment().to(user.createdAt),
            inline: true
        });
        if (member) {
            if (member.nick) {
                fields.push({name: this.t('user-info.nick', {lngs: msg.lang}), value: member.nick, inline: true});
            }
            fields.push({name: this.t('user-info.status', {lngs: msg.lang}), value: member.status, inline: true});
            if (member.game) {
                fields.push({
                    name: this.t('user-info.playing', {lngs: msg.lang}),
                    value: member.game.name,
                    inline: true
                });
            }
            fields.push({
                name: this.t('user-info.join', {lngs: msg.lang}),
                value: moment().to(member.joinedAt),
                inline: true
            });
            fields.push({
                name: this.t('user-info.role', {lngs: msg.lang}),
                value: member.roles.length,
                inline: true
            });
        }
        fields.push({
            name: 'LP',
            value: dbUser.rep,
            inline: true
        });
        fields.push({
            name: this.t('user-info.bot', {lngs: msg.lang}),
            value: user.bot ? ':white_check_mark: ' : ':x: ',
            inline: true
        });
        return fields;
    }
}
module.exports = UserInfo;<commit_msg>gif support for animated avatars<commit_after>/**
 * Created by julia on 07.11.2016.
 */
let Command = require('../../structures/command');
let moment = require('moment');
let UserManager = require('../../modules/userManager');
let winston = require('winston');
class UserInfo extends Command {
    constructor(t) {
        super();
        this.cmd = "uinfo";
        this.cat = "misc";
        this.needGuild = false;
        this.t = t;
        this.accessLevel = 0;
        this.u = new UserManager();
    }

    run(msg) {
        let user;
        let member;
        if (msg.mentions.length > 0) {
            user = msg.mentions[0];
            member = msg.guild ? msg.guild.members.find(u => u.id === user.id) : null;
            this.buildReply(msg, user, member);
        } else {
            user = msg.author;
            member = msg.guild ? msg.member : null;
            this.buildReply(msg, user, member);
        }
    }

    buildReply(msg, user, member) {
        let avatar = user.avatarURL ? (user.avatar.startsWith('a_') ? `https://cdn.discordapp.com/avatars/${user.id}/${user.avatar}.gif` : user.avatarURL) : user.defaultAvatarURL;
        avatar = avatar.replace(/[^a-zA-Z0-9_\-./:]/, "");
        this.u.loadUser(user, (err, dbUser) => {
            if (err) return winston.error(err);
            let reply = {
                embed: {
                    author: {
                        name: `${this.t('user-info.info', {lngs: msg.lang})}: ${user.username}#${user.discriminator}`,
                        icon_url: avatar
                    },
                    fields: this.buildUserInfo(msg, user, member, dbUser),
                    image: {url: avatar},
                    color: 0x00ADFF
                }
            };
            msg.channel.createMessage(reply).then().catch(err => {
                // console.error(err);
            });
        });
    }

    buildUserInfo(msg, user, member, dbUser) {
        let fields = [];
        fields.push({name: this.t('user-info.id', {lngs: msg.lang}), value: user.id, inline: true});
        fields.push({name: this.t('user-info.name', {lngs: msg.lang}), value: user.username, inline: true});
        fields.push({
            name: this.t('user-info.discriminator', {lngs: msg.lang}),
            value: user.discriminator,
            inline: true
        });
        fields.push({
            name: this.t('user-info.created', {lngs: msg.lang}),
            value: moment().to(user.createdAt),
            inline: true
        });
        if (member) {
            if (member.nick) {
                fields.push({name: this.t('user-info.nick', {lngs: msg.lang}), value: member.nick, inline: true});
            }
            fields.push({name: this.t('user-info.status', {lngs: msg.lang}), value: member.status, inline: true});
            if (member.game) {
                fields.push({
                    name: this.t('user-info.playing', {lngs: msg.lang}),
                    value: member.game.name,
                    inline: true
                });
            }
            fields.push({
                name: this.t('user-info.join', {lngs: msg.lang}),
                value: moment().to(member.joinedAt),
                inline: true
            });
            fields.push({
                name: this.t('user-info.role', {lngs: msg.lang}),
                value: member.roles.length,
                inline: true
            });
        }
        fields.push({
            name: 'LP',
            value: dbUser.rep,
            inline: true
        });
        fields.push({
            name: this.t('user-info.bot', {lngs: msg.lang}),
            value: user.bot ? ':white_check_mark: ' : ':x: ',
            inline: true
        });
        return fields;
    }
}
module.exports = UserInfo;<|endoftext|>