<commit_before>var jQuery = jQuery;

(function ($) {

    var
        showContentOnload = function (params) {
            var
                URLHash = location.hash,
                id;

            params.container.find("li").hide();

            if (params.selectTabOnload) {
                if (URLHash) {
                    id = URLHash;
                }
            }

            if (!id) {
                id = params.controller.parent().find("a.selected").attr("href");
            }

            params.container.find("li.do-ui-tabs-container-option" + id).show();

            // selected = container.find("li.#{tabAnchor.attr("class")}")
            // selected = container.find("li#{tabAnchor.attr("href")}")
            //  if selected.length == 0
            //    url = $(this).data("url")
            //    if url
            //      content = $("

").addClass tabAnchor.attr("class")
            //      container.append content

            //      format = $(this).data("format")
            //      if !format
            //        format = "js"

            //      $.get url, {format: format},
            //        (data, status, xhr)->
            //          if format == "html"
            //            content.html data
        },

        selectTab = function (handle, params) {
            var
                URLHash = location.hash,
                parent,
                items,
                tabSelected,
                contentSelected;

            if (handle instanceof jQuery.Event) {
                handle = $(handle.target);
            } else {
                if (handle instanceof jQuery) {
                    handle = $(handle);
                }
            }

            parent = handle.closest("ul");
            items = parent.find("li");

            tabSelected = items.find("a." + params.selectedTabClass);

            if (URLHash) {
                tabSelected = items.findAnchorWithoutHref();
                tabSelected.attr("href", URLHash);
            } else {
                contentSelected = $(params.container)
                    .find(params.container.find("li:visible"));
                tabSelected.attr("href", "#" + contentSelected.attr("id"));
            }

            items.find("a").removeClass(params.selectedTabClass);
            handle.addClass(params.selectedTabClass);
        },

        selectTabOnload = function (params) {
            var
                id;

            if (params.container) {
                id = params.container.find("li.do-ui-tabs-container-option:visible")
                    .attr("id");
            }

            params.controller.parent().findAnchorByHref("#"+id).removeAttr("href");
        },

        showContent = function (handle, params) {
            var
                id = $(handle.target).attr("href");

            params.container.find("li.do-ui-tabs-container-option").hide();
            params.container.find("li.do-ui-tabs-container-option" + id).show();
        };

    $.tabsController = function (params) {
        var
            anchor;

        if (params) {
            // creates anchor
            if (params.controller.prop("tagName") !== "A") {
                params.controller.each(function (i, o) {
                    anchor = $("");
                    $(o).append(anchor);
                    if ($(o).attr("id")) {
                        anchor.attr("href", $(o).attr("id"));
                    }
                    if ($(o).attr("class")) {
                        anchor.attr("class", $(o).attr("class"));
                    }
                });
            }

            if (params.container) {
                params.container.addClass("do-ui-tabs-container");
                params.container.find("li").addClass("do-ui-tabs-container-option");
                showContentOnload(params);
            }

            selectTabOnload(params);

            // if (params.selectTabOnload) {

            params.controller.click(function (e) {
                /* se via ajax, por exemplo
                /* aqui deverá vir a lógica de como carregar o conteúdo,
                */
                selectTab(e, params);
                showContent(e, params);
                location.hash = $(e.target).attr("href");
                $(e.target).removeAttr("href");
            });
            // }

        }

        // if (parent.find("ul.do-ui-tabs-container").length) {
        //     showContentOnload(jqObj, params);
        // }

        // jqObj.click(function (e) {
        //     /* se via ajax, por exemplo
        //     /* aqui deverá vir a lógica de como carregar o conteúdo,
        //     */
        //     showContent(e);
        // });
    };

}(jQuery));
<commit_msg>ajusta todos os bugs em abas<commit_after>var jQuery = jQuery;

(function ($) {

    var
        showContentOnload = function (params) {
            var
                URLHash = location.hash,
                id;

            params.container.find("li").hide();

            if (params.selectTabOnload) {
                if (URLHash) {
                    id = URLHash;
                }
            }

            if (!id) {
                id = params.controller.parent().find("a.selected").attr("href");
            }

            params.container.find("li.do-ui-tabs-container-option" + id).show();

            // selected = container.find("li.#{tabAnchor.attr("class")}")
            // selected = container.find("li#{tabAnchor.attr("href")}")
            //  if selected.length == 0
            //    url = $(this).data("url")
            //    if url
            //      content = $("

").addClass tabAnchor.attr("class")
            //      container.append content

            //      format = $(this).data("format")
            //      if !format
            //        format = "js"

            //      $.get url, {format: format},
            //        (data, status, xhr)->
            //          if format == "html"
            //            content.html data
        },

        selectTabOnload = function (params) {
            var
                href,
                URLHash = location.hash,
                tabSelected = params.controller.parent().find("a.selected");

            if (params.selectTabOnload) {
                if (URLHash) {
                    href = URLHash;
                }
                else if (tabSelected) {
                    href = tabSelected.attr("href");
                }
                else {
                    href = location.pathname.match(/[a-z\/_-]+[a-z]+/);
                }
            }
            else if (tabSelected) {
                href = tabSelected.attr("href")
            }

            params.controller.parent().findAnchorByHref(href).removeAttr("href");
        },

        showContent = function (handle, params) {
            var
                id = $(handle.target).attr("href");

            params.container.find("li.do-ui-tabs-container-option").hide();
            params.container.find("li.do-ui-tabs-container-option" + id).show();
        },

        selectTab = function (handle, params) {
            var
                URLHash = location.hash,
                parent,
                items,
                contentSelected,
                tabSelected,
                id;

            if (handle instanceof jQuery.Event) {
                handle = $(handle.target);
            } else {
                if (handle instanceof jQuery) {
                    handle = $(handle);
                }
            }

            parent = handle.closest("ul");
            items = parent.find("li");

            contentSelected = params.container
                .find("li.do-ui-tabs-container-option:visible");
            id = contentSelected.attr("id");

            tabSelected = params.controller.parent().findAnchorWithoutHref();
            tabSelected.attr("href", "#" + id);

            items.find("a").removeClass(params.selectedTabClass);
            handle.addClass(params.selectedTabClass);
        };

    $.tabsController = function (params) {
        var
            anchor;

        if (params) {
            // creates anchor
            if (params.controller.prop("tagName") !== "A") {
                params.controller.each(function (i, o) {
                    anchor = $("");
                    $(o).append(anchor);
                    if ($(o).attr("id")) {
                        anchor.attr("href", $(o).attr("id"));
                    }
                    if ($(o).attr("class")) {
                        anchor.attr("class", $(o).attr("class"));
                    }
                });
            }

            if (params.container) {
                params.container.addClass("do-ui-tabs-container");
                params.container.find("li").addClass("do-ui-tabs-container-option");
                showContentOnload(params);
            }
            selectTabOnload(params);

            params.controller.click(function (e) {
                /* se via ajax, por exemplo
                /* aqui deverá vir a lógica de como carregar o conteúdo,
                */
                selectTab(e, params);
                showContent(e, params);
                if (params.selectTabOnload) {
                    location.hash = $(e.target).attr("href");
                }
                $(e.target).removeAttr("href");
            });
        }
    };

}(jQuery));
<|endoftext|>


<commit_before>/**
 * Particles component for A-Frame.
 *
 * ShaderParticleEngine by Squarefeet (https://github.com/squarefeet).
 */

var THREE = AFRAME.THREE;
var SPE = require('./lib/SPE.js');

if (typeof AFRAME === 'undefined') {
  throw new Error('Component attempted to register before AFRAME was available.');
}

AFRAME.registerComponent('particle-system', {

    schema: {
        preset: {
            type: 'string',
            default: ''
        },
        maxAge: {
            type: 'number'
        },
        positionSpread: {
            type: 'vec3'
        },
        type: {
            type: 'number'
        },
        rotationAxis: {
            type: 'string'
        },
        rotationAngle: {
            type: 'number'
        },
        accelerationValue: {
            type: 'vec3'
        },
        accelerationSpread: {
            type: 'vec3'
        },
        velocityValue: {
            type: 'vec3'
        },
        velocitySpread: {
            type: 'vec3'
        },
        color: {
            type: 'string'
        },
        size: {
            type: 'number'
        },
        direction: {
            type: 'number'
        },
        duration: {
            type: 'number'
        },
        particleCount: {
            type: 'number'
        },
        texture: {
            type: 'string'
        },
        randomize: {
            type: 'boolean'
        },
        opacity: {
          type: 'number',
        },
        maxParticleCount: {
            type: 'number',
            default: 250000
        }
    },

    init: function() {

        this.presets = [];

        /* preset settings can be overwritten */

        this.presets['default'] = {
            maxAge: (this.data.maxAge!==0?this.data.maxAge:6),
            positionSpread: (this.data.positionSpread.x!==0&&this.data.positionSpread.y!==0&&this.data.positionSpread.z!==0?this.data.positionSpread:{x:0,y:0,z:0}),
            type: (this.data.type!==0?this.data.type:SPE.distributions.BOX), /* SPE.distributions.SPHERE, SPE.distributions.DISC */
            rotationAxis: (this.data.rotationAxis!==''?this.data.rotationAxis:'x'),
            rotationAngle: (this.data.rotationAngle!==0?this.data.rotationAngle:0),
            accelerationValue: (this.data.accelerationValue.x!==0&&this.data.accelerationValue.y!==0&&this.data.accelerationValue.z!==0?this.data.accelerationValue:{x: 0, y: -10, z: 0}),
            accelerationSpread: (this.data.accelerationSpread.x!==0&&this.data.accelerationSpread.y!==0&&this.data.accelerationSpread.z!==0?this.data.accelerationSpread:{x: 10, y: 0, z: 10}),
            velocityValue: (this.data.velocityValue.x!==0&&this.data.velocityValue.y!==0&&this.data.velocityValue.z!==0?this.data.velocityValue:{x: 0, y: 25, z: 0}),
            velocitySpread: (this.data.velocitySpread.x!==0&&this.data.velocitySpread.y!==0&&this.data.velocitySpread.z!==0?this.data.velocitySpread:{x: 10, y: 7.5, z: 10}),
            color: (this.data.color!==''?this.data.color:'#0000FF,#FF0000'),
            size: (this.data.size!==0?this.data.size:1),
            opacity: { value: (this.data.opacity!=0?this.data.opacity:1) },
            direction: (this.data.direction!==0?this.data.direction:1),
            duration: (this.data.duration!=null?this.data.duration:null),
            particleCount: (this.data.particleCount!==0?this.data.particleCount:1000),
            texture: (this.data.texture!==''?this.data.texture:'https://cdn.rawgit.com/IdeaSpaceVR/aframe-particle-system-component/master/dist/images/star2.png'),
            randomize: false
        };

        this.presets['dust'] = {
            maxAge: (this.data.maxAge!==0?this.data.maxAge:20),
            positionSpread: (this.data.positionSpread.x!==0&&this.data.positionSpread.y!==0&&this.data.positionSpread.z!==0?this.data.positionSpread:{x:100,y:100,z:100}),
            type: (this.data.type!==0?this.data.type:SPE.distributions.BOX), /* SPE.distributions.SPHERE, SPE.distributions.DISC */
            rotationAxis: (this.data.rotationAxis!==''?this.data.rotationAxis:'x'),
            rotationAngle: (this.data.rotationAngle!==0?this.data.rotationAngle:3.14),
            accelerationValue: (this.data.accelerationValue.x!==0&&this.data.accelerationValue.y!==0&&this.data.accelerationValue.z!==0?this.data.accelerationValue:{x: 0, y: 0, z: 0}),
            accelerationSpread: (this.data.accelerationSpread.x!==0&&this.data.accelerationSpread.y!==0&&this.data.accelerationSpread.z!==0?this.data.accelerationSpread:{x: 0, y: 0, z: 0}),
            velocityValue: (this.data.velocityValue.x!==0&&this.data.velocityValue.y!==0&&this.data.velocityValue.z!==0?this.data.velocityValue:{x: 1, y: 0.3, z: 1}),
            velocitySpread: (this.data.velocitySpread.x!==0&&this.data.velocitySpread.y!==0&&this.data.velocitySpread.z!==0?this.data.velocitySpread:{x: 0.5, y: 1, z: 0.5}),
            color: (this.data.color!==''?this.data.color:'#FFFFFF'),
            size: (this.data.size!==0?this.data.size:1),
            opacity: { value: (this.data.opacity!=0?this.data.opacity:1) },
            direction: (this.data.direction!==0?this.data.direction:1),
            duration: (this.data.duration!=null?this.data.duration:null),
            particleCount: (this.data.particleCount!==0?this.data.particleCount:100),
            texture: (this.data.texture!==''?this.data.texture:'https://cdn.rawgit.com/IdeaSpaceVR/aframe-particle-system-component/master/dist/images/smokeparticle.png'),
            randomize: false
        };

        this.presets['snow'] = {
            maxAge: (this.data.maxAge!==0?this.data.maxAge:20),
            positionSpread: (this.data.positionSpread.x!==0&&this.data.positionSpread.y!==0&&this.data.positionSpread.z!==0?this.data.positionSpread:{x:100,y:100,z:100}),
            type: (this.data.type!==0?this.data.type:SPE.distributions.BOX), /* SPE.distributions.SPHERE, SPE.distributions.DISC */
            rotationAxis: (this.data.rotationAxis!==''?this.data.rotationAxis:'x'),
            rotationAngle: (this.data.rotationAngle!==0?this.data.rotationAngle:3.14),
            accelerationValue: (this.data.accelerationValue.x!==0&&this.data.accelerationValue.y!==0&&this.data.accelerationValue.z!==0?this.data.accelerationValue:{x: 0, y: 0, z: 0}),
            accelerationSpread: (this.data.accelerationSpread.x!==0&&this.data.accelerationSpread.y!==0&&this.data.accelerationSpread.z!==0?this.data.accelerationSpread:{x: 0.2, y: 0, z: 0.2}),
            velocityValue: (this.data.velocityValue.x!==0&&this.data.velocityValue.y!==0&&this.data.velocityValue.z!==0?this.data.velocityValue:{x: 0, y: 8, z: 0}),
            velocitySpread: (this.data.velocitySpread.x!==0&&this.data.velocitySpread.y!==0&&this.data.velocitySpread.z!==0?this.data.velocitySpread:{x: 2, y: 0, z: 2}),
            color: (this.data.color!==''?this.data.color:'#FFFFFF'),
            size: (this.data.size!==0?this.data.size:1),
            opacity: { value: (this.data.opacity!=0?this.data.opacity:1) },
            direction: (this.data.direction!==0?this.data.direction:1),
            duration: (this.data.duration!=null?this.data.duration:null),
            particleCount: (this.data.particleCount!==0?this.data.particleCount:200),
            texture: (this.data.texture!==''?this.data.texture:'https://cdn.rawgit.com/IdeaSpaceVR/aframe-particle-system-component/master/dist/images/smokeparticle.png'),
            randomize: false
        };

        this.presets['rain'] = {
            maxAge: (this.data.maxAge!==0?this.data.maxAge:1),
            positionSpread: (this.data.positionSpread.x!==0&&this.data.positionSpread.y!==0&&this.data.positionSpread.z!==0?this.data.positionSpread:{x:100,y:100,z:100}),
            type: (this.data.type!==0?this.data.type:SPE.distributions.BOX), /* SPE.distributions.SPHERE, SPE.distributions.DISC */
            rotationAxis: (this.data.rotationAxis!==''?this.data.rotationAxis:'x'),
            rotationAngle: (this.data.rotationAngle!==0?this.data.rotationAngle:3.14),
            accelerationValue: (this.data.accelerationValue.x!==0&&this.data.accelerationValue.y!==0&&this.data.accelerationValue.z!==0?this.data.accelerationValue:{x: 0, y: 3, z: 0}),
            accelerationSpread: (this.data.accelerationSpread.x!==0&&this.data.accelerationSpread.y!==0&&this.data.accelerationSpread.z!==0?this.data.accelerationSpread:{x: 2, y: 1, z: 2}),
            velocityValue: (this.data.velocityValue.x!==0&&this.data.velocityValue.y!==0&&this.data.velocityValue.z!==0?this.data.velocityValue:{x: 0, y: 75, z: 0}),
            velocitySpread: (this.data.velocitySpread.x!==0&&this.data.velocitySpread.y!==0&&this.data.velocitySpread.z!==0?this.data.velocitySpread:{x: 10, y: 50, z: 10}),
            color: (this.data.color!==''?this.data.color:'#FFFFFF'),
            size: (this.data.size!==0?this.data.size:0.4),
            opacity: { value: (this.data.opacity!=0?this.data.opacity:1) },
            direction: (this.data.direction!==0?this.data.direction:1),
            duration: (this.data.duration!=null?this.data.duration:null),
            particleCount: (this.data.particleCount!==0?this.data.particleCount:1000),
            texture: (this.data.texture!==''?this.data.texture:'https://cdn.rawgit.com/IdeaSpaceVR/aframe-particle-system-component/master/dist/images/raindrop.png'),
            randomize: false
        };

    },

    update: function (oldData) {

        this.clock = new THREE.Clock();

        if (this.data.preset != '' && this.data.preset in this.presets) {

            this.initParticleSystem(this.presets[this.data.preset]);

        } else {

            this.initParticleSystem(this.presets['default']);
        }

    },

    tick: function(time) {

        this.particleGroup.tick(this.clock.getDelta());
    },

    remove: function() {},

    initParticleSystem: function(settings) {

        var loader = new THREE.TextureLoader();
        var particle_texture = loader.load(
            settings.texture,
            function (texture) {
                return texture;
            },
            function (xhr) {
              console.log((xhr.loaded / xhr.total * 100) + '% loaded');
            },
            function (xhr) {
              console.log('An error occurred');
            }
        );

        this.particleGroup = new SPE.Group({
            texture: {
                value: particle_texture
            },
            maxParticleCount: this.data.maxParticleCount
        });

        /* color */
        var color_arr = [];
        settings.color.split(',').forEach((function(c) {
            color_arr.push(new THREE.Color(this.hexToRgb(c).r, this.hexToRgb(c).g, this.hexToRgb(c).b));
        }).bind(this));

        var emitter = new SPE.Emitter({
            maxAge: {
                value: settings.maxAge
            },
            type: {
                value: settings.type
            },
            position: {
                value: this.el.object3D.position,
                spread: new THREE.Vector3(settings.positionSpread.x, settings.positionSpread.y, settings.positionSpread.z),
                randomize: settings.randomize
                //spreadClamp: new THREE.Vector3( 2, 2, 2 ),
                //radius: 4
            },
            rotation: {
                axis: (settings.rotationAxis=='x'?new THREE.Vector3(1, 0, 0):(settings.rotationAxis=='y'?new THREE.Vector3(0, 1, 0):(settings.rotationAxis=='z'?new THREE.Vector3(0, 0, 1):new THREE.Vector3(0, 1, 0)))),
                angle: settings.rotationAngle,
                static: true
            },
            acceleration: {
                value: new THREE.Vector3(settings.accelerationValue.x, settings.accelerationValue.y, settings.accelerationValue.z),
                spread: new THREE.Vector3(settings.accelerationSpread.x, settings.accelerationSpread.y, settings.accelerationSpread.z)
            },
            velocity: {
                value: new THREE.Vector3(settings.velocityValue.x, settings.velocityValue.y, settings.velocityValue.z),
                spread: new THREE.Vector3(settings.velocitySpread.x, settings.velocitySpread.y, settings.velocitySpread.z)
            },
            color: {
                value: color_arr
            },
            size: {
                value: settings.size
            },
            /*wiggle: { value: 4, spread: 2 }, //settings.wiggle,*/
            /*drag: {
                value: settings.drag
            },*/
            direction: {
                value: settings.direction
            },
            duration: {
                value: settings.duration
            },
            opacity: settings.opacity,
            particleCount: settings.particleCount
        });

        this.particleGroup.addEmitter(emitter);
        this.el.sceneEl.object3D.add(this.particleGroup.mesh);
    },

    hexToRgb: function(hex) {

        var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? {
            r: parseInt(result[1], 16),
            g: parseInt(result[2], 16),
            b: parseInt(result[3], 16)
        } : null;

    }

});

<commit_msg>fixed<commit_after>/**
 * Particles component for A-Frame.
 *
 * ShaderParticleEngine by Squarefeet (https://github.com/squarefeet).
 */

var SPE = require('./lib/SPE.js');

if (typeof AFRAME === 'undefined') {
  throw new Error('Component attempted to register before AFRAME was available.');
}

AFRAME.registerComponent('particle-system', {

    schema: {
        preset: {
            type: 'string',
            default: ''
        },
        maxAge: {
            type: 'number'
        },
        positionSpread: {
            type: 'vec3'
        },
        type: {
            type: 'number'
        },
        rotationAxis: {
            type: 'string'
        },
        rotationAngle: {
            type: 'number'
        },
        accelerationValue: {
            type: 'vec3'
        },
        accelerationSpread: {
            type: 'vec3'
        },
        velocityValue: {
            type: 'vec3'
        },
        velocitySpread: {
            type: 'vec3'
        },
        color: {
            type: 'string'
        },
        size: {
            type: 'number'
        },
        direction: {
            type: 'number'
        },
        duration: {
            type: 'number'
        },
        particleCount: {
            type: 'number'
        },
        texture: {
            type: 'string'
        },
        randomize: {
            type: 'boolean'
        },
        opacity: {
          type: 'number',
        },
        maxParticleCount: {
            type: 'number',
            default: 250000
        }
    },

    init: function() {

        this.presets = [];

        /* preset settings can be overwritten */

        this.presets['default'] = {
            maxAge: (this.data.maxAge!==0?this.data.maxAge:6),
            positionSpread: (this.data.positionSpread.x!==0&&this.data.positionSpread.y!==0&&this.data.positionSpread.z!==0?this.data.positionSpread:{x:0,y:0,z:0}),
            type: (this.data.type!==0?this.data.type:SPE.distributions.BOX), /* SPE.distributions.SPHERE, SPE.distributions.DISC */
            rotationAxis: (this.data.rotationAxis!==''?this.data.rotationAxis:'x'),
            rotationAngle: (this.data.rotationAngle!==0?this.data.rotationAngle:0),
            accelerationValue: (this.data.accelerationValue.x!==0&&this.data.accelerationValue.y!==0&&this.data.accelerationValue.z!==0?this.data.accelerationValue:{x: 0, y: -10, z: 0}),
            accelerationSpread: (this.data.accelerationSpread.x!==0&&this.data.accelerationSpread.y!==0&&this.data.accelerationSpread.z!==0?this.data.accelerationSpread:{x: 10, y: 0, z: 10}),
            velocityValue: (this.data.velocityValue.x!==0&&this.data.velocityValue.y!==0&&this.data.velocityValue.z!==0?this.data.velocityValue:{x: 0, y: 25, z: 0}),
            velocitySpread: (this.data.velocitySpread.x!==0&&this.data.velocitySpread.y!==0&&this.data.velocitySpread.z!==0?this.data.velocitySpread:{x: 10, y: 7.5, z: 10}),
            color: (this.data.color!==''?this.data.color:'#0000FF,#FF0000'),
            size: (this.data.size!==0?this.data.size:1),
            opacity: { value: (this.data.opacity!=0?this.data.opacity:1) },
            direction: (this.data.direction!==0?this.data.direction:1),
            duration: (this.data.duration!=null?this.data.duration:null),
            particleCount: (this.data.particleCount!==0?this.data.particleCount:1000),
            texture: (this.data.texture!==''?this.data.texture:'https://cdn.rawgit.com/IdeaSpaceVR/aframe-particle-system-component/master/dist/images/star2.png'),
            randomize: false
        };

        this.presets['dust'] = {
            maxAge: (this.data.maxAge!==0?this.data.maxAge:20),
            positionSpread: (this.data.positionSpread.x!==0&&this.data.positionSpread.y!==0&&this.data.positionSpread.z!==0?this.data.positionSpread:{x:100,y:100,z:100}),
            type: (this.data.type!==0?this.data.type:SPE.distributions.BOX), /* SPE.distributions.SPHERE, SPE.distributions.DISC */
            rotationAxis: (this.data.rotationAxis!==''?this.data.rotationAxis:'x'),
            rotationAngle: (this.data.rotationAngle!==0?this.data.rotationAngle:3.14),
            accelerationValue: (this.data.accelerationValue.x!==0&&this.data.accelerationValue.y!==0&&this.data.accelerationValue.z!==0?this.data.accelerationValue:{x: 0, y: 0, z: 0}),
            accelerationSpread: (this.data.accelerationSpread.x!==0&&this.data.accelerationSpread.y!==0&&this.data.accelerationSpread.z!==0?this.data.accelerationSpread:{x: 0, y: 0, z: 0}),
            velocityValue: (this.data.velocityValue.x!==0&&this.data.velocityValue.y!==0&&this.data.velocityValue.z!==0?this.data.velocityValue:{x: 1, y: 0.3, z: 1}),
            velocitySpread: (this.data.velocitySpread.x!==0&&this.data.velocitySpread.y!==0&&this.data.velocitySpread.z!==0?this.data.velocitySpread:{x: 0.5, y: 1, z: 0.5}),
            color: (this.data.color!==''?this.data.color:'#FFFFFF'),
            size: (this.data.size!==0?this.data.size:1),
            opacity: { value: (this.data.opacity!=0?this.data.opacity:1) },
            direction: (this.data.direction!==0?this.data.direction:1),
            duration: (this.data.duration!=null?this.data.duration:null),
            particleCount: (this.data.particleCount!==0?this.data.particleCount:100),
            texture: (this.data.texture!==''?this.data.texture:'https://cdn.rawgit.com/IdeaSpaceVR/aframe-particle-system-component/master/dist/images/smokeparticle.png'),
            randomize: false
        };

        this.presets['snow'] = {
            maxAge: (this.data.maxAge!==0?this.data.maxAge:20),
            positionSpread: (this.data.positionSpread.x!==0&&this.data.positionSpread.y!==0&&this.data.positionSpread.z!==0?this.data.positionSpread:{x:100,y:100,z:100}),
            type: (this.data.type!==0?this.data.type:SPE.distributions.BOX), /* SPE.distributions.SPHERE, SPE.distributions.DISC */
            rotationAxis: (this.data.rotationAxis!==''?this.data.rotationAxis:'x'),
            rotationAngle: (this.data.rotationAngle!==0?this.data.rotationAngle:3.14),
            accelerationValue: (this.data.accelerationValue.x!==0&&this.data.accelerationValue.y!==0&&this.data.accelerationValue.z!==0?this.data.accelerationValue:{x: 0, y: 0, z: 0}),
            accelerationSpread: (this.data.accelerationSpread.x!==0&&this.data.accelerationSpread.y!==0&&this.data.accelerationSpread.z!==0?this.data.accelerationSpread:{x: 0.2, y: 0, z: 0.2}),
            velocityValue: (this.data.velocityValue.x!==0&&this.data.velocityValue.y!==0&&this.data.velocityValue.z!==0?this.data.velocityValue:{x: 0, y: 8, z: 0}),
            velocitySpread: (this.data.velocitySpread.x!==0&&this.data.velocitySpread.y!==0&&this.data.velocitySpread.z!==0?this.data.velocitySpread:{x: 2, y: 0, z: 2}),
            color: (this.data.color!==''?this.data.color:'#FFFFFF'),
            size: (this.data.size!==0?this.data.size:1),
            opacity: { value: (this.data.opacity!=0?this.data.opacity:1) },
            direction: (this.data.direction!==0?this.data.direction:1),
            duration: (this.data.duration!=null?this.data.duration:null),
            particleCount: (this.data.particleCount!==0?this.data.particleCount:200),
            texture: (this.data.texture!==''?this.data.texture:'https://cdn.rawgit.com/IdeaSpaceVR/aframe-particle-system-component/master/dist/images/smokeparticle.png'),
            randomize: false
        };

        this.presets['rain'] = {
            maxAge: (this.data.maxAge!==0?this.data.maxAge:1),
            positionSpread: (this.data.positionSpread.x!==0&&this.data.positionSpread.y!==0&&this.data.positionSpread.z!==0?this.data.positionSpread:{x:100,y:100,z:100}),
            type: (this.data.type!==0?this.data.type:SPE.distributions.BOX), /* SPE.distributions.SPHERE, SPE.distributions.DISC */
            rotationAxis: (this.data.rotationAxis!==''?this.data.rotationAxis:'x'),
            rotationAngle: (this.data.rotationAngle!==0?this.data.rotationAngle:3.14),
            accelerationValue: (this.data.accelerationValue.x!==0&&this.data.accelerationValue.y!==0&&this.data.accelerationValue.z!==0?this.data.accelerationValue:{x: 0, y: 3, z: 0}),
            accelerationSpread: (this.data.accelerationSpread.x!==0&&this.data.accelerationSpread.y!==0&&this.data.accelerationSpread.z!==0?this.data.accelerationSpread:{x: 2, y: 1, z: 2}),
            velocityValue: (this.data.velocityValue.x!==0&&this.data.velocityValue.y!==0&&this.data.velocityValue.z!==0?this.data.velocityValue:{x: 0, y: 75, z: 0}),
            velocitySpread: (this.data.velocitySpread.x!==0&&this.data.velocitySpread.y!==0&&this.data.velocitySpread.z!==0?this.data.velocitySpread:{x: 10, y: 50, z: 10}),
            color: (this.data.color!==''?this.data.color:'#FFFFFF'),
            size: (this.data.size!==0?this.data.size:0.4),
            opacity: { value: (this.data.opacity!=0?this.data.opacity:1) },
            direction: (this.data.direction!==0?this.data.direction:1),
            duration: (this.data.duration!=null?this.data.duration:null),
            particleCount: (this.data.particleCount!==0?this.data.particleCount:1000),
            texture: (this.data.texture!==''?this.data.texture:'https://cdn.rawgit.com/IdeaSpaceVR/aframe-particle-system-component/master/dist/images/raindrop.png'),
            randomize: false
        };

    },

    update: function (oldData) {

        this.clock = new THREE.Clock();

        if (this.data.preset != '' && this.data.preset in this.presets) {

            this.initParticleSystem(this.presets[this.data.preset]);

        } else {

            this.initParticleSystem(this.presets['default']);
        }

    },

    tick: function(time) {

        this.particleGroup.tick(this.clock.getDelta());
    },

    remove: function() {},

    initParticleSystem: function(settings) {

        var loader = new THREE.TextureLoader();
        var particle_texture = loader.load(
            settings.texture,
            function (texture) {
                return texture;
            },
            function (xhr) {
              console.log((xhr.loaded / xhr.total * 100) + '% loaded');
            },
            function (xhr) {
              console.log('An error occurred');
            }
        );

        this.particleGroup = new SPE.Group({
            texture: {
                value: particle_texture
            },
            maxParticleCount: this.data.maxParticleCount
        });

        /* color */
        var color_arr = [];
        settings.color.split(',').forEach((function(c) {
            color_arr.push(new THREE.Color(this.hexToRgb(c).r, this.hexToRgb(c).g, this.hexToRgb(c).b));
        }).bind(this));

        var emitter = new SPE.Emitter({
            maxAge: {
                value: settings.maxAge
            },
            type: {
                value: settings.type
            },
            position: {
                value: this.el.object3D.position,
                spread: new THREE.Vector3(settings.positionSpread.x, settings.positionSpread.y, settings.positionSpread.z),
                randomize: settings.randomize
                //spreadClamp: new THREE.Vector3( 2, 2, 2 ),
                //radius: 4
            },
            rotation: {
                axis: (settings.rotationAxis=='x'?new THREE.Vector3(1, 0, 0):(settings.rotationAxis=='y'?new THREE.Vector3(0, 1, 0):(settings.rotationAxis=='z'?new THREE.Vector3(0, 0, 1):new THREE.Vector3(0, 1, 0)))),
                angle: settings.rotationAngle,
                static: true
            },
            acceleration: {
                value: new THREE.Vector3(settings.accelerationValue.x, settings.accelerationValue.y, settings.accelerationValue.z),
                spread: new THREE.Vector3(settings.accelerationSpread.x, settings.accelerationSpread.y, settings.accelerationSpread.z)
            },
            velocity: {
                value: new THREE.Vector3(settings.velocityValue.x, settings.velocityValue.y, settings.velocityValue.z),
                spread: new THREE.Vector3(settings.velocitySpread.x, settings.velocitySpread.y, settings.velocitySpread.z)
            },
            color: {
                value: color_arr
            },
            size: {
                value: settings.size
            },
            /*wiggle: { value: 4, spread: 2 }, //settings.wiggle,*/
            /*drag: {
                value: settings.drag
            },*/
            direction: {
                value: settings.direction
            },
            duration: {
                value: settings.duration
            },
            opacity: settings.opacity,
            particleCount: settings.particleCount
        });

        this.particleGroup.addEmitter(emitter);
        this.el.sceneEl.object3D.add(this.particleGroup.mesh);
    },

    hexToRgb: function(hex) {

        var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? {
            r: parseInt(result[1], 16),
            g: parseInt(result[2], 16),
            b: parseInt(result[3], 16)
        } : null;

    }

});

<|endoftext|>


<commit_before>/**
 * Koowa Framework - http://developer.joomlatools.com/koowa
 *
 * @copyright	Copyright (C) 2007 - 2013 Johan Janssens and Timble CVBA. (http://www.timble.net)
 * @license		GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link		http://github.com/joomlatools/koowa for the canonical source repository
 */

/**
 * Koowa global namespace
 *
 * @author      Johan Janssens <johan@nooku.org>
 * @category    Nooku
 * @package     Nooku_Media
 * @subpackage  Javascript
 */
if(!Koowa) {
    var Koowa = {};
}

(function($){

$(document).ready(function() {
    $('.submitable').on('click', function(event){
        var target = $(event.target);

        event.preventDefault();

        new Koowa.Form($.parseJSON(target.attr('rel'))).submit();
    });

    $('.-koowa-grid').each(function(i, grid) { // mootools
        var toolbar;

        grid = document.id(grid);
        toolbar = grid.get('data-toolbar') || '.toolbar-list';

        new Koowa.Grid(grid);

        new Koowa.Controller.Grid({form: grid, toolbar: document.getElement(toolbar)});
    });

    $('.-koowa-form').each(function(i, form) { // mootools
        var toolbar;

        form = document.id(form);
        toolbar = form.get('data-toolbar') || '.toolbar-list';

        new Koowa.Controller.Form({form: form, toolbar: document.getElement(toolbar)});
    });
});

/**
 * Creates a 'virtual form'
 *
 * @param   json    Configuration:  method, url, params, formelem
 * @example new KForm({method:'post', url:'foo=bar&id=1', params:{field1:'val1', field2...}}).submit();
 */
Koowa.Form = new Class({

    initialize: function(config) {
        this.config = config;
        if(this.config.element) {
            this.form = $(document[this.config.element]);
        }
        else {
            this.form = $('<form/>', {
                name: 'dynamicform',
                method: this.config.method,
                action: this.config.url
            });
            $(document.body).append(this.form);
        }
    },
    addField: function(name, value) {
        var elem = $('<input/>', {
            name: name,
            value: value,
            type: 'hidden'
        });
        elem.appendTo(this.form);

        return this;
    },

    submit: function() {
        $.each(this.config.params, function(name, value){
            this.addField(name, value);
        }.bind(this));

        this.form.submit();
    }
});

/**
 * Grid class
 *
 * @package     Koowa_Media
 * @subpackage  Javascript
 */
Koowa.Grid = new Class({
    initialize: function(element){
        var self = this;

        this.element    = $(element);
        this.form       = this.element.is('form') ? this.element : this.element.closest('form');
        this.toggles    = this.element.find('.-koowa-grid-checkall');
        this.checkboxes = this.element.find('.-koowa-grid-checkbox').filter(function(i, checkbox) {
            return !$(checkbox).prop('disabled');
        });

        if(!this.checkboxes.length) {
            this.toggles.prop('disabled', true);
        }

        this.toggles.on('change', function(event, ignore){
            if(!ignore) {
                self.checkAll($(this).prop('checked'));
            }
        });

        this.checkboxes.on('change', function(event, ignore){
            if(!ignore) {
                self.uncheckAll();
            }
        });
    },
    checkAll: function(value){
        var changed = this.checkboxes.filter(function(i, checkbox){
            return $(checkbox).prop('checked') !== value;
        });

        this.checkboxes.prop('checked', value);
        changed.trigger('change', true);
    },

    uncheckAll: function(){
        var total = this.checkboxes.filter(function(i, checkbox){
            return $(checkbox).prop('checked') !== false;
        }).length;

        this.toggles.prop('checked', this.checkboxes.length === total);
        this.toggles.trigger('change', true);
    }
});

/**
 * Find all selected checkboxes' ids in the grid
 *
 * @param   {string|object|null} context   A DOM Element, Document, or jQuery to use as context
 * @return  array           The items' ids
 */
Koowa.Grid.getAllSelected = function(context) {
    return $('.-koowa-grid-checkbox:checked', context);
};

/**
 * Get a query string for selected checkboxes
 *
 * @param   {string|object|null} context   A DOM Element, Document, or jQuery to use as context
 * @return  array           The items' ids
 */
Koowa.Grid.getIdQuery = function(context) {
    // We could do $.param(this.getAllSelected(scope)) but this way is faster since we iterate once not twice
    return this.getAllSelected(context).serialize();
};

/**
 * Controller class, execute actions complete with command chains
 *
 * @package     Koowa_Media
 * @subpackage  Javascript
 */
Koowa.Controller = new Class({

    Implements: [Options, Events],

    form: null,
    toolbar: null,
    buttons: null,

    token_name: null,
    token_value: null,

    options: {
        toolbar: false,
        url: window.location.href
    },

    initialize: function(options){
        var self = this;

        this.setOptions(options);

        this.form = $(this.options.form);
        this.toolbar = $(this.options.toolbar);

        this.form.data('controller', this);

        if (this.form.attr('action') && !this.options.url) {
            this.options.url = this.form.attr('action');
        }

        //Set options that is coming from data attributes on the form element
        this.setOptions(this.form.data());

        this.form.data('controller', this);

        // TODO does this work?
        //this.addEvent('execute', this.execute.bind(this));

        //Attach toolbar buttons actions
        if(this.toolbar) {
            this.buttons = this.toolbar.find('.toolbar').filter(function(){
                return $(this).data('action');
            });

            this.token_name = this.form.data('token-name');
            this.token_value = this.form.data('token-value');

            this.buttons.each(function() {
                var button = $(this),
                    data = button.data('data'),
                    options = button.data(),
                    action = button.data('action');

                data = (data && $.type(data) === 'string') ? $.parseJSON(data) : {};

                //Set token data
                if (self.token_name) {
                    data[self.token_name] = self.token_value;
                }

                button.on('click', function(event){
                    event.preventDefault();

                    if(!button.hasClass('disabled')) {
                        self.setOptions(options);
                        self.fireEvent('execute', [action, data, button.data('novalidate') === 'novalidate']);
                    }
                });
            });
        }
    },

    execute: function(event, action, data, novalidate){
        var method = '_action' + action[0].toUpperCase() + action.substr(1);

        this.options.action = action;
        if(this.fireEvent('before.'+action, [data, novalidate])) {
            if(this[method]) {
                this[method].call(this, data, novalidate);
            } else {
                this._action_default.call(this, action, data, novalidate);
            }
            this.fireEvent('after.'+action, [data, novalidate]);
        }

        return this;
    },

    /* @TODO refactor to use jQuery.fn.on, but keep addEvent for legacy */
    addEvent: function(type, fn){
        // @TODO test if this.form.on(type, fn) works just as good as this code
        return this.form.on.apply(this.form, [type, fn]);
    },

    /* @TODO refactor to use jQuery.fn.on, but keep addEvent for legacy */
    removeEvent: function(type, fn){
        // @TODO test if this.form.on(type, fn) works just as good as this code
        return this.form.off.apply(this.form, [type, fn]);
    },

    fireEvent: function(type, args){
        var event = jQuery.Event(type);
        this.form.trigger(event, args);
        return !event.isDefaultPrevented();
    },

    checkValidity: function(){
        var buttons;

        if (this.buttons) {
            this.fireEvent('before.validate');

            buttons = this.buttons.filter(function(){
                return $(this).data('novalidate') !== 'novalidate';
            });

            if (this.fireEvent('validate')) {
                buttons.removeClass('disabled');
            } else {
                buttons.addClass('disabled');
            }

            this.fireEvent('after.validate');
        }
    }
});

/**
 * Controller class specialized for grids, extends Koowa.Controller
 *
 * @package     Koowa_Media
 * @subpackage  Javascript
 */
Koowa.Controller.Grid = new Class({

    Extends: Koowa.Controller,

    options: {
        inputs: '.-koowa-grid-checkbox, .-koowa-grid-checkall'
    },
    initialize: function(options){
        var thead, checkboxes,
            self = this;

        this.parent(options);

        this.addEvent('validate', this.validate);

        if (this.options.inputs && this.buttons) {
            this.checkValidity();
            this.form.find(this.options.inputs).on('change', function(event, ignore){
                if (!ignore) {
                    this.checkValidity();
                }
            }.bind(this));
        }

        this.token_name = this.form.data('token-name');
        this.token_value = this.form.data('token-value');

        this.setTableHeaders();
        this.setTableRows();

        //<select> elements in headers and footers are for filters, so they need to submit the form on change
        this.form.find('thead select, tfoot select').on('change', function(){
            self.form.submit();
        });

    },

    setTableHeaders: function() {
        //Make the table headers "clickable"
        this.form.find('thead tr > *').each(function() {
            var element = $(this),
                link = element.find('a'),
                checkall = element.find('.-koowa-grid-checkall');

            if (link.length) {
                element.on('click', function(event){
                    //Don't do anything if the event target is the same as the element
                    if($(event.target)[0] != element[0]) {
                        return;
                    }

                    //Run this check on click, so that progressive enhancements isn't bulldozed
                    if(link.prop('href')) {
                        window.location.href = link.prop('href');
                    } else {
                        link.trigger('click', event);
                    }
                });

                if(link.hasClass('-koowa-asc')) {
                    element.addClass('-koowa-asc');
                } else if(link.hasClass('-koowa-desc')) {
                    element.addClass('-koowa-desc');
                }

                return this;
            } else if(checkall.length) {
                //Making the <td> or <th> element that's the parent of a checkall checkbox toggle the checkbox when clicked
                element.on('click', function(event){
                    //Don't do anything if the event target is the same as the element
                    if($(event.target)[0] != element[0]) {
                        return true;
                    }

                    //Checkall uses change for other purposes
                    checkall.prop('checked', checkall.is(':checked') ? false : true).trigger('change');
                });
            }

            element.addClass('void');
        });
    },
    setTableRows: function() {
        var checkboxes = this.form.find('tbody tr .-koowa-grid-checkbox');

        this.form.find('tbody tr').each(function(){
            var tr = $(this),
                checkbox = tr.find('.-koowa-grid-checkbox');

            if(tr.data('readonly') == true || !checkbox.length) {
                return;
            }

            // Trigger checkbox when the user clicks anywhere in the row
            tr.on('click', function(event){
                if($(event.target).is('[type=checkbox]')) {
                    return;
                }

                checkbox.prop('checked', !checkbox.prop('checked')).trigger('change');
            });

            // Checkbox should add selected and selected-multiple classes to the row
            checkbox.on('change', function(){
                var selected,
                    parent = tr.parent();

                $(this).prop('checked') ? tr.addClass('selected') : tr.removeClass('selected');

                selected = tr.hasClass('selected') + tr.siblings('.selected').length;

                if(selected > 1) {
                    parent.addClass('selected-multiple').removeClass('selected-single')
                } else {
                    parent.removeClass('selected-multiple').addClass('selected-single');
                }
            }.bind(checkbox)).trigger('change', true);

            // Set up buttons such as publish/unpublish triggers
            tr.find('[data-action]').each(function() {
                var action = $(this),
                    data = action.data('data'),
                    options = action.data(),
                    actionName = action.data('action'),
                    eventType = action.data('event-type');

                data = (data && $.type(data) === 'string') ? $.parseJSON(data) : {};

                //Set token data
                if(self.token_name) {
                    data[self.token_name] = self.token_value;
                }

                if(!eventType) {
                    eventType = action.is('[type="radio"],[type="checkbox"],select') ? 'change' : 'click';
                }

                action.on(eventType, function(){
                    checkboxes.prop('checked', '');
                    checkbox.prop('checked', 'checked');
                    checkboxes.trigger('change', true);

                    self.setOptions(options);
                    self.fireEvent('execute', [actionName, data, true]);
                });
            });
        });
    },
    validate: function(){
        return Koowa.Grid.getIdQuery() || false;
    },

    _action_default: function(action, data, novalidate){
        var idQuery, append, options;

        if(!novalidate && !this.fireEvent('validate')) {
            return false;
        }

        idQuery = Koowa.Grid.getIdQuery();
        append = this.options.url.match(/\?/) ? '&' : '?'; // mootools?
        options = {
            method:'post',
            url: this.options.url+(idQuery ? append+idQuery : ''),
            params: $.extend({}, {action: action}, data)
        };
        new Koowa.Form(options).submit();
    }
});

/**
 * Controller class specialized for forms, extends Koowa.Controller
 *
 * @package     Koowa_Media
 * @subpackage  Javascript
 */
Koowa.Controller.Form = new Class({

    Extends: Koowa.Controller,

    _action_default: function(action, data, novalidate){
        if(!novalidate && !this.fireEvent('validate')) {
            return false;
        }

        this.form.append($('<input/>', {name: 'action', type: 'hidden', value: action}));
        this.form.submit();
    }

});

})(jQuery);<commit_msg>re #28: Second go at Koowa.Controller<commit_after>/**
 * Koowa Framework - http://developer.joomlatools.com/koowa
 *
 * @copyright	Copyright (C) 2007 - 2013 Johan Janssens and Timble CVBA. (http://www.timble.net)
 * @license		GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link		http://github.com/joomlatools/koowa for the canonical source repository
 */

/**
 * Koowa global namespace
 *
 * @author      Johan Janssens <johan@nooku.org>
 * @category    Nooku
 * @package     Nooku_Media
 * @subpackage  Javascript
 */
if(!Koowa) {
    var Koowa = {};
}

(function($){

$(document).ready(function() {
    $('.submitable').on('click', function(event){
        var target = $(event.target);

        event.preventDefault();

        new Koowa.Form($.parseJSON(target.attr('rel'))).submit();
    });

    $('.-koowa-grid').each(function() {
        new Koowa.Controller.Grid({
            form: this
        });
    });

    $('.-koowa-form').each(function() {
        new Koowa.Controller.Form({
            form: this
        });
    });
});

/**
 * Creates a 'virtual form'
 *
 * @param   json    Configuration:  method, url, params, formelem
 * @example new KForm({method:'post', url:'foo=bar&id=1', params:{field1:'val1', field2...}}).submit();
 */
Koowa.Form = new Class({

    initialize: function(config) {
        this.config = config;
        if(this.config.element) {
            this.form = $(document[this.config.element]);
        }
        else {
            this.form = $('<form/>', {
                name: 'dynamicform',
                method: this.config.method,
                action: this.config.url
            });
            $(document.body).append(this.form);
        }
    },
    addField: function(name, value) {
        var elem = $('<input/>', {
            name: name,
            value: value,
            type: 'hidden'
        });
        elem.appendTo(this.form);

        return this;
    },

    submit: function() {
        $.each(this.config.params, function(name, value){
            this.addField(name, value);
        }.bind(this));

        this.form.submit();
    }
});

/**
 * Grid class
 *
 * @package     Koowa_Media
 * @subpackage  Javascript
 */
Koowa.Grid = new Class({
    initialize: function(element){
        var self = this;

        this.element    = $(element);
        this.form       = this.element.is('form') ? this.element : this.element.closest('form');
        this.toggles    = this.element.find('.-koowa-grid-checkall');
        this.checkboxes = this.element.find('.-koowa-grid-checkbox').filter(function(i, checkbox) {
            return !$(checkbox).prop('disabled');
        });

        if(!this.checkboxes.length) {
            this.toggles.prop('disabled', true);
        }

        this.toggles.on('change', function(event, ignore){
            if(!ignore) {
                self.checkAll($(this).prop('checked'));
            }
        });

        this.checkboxes.on('change', function(event, ignore){
            if(!ignore) {
                self.uncheckAll();
            }
        });
    },
    checkAll: function(value){
        var changed = this.checkboxes.filter(function(i, checkbox){
            return $(checkbox).prop('checked') !== value;
        });

        this.checkboxes.prop('checked', value);
        changed.trigger('change', true);
    },

    uncheckAll: function(){
        var total = this.checkboxes.filter(function(i, checkbox){
            return $(checkbox).prop('checked') !== false;
        }).length;

        this.toggles.prop('checked', this.checkboxes.length === total);
        this.toggles.trigger('change', true);
    }
});

/**
 * Find all selected checkboxes' ids in the grid
 *
 * @param   {string|object|null} context   A DOM Element, Document, or jQuery to use as context
 * @return  array           The items' ids
 */
Koowa.Grid.getAllSelected = function(context) {
    return $('.-koowa-grid-checkbox:checked', context);
};

/**
 * Get a query string for selected checkboxes
 *
 * @param   {string|object|null} context   A DOM Element, Document, or jQuery to use as context
 * @return  array           The items' ids
 */
Koowa.Grid.getIdQuery = function(context) {
    return decodeURIComponent(this.getAllSelected(context).serialize());
};

/**
 * Controller class, execute actions complete with command chains
 *
 * @package     Koowa_Media
 * @subpackage  Javascript
 */
Koowa.Controller = new Class({

    Implements: [Options, Events],

    form: null,
    toolbar: null,
    buttons: null,

    token_name: null,
    token_value: null,

    options: {
        toolbar: '.toolbar-list',
        url: window.location.href
    },

    initialize: function(options){
        this.setOptions(options);

        this.form = $(this.options.form);

        this.setOptions(this.form.data());

        if (this.form.attr('action')) {
            this.options.url = this.form.attr('action');
        }

        this.toolbar = $(this.options.toolbar);
        this.form.data('controller', this);

        this.addEvent('execute', this.execute.bind(this));

        this.token_name = this.form.data('token-name');
        this.token_value = this.form.data('token-value');

        if(this.toolbar) {
            this.setToolbar();
        }
    },
    setToolbar: function() {
        var self = this;

        this.buttons = this.toolbar.find('.toolbar[data-action]');

        this.buttons.each(function() {
            var button = $(this),
                options = button.data(),
                data = options.data,
                action = options.action,
                novalidate = options.novalidate === 'novalidate',
                eventAdded = options.eventAdded;

            if (eventAdded) {
                return;
            }

            if (typeof data !== 'object') {
                data = (data && $.type(data) === 'string') ? $.parseJSON(data) : {};
            }

            //Set token data
            if (self.token_name) {
                data[self.token_name] = self.token_value;
            }

            button.on('click', function(event) {
                event.preventDefault();

                if (!button.hasClass('disabled')) {
                    self.setOptions(options);
                    self.fireEvent('execute', [action, data, novalidate]);
                }
            });

            button.data('event-added', true);
        });
    },
    execute: function(event, action, data, novalidate){
        var method = '_action' + action[0].toUpperCase() + action.substr(1);

        this.options.action = action;
        if(this.fireEvent('before.'+action, [data, novalidate])) {
            if(this[method]) {
                this[method].call(this, data, novalidate);
            } else {
                this._action_default.call(this, action, data, novalidate);
            }
            this.fireEvent('after.'+action, [data, novalidate]);
        }

        return this;
    },

    /* @TODO refactor to use jQuery.fn.on, but keep addEvent for legacy */
    addEvent: function(type, fn){
        // @TODO test if this.form.on(type, fn) works just as good as this code
        return this.form.on.apply(this.form, [type, fn]);
    },

    /* @TODO refactor to use jQuery.fn.on, but keep addEvent for legacy */
    removeEvent: function(type, fn){
        // @TODO test if this.form.on(type, fn) works just as good as this code
        return this.form.off.apply(this.form, [type, fn]);
    },

    fireEvent: function(type, args){
        var event = jQuery.Event(type);
        this.form.trigger(event, args);
        return !event.isDefaultPrevented();
    },

    checkValidity: function(){
        var buttons;

        if (this.buttons) {
            this.fireEvent('before.validate');

            buttons = this.buttons.filter('[data-novalidate!="novalidate"]');

            if (this.fireEvent('validate')) {
                buttons.removeClass('disabled');
            } else {
                buttons.addClass('disabled');
            }

            this.fireEvent('after.validate');
        }
    }
});

/**
 * Controller class specialized for grids, extends Koowa.Controller
 *
 * @package     Koowa_Media
 * @subpackage  Javascript
 */
Koowa.Controller.Grid = new Class({

    Extends: Koowa.Controller,

    options: {
        inputs: '.-koowa-grid-checkbox, .-koowa-grid-checkall'
    },
    initialize: function(options){
        var thead,
            self = this;

        this.parent(options);

        this.grid = new Koowa.Grid(this.form);

        this.addEvent('validate', this.validate);

        if (this.options.inputs && this.buttons) {
            this.checkValidity();
            this.form.find(this.options.inputs).on('change', function(event, ignore){
                if (!ignore) {
                    this.checkValidity();
                }
            }.bind(this));
        }

        this.token_name = this.form.data('token-name');
        this.token_value = this.form.data('token-value');

        this.setTableHeaders();
        this.setTableRows();

        //<select> elements in headers and footers are for filters, so they need to submit the form on change
        this.form.find('thead select, tfoot select').on('change', function(){
            self.form.submit();
        });

    },

    setTableHeaders: function() {
        //Make the table headers "clickable"
        this.form.find('thead tr > *').each(function() {
            var element = $(this),
                link = element.find('a'),
                checkall = element.find('.-koowa-grid-checkall');

            if (link.length) {
                element.on('click', function(event){
                    //Don't do anything if the event target is the same as the element
                    if($(event.target)[0] != element[0]) {
                        return;
                    }

                    //Run this check on click, so that progressive enhancements isn't bulldozed
                    if(link.prop('href')) {
                        window.location.href = link.prop('href');
                    } else {
                        link.trigger('click', event);
                    }
                });

                if(link.hasClass('-koowa-asc')) {
                    element.addClass('-koowa-asc');
                } else if(link.hasClass('-koowa-desc')) {
                    element.addClass('-koowa-desc');
                }

                return this;
            } else if(checkall.length) {
                //Making the <td> or <th> element that's the parent of a checkall checkbox toggle the checkbox when clicked
                element.on('click', function(event){
                    //Don't do anything if the event target is the same as the element
                    if($(event.target)[0] != element[0]) {
                        return true;
                    }

                    //Checkall uses change for other purposes
                    checkall.prop('checked', checkall.is(':checked') ? false : true).trigger('change');
                });
            }

            element.addClass('void');
        });
    },
    setTableRows: function() {
        var checkboxes = this.form.find('tbody tr .-koowa-grid-checkbox');

        this.form.find('tbody tr').each(function(){
            var tr = $(this),
                checkbox = tr.find('.-koowa-grid-checkbox');

            if(tr.data('readonly') == true || !checkbox.length) {
                return;
            }

            // Trigger checkbox when the user clicks anywhere in the row
            tr.on('click', function(event){
                if($(event.target).is('[type=checkbox]')) {
                    return;
                }

                checkbox.prop('checked', !checkbox.prop('checked')).trigger('change');
            });

            // Checkbox should add selected and selected-multiple classes to the row
            checkbox.on('change', function(){
                var selected,
                    parent = tr.parent();

                $(this).prop('checked') ? tr.addClass('selected') : tr.removeClass('selected');

                selected = tr.hasClass('selected') + tr.siblings('.selected').length;

                if(selected > 1) {
                    parent.addClass('selected-multiple').removeClass('selected-single')
                } else {
                    parent.removeClass('selected-multiple').addClass('selected-single');
                }
            }.bind(checkbox)).trigger('change', true);

            // Set up buttons such as publish/unpublish triggers
            tr.find('[data-action]').each(function() {
                var action = $(this),
                    data = action.data('data'),
                    options = action.data(),
                    actionName = action.data('action'),
                    eventType = action.data('event-type');

                data = (data && $.type(data) === 'string') ? $.parseJSON(data) : {};

                //Set token data
                if(self.token_name) {
                    data[self.token_name] = self.token_value;
                }

                if(!eventType) {
                    eventType = action.is('[type="radio"],[type="checkbox"],select') ? 'change' : 'click';
                }

                action.on(eventType, function(){
                    checkboxes.prop('checked', '');
                    checkbox.prop('checked', 'checked');
                    checkboxes.trigger('change', true);

                    self.setOptions(options);
                    self.fireEvent('execute', [actionName, data, true]);
                });
            });
        });
    },
    validate: function(){
        return Koowa.Grid.getIdQuery() || false;
    },

    _action_default: function(action, data, novalidate){
        var idQuery, append, options;

        if(!novalidate && !this.fireEvent('validate')) {
            return false;
        }

        idQuery = Koowa.Grid.getIdQuery();
        append = this.options.url.match(/\?/) ? '&' : '?'; // mootools?
        options = {
            method:'post',
            url: this.options.url+(idQuery ? append+idQuery : ''),
            params: $.extend({}, {action: action}, data)
        };

        new Koowa.Form(options).submit();
    }
});

/**
 * Controller class specialized for forms, extends Koowa.Controller
 *
 * @package     Koowa_Media
 * @subpackage  Javascript
 */
Koowa.Controller.Form = new Class({

    Extends: Koowa.Controller,

    _action_default: function(action, data, novalidate){
        if(!novalidate && !this.fireEvent('validate')) {
            return false;
        }

        this.form.append($('<input/>', {name: 'action', type: 'hidden', value: action}));
        this.form.submit();
    }

});

})(jQuery);<|endoftext|>


<commit_before>// export const URL = 'https://api.twinkle.network';
export const URL = 'http://localhost:3500';
<commit_msg>minor change<commit_after>export const URL = 'https://api.twinkle.network';
// export const URL = 'http://localhost:3500';
<|endoftext|>


<commit_before>/* global describe it expect fail belhop */
describe('belhop', function() {
  'use strict';

  var types = [];

  describe('annotation', function() {

    describe('types', function() {

      it('can be retrieved', function(done) {
        expect(belhop.annotations.getTypes).toBeDefined();
        var onSucc = function(annotations, status, xhr) {
          expect(xhr.status).toEqual(200);
          expect(annotations.length).toBeGreaterThan(0);
          annotations.forEach(function(x) {
            types.push(x);
          });
          done();
        };
        var onErr = function(xhr) {
          expect(xhr.status).toEqual(200);
          done();
        };
        var cb = belhop.factory.callback(onSucc, onErr);
        belhop.annotations.getTypes(cb);
      });

      it('can be retrieved individually', function(done) {
        var retrieved = 0;
        expect(types.length).toBeGreaterThan(0);
        var onSucc = function(annotations, status, xhr) {
          expect(xhr.status).toEqual(200);
          retrieved++;
          if (retrieved === types.length) {
            done();
          }
        };
        var onErr = function(xhr) {
          expect(xhr.status).toEqual(200);
          done();
        };
        var cb = belhop.factory.callback(onSucc, onErr);
        types.forEach(function(x) {
          belhop.annotations.getType(x.prefix, cb);
        });
      });

      it('can be retrieved even when not found', function(done) {
        var onSucc = function(annotations, status, xhr) {
          expect(xhr.status).toEqual(404);
          expect(annotations).toBeNull();
          done();
        };
        var onErr = function() {
          fail();
        };
        var cb = belhop.factory.callback(onSucc, onErr);
        belhop.annotations.getType('BAD_ANNOTYPE_PREFIX', cb);
      });

    });

    describe('values', function() {

      it('can be retrieved', function(done) {
        expect(belhop.annotations.getValue).toBeDefined();
        var onSucc = function(annotationValue, status, xhr) {
          expect(xhr.status).toEqual(200);
          expect(annotationValue).not.toBeNull();
          done();
        };
        var onErr = function(xhr) {
          expect(xhr.status).toEqual(200);
          done();
        };
        var cb = belhop.factory.callback(onSucc, onErr);
        belhop.annotations.getValue('taxon', '9606', cb);
      });

      it('can be retrieved even when not found', function(done) {
        var onSucc = function(annotations, status, xhr) {
          expect(xhr.status).toEqual(404);
          expect(annotations).toBeNull();
          done();
        };
        var onErr = function() {
          fail();
        };
        var cb = belhop.factory.callback(onSucc, onErr);
        belhop.annotations.getValue('BAD_ANNOTYPE_PREFIX', 'BAD_VALUE', cb);
      });

      it('can be searched', function(done) {
        done();
      });

    });

  });

});
<commit_msg>spec test annotation global/scoped search<commit_after>/* global describe it expect fail belhop */
describe('belhop', function() {
  'use strict';

  var types = [];

  describe('annotation', function() {

    describe('types', function() {

      it('can be retrieved', function(done) {
        expect(belhop.annotations.getTypes).toBeDefined();
        var onSucc = function(annotations, status, xhr) {
          expect(xhr.status).toEqual(200);
          expect(annotations.length).toBeGreaterThan(0);
          annotations.forEach(function(x) {
            types.push(x);
          });
          done();
        };
        var onErr = function(xhr) {
          expect(xhr.status).toEqual(200);
          done();
        };
        var cb = belhop.factory.callback(onSucc, onErr);
        belhop.annotations.getTypes(cb);
      });

      it('can be retrieved individually', function(done) {
        var retrieved = 0;
        expect(types.length).toBeGreaterThan(0);
        var onSucc = function(annotations, status, xhr) {
          expect(xhr.status).toEqual(200);
          retrieved++;
          if (retrieved === types.length) {
            done();
          }
        };
        var onErr = function(xhr) {
          expect(xhr.status).toEqual(200);
          done();
        };
        var cb = belhop.factory.callback(onSucc, onErr);
        types.forEach(function(x) {
          belhop.annotations.getType(x.prefix, cb);
        });
      });

      it('can be retrieved even when not found', function(done) {
        var onSucc = function(annotations, status, xhr) {
          expect(xhr.status).toEqual(404);
          expect(annotations).toBeNull();
          done();
        };
        var onErr = function() {
          fail();
        };
        var cb = belhop.factory.callback(onSucc, onErr);
        belhop.annotations.getType('BAD_ANNOTYPE_PREFIX', cb);
      });

    });

    describe('values', function() {

      it('can be retrieved', function(done) {
        expect(belhop.annotations.getValue).toBeDefined();
        var onSucc = function(annotationValue, status, xhr) {
          expect(xhr.status).toEqual(200);
          expect(annotationValue).not.toBeNull();
          done();
        };
        var onErr = function(xhr) {
          expect(xhr.status).toEqual(200);
          done();
        };
        var cb = belhop.factory.callback(onSucc, onErr);
        belhop.annotations.getValue('taxon', '9606', cb);
      });

      it('can be retrieved even when not found', function(done) {
        var onSucc = function(annotations, status, xhr) {
          expect(xhr.status).toEqual(404);
          expect(annotations).toBeNull();
          done();
        };
        var onErr = function() {
          fail();
        };
        var cb = belhop.factory.callback(onSucc, onErr);
        belhop.annotations.getValue('BAD_ANNOTYPE_PREFIX', 'BAD_VALUE', cb);
      });

      it('can be searched globally', function(done) {
        var onSucc = function(values, status, xhr) {
          expect(xhr.status).toEqual(200);
          expect(values).not.toBeNull();
          expect(values.length).toBeGreaterThan(0);
          done();
        };
        var onErr = function(xhr) {
          expect(xhr.status).toEqual(200);
          done();
        };
        var cb = belhop.factory.callback(onSucc, onErr);
        belhop.annotations.search('9606', cb);
      });

      it('can be searched in a single annotation', function(done) {
        var onSucc = function(values, status, xhr) {
          expect(xhr.status).toEqual(200);
          expect(values).not.toBeNull();
          expect(values.length).toBeGreaterThan(0);
          done();
        };
        var onErr = function(xhr) {
          expect(xhr.status).toEqual(200);
          done();
        };
        var cb = belhop.factory.callback(onSucc, onErr);
        belhop.annotations.searchByType('taxon', '9606', cb);
      });

    });

  });

});
<|endoftext|>


<commit_before>/*
 * (c) Copyright Ascensio System SIA 2010-2016
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

"use strict";
(
/**
* @param {Window} window
* @param {undefined} undefined
*/
function (window, undefined) {
var AscBrowser = {
    userAgent : "",
    isIE : false,
    isMacOs : false,
    isSafariMacOs : false,
    isAppleDevices : false,
    isAndroid : false,
    isMobile : false,
	isMobileVersion : false,
    isGecko : false,
    isChrome : false,
    isOpera : false,
    isWebkit : false,
    isSafari : false,
    isArm : false,
    isMozilla : false,
	isRetina : false,
    isLinuxOS : false
};

// user agent lower case
AscBrowser.userAgent = navigator.userAgent.toLowerCase();

// ie detect
AscBrowser.isIE =  (AscBrowser.userAgent.indexOf("msie") > -1 ||
                    AscBrowser.userAgent.indexOf("trident") > -1 ||
					AscBrowser.userAgent.indexOf("edge") > -1);

AscBrowser.isIeEdge = (AscBrowser.userAgent.indexOf("edge/") > -1);

AscBrowser.isIE9 =  (AscBrowser.userAgent.indexOf("msie9") > -1 || AscBrowser.userAgent.indexOf("msie 9") > -1);
AscBrowser.isIE10 =  (AscBrowser.userAgent.indexOf("msie10") > -1 || AscBrowser.userAgent.indexOf("msie 10") > -1);

// macOs detect
AscBrowser.isMacOs = (AscBrowser.userAgent.indexOf('mac') > -1);

// chrome detect
AscBrowser.isChrome = !AscBrowser.isIE && (AscBrowser.userAgent.indexOf("chrome") > -1);

// safari detect
AscBrowser.isSafari = !AscBrowser.isIE && !AscBrowser.isChrome && (AscBrowser.userAgent.indexOf("safari") > -1);

// macOs safari detect
AscBrowser.isSafariMacOs = (AscBrowser.isSafari && AscBrowser.isMacOs);

// apple devices detect
AscBrowser.isAppleDevices = (AscBrowser.userAgent.indexOf("ipad") > -1 ||
                             AscBrowser.userAgent.indexOf("iphone") > -1 ||
                             AscBrowser.userAgent.indexOf("ipod") > -1);

// android devices detect
AscBrowser.isAndroid = (AscBrowser.userAgent.indexOf("android") > -1);

// mobile detect
AscBrowser.isMobile = /android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent || navigator.vendor || window.opera);

// gecko detect
AscBrowser.isGecko = (AscBrowser.userAgent.indexOf("gecko/") > -1);

// opera detect
AscBrowser.isOpera = (!!window.opera || AscBrowser.userAgent.indexOf("opr/") > -1);

// webkit detect
AscBrowser.isWebkit = !AscBrowser.isIE && (AscBrowser.userAgent.indexOf("webkit") > -1);

// arm detect
AscBrowser.isArm = (AscBrowser.userAgent.indexOf("arm") > -1);

AscBrowser.isMozilla = !AscBrowser.isIE && (AscBrowser.userAgent.indexOf("firefox") > -1);

AscBrowser.isLinuxOS = (AscBrowser.userAgent.indexOf(" linux ") > -1);

AscBrowser.zoom = 1;

AscBrowser.checkZoom = function()
{
    if (AscBrowser.isAndroid)
        return;

    if (AscBrowser.isChrome && !AscBrowser.isOpera && document && document.firstElementChild && document.body)
    {
        document.firstElementChild.style.zoom = "reset";
        AscBrowser.zoom = document.body.clientWidth / window.innerWidth;

		AscBrowser.isRetina = (Math.abs(2 - (window.devicePixelRatio / AscBrowser.zoom)) < 0.01);
    }
};

AscBrowser.checkZoom();
// detect retina (http://habrahabr.ru/post/159419/)
AscBrowser.isRetina = (Math.abs(2 - (window.devicePixelRatio / AscBrowser.zoom)) < 0.01);

    //--------------------------------------------------------export----------------------------------------------------
    window['AscCommon'] = window['AscCommon'] || {};
    window['AscCommon'].AscBrowser = AscBrowser; // ToDo убрать window['AscBrowser']
})(window);
<commit_msg>detect browser zoom (chrome)<commit_after>/*
 * (c) Copyright Ascensio System SIA 2010-2016
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
 * EU, LV-1021.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

"use strict";
(
/**
* @param {Window} window
* @param {undefined} undefined
*/
function (window, undefined) {
var AscBrowser = {
    userAgent : "",
    isIE : false,
    isMacOs : false,
    isSafariMacOs : false,
    isAppleDevices : false,
    isAndroid : false,
    isMobile : false,
	isMobileVersion : false,
    isGecko : false,
    isChrome : false,
    isOpera : false,
    isWebkit : false,
    isSafari : false,
    isArm : false,
    isMozilla : false,
	isRetina : false,
    isLinuxOS : false
};

// user agent lower case
AscBrowser.userAgent = navigator.userAgent.toLowerCase();

// ie detect
AscBrowser.isIE =  (AscBrowser.userAgent.indexOf("msie") > -1 ||
                    AscBrowser.userAgent.indexOf("trident") > -1 ||
					AscBrowser.userAgent.indexOf("edge") > -1);

AscBrowser.isIeEdge = (AscBrowser.userAgent.indexOf("edge/") > -1);

AscBrowser.isIE9 =  (AscBrowser.userAgent.indexOf("msie9") > -1 || AscBrowser.userAgent.indexOf("msie 9") > -1);
AscBrowser.isIE10 =  (AscBrowser.userAgent.indexOf("msie10") > -1 || AscBrowser.userAgent.indexOf("msie 10") > -1);

// macOs detect
AscBrowser.isMacOs = (AscBrowser.userAgent.indexOf('mac') > -1);

// chrome detect
AscBrowser.isChrome = !AscBrowser.isIE && (AscBrowser.userAgent.indexOf("chrome") > -1);

// safari detect
AscBrowser.isSafari = !AscBrowser.isIE && !AscBrowser.isChrome && (AscBrowser.userAgent.indexOf("safari") > -1);

// macOs safari detect
AscBrowser.isSafariMacOs = (AscBrowser.isSafari && AscBrowser.isMacOs);

// apple devices detect
AscBrowser.isAppleDevices = (AscBrowser.userAgent.indexOf("ipad") > -1 ||
                             AscBrowser.userAgent.indexOf("iphone") > -1 ||
                             AscBrowser.userAgent.indexOf("ipod") > -1);

// android devices detect
AscBrowser.isAndroid = (AscBrowser.userAgent.indexOf("android") > -1);

// mobile detect
AscBrowser.isMobile = /android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent || navigator.vendor || window.opera);

// gecko detect
AscBrowser.isGecko = (AscBrowser.userAgent.indexOf("gecko/") > -1);

// opera detect
AscBrowser.isOpera = (!!window.opera || AscBrowser.userAgent.indexOf("opr/") > -1);

// webkit detect
AscBrowser.isWebkit = !AscBrowser.isIE && (AscBrowser.userAgent.indexOf("webkit") > -1);

// arm detect
AscBrowser.isArm = (AscBrowser.userAgent.indexOf("arm") > -1);

AscBrowser.isMozilla = !AscBrowser.isIE && (AscBrowser.userAgent.indexOf("firefox") > -1);

AscBrowser.isLinuxOS = (AscBrowser.userAgent.indexOf(" linux ") > -1);

AscBrowser.zoom = 1;

AscBrowser.checkZoom = function()
{
    if (AscBrowser.isAndroid)
        return;

	AscBrowser.zoom = 1.0;
	AscBrowser.isRetina = false;

    if (AscBrowser.isChrome && !AscBrowser.isOpera && document && document.firstElementChild && document.body)
    {
        if (window.innerWidth > 300)
			AscBrowser.zoom = window.outerWidth / window.innerWidth;

        if (Math.abs(AscBrowser.zoom - 1) < 0.1)
            AscBrowser.zoom = 1;

        AscBrowser.zoom = window.outerWidth / window.innerWidth;

        var _devicePixelRatio = window.devicePixelRatio / AscBrowser.zoom;

        // device pixel ratio: кратно 0.5
        _devicePixelRatio = (5 * (((2.5 + 10 * _devicePixelRatio) / 5) >> 0)) / 10;

        AscBrowser.zoom = window.devicePixelRatio / _devicePixelRatio;
        if (2 == _devicePixelRatio)
            AscBrowser.isRetina = true;

		// chrome 54.x: zoom = "reset" - clear retina zoom (windows)
		//document.firstElementChild.style.zoom = "reset";
		document.firstElementChild.style.zoom = 1.0 / AscBrowser.zoom;
    }
    else
    {
		AscBrowser.isRetina = (Math.abs(2 - (window.devicePixelRatio / AscBrowser.zoom)) < 0.01);
    }
};

AscBrowser.checkZoom();

    //--------------------------------------------------------export----------------------------------------------------
    window['AscCommon'] = window['AscCommon'] || {};
    window['AscCommon'].AscBrowser = AscBrowser; // ToDo убрать window['AscBrowser']
})(window);
<|endoftext|>


<commit_before>function alldeps (mod, deps, name, parentVersion) {
  name = name || mod.name;
  return Object.keys(mod.dependencies).reduce(function (all, dependency) {
    if (!all.hasOwnProperty(dependency)) {
      all[dependency] = {};
    }

    var version = mod.dependencies[dependency].version;
    var resolved = mod.dependencies[dependency].resolved;
    if (!all[dependency].hasOwnProperty(version)) {
      all[dependency][resolved] = {};
    }

    all[dependency][resolved][name] = parentVersion || version;
    if (mod.dependencies[dependency].dependencies) {
      alldeps(mod.dependencies[dependency], all, dependency, version);
    }
    return all;
  }, deps || {});
}

/**
 * Checks all modules dependencies versions within a npm-shrinkwrap to not be
 * duplicated from different parent dependencies.
 *
 * For instance if there are a couple of dependencies using a different version
 * of backbone it will return backbone with its parent dependencies.
 */
function duplicatedDependencies (shrinkwrap, modulesToValidate) {
  shrinkwrap = shrinkwrap || require('./npm-shrinkwrap.json');
  var all = alldeps(shrinkwrap);

  modulesToValidate = modulesToValidate || Object.keys(all);

  return modulesToValidate.reduce(function (duplicatedMods, mod) {
    if (all[mod] === undefined) {
      console.error('!!! ERROR !!!');
      console.error('Trying to get all dependencies from ', mod, ' but it does not exist.');
      console.error('!!! ERROR !!!');
    }
    var modVersions = Object.keys(all[mod]);
    if (modVersions.length > 1) {
      var invalidMod = { name: mod, versions: [] };

      modVersions.forEach(function (modVersion) {
        invalidMod.versions.push({version: modVersion, from: all[mod][modVersion]});
      });
      duplicatedMods.push(invalidMod);
    }
    return duplicatedMods;
  }, []);
}

/**
 * Checks if the version of a shrinkwrap file matches with the version of another shrinkwrap file.
 * It is necessary to pass the modules to validate.
 *
 * It will return the modules where the version differs.
 */
function dependenciesVersion (shrinkwrapOne, shrinkwrapTwo, modulesToValidate) {
  var allDependenciesOne = alldeps(shrinkwrapOne);
  var allDependenciesTwo = alldeps(shrinkwrapTwo);

  return modulesToValidate.reduce(function (depWithDiffVer, mod) {
    var verDepFromOne = Object.keys(allDependenciesOne[mod])[0];
    var verDepFromTwo = Object.keys(allDependenciesTwo[mod])[0];

    if (verDepFromOne !== verDepFromTwo) {
      depWithDiffVer.push(mod);
    }

    return depWithDiffVer;
  }, []);
}

module.exports = {
  checkDuplicatedDependencies: duplicatedDependencies,
  checkDependenciesVersion: dependenciesVersion
};
<commit_msg>Rename var<commit_after>function alldeps (mod, deps, name, parentVersion) {
  name = name || mod.name;
  return Object.keys(mod.dependencies).reduce(function (all, dependency) {
    if (!all.hasOwnProperty(dependency)) {
      all[dependency] = {};
    }

    var version = mod.dependencies[dependency].version;
    var resolved = mod.dependencies[dependency].resolved;
    if (!all[dependency].hasOwnProperty(version)) {
      all[dependency][resolved] = {};
    }

    all[dependency][resolved][name] = parentVersion || version;
    if (mod.dependencies[dependency].dependencies) {
      alldeps(mod.dependencies[dependency], all, dependency, version);
    }
    return all;
  }, deps || {});
}

/**
 * Checks all modules dependencies versions within a npm-shrinkwrap or package-lock to not be
 * duplicated from different parent dependencies.
 *
 * For instance if there are a couple of dependencies using a different version
 * of backbone it will return backbone with its parent dependencies.
 */
function duplicatedDependencies (lockFileContent, modulesToValidate) {
  lockFileContent = lockFileContent || require('./npm-shrinkwrap.json');
  var all = alldeps(lockFileContent);

  modulesToValidate = modulesToValidate || Object.keys(all);

  return modulesToValidate.reduce(function (duplicatedMods, mod) {
    if (all[mod] === undefined) {
      console.error('!!! ERROR !!!');
      console.error('Trying to get all dependencies from ', mod, ' but it does not exist.');
      console.error('!!! ERROR !!!');
    }
    var modVersions = Object.keys(all[mod]);
    if (modVersions.length > 1) {
      var invalidMod = { name: mod, versions: [] };

      modVersions.forEach(function (modVersion) {
        invalidMod.versions.push({version: modVersion, from: all[mod][modVersion]});
      });
      duplicatedMods.push(invalidMod);
    }
    return duplicatedMods;
  }, []);
}

/**
 * Checks if the version of a shrinkwrap or package-lock file matches with the version of another lock file.
 * It is necessary to pass the modules to validate.
 *
 * It will return the modules where the version differs.
 */
function dependenciesVersion (lockFileContentOne, lockFileContentTwo, modulesToValidate) {
  var allDependenciesOne = alldeps(lockFileContentOne);
  var allDependenciesTwo = alldeps(lockFileContentTwo);

  return modulesToValidate.reduce(function (depWithDiffVer, mod) {
    var verDepFromOne = Object.keys(allDependenciesOne[mod])[0];
    var verDepFromTwo = Object.keys(allDependenciesTwo[mod])[0];

    if (verDepFromOne !== verDepFromTwo) {
      depWithDiffVer.push(mod);
    }

    return depWithDiffVer;
  }, []);
}

module.exports = {
  checkDuplicatedDependencies: duplicatedDependencies,
  checkDependenciesVersion: dependenciesVersion
};
<|endoftext|>


<commit_before>var Stream = require('stream')

module.exports = function (write, end) {
  var stream = new Stream()
  var buffer = [], ended = false, destroyed = false, emitEnd
  stream.writable = stream.readable = true
  stream.paused = false
  stream._paused = false
  stream.buffer = buffer

  stream.writePause = false
  stream
    .on('pause', function () {
      stream.writePause = true //LEGACY, DO NOT USE
      stream._paused = true
    })
    .on('drain', function () {
      stream.writePause = false //LEGACY, DO NOT USE
      stream._paused = false
    })

  function destroySoon () {
    process.nextTick(stream.destroy.bind(stream))
  }

  if(write)
    stream.on('write', write)
  if(end)
    stream.on('ended', end)

  //destroy the stream once both ends are over
  //but do it in nextTick, so that other listeners
  //on end have time to respond
  stream.once('end', function () {
    stream.readable = false
    if(!stream.writable) {
      process.nextTick(function () {
        stream.destroy()
      })
    }
  })

  stream.once('_end', function () {
    stream.writable = false
    if(!stream.readable)
      stream.destroy()
  })

  // this is the default write method,
  // if you overide it, you are resposible
  // for pause state.

  stream.emitData = //LEGACY, DO NOT USE
  stream.sendData = //LEGACY, DO NOT USE
  stream._data = function (data) {
    if(!stream.paused && !buffer.length)
      stream.emit('data', data)
    else
      buffer.push(data)
    return !(stream.paused || buffer.length)
  }

  stream.emitEnd = //LEGACY, DO NOT USE
  stream.sendEnd = //LEGACY, DO NOT USE
  stream._end = function (data) {
    if(data) stream._data(data)
    if(emitEnd) return
    emitEnd = true
    //destroy is handled above.
    stream.drain()
  }

  stream.write = function (data) {
    stream.emit('write', data) //LEGACY, DO NOT USE
    stream.emit('_data', data)
    return !stream._paused
  }
  stream.end = function () {
    stream.writable = false
    if(stream.ended) return
    stream.ended = true
    stream.emit('ended') //LEGACY, DO NOT USE
    stream.emit('_end')
  }

  stream.drain = function () {
    if(!buffer.length && !emitEnd) return
    //if the stream is paused after just before emitEnd()
    //end should be buffered.
    while(!stream.paused) {
      if(buffer.length) {
        stream.emit('data', buffer.shift())
        if(buffer.length == 0) {
          stream.emit('read-drain') //LEGACY, DO NOT USE
          stream.emit('_drain')
        }
      }
      else if(emitEnd && stream.readable) {
        stream.readable = false
        stream.emit('end')
        return
      } else {
        //if the buffer has emptied. emit drain.
        return true
      }
    }
  }
  var started = false
  stream.resume = function () {
    //this is where I need pauseRead, and pauseWrite.
    //here the reading side is unpaused,
    //but the writing side may still be paused.
    //the whole buffer might not empity at once.
    //it might pause again.
    //the stream should never emit data inbetween pause()...resume()
    //and write should return !buffer.length
    started = true
    stream.paused = false
    stream.drain() //will emit drain if buffer empties.
    return stream
  }

  stream.destroy = function () {
    if(destroyed) return
    destroyed = ended = true
    buffer.length = 0
    stream.emit('close')
  }
  var pauseCalled = false
  stream.pause = function () {
    started = true
    stream.paused = true
    stream.emit('_pause')
    return stream
  }
  stream._pause = function () {
    if(!stream._paused) {
      stream._paused = true
      stream.emit('pause')
    }
    return this
  }
  stream.paused = true
  process.nextTick(function () {
    //unless the user manually paused
    if(started) return
    stream.resume()
  })

  return stream
}

<commit_msg>remove legacy stuff<commit_after>var Stream = require('stream')

module.exports = function (write, end) {
  var stream = new Stream()
  var buffer = [], ended = false, destroyed = false, emitEnd
  stream.writable = stream.readable = true
  stream.paused = false
  stream._paused = false
  stream.buffer = buffer

  stream
    .on('pause', function () {
      stream._paused = true
    })
    .on('drain', function () {
      stream._paused = false
    })

  function destroySoon () {
    process.nextTick(stream.destroy.bind(stream))
  }

  if(write)
    stream.on('_data', write)
  if(end)
    stream.on('_end', end)

  //destroy the stream once both ends are over
  //but do it in nextTick, so that other listeners
  //on end have time to respond
  stream.once('end', function () {
    stream.readable = false
    if(!stream.writable) {
      process.nextTick(function () {
        stream.destroy()
      })
    }
  })

  stream.once('_end', function () {
    stream.writable = false
    if(!stream.readable)
      stream.destroy()
  })

  // this is the default write method,
  // if you overide it, you are resposible
  // for pause state.

  stream._data = function (data) {
    if(!stream.paused && !buffer.length)
      stream.emit('data', data)
    else
      buffer.push(data)
    return !(stream.paused || buffer.length)
  }

  stream._end = function (data) {
    if(data) stream._data(data)
    if(emitEnd) return
    emitEnd = true
    //destroy is handled above.
    stream.drain()
  }

  stream.write = function (data) {
    stream.emit('_data', data)
    return !stream._paused
  }

  stream.end = function () {
    stream.writable = false
    if(stream.ended) return
    stream.ended = true
    stream.emit('_end')
  }

  stream.drain = function () {
    if(!buffer.length && !emitEnd) return
    //if the stream is paused after just before emitEnd()
    //end should be buffered.
    while(!stream.paused) {
      if(buffer.length) {
        stream.emit('data', buffer.shift())
        if(buffer.length == 0) {
          stream.emit('_drain')
        }
      }
      else if(emitEnd && stream.readable) {
        stream.readable = false
        stream.emit('end')
        return
      } else {
        //if the buffer has emptied. emit drain.
        return true
      }
    }
  }
  var started = false
  stream.resume = function () {
    //this is where I need pauseRead, and pauseWrite.
    //here the reading side is unpaused,
    //but the writing side may still be paused.
    //the whole buffer might not empity at once.
    //it might pause again.
    //the stream should never emit data inbetween pause()...resume()
    //and write should return !buffer.length
    started = true
    stream.paused = false
    stream.drain() //will emit drain if buffer empties.
    return stream
  }

  stream.destroy = function () {
    if(destroyed) return
    destroyed = ended = true
    buffer.length = 0
    stream.emit('close')
  }
  var pauseCalled = false
  stream.pause = function () {
    started = true
    stream.paused = true
    stream.emit('_pause')
    return stream
  }
  stream._pause = function () {
    if(!stream._paused) {
      stream._paused = true
      stream.emit('pause')
    }
    return this
  }
  stream.paused = true
  process.nextTick(function () {
    //unless the user manually paused
    if(started) return
    stream.resume()
  })

  return stream
}

<|endoftext|>