<commit_before>const debug = require('debug')('hubot-dispatcher');
const EventEmitter = require('events').EventEmitter;

const dispatcher = new EventEmitter();

// const _emit = dispatcher.emit;
// dispatcher.emit = function emit(ev) {
//   debug.apply(null, arguments);
//   return _emit.apply(dispatcher, arguments);
// }

process.on('SIGINT', function() {
  dispatcher.emit('ctrlc');
});

module.exports = dispatcher;
<commit_msg>dispatcher: add semicolon<commit_after>const debug = require('debug')('hubot-dispatcher');
const EventEmitter = require('events').EventEmitter;

const dispatcher = new EventEmitter();

// const _emit = dispatcher.emit;
// dispatcher.emit = function emit(ev) {
//   debug.apply(null, arguments);
//   return _emit.apply(dispatcher, arguments);
// };

process.on('SIGINT', function() {
  dispatcher.emit('ctrlc');
});

module.exports = dispatcher;
<|endoftext|>


<commit_before>pc.extend(pc, function () {

    var _backbufferRt = [null, null]; // 2 RTs may be needed for ping-ponging
    var _constInput = null;
    var _postEffectChain = [];

    var _createBackbufferRt = function(id, device, format) {
        var tex = new pc.Texture(device, {
                    format: format,
                    width: device.width,
                    height: device.height,
        });
        tex.minFilter = pc.FILTER_NEAREST;
        tex.magFilter = pc.FILTER_NEAREST;
        tex.addressU = pc.ADDRESS_CLAMP_TO_EDGE;
        tex.addressV = pc.ADDRESS_CLAMP_TO_EDGE;

        _backbufferRt[id]._colorBuffer = tex;
    };

    var _destroyBackbufferRt = function(id) {
        _backbufferRt[id].colorBuffer.destroy();
        _backbufferRt[id].destroy();
    };

    var _collectUniforms = function(code) {
        var strs = code.match(/uniform[ \t\n\r]+\S+[ \t\n\r]+\S+[ \t\n\r]*\;/g) || []; // look ma I know regexp
        var start, end, uname;
        var uniforms = [];
        for(var i=0; i<strs.length; i++) {
            start = strs[i].search(/\S+[ \t\n\r]*\;/);
            end = strs[i].search(/[ \t\n\r]*\;/);
            uname = strs[i].substr(start, end - start);
            if (uname !== "uColorBuffer") { // this one is OK to be shared
                uniforms.push(uname);
            }
        }
        return uniforms;
    };

    var _uniformsCollide = function(layers, chain, count, shader) {
        var uniforms = _collectUniforms(shader.definition.fshader);
        if (uniforms.length === 0) return false;

        var i, j, k, uniforms2;
        var uname;
        for(i=0; i<count; i++) {
            for(j=0; j<uniforms.length; j++) {
                uname = uniforms[j];
                uniforms2 = _collectUniforms(layers[chain[i]].shader.definition.fshader);
                for(k=0; k<uniforms2.length; k++) {
                    if (uniforms2[k] === uname) {
                        return true;
                    }
                }
            }
        }

        return false;
    };

    // collect global vars and return collisions with what's already in the list
    var _collectGlobalTempVars = function(code, list) {
        // Get code without any scoped stuff
        var len = code.length;
        var chr;
        var scopeStart = 0;
        var scopeEnd = 0;
        var scopeDepth = 0;
        var codeStart = 0;
        var codeWithoutScopes = "";
        var i, j;
        for(i=0; i<len; i++) {
            chr = code.charAt(i);
            if (chr === "{") {
                if (scopeDepth === 0) {
                    scopeStart = i;
                }
                scopeDepth++;
            } else if (chr === "}") {
                if (scopeDepth === 1) {
                    scopeEnd = i;
                    codeWithoutScopes += code.substr(codeStart, (scopeStart - codeStart) + 1);
                    codeStart = scopeEnd;
                }
                scopeDepth--;
            }
        }
        codeWithoutScopes += code.substr(codeStart, (code.length - codeStart) + 1);

        // Find all global variable declarations and detect collisions
        // ... won't work with re#defined types
        var collisions = null;
        var decls = codeWithoutScopes.match(/(float|int|bool|vec2|vec3|vec4|struct)([ \t\n\r]+[^\;]+[ \t\n\r]*\,*)+\;/g) || [];
        var vars, varName;
        for(i=0; i<decls.length; i++) {
            vars = decls[i].split(",");
            for(j=0; j<vars.length; j++) {
                varName = vars[j].replace(/(float|int|bool|vec2|vec3|vec4|struct|\,|\;|\{|\})/g, "").trim();
                if (list.indexOf(varName) >= 0) {
                    if (!collisions) collisions = [];
                    collisions.push(varName);
                } else {
                    list.push(varName);
                }
            }
        }

        // find all varying/uniform declarations (ideally should be possible to filter them out with first search...)
         //and remove from list
        var unrelevantDecls = codeWithoutScopes.match(/(uniform|varying|in|out)[ \t\n\r]+(float|int|bool|vec2|vec3|vec4|struct)([ \t\n\r]+[^\;]+[ \t\n\r]*\,*)+\;/g) || [];
        var index;
        for(i=0; i<unrelevantDecls.length; i++) {
            vars = unrelevantDecls[i].split(",");
            for(j=0; j<vars.length; j++) {
                varName = vars[j].replace(/(float|int|bool|vec2|vec3|vec4|struct|uniform|varying|in|out|\,|\;|\{|\})/g, "").trim();
                index = list.indexOf(varName);
                if (index >= 0) {
                    list.splice(index, 1);
                }
            }
        }

        return collisions;
    };

    /**
     * @name pc.PostEffectPass
     */
    function PostEffectPass(script, options) {
        var app = script.app;
        this.app = app;
        this.srcRenderTarget = options.srcRenderTarget;
        this.destRenderTarget = options.destRenderTarget;
        this.cameras = options.cameras ? options.cameras : [];
        this.hdr = options.hdr;
        this.shader = options.shader;

        var self = this;
        var device = app.graphicsDevice;

        this.layer = new pc.Layer({ // grab that and put to layer composition
            opaqueSortMode: pc.SORTMODE_NONE,
            transparentSortMode: pc.SORTMODE_NONE,
            simple: true,
            name: options.name,

            onPostRender: function() {
                // call posteffect render function
                _constInput.setValue(self.srcRenderTarget ? self.srcRenderTarget : _backbufferRt[this._backbufferRtId]._colorBuffer);
                //script.renderTarget = this.renderTarget;
                script.render(device);

                if (this._postEffectCombined && this._postEffectCombined < 0) return;
                pc.drawQuadWithShader(device, this.renderTarget,  this._postEffectCombinedShader ? this._postEffectCombinedShader : this.shader);

                if (self.srcRenderTarget) return; // don't do anything else if this effect was not reading backbuffer RT
                // remap RT back to actual backbuffer in all layers prior to this effect
                var layers = app.scene.activeLayerComposition.layerList;
                for(var i=0; i<layers.length; i++) {
                    if (layers[i] === self.layer) break;
                    if (layers[i].renderTarget === _backbufferRt[0] || layers[i].renderTarget === _backbufferRt[1]) {
                        layers[i].renderTarget = null;
                    }
                }
            }
        });
        for(var i=0; i<this.cameras.length; i++) {
            this.layer.addCamera(this.cameras[i]);
        }
        this.layer.isPostEffect = true;
        this.layer.unmodifiedUvs = options.unmodifiedUvs;
        this.layer.shader = options.shader;

        if (!_constInput) {
            // system initialization
            _constInput = device.scope.resolve("uColorBuffer"); // default input texture uniform name
            var _backbufferMsaa = device.supportsMsaa ? 4 : 1; // if context is created with antialias: true, backbuffer RT will use 4 MSAA samples
            for(var i=0; i<2; i++) { // create backbuffer RT objects, but don't allocate any memory for them just yet
                _backbufferRt[i] = new pc.RenderTarget({
                    depth: true,
                    stencil: device.supportsStencil,
                    samples: _backbufferMsaa
                });
            }
            app.on("prerender", function() { // before every app.render, if any effect reads from backbuffer, we must replace real backbuffer with our backbuffer RTs prior to effect

                /*
                getting from
                    world -> backbuffer
                    backbuffer -> post1 -> backbuffer
                    backbuffer -> post2 -> backbuffer
                to
                    world -> rt0
                    rt0 -> post1 -> rt1
                    rt1 -> post2 -> backbuffer
                */

                var layers = app.scene.activeLayerComposition.layerList;
                var i, j;
                var offset = 0;
                var rtId = 0;
                var backbufferRtUsed = false;
                var backbufferRt2Used = false;
                var backbufferRtFormat = pc.PIXELFORMAT_R8_G8_B8_A8;
                for(i=0; i<layers.length; i++) {
                    if (layers[i].isPostEffect && !layers[i].srcRenderTarget) { // layer i is posteffect reading from backbuffer
                        for(j=i-1; j>=offset; j--) {
                            if (!layers[j].renderTarget) { // layer j is prior to layer i and is rendering to backbuffer
                                layers[j].renderTarget = _backbufferRt[rtId]; // replace backbuffer with backbuffer RT
                            }
                        }
                        layers[i]._backbufferRtId = rtId; // set input hint for post effect
                        offset = i;
                        backbufferRtUsed = true; // 1st backbuffer RT used
                        if (rtId === 1) backbufferRt2Used = true; // 2nd backbuffer RT used
                        if (layers[i].hdr) backbufferRtFormat = pc.PIXELFORMAT_111110F; // backbuffer RT must be HDR
                        rtId = 1 - rtId; // pingpong RT
                    }
                }

                // create/resize backbuffer render target if needed

                if (backbufferRtUsed) {
                    if (!_backbufferRt[0].colorBuffer) {
                        _createBackbufferRt(0, device, backbufferRtFormat);
                    } else if (_backbufferRt[0].width !== device.width || _backbufferRt[0].height !== device.height || _backbufferRt[0]._format !== backbufferRtFormat) {
                        _destroyBackbufferRt(0);
                        _createBackbufferRt(0, device, backbufferRtFormat);
                    }
                }

                if (backbufferRt2Used) {
                    if (!_backbufferRt[1].colorBuffer) {
                        _createBackbufferRt(1, device, backbufferRtFormat);
                    } else if (_backbufferRt[1].width !== device.width || _backbufferRt[1].height !== device.height || _backbufferRt[1]._format !== backbufferRtFormat) {
                        _destroyBackbufferRt(1);
                        _createBackbufferRt(1, device, backbufferRtFormat);
                    }
                }

                if (!app.scene.activeLayerComposition._dirty) return;

                // only called if layer order changed
                // detect chains of posteffects and combine if possible
                // won't work with uniform collisions
                // #ifdef DEBUG
                console.log("Trying to combine shaders...");
                // #endif
                var iterator = 0;
                var breakChain = false;
                var collisions, k;
                for(i=0; i<layers.length; i++) {
                    breakChain = false;

                    if (layers[i].isPostEffect && (iterator === 0 || (layers[i].unmodifiedUvs && !_uniformsCollide(layers, _postEffectChain, iterator, layers[i].shader)))) {
                        _postEffectChain[iterator] = i; // add effect to chain
                        iterator++;
                        if (i === layers.length - 1) breakChain = true; // this is the last layer
                    } else {
                        if (iterator > 0) {
                            breakChain = true; // next layer is not effect
                        }
                    }

                    if (breakChain) {
                        if (iterator > 1) {
                            //console.log(_postEffectChain);
                            // combine multiple shaders

                            var cachedName = "post_";
                            var layer;
                            for(j=0; j<iterator; j++) {
                                layer = layers[_postEffectChain[j]];
                                cachedName += layer.name ? layer.name : layer.id;
                                if (j < iterator - 1) cachedName += "_";
                            }
                            var shader = device.programLib._cache[cachedName];
                            if (!shader) {
                                var subCode;
                                var code = "vec4 shaderOutput;\n"; // this is will be used instead of gl_FragColor; reading from real gl_FragColor is buggy on some platforms
                                var mainCode = "void main() {\n";
                                var globalTempVars = [];

                                for(j=0; j<iterator; j++) {
                                    subCode = layers[_postEffectChain[j]].shader.definition.fshader + "\n";
                                    /*
                                        For every shader's code:
                                        - Replace #version, because createShaderFromCode will append a new one anyway;
                                        - Replace pc_fragColor and #define gl_FragColor for the same reason;
                                        - Replace any usage of gl_FragColor to shaderOutput;
                                    */
                                    subCode = subCode.replace(/#version/g, "//").replace(/out highp vec4 pc_fragColor;/g, "//").replace(/#define gl_FragColor/g, "//").replace(/gl_FragColor/g, "shaderOutput");
                                    if (j > 0) {
                                        /*
                                            For every shader's code > 0:
                                            - Remove definition of uColorBuffer (should be defined in code 0 already);
                                            - Remove definition of vUv0 (same reason);
                                            - Replace reading from uColorBuffer with reading from shaderOutput.
                                        */
                                        subCode = subCode.replace(/uniform[ \t\n\r]+sampler2D[ \t\n\r]+uColorBuffer;/g, "//").replace(/(varying|in)[ \t\n\r]+vec2[ \t\n\r]+vUv0;/g, "//").replace(/(texture2D|texture)[ \t\n\r]*\([ \t\n\r]*uColorBuffer/g, "shaderOutput;\/\/");
                                    }
                                    // Replace main() with mainX()
                                    subCode = subCode.replace(/void[ \t\n\r]+main/g, "void main" + j);

                                    // Check for global variable collisions
                                    collisions = _collectGlobalTempVars(subCode, globalTempVars);
                                    if (collisions) {
                                        for(k=0; k<collisions.length; k++) {
                                            subCode = subCode.replace(new RegExp("\\b" + collisions[k] + "\\b", 'g'), collisions[k] + "NNNN" + j);
                                        }
                                    }

                                    code += subCode;
                                    mainCode += "main" + j + "();\n";
                                }
                                mainCode += "gl_FragColor = shaderOutput;\n}\n";
                                shader = pc.shaderChunks.createShaderFromCode(device,
                                                                      pc.shaderChunks.fullscreenQuadVS,
                                                                      code + mainCode,
                                                                      cachedName);
                                // #ifdef DEBUG
                                console.log("Combined " + cachedName);
                                // #endif
                            }
                            for(j=0; j<iterator; j++) {
                                layers[_postEffectChain[j]]._postEffectCombined = (j === iterator - 1) ? 1 : -1;
                            }
                            layers[_postEffectChain[iterator - 1]]._postEffectCombinedShader = shader;
                        }
                        iterator = 0;
                    }
                }

            }, this);
        }
    }

    return {
        PostEffectPass: PostEffectPass
    };
}());
<commit_msg>fix ping-ponging RTs for combined post effects<commit_after>pc.extend(pc, function () {

    var _backbufferRt = [null, null]; // 2 RTs may be needed for ping-ponging
    var _constInput = null;
    var _postEffectChain = [];

    var _createBackbufferRt = function(id, device, format) {
        var tex = new pc.Texture(device, {
                    format: format,
                    width: device.width,
                    height: device.height,
        });
        tex.minFilter = pc.FILTER_NEAREST;
        tex.magFilter = pc.FILTER_NEAREST;
        tex.addressU = pc.ADDRESS_CLAMP_TO_EDGE;
        tex.addressV = pc.ADDRESS_CLAMP_TO_EDGE;

        _backbufferRt[id]._colorBuffer = tex;
    };

    var _destroyBackbufferRt = function(id) {
        _backbufferRt[id].colorBuffer.destroy();
        _backbufferRt[id].destroy();
    };

    var _collectUniforms = function(code) {
        var strs = code.match(/uniform[ \t\n\r]+\S+[ \t\n\r]+\S+[ \t\n\r]*\;/g) || []; // look ma I know regexp
        var start, end, uname;
        var uniforms = [];
        for(var i=0; i<strs.length; i++) {
            start = strs[i].search(/\S+[ \t\n\r]*\;/);
            end = strs[i].search(/[ \t\n\r]*\;/);
            uname = strs[i].substr(start, end - start);
            if (uname !== "uColorBuffer") { // this one is OK to be shared
                uniforms.push(uname);
            }
        }
        return uniforms;
    };

    var _uniformsCollide = function(layers, chain, count, shader) {
        var uniforms = _collectUniforms(shader.definition.fshader);
        if (uniforms.length === 0) return false;

        var i, j, k, uniforms2;
        var uname;
        for(i=0; i<count; i++) {
            for(j=0; j<uniforms.length; j++) {
                uname = uniforms[j];
                uniforms2 = _collectUniforms(layers[chain[i]].shader.definition.fshader);
                for(k=0; k<uniforms2.length; k++) {
                    if (uniforms2[k] === uname) {
                        return true;
                    }
                }
            }
        }

        return false;
    };

    // collect global vars and return collisions with what's already in the list
    var _collectGlobalTempVars = function(code, list) {
        // Get code without any scoped stuff
        var len = code.length;
        var chr;
        var scopeStart = 0;
        var scopeEnd = 0;
        var scopeDepth = 0;
        var codeStart = 0;
        var codeWithoutScopes = "";
        var i, j;
        for(i=0; i<len; i++) {
            chr = code.charAt(i);
            if (chr === "{") {
                if (scopeDepth === 0) {
                    scopeStart = i;
                }
                scopeDepth++;
            } else if (chr === "}") {
                if (scopeDepth === 1) {
                    scopeEnd = i;
                    codeWithoutScopes += code.substr(codeStart, (scopeStart - codeStart) + 1);
                    codeStart = scopeEnd;
                }
                scopeDepth--;
            }
        }
        codeWithoutScopes += code.substr(codeStart, (code.length - codeStart) + 1);

        // Find all global variable declarations and detect collisions
        // ... won't work with re#defined types
        var collisions = null;
        var decls = codeWithoutScopes.match(/(float|int|bool|vec2|vec3|vec4|struct)([ \t\n\r]+[^\;]+[ \t\n\r]*\,*)+\;/g) || [];
        var vars, varName;
        for(i=0; i<decls.length; i++) {
            vars = decls[i].split(",");
            for(j=0; j<vars.length; j++) {
                varName = vars[j].replace(/(float|int|bool|vec2|vec3|vec4|struct|\,|\;|\{|\})/g, "").trim();
                if (list.indexOf(varName) >= 0) {
                    if (!collisions) collisions = [];
                    collisions.push(varName);
                } else {
                    list.push(varName);
                }
            }
        }

        // find all varying/uniform declarations (ideally should be possible to filter them out with first search...)
         //and remove from list
        var unrelevantDecls = codeWithoutScopes.match(/(uniform|varying|in|out)[ \t\n\r]+(float|int|bool|vec2|vec3|vec4|struct)([ \t\n\r]+[^\;]+[ \t\n\r]*\,*)+\;/g) || [];
        var index;
        for(i=0; i<unrelevantDecls.length; i++) {
            vars = unrelevantDecls[i].split(",");
            for(j=0; j<vars.length; j++) {
                varName = vars[j].replace(/(float|int|bool|vec2|vec3|vec4|struct|uniform|varying|in|out|\,|\;|\{|\})/g, "").trim();
                index = list.indexOf(varName);
                if (index >= 0) {
                    list.splice(index, 1);
                }
            }
        }

        return collisions;
    };

    /**
     * @name pc.PostEffectPass
     */
    function PostEffectPass(script, options) {
        var app = script.app;
        this.app = app;
        this.srcRenderTarget = options.srcRenderTarget;
        this.destRenderTarget = options.destRenderTarget;
        this.cameras = options.cameras ? options.cameras : [];
        this.hdr = options.hdr;
        this.shader = options.shader;

        var self = this;
        var device = app.graphicsDevice;

        this.layer = new pc.Layer({ // grab that and put to layer composition
            opaqueSortMode: pc.SORTMODE_NONE,
            transparentSortMode: pc.SORTMODE_NONE,
            simple: true,
            name: options.name,

            onPostRender: function() {
                if (this._postEffectCombined && this._postEffectCombined < 0) return;

                // call posteffect render function
                _constInput.setValue(self.srcRenderTarget ? self.srcRenderTarget : _backbufferRt[this._backbufferRtId]._colorBuffer);
                script.render(device);

                pc.drawQuadWithShader(device, this.renderTarget,  this._postEffectCombinedShader ? this._postEffectCombinedShader : this.shader);

                if (self.srcRenderTarget) return; // don't do anything else if this effect was not reading backbuffer RT
                // remap RT back to actual backbuffer in all layers prior to this effect
                var layers = app.scene.activeLayerComposition.layerList;
                for(var i=0; i<layers.length; i++) {
                    if (layers[i] === self.layer) break;
                    if (layers[i].renderTarget === _backbufferRt[0] || layers[i].renderTarget === _backbufferRt[1]) {
                        layers[i].renderTarget = null;
                    }
                }
            }
        });
        for(var i=0; i<this.cameras.length; i++) {
            this.layer.addCamera(this.cameras[i]);
        }
        this.layer.isPostEffect = true;
        this.layer.unmodifiedUvs = options.unmodifiedUvs;
        this.layer.shader = options.shader;

        if (!_constInput) {
            // system initialization
            _constInput = device.scope.resolve("uColorBuffer"); // default input texture uniform name
            var _backbufferMsaa = device.supportsMsaa ? 4 : 1; // if context is created with antialias: true, backbuffer RT will use 4 MSAA samples
            for(var i=0; i<2; i++) { // create backbuffer RT objects, but don't allocate any memory for them just yet
                _backbufferRt[i] = new pc.RenderTarget({
                    depth: true,
                    stencil: device.supportsStencil,
                    samples: _backbufferMsaa
                });
            }
            app.on("prerender", function() { // before every app.render, if any effect reads from backbuffer, we must replace real backbuffer with our backbuffer RTs prior to effect

                var layers = app.scene.activeLayerComposition.layerList;
                var i, j;
                var offset = 0;
                var rtId = 0;
                var backbufferRtUsed = false;
                var backbufferRt2Used = false;
                var backbufferRtFormat = pc.PIXELFORMAT_R8_G8_B8_A8;

                if (app.scene.activeLayerComposition._dirty) {
                    // only called if layer order changed
                    // detect chains of posteffects and combine if possible
                    // won't work with uniform collisions
                    // #ifdef DEBUG
                    console.log("Trying to combine shaders...");
                    // #endif
                    var iterator = 0;
                    var breakChain = false;
                    var collisions, k;
                    for(i=0; i<layers.length; i++) {
                        breakChain = false;

                        if (layers[i].isPostEffect && (iterator === 0 || (layers[i].unmodifiedUvs && !_uniformsCollide(layers, _postEffectChain, iterator, layers[i].shader)))) {
                            _postEffectChain[iterator] = i; // add effect to chain
                            iterator++;
                            if (i === layers.length - 1) breakChain = true; // this is the last layer
                        } else {
                            if (iterator > 0) {
                                breakChain = true; // next layer is not effect
                            }
                        }

                        if (breakChain) {
                            if (iterator > 1) {
                                //console.log(_postEffectChain);
                                // combine multiple shaders

                                var cachedName = "post_";
                                var layer;
                                for(j=0; j<iterator; j++) {
                                    layer = layers[_postEffectChain[j]];
                                    cachedName += layer.name ? layer.name : layer.id;
                                    if (j < iterator - 1) cachedName += "_";
                                }
                                var shader = device.programLib._cache[cachedName];
                                if (!shader) {
                                    var subCode;
                                    var code = "vec4 shaderOutput;\n"; // this is will be used instead of gl_FragColor; reading from real gl_FragColor is buggy on some platforms
                                    var mainCode = "void main() {\n";
                                    var globalTempVars = [];

                                    for(j=0; j<iterator; j++) {
                                        subCode = layers[_postEffectChain[j]].shader.definition.fshader + "\n";
                                        /*
                                            For every shader's code:
                                            - Replace #version, because createShaderFromCode will append a new one anyway;
                                            - Replace pc_fragColor and #define gl_FragColor for the same reason;
                                            - Replace any usage of gl_FragColor to shaderOutput;
                                        */
                                        subCode = subCode.replace(/#version/g, "//").replace(/out highp vec4 pc_fragColor;/g, "//").replace(/#define gl_FragColor/g, "//").replace(/gl_FragColor/g, "shaderOutput");
                                        if (j > 0) {
                                            /*
                                                For every shader's code > 0:
                                                - Remove definition of uColorBuffer (should be defined in code 0 already);
                                                - Remove definition of vUv0 (same reason);
                                                - Replace reading from uColorBuffer with reading from shaderOutput.
                                            */
                                            subCode = subCode.replace(/uniform[ \t\n\r]+sampler2D[ \t\n\r]+uColorBuffer;/g, "//").replace(/(varying|in)[ \t\n\r]+vec2[ \t\n\r]+vUv0;/g, "//").replace(/(texture2D|texture)[ \t\n\r]*\([ \t\n\r]*uColorBuffer/g, "shaderOutput;\/\/");
                                        }
                                        // Replace main() with mainX()
                                        subCode = subCode.replace(/void[ \t\n\r]+main/g, "void main" + j);

                                        // Check for global variable collisions
                                        collisions = _collectGlobalTempVars(subCode, globalTempVars);
                                        if (collisions) {
                                            for(k=0; k<collisions.length; k++) {
                                                subCode = subCode.replace(new RegExp("\\b" + collisions[k] + "\\b", 'g'), collisions[k] + "NNNN" + j);
                                            }
                                        }

                                        code += subCode;
                                        mainCode += "main" + j + "();\n";
                                    }
                                    mainCode += "gl_FragColor = shaderOutput;\n}\n";
                                    shader = pc.shaderChunks.createShaderFromCode(device,
                                                                          pc.shaderChunks.fullscreenQuadVS,
                                                                          code + mainCode,
                                                                          cachedName);
                                    // #ifdef DEBUG
                                    console.log("Combined " + cachedName);
                                    // #endif
                                }
                                for(j=0; j<iterator; j++) {
                                    layers[_postEffectChain[j]]._postEffectCombined = (j === iterator - 1) ? 1 : -1;
                                }
                                layers[_postEffectChain[iterator - 1]]._postEffectCombinedShader = shader;
                            }
                            iterator = 0;
                        }
                    }
                }

                /*
                getting from
                    world -> backbuffer
                    backbuffer -> post1 -> backbuffer
                    backbuffer -> post2 -> backbuffer
                to
                    world -> rt0
                    rt0 -> post1 -> rt1
                    rt1 -> post2 -> backbuffer
                */

                for(i=0; i<layers.length; i++) {
                    if (layers[i].isPostEffect && layers[i]._postEffectCombined >= 0 && !layers[i].srcRenderTarget) { // layer i is posteffect reading from backbuffer
                        for(j=i-1; j>=offset; j--) {
                            if (!layers[j].renderTarget) { // layer j is prior to layer i and is rendering to backbuffer
                                layers[j].renderTarget = _backbufferRt[rtId]; // replace backbuffer with backbuffer RT
                            }
                        }
                        layers[i]._backbufferRtId = rtId; // set input hint for post effect
                        offset = i;
                        backbufferRtUsed = true; // 1st backbuffer RT used
                        if (rtId === 1) backbufferRt2Used = true; // 2nd backbuffer RT used
                        if (layers[i].hdr) backbufferRtFormat = pc.PIXELFORMAT_111110F; // backbuffer RT must be HDR
                        rtId = 1 - rtId; // pingpong RT
                    }
                }

                // create/resize backbuffer render target if needed

                if (backbufferRtUsed) {
                    if (!_backbufferRt[0].colorBuffer) {
                        _createBackbufferRt(0, device, backbufferRtFormat);
                    } else if (_backbufferRt[0].width !== device.width || _backbufferRt[0].height !== device.height || _backbufferRt[0]._format !== backbufferRtFormat) {
                        _destroyBackbufferRt(0);
                        _createBackbufferRt(0, device, backbufferRtFormat);
                    }
                }

                if (backbufferRt2Used) {
                    if (!_backbufferRt[1].colorBuffer) {
                        _createBackbufferRt(1, device, backbufferRtFormat);
                    } else if (_backbufferRt[1].width !== device.width || _backbufferRt[1].height !== device.height || _backbufferRt[1]._format !== backbufferRtFormat) {
                        _destroyBackbufferRt(1);
                        _createBackbufferRt(1, device, backbufferRtFormat);
                    }
                }

            }, this);
        }
    }

    return {
        PostEffectPass: PostEffectPass
    };
}());
<|endoftext|>


<commit_before>/*! Balloons.js v0.2.0 http://balloonsjs.com/ | Released under the MIT license. */!function(window){"use strict";var Q={};Q.clone=function(obj){var prop,copy={};for(prop in obj)obj[prop]&&(copy[prop]=obj[prop]);return copy},Q.extend=function(destination,from){var prop;for(prop in from)from[prop]&&(destination[prop]=from[prop]);return destination},Q.inherit=function(child,uber){var obj=child.prototype||{};return child.prototype=Q.extend(obj,uber.prototype),uber.prototype},window.Q=Q}(this),function(Q){"use strict";function Emitter(){return this}Emitter.prototype.on=function(event,listener,once){return this._eventsCollection=this._eventsCollection||{},listener.once=once||!1,void 0===this._eventsCollection[event]&&(this._eventsCollection[event]=[]),this._eventsCollection[event].push(listener),this},Emitter.prototype.once=function(event,listener){return this.on(event,listener,!0),this},Emitter.prototype.off=function(event,listener){if(void 0===this._eventsCollection)return this;var len,listeners=this._eventsCollection[event],i=0;if(void 0!==listeners)for(len=listeners.length,i;len>i;i+=1)if(listeners[i]===listener){listeners.splice(i,1);break}return this},Emitter.prototype.getListeners=function(event){return this._eventsCollection[event]},Emitter.prototype.emit=function(){var listeners,len,args=Array.prototype.slice.call(arguments,0),event=args.shift(),i=0;if("string"==typeof event&&(event={type:event}),event.target||(event.target=this),void 0!==this._eventsCollection&&void 0!==this._eventsCollection[event.type])for(listeners=this._eventsCollection[event.type],len=listeners.length,i;len>i;i+=1)listeners[i].apply(this,args),listeners[i].once&&(this.off(event.type,listeners[i]),len-=1,i-=1);return this},Q.emitter=function(component){return component?Q.inherit(component,Emitter):new Emitter},Q.mediator=new Emitter}(this.Q),function(window,Q){"use strict";function Component(){return this}Component.prototype._init=function(){var that=this;return this._enabled=!0,void 0!==this.init&&this.init.apply(that,arguments),window.setTimeout(function(){that.emit("ready")},50),this},Component.prototype.name="component",Component.prototype.constructor=Component,Component.prototype.enable=function(){return this._enabled=!0,this.emit("enable"),this},Component.prototype.disable=function(){return this._enabled=!1,this.emit("disable"),this},Component.prototype.destroy=function(){this.disable(),this.emit("destroy")},Component.prototype.inflate=function(members){return Q.extend(this.constructor.prototype,members),this},Q.emitter(Component),Q.define=function(parents,members){function Balloon(){return this._init.apply(this,arguments),this}return void 0===members&&(members=parents,parents=[]),parents.unshift(Component),parents.forEach(function(uber){Q.inherit(Balloon,uber)}),Q.extend(Balloon.prototype,members),Balloon}}(this,this.Q);<commit_msg>Update dist version.<commit_after>/*! Balloons.js v0.2.0 http://balloonsjs.com/ | Released under the MIT license. */!function(a){"use strict";var b={};b.clone=function(a){var b,c={};for(b in a)a[b]&&(c[b]=a[b]);return c},b.extend=function(a,b){var c;for(c in b)b[c]&&(a[c]=b[c]);return a},b.inherit=function(a,c){var d=a.prototype||{};return a.prototype=b.extend(d,c.prototype),c.prototype},a.Q=b}(this),function(a){"use strict";function b(){return this}b.prototype.on=function(a,b,c){return this._eventsCollection=this._eventsCollection||{},b.once=c||!1,void 0===this._eventsCollection[a]&&(this._eventsCollection[a]=[]),this._eventsCollection[a].push(b),this},b.prototype.once=function(a,b){return this.on(a,b,!0),this},b.prototype.off=function(a,b){if(void 0===this._eventsCollection)return this;var c,d=this._eventsCollection[a],e=0;if(void 0!==d)for(c=d.length,e;c>e;e+=1)if(d[e]===b){d.splice(e,1);break}return this},b.prototype.getListeners=function(a){return this._eventsCollection[a]},b.prototype.emit=function(){var a,b,c=Array.prototype.slice.call(arguments,0),d=c.shift(),e=0;if("string"==typeof d&&(d={type:d}),d.target||(d.target=this),void 0!==this._eventsCollection&&void 0!==this._eventsCollection[d.type])for(a=this._eventsCollection[d.type],b=a.length,e;b>e;e+=1)a[e].apply(this,c),a[e].once&&(this.off(d.type,a[e]),b-=1,e-=1);return this},a.emitter=function(c){return c?a.inherit(c,b):new b},a.mediator=new b}(this.Q),function(a,b){"use strict";function c(){return this}c.prototype._init=function(){var b=this;return this._enabled=!0,void 0!==this.init&&this.init.apply(b,arguments),a.setTimeout(function(){b.emit("ready")},50),this},c.prototype.name="component",c.prototype.constructor=c,c.prototype.enable=function(){return this._enabled=!0,this.emit("enable"),this},c.prototype.disable=function(){return this._enabled=!1,this.emit("disable"),this},c.prototype.destroy=function(){this.disable(),this.emit("destroy")},c.prototype.inflate=function(a){return b.extend(this.constructor.prototype,a),this},b.emitter(c),b.define=function(a,d){function e(){return this._init.apply(this,arguments),this}return void 0===d&&(d=a,a=[]),a.unshift(c),a.forEach(function(a){b.inherit(e,a)}),b.extend(e.prototype,d),e}}(this,this.Q);<|endoftext|>


<commit_before>var config = require("../utils/config");
var term = require("ringo/term");
var shell = require("ringo/shell");
var {Parser} = require("ringo/args");
var log = require("ringo/logging").getLogger(module.id);
var fs = require("fs");
var semver = require("ringo-semver");
var registry = require("../utils/registry");
var packages = require("../utils/packages");

var parser = new Parser();
parser.addOption("v", "verbose", null, "Print verbose information");

exports.help = function help() {
    term.writeln("\nInstalls a package.\n");
    term.writeln("Usage:");
    term.writeln("  rp install [options] <name> [version]");
    term.writeln("\nOptions:");
    term.writeln(parser.help());
    return true;
};

exports.info = function info() {
    term.writeln(term.BOLD, "  install", term.RESET, "-", "Install a new package");
    return true;
};

exports.install = function install(args) {
    var opts = {};
    try {
        parser.parse(args, opts);
    } catch (e) {
        term.writeln(term.RED, e.message, term.RESET);
        term.writeln("Available options:");
        term.writeln(parser.help());
        return;
    }
    var packageName = args.shift();
    var version = args.shift();
    if (version != undefined) {
        try {
            version = semver.cleanVersion(version);
        } catch (e) {
            term.writeln(term.RED, "Invalid version number", version, term.RESET);
            return;
        }
    }
    // check if package exists in registry
    if (!registry.exists(packageName)) {
        term.writeln(term.RED, "Package '" + packageName + "' does not exist in registry", term.RESET);
        return false;
    } else if (version && !registry.exists(packageName, version)) {
        term.writeln(term.RED, "Version", version, "of package", packageName,
                "does not exist in registry", term.RESET);
        return false;
    }
    // check if package is already activated
    if (packages.isActivated(packageName)) {
        // TODO: display version number of active package
        term.writeln(term.RED, "Package", packageName,
                "is active, please deactivate or uninstall it", term.RESET);
        return false;
    }

    var descriptor = registry.getPackageDescriptor(packageName, version);
    if (descriptor == null) {
        term.writeln(term.RED, "Package cache is outdated, please do a 'rp cache init'", term.RESET);
        return false;
    }
    var pkgList = packages.resolveDependencies(descriptor);
    if (pkgList.length > 1) {
        var toInstall = [pkg for each (pkg in pkgList)
            if (!packages.isInstalled(pkg.name, pkg.version) && !packages.isActivated(pkg.name, pkg.version))];
        var toActivate = [pkg for each (pkg in pkgList)
            if (!packages.isActivated(pkg.name, pkg.version))];
        // ask for confirmation to install dependent packages
        if (toInstall.length > 0) {
            term.writeln("\nAbout to", term.BOLD, "install", term.RESET,
                    "the following packages:");
            for each (var pkg in toInstall) {
                term.writeln("  ", pkg.name, pkg.version);
            }
        }
        if (toActivate.length > 0) {
            term.writeln("\nAbout to", term.BOLD, "activate", term.RESET, "the following packages:");
            for each (var pkg in toActivate) {
                term.writeln("  ", pkg.name, pkg.version);
            }
        }
        var confirmation = shell.readln("\nDo you want to proceed? (Y/n) ");
        if (confirmation != "" && confirmation != "y") {
            term.writeln("\nAborted");
            return false;
        }
        installPackages(toInstall);
        activatePackages(toActivate);
    }
    term.writeln(term.GREEN, "Finished", term.RESET);
    return true;
};

function installPackages(arr) {
    // loop over all packages in the list and install them
    for each (let descriptor in arr) {
        var archivePath = null;
        try {
            archivePath = installPackage(descriptor);
        } catch (e) {
            term.writeln(term.RED, e.message, term.RESET);
            // cleanup: remove temporary package archive file
            if (archivePath !== null && fs.exists(archivePath)) {
                fs.remove(archivePath);
            }
        }
    }
}

function activatePackages(arr) {
    for each (let descriptor in arr) {
        activatePackage(descriptor);
    }
}

function installPackage(descriptor) {
    if (!packages.isInstalled(descriptor.name, descriptor.version)) {
        var [archivePath, checksums] = registry.getPackage(descriptor);
        for each (var key in Object.keys(checksums)) {
            if (descriptor.checksums[key] !== checksums[key]) {
                throw new Error(key.toUpperCase() + " checksum mismatch");
            }
        }
        var dir = packages.install(archivePath, descriptor.name, descriptor.version);
        term.writeln("Installed", descriptor.name,
                descriptor.version, "in", fs.resolve(dir));

    } else {
        term.writeln("Package", descriptor.name, descriptor.version,
                "is already installed");
    }
    return archivePath;
}

function activatePackage(descriptor) {
    if (!packages.isActivated(descriptor.name)) {
        var link = packages.activate(descriptor.name, descriptor.version);
        term.writeln("Activated", descriptor.name,
                descriptor.version, "in", fs.resolve(link));
    } else {
        term.writeln("Package", descriptor.name, descriptor.version,
                "is already activated");
    }
}<commit_msg>fixed install command - pkgList always contains at least one descriptor<commit_after>var config = require("../utils/config");
var term = require("ringo/term");
var shell = require("ringo/shell");
var {Parser} = require("ringo/args");
var log = require("ringo/logging").getLogger(module.id);
var fs = require("fs");
var semver = require("ringo-semver");
var registry = require("../utils/registry");
var packages = require("../utils/packages");

var parser = new Parser();
parser.addOption("v", "verbose", null, "Print verbose information");

exports.help = function help() {
    term.writeln("\nInstalls a package.\n");
    term.writeln("Usage:");
    term.writeln("  rp install [options] <name> [version]");
    term.writeln("\nOptions:");
    term.writeln(parser.help());
    return true;
};

exports.info = function info() {
    term.writeln(term.BOLD, "  install", term.RESET, "-", "Install a new package");
    return true;
};

exports.install = function install(args) {
    var opts = {};
    try {
        parser.parse(args, opts);
    } catch (e) {
        term.writeln(term.RED, e.message, term.RESET);
        term.writeln("Available options:");
        term.writeln(parser.help());
        return;
    }
    var packageName = args.shift();
    var version = args.shift();
    if (version != undefined) {
        try {
            version = semver.cleanVersion(version);
        } catch (e) {
            term.writeln(term.RED, "Invalid version number", version, term.RESET);
            return;
        }
    }
    // check if package exists in registry
    if (!registry.exists(packageName)) {
        term.writeln(term.RED, "Package '" + packageName + "' does not exist in registry", term.RESET);
        return false;
    } else if (version && !registry.exists(packageName, version)) {
        term.writeln(term.RED, "Version", version, "of package", packageName,
                "does not exist in registry", term.RESET);
        return false;
    }
    // check if package is already activated
    if (packages.isActivated(packageName)) {
        // TODO: display version number of active package
        term.writeln(term.RED, "Package", packageName,
                "is active, please deactivate or uninstall it", term.RESET);
        return false;
    }

    var descriptor = registry.getPackageDescriptor(packageName, version);
    if (descriptor == null) {
        term.writeln(term.RED, "Package cache is outdated, please do a 'rp cache init'", term.RESET);
        return false;
    }
    var pkgList = packages.resolveDependencies(descriptor);
    var toInstall = [pkg for each (pkg in pkgList)
        if (!packages.isInstalled(pkg.name, pkg.version) && !packages.isActivated(pkg.name, pkg.version))];
    var toActivate = [pkg for each (pkg in pkgList)
        if (!packages.isActivated(pkg.name, pkg.version))];
    // ask for confirmation to install dependent packages
    if (toInstall.length > 0) {
        term.writeln("\nAbout to", term.BOLD, "install", term.RESET,
                "the following packages:");
        for each (var pkg in toInstall) {
            term.writeln("  ", pkg.name, pkg.version);
        }
    }
    if (toActivate.length > 0) {
        term.writeln("\nAbout to", term.BOLD, "activate", term.RESET, "the following packages:");
        for each (var pkg in toActivate) {
            term.writeln("  ", pkg.name, pkg.version);
        }
    }
    var confirmation = shell.readln("\nDo you want to proceed? (Y/n) ");
    if (confirmation != "" && confirmation != "y") {
        term.writeln("\nAborted");
        return false;
    }
    installPackages(toInstall);
    activatePackages(toActivate);
    term.writeln(term.GREEN, "Finished", term.RESET);
    return true;
};

function installPackages(arr) {
    // loop over all packages in the list and install them
    for each (let descriptor in arr) {
        var archivePath = null;
        try {
            archivePath = installPackage(descriptor);
        } catch (e) {
            term.writeln(term.RED, e.message, term.RESET);
            // cleanup: remove temporary package archive file
            if (archivePath !== null && fs.exists(archivePath)) {
                fs.remove(archivePath);
            }
        }
    }
}

function activatePackages(arr) {
    for each (let descriptor in arr) {
        activatePackage(descriptor);
    }
}

function installPackage(descriptor) {
    if (!packages.isInstalled(descriptor.name, descriptor.version)) {
        var [archivePath, checksums] = registry.getPackage(descriptor);
        for each (var key in Object.keys(checksums)) {
            if (descriptor.checksums[key] !== checksums[key]) {
                throw new Error(key.toUpperCase() + " checksum mismatch");
            }
        }
        var dir = packages.install(archivePath, descriptor.name, descriptor.version);
        term.writeln("Installed", descriptor.name,
                descriptor.version, "in", fs.resolve(dir));

    } else {
        term.writeln("Package", descriptor.name, descriptor.version,
                "is already installed");
    }
    return archivePath;
}

function activatePackage(descriptor) {
    if (!packages.isActivated(descriptor.name)) {
        var link = packages.activate(descriptor.name, descriptor.version);
        term.writeln("Activated", descriptor.name,
                descriptor.version, "in", fs.resolve(link));
    } else {
        term.writeln("Package", descriptor.name, descriptor.version,
                "is already activated");
    }
}<|endoftext|>


<commit_before>"use strict";Array.isArray||(Array.isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)}),window.AudioContext=window.AudioContext||window.webkitAudioContext;
"use strict";var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};window.jd=function(e,t){function n(e,r){return r?("string"==typeof r&&(r=n(r)),r.querySelector(e)):o[e]||(o[e]=t.querySelector(e))}function r(e,n,r,o){var i=t.createElement(e);if("string"==typeof n)i.textContent=n;else if(n instanceof HTMLElement)i.appendChild(n);else if(null!==n&&"object"===(void 0===n?"undefined":_typeof(n)))for(var f in n)if("_"===f)n[f]instanceof HTMLElement?i.appendChild(n[f]):i.textContent=n[f];else if(null!==n[f]&&"object"===_typeof(n[f])){if("style"===f)for(var l in n[f])i.style.setProperty(l,n[f][l]);else if("events"===f)for(var y in n[f])i.addEventListener(y,n[f][y])}else i.setAttribute(f,n[f]);if(Array.isArray(r)){var a=!0,u=!1,c=void 0;try{for(var p,s=r[Symbol.iterator]();!(a=(p=s.next()).done);a=!0){var d=p.value;i.appendChild(d)}}catch(e){u=!0,c=e}finally{try{!a&&s.return&&s.return()}finally{if(u)throw c}}}return o&&o.appendChild(i),i}var o={};return{find:n,f:n,create:r,c:r}}(window,document);
"use strict";function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}();!function(){function e(){localStorage.setItem("q","1"),document.body.removeChild(jd.f(".main")),document.body.appendChild(jd.c("form",{events:{submit:function(e){return e.preventDefault(),"pointprojects"===jd.f("input",e.target).value&&(localStorage.removeItem("q"),location.reload()),!1}}},[jd.c("input",{style:{border:"1px solid white"},autofocus:!0})]))}function t(e){l.emit("login",e,location.hash?location.hash.slice(1):void 0)}function n(){return f.setTime(Date.now()),(f.getHours()%12||12)+":"+("0"+f.getMinutes()).slice(-2)}function i(e){return e.replace(m,function(e){return''+(v.test(e)?"":e)+""})}function a(e){var t=document.createElement("link"),n=document.getElementById("dynamic-favicon");t.id="dynamic-favicon",t.rel="icon",t.href=e,n&&document.head.removeChild(n),document.head.appendChild(t)}null!==localStorage.getItem("q")&&e();var o=function(){function e(t,n){var i=this;_classCallCheck(this,e),this.name=n,this.buildItem=t,this.el=jd.f(".rooms"),this.ul=jd.f("ul",this.el),this.header=jd.f("span",this.el),jd.f("button",this.el).addEventListener("click",function(e){jd.f("form",i.el).classList.toggle("hide"),jd.f("input",i.el).focus()}),this.count=0}return _createClass(e,[{key:"init",value:function(e,t){for(var n in e)this.add(e[n]);t.appendChild(this.el)}},{key:"add",value:function(e){this.ul.appendChild(this.buildItem(jd.c("li"),e)),++this.count,this.header.textContent=this.name+" ("+this.count+")"}},{key:"remove",value:function(e){this.ul.removeChild(e),--this.count}}]),e}(),s={},r=function(){function e(t,n){_classCallCheck(this,e),this.id=t,this.nickname=n,this.displayName=n,c===t&&(this.displayName+=" (me)"),"jweiss"===this.nickname?this.hueRotate=-100:"Topher"===this.nickname?this.hueRotate=-220:this.hueRotate=65*t,this.hsl="hsl("+(210+this.hueRotate)+", 75%, 50%)"}return _createClass(e,[{key:"createIcon",value:function(){return jd.c("img",{class:"m-icon",style:{filter:"hue-rotate("+this.hueRotate+"deg)"}})}},{key:"createLabel",value:function(){return jd.c("span",{_:this.displayName,style:{color:this.hsl}})}}]),e}();r.create=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var i=new(Function.prototype.bind.apply(r,[null].concat(t)));return s[i.id]=i,i};var c=void 0,l=io();l.on("ban",e);var d=jd.f(".nickname",".main");d.addEventListener("submit",function(e){return e.preventDefault(),t(jd.f("input",e.target).value),!1}),localStorage.getItem("nickname")?t(localStorage.getItem("nickname")):d.classList.remove("hide"),l.on("nickInvalid",function(e,t){jd.f(".error",d).textContent='Nickname "'+e+'" '+t+".",d.classList.remove("hide")}),l.on("login",function(e,t){jd.f(".main").removeChild(jd.f(".nickname",".main")),c=e,r.create(e,t),window.localStorage.setItem("nickname",t),jd.c("div",{class:"message"},[s[c].createIcon(),jd.c("div",{class:"m-content"},[jd.c("div",{class:"m-header"},[s[c].createLabel(),jd.c("button",{class:"fa fa-times",events:{click:function(){localStorage.removeItem("nickname"),location.reload()}}})])])],jd.f(".names",".people"))});var u=new o(function(e,t){return t.isPrivate&&e.classList.add("hide"),t.creator&&(e.style.color=t.creator.hsl),e.textContent=t.name,e.addEventListener("click",function(){l.emit("join",t.id)}),t.li=e,e},"Rooms");l.on("join",function(e,t,n){for(var i=j[e],a=[],o=0;o<n.length;o+=2)r.create(n[o],n[o+1]),a.push(n[o+1]);if(!i.el){i.link=location.origin+"/#"+t,i.setUpWindow();var l="joined "+(i.creator?i.creator.nickname+"'s":"the")+" room "+i.name;a.length&&(l+=" with "+a.join(", ")),i.addUpdate(l,s[c]),i.isPrivate&&i.li.classList.remove("hide")}}),l.on("tell",function(e,t,n){var i=s[n];j[e].addMessage(t,i),i.typingIndicator&&i.typingIndicator.classList.add("hide")}),l.on("typing",function(e,t){var n=s[t];n.typingIndicator?n.typingIndicator.classList.remove("hide"):(n.typingIndicator=n.createIcon(),j[e].typing.appendChild(n.typingIndicator))}),l.on("not typing",function(e,t){var n=s[t];n.typingIndicator&&n.typingIndicator.classList.add("hide")}),l.on("+member",function(e,t,n){r.create(t,n),j[e].addUpdate(n+" has joined the room",s[t])}),l.on("-member",function(e,t){j[e].addUpdate(s[t].nickname+" has left the room",s[t])}),l.on("left",function(e){j[e].leave()});var f=new Date,h=0,m=/((http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?)/g,v=/\.(jpe?g|png|gif)$/g,p=function(){function e(t,n,i){_classCallCheck(this,e),this.name=n,this.id=t,this.isPrivate=!!i.isPrivate,this.creatorId=i.creatorId,this.isPermanent=!!i.isPermanent}return _createClass(e,[{key:"setUpWindow",value:function(){var e=this;this.el=jd.c("div",{class:"window"},[jd.c("header",null,[jd.c("span",null,[jd.c("button",jd.c("a",{class:"fa fa-link",href:this.link,tabindex:2})),jd.c("button",jd.c("a",{class:"fa fa-envelope",href:"mailto:?subject=Articulatte%20room%20invite&body=Join%20here!%20"+this.link,tabindex:2}))]),jd.c("span",{_:this.name,style:this.creator?{color:this.creator.hsl}:null}),jd.c("button",{class:"fa fa-times",events:{click:function(t){l.emit("leave",e.id)}}})]),jd.c("div",{class:"feed"}),jd.c("div",{class:"typing"}),jd.c("form",{class:"field"},[jd.c("textarea",{class:"f-input",maxlength:1e3,tabindex:1,rows:1}),jd.c("button",{class:"f-submit fa fa-reply"})])],jd.f(".windows")),this.field=jd.f(".field",this.el),this.input=jd.f(".f-input",this.field),this.input.addEventListener("keydown",function(t){if(!t.shiftKey&&13===t.keyCode){t.preventDefault();var n=i(e.input.value.trim().substr(0,1e3));if(Date.now()-h<100||!n.length)return;return h=Date.now(),l.emit("tell",e.id,n),e.field.reset(),e.addMessage(n,s[c]),!1}l.emit("typing",e.id),clearTimeout(e.typeTimeoutId),e.typeTimeoutId=setTimeout(function(){l.emit("not typing",e.id)},3e3)}),this.input.focus(),this.feed=jd.f(".feed",this.el),this.typing=jd.f(".typing",this.el)}},{key:"leave",value:function(){jd.f(".windows").removeChild(this.el),delete this.el,delete this.field,delete this.input,delete this.feed}},{key:"addMessage",value:function(e,t){var i=jd.c("div",{class:"m-text"});-1===e.indexOf("<")?i.textContent=e:i.innerHTML=e;var a=n();this.lastSenderId===t.id&&this.lastTime===a?this.lastContent.appendChild(i):(this.lastContent=jd.c("div",{class:"m-content"},[jd.c("div",{class:"m-header"},[t.createLabel(),jd.c("span",{class:"m-time",_:a})]),i]),jd.c("div",{class:"message"},[t.createIcon(),this.lastContent],this.feed)),this.lastSenderId=t.id,this.lastTime=a,this.scroll(),y.notify()}},{key:"addUpdate",value:function(e,t){jd.c("div",{class:"update",_:e,style:t?{color:t.hsl}:null},[jd.c("span",{class:"m-time",_:n()})],jd.f(".feed",this.el)),this.scroll(),this.lastSenderId=-1}},{key:"scroll",value:function(){this.feed.scrollHeight-(this.feed.scrollTop+this.feed.clientHeight)<this.feed.clientHeight/2&&(this.feed.scrollTop=this.feed.scrollHeight)}},{key:"creator",get:function(){return s[this.creatorId]}}]),e}(),j={};p.create=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var i=new(Function.prototype.bind.apply(p,[null].concat(t)));return j[i.id]=i,i},l.once("rooms",function(e){for(var t=0;t<e.length;t+=5)p.create(e[t],e[t+1],{creatorId:e[t+2],isPrivate:!!e[t+3],isPermanent:!!e[t+4]});u.init(j,jd.f(".people"))}),l.on("reconnect",function(){for(var e in j)l.emit("join",j[e].id)}),l.on("-room",function(e){u.remove(j[e].li),delete j[e]});var g={el:jd.f("form",u.el),privateCount:5,permanentCount:1};g.name=jd.f('input[type="text"]',g.el),g.isPrivate=jd.f('label[name="priv"]',g.el),g.isPermanent=jd.f('label[name="perm"]',g.el),g.el.addEventListener("submit",function(e){return e.preventDefault(),l.emit("+room",g.name.value.trim(),jd.f("input",g.isPrivate).checked?1:0,jd.f("input",g.isPermanent).checked?1:0),!1}),l.on("+room",function(e,t,n,i,a){u.add(p.create(e,t,{creatorId:n,isPrivate:i,isPermanent:a})),n===c&&(jd.f("form",".rooms").reset(),jd.f("form",".rooms").classList.add("hide"),i&&--g.privateCount<=0&&g.el.removeChild(g.isPrivate),a&&--g.permanentCount<=0&&g.el.removeChild(g.isPermanent))}),l.on("roomInvalid",function(e,t){jd.f(".error",g.el).textContent='Name "'+e+'" '+t+"."});var y=function(){function e(){if(n){var e=n.createOscillator(),t=n.createGain();e.connect(t),e.frequency.value=587.33,t.gain.setValueAtTime(0,n.currentTime),t.gain.linearRampToValueAtTime(.8,n.currentTime+.1),t.gain.linearRampToValueAtTime(0,n.currentTime+.7),t.connect(n.destination),e.start(),e.stop(n.currentTime+.8)}}var t=!0;window.addEventListener("focus",function(){t=!0,a("fav.ico")}),window.addEventListener("blur",function(){t=!1});var n=AudioContext?new AudioContext:null;return{notify:function(){t||(a("update.ico"),e())}}}()}();<commit_msg>gulped<commit_after>"use strict";Array.isArray||(Array.isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)}),window.AudioContext=window.AudioContext||window.webkitAudioContext;
"use strict";var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};window.jd=function(e,t){function n(e,r){return r?("string"==typeof r&&(r=n(r)),r.querySelector(e)):o[e]||(o[e]=t.querySelector(e))}function r(e,n,r,o){var i=t.createElement(e);if("string"==typeof n)i.textContent=n;else if(n instanceof HTMLElement)i.appendChild(n);else if(null!==n&&"object"===(void 0===n?"undefined":_typeof(n)))for(var f in n)if("_"===f)n[f]instanceof HTMLElement?i.appendChild(n[f]):i.textContent=n[f];else if(null!==n[f]&&"object"===_typeof(n[f])){if("style"===f)for(var l in n[f])i.style.setProperty(l,n[f][l]);else if("events"===f)for(var y in n[f])i.addEventListener(y,n[f][y])}else i.setAttribute(f,n[f]);if(Array.isArray(r)){var a=!0,u=!1,c=void 0;try{for(var p,s=r[Symbol.iterator]();!(a=(p=s.next()).done);a=!0){var d=p.value;i.appendChild(d)}}catch(e){u=!0,c=e}finally{try{!a&&s.return&&s.return()}finally{if(u)throw c}}}return o&&o.appendChild(i),i}var o={};return{find:n,f:n,create:r,c:r}}(window,document);
"use strict";function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function e(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(t,n,i){return n&&e(t.prototype,n),i&&e(t,i),t}}();!function(){function e(){localStorage.setItem("q","1"),document.body.removeChild(jd.f(".main")),document.body.appendChild(jd.c("form",{events:{submit:function(e){return e.preventDefault(),"pointprojects"===jd.f("input",e.target).value&&(localStorage.removeItem("q"),location.reload()),!1}}},[jd.c("input",{style:{border:"1px solid white"},autofocus:!0})]))}function t(e){l.emit("login",e,location.hash?location.hash.slice(1):void 0)}function n(){return f.setTime(Date.now()),(f.getHours()%12||12)+":"+("0"+f.getMinutes()).slice(-2)}function i(e){return e.replace(m,function(e){return''+(v.test(e)?"":e)+""})}function a(e){var t=document.createElement("link"),n=document.getElementById("dynamic-favicon");t.id="dynamic-favicon",t.rel="icon",t.href=e,n&&document.head.removeChild(n),document.head.appendChild(t)}null!==localStorage.getItem("q")&&e();var o=function(){function e(t,n){var i=this;_classCallCheck(this,e),this.name=n,this.buildItem=t,this.el=jd.f(".rooms"),this.ul=jd.f("ul",this.el),this.header=jd.f("span",this.el),jd.f("button",this.el).addEventListener("click",function(e){jd.f("form",i.el).classList.toggle("hide"),jd.f("input",i.el).focus()}),this.count=0}return _createClass(e,[{key:"init",value:function(e,t){for(var n in e)this.add(e[n]);t.appendChild(this.el)}},{key:"add",value:function(e){this.ul.appendChild(this.buildItem(jd.c("li"),e)),++this.count,this.header.textContent=this.name+" ("+this.count+")"}},{key:"remove",value:function(e){this.ul.removeChild(e),--this.count}}]),e}(),s={},r=function(){function e(t,n){_classCallCheck(this,e),this.id=t,this.nickname=n,this.displayName=n,c===t&&(this.displayName+=" (me)"),"jweiss"===this.nickname?this.hueRotate=-100:"Topher"===this.nickname?this.hueRotate=-220:this.hueRotate=65*t,this.hsl="hsl("+(210+this.hueRotate)+", 75%, 50%)"}return _createClass(e,[{key:"createIcon",value:function(){return jd.c("img",{class:"m-icon",style:{filter:"hue-rotate("+this.hueRotate+"deg)"}})}},{key:"createLabel",value:function(){return jd.c("span",{_:this.displayName,style:{color:this.hsl}})}}]),e}();r.create=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var i=new(Function.prototype.bind.apply(r,[null].concat(t)));return s[i.id]=i,i};var c=void 0,l=io();l.on("ban",e);var d=jd.f(".nickname",".main");d.addEventListener("submit",function(e){return e.preventDefault(),t(jd.f("input",e.target).value),!1}),localStorage.getItem("nickname")?t(localStorage.getItem("nickname")):d.classList.remove("hide"),l.on("nickInvalid",function(e,t){jd.f(".error",d).textContent='Nickname "'+e+'" '+t+".",d.classList.remove("hide")}),l.on("login",function(e,t){jd.f(".main").removeChild(jd.f(".nickname",".main")),c=e,r.create(e,t),window.localStorage.setItem("nickname",t),jd.c("div",{class:"message"},[s[c].createIcon(),jd.c("div",{class:"m-content"},[jd.c("div",{class:"m-header"},[s[c].createLabel(),jd.c("button",{class:"fa fa-times",events:{click:function(){localStorage.removeItem("nickname"),location.reload()}}})])])],jd.f(".names",".people"))});var u=new o(function(e,t){return t.isPrivate&&e.classList.add("hide"),t.creator&&(e.style.color=t.creator.hsl),e.textContent=t.name,e.addEventListener("click",function(){l.emit("join",t.id)}),t.li=e,e},"Rooms");l.on("join",function(e,t,n){for(var i=j[e],a=[],o=0;o<n.length;o+=2)r.create(n[o],n[o+1]),a.push(n[o+1]);if(!i.el){i.link=location.origin+"/#"+t,i.setUpWindow();var l="joined "+(i.creator?i.creator.nickname+"'s":"the")+" room "+i.name;a.length&&(l+=" with "+a.join(", ")),i.addUpdate(l,s[c]),i.isPrivate&&i.li.classList.remove("hide")}}),l.on("tell",function(e,t,n){var i=s[n];j[e].addMessage(t,i),i.typingIndicator&&i.typingIndicator.classList.add("hide")}),l.on("typing",function(e,t){var n=s[t];n.typingIndicator?n.typingIndicator.classList.remove("hide"):(n.typingIndicator=n.createIcon(),j[e].typing.appendChild(n.typingIndicator))}),l.on("not typing",function(e,t){var n=s[t];n.typingIndicator&&n.typingIndicator.classList.add("hide")}),l.on("+member",function(e,t,n){r.create(t,n),j[e].addUpdate(n+" has joined the room",s[t])}),l.on("-member",function(e,t){var n=s[t],i=j[e];i.addUpdate(n.nickname+" has left the room",n),i.typing.removeChild(n.typingIndicator)}),l.on("left",function(e){j[e].leave()});var f=new Date,h=0,m=/((http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?)/g,v=/\.(jpe?g|png|gif)$/g,p=function(){function e(t,n,i){_classCallCheck(this,e),this.name=n,this.id=t,this.isPrivate=!!i.isPrivate,this.creatorId=i.creatorId,this.isPermanent=!!i.isPermanent}return _createClass(e,[{key:"setUpWindow",value:function(){var e=this;this.el=jd.c("div",{class:"window"},[jd.c("header",null,[jd.c("span",null,[jd.c("button",jd.c("a",{class:"fa fa-link",href:this.link,tabindex:2})),jd.c("button",jd.c("a",{class:"fa fa-envelope",href:"mailto:?subject=Articulatte%20room%20invite&body=Join%20here!%20"+this.link,tabindex:2}))]),jd.c("span",{_:this.name,style:this.creator?{color:this.creator.hsl}:null}),jd.c("button",{class:"fa fa-times",events:{click:function(t){l.emit("leave",e.id)}}})]),jd.c("div",{class:"feed"}),jd.c("div",{class:"typing"}),jd.c("form",{class:"field"},[jd.c("textarea",{class:"f-input",maxlength:1e3,tabindex:1,rows:1}),jd.c("button",{class:"f-submit fa fa-reply"})])],jd.f(".windows")),this.field=jd.f(".field",this.el),this.input=jd.f(".f-input",this.field),this.input.addEventListener("keydown",function(t){if(!t.shiftKey&&13===t.keyCode){t.preventDefault();var n=i(e.input.value.trim().substr(0,1e3));if(Date.now()-h<100||!n.length)return;return h=Date.now(),l.emit("tell",e.id,n),e.field.reset(),e.addMessage(n,s[c]),!1}l.emit("typing",e.id),clearTimeout(e.typeTimeoutId),e.typeTimeoutId=setTimeout(function(){l.emit("not typing",e.id)},3e3)}),this.input.focus(),this.feed=jd.f(".feed",this.el),this.typing=jd.f(".typing",this.el)}},{key:"leave",value:function(){jd.f(".windows").removeChild(this.el),delete this.el,delete this.field,delete this.input,delete this.feed}},{key:"addMessage",value:function(e,t){var i=jd.c("div",{class:"m-text"});-1===e.indexOf("<")?i.textContent=e:i.innerHTML=e;var a=n();this.lastSenderId===t.id&&this.lastTime===a?this.lastContent.appendChild(i):(this.lastContent=jd.c("div",{class:"m-content"},[jd.c("div",{class:"m-header"},[t.createLabel(),jd.c("span",{class:"m-time",_:a})]),i]),jd.c("div",{class:"message"},[t.createIcon(),this.lastContent],this.feed)),this.lastSenderId=t.id,this.lastTime=a,this.scroll(),y.notify()}},{key:"addUpdate",value:function(e,t){jd.c("div",{class:"update",_:e,style:t?{color:t.hsl}:null},[jd.c("span",{class:"m-time",_:n()})],jd.f(".feed",this.el)),this.scroll(),this.lastSenderId=-1}},{key:"scroll",value:function(){this.feed.scrollHeight-(this.feed.scrollTop+this.feed.clientHeight)<this.feed.clientHeight/2&&(this.feed.scrollTop=this.feed.scrollHeight)}},{key:"creator",get:function(){return s[this.creatorId]}}]),e}(),j={};p.create=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var i=new(Function.prototype.bind.apply(p,[null].concat(t)));return j[i.id]=i,i},l.once("rooms",function(e){for(var t=0;t<e.length;t+=5)p.create(e[t],e[t+1],{creatorId:e[t+2],isPrivate:!!e[t+3],isPermanent:!!e[t+4]});u.init(j,jd.f(".people"))}),l.on("reconnect",function(){for(var e in j)l.emit("join",j[e].id)}),l.on("-room",function(e){u.remove(j[e].li),delete j[e]});var g={el:jd.f("form",u.el),privateCount:5,permanentCount:1};g.name=jd.f('input[type="text"]',g.el),g.isPrivate=jd.f('label[name="priv"]',g.el),g.isPermanent=jd.f('label[name="perm"]',g.el),g.el.addEventListener("submit",function(e){return e.preventDefault(),l.emit("+room",g.name.value.trim(),jd.f("input",g.isPrivate).checked?1:0,jd.f("input",g.isPermanent).checked?1:0),!1}),l.on("+room",function(e,t,n,i,a){u.add(p.create(e,t,{creatorId:n,isPrivate:i,isPermanent:a})),n===c&&(jd.f("form",".rooms").reset(),jd.f("form",".rooms").classList.add("hide"),i&&--g.privateCount<=0&&g.el.removeChild(g.isPrivate),a&&--g.permanentCount<=0&&g.el.removeChild(g.isPermanent))}),l.on("roomInvalid",function(e,t){jd.f(".error",g.el).textContent='Name "'+e+'" '+t+"."});var y=function(){function e(){if(n){var e=n.createOscillator(),t=n.createGain();e.connect(t),e.frequency.value=587.33,t.gain.setValueAtTime(0,n.currentTime),t.gain.linearRampToValueAtTime(.8,n.currentTime+.1),t.gain.linearRampToValueAtTime(0,n.currentTime+.7),t.connect(n.destination),e.start(),e.stop(n.currentTime+.8)}}var t=!0;window.addEventListener("focus",function(){t=!0,a("fav.ico")}),window.addEventListener("blur",function(){t=!1});var n=AudioContext?new AudioContext:null;return{notify:function(){t||(a("update.ico"),e())}}}()}();<|endoftext|>


<commit_before>/*!__GLOBAL_NAMES__!*/
(function(config, definitions, undefined) {

    var modules = {
//        '/path/to/module.js': function() { return module; },
    };

    var aliases = {
//        'shortName': '/long/path/to/file.js'
    };

    for (var alias in config.aliases) {
        aliases[alias] = config.aliases[alias];
    }

    var require = function(path) {
        path = aliases[path] || path;
        return modules[path]();
    };

    var define = function(path, definition) {
        var module;

        modules[path] = function() {
            if (module) {
                return module.exports;
            }
            module = { exports: {} };
            definition.apply(null, [ require, module, module.exports ]);
            return module.exports;
        };
    };

    for (var path in definitions) {
        define(path, definitions[path]);
    }

    require(config.main);

}(
    /*!__CONFIG__!*/,
    /*!__MODULE_DEFINITIONS__!*/
));
/*!__GLOBAL_VALUES__!*/
<commit_msg>Removed unnecessary apply() call<commit_after>/*!__GLOBAL_NAMES__!*/
(function(config, definitions, undefined) {

    var modules = {
//        '/path/to/module.js': function() { return module; },
    };

    var aliases = {
//        'shortName': '/long/path/to/file.js'
    };

    for (var alias in config.aliases) {
        aliases[alias] = config.aliases[alias];
    }

    var require = function(path) {
        path = aliases[path] || path;
        return modules[path]();
    };

    var define = function(path, definition) {
        var module;

        modules[path] = function() {
            if (module) {
                return module.exports;
            }
            module = { exports: {} };
            definition(require, module, module.exports);
            return module.exports;
        };
    };

    for (var path in definitions) {
        define(path, definitions[path]);
    }

    require(config.main);

}(
    /*!__CONFIG__!*/,
    /*!__MODULE_DEFINITIONS__!*/
));
/*!__GLOBAL_VALUES__!*/
<|endoftext|>


<commit_before>// @flow
import * as React from 'react'
import {Avatar, Text, Box, PopupDialog, ScrollView, Checkbox, Icon} from '../../common-adapters'
import {globalStyles, globalColors, globalMargins} from '../../styles'

import type {Props, RowProps} from '.'

const Row = (props: RowProps & {onToggle: () => void}) => (
  <Box
    style={{
      ...globalStyles.flexBoxColumn,
      paddingLeft: globalMargins.medium,
      paddingRight: globalMargins.medium,
    }}
  >
    <Box style={{...globalStyles.flexBoxRow, alignItems: 'center', height: 40}}>
      <Box style={_rowBox}>
        <Box style={{...globalStyles.flexBoxRow, alignItems: 'center', width: 16}}>
          <Checkbox
            checked={props.selected}
            label=""
            onCheck={props.onToggle}
            style={{alignSelf: 'flext-start', marginRight: 0}}
          />
        </Box>
        <Box style={{...globalStyles.flexBoxColumn, marginLeft: globalMargins.tiny, height: 32}}>
          <Text type="BodySemibold" style={{color: globalColors.blue}}>#{props.name}</Text>
          <Text type="BodySmall">{props.description}</Text>
        </Box>
      </Box>
    </Box>
  </Box>
)

const _rowBox = {
  ...globalStyles.flexBoxRow,
  alignItems: 'flex-start',
  flex: 1,
  paddingBottom: globalMargins.xtiny,
  paddingTop: globalMargins.xtiny,
}

const ManageChannels = (props: Props) => (
  <PopupDialog onClose={props.onClose} styleCover={_styleCover} styleContainer={_styleContainer}>
    <Box style={_boxStyle}>
      <Avatar isTeam={true} teamname={props.teamname} size={24} />
      <Text type="BodySmallSemibold" style={{color: globalColors.darkBlue, marginTop: globalMargins.xtiny}}>
        {props.teamname}
      </Text>
      <Text type="Header" style={{marginBottom: globalMargins.tiny, marginTop: globalMargins.tiny}}>
        {props.channels.length} {props.channels.length !== 1 ? 'chat channels' : 'chat channel'}
      </Text>
      <ScrollView style={{alignSelf: 'flex-start', width: '100%', paddingBottom: globalMargins.xlarge}}>
        {props.channels.map(c => <Row key={c.name} {...c} onToggle={() => props.onToggle(c.name)} />)}
      </ScrollView>
      <Box style={_createStyle}>
        <Icon style={_createIcon} type="iconfont-new" onClick={props.onCreate} />
        <Text type="BodyBigLink" onClick={props.onCreate}>New chat channel</Text>
      </Box>
    </Box>
  </PopupDialog>
)

const _boxStyle = {
  ...globalStyles.flexBoxColumn,
  alignItems: 'center',
  paddingLeft: globalMargins.large,
  paddingRight: globalMargins.large,
  paddingTop: globalMargins.medium,
}

const _createIcon = {
  color: globalColors.blue,
  display: 'block',
  hoverColor: globalColors.blue2,
  marginRight: globalMargins.xtiny,
}

const _createStyle = {
  ...globalStyles.flexBoxRow,
  alignItems: 'center',
  position: 'absolute',
  right: 32,
  top: 32,
}

const _styleCover = {
  alignItems: 'center',
  backgroundColor: globalColors.black_60,
  justifyContent: 'center',
}

const _styleContainer = {
  width: 620,
  height: 520,
}

export default ManageChannels
<commit_msg>Fix (#8592)<commit_after>// @flow
import * as React from 'react'
import {Avatar, Text, Box, PopupDialog, ScrollView, Checkbox, Icon} from '../../common-adapters'
import {globalStyles, globalColors, globalMargins} from '../../styles'

import type {Props, RowProps} from '.'

const Row = (props: RowProps & {onToggle: () => void}) => (
  <Box
    style={{
      ...globalStyles.flexBoxColumn,
      paddingLeft: globalMargins.medium,
      paddingRight: globalMargins.medium,
    }}
  >
    <Box style={{...globalStyles.flexBoxRow, alignItems: 'center', minHeight: 40}}>
      <Box style={_rowBox}>
        <Box style={{...globalStyles.flexBoxRow, alignItems: 'center', width: 16}}>
          <Checkbox
            checked={props.selected}
            label=""
            onCheck={props.onToggle}
            style={{alignSelf: 'flext-start', marginRight: 0}}
          />
        </Box>
        <Box style={{...globalStyles.flexBoxColumn, marginLeft: globalMargins.tiny, minHeight: 32}}>
          <Text type="BodySemibold" style={{color: globalColors.blue}}>#{props.name}</Text>
          <Text type="BodySmall">{props.description}</Text>
        </Box>
      </Box>
    </Box>
  </Box>
)

const _rowBox = {
  ...globalStyles.flexBoxRow,
  alignItems: 'flex-start',
  flex: 1,
  paddingBottom: globalMargins.xtiny,
  paddingTop: globalMargins.xtiny,
}

const ManageChannels = (props: Props) => (
  <PopupDialog onClose={props.onClose} styleCover={_styleCover} styleContainer={_styleContainer}>
    <Box style={_boxStyle}>
      <Avatar isTeam={true} teamname={props.teamname} size={24} />
      <Text type="BodySmallSemibold" style={{color: globalColors.darkBlue, marginTop: globalMargins.xtiny}}>
        {props.teamname}
      </Text>
      <Text type="Header" style={{marginBottom: globalMargins.tiny, marginTop: globalMargins.tiny}}>
        {props.channels.length} {props.channels.length !== 1 ? 'chat channels' : 'chat channel'}
      </Text>
      <ScrollView style={{alignSelf: 'flex-start', width: '100%', paddingBottom: globalMargins.xlarge}}>
        {props.channels.map(c => <Row key={c.name} {...c} onToggle={() => props.onToggle(c.name)} />)}
      </ScrollView>
      <Box style={_createStyle}>
        <Icon style={_createIcon} type="iconfont-new" onClick={props.onCreate} />
        <Text type="BodyBigLink" onClick={props.onCreate}>New chat channel</Text>
      </Box>
    </Box>
  </PopupDialog>
)

const _boxStyle = {
  ...globalStyles.flexBoxColumn,
  alignItems: 'center',
  paddingLeft: globalMargins.large,
  paddingRight: globalMargins.large,
  paddingTop: globalMargins.medium,
}

const _createIcon = {
  color: globalColors.blue,
  display: 'block',
  hoverColor: globalColors.blue2,
  marginRight: globalMargins.xtiny,
}

const _createStyle = {
  ...globalStyles.flexBoxRow,
  alignItems: 'center',
  position: 'absolute',
  right: 32,
  top: 32,
}

const _styleCover = {
  alignItems: 'center',
  backgroundColor: globalColors.black_60,
  justifyContent: 'center',
}

const _styleContainer = {
  width: 620,
  height: 520,
}

export default ManageChannels
<|endoftext|>


<commit_before>import _ from 'lodash';
import React from 'react';
import PropTypes from 'prop-types';

import PermissionSetDetails from './PermissionSetDetails';
import PermissionSetForm from './PermissionSetForm';

class PermissionSets extends React.Component {
  static propTypes = {
    label: PropTypes.string.isRequired,
    resources: PropTypes.shape({
      entries: PropTypes.shape({
        records: PropTypes.arrayOf(PropTypes.object),
      }),
    }).isRequired,
    mutator: PropTypes.shape({
      permissionSets: PropTypes.shape({
        POST: PropTypes.func,
        PUT: PropTypes.func,
        DELETE: PropTypes.func,
      }),
    }).isRequired,
  };

  static manifest = Object.freeze({
    entries: {
      type: 'okapi',
      records: 'permissions',
      DELETE: {
        path: 'perms/permissions',
      },
      POST: {
        path: 'perms/permissions',
      },
      PUT: {
        path: 'perms/permissions',
      },
      GET: {
        path: 'perms/permissions?length=1000&query=(mutable=true)&expandSubs=true',
      },
      path: 'perms/permissions',
    },
  });

  render() {
    return (
      <EntryManager
        {...this.props}
        parentMutator={this.props.mutator}
        entryList={_.sortBy((this.props.resources.entries || {}).records || [], ['displayName'])}
        detailComponent={PermissionSetDetails}
        paneTitle={this.props.label}
        entryLabel="permission set"
        entryFormComponent={PermissionSetForm}
        nameKey="displayName"
        permissions={{
          put: 'perms.permissions.item.post',
          post: 'perms.permissions.item.post',
          delete: 'perms.permissions.item.delete',
        }}
      />
    );
  }
}

export default PermissionSets;
<commit_msg>Added Entry Manager back<commit_after>import _ from 'lodash';
import React from 'react';
import PropTypes from 'prop-types';
import PermissionSetDetails from './PermissionSetDetails';
import PermissionSetForm from './PermissionSetForm';
import EntryManager from '@folio/stripes-smart-components/lib/EntryManager';

class PermissionSets extends React.Component {
  static propTypes = {
    label: PropTypes.string.isRequired,
    resources: PropTypes.shape({
      entries: PropTypes.shape({
        records: PropTypes.arrayOf(PropTypes.object),
      }),
    }).isRequired,
    mutator: PropTypes.shape({
      permissionSets: PropTypes.shape({
        POST: PropTypes.func,
        PUT: PropTypes.func,
        DELETE: PropTypes.func,
      }),
    }).isRequired,
  };

  static manifest = Object.freeze({
    entries: {
      type: 'okapi',
      records: 'permissions',
      DELETE: {
        path: 'perms/permissions',
      },
      POST: {
        path: 'perms/permissions',
      },
      PUT: {
        path: 'perms/permissions',
      },
      GET: {
        path: 'perms/permissions?length=1000&query=(mutable=true)&expandSubs=true',
      },
      path: 'perms/permissions',
    },
  });

  render() {
    return (
      <EntryManager
        {...this.props}
        parentMutator={this.props.mutator}
        entryList={_.sortBy((this.props.resources.entries || {}).records || [], ['displayName'])}
        detailComponent={PermissionSetDetails}
        paneTitle={this.props.label}
        entryLabel="permission set"
        entryFormComponent={PermissionSetForm}
        nameKey="displayName"
        permissions={{
          put: 'perms.permissions.item.post',
          post: 'perms.permissions.item.post',
          delete: 'perms.permissions.item.delete',
        }}
      />
    );
  }
}

export default PermissionSets;
<|endoftext|>


<commit_before>/**
 * @classdesc
 * A layer used to display tiled map services, such as [google maps]{@link http://maps.google.com}, [open street maps]{@link http://www.osm.org}
 * @class
 * @category layer
 * @extends maptalks.Layer
 * @param {String|Number} id - tile layer's id
 * @param {Object} [options=null] - construct options
 * @param {Boolean} [options.debug=false] - if set to true, tile's border will be drawn and tile's xyz coordinate will be drawn on the left top corner.
 * @param {*} options.* - any other option defined in [maptalks.Layer]{@link maptalks.Layer#options}
 */
Z.TileLayer = Z.Layer.extend(/** @lends maptalks.TileLayer.prototype */{

    options: {
        'errorTileUrl'  : '#',
        'urlTemplate'   : '#',
        'subdomains'    : null,

        'gradualLoading' : true,

        'repeatWorld'   : true,

        'renderWhenPanning' : false,
        //移图时地图的更新间隔, 默认为0即实时更新, -1表示不更新.如果效率较慢则可改为适当的值
        'renderSpanWhenPanning' : (function(){return Z.Browser.mobile?-1:200;})(),

        'crossOrigin' : null,

        'tileSize' : {
            'width'   : 256,
            'height'  : 256
        },

        'tileSystem' : null,
        'debug'      : false
    },

    initialize:function(id,opts) {
        this.setId(id);
        Z.Util.setOptions(this,opts);
    },

    /**
     * Get tile size of the tile layer
     * @return {maptalks.Size}
     */
    getTileSize:function() {
        var size = this.options['tileSize'];
        return new Z.Size(size['width'], size['height']);
    },

    /**
     * Clear the layer
     * @return {maptalks.TileLayer} this
     */
    clear:function() {
        if (this._renderer) {
            this._renderer.clear();
        }
        return this;
    },

    /**
     * initialize [tileConfig]{@link maptalks.TileConfig} for the tilelayer
     * @private
     */
    _initTileConfig:function() {
        var map = this.getMap();
        this._defaultTileConfig = new Z.TileConfig(Z.TileSystem.getDefault(map.getProjection()), map.getFullExtent(), this.getTileSize());
        if (this.options['tileSystem']) {
            this._tileConfig = new Z.TileConfig(this.options['tileSystem'], map.getFullExtent(), this.getTileSize());
        }
    },

    _getTileConfig:function(){
        if (!this._defaultTileConfig) {
            this._initTileConfig();
        }
        var tileConfig = this._tileConfig;
        if (tileConfig) {return tileConfig;}
        var map = this.getMap();
        //inherit baselayer's tileconfig
        if (map && map.getBaseLayer() && map.getBaseLayer()._getTileConfig) {
            return map.getBaseLayer()._getTileConfig();
        }
        return this._defaultTileConfig;
    },

    _getTiles:function(canvasSize) {
        // rendWhenReady = false;
        var map =this.getMap();
        if (!map) {
            return null;
        }
        if (!this.isVisible()) {
            return null;
        }

        var tileConfig = this._getTileConfig();
        if (!tileConfig) {return null;}

        var tileSize = this.getTileSize(),
            zoom = map.getZoom(),
            res = map._getResolution(),
            mapDomOffset = map.offsetPlatform();

        var holderLeft=mapDomOffset.x,
            holderTop = mapDomOffset.y,
            mapWidth = map.width,
            mapHeight = map.height;
            //中心瓦片信息,包括瓦片编号,和中心点在瓦片上相对左上角的位置
        var centerTileIndex =  tileConfig.getCenterTileIndex(map._getPrjCenter(), res);
        //计算中心瓦片的top和left偏移值
        var centerTileViewPoint=new Z.Point(+(mapWidth/2-centerTileIndex['offsetLeft']),
                                                +(mapHeight/2-centerTileIndex['offsetTop']))._round();
        if (!canvasSize || !(canvasSize instanceof Z.Size)) {
            canvasSize = new Z.Size(mapWidth, mapHeight);
        }
        //中心瓦片上下左右的瓦片数
        var tileTopNum =Math.ceil(Math.abs((canvasSize['height'] - mapHeight)/2 + centerTileViewPoint.y)/tileSize['height']),
            tileLeftNum=Math.ceil(Math.abs((canvasSize['width']- mapWidth)/2 + centerTileViewPoint.x)/tileSize['width']),
            tileBottomNum=Math.ceil(Math.abs((canvasSize['height'] - mapHeight)/2 + mapHeight-centerTileViewPoint.y)/tileSize['height']),
            tileRightNum=Math.ceil(Math.abs((canvasSize['width'] - mapWidth)/2 + mapWidth-centerTileViewPoint.x)/tileSize['width']);

    //  只加中心的瓦片，用做调试
    //  var centerTileImg = this._createTileImage(centerTileViewPoint.x,centerTileViewPoint.y,this.config._getTileUrl(centerTileIndex['topIndex'],centerTileIndex['leftIndex'],zoom),tileSize['height'],tileSize['width']);
    //  tileContainer.appendChild(centerTileImg);

        var tiles = [];
        var fullExtent = new Z.PointExtent();
        //TODO 瓦片从中心开始加起
        for (var i=-(tileLeftNum);i<tileRightNum;i++){
            for (var j=-(tileTopNum);j<=tileBottomNum;j++){
                    var tileIndex = tileConfig.getNeighorTileIndex(centerTileIndex['y'], centerTileIndex['x'], j,i, res, this.options['repeatWorld']);
                    var tileLeft = centerTileViewPoint.x + tileSize['width']*i-holderLeft;
                    var tileTop = centerTileViewPoint.y +tileSize['height']*j-holderTop;
                    var tileUrl = this._getTileUrl(tileIndex['x'],tileIndex['y'],zoom);
                    var tileId=[tileIndex['y'], tileIndex['x'], zoom].join('__');
                    var tileDesc = {
                        'url' : tileUrl,
                        'viewPoint': new Z.Point(tileLeft, tileTop),
                        'id'  : tileId,
                        'zoom' : zoom
                    };
                    tiles.push(tileDesc);
                    fullExtent = fullExtent.combine(new Z.PointExtent(
                        tileDesc['viewPoint'],
                        tileDesc['viewPoint'].add(tileSize['width'],tileSize['height'])
                        )
                    );
            }
        }
        var f = 1;
        if (Z.Browser.ie || Z.Browser.edge) {
            f = -1;
        }
        //瓦片排序, 地图中心的瓦片排在末尾, 末尾的瓦片先载入
        tiles.sort(function (a, b) {
            return f * (b['viewPoint'].distanceTo(centerTileViewPoint)-a['viewPoint'].distanceTo(centerTileViewPoint));
        });
        return {
            'tiles' : tiles,
            'fullExtent' : fullExtent
        };
    },

    _getTileUrl:function(x,y,z) {
        if (!this.options['urlTemplate']) {
            return this.options['errorTileUrl'];
        }
        var urlTemplate = this.options['urlTemplate'];
        if (Z.Util.isFunction(urlTemplate)) {
            return urlTemplate(x,y,z);
        }
        var domain = '';
        if (this.options['subdomains']) {
            var subdomains = this.options['subdomains'];
            if (Z.Util.isArrayHasData(subdomains)) {
                var length = subdomains.length;
                var s = (x+y) % length;
                if (s<0) {
                    s=0;
                }
                domain = subdomains[s];
            }
        }
        var data = {
            'x' : x,
            'y' : y,
            'z' : z,
            's' : domain
        };
        return urlTemplate.replace(/\{ *([\w_]+) *\}/g,function (str, key) {
            var value = data[key];

            if (value === undefined) {
                throw new Error('No value provided for variable ' + str);

            } else if (typeof value === 'function') {
                value = value(data);
            }
            return value;
        });
    }
});

/**
 * Export the tile layer's profile json.

 * Layer's profile is a snapshot of the layer in JSON format.

 * It can be used to reproduce the instance by [fromJSON]{@link maptalks.Layer#fromJSON} method
 * @return {Object} layer's profile JSON
 */
Z.TileLayer.prototype.toJSON=function() {
    var profile = {
        "type":"TileLayer",
        "id":this.getId(),
        "options" : this.config()
    };
    return profile;
}

/**
 * Reproduce a TileLayer from layer's profile JSON.
 * @param  {Object} layerJSON - layer's profile JSON
 * @return {maptalks.TileLayer}
 * @static
 * @private
 * @function
 */
Z.TileLayer._fromJSON=function(layerJSON) {
    if (!layerJSON || layerJSON['type'] !== 'TileLayer') {return null;}
    return new Z.TileLayer(layerJSON['id'], layerJSON['options']);
}

Z.Util.extend(Z.TileLayer,Z.Renderable);
<commit_msg>reduce renderSpanWhenPanning to 80<commit_after>/**
 * @classdesc
 * A layer used to display tiled map services, such as [google maps]{@link http://maps.google.com}, [open street maps]{@link http://www.osm.org}
 * @class
 * @category layer
 * @extends maptalks.Layer
 * @param {String|Number} id - tile layer's id
 * @param {Object} [options=null] - construct options
 * @param {Boolean} [options.debug=false] - if set to true, tile's border will be drawn and tile's xyz coordinate will be drawn on the left top corner.
 * @param {*} options.* - any other option defined in [maptalks.Layer]{@link maptalks.Layer#options}
 */
Z.TileLayer = Z.Layer.extend(/** @lends maptalks.TileLayer.prototype */{

    options: {
        'errorTileUrl'  : '#',
        'urlTemplate'   : '#',
        'subdomains'    : null,

        'gradualLoading' : true,

        'repeatWorld'   : true,

        'renderWhenPanning' : false,
        //移图时地图的更新间隔, 默认为0即实时更新, -1表示不更新.如果效率较慢则可改为适当的值
        'renderSpanWhenPanning' : (function(){return Z.Browser.mobile?-1:80;})(),

        'crossOrigin' : null,

        'tileSize' : {
            'width'   : 256,
            'height'  : 256
        },

        'tileSystem' : null,
        'debug'      : false
    },

    initialize:function(id,opts) {
        this.setId(id);
        Z.Util.setOptions(this,opts);
    },

    /**
     * Get tile size of the tile layer
     * @return {maptalks.Size}
     */
    getTileSize:function() {
        var size = this.options['tileSize'];
        return new Z.Size(size['width'], size['height']);
    },

    /**
     * Clear the layer
     * @return {maptalks.TileLayer} this
     */
    clear:function() {
        if (this._renderer) {
            this._renderer.clear();
        }
        return this;
    },

    /**
     * initialize [tileConfig]{@link maptalks.TileConfig} for the tilelayer
     * @private
     */
    _initTileConfig:function() {
        var map = this.getMap();
        this._defaultTileConfig = new Z.TileConfig(Z.TileSystem.getDefault(map.getProjection()), map.getFullExtent(), this.getTileSize());
        if (this.options['tileSystem']) {
            this._tileConfig = new Z.TileConfig(this.options['tileSystem'], map.getFullExtent(), this.getTileSize());
        }
    },

    _getTileConfig:function(){
        if (!this._defaultTileConfig) {
            this._initTileConfig();
        }
        var tileConfig = this._tileConfig;
        if (tileConfig) {return tileConfig;}
        var map = this.getMap();
        //inherit baselayer's tileconfig
        if (map && map.getBaseLayer() && map.getBaseLayer()._getTileConfig) {
            return map.getBaseLayer()._getTileConfig();
        }
        return this._defaultTileConfig;
    },

    _getTiles:function(canvasSize) {
        // rendWhenReady = false;
        var map =this.getMap();
        if (!map) {
            return null;
        }
        if (!this.isVisible()) {
            return null;
        }

        var tileConfig = this._getTileConfig();
        if (!tileConfig) {return null;}

        var tileSize = this.getTileSize(),
            zoom = map.getZoom(),
            res = map._getResolution(),
            mapDomOffset = map.offsetPlatform();

        var holderLeft=mapDomOffset.x,
            holderTop = mapDomOffset.y,
            mapWidth = map.width,
            mapHeight = map.height;
            //中心瓦片信息,包括瓦片编号,和中心点在瓦片上相对左上角的位置
        var centerTileIndex =  tileConfig.getCenterTileIndex(map._getPrjCenter(), res);
        //计算中心瓦片的top和left偏移值
        var centerTileViewPoint=new Z.Point(+(mapWidth/2-centerTileIndex['offsetLeft']),
                                                +(mapHeight/2-centerTileIndex['offsetTop']))._round();
        if (!canvasSize || !(canvasSize instanceof Z.Size)) {
            canvasSize = new Z.Size(mapWidth, mapHeight);
        }
        //中心瓦片上下左右的瓦片数
        var tileTopNum =Math.ceil(Math.abs((canvasSize['height'] - mapHeight)/2 + centerTileViewPoint.y)/tileSize['height']),
            tileLeftNum=Math.ceil(Math.abs((canvasSize['width']- mapWidth)/2 + centerTileViewPoint.x)/tileSize['width']),
            tileBottomNum=Math.ceil(Math.abs((canvasSize['height'] - mapHeight)/2 + mapHeight-centerTileViewPoint.y)/tileSize['height']),
            tileRightNum=Math.ceil(Math.abs((canvasSize['width'] - mapWidth)/2 + mapWidth-centerTileViewPoint.x)/tileSize['width']);

    //  只加中心的瓦片，用做调试
    //  var centerTileImg = this._createTileImage(centerTileViewPoint.x,centerTileViewPoint.y,this.config._getTileUrl(centerTileIndex['topIndex'],centerTileIndex['leftIndex'],zoom),tileSize['height'],tileSize['width']);
    //  tileContainer.appendChild(centerTileImg);

        var tiles = [];
        var fullExtent = new Z.PointExtent();
        //TODO 瓦片从中心开始加起
        for (var i=-(tileLeftNum);i<tileRightNum;i++){
            for (var j=-(tileTopNum);j<=tileBottomNum;j++){
                    var tileIndex = tileConfig.getNeighorTileIndex(centerTileIndex['y'], centerTileIndex['x'], j,i, res, this.options['repeatWorld']);
                    var tileLeft = centerTileViewPoint.x + tileSize['width']*i-holderLeft;
                    var tileTop = centerTileViewPoint.y +tileSize['height']*j-holderTop;
                    var tileUrl = this._getTileUrl(tileIndex['x'],tileIndex['y'],zoom);
                    var tileId=[tileIndex['y'], tileIndex['x'], zoom].join('__');
                    var tileDesc = {
                        'url' : tileUrl,
                        'viewPoint': new Z.Point(tileLeft, tileTop),
                        'id'  : tileId,
                        'zoom' : zoom
                    };
                    tiles.push(tileDesc);
                    fullExtent = fullExtent.combine(new Z.PointExtent(
                        tileDesc['viewPoint'],
                        tileDesc['viewPoint'].add(tileSize['width'],tileSize['height'])
                        )
                    );
            }
        }
        var f = 1;
        if (Z.Browser.ie || Z.Browser.edge) {
            f = -1;
        }
        //瓦片排序, 地图中心的瓦片排在末尾, 末尾的瓦片先载入
        tiles.sort(function (a, b) {
            return f * (b['viewPoint'].distanceTo(centerTileViewPoint)-a['viewPoint'].distanceTo(centerTileViewPoint));
        });
        return {
            'tiles' : tiles,
            'fullExtent' : fullExtent
        };
    },

    _getTileUrl:function(x,y,z) {
        if (!this.options['urlTemplate']) {
            return this.options['errorTileUrl'];
        }
        var urlTemplate = this.options['urlTemplate'];
        if (Z.Util.isFunction(urlTemplate)) {
            return urlTemplate(x,y,z);
        }
        var domain = '';
        if (this.options['subdomains']) {
            var subdomains = this.options['subdomains'];
            if (Z.Util.isArrayHasData(subdomains)) {
                var length = subdomains.length;
                var s = (x+y) % length;
                if (s<0) {
                    s=0;
                }
                domain = subdomains[s];
            }
        }
        var data = {
            'x' : x,
            'y' : y,
            'z' : z,
            's' : domain
        };
        return urlTemplate.replace(/\{ *([\w_]+) *\}/g,function (str, key) {
            var value = data[key];

            if (value === undefined) {
                throw new Error('No value provided for variable ' + str);

            } else if (typeof value === 'function') {
                value = value(data);
            }
            return value;
        });
    }
});

/**
 * Export the tile layer's profile json.

 * Layer's profile is a snapshot of the layer in JSON format.

 * It can be used to reproduce the instance by [fromJSON]{@link maptalks.Layer#fromJSON} method
 * @return {Object} layer's profile JSON
 */
Z.TileLayer.prototype.toJSON=function() {
    var profile = {
        "type":"TileLayer",
        "id":this.getId(),
        "options" : this.config()
    };
    return profile;
}

/**
 * Reproduce a TileLayer from layer's profile JSON.
 * @param  {Object} layerJSON - layer's profile JSON
 * @return {maptalks.TileLayer}
 * @static
 * @private
 * @function
 */
Z.TileLayer._fromJSON=function(layerJSON) {
    if (!layerJSON || layerJSON['type'] !== 'TileLayer') {return null;}
    return new Z.TileLayer(layerJSON['id'], layerJSON['options']);
}

Z.Util.extend(Z.TileLayer,Z.Renderable);
<|endoftext|>