<commit_before>'use strict';
/*!
 * jquery-confirm v1.5.1 (http://craftpip.github.io/jquery-confirm/)
 * Author: Boniface Pereira
 * Website: www.craftpip.com
 * Contact: hey@craftpip.com
 *
 * Copyright 2013-2015 jquery-confirm
 * Licensed under MIT (https://github.com/craftpip/jquery-confirm/blob/master/LICENSE)
 */

if (typeof jQuery === 'undefined') {
    throw new Error('jquery-confirm requires jQuery');
}

var jconfirm, Jconfirm;
(function ($) {
    $.confirm = function (options) {
        /*
         *  Alias of jconfirm
         */
        return jconfirm(options);
    };
    $.alert = function (options) {
        /*
         *  Alias of jconfirm
         */
        options.cancelButton = false;
        return jconfirm(options);
    };
    $.dialog = function (options) {
        /*
         *  Alias of jconfirm
         */
        options.cancelButton = false;
        options.confirmButton = false;
        return jconfirm(options);
    };
    jconfirm = function (options) {
        /*
         * initial function for calling.
         */
        if (jconfirm.defaults) {
            /*
             * Merge global defaults with plugin defaults
             */
            $.extend(jconfirm.pluginDefaults, jconfirm.defaults);
        }
        /*
         * merge options with plugin defaults.
         */
        var options = $.extend({}, jconfirm.pluginDefaults, options);
        return new Jconfirm(options);
    };
    Jconfirm = function (options) {
        /*
         * constructor function Jconfirm,
         * options = user options.
         */
        $.extend(this, options);
        this._init();
    };
    Jconfirm.prototype = {
        _init: function () {
            var that = this;
            this._rand = Math.round(Math.random() * 99999);
            this._buildHTML();
            this._bindEvents();
            setTimeout(function () {
                that.open();
            }, 0);
        },
        animations: ['anim-scale', 'anim-top', 'anim-bottom', 'anim-left', 'anim-right', 'anim-zoom', 'anim-opacity', 'anim-none', 'anim-rotate', 'anim-rotatex', 'anim-rotatey', 'anim-scalex', 'anim-scaley'],
        _buildHTML: function () {
            var that = this;
            /*
             * Cleaning animations.
             */
            this.animation = 'anim-' + this.animation.toLowerCase();
            if (this.animation === 'none')
                this.animationSpeed = 0;
            /*
             * Append html to body.
             */
            this.$el = $(this.template).appendTo(this.container).addClass(this.theme);
            this.$b = this.$el.find('.jconfirm-box').css({
                '-webkit-transition-duration': this.animationSpeed / 1000 + 's',
                'transition-duration': this.animationSpeed / 1000 + 's'
            });

            this.$b.addClass(this.animation);

            var that = this;
            /*
             * timeout needed for DOM render time. or it never animates.
             */
            setTimeout(function(){
                that.$el.find('.jconfirm-bg').animate({
                    opacity: 1
                }, that.animationSpeed/2);
            }, 1);
            /*
             * setup html contents
             */
            this.$el.find('div.title').html(' ' + this.title);
            var contentDiv = this.$el.find('div.content');

            /*
             * Settings up buttons
             */
            var $btnc = this.$el.find('.buttons');
            if (this.confirmButton && this.confirmButton.trim() !== '') {
                this.$confirmButton = $('<button class="btn">' + this.confirmButton + '</button>').appendTo($btnc);
                this.$confirmButton.addClass(this.confirmButtonClass);
            }
            if (this.cancelButton && this.cancelButton.trim() !== '') {
                this.$cancelButton = $('<button class="btn">' + this.cancelButton + '</button>').appendTo($btnc);
                this.$cancelButton.addClass(this.cancelButtonClass);
            }
            if (!this.confirmButton && !this.cancelButton) {
                $btnc.remove();
                if (this.closeIcon)
                    this.$closeButton = this.$b.find('.closeIcon').show();
            }

            /*
             * If user provides a Url to load the content from.
             * Check if it has HTTP protocol.
             */
            if (this.content.substr(0, 4).toLowerCase() === 'url:') {
                contentDiv.html('');
                $btnc.find('button').attr('disabled', 'disabled');
                var url = this.content.substring(4, this.content.length);
                setTimeout(function () {
                    $.get(url, function (html) {
                        contentDiv.html(html);
                        $btnc.find('button').removeAttr('disabled');
                        that.setDialogCenter();
                    });
                }, 1);
            } else {
                contentDiv.html(this.content);
            }
            if (this.autoClose)
                this._startCountDown();
        },
        _startCountDown: function () {
            var opt = this.autoClose.split('|');
            if (/cancel/.test(opt[0]) && this.type === 'alert')
                return false;
            if (/confirm|cancel/.test(opt[0])) {
                this.$cd = $(' ').appendTo(this['$' + opt[0] + 'Button']);
                var that = this;
                that.$cd.parent().click();
                var time = opt[1] / 1000;
                this.interval = setInterval(function () {
                    that.$cd.html(' [' + (time -= 1) + ']');
                    if (time === 0) {
                        that.$cd.parent().trigger('click');
                        clearInterval(that.interval);
                    }
                }, 1000);
            }
        },
        _bindEvents: function () {
            var that = this;
            this.$el.find('.jconfirm-bg').click(function (e) {
                if (that.backgroundDismiss) {
                    that.cancel();
                    that.close();
                } else {
                    that.$b.addClass('hilight');
                    setTimeout(function () {
                        that.$b.removeClass('hilight');
                    }, 400);
                }
            });
            if (this.$confirmButton) {
                this.$confirmButton.click(function (e) {
                    e.preventDefault();
                    var r = that.confirm(that.$b);
                    if (typeof r === 'undefined' || r)
                        that.close();
                });
            }
            if (this.$cancelButton) {
                this.$cancelButton.click(function (e) {
                    e.preventDefault();
                    var r = that.cancel(that.$b);
                    if (typeof r === 'undefined' || r)
                        that.close();
                });
            }
            if (this.$closeButton) {
                this.$closeButton.click(function (e) {
                    e.preventDefault();
                    that.cancel();
                    that.close();
                });
            }
            if (this.keyboardEnabled) {
                setTimeout(function () {
                    $(window).on('keyup.' + this._rand, function (e) {
                        that.reactOnKey(e);
                    });
                }, 500);
            }

            $(window).on('resize.' + this._rand, function () {
                that.setDialogCenter();
            });

            this.setDialogCenter();
        },
        reactOnKey: function key(e) {
            /*
             * prevent keyup event if the dialog is not last!
             */
            var a = $('.jconfirm');
            if (a.eq(a.length - 1)[0] !== this.$el[0])
                return false;

            var key = e.which;
            console.log(e);
            if (key === 27) {
                /*
                 * if ESC key
                 */
                if (!this.backgroundDismiss) {
                    /*
                     * If background dismiss is false, Glow the modal.
                     */
                    this.$el.find('.jconfirm-bg').click();
                    return false;
                }

                if (this.$cancelButton) {
                    this.$cancelButton.click();
                } else {
                    this.close();
                }
            }
            if (key === 13) {
                /*
                 * if ENTER key
                 */
                if (this.$confirmButton) {
                    this.$confirmButton.click();
                } else {

                }
            }
        },
        setDialogCenter: function () {
            var h = $(window).height(),
                    h2 = this.$b.height(),
                    mar = (h - h2) / 2;
            this.$b.find('.content').css({
                'max-height': h - 200 + 'px'
            });
            this.$b.css({
                'margin-top': mar
            });
        },
        close: function () {
            var that = this;
            /*
             unbind the window resize & keyup event.
             */
            $(window).unbind('resize.' + this._rand);
            if (this.keyboardEnabled)
                $(window).unbind('keyup.' + this._rand);

            this.$el.find('.jconfirm-bg').animate({
                opacity: 0
            }, this.animationSpeed/2);
            this.$b.addClass(this.animation);
            $('body').removeClass('jconfirm-noscroll');
            setTimeout(function () {
                that.$el.remove();
            }, this.animationSpeed+30); // wait 30 miliseconds more, ensure everything is done.
        },
        open: function () {
            var that = this;
            $('body').addClass('jconfirm-noscroll');
            this.$b.removeClass(this.animations.join(' '));
            /**
             * Blur the focused elements, prevents re-execution with button press.
             */
            $('body :focus').trigger('blur');
        }
    };

    jconfirm.pluginDefaults = {
        template: '

',
        title: 'Hello',
        content: 'Are you sure to continue?',
        icon: '',
        confirmButton: 'Okay',
        cancelButton: 'Cancel',
        confirmButtonClass: 'btn-default',
        cancelButtonClass: 'btn-default',
        theme: 'white',
        animation: 'scale',
        animationSpeed: 400,
        keyboardEnabled: false,
        container: 'body',
        confirm: function () {
        },
        cancel: function () {
        },
        backgroundDismiss: true,
        autoClose: false,
        closeIcon: true,
    };
})(jQuery);<commit_msg>keyboard action , trigger Confirm on SPACE<commit_after>'use strict';
/*!
 * jquery-confirm v1.5.1 (http://craftpip.github.io/jquery-confirm/)
 * Author: Boniface Pereira
 * Website: www.craftpip.com
 * Contact: hey@craftpip.com
 *
 * Copyright 2013-2015 jquery-confirm
 * Licensed under MIT (https://github.com/craftpip/jquery-confirm/blob/master/LICENSE)
 */

if (typeof jQuery === 'undefined') {
    throw new Error('jquery-confirm requires jQuery');
}

var jconfirm, Jconfirm;
(function ($) {
    $.confirm = function (options) {
        /*
         *  Alias of jconfirm
         */
        return jconfirm(options);
    };
    $.alert = function (options) {
        /*
         *  Alias of jconfirm
         */
        options.cancelButton = false;
        return jconfirm(options);
    };
    $.dialog = function (options) {
        /*
         *  Alias of jconfirm
         */
        options.cancelButton = false;
        options.confirmButton = false;
        return jconfirm(options);
    };
    jconfirm = function (options) {
        /*
         * initial function for calling.
         */
        if (jconfirm.defaults) {
            /*
             * Merge global defaults with plugin defaults
             */
            $.extend(jconfirm.pluginDefaults, jconfirm.defaults);
        }
        /*
         * merge options with plugin defaults.
         */
        var options = $.extend({}, jconfirm.pluginDefaults, options);
        return new Jconfirm(options);
    };
    Jconfirm = function (options) {
        /*
         * constructor function Jconfirm,
         * options = user options.
         */
        $.extend(this, options);
        this._init();
    };
    Jconfirm.prototype = {
        _init: function () {
            var that = this;
            this._rand = Math.round(Math.random() * 99999);
            this._buildHTML();
            this._bindEvents();
            setTimeout(function () {
                that.open();
            }, 0);
        },
        animations: ['anim-scale', 'anim-top', 'anim-bottom', 'anim-left', 'anim-right', 'anim-zoom', 'anim-opacity', 'anim-none', 'anim-rotate', 'anim-rotatex', 'anim-rotatey', 'anim-scalex', 'anim-scaley'],
        _buildHTML: function () {
            var that = this;
            /*
             * Cleaning animations.
             */
            this.animation = 'anim-' + this.animation.toLowerCase();
            if (this.animation === 'none')
                this.animationSpeed = 0;
            /*
             * Append html to body.
             */
            this.$el = $(this.template).appendTo(this.container).addClass(this.theme);
            this.$b = this.$el.find('.jconfirm-box').css({
                '-webkit-transition-duration': this.animationSpeed / 1000 + 's',
                'transition-duration': this.animationSpeed / 1000 + 's'
            });

            this.$b.addClass(this.animation);

            var that = this;
            /*
             * timeout needed for DOM render time. or it never animates.
             */
            setTimeout(function(){
                that.$el.find('.jconfirm-bg').animate({
                    opacity: 1
                }, that.animationSpeed/2);
            }, 1);
            /*
             * setup html contents
             */
            this.$el.find('div.title').html(' ' + this.title);
            var contentDiv = this.$el.find('div.content');

            /*
             * Settings up buttons
             */
            var $btnc = this.$el.find('.buttons');
            if (this.confirmButton && this.confirmButton.trim() !== '') {
                this.$confirmButton = $('<button class="btn">' + this.confirmButton + '</button>').appendTo($btnc);
                this.$confirmButton.addClass(this.confirmButtonClass);
            }
            if (this.cancelButton && this.cancelButton.trim() !== '') {
                this.$cancelButton = $('<button class="btn">' + this.cancelButton + '</button>').appendTo($btnc);
                this.$cancelButton.addClass(this.cancelButtonClass);
            }
            if (!this.confirmButton && !this.cancelButton) {
                $btnc.remove();
                if (this.closeIcon)
                    this.$closeButton = this.$b.find('.closeIcon').show();
            }

            /*
             * If user provides a Url to load the content from.
             * Check if it has HTTP protocol.
             */
            if (this.content.substr(0, 4).toLowerCase() === 'url:') {
                contentDiv.html('');
                $btnc.find('button').attr('disabled', 'disabled');
                var url = this.content.substring(4, this.content.length);
                setTimeout(function () {
                    $.get(url, function (html) {
                        contentDiv.html(html);
                        $btnc.find('button').removeAttr('disabled');
                        that.setDialogCenter();
                    });
                }, 1);
            } else {
                contentDiv.html(this.content);
            }
            if (this.autoClose)
                this._startCountDown();
        },
        _startCountDown: function () {
            var opt = this.autoClose.split('|');
            if (/cancel/.test(opt[0]) && this.type === 'alert')
                return false;
            if (/confirm|cancel/.test(opt[0])) {
                this.$cd = $(' ').appendTo(this['$' + opt[0] + 'Button']);
                var that = this;
                that.$cd.parent().click();
                var time = opt[1] / 1000;
                this.interval = setInterval(function () {
                    that.$cd.html(' [' + (time -= 1) + ']');
                    if (time === 0) {
                        that.$cd.parent().trigger('click');
                        clearInterval(that.interval);
                    }
                }, 1000);
            }
        },
        _bindEvents: function () {
            var that = this;
            this.$el.find('.jconfirm-bg').click(function (e) {
                if (that.backgroundDismiss) {
                    that.cancel();
                    that.close();
                } else {
                    that.$b.addClass('hilight');
                    setTimeout(function () {
                        that.$b.removeClass('hilight');
                    }, 400);
                }
            });
            if (this.$confirmButton) {
                this.$confirmButton.click(function (e) {
                    e.preventDefault();
                    var r = that.confirm(that.$b);
                    if (typeof r === 'undefined' || r)
                        that.close();
                });
            }
            if (this.$cancelButton) {
                this.$cancelButton.click(function (e) {
                    e.preventDefault();
                    var r = that.cancel(that.$b);
                    if (typeof r === 'undefined' || r)
                        that.close();
                });
            }
            if (this.$closeButton) {
                this.$closeButton.click(function (e) {
                    e.preventDefault();
                    that.cancel();
                    that.close();
                });
            }
            if (this.keyboardEnabled) {
                setTimeout(function () {
                    $(window).on('keyup.' + this._rand, function (e) {
                        that.reactOnKey(e);
                    });
                }, 500);
            }

            $(window).on('resize.' + this._rand, function () {
                that.setDialogCenter();
            });

            this.setDialogCenter();
        },
        reactOnKey: function key(e) {
            /*
             * prevent keyup event if the dialog is not last!
             */
            var a = $('.jconfirm');
            if (a.eq(a.length - 1)[0] !== this.$el[0])
                return false;

            var key = e.which;
            console.log(key);
            if (key === 27) {
                /*
                 * if ESC key
                 */
                if (!this.backgroundDismiss) {
                    /*
                     * If background dismiss is false, Glow the modal.
                     */
                    this.$el.find('.jconfirm-bg').click();
                    return false;
                }

                if (this.$cancelButton) {
                    this.$cancelButton.click();
                } else {
                    this.close();
                }
            }
            if (key === 13 || key == 32) {
                /*
                 * if ENTER or SPACE key
                 */
                if (this.$confirmButton) {
                    this.$confirmButton.click();
                } else {

                }
            }
        },
        setDialogCenter: function () {
            var h = $(window).height(),
                    h2 = this.$b.height(),
                    mar = (h - h2) / 2;
            this.$b.find('.content').css({
                'max-height': h - 200 + 'px'
            });
            this.$b.css({
                'margin-top': mar
            });
        },
        close: function () {
            var that = this;
            /*
             unbind the window resize & keyup event.
             */
            $(window).unbind('resize.' + this._rand);
            if (this.keyboardEnabled)
                $(window).unbind('keyup.' + this._rand);

            this.$el.find('.jconfirm-bg').animate({
                opacity: 0
            }, this.animationSpeed/2);
            this.$b.addClass(this.animation);
            $('body').removeClass('jconfirm-noscroll');
            setTimeout(function () {
                that.$el.remove();
            }, this.animationSpeed+30); // wait 30 miliseconds more, ensure everything is done.
        },
        open: function () {
            var that = this;
            $('body').addClass('jconfirm-noscroll');
            this.$b.removeClass(this.animations.join(' '));
            /**
             * Blur the focused elements, prevents re-execution with button press.
             */
            $('body :focus').trigger('blur');
        }
    };

    jconfirm.pluginDefaults = {
        template: '

',
        title: 'Hello',
        content: 'Are you sure to continue?',
        icon: '',
        confirmButton: 'Okay',
        cancelButton: 'Cancel',
        confirmButtonClass: 'btn-default',
        cancelButtonClass: 'btn-default',
        theme: 'white',
        animation: 'scale',
        animationSpeed: 400,
        keyboardEnabled: false,
        container: 'body',
        confirm: function () {
        },
        cancel: function () {
        },
        backgroundDismiss: true,
        autoClose: false,
        closeIcon: true,
    };
})(jQuery);<|endoftext|>


<commit_before>import React from 'react';
import './status-button.scss';
import classnames from 'classnames';

export default (props) => (
  <button className={classnames('button', `-${props.type}`)} onClick={() => props.setStatus(props.type)}>
    {props.type}
  </button>
);
<commit_msg>Slices the last two characters off the button text<commit_after>import React from 'react';
import './status-button.scss';
import classnames from 'classnames';

export default (props) => (
  <button className={classnames('button', `-${props.type}`)} onClick={() => props.setStatus(props.type)}>
    // This technical debt was lovingly created by Luke Patton
    // When we aren't in crisis mode, we should untangle this button name from the prop name
    {props.type.slice(0,-2)}
  </button>
);
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import THREE from 'three';
import TWEEN from 'tween.js';

import { randomWithRange } from '../../businessLogic/mathHelpers';

export default class Orthofloat extends Component {
    componentDidMount() {
        this.initializeScene();
    }

    componentWillReceiveProps({ hue }) {
        if (hue !== this.props.hue) {
            this.cubeMaterial.color.setHSL(hue, this.colorSaturation, this.colorLightness);
        }
    }

    initializeScene() {
        // set some common variables
        this.windowHeight = window.innerHeight;
        this.windowWidth = window.innerWidth;

        this.scene = new THREE.Scene();
        this.camera = new THREE.OrthographicCamera(this.windowWidth / - 16, this.windowWidth / 16, this.windowHeight / 16, this.windowHeight / - 16, -200, 500);
        this.camera.position.x = 120;
        this.camera.lookAt(this.scene.position);

        this.addCubesToScene();

        this.directionalLight = new THREE.DirectionalLight( 0xffffff, 0.7 );
        this.directionalLight.position.set(60, 60, 60);
        this.scene.add(this.directionalLight);

        this.ambientLight = new THREE.AmbientLight(0x4B4B4B);
        this.scene.add(this.ambientLight);

        this.renderer = new THREE.WebGLRenderer();
        this.renderer.setClearColor(new THREE.Color(0xffffff, 1.0));
        this.renderer.setSize(this.windowWidth, this.windowHeight);

        this.el.appendChild(this.renderer.domElement);
        this.renderer.render(this.scene, this.camera);

        this.renderAnimation();
    }

    addCubesToScene() {
        this.cubeSize = 4;
        const cubeGeometry = new THREE.CubeGeometry(this.cubeSize, this.cubeSize, this.cubeSize);
        const colorAsHSL = new THREE.Color();
        this.colorSaturation = 1;
        this.colorLightness = 0.7;
        colorAsHSL.setHSL(this.props.hue, this.colorSaturation, this.colorLightness);
        this.cubeMaterial = new THREE.MeshLambertMaterial({color: colorAsHSL.getHex()});
        this.cubes = [];
        for (let i = 0; i < 20; i++) {
            const cube = new THREE.Mesh(cubeGeometry, this.cubeMaterial);
            cube.position.y = randomWithRange(this.windowHeight / 16, this.windowHeight / -16);
            cube.position.z = randomWithRange(this.windowWidth / 16, this.windowWidth / -16);
            cube.rotation.set(randomWithRange(0, Math.PI), randomWithRange(0, Math.PI), randomWithRange(0, Math.PI));
            cube.rotationSpeed = {
                x: randomWithRange(-0.01, 0.01),
                y: randomWithRange(-0.01, 0.01),
                z: randomWithRange(-0.01, 0.01)
            };
            cube.yVelocity = randomWithRange(0.03, 0.1);
            cube.zVelocity = randomWithRange(-0.01, 0.01);
            this.cubes.push(cube);
            this.scene.add(cube);
        }
    }

    renderAnimation() {
        for (const cube of this.cubes) {
            // if cube is above top of window
            if (cube.position.y > (this.windowHeight / 16 + this.cubeSize * 3)) {
                // put it below the bottom of the window and give it a random z position
                cube.position.y -= (this.windowHeight / 8 + this.cubeSize * 6);
                cube.position.z = randomWithRange(this.windowWidth / 16, this.windowWidth / -16);

                // give it new velocities
                cube.yVelocity = randomWithRange(0.03, 0.1);
                cube.zVelocity = randomWithRange(-0.01, 0.01);

                // give the cube new rotation speeds
                for (const axis of ['x', 'y', 'z']) {
                    cube.rotationSpeed[axis] = randomWithRange(-0.01, 0.01);
                }
            }

            // translate the cube
            cube.position.y += cube.yVelocity;
            cube.position.z += cube.zVelocity;

            // rotate the cube around its axes
            for (const axis of ['x', 'y', 'z']) {
                cube.rotation[axis] += cube.rotationSpeed[axis];
            }
     }

        requestAnimationFrame(() => this.renderAnimation());
        this.renderer.render(this.scene, this.camera);
    }

    render() {
        return
 this.el = c} />;
    }
}

Orthofloat.propTypes = {
    hue: PropTypes.number.isRequired
};

Orthofloat.defaultProps = {
    hue: 0.35714285714285715
};<commit_msg>tweening color change<commit_after>import React, { Component, PropTypes } from 'react';
import THREE from 'three';
import TWEEN from 'tween.js';

import { randomWithRange } from '../../businessLogic/mathHelpers';

export default class Orthofloat extends Component {
    componentDidMount() {
        this.initializeScene();
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.hue !== this.props.hue) {
            const { color } = this.cubeMaterial;
            const colorSL = { s: this.colorSaturation, l: this.colorLightness };
            const tween = new TWEEN.Tween({ h: this.props.hue})
                    .to({ h: nextProps.hue }, 1000)
                    .onUpdate(function() {
                        color.setHSL(this.h, colorSL.s, colorSL.l);
                    })
                    .start();
        }
    }

    initializeScene() {
        // set some common variables
        this.windowHeight = window.innerHeight;
        this.windowWidth = window.innerWidth;

        this.scene = new THREE.Scene();
        this.camera = new THREE.OrthographicCamera(this.windowWidth / - 16, this.windowWidth / 16, this.windowHeight / 16, this.windowHeight / - 16, -200, 500);
        this.camera.position.x = 120;
        this.camera.lookAt(this.scene.position);

        this.addCubesToScene();

        this.directionalLight = new THREE.DirectionalLight( 0xffffff, 0.7 );
        this.directionalLight.position.set(60, 60, 60);
        this.scene.add(this.directionalLight);

        this.ambientLight = new THREE.AmbientLight(0x4B4B4B);
        this.scene.add(this.ambientLight);

        this.renderer = new THREE.WebGLRenderer();
        this.renderer.setClearColor(new THREE.Color(0xffffff, 1.0));
        this.renderer.setSize(this.windowWidth, this.windowHeight);

        this.el.appendChild(this.renderer.domElement);
        this.renderer.render(this.scene, this.camera);

        this.renderAnimation();
    }

    addCubesToScene() {
        this.cubeSize = 4;
        const cubeGeometry = new THREE.CubeGeometry(this.cubeSize, this.cubeSize, this.cubeSize);
        const colorAsHSL = new THREE.Color();
        this.colorSaturation = 1;
        this.colorLightness = 0.7;
        colorAsHSL.setHSL(this.props.hue, this.colorSaturation, this.colorLightness);
        this.cubeMaterial = new THREE.MeshLambertMaterial({color: colorAsHSL.getHex()});
        this.cubes = [];
        for (let i = 0; i < 20; i++) {
            const cube = new THREE.Mesh(cubeGeometry, this.cubeMaterial);
            cube.position.y = randomWithRange(this.windowHeight / 16, this.windowHeight / -16);
            cube.position.z = randomWithRange(this.windowWidth / 16, this.windowWidth / -16);
            cube.rotation.set(randomWithRange(0, Math.PI), randomWithRange(0, Math.PI), randomWithRange(0, Math.PI));
            cube.rotationSpeed = {
                x: randomWithRange(-0.01, 0.01),
                y: randomWithRange(-0.01, 0.01),
                z: randomWithRange(-0.01, 0.01)
            };
            cube.yVelocity = randomWithRange(0.03, 0.1);
            cube.zVelocity = randomWithRange(-0.01, 0.01);
            this.cubes.push(cube);
            this.scene.add(cube);
        }
    }

    renderAnimation() {
        for (const cube of this.cubes) {
            // if cube is above top of window
            if (cube.position.y > (this.windowHeight / 16 + this.cubeSize * 3)) {
                // put it below the bottom of the window and give it a random z position
                cube.position.y -= (this.windowHeight / 8 + this.cubeSize * 6);
                cube.position.z = randomWithRange(this.windowWidth / 16, this.windowWidth / -16);

                // give it new velocities
                cube.yVelocity = randomWithRange(0.03, 0.1);
                cube.zVelocity = randomWithRange(-0.01, 0.01);

                // give the cube new rotation speeds
                for (const axis of ['x', 'y', 'z']) {
                    cube.rotationSpeed[axis] = randomWithRange(-0.01, 0.01);
                }
            }

            // translate the cube
            cube.position.y += cube.yVelocity;
            cube.position.z += cube.zVelocity;

            // rotate the cube around its axes
            for (const axis of ['x', 'y', 'z']) {
                cube.rotation[axis] += cube.rotationSpeed[axis];
            }
     }

        requestAnimationFrame(() => this.renderAnimation());
        TWEEN.update();
        this.renderer.render(this.scene, this.camera);
    }

    render() {
        return
 this.el = c} />;
    }
}

Orthofloat.propTypes = {
    hue: PropTypes.number.isRequired
};

Orthofloat.defaultProps = {
    hue: 0.35714285714285715
};<|endoftext|>


<commit_before>import core from 'core-js';
import {TemplateRegistryEntry} from './template-registry-entry';

var hasTemplateElement = ('content' in document.createElement('template'));

function importElements(frag, link, callback) {
  document.head.appendChild(frag);

  if(window.Polymer && Polymer.whenReady){
    Polymer.whenReady(callback);
  }else{
    link.addEventListener('load', callback);
  }
}

export class Loader {
  constructor(){
    this.templateRegistry = {};
  }

  loadModule(id){
    throw new Error('Loaders must implement loadModule(id).');
  }

  loadAllModules(ids){
    throw new Error('Loader must implement loadAllModules(ids).');
  }

  loadTemplate(url){
    throw new Error('Loader must implement loadTemplate(url).');
  }

  loadText(url){
    throw new Error('Loader must implement loadText(url).');
  }

  getOrCreateTemplateRegistryEntry(id){
    var entry = this.templateRegistry[id];

    if(entry === undefined){
      this.templateRegistry[id] = entry = new TemplateRegistryEntry(id);
    }

    return entry;
  }

  importDocument(url){
    return new Promise((resolve, reject) => {
      var frag = document.createDocumentFragment();
      var link = document.createElement('link');

      link.rel = 'import';
      link.href = url;
      frag.appendChild(link);

      importElements(frag, link, () => resolve(link.import));
    });
  }

  importTemplate(url){
    return this.importDocument(url).then(doc => {
      return this.findTemplate(doc, url);
    });
  }

  findTemplate(doc, url){
    if(!hasTemplateElement){
      HTMLTemplateElement.bootstrap(doc);
    }

    var template = doc.getElementsByTagName('template')[0];

    if(!template){
      throw new Error(`There was no template element found in '${url}'.`);
    }

    return template;
  }
}
<commit_msg>feat(loader): add support for view bundles<commit_after>import core from 'core-js';
import {TemplateRegistryEntry} from './template-registry-entry';

var hasTemplateElement = ('content' in document.createElement('template'));

function importElements(frag, link, callback) {
  if(frag){
    document.head.appendChild(frag);
  }

  if(window.Polymer && Polymer.whenReady){
    Polymer.whenReady(callback);
  }else{
    link.addEventListener('load', callback);
  }
}

export class Loader {
  constructor(){
    this.templateRegistry = {};
  }

  loadModule(id){
    throw new Error('Loaders must implement loadModule(id).');
  }

  loadAllModules(ids){
    throw new Error('Loader must implement loadAllModules(ids).');
  }

  loadTemplate(url){
    throw new Error('Loader must implement loadTemplate(url).');
  }

  loadText(url){
    throw new Error('Loader must implement loadText(url).');
  }

  getOrCreateTemplateRegistryEntry(id){
    var entry = this.templateRegistry[id];

    if(entry === undefined){
      this.templateRegistry[id] = entry = new TemplateRegistryEntry(id);
    }

    return entry;
  }

  importDocument(url){
    return new Promise((resolve, reject) => {
      var frag = document.createDocumentFragment();
      var link = document.createElement('link');

      link.rel = 'import';
      link.href = url;
      frag.appendChild(link);

      importElements(frag, link, () => resolve(link.import));
    });
  }

  importBundle(link){
    return new Promise((resolve, reject) => {
      if(link.import){
        if(!hasTemplateElement){
          HTMLTemplateElement.bootstrap(link.import);
        }

        resolve(link.import);
      }else{
        importElements(null, link, () => {
          if(!hasTemplateElement){
            HTMLTemplateElement.bootstrap(link.import);
          }

          resolve(link.import);
        });
      }
    });
  }

  importTemplate(url){
    return this.importDocument(url).then(doc => {
      return this.findTemplate(doc, url);
    });
  }

  findTemplate(doc, url){
    if(!hasTemplateElement){
      HTMLTemplateElement.bootstrap(doc);
    }

    var template = doc.getElementsByTagName('template')[0];

    if(!template){
      throw new Error(`There was no template element found in '${url}'.`);
    }

    return template;
  }

  findBundledTemplate(name, entry){
    if(this.bundle){
      var found = this.bundle.getElementById(name);
      if(found){
        entry.setTemplate(found);
        return Promise.resolve(true);
      }
    }else if(!this.bundleChecked){
      this.bundleChecked = true;

      var bundleLink = document.querySelector('link[aurelia-view-bundle]');
      if(bundleLink){
        return this.importBundle(bundleLink).then(doc => {
          this.bundle = doc;
          var found = this.bundle.getElementById(name);
          if(found){
            entry.setTemplate(found);
            return Promise.resolve(true);
          }
        });
      }
    }

    return Promise.resolve(false);
  }
}
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import bowser from 'bowser';
import classNames from 'classnames';
import THREE from 'three';
import TWEEN from 'tween.js';
import Stats from 'stats.js';
import lodashThrottle from 'lodash/throttle';
import lodashIsEqual from 'lodash/isEqual';

import { randomWithRange } from '../../businessLogic/mathHelpers';
import { averageRGB, randomRGB } from '../../businessLogic/threeHelpers';

import './orthofloat.scss';

export default class Orthofloat extends Component {
    constructor(props) {
        super(props);

        this.state = {
            windowHeight: window.innerHeight,
            windowWidth: window.innerWidth
        };
    }

    componentWillMount() {
        this.setVendorPrefix();
        this.stripeWidth = 25;
    }

    componentDidMount() {
        this.initializeScene();

        this.windowResizeFunc = lodashThrottle(() => this.onWindowResize(), 16.667);
        window.addEventListener('resize', this.windowResizeFunc);
    }

    componentWillReceiveProps(nextProps) {
        if (!lodashIsEqual(nextProps.bottomColor, this.props.bottomColor)) {
            const { randomShapeMaterialBottom, randomShapeMaterialTop, randomShapeMaterialMid } = this;
            const oldColors = {
                bottomR: this.props.bottomColor.r,
                bottomG: this.props.bottomColor.g,
                bottomB: this.props.bottomColor.b,
                topR: this.props.topColor.r,
                topG: this.props.topColor.g,
                topB: this.props.topColor.b
            };
            const newColors = {
                bottomR: nextProps.bottomColor.r,
                bottomG: nextProps.bottomColor.g,
                bottomB: nextProps.bottomColor.b,
                topR: nextProps.topColor.r,
                topG: nextProps.topColor.g,
                topB: nextProps.topColor.b
            };
            const tween = new TWEEN.Tween(oldColors)
                .to(newColors, 1000)
                .easing(TWEEN.Easing.Quadratic.Out)
                .onUpdate(function() {
                    randomShapeMaterialBottom.color = {
                        r: this.bottomR,
                        g: this.bottomG,
                        b: this.bottomB
                    };
                    randomShapeMaterialTop.color = {
                        r: this.topR,
                        g: this.topG,
                        b: this.topB
                    };
                    randomShapeMaterialMid.color = {
                        r: (this.bottomR + this.topR) / 2,
                        g: (this.bottomG + this.topG) / 2,
                        b: (this.bottomB + this.topB) / 2
                    };
                })
                .start();
        }
    }

    componentWillUnmount() {
        window.removeEventListener('resize', this.windowResizeFunc);
    }

    initializeScene() {
        this.scene = new THREE.Scene();

        this.initializeCamera();
        this.initializeMeshes();
        this.initializeLights();
        this.initializeRenderer();

        if (this.props.initializeWithStats) {
            this.initializeStats();
        }

        this.renderAnimation();
    }

    initializeCamera() {
        const { windowHeight, windowWidth } = this.state;
        this.camFactor = 16;
        this.camera = new THREE.OrthographicCamera(
            windowWidth / - this.camFactor,
            windowWidth / this.camFactor,
            windowHeight / this.camFactor,
            windowHeight / - this.camFactor,
            -200,
            500
        );
        this.camera.position.x = 120;
        this.camera.lookAt(this.scene.position);
    }

    initializeMeshes() {
        this.meshSize = 2.5;
        this.initializeRandomShapes();
        this.initializeTetrahedrons();
    }

    initializeRandomShapes() {
        const { bottomColor, topColor } = this.props;
        const threeTopColor = new THREE.Color(topColor.r, topColor.g, topColor.b);
        const threeBottomColor = new THREE.Color(bottomColor.r, bottomColor.g, bottomColor.b);
        this.randomShapeMaterialTop = new THREE.MeshBasicMaterial({ color: threeTopColor });
        this.randomShapeMaterialBottom = new THREE.MeshBasicMaterial({ color: threeBottomColor });
        this.randomShapeMaterialMid = new THREE.MeshBasicMaterial({ color: new THREE.Color(
            (this.randomShapeMaterialTop.color.r + this.randomShapeMaterialBottom.color.r) / 2,
            (this.randomShapeMaterialTop.color.g + this.randomShapeMaterialBottom.color.g) / 2,
            (this.randomShapeMaterialTop.color.b + this.randomShapeMaterialBottom.color.b) / 2
        )});
        this.randomShapes = [];
        for (let i = 0; i < 53; i++) {
            let shape;
            switch (i % 5) {
                case 0:
                    shape = new THREE.Mesh(this.generateRandomGeometry(), this.randomShapeMaterialTop);
                    break;
                case 1:
                    shape = new THREE.Mesh(this.generateRandomGeometry(), this.randomShapeMaterialBottom);
                    break;
                case 2:
                    shape = new THREE.Mesh(this.generateRandomGeometry(), this.randomShapeMaterialMid);
                    break;
                case 3:
                    shape = new THREE.Mesh(
                        this.generateRandomGeometry(),
                        new THREE.MeshBasicMaterial({ color: threeTopColor })
                    );
                    shape.colorTopToBottom = true;
                    break;
                case 4:
                default:
                    shape = new THREE.Mesh(
                        this.generateRandomGeometry(),
                        new THREE.MeshBasicMaterial({ color: threeBottomColor })
                    );
                    shape.colorBottomToTop = true;
            }
            this.setMeshInSpace(shape);
            this.randomShapes.push(shape);
            this.scene.add(shape);
        }
    }

    generateRandomGeometry() {
        const meshSize = randomWithRange(0.25, 2) * this.meshSize;
        switch (Math.floor(Math.random() * 11)) {
            case 10:
                return new THREE.TorusKnotGeometry(
                    meshSize, meshSize / 3, 40, 12, randomWithRange(1, 20), randomWithRange(1, 20)
                );
            case 9:
                return new THREE.TorusGeometry(meshSize, meshSize / 4, 16, 16, 4);
            case 8:
                return new THREE.SphereGeometry(meshSize, 16, 16);
            case 7:
                return new THREE.RingGeometry(meshSize / 2, meshSize, 16);
            case 6:
                return new THREE.PlaneGeometry(meshSize, meshSize, 0);
            case 5:
                return new THREE.OctahedronGeometry(meshSize, 0);
            case 4:
                return new THREE.IcosahedronGeometry(meshSize, 0);
            case 3:
                return new THREE.DodecahedronGeometry(meshSize, 0);
            case 2:
                return new THREE.CylinderGeometry(meshSize, meshSize, meshSize, 16);
            case 1:
                return new THREE.CircleGeometry(meshSize, 16);
            case 0:
            default:
                return new THREE.BoxGeometry(meshSize, meshSize, meshSize);
        }
    }

    initializeTetrahedrons() {
        const tetraGeometry = new THREE.TetrahedronGeometry(this.meshSize);
        const color = new THREE.Color(0xff6ba9);
        const tetraMaterial = new THREE.MeshBasicMaterial({color});
        this.tetras = [];
        for (let i = 0; i < 50; i++) {
            const tetra = new THREE.Mesh(tetraGeometry, tetraMaterial);
            this.setMeshInSpace(tetra);
            this.tetras.push(tetra);
            this.scene.add(tetra);
        }
    }

    setMeshInSpace(mesh) {
        const { windowHeight, windowWidth } = this.state;
        mesh.position.y = randomWithRange(windowHeight / 16, windowHeight / -16);
        mesh.position.z = randomWithRange(windowWidth / 16, windowWidth / -16);
        mesh.rotation.set(randomWithRange(0, Math.PI), randomWithRange(0, Math.PI), randomWithRange(0, Math.PI));
        mesh.rotationSpeed = {
            x: randomWithRange(-0.01, 0.01),
            y: randomWithRange(-0.01, 0.01),
            z: randomWithRange(-0.01, 0.01)
        };
        mesh.yVelocity = randomWithRange(0.03, 0.1);
        mesh.zVelocity = randomWithRange(-0.01, 0.01);
    }

    initializeLights() {
        const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.7 );
        directionalLight.position.set(60, 60, 60);
        this.scene.add(directionalLight);

        const ambientLight = new THREE.AmbientLight(0x4B4B4B);
        this.scene.add(ambientLight);
    }

    initializeRenderer() {
        const { windowHeight, windowWidth } = this.state;
        this.renderer = new THREE.WebGLRenderer({ alpha: true });
        this.renderer.setSize(windowWidth, windowHeight);

        this.el.appendChild(this.renderer.domElement);
        this.renderer.render(this.scene, this.camera);
    }

    initializeStats() {
        this.stats = new Stats();
        this.el.appendChild(this.stats.dom);
    }

    setVendorPrefix() {
        if (bowser.webkit) {
            this.vendorPrefix = '-webkit-';
        } else if (bowser.firefox) {
            this.vendorPrefix = '-moz-';
        } else if (bowser.opera) {
            this.vendorPrefix = '-o-';
        } else {
            this.vendorPrefix = '';
        }
    }

    onWindowResize() {
        const windowHeight = window.innerHeight,
              windowWidth = window.innerWidth;

        this.setState({ windowHeight, windowWidth });

        this.renderer.setSize(windowWidth, windowHeight);

        this.camera.left = windowWidth / -this.camFactor;
        this.camera.right = windowWidth / this.camFactor;
        this.camera.top = windowHeight / this.camFactor;
        this.camera.bottom = windowHeight / -this.camFactor;
        this.camera.updateProjectionMatrix();
    }

    renderAnimation() {
        if (this.stats && this.props.showStats) {
            this.stats.begin();
        }

        const { windowHeight, windowWidth } = this.state;
        const { topColor, bottomColor } = this.props;

        for (let mesh of this.randomShapes) {
            this.moveMesh(mesh);

            if (mesh.colorTopToBottom) {
                const visibleHeight = (windowHeight / 8);
                const positionFromBottom = mesh.position.y + (windowHeight / 16);
                const ratioUpScreen = Math.min(Math.max(positionFromBottom / visibleHeight, 0), 1);
                const newColor = {
                    r: topColor.r * (1 - ratioUpScreen) + bottomColor.r * ratioUpScreen,
                    g: topColor.g * (1 - ratioUpScreen) + bottomColor.g * ratioUpScreen,
                    b: topColor.b * (1 - ratioUpScreen) + bottomColor.b * ratioUpScreen
                };
                mesh.material.color = newColor;
            } else if (mesh.colorBottomToTop) {
                const visibleHeight = (windowHeight / 8);
                const positionFromBottom = mesh.position.y + (windowHeight / 16);
                const ratioUpScreen = Math.min(Math.max(positionFromBottom / visibleHeight, 0), 1);
                const newColor = {
                    r: bottomColor.r * (1 - ratioUpScreen) + topColor.r * ratioUpScreen,
                    g: bottomColor.g * (1 - ratioUpScreen) + topColor.g * ratioUpScreen,
                    b: bottomColor.b * (1 - ratioUpScreen) + topColor.b * ratioUpScreen
                };
                mesh.material.color = newColor;
            }
        }

        for (let mesh of this.tetras) {
            this.moveMesh(mesh);
        }

        TWEEN.update();
        this.renderer.render(this.scene, this.camera);

        if (this.stats && this.props.showStats) {
            this.stats.end();
        }

        requestAnimationFrame(() => this.renderAnimation());
    }

    moveMesh(mesh) {
        const { windowHeight, windowWidth } = this.state;

        // if shape is above top of window
        if (mesh.position.y > (windowHeight / 16 + this.meshSize * 3)) {
            // put it below the bottom of the window and give it a random z position
            mesh.position.y -= (windowHeight / 8 + this.meshSize * 6);
            mesh.position.z = randomWithRange(windowWidth / 16, windowWidth / -16);

            // give it new velocities
            mesh.yVelocity = randomWithRange(0.03, 0.1);
            mesh.zVelocity = randomWithRange(-0.01, 0.01);

            // give the mesh new rotation speeds
            for (let axis of ['x', 'y', 'z']) {
                mesh.rotationSpeed[axis] = randomWithRange(-0.01, 0.01);
            }
        }

        // translate the mesh
        mesh.position.y += mesh.yVelocity;
        mesh.position.z += mesh.zVelocity;

        // rotate the mesh around its axes
        for (let axis of ['x', 'y', 'z']) {
            mesh.rotation[axis] += mesh.rotationSpeed[axis];
        }
    }

    render() {
        const { showStats, topColor, bottomColor } = this.props;
        const { windowHeight, windowWidth } = this.state;
        const className = classNames('orthofloat-wrapper', { 'show-stats': showStats });
        const topColorStyle = (new THREE.Color(topColor.r, topColor.g, topColor.b)).getStyle();
        const bottomColorStyle = (new THREE.Color(bottomColor.r, bottomColor.g, bottomColor.b)).getStyle();
        const wrapperStyle = {
            backgroundImage: `${this.vendorPrefix}linear-gradient(${topColorStyle}, ${bottomColorStyle})`
        };
        const stripeStyle = {
            width: `${this.stripeWidth}px`,
            marginRight: `${this.stripeWidth}px`,
            backgroundImage: `${this.vendorPrefix}linear-gradient(${bottomColorStyle}, ${topColorStyle})`
        };
        const numOfStripes = Math.ceil(windowWidth / (this.stripeWidth * 2));
        let stripes = [];
        for (let i = 0; i < numOfStripes; i++) {
            stripes.push(
);
        }

        return (

 this.el = c}>

                    {stripes}

        );
    }
}

Orthofloat.propTypes = {
    bottomColor: PropTypes.shape({
        r: PropTypes.number.isRequired,
        g: PropTypes.number.isRequired,
        b: PropTypes.number.isRequired
    }),
    topColor: PropTypes.shape({
        r: PropTypes.number.isRequired,
        g: PropTypes.number.isRequired,
        b: PropTypes.number.isRequired
    }),
    initializeWithStats: PropTypes.bool,
    showStats: PropTypes.bool
};

Orthofloat.defaultProps = {
    bottomColor: randomRGB(),
    topColor: randomRGB(),
    initializeWithStats: false,
    showStats: false
};<commit_msg>use threeHelper averageRGB to get average between top and bottom material colors<commit_after>import React, { Component, PropTypes } from 'react';
import bowser from 'bowser';
import classNames from 'classnames';
import THREE from 'three';
import TWEEN from 'tween.js';
import Stats from 'stats.js';
import lodashThrottle from 'lodash/throttle';
import lodashIsEqual from 'lodash/isEqual';

import { randomWithRange } from '../../businessLogic/mathHelpers';
import { averageRGB, randomRGB } from '../../businessLogic/threeHelpers';

import './orthofloat.scss';

export default class Orthofloat extends Component {
    constructor(props) {
        super(props);

        this.state = {
            windowHeight: window.innerHeight,
            windowWidth: window.innerWidth
        };
    }

    componentWillMount() {
        this.setVendorPrefix();
        this.stripeWidth = 25;
    }

    componentDidMount() {
        this.initializeScene();

        this.windowResizeFunc = lodashThrottle(() => this.onWindowResize(), 16.667);
        window.addEventListener('resize', this.windowResizeFunc);
    }

    componentWillReceiveProps(nextProps) {
        if (!lodashIsEqual(nextProps.bottomColor, this.props.bottomColor)) {
            const { randomShapeMaterialBottom, randomShapeMaterialTop, randomShapeMaterialMid } = this;
            const oldColors = {
                bottomR: this.props.bottomColor.r,
                bottomG: this.props.bottomColor.g,
                bottomB: this.props.bottomColor.b,
                topR: this.props.topColor.r,
                topG: this.props.topColor.g,
                topB: this.props.topColor.b
            };
            const newColors = {
                bottomR: nextProps.bottomColor.r,
                bottomG: nextProps.bottomColor.g,
                bottomB: nextProps.bottomColor.b,
                topR: nextProps.topColor.r,
                topG: nextProps.topColor.g,
                topB: nextProps.topColor.b
            };
            const tween = new TWEEN.Tween(oldColors)
                .to(newColors, 1000)
                .easing(TWEEN.Easing.Quadratic.Out)
                .onUpdate(function() {
                    randomShapeMaterialBottom.color = {
                        r: this.bottomR,
                        g: this.bottomG,
                        b: this.bottomB
                    };
                    randomShapeMaterialTop.color = {
                        r: this.topR,
                        g: this.topG,
                        b: this.topB
                    };
                    randomShapeMaterialMid.color = averageRGB(
                        randomShapeMaterialBottom.color,
                        randomShapeMaterialTop.color
                    );
                })
                .start();
        }
    }

    componentWillUnmount() {
        window.removeEventListener('resize', this.windowResizeFunc);
    }

    initializeScene() {
        this.scene = new THREE.Scene();

        this.initializeCamera();
        this.initializeMeshes();
        this.initializeLights();
        this.initializeRenderer();

        if (this.props.initializeWithStats) {
            this.initializeStats();
        }

        this.renderAnimation();
    }

    initializeCamera() {
        const { windowHeight, windowWidth } = this.state;
        this.camFactor = 16;
        this.camera = new THREE.OrthographicCamera(
            windowWidth / - this.camFactor,
            windowWidth / this.camFactor,
            windowHeight / this.camFactor,
            windowHeight / - this.camFactor,
            -200,
            500
        );
        this.camera.position.x = 120;
        this.camera.lookAt(this.scene.position);
    }

    initializeMeshes() {
        this.meshSize = 2.5;
        this.initializeRandomShapes();
        this.initializeTetrahedrons();
    }

    initializeRandomShapes() {
        const { bottomColor, topColor } = this.props;
        const threeTopColor = new THREE.Color(topColor.r, topColor.g, topColor.b);
        const threeBottomColor = new THREE.Color(bottomColor.r, bottomColor.g, bottomColor.b);
        this.randomShapeMaterialTop = new THREE.MeshBasicMaterial({ color: threeTopColor });
        this.randomShapeMaterialBottom = new THREE.MeshBasicMaterial({ color: threeBottomColor });
        const averageColor = averageRGB(this.randomShapeMaterialTop.color, this.randomShapeMaterialBottom.color);
        this.randomShapeMaterialMid = new THREE.MeshBasicMaterial({
            color: new THREE.Color(averageColor.r, averageColor.g, averageColor.b)
        });
        this.randomShapes = [];
        for (let i = 0; i < 53; i++) {
            let shape;
            switch (i % 5) {
                case 0:
                    shape = new THREE.Mesh(this.generateRandomGeometry(), this.randomShapeMaterialTop);
                    break;
                case 1:
                    shape = new THREE.Mesh(this.generateRandomGeometry(), this.randomShapeMaterialBottom);
                    break;
                case 2:
                    shape = new THREE.Mesh(this.generateRandomGeometry(), this.randomShapeMaterialMid);
                    break;
                case 3:
                    shape = new THREE.Mesh(
                        this.generateRandomGeometry(),
                        new THREE.MeshBasicMaterial({ color: threeTopColor })
                    );
                    shape.colorTopToBottom = true;
                    break;
                case 4:
                default:
                    shape = new THREE.Mesh(
                        this.generateRandomGeometry(),
                        new THREE.MeshBasicMaterial({ color: threeBottomColor })
                    );
                    shape.colorBottomToTop = true;
            }
            this.setMeshInSpace(shape);
            this.randomShapes.push(shape);
            this.scene.add(shape);
        }
    }

    generateRandomGeometry() {
        const meshSize = randomWithRange(0.25, 2) * this.meshSize;
        switch (Math.floor(Math.random() * 11)) {
            case 10:
                return new THREE.TorusKnotGeometry(
                    meshSize, meshSize / 3, 40, 12, randomWithRange(1, 20), randomWithRange(1, 20)
                );
            case 9:
                return new THREE.TorusGeometry(meshSize, meshSize / 4, 16, 16, 4);
            case 8:
                return new THREE.SphereGeometry(meshSize, 16, 16);
            case 7:
                return new THREE.RingGeometry(meshSize / 2, meshSize, 16);
            case 6:
                return new THREE.PlaneGeometry(meshSize, meshSize, 0);
            case 5:
                return new THREE.OctahedronGeometry(meshSize, 0);
            case 4:
                return new THREE.IcosahedronGeometry(meshSize, 0);
            case 3:
                return new THREE.DodecahedronGeometry(meshSize, 0);
            case 2:
                return new THREE.CylinderGeometry(meshSize, meshSize, meshSize, 16);
            case 1:
                return new THREE.CircleGeometry(meshSize, 16);
            case 0:
            default:
                return new THREE.BoxGeometry(meshSize, meshSize, meshSize);
        }
    }

    initializeTetrahedrons() {
        const tetraGeometry = new THREE.TetrahedronGeometry(this.meshSize);
        const color = new THREE.Color(0xff6ba9);
        const tetraMaterial = new THREE.MeshBasicMaterial({color});
        this.tetras = [];
        for (let i = 0; i < 50; i++) {
            const tetra = new THREE.Mesh(tetraGeometry, tetraMaterial);
            this.setMeshInSpace(tetra);
            this.tetras.push(tetra);
            this.scene.add(tetra);
        }
    }

    setMeshInSpace(mesh) {
        const { windowHeight, windowWidth } = this.state;
        mesh.position.y = randomWithRange(windowHeight / 16, windowHeight / -16);
        mesh.position.z = randomWithRange(windowWidth / 16, windowWidth / -16);
        mesh.rotation.set(randomWithRange(0, Math.PI), randomWithRange(0, Math.PI), randomWithRange(0, Math.PI));
        mesh.rotationSpeed = {
            x: randomWithRange(-0.01, 0.01),
            y: randomWithRange(-0.01, 0.01),
            z: randomWithRange(-0.01, 0.01)
        };
        mesh.yVelocity = randomWithRange(0.03, 0.1);
        mesh.zVelocity = randomWithRange(-0.01, 0.01);
    }

    initializeLights() {
        const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.7 );
        directionalLight.position.set(60, 60, 60);
        this.scene.add(directionalLight);

        const ambientLight = new THREE.AmbientLight(0x4B4B4B);
        this.scene.add(ambientLight);
    }

    initializeRenderer() {
        const { windowHeight, windowWidth } = this.state;
        this.renderer = new THREE.WebGLRenderer({ alpha: true });
        this.renderer.setSize(windowWidth, windowHeight);

        this.el.appendChild(this.renderer.domElement);
        this.renderer.render(this.scene, this.camera);
    }

    initializeStats() {
        this.stats = new Stats();
        this.el.appendChild(this.stats.dom);
    }

    setVendorPrefix() {
        if (bowser.webkit) {
            this.vendorPrefix = '-webkit-';
        } else if (bowser.firefox) {
            this.vendorPrefix = '-moz-';
        } else if (bowser.opera) {
            this.vendorPrefix = '-o-';
        } else {
            this.vendorPrefix = '';
        }
    }

    onWindowResize() {
        const windowHeight = window.innerHeight,
              windowWidth = window.innerWidth;

        this.setState({ windowHeight, windowWidth });

        this.renderer.setSize(windowWidth, windowHeight);

        this.camera.left = windowWidth / -this.camFactor;
        this.camera.right = windowWidth / this.camFactor;
        this.camera.top = windowHeight / this.camFactor;
        this.camera.bottom = windowHeight / -this.camFactor;
        this.camera.updateProjectionMatrix();
    }

    renderAnimation() {
        if (this.stats && this.props.showStats) {
            this.stats.begin();
        }

        const { windowHeight, windowWidth } = this.state;
        const { topColor, bottomColor } = this.props;

        for (let mesh of this.randomShapes) {
            this.moveMesh(mesh);

            if (mesh.colorTopToBottom) {
                const visibleHeight = (windowHeight / 8);
                const positionFromBottom = mesh.position.y + (windowHeight / 16);
                const ratioUpScreen = Math.min(Math.max(positionFromBottom / visibleHeight, 0), 1);
                const newColor = {
                    r: topColor.r * (1 - ratioUpScreen) + bottomColor.r * ratioUpScreen,
                    g: topColor.g * (1 - ratioUpScreen) + bottomColor.g * ratioUpScreen,
                    b: topColor.b * (1 - ratioUpScreen) + bottomColor.b * ratioUpScreen
                };
                mesh.material.color = newColor;
            } else if (mesh.colorBottomToTop) {
                const visibleHeight = (windowHeight / 8);
                const positionFromBottom = mesh.position.y + (windowHeight / 16);
                const ratioUpScreen = Math.min(Math.max(positionFromBottom / visibleHeight, 0), 1);
                const newColor = {
                    r: bottomColor.r * (1 - ratioUpScreen) + topColor.r * ratioUpScreen,
                    g: bottomColor.g * (1 - ratioUpScreen) + topColor.g * ratioUpScreen,
                    b: bottomColor.b * (1 - ratioUpScreen) + topColor.b * ratioUpScreen
                };
                mesh.material.color = newColor;
            }
        }

        for (let mesh of this.tetras) {
            this.moveMesh(mesh);
        }

        TWEEN.update();
        this.renderer.render(this.scene, this.camera);

        if (this.stats && this.props.showStats) {
            this.stats.end();
        }

        requestAnimationFrame(() => this.renderAnimation());
    }

    moveMesh(mesh) {
        const { windowHeight, windowWidth } = this.state;

        // if shape is above top of window
        if (mesh.position.y > (windowHeight / 16 + this.meshSize * 3)) {
            // put it below the bottom of the window and give it a random z position
            mesh.position.y -= (windowHeight / 8 + this.meshSize * 6);
            mesh.position.z = randomWithRange(windowWidth / 16, windowWidth / -16);

            // give it new velocities
            mesh.yVelocity = randomWithRange(0.03, 0.1);
            mesh.zVelocity = randomWithRange(-0.01, 0.01);

            // give the mesh new rotation speeds
            for (let axis of ['x', 'y', 'z']) {
                mesh.rotationSpeed[axis] = randomWithRange(-0.01, 0.01);
            }
        }

        // translate the mesh
        mesh.position.y += mesh.yVelocity;
        mesh.position.z += mesh.zVelocity;

        // rotate the mesh around its axes
        for (let axis of ['x', 'y', 'z']) {
            mesh.rotation[axis] += mesh.rotationSpeed[axis];
        }
    }

    render() {
        const { showStats, topColor, bottomColor } = this.props;
        const { windowHeight, windowWidth } = this.state;
        const className = classNames('orthofloat-wrapper', { 'show-stats': showStats });
        const topColorStyle = (new THREE.Color(topColor.r, topColor.g, topColor.b)).getStyle();
        const bottomColorStyle = (new THREE.Color(bottomColor.r, bottomColor.g, bottomColor.b)).getStyle();
        const wrapperStyle = {
            backgroundImage: `${this.vendorPrefix}linear-gradient(${topColorStyle}, ${bottomColorStyle})`
        };
        const stripeStyle = {
            width: `${this.stripeWidth}px`,
            marginRight: `${this.stripeWidth}px`,
            backgroundImage: `${this.vendorPrefix}linear-gradient(${bottomColorStyle}, ${topColorStyle})`
        };
        const numOfStripes = Math.ceil(windowWidth / (this.stripeWidth * 2));
        let stripes = [];
        for (let i = 0; i < numOfStripes; i++) {
            stripes.push(
);
        }

        return (

 this.el = c}>

                    {stripes}

        );
    }
}

Orthofloat.propTypes = {
    bottomColor: PropTypes.shape({
        r: PropTypes.number.isRequired,
        g: PropTypes.number.isRequired,
        b: PropTypes.number.isRequired
    }),
    topColor: PropTypes.shape({
        r: PropTypes.number.isRequired,
        g: PropTypes.number.isRequired,
        b: PropTypes.number.isRequired
    }),
    initializeWithStats: PropTypes.bool,
    showStats: PropTypes.bool
};

Orthofloat.defaultProps = {
    bottomColor: randomRGB(),
    topColor: randomRGB(),
    initializeWithStats: false,
    showStats: false
};<|endoftext|>


<commit_before>/*global window*/
(function (angular, sprintf, vsprintf, moment) {
	'use strict';

	angular.module('logger', []).
	provider('logEnhancer', function() {
        this.loggingPattern = '%s - %s: '; // default logging pattern, overwrite in config phase
        this.LEVEL = { TRACE: 4, DEBUG: 3, INFO: 2, WARN: 1, ERROR: 0 }; // with these configure loglevels in config fase
        this.logLevels = {'*': this.LEVEL.TRACE}; // everything by everyone should be visible by default

		this.$get = function() {
			var loggingPattern = this.loggingPattern;
			var LEVEL = this.LEVEL;
			var logLevels = this.logLevels;
			return {

                // Actually modifies $log. Without calling this in the run phase, $log remains untouched
				enhanceAngularLog : function($log) {
					$log.enabledContexts = [];

					$log.getInstance = function(context) {
						return {
							log	: enhanceLogging($log.log, LEVEL.INFO, context, loggingPattern),
							info	: enhanceLogging($log.info, LEVEL.INFO, context, loggingPattern),
							warn	: enhanceLogging($log.warn, LEVEL.WARN, context, loggingPattern),
							debug	: enhanceLogging($log.debug, LEVEL.DEBUG, context, loggingPattern),
							error	: enhanceLogging($log.error, LEVEL.ERROR, context, loggingPattern),
							enableLogging : function(enable) {
								$log.enabledContexts[context] = enable;
							}
						};
					};

					function enhanceLogging(loggingFunc, level, context, loggingPattern) {
						return function() {
							var contextEnabled = $log.enabledContexts[context];
							if (contextEnabled === undefined || contextEnabled) {
                                if (levelPassesThreshold(context, level)) {
	                                loggingFunc.apply(null, enhanceLogline(arguments, context, loggingPattern));
                                }
                            }
						};

						function enhanceLogline(args, context, loggingPattern) {
							var dateStr = '';
	                        if (moment) {
	                            dateStr = moment().format("dddd h:mm:ss a");
	                        } else {
	                            var d = new Date();
	                            var timeStr = new Date().toTimeString().match( /^([0-9]{2}:[0-9]{2}:[0-9]{2})/ )[0];
	                            dateStr = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + timeStr;
	                        }

							var prefix = '';
	                        if (sprintf && moment) {
	                        	prefix = sprintf(loggingPattern, dateStr, context);
	                        } else {
	                        	// use fixed layout: '%s::[%s]> '
	                        	prefix = dateStr + '::[' + context + ']> ';
	                        }

							var modifiedArguments = [].slice.call(args);
							modifiedArguments.unshift(prefix);
							return modifiedArguments;
						}
					}

                    function levelPassesThreshold(context, level) {
                        return level <= getLogLevelThreshold(context);

                        function getLogLevelThreshold(context) {
                            if (logLevels[context]) {
                                return logLevels[context];
                            } else if (context.indexOf('.') != -1) {
                                return getLogLevelThreshold(context.substring(0, context.lastIndexOf('.')));
                            } else {
                                return logLevels['*'];
                            }
                        }
                    }
				}
			};
		};
	}).
    config(['logEnhancerProvider',
        function (logEnhancerProvider) {
            logEnhancerProvider.loggingPattern = '%s::[%s]> ';
            logEnhancerProvider.logLevels = {'*': logEnhancerProvider.LEVEL.TRACE};
            /*
                // example structure:
                logEnhancerProvider.logLevels = {
                    'a.b.c': logEnhancerProvider.LEVEL.TRACE, // trace + debug + info + warn + error
                    'a.b.d': logEnhancerProvider.LEVEL.ERROR, // error
                    'a.b': logEnhancerProvider.LEVEL.DEBUG, // debug + info + warn + error
                    'a': logEnhancerProvider.LEVEL.WARN, // warn + error
                    '*': logEnhancerProvider.LEVEL.INFO // info + warn + error
                };
            */
        }
    ]).
    run(['$log', 'logEnhancer',
        function ($log, logEnhancer) {
            if (!sprintf) {
                $log.warn("sprintf.js not found: https://github.com/alexei/sprintf.js, using fixed layout pattern '%s::[%s]> '");
            }
            if (!moment) {
                $log.warn("moment.js not found: http://momentjs.com, using simple Date format");
            }
            logEnhancer.enhanceAngularLog($log);
			$log.info('logging enhancer initiated');
        }
    ]);
}(window.angular, window.sprintf, window.vsprintf, window.moment));<commit_msg>allow logLevels to be changes after config phase as well<commit_after>/*global window*/
(function (angular, sprintf, vsprintf, moment) {
	'use strict';

	angular.module('logger', []).
	provider('logEnhancer', function() {
        this.loggingPattern = '%s - %s: '; // default logging pattern, overwrite in config phase
        this.LEVEL = { TRACE: 4, DEBUG: 3, INFO: 2, WARN: 1, ERROR: 0 }; // with these configure loglevels in config fase
        this.logLevels = {'*': this.LEVEL.TRACE}; // everything by everyone should be visible by default

		this.$get = function() {
			var enabledContexts = [];
			var loggingPattern = this.loggingPattern;
			var LEVEL = this.LEVEL;
			var logLevels = this.logLevels;
			return {

                // Actually modifies $log. Without calling this in the run phase, $log remains untouched
				enhanceAngularLog : function($log) {
					$log.LEVEL = LEVEL; // assign to $log, so the user can change them after config phase
					$log.logLevels = logLevels; // assign to $log, so the user can change them after config phase

					$log.getInstance = function(context) {
						return {
							log	: enhanceLogging($log.log, $log.LEVEL.INFO, context, loggingPattern),
							info	: enhanceLogging($log.info, $log.LEVEL.INFO, context, loggingPattern),
							warn	: enhanceLogging($log.warn, $log.LEVEL.WARN, context, loggingPattern),
							debug	: enhanceLogging($log.debug, $log.LEVEL.DEBUG, context, loggingPattern),
							error	: enhanceLogging($log.error, $log.LEVEL.ERROR, context, loggingPattern),
							enableLogging : function(enable) {
								enabledContexts[context] = enable;
							}
						};
					};

					function enhanceLogging(loggingFunc, level, context, loggingPattern) {
						return function() {
							var contextEnabled = enabledContexts[context];
							if (contextEnabled === undefined || contextEnabled) {
                                if (levelPassesThreshold(context, level)) {
	                                loggingFunc.apply(null, enhanceLogline(arguments, context, loggingPattern));
                                }
                            }
						};

						function enhanceLogline(args, context, loggingPattern) {
							var dateStr = '';
	                        if (moment) {
	                            dateStr = moment().format("dddd h:mm:ss a");
	                        } else {
	                            var d = new Date();
	                            var timeStr = new Date().toTimeString().match( /^([0-9]{2}:[0-9]{2}:[0-9]{2})/ )[0];
	                            dateStr = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + timeStr;
	                        }

							var prefix = '';
	                        if (sprintf && moment) {
	                        	prefix = sprintf(loggingPattern, dateStr, context);
	                        } else {
	                        	// use fixed layout: '%s::[%s]> '
	                        	prefix = dateStr + '::[' + context + ']> ';
	                        }

							var modifiedArguments = [].slice.call(args);
							modifiedArguments.unshift(prefix);
							return modifiedArguments;
						}
					}

                    function levelPassesThreshold(context, level) {
                        return level <= getLogLevelThreshold(context);

                        function getLogLevelThreshold(context) {
                            if ($log.logLevels[context]) {
                                return $log.logLevels[context];
                            } else if (context.indexOf('.') != -1) {
                                return getLogLevelThreshold(context.substring(0, context.lastIndexOf('.')));
                            } else {
                                return $log.logLevels['*'];
                            }
                        }
                    }
				}
			};
		};
	}).
    config(['logEnhancerProvider',
        function (logEnhancerProvider) {
            logEnhancerProvider.loggingPattern = '%s::[%s]> ';
            logEnhancerProvider.logLevels = {'*': logEnhancerProvider.LEVEL.TRACE};
            /*
                // example structure:
                logEnhancerProvider.logLevels = {
                    'a.b.c': logEnhancerProvider.LEVEL.TRACE, // trace + debug + info + warn + error
                    'a.b.d': logEnhancerProvider.LEVEL.ERROR, // error
                    'a.b': logEnhancerProvider.LEVEL.DEBUG, // debug + info + warn + error
                    'a': logEnhancerProvider.LEVEL.WARN, // warn + error
                    '*': logEnhancerProvider.LEVEL.INFO // info + warn + error
                };
            */
        }
    ]).
    run(['$log', 'logEnhancer',
        function ($log, logEnhancer) {
            if (!sprintf) {
                $log.warn("sprintf.js not found: https://github.com/alexei/sprintf.js, using fixed layout pattern '%s::[%s]> '");
            }
            if (!moment) {
                $log.warn("moment.js not found: http://momentjs.com, using simple Date format");
            }
            logEnhancer.enhanceAngularLog($log);
			$log.info('logging enhancer initiated');
        }
    ]);
}(window.angular, window.sprintf, window.vsprintf, window.moment));<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

/*jslint node: true, nomen: true, white: true*/

var crypto = require('crypto'),
    format = require('./compat').format,
    fs = require('fs'),
    path = require('path'),
    und = require('underscore');

var opts,
    _assets,
    _cache = {};

"use strict";

exports.setup = function (assets, options) {
  _assets = assets;
  if (!options) options = {};
  opts = options;
  if (options.production === undefined) {
    opts.production = true;
  }
  if (!options.root) opts.root = '.';
  if (!options.prefix) {
    opts.prefix = '';
  // Must end with a '/'
  } else if (options.prefix.slice(-1) !== '/') {
    opts.prefix += '/';
  }
  // Don't lead with a '/'
  if (opts.prefix.charAt(0) === '/') {
    opts.prefix = opts.prefix.slice(1);
  }
  if (options.control_headers === undefined) {
    opts.control_headers = false;
  }
  if (options.debug === undefined) {
    opts.debug = false;
  }

  return function (req, resp, next) {
    // If the first path element is a md5 hash AND one of the following:
    // * the path is opts.prefix
    // * the filename is a key in our opts[family]
    // * or the file exists on the filesystem
    var prefix = escape_regex(no_url(opts.prefix)),
        fmt = format('^\\/%s[a-f0-9]{10}', prefix),
        m = req.url.match(new RegExp(fmt)),
        true_path, exists;

    resp.local('cachify_js', cachify_js);
    resp.local('cachify_css', cachify_css);
    resp.local('cachify', cachify);
    if (m && m.index === 0) {
      // 10 first characters of md5 + 1 for slash
      true_path = req.url.slice(prefix.length + 11);
      exists = false;

      if (opts.prefix !== '' &&
          req.url.indexOf('/' + opts.prefix) === 0) {
        exists = true;
      } else if (assets[true_path]) {
        exists = true;
      }

      if (exists === false) {
        if (_cache[true_path]) {
          if (_cache[true_path].exists === true) {
            exists = true;
          }
        } else {
          // Would we ever want to use cachify for non-file resources?
          if (path.existsSync(path.join(opts.root, true_path))) {
            exists = true;
            _cache[true_path] = {exists: true};
          } else {
            // Hmm potential DOS Attack here... maybe we shouldn't cache
            // checking disk every time isn't that bad - just like static
            // middleware
            // Or use an LRU?
            console.warn('Cachify like URL, but no file found');
            _cache[true_path] = {exists: false};
          }
        }
      }
      if (exists === true) {
        resp.setHeader('Cache-Control', 'public, max-age=31536000');
        req.url = true_path;
        if (opts.control_headers === true) {
          resp.on('header', function () {
            // Relax other middleware... I got this one
            ['ETag', 'Last-Modified'].forEach(function (header) {
              if (resp.getHeader(header)) resp.removeHeader(header);
              if (resp.getHeader(header)) resp.removeHeader(header);
            });
          });
        }
      }
    }
    next();
  };
};

/**
 * If filename is an absolute path (starts with a '/') The hash
 * will be pre-pended with be slashified.
 * Examples:
 * /foo.js                   -> /a998d8e98f/foo.js
 * foo.js                    -> a998d8e98f/foo.js
 * http://example.com/foo.js -> http://example.com/foo.js
 */
var hashify = function (filename, hash) {
  if (typeof filename !== 'string')
    throw "cachify ERROR, expected string for filename, got " + filename;
  if (filename.indexOf('://') !== -1) {
    return filename;
  }
  if (! hash && opts.global_hash) {
    hash = opts.global_hash;
  }

  if (opts.production !== true &&
      opts.debug === false) {
    return filename;
  }
  if (hash) {
    // No-op, specifing a hash skips all this craziness
  } else if (_cache[filename] && _cache[filename].hash) {
    hash = _cache[filename].hash;
    console.info('cache hit ', filename);
  } else {
    console.info('cache miss ', filename);
    var md5 = crypto.createHash('md5');
    try {
      var data = fs.readFileSync(path.join(opts.root, filename));
      md5.update(data);
      // Expensive, maintain in-memory cache
      if (! _cache[filename]) _cache[filename] = {exists: true};
      hash = _cache[filename].hash = md5.digest('hex').slice(0, 10);
    } catch (e) {
      // Not intersting to cache, programmer error?
      console.error('Cachify bailing on hash... no such file ' + filename );
      console.error(e);
      return filename;
    }
  }
  if (opts.prefix.indexOf('://') === -1 &&
      filename[0] === '/') {
    return format('/%s%s%s', opts.prefix, hash, filename);
  } else {
    return format('%s%s/%s', opts.prefix, hash, filename);
  }
};

var prod_or_dev_tags = function (filename, link_fmt, hash) {
  if (opts.production !== true &&
      _assets[filename]) {
        return und.map(_assets[filename], function (f) {
          return format(link_fmt, hashify(f, hash));
        }).join('\n');
  }
  return format(link_fmt, hashify(filename, hash));
};

exports.cachify_js = cachify_js = function (filename, options) {
  if (! options) options = {};
  return prod_or_dev_tags(filename,
                          '<script src="%s"></script>',
                          options['hash']);
};

exports.cachify_css = cachify_css = function (filename, options) {
  if (! options) options = {};
  return prod_or_dev_tags(filename,
                          '<link href="%s" rel="stylesheet" type="text/css">',
                          options['hash']);
};

exports.cachify = cachify = function (filename, options) {
  var tag_format;
  if (! options) options = {};
  if (options['tag_format'])
      tag_format = options['tag_format'];
  else
      tag_format = '%s';
  return prod_or_dev_tags(filename, tag_format, options['hash']);
};

var no_url = function (prefix) {
  if (prefix.indexOf('://') === -1) return prefix;
  var m = prefix.match(/^[a-z]{3,5}:\/\/[a-z0-9-_.]*(?:\:[0-9]*)?\/(.*)$/i);
  if (m) return m[1];
  else return prefix;
};

var escape_regex = function (str) {
  return str.replace('/', '\/');
};<commit_msg>Removing debug level console.log<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

/*jslint node: true, nomen: true, white: true*/

var crypto = require('crypto'),
    format = require('./compat').format,
    fs = require('fs'),
    path = require('path'),
    und = require('underscore');

var opts,
    _assets,
    _cache = {};

"use strict";

exports.setup = function (assets, options) {
  _assets = assets;
  if (!options) options = {};
  opts = options;
  if (options.production === undefined) {
    opts.production = true;
  }
  if (!options.root) opts.root = '.';
  if (!options.prefix) {
    opts.prefix = '';
  // Must end with a '/'
  } else if (options.prefix.slice(-1) !== '/') {
    opts.prefix += '/';
  }
  // Don't lead with a '/'
  if (opts.prefix.charAt(0) === '/') {
    opts.prefix = opts.prefix.slice(1);
  }
  if (options.control_headers === undefined) {
    opts.control_headers = false;
  }
  if (options.debug === undefined) {
    opts.debug = false;
  }

  return function (req, resp, next) {
    // If the first path element is a md5 hash AND one of the following:
    // * the path is opts.prefix
    // * the filename is a key in our opts[family]
    // * or the file exists on the filesystem
    var prefix = escape_regex(no_url(opts.prefix)),
        fmt = format('^\\/%s[a-f0-9]{10}', prefix),
        m = req.url.match(new RegExp(fmt)),
        true_path, exists;

    resp.local('cachify_js', cachify_js);
    resp.local('cachify_css', cachify_css);
    resp.local('cachify', cachify);
    if (m && m.index === 0) {
      // 10 first characters of md5 + 1 for slash
      true_path = req.url.slice(prefix.length + 11);
      exists = false;

      if (opts.prefix !== '' &&
          req.url.indexOf('/' + opts.prefix) === 0) {
        exists = true;
      } else if (assets[true_path]) {
        exists = true;
      }

      if (exists === false) {
        if (_cache[true_path]) {
          if (_cache[true_path].exists === true) {
            exists = true;
          }
        } else {
          // Would we ever want to use cachify for non-file resources?
          if (path.existsSync(path.join(opts.root, true_path))) {
            exists = true;
            _cache[true_path] = {exists: true};
          } else {
            // Hmm potential DOS Attack here... maybe we shouldn't cache
            // checking disk every time isn't that bad - just like static
            // middleware
            // Or use an LRU?
            console.warn('Cachify like URL, but no file found');
            _cache[true_path] = {exists: false};
          }
        }
      }
      if (exists === true) {
        resp.setHeader('Cache-Control', 'public, max-age=31536000');
        req.url = true_path;
        if (opts.control_headers === true) {
          resp.on('header', function () {
            // Relax other middleware... I got this one
            ['ETag', 'Last-Modified'].forEach(function (header) {
              if (resp.getHeader(header)) resp.removeHeader(header);
              if (resp.getHeader(header)) resp.removeHeader(header);
            });
          });
        }
      }
    }
    next();
  };
};

/**
 * If filename is an absolute path (starts with a '/') The hash
 * will be pre-pended with be slashified.
 * Examples:
 * /foo.js                   -> /a998d8e98f/foo.js
 * foo.js                    -> a998d8e98f/foo.js
 * http://example.com/foo.js -> http://example.com/foo.js
 */
var hashify = function (filename, hash) {
  if (typeof filename !== 'string')
    throw "cachify ERROR, expected string for filename, got " + filename;
  if (filename.indexOf('://') !== -1) {
    return filename;
  }
  if (! hash && opts.global_hash) {
    hash = opts.global_hash;
  }

  if (opts.production !== true &&
      opts.debug === false) {
    return filename;
  }
  if (hash) {
    // No-op, specifing a hash skips all this craziness
  } else if (_cache[filename] && _cache[filename].hash) {
    hash = _cache[filename].hash;
    //console.info('cache hit ', filename);
  } else {
    //console.info('cache miss ', filename);
    var md5 = crypto.createHash('md5');
    try {
      var data = fs.readFileSync(path.join(opts.root, filename));
      md5.update(data);
      // Expensive, maintain in-memory cache
      if (! _cache[filename]) _cache[filename] = {exists: true};
      hash = _cache[filename].hash = md5.digest('hex').slice(0, 10);
    } catch (e) {
      // Not intersting to cache, programmer error?
      console.error('Cachify bailing on hash... no such file ' + filename );
      console.error(e);
      return filename;
    }
  }
  if (opts.prefix.indexOf('://') === -1 &&
      filename[0] === '/') {
    return format('/%s%s%s', opts.prefix, hash, filename);
  } else {
    return format('%s%s/%s', opts.prefix, hash, filename);
  }
};

var prod_or_dev_tags = function (filename, link_fmt, hash) {
  if (opts.production !== true &&
      _assets[filename]) {
        return und.map(_assets[filename], function (f) {
          return format(link_fmt, hashify(f, hash));
        }).join('\n');
  }
  return format(link_fmt, hashify(filename, hash));
};

exports.cachify_js = cachify_js = function (filename, options) {
  if (! options) options = {};
  return prod_or_dev_tags(filename,
                          '<script src="%s"></script>',
                          options['hash']);
};

exports.cachify_css = cachify_css = function (filename, options) {
  if (! options) options = {};
  return prod_or_dev_tags(filename,
                          '<link href="%s" rel="stylesheet" type="text/css">',
                          options['hash']);
};

exports.cachify = cachify = function (filename, options) {
  var tag_format;
  if (! options) options = {};
  if (options['tag_format'])
      tag_format = options['tag_format'];
  else
      tag_format = '%s';
  return prod_or_dev_tags(filename, tag_format, options['hash']);
};

var no_url = function (prefix) {
  if (prefix.indexOf('://') === -1) return prefix;
  var m = prefix.match(/^[a-z]{3,5}:\/\/[a-z0-9-_.]*(?:\:[0-9]*)?\/(.*)$/i);
  if (m) return m[1];
  else return prefix;
};

var escape_regex = function (str) {
  return str.replace('/', '\/');
};<|endoftext|>


<commit_before>'use strict';

var async = require('async');
var rarity = require('rarity');
var Anyfetch = require('anyfetch');

var util = require('../util.js');
var Token = require('../models/token.js');
var Childs = require('../Childs.js');

// This worker is used to manage a list of queues, it contain one task per user calling /update
module.exports = function usersQueueGenerator(server, config, workersFile, updateFile) {
  var log = require('../index.js').log;

  return function usersQueue(job, finalCb) {
    if(server.childs[job.data.anyfetchToken]) {
      return finalCb();
    }

    async.waterfall([
      function retrieveToken(cb) {
        Token.findOne({anyfetchToken: job.data.anyfetchToken}).exec(rarity.slice(2, cb));
      },
      function createQueue(token, cb) {
        if(!token || token.requireRefresh) {
          // Token was probably revoked or not valid anymore
          finalCb();
          return cb(null);
        }

        var isFirst = !token.cursor;
        var dateStartOfTasks = new Date();

        log.info({
          user: token.accountName,
        }, "Starting tasks");

        var jsonToken = token.toJSON();
        jsonToken.anyfetchApiUrl = job.data.anyfetchApiUrl;

        var anyfetchClient = new Anyfetch(job.data.anyfetchToken);
        anyfetchClient.setApiUrl(job.data.anyfetchApiUrl);

        var data = {
          updateFile: updateFile,
          workersFile: workersFile,
          config: config,
          token: jsonToken
        };

        var queue = server.yaqsClient.createQueue(token.accountName);

        // Start the childs, and add listeners
        var childs = new Childs(config.concurrency || 1, __dirname + '/../child-process.js', data);

        childs.on('stop', function(forced) {
          log.info({
            user: token.accountName
          }, "End of tasks");

          childs.removeAllListeners();

          if(forced) {
            return finalCb();
          }

          delete server.childs[token.anyfetchToken];
          queue.remove(function(err) {
            if(err) {
              return finalCb(err);
            }

            anyfetchClient.trackProviderUpdate({
              is_first: isFirst,
              time_spent_on_queue: dateStartOfTasks - token.lastUpdate,
              time_spent_on_tasks: new Date() - dateStartOfTasks,
              total_time_spent: new Date() - token.lastUpdate
            }, util.logError);

            // Unlock the token
            token.isUpdating = false;
            token.save(finalCb);
          });
        });

        childs.on('message', function(data) {
          if(data.type === 'event') {
            if(data.event === 'failed') {
              util.logError(data.err, data.job);
            }

            data.job.queue = queue;
            server.usersQueue.emit('job.' + data.job.data.type + '.' + data.event, data.job, data.err);
          }
          else if(data.type === 'refresh') {
            anyfetchClient.requireRefresh(function(err) {
              if(err) {
                util.logError(err, data.job);
              }

              childs.kill();
            });
          }
        });

        childs.start();

        childs.queue = queue;
        childs.anyfetchApiUrl = token.anyfetchApiUrl;

        server.childs[token.anyfetchToken] = childs;

        cb();
      }
    ], util.logError);
  };
};
<commit_msg>Change name of anyfetch.js method<commit_after>'use strict';

var async = require('async');
var rarity = require('rarity');
var Anyfetch = require('anyfetch');

var util = require('../util.js');
var Token = require('../models/token.js');
var Childs = require('../Childs.js');

// This worker is used to manage a list of queues, it contain one task per user calling /update
module.exports = function usersQueueGenerator(server, config, workersFile, updateFile) {
  var log = require('../index.js').log;

  return function usersQueue(job, finalCb) {
    if(server.childs[job.data.anyfetchToken]) {
      return finalCb();
    }

    async.waterfall([
      function retrieveToken(cb) {
        Token.findOne({anyfetchToken: job.data.anyfetchToken}).exec(rarity.slice(2, cb));
      },
      function createQueue(token, cb) {
        if(!token || token.requireRefresh) {
          // Token was probably revoked or not valid anymore
          finalCb();
          return cb(null);
        }

        var isFirst = !token.cursor;
        var dateStartOfTasks = new Date();

        log.info({
          user: token.accountName,
        }, "Starting tasks");

        var jsonToken = token.toJSON();
        jsonToken.anyfetchApiUrl = job.data.anyfetchApiUrl;

        var anyfetchClient = new Anyfetch(job.data.anyfetchToken);
        anyfetchClient.setApiUrl(job.data.anyfetchApiUrl);

        var data = {
          updateFile: updateFile,
          workersFile: workersFile,
          config: config,
          token: jsonToken
        };

        var queue = server.yaqsClient.createQueue(token.accountName);

        // Start the childs, and add listeners
        var childs = new Childs(config.concurrency || 1, __dirname + '/../child-process.js', data);

        childs.on('stop', function(forced) {
          log.info({
            user: token.accountName
          }, "End of tasks");

          childs.removeAllListeners();

          if(forced) {
            return finalCb();
          }

          delete server.childs[token.anyfetchToken];
          queue.remove(function(err) {
            if(err) {
              return finalCb(err);
            }

            anyfetchClient.trackProviderUpdate({
              is_first: isFirst,
              time_spent_on_queue: dateStartOfTasks - token.lastUpdate,
              time_spent_on_tasks: new Date() - dateStartOfTasks,
              total_time_spent: new Date() - token.lastUpdate
            }, util.logError);

            // Unlock the token
            token.isUpdating = false;
            token.save(finalCb);
          });
        });

        childs.on('message', function(data) {
          if(data.type === 'event') {
            if(data.event === 'failed') {
              util.logError(data.err, data.job);
            }

            data.job.queue = queue;
            server.usersQueue.emit('job.' + data.job.data.type + '.' + data.event, data.job, data.err);
          }
          else if(data.type === 'refresh') {
            anyfetchClient.tokenRefresh(function(err) {
              if(err) {
                util.logError(err, data.job);
              }

              childs.kill();
            });
          }
        });

        childs.start();

        childs.queue = queue;
        childs.anyfetchApiUrl = token.anyfetchApiUrl;

        server.childs[token.anyfetchToken] = childs;

        cb();
      }
    ], util.logError);
  };
};
<|endoftext|>


<commit_before>module.exports = function(config) {
  // find modules to exclude from compilation
  var reappIncludeModules = [
      'reapp-ui',
      'reapp-routes'
    ].concat(config.parseModules || []);

  var userModules = Object.keys(require(config.dir + '/package.json').dependencies);
  var excludeModules = userModules.filter(function(dep) {
    return reappIncludeModules.indexOf(dep) === -1;
  }).map(function(name) {
    return 'node_modules/' + name;
  });

  excludeModules = excludeModules.concat(
    config.excludeModules || [],
    'socket\\.io'
  );

  if (config.debug)
    console.log('Not running babel on modules...', excludeModules.join(', '), "\n");

  return new RegExp(excludeModules.join('|'))
}<commit_msg>fix component needs es6<commit_after>module.exports = function(config) {
  // find modules to exclude from compilation
  var reappIncludeModules = [
      'reapp-ui',
      'reapp-routes',
      'reapp-component'
    ].concat(config.parseModules || []);

  var userModules = Object.keys(require(config.dir + '/package.json').dependencies);
  var excludeModules = userModules.filter(function(dep) {
    return reappIncludeModules.indexOf(dep) === -1;
  }).map(function(name) {
    return 'node_modules/' + name;
  });

  excludeModules = excludeModules.concat(
    config.excludeModules || [],
    'socket\\.io'
  );

  if (config.debug)
    console.log('Not running babel on modules...', excludeModules.join(', '), "\n");

  return new RegExp(excludeModules.join('|'))
}<|endoftext|>