<commit_before>function create_uploader() {
    "use strict";
    var r = new Resumable({
        target:'/upload_chunk/',
        simultaneousUploads: 1,
        //chunkSize: 1,
        maxFiles: 1,
        query: {
            'csrfmiddlewaretoken': $("input[name='csrfmiddlewaretoken']").val()
        }
    });

    if (!r.support) {
        $("#chunk_upload_container").hide();
        $("#old_school_panel").show();
        return;
    }

    r.on('fileAdded', function() { r.upload(); });
    r.on('uploadStart', function(){
        $("#chunk_upload_container").hide();
        $("#uploading_panel").show();
    });
    r.on('complete', function(){
        window.location.href = "/upload/parser/"+r.files[0].fileName;
    });
    r.on('progress', function(){
        $("#progress_meter").css("width", (100 * r.progress())+"%");
        $("#progress_meter").html(Math.round(100 * r.progress())+"%");
        $("#progress_meter").attr("aria-valuenow", Math.round(100 * r.progress()));
    });

    r.assignBrowse(document.getElementById('upload_dataset_browse'));
    r.assignDrop(document.getElementById('upload_dataset_droptarget'));

}

function add_parser_form_events() {
    "use strict";

    function update_preview() {
        $("#update_preview").val("1");
        $("#dataset_parser_form").submit();
    }

    $("#dataset_delimiter").change(function() {
        update_preview();
    });

    $("#has_column_headers").change(function() {
        update_preview();
    });
}

function add_finalize_form_events() {
    "use strict";
    // Chunk one is uploaded for the dataset preview.
    var current_file_chunk = 2;

    function has_title() {
        if ($("#id_dataset_name").val().match(/[a-zA-Z0-9]/))   {
            return true;
        }
        return false;
    }

    function post_chunk_upload(data, text_status) {
        if (data == "next_chunk") {
            current_file_chunk += 1;
            upload_next_chunk();
            return;
        }
        if (data == "upload_complete") {
            send_finalize();
        }
    }

    function send_to_dataset(data, text_status, xhr) {
        window.location.href = xhr.getResponseHeader("Location");
    }

    function poll_finalize(data, text_status, xhr) {
        var filename = $("input[name='original_name']").val();
        var dataset_name = $("#id_dataset_name").val();
        if (data == "Done") {
            window.location.href = "/detail/"+encodeURIComponent(sqlshare_user)+"/"+encodeURIComponent(dataset_name);
        }
        else {
            window.setTimeout(function() {
                $.ajax({
                    url: "/upload/finalize_process/" + filename,
                    method: "GET",
                    success: poll_finalize
                });
            }, 1000);

        }
    }

    function send_finalize() {
        var filename = $("input[name='original_name']").val();
        $.ajax({
            url: "/upload/finalize_process/" + filename,
            method: "POST",
            data: {
                'csrfmiddlewaretoken': $("input[name='csrfmiddlewaretoken']").val(),
                "finalize": true,
                "dataset_name": $("input[name='dataset_name']").val(),
                "dataset_description": $("textarea[name='dataset_description']").val(),
                "is_public": $("input[name='is_public']").is(':checked')
            },
            success: poll_finalize
        });

    }

    function upload_next_chunk() {
        var filename = $("input[name='original_name']").val();
        $.ajax({
            url: "/upload/finalize_process/" + filename,
            method: "POST",
            data: {
                'csrfmiddlewaretoken': $("input[name='csrfmiddlewaretoken']").val(),
                chunk: current_file_chunk
            },
            success: post_chunk_upload
        });
    }

    $("#id_dataset_name").keyup(function() {
        if (has_title()) {
            $("#title_required").hide();
            $("#save_button").prop("disabled", false);
        }
        else {
            $("#title_required").show();
            $("#save_button").prop("disabled", true);
        }
    });

    $("#save_button").click(function() {
        if (has_title()) {
            $("#final_settings_panel").hide();
            $("#uploading_panel").show();
            upload_next_chunk();
        }
    });
}

<commit_msg>Keep showing the progress meter and upload target together.<commit_after>function create_uploader() {
    "use strict";
    var r = new Resumable({
        target:'/upload_chunk/',
        simultaneousUploads: 1,
        //chunkSize: 1,
        maxFiles: 1,
        query: {
            'csrfmiddlewaretoken': $("input[name='csrfmiddlewaretoken']").val()
        }
    });

    if (!r.support) {
        $("#chunk_upload_container").hide();
        $("#old_school_panel").show();
        return;
    }

    r.on('fileAdded', function() { r.upload(); });
    r.on('uploadStart', function(){
        //$("#chunk_upload_container").hide();
        $("#uploading_panel").show();
    });
    r.on('complete', function(){
        window.location.href = "/upload/parser/"+r.files[0].fileName;
    });
    r.on('progress', function(){
        $("#progress_meter").css("width", (100 * r.progress())+"%");
        $("#progress_meter").html(Math.round(100 * r.progress())+"%");
        $("#progress_meter").attr("aria-valuenow", Math.round(100 * r.progress()));
    });

    r.assignBrowse(document.getElementById('upload_dataset_browse'));
    r.assignDrop(document.getElementById('upload_dataset_droptarget'));

}

function add_parser_form_events() {
    "use strict";

    function update_preview() {
        $("#update_preview").val("1");
        $("#dataset_parser_form").submit();
    }

    $("#dataset_delimiter").change(function() {
        update_preview();
    });

    $("#has_column_headers").change(function() {
        update_preview();
    });
}

function add_finalize_form_events() {
    "use strict";
    // Chunk one is uploaded for the dataset preview.
    var current_file_chunk = 2;

    function has_title() {
        if ($("#id_dataset_name").val().match(/[a-zA-Z0-9]/))   {
            return true;
        }
        return false;
    }

    function post_chunk_upload(data, text_status) {
        if (data == "next_chunk") {
            current_file_chunk += 1;
            upload_next_chunk();
            return;
        }
        if (data == "upload_complete") {
            send_finalize();
        }
    }

    function send_to_dataset(data, text_status, xhr) {
        window.location.href = xhr.getResponseHeader("Location");
    }

    function poll_finalize(data, text_status, xhr) {
        var filename = $("input[name='original_name']").val();
        var dataset_name = $("#id_dataset_name").val();
        if (data == "Done") {
            window.location.href = "/detail/"+encodeURIComponent(sqlshare_user)+"/"+encodeURIComponent(dataset_name);
        }
        else {
            window.setTimeout(function() {
                $.ajax({
                    url: "/upload/finalize_process/" + filename,
                    method: "GET",
                    success: poll_finalize
                });
            }, 1000);

        }
    }

    function send_finalize() {
        var filename = $("input[name='original_name']").val();
        $.ajax({
            url: "/upload/finalize_process/" + filename,
            method: "POST",
            data: {
                'csrfmiddlewaretoken': $("input[name='csrfmiddlewaretoken']").val(),
                "finalize": true,
                "dataset_name": $("input[name='dataset_name']").val(),
                "dataset_description": $("textarea[name='dataset_description']").val(),
                "is_public": $("input[name='is_public']").is(':checked')
            },
            success: poll_finalize
        });

    }

    function upload_next_chunk() {
        var filename = $("input[name='original_name']").val();
        $.ajax({
            url: "/upload/finalize_process/" + filename,
            method: "POST",
            data: {
                'csrfmiddlewaretoken': $("input[name='csrfmiddlewaretoken']").val(),
                chunk: current_file_chunk
            },
            success: post_chunk_upload
        });
    }

    $("#id_dataset_name").keyup(function() {
        if (has_title()) {
            $("#title_required").hide();
            $("#save_button").prop("disabled", false);
        }
        else {
            $("#title_required").show();
            $("#save_button").prop("disabled", true);
        }
    });

    $("#save_button").click(function() {
        if (has_title()) {
            $("#final_settings_panel").hide();
            $("#uploading_panel").show();
            upload_next_chunk();
        }
    });
}

<|endoftext|>


<commit_before>define([
	"floom/material",
	"floom/particle",
	"floom/node",
	"floom/grid",
	"floom/integrator",
	"floom/simulator",
	"floom/tool",
	"physics/jello"
], function(Material, Particle, Node, Grid, Integrator, Simulator, Tool, Jello) {
	var System = function() {

		this.wall = new Jello.AABB(
			new Jello.Vector2(-50, 2),
			new Jello.Vector2(50, 100)
		);
		this.materials = [];
		this.gravity = new Jello.Vector2(0,-0.05);// 0.004, 0.02
		this.particles = [];
		this.grid = new Grid();
		this.integrator = new Integrator(this.grid);
		this.tool = new Tool(this);

		this.createNewMaterial()
			.setRestDensity(1)
			.setSmoothing(0.5);

		this.createNewMaterial()
			.setRestDensity(2)
			.setSmoothing(1.0);

		this.createNewMaterial()
			.setRestDensity(4)
			.setSmoothing(1.0);

		this.createNewMaterial()
			.setRestDensity(8)
			.setSmoothing(1.0);

		this.useSurfaceTensionImplementation = true;
		this.drawGrid = true;
		this.createDatGui();

		for (var i = -45; i < 0; i++) {
	        for (var j = 5; j < 25; j++) {
	        	this.particles.push(new Particle(i, j, 0.1, 0, this.materials[0]));
	        }
	    }

	    for (var i = 5; i < 50; i++) {
	        for (var j = 5; j < 25; j++) {
	        	this.particles.push(new Particle(i, j, -0.1, 0, this.materials[1]));
	        }
	    }

	    for (var i = -45; i < 0; i++) {
	        for (var j = 30; j < 50; j++) {
	        	this.particles.push(new Particle(i, j, 0.1, 0, this.materials[2]));
	        }
	    }

	    for (var i = 5; i < 50; i++) {
	        for (var j = 30; j < 50; j++) {
	        	this.particles.push(new Particle(i, j, -0.1, 0, this.materials[3]));
	        }
	    }

	    this.simulator = new Simulator();
	};

	System.prototype.getNumberOfParticles = function() {
		return this.particles.length;
	};

	System.prototype.getNumberOfMaterials = function() {
		return this.materials.length;
	};

	System.prototype.createNewMaterial = function() {
		var newMaterial = new Material(this.materials.length);
		this.materials.push(newMaterial);

		return newMaterial;
	};

	System.prototype.createDatGui = function() {
		if(Bloob.debug && Bloob.debug.datGui) {
			var datGui = new dat.GUI();
			datGui.add(this.gravity, "x").min(-0.2).max(0.2).step(-0.01);
			datGui.add(this.gravity, "y").min(-0.2).max(0.2).step(-0.01);
			datGui.add(this, "useSurfaceTensionImplementation");
			datGui.add(this, "drawGrid");

			this.materials[0].addDebugGui(datGui);
			this.materials[1].addDebugGui(datGui);
			this.materials[2].addDebugGui(datGui);
			this.materials[3].addDebugGui(datGui);
		}
	};

	/*
	 * UPDATE
	 */
	System.prototype.update = function() {
		this.tool.update();
		this.grid.update(this);

		if(this.useSurfaceTensionImplementation) {
			this.simulator.update(this);
		} else {
			this.calculateParticleKernels();
			this.sumParticleDensityFromGridAndAddPressureansElasticForcesToGrid();
			this.divideGridAccelerationByMass();
			this.accelerateParticlesAndInterpolateVelocityBackToGrid();
			this.divideGridVelocityByMass();
			this.advanceParticles();
		}
	};

	System.prototype.calculateParticleKernels = function() {
		// calculate particle kernels, and add density and density gradients to the grid
		_.each(this.particles, function(p, pIndex) {
			this.integrator.updateStateAndGradientOf(p);
			this.integrator.prepareParticle(p);

			this.integrator.integrate(p, function(particle, node, phi, gxpy, pxgy) {
				node.mass += phi;
			});
		}, this);
	};

	System.prototype.sumParticleDensityFromGridAndAddPressureansElasticForcesToGrid = function() {
		// Sum particle density from grid, and add pressure and elastic forces to grid
		_.each(this.particles, function(p, pIndex) {
	        var density = 0;
			this.integrator.integrate(p, function(particle, node, phi, gxpy, pxgy) {
				density += phi*node.mass;
			});

			var restDensity = p.material.restDensity;
			var pressure = (density-restDensity)/restDensity;
			if (pressure > 4.0)
				pressure = 4.0;

			var f = Jello.Vector2.Zero.copy();
			if (p.position.x < this.wall.Min.x) {
				f.x += this.wall.Min.x - p.position.x;
	            p.velocity.x *= 0.1;
			}
			if (p.position.x > this.wall.Max.x) {
				f.x += this.wall.Max.x - p.position.x;
	            p.velocity.x *= 0.1;
			}
			if (p.position.y < this.wall.Min.y) {
				f.y += this.wall.Min.y - p.position.y;
	            p.velocity.y *= 0.1;
			}
			if (p.position.y > this.wall.Max.y) {
				f.y += this.wall.Max.y - p.position.y;
	            p.velocity.y *= 0.1;
			}

			this.integrator.integrate(p, function(particle, node, phi, gxpy, pxgy) {
				node.acceleration.x += -(gxpy * pressure) + f.x * phi;
				node.acceleration.y += -(pxgy * pressure) + f.y * phi;
			});
		}, this);
	};

	// divide grid acceleration by mass
	System.prototype.divideGridAccelerationByMass = function() {
		this.grid.iterate(function(n) {
			if (n.mass > 0.0) {
				n.acceleration.divFloatSelf(n.mass);
				n.acceleration.addSelf(this.gravity);
			}
		}, this);
	};

	// accelerate particles and interpolate velocity back to grid
	System.prototype.accelerateParticlesAndInterpolateVelocityBackToGrid = function() {
		_.each(this.particles, function(p, pIndex) {
			this.integrator.integrate(p, function(particle, node, phi, gxpy, pxgy) {
				particle.velocity.addSelf(node.acceleration.mulFloat(phi));
			});
			this.integrator.integrate(p, function(particle, node, phi, gxpy, pxgy) {
				node.velocity.addSelf(particle.velocity.mulFloat(phi));
			});
		}, this);
	};

	// divide grid velocity by mass
	System.prototype.divideGridVelocityByMass = function() {
		this.grid.iterate(function(n) {
			if (n.mass > 0.0) {
				n.velocity.divFloatSelf(n.mass);
			}
		}, this);
	};

	System.prototype.advanceParticles = function() {
		// advance particles
		_.each(this.particles, function(p, pIndex) {
	        p.gridVelocity.set(Jello.Vector2.Zero);
			this.integrator.integrate(p, function(particle, node, phi, gxpy, pxgy) {
				particle.gridVelocity.addSelf(node.velocity.mulFloat(phi));
			});
			p.position.addSelf(p.gridVelocity);
			p.velocity.addSelf(p.gridVelocity.sub(p.velocity).mulFloat(p.material.smoothing));
		}, this);
	};

	/*
	 * DRAWING
	 */
	System.prototype.draw = function(renderer) {
		// draw grid nodes
		if(this.drawGrid)
			this.grid.draw(renderer);

		// draw mouse cursor
		this.tool.draw();

		// draw all particles in the system
		_.each(this.particles, function(p) {
			p.draw(renderer);
		}, this);
	};

	return System;
});
<commit_msg>use loop instead of hard coded number<commit_after>define([
	"floom/material",
	"floom/particle",
	"floom/node",
	"floom/grid",
	"floom/integrator",
	"floom/simulator",
	"floom/tool",
	"physics/jello"
], function(Material, Particle, Node, Grid, Integrator, Simulator, Tool, Jello) {
	var System = function() {

		this.wall = new Jello.AABB(
			new Jello.Vector2(-50, 2),
			new Jello.Vector2(50, 100)
		);
		this.materials = [];
		this.gravity = new Jello.Vector2(0,-0.05);// 0.004, 0.02
		this.particles = [];
		this.grid = new Grid();
		this.integrator = new Integrator(this.grid);
		this.tool = new Tool(this);

		this.createNewMaterial()
			.setRestDensity(1)
			.setSmoothing(0.5);

		this.createNewMaterial()
			.setRestDensity(2)
			.setSmoothing(1.0);

		this.createNewMaterial()
			.setRestDensity(4)
			.setSmoothing(1.0);

		this.createNewMaterial()
			.setRestDensity(8)
			.setSmoothing(1.0);

		this.useSurfaceTensionImplementation = true;
		this.drawGrid = true;
		this.createDatGui();

		for (var i = -45; i < 0; i++) {
	        for (var j = 5; j < 25; j++) {
	        	this.particles.push(new Particle(i, j, 0.1, 0, this.materials[0]));
	        }
	    }

	    for (var i = 5; i < 50; i++) {
	        for (var j = 5; j < 25; j++) {
	        	this.particles.push(new Particle(i, j, -0.1, 0, this.materials[1]));
	        }
	    }

	    for (var i = -45; i < 0; i++) {
	        for (var j = 30; j < 50; j++) {
	        	this.particles.push(new Particle(i, j, 0.1, 0, this.materials[2]));
	        }
	    }

	    for (var i = 5; i < 50; i++) {
	        for (var j = 30; j < 50; j++) {
	        	this.particles.push(new Particle(i, j, -0.1, 0, this.materials[3]));
	        }
	    }

	    this.simulator = new Simulator();
	};

	System.prototype.getNumberOfParticles = function() {
		return this.particles.length;
	};

	System.prototype.getNumberOfMaterials = function() {
		return this.materials.length;
	};

	System.prototype.createNewMaterial = function() {
		var newMaterial = new Material(this.materials.length);
		this.materials.push(newMaterial);

		return newMaterial;
	};

	System.prototype.createDatGui = function() {
		if(Bloob.debug && Bloob.debug.datGui) {
			var datGui = new dat.GUI();
			datGui.add(this.gravity, "x").min(-0.2).max(0.2).step(-0.01);
			datGui.add(this.gravity, "y").min(-0.2).max(0.2).step(-0.01);
			datGui.add(this, "useSurfaceTensionImplementation");
			datGui.add(this, "drawGrid");

			_.each(this.materials, function(material) {
				material.addDebugGui(datGui);
			}, this);
		}
	};

	/*
	 * UPDATE
	 */
	System.prototype.update = function() {
		this.tool.update();
		this.grid.update(this);

		if(this.useSurfaceTensionImplementation) {
			this.simulator.update(this);
		} else {
			this.calculateParticleKernels();
			this.sumParticleDensityFromGridAndAddPressureansElasticForcesToGrid();
			this.divideGridAccelerationByMass();
			this.accelerateParticlesAndInterpolateVelocityBackToGrid();
			this.divideGridVelocityByMass();
			this.advanceParticles();
		}
	};

	System.prototype.calculateParticleKernels = function() {
		// calculate particle kernels, and add density and density gradients to the grid
		_.each(this.particles, function(p, pIndex) {
			this.integrator.updateStateAndGradientOf(p);
			this.integrator.prepareParticle(p);

			this.integrator.integrate(p, function(particle, node, phi, gxpy, pxgy) {
				node.mass += phi;
			});
		}, this);
	};

	System.prototype.sumParticleDensityFromGridAndAddPressureansElasticForcesToGrid = function() {
		// Sum particle density from grid, and add pressure and elastic forces to grid
		_.each(this.particles, function(p, pIndex) {
	        var density = 0;
			this.integrator.integrate(p, function(particle, node, phi, gxpy, pxgy) {
				density += phi*node.mass;
			});

			var restDensity = p.material.restDensity;
			var pressure = (density-restDensity)/restDensity;
			if (pressure > 4.0)
				pressure = 4.0;

			var f = Jello.Vector2.Zero.copy();
			if (p.position.x < this.wall.Min.x) {
				f.x += this.wall.Min.x - p.position.x;
	            p.velocity.x *= 0.1;
			}
			if (p.position.x > this.wall.Max.x) {
				f.x += this.wall.Max.x - p.position.x;
	            p.velocity.x *= 0.1;
			}
			if (p.position.y < this.wall.Min.y) {
				f.y += this.wall.Min.y - p.position.y;
	            p.velocity.y *= 0.1;
			}
			if (p.position.y > this.wall.Max.y) {
				f.y += this.wall.Max.y - p.position.y;
	            p.velocity.y *= 0.1;
			}

			this.integrator.integrate(p, function(particle, node, phi, gxpy, pxgy) {
				node.acceleration.x += -(gxpy * pressure) + f.x * phi;
				node.acceleration.y += -(pxgy * pressure) + f.y * phi;
			});
		}, this);
	};

	// divide grid acceleration by mass
	System.prototype.divideGridAccelerationByMass = function() {
		this.grid.iterate(function(n) {
			if (n.mass > 0.0) {
				n.acceleration.divFloatSelf(n.mass);
				n.acceleration.addSelf(this.gravity);
			}
		}, this);
	};

	// accelerate particles and interpolate velocity back to grid
	System.prototype.accelerateParticlesAndInterpolateVelocityBackToGrid = function() {
		_.each(this.particles, function(p, pIndex) {
			this.integrator.integrate(p, function(particle, node, phi, gxpy, pxgy) {
				particle.velocity.addSelf(node.acceleration.mulFloat(phi));
			});
			this.integrator.integrate(p, function(particle, node, phi, gxpy, pxgy) {
				node.velocity.addSelf(particle.velocity.mulFloat(phi));
			});
		}, this);
	};

	// divide grid velocity by mass
	System.prototype.divideGridVelocityByMass = function() {
		this.grid.iterate(function(n) {
			if (n.mass > 0.0) {
				n.velocity.divFloatSelf(n.mass);
			}
		}, this);
	};

	System.prototype.advanceParticles = function() {
		// advance particles
		_.each(this.particles, function(p, pIndex) {
	        p.gridVelocity.set(Jello.Vector2.Zero);
			this.integrator.integrate(p, function(particle, node, phi, gxpy, pxgy) {
				particle.gridVelocity.addSelf(node.velocity.mulFloat(phi));
			});
			p.position.addSelf(p.gridVelocity);
			p.velocity.addSelf(p.gridVelocity.sub(p.velocity).mulFloat(p.material.smoothing));
		}, this);
	};

	/*
	 * DRAWING
	 */
	System.prototype.draw = function(renderer) {
		// draw grid nodes
		if(this.drawGrid)
			this.grid.draw(renderer);

		// draw mouse cursor
		this.tool.draw();

		// draw all particles in the system
		_.each(this.particles, function(p) {
			p.draw(renderer);
		}, this);
	};

	return System;
});
<|endoftext|>


<commit_before>'use strict';

/*
 * Client entrypoint.
 *
 * This script contains all code necessary to bootstrap Tanura in a client.
 */

/**
 * Information about Nuve.
 */
tanura.nuve = {
    url: tanura.url + 'nuve/',
    room: null
};

/**
 * Information about Erizo.
 */
tanura.erizo = {
    localStream: null
};

/**
 * Information about the whiteboard.
 */
tanura.whiteboard = {
    url: tanura.url + 'whiteboard/',
    canvas: null
};

/**
 * Tanura init routine.
 */
tanura.run = function() {
    /**
     * Fake resize indicator.  Because of CSS bugs and limitations, Tanura will
     * sometimes have to change layout parameters manually in Js. As this
     * happens after the resize, a second resize event may be triggered to give
     * other Js code the ability to react to changes Tanura has made to the
     * layout. In this case, this variable will be set to true, to tell Tanura,
     * that the resize event was a fake resize event triggered by Tanura's own
     * code and should be ignored.
     */
    var fakeResize = false;

    /**
     * Options that should be used to stream.
     */
    var streamOpts = {
        audio: !! tanura.options.audio,
        video: !! tanura.options.video,
        data: true,
        screen: false,
    };

    /**
     * The stream options Tanura will fall back to.  These options will be used
     * when establishing a stream with the default options fails. This is
     * usually due to the user not granting the necessary permissions, the
     * browser not supporting all necessary features, or is blocking some of
     * them due to security concerns.
     */
    var fallbackStreamOpts = {
        audio: false,
        video: false,
        data: true,
        screen: false,
    };

    /**
     * This will initialize the whiteboard on the canvas from a given snapshot.
     */
    var mkCanvas = (_) => {
        tanura.whiteboard.canvas =
            LC.init(document.getElementById('whiteboard'), {snapshot: _});
        tanura
            .whiteboard
            .canvas
            .setTool(new LC.tools.Pencil(tanura.whiteboard.canvas));
        tanura.whiteboard.canvas.on('drawEnd', () =>
                tanura.erizo.localStream.sendData({
                    type: 'canvas-draw',
                    data: tanura.whiteboard.canvas.getSnapshot()
                }));
    }

    var body = document.getElementsByTagName('body')[0];

    // Manually calculate the size of some elements to work around flexbox
    // issues and limitations.
    var f = () => {
        if (!fakeResize) {

            // Wait for transitions.
            setTimeout(() => {
                // Fire the resize-event.
                tanura.eventHandler.fire('client_resized', document);

                // Pass another resize for Literallycanvas.
                fakeResize = true;
                dispatchEvent(new Event('resize'));
            }, 200);
        } else {
            fakeResize = false;
        }
    }
    tanura.throttle('resize', 'throttledResize');
    window.addEventListener('throttledResize', f);
    f();

    // Connect to Tanura.
    var connect = () => {
        tanura.eventHandler.fire('client_loaded', document);

        // Wait for Erizo to load.
        if (typeof Erizo === 'undefined' || Erizo == null) {
            setTimeout(connect, 100);
            return;
        }

        // Prepare a request for a room token.
        var req = new XMLHttpRequest();
        req.addEventListener('load', function() {
            var token = this.responseText;
            tanura.log(token);
            tanura.nuve.room = Erizo.Room({token: token});
            var join = function() {
                // Add a single stream to the DOM.
                var addStream = function(_, o) {
                    if (_.hasVideo()) {
                        var e = document.createElement('div');
                        e.setAttribute('id', 'videoEntry_' + _.getID());
                        document.getElementById('people').appendChild(e);
                        _.show('videoEntry_' + _.getID(), o);
                    }
                };

                // Subscribe to a list of streams.
                var subscribeToStreams = function(l) {
                    for (var i in l) {
                        tanura.nuve.room.subscribe(l[i]);
                        l[i].addEventListener(
                                    'bandwidth-alert',
                                    function(_) {
                                        tanura.log(
                                                'Bandwidth Alert',
                                                _.msg,
                                                _.bandwidth);
                                    });
                        l[i].addEventListener('stream-data', (_) => {
                            switch(_.msg.type) {
                                case 'canvas-clear':
                                    tanura.whiteboard.canvas.clear();
                                    tanura
                                        .eventHandler
                                        .fire(
                                                'whiteboard_cleared',
                                                tanura
                                                    .whiteboard
                                                    .canvas
                                                    .getSnapshot());
                                    break;
                                case 'canvas-draw':
                                    tanura
                                        .whiteboard
                                        .canvas
                                        .loadSnapshot(_.msg.data);
                                    tanura
                                        .eventHandler
                                        .fire('whiteboard_changed', _.msg.data);
                                    break;
                                case 'canvas-init':
                                    if (!tanura.whiteboard.canvas) {
                                        mkCanvas(_.msg.data);
                                    }
                                    tanura.log(
                                            'Created canvas from existing '
                                            + 'snapshot.');
                                    break;
                                default:
                                    tanura
                                        .eventHandler
                                        .fire('data_received', _.msg.data);
                            }
                        });
                    }
                };

                // This will run as soon as signalling is fully initialized.
                tanura
                    .nuve
                    .room
                    .addEventListener('room-connected', function(_) {
                        tanura
                            .eventHandler
                            .fire('connection_opened', tanura.nuve.room);

                        // If we are the only one in the room, add a fresh
                        // whiteboard.
                        if (_.streams.length == 0) {
                            mkCanvas();
                            tanura
                                .eventHandler
                                .fire(
                                        'whiteboard_created',
                                        tanura.whiteboard.canvas.getSnapshot());
                        }

                        // Publish the local stream.
                        tanura
                            .nuve
                            .room
                            .publish(
                                    tanura.erizo.localStream,
                                    {maxVideoBW: 300});
                        subscribeToStreams(_.streams);

                        // Init done, run callback.
                        tanura.eventHandler.fire('client_initialized', document);
                    });

                // This will run whenever the client was successfully subscribed
                // to a new stream.
                tanura
                    .nuve
                    .room
                    .addEventListener('stream-subscribed', function(_) {
                        addStream(_.stream);
                    });

                // This will run whenever a new stream was added to the room.
                tanura
                    .nuve
                    .room
                    .addEventListener('stream-added', function(_) {
                        // Attach to the new stream.
                        subscribeToStreams([_.stream]);

                        tanura.eventHandler.fire('stream_added', _.stream);

                        // If the new stream is not our own stream.
                        if (
                            tanura.erizo.localStream.getID() != _.stream.getID()
                        ) {
                            // Send the newcomer the current state of the
                            // whiteboard.  This is wasteful as the new client
                            // will get the state by each other client, but
                            // I don't know a better way to do it.  The way
                            // forward will likely be to have the server control
                            // the whiteboard.
                            tanura.erizo.localStream.sendData({
                                type: 'canvas-init',
                                data: tanura.whiteboard.canvas.getSnapshot()
                            });
                        }
                    });

                // This will run whenever a stream fails.
                tanura.nuve.room.addEventListener('stream-failed', function(_) {
                    tanura.eventHandler.fire('stream_failed', _.stream);
                });

                // This will run whenever a stream disappeared from the room.
                tanura
                    .nuve
                    .room
                    .addEventListener('stream-removed', function(_) {
                        tanura.eventHandler.fire('stream_removed', _.stream);
                        document
                            .getElementById('videoEntry_' + _.stream.getID())
                            .remove();
                    });

                // This will run whenever a streamer cannot keep up the
                // bandwidth the room requires.
                tanura
                    .nuve
                    .room
                    .addEventListener('bandwidth-alert', function(_) {
                        tanura.eventHandler.fire('stream_throttled', _.stream);
                    });

                // This will run if connecting to the room has failed.
                tanura.nuve.room.addEventListener('room-error', function(_) {
                        tanura
                            .eventHandler
                            .fire('connection_failed', tanura.nuve.room);
                    });

                // This will run when the room is disconnected.
                tanura
                    .nuve
                    .room
                    .addEventListener('room-disconnected', function(_) {
                        tanura
                            .eventHandler
                            .fire('connection_closed', tanura.nuve.room);
                    });

                // All set. Connect to the room.
                tanura.nuve.room.connect();

                // Don't attach to the local stream. For development purposes it
                // is nicer if the users own stream is attached remotely too.
                //addStream(tanura.erizo.localStream, {speaker: false});
            }

            // Get local media.
            tanura.erizo.localStream = Erizo.Stream(streamOpts);
            tanura
                .erizo
                .localStream
                .addEventListener('access-accepted', function(_) {
                    tanura.eventHandler.fire('media_granted_preferred', streamOpts);
                    join();
                });
            tanura
                .erizo
                .localStream
                .addEventListener('access-denied', function(_) {
                    tanura.eventHandler.fire('media_denied_preferred', streamOpts);
                    tanura.erizo.localStream.close();
                    tanura.erizo.localStream = Erizo.Stream(fallbackStreamOpts);
                    tanura
                        .erizo
                        .localStream
                        .addEventListener('access-accepted', function(_) {
                            tanura
                                .eventHandler
                                .fire(
                                        'media_granted_fallback',
                                        fallbackStreamOpts);
                            join();
                        });
                    tanura
                        .erizo
                        .localStream
                        .addEventListener('access-denied', function(_) {
                            tanura
                                .eventHandler
                                .fire(
                                        'media_denied_fallback',
                                        fallbackStreamOpts);
                        });
                    tanura.erizo.localStream.init();
                });
            tanura.erizo.localStream.init();
        });
        req.open('POST', tanura.nuve.url + 'createToken/', true);
        req.setRequestHeader('Content-Type', 'application/json');

        // Send the room-token request.
        req.send(JSON.stringify({username: 'user', role: 'presenter'}));
    }

    connect();
}

// Run, if initialisation is done already.
if (tanura.options) { tanura.run(); }
<commit_msg>Fire tanura.eventHandler.events.whiteboard_loaded[].<commit_after>'use strict';

/*
 * Client entrypoint.
 *
 * This script contains all code necessary to bootstrap Tanura in a client.
 */

/**
 * Information about Nuve.
 */
tanura.nuve = {
    url: tanura.url + 'nuve/',
    room: null
};

/**
 * Information about Erizo.
 */
tanura.erizo = {
    localStream: null
};

/**
 * Information about the whiteboard.
 */
tanura.whiteboard = {
    url: tanura.url + 'whiteboard/',
    canvas: null
};

/**
 * Tanura init routine.
 */
tanura.run = function() {
    /**
     * Fake resize indicator.  Because of CSS bugs and limitations, Tanura will
     * sometimes have to change layout parameters manually in Js. As this
     * happens after the resize, a second resize event may be triggered to give
     * other Js code the ability to react to changes Tanura has made to the
     * layout. In this case, this variable will be set to true, to tell Tanura,
     * that the resize event was a fake resize event triggered by Tanura's own
     * code and should be ignored.
     */
    var fakeResize = false;

    /**
     * Options that should be used to stream.
     */
    var streamOpts = {
        audio: !! tanura.options.audio,
        video: !! tanura.options.video,
        data: true,
        screen: false,
    };

    /**
     * The stream options Tanura will fall back to.  These options will be used
     * when establishing a stream with the default options fails. This is
     * usually due to the user not granting the necessary permissions, the
     * browser not supporting all necessary features, or is blocking some of
     * them due to security concerns.
     */
    var fallbackStreamOpts = {
        audio: false,
        video: false,
        data: true,
        screen: false,
    };

    /**
     * This will initialize the whiteboard on the canvas from a given snapshot.
     */
    var mkCanvas = (_) => {
        tanura.whiteboard.canvas =
            LC.init(document.getElementById('whiteboard'), {snapshot: _});
        tanura
            .whiteboard
            .canvas
            .setTool(new LC.tools.Pencil(tanura.whiteboard.canvas));
        tanura.whiteboard.canvas.on('drawEnd', () =>
                tanura.erizo.localStream.sendData({
                    type: 'canvas-draw',
                    data: tanura.whiteboard.canvas.getSnapshot()
                }));
    }

    var body = document.getElementsByTagName('body')[0];

    // Manually calculate the size of some elements to work around flexbox
    // issues and limitations.
    var f = () => {
        if (!fakeResize) {

            // Wait for transitions.
            setTimeout(() => {
                // Fire the resize-event.
                tanura.eventHandler.fire('client_resized', document);

                // Pass another resize for Literallycanvas.
                fakeResize = true;
                dispatchEvent(new Event('resize'));
            }, 200);
        } else {
            fakeResize = false;
        }
    }
    tanura.throttle('resize', 'throttledResize');
    window.addEventListener('throttledResize', f);
    f();

    // Connect to Tanura.
    var connect = () => {
        tanura.eventHandler.fire('client_loaded', document);

        // Wait for Erizo to load.
        if (typeof Erizo === 'undefined' || Erizo == null) {
            setTimeout(connect, 100);
            return;
        }

        // Prepare a request for a room token.
        var req = new XMLHttpRequest();
        req.addEventListener('load', function() {
            var token = this.responseText;
            tanura.log(token);
            tanura.nuve.room = Erizo.Room({token: token});
            var join = function() {
                // Add a single stream to the DOM.
                var addStream = function(_, o) {
                    if (_.hasVideo()) {
                        var e = document.createElement('div');
                        e.setAttribute('id', 'videoEntry_' + _.getID());
                        document.getElementById('people').appendChild(e);
                        _.show('videoEntry_' + _.getID(), o);
                    }
                };

                // Subscribe to a list of streams.
                var subscribeToStreams = function(l) {
                    for (var i in l) {
                        tanura.nuve.room.subscribe(l[i]);
                        l[i].addEventListener(
                                    'bandwidth-alert',
                                    function(_) {
                                        tanura.log(
                                                'Bandwidth Alert',
                                                _.msg,
                                                _.bandwidth);
                                    });
                        l[i].addEventListener('stream-data', (_) => {
                            switch(_.msg.type) {
                                case 'canvas-clear':
                                    tanura.whiteboard.canvas.clear();
                                    tanura
                                        .eventHandler
                                        .fire(
                                                'whiteboard_cleared',
                                                tanura
                                                    .whiteboard
                                                    .canvas
                                                    .getSnapshot());
                                    break;
                                case 'canvas-draw':
                                    tanura
                                        .whiteboard
                                        .canvas
                                        .loadSnapshot(_.msg.data);
                                    tanura
                                        .eventHandler
                                        .fire('whiteboard_changed', _.msg.data);
                                    break;
                                case 'canvas-init':
                                    if (!tanura.whiteboard.canvas) {
                                        mkCanvas(_.msg.data);
                                        tanura
                                            .eventHandler
                                            .fire(
                                                    'whiteboard_loaded',
                                                    _.msg.data);
                                    }
                                    break;
                                default:
                                    tanura
                                        .eventHandler
                                        .fire('data_received', _.msg.data);
                            }
                        });
                    }
                };

                // This will run as soon as signalling is fully initialized.
                tanura
                    .nuve
                    .room
                    .addEventListener('room-connected', function(_) {
                        tanura
                            .eventHandler
                            .fire('connection_opened', tanura.nuve.room);

                        // If we are the only one in the room, add a fresh
                        // whiteboard.
                        if (_.streams.length == 0) {
                            mkCanvas();
                            tanura
                                .eventHandler
                                .fire(
                                        'whiteboard_created',
                                        tanura.whiteboard.canvas.getSnapshot());
                        }

                        // Publish the local stream.
                        tanura
                            .nuve
                            .room
                            .publish(
                                    tanura.erizo.localStream,
                                    {maxVideoBW: 300});
                        subscribeToStreams(_.streams);

                        // Init done, run callback.
                        tanura.eventHandler.fire('client_initialized', document);
                    });

                // This will run whenever the client was successfully subscribed
                // to a new stream.
                tanura
                    .nuve
                    .room
                    .addEventListener('stream-subscribed', function(_) {
                        addStream(_.stream);
                    });

                // This will run whenever a new stream was added to the room.
                tanura
                    .nuve
                    .room
                    .addEventListener('stream-added', function(_) {
                        // Attach to the new stream.
                        subscribeToStreams([_.stream]);

                        tanura.eventHandler.fire('stream_added', _.stream);

                        // If the new stream is not our own stream.
                        if (
                            tanura.erizo.localStream.getID() != _.stream.getID()
                        ) {
                            // Send the newcomer the current state of the
                            // whiteboard.  This is wasteful as the new client
                            // will get the state by each other client, but
                            // I don't know a better way to do it.  The way
                            // forward will likely be to have the server control
                            // the whiteboard.
                            tanura.erizo.localStream.sendData({
                                type: 'canvas-init',
                                data: tanura.whiteboard.canvas.getSnapshot()
                            });
                        }
                    });

                // This will run whenever a stream fails.
                tanura.nuve.room.addEventListener('stream-failed', function(_) {
                    tanura.eventHandler.fire('stream_failed', _.stream);
                });

                // This will run whenever a stream disappeared from the room.
                tanura
                    .nuve
                    .room
                    .addEventListener('stream-removed', function(_) {
                        tanura.eventHandler.fire('stream_removed', _.stream);
                        document
                            .getElementById('videoEntry_' + _.stream.getID())
                            .remove();
                    });

                // This will run whenever a streamer cannot keep up the
                // bandwidth the room requires.
                tanura
                    .nuve
                    .room
                    .addEventListener('bandwidth-alert', function(_) {
                        tanura.eventHandler.fire('stream_throttled', _.stream);
                    });

                // This will run if connecting to the room has failed.
                tanura.nuve.room.addEventListener('room-error', function(_) {
                        tanura
                            .eventHandler
                            .fire('connection_failed', tanura.nuve.room);
                    });

                // This will run when the room is disconnected.
                tanura
                    .nuve
                    .room
                    .addEventListener('room-disconnected', function(_) {
                        tanura
                            .eventHandler
                            .fire('connection_closed', tanura.nuve.room);
                    });

                // All set. Connect to the room.
                tanura.nuve.room.connect();

                // Don't attach to the local stream. For development purposes it
                // is nicer if the users own stream is attached remotely too.
                //addStream(tanura.erizo.localStream, {speaker: false});
            }

            // Get local media.
            tanura.erizo.localStream = Erizo.Stream(streamOpts);
            tanura
                .erizo
                .localStream
                .addEventListener('access-accepted', function(_) {
                    tanura.eventHandler.fire('media_granted_preferred', streamOpts);
                    join();
                });
            tanura
                .erizo
                .localStream
                .addEventListener('access-denied', function(_) {
                    tanura.eventHandler.fire('media_denied_preferred', streamOpts);
                    tanura.erizo.localStream.close();
                    tanura.erizo.localStream = Erizo.Stream(fallbackStreamOpts);
                    tanura
                        .erizo
                        .localStream
                        .addEventListener('access-accepted', function(_) {
                            tanura
                                .eventHandler
                                .fire(
                                        'media_granted_fallback',
                                        fallbackStreamOpts);
                            join();
                        });
                    tanura
                        .erizo
                        .localStream
                        .addEventListener('access-denied', function(_) {
                            tanura
                                .eventHandler
                                .fire(
                                        'media_denied_fallback',
                                        fallbackStreamOpts);
                        });
                    tanura.erizo.localStream.init();
                });
            tanura.erizo.localStream.init();
        });
        req.open('POST', tanura.nuve.url + 'createToken/', true);
        req.setRequestHeader('Content-Type', 'application/json');

        // Send the room-token request.
        req.send(JSON.stringify({username: 'user', role: 'presenter'}));
    }

    connect();
}

// Run, if initialisation is done already.
if (tanura.options) { tanura.run(); }
<|endoftext|>


<commit_before>// 1. Get required resources
var fs = require('fs'); //requires the node 'fs' library.
var clientData = require('./clients')
var targetCompany = process.argv[2] //search parameter is the 3rd array item.
console.log(targetCompany);

// 2. load the clients.json file into the var 'clientData' (using absolute path).
// const clientData = JSON.parse(fs.readFileSync('./clients.json', 'utf8')); //

function byCompany(clientObj, index, clientData) {
    // console.log(clientObj);
  if (clientObj.company == targetCompany) {
        return true;
    }
    else {
         return false;
     }}

var clientsFound = clientData.filter(byCompany);
// console.log(JSON.parse(clientsFound,));
console.log(clientsFound); // print all the values of clientsFound

for (i in clientsFound){
    console.log(i);
    for (key in clientsFound[i]){
      if(key !== 'no_employees' && key !== 'phone' && key !== 'created_at') {
        console.log( key + ": " + clientsFound[i][key]);
      }

    }
}

// Return these values
        // clientsFound.id
        // clientsFound.rep_name
        // clientsFound.company
        // clientsFound.city
        // clientsFound.state

        <commit_msg>SearchByCompany.js complete.<commit_after>// 1. Get required resources
var fs = require('fs'); //requires the node 'fs' library.
var clientData = require('./clients')
var targetCompany = process.argv[2] //search parameter is the 3rd array item.
console.log(targetCompany);

// 2. load the clients.json file into the var 'clientData' (using absolute path).
// const clientData = JSON.parse(fs.readFileSync('./clients.json', 'utf8')); //

function byCompany(clientObj, index, clientData) {
    // console.log(clientObj);
  if (clientObj.company == targetCompany) {
        return true;
    }
    else {
         return false;
     }}

var clientsFound = clientData.filter(byCompany);
// console.log(JSON.parse(clientsFound,));
console.log(clientsFound); // print all the values of clientsFound

for (i in clientsFound){
    console.log(i);
    for (key in clientsFound[i]){
      if(key !== 'no_employees' && key !== 'phone' && key !== 'created_at') { // filters out unwanted keys.  NOTE: Must use '&&'!  '||' ("OR" operator) does not work in JS 'if'.  This is NOT SQL.
        console.log( key + ": " + clientsFound[i][key]);
      }

    }
}

// Return these values
        // clientsFound.id
        // clientsFound.rep_name
        // clientsFound.company
        // clientsFound.city
        // clientsFound.state

        <|endoftext|>


<commit_before>import React from 'react';
import _ from 'lodash';

import SuppliedForm from './SuppliedForm';

import LabeledForm from './LabeledForm'

function KbForm(component = LabeledForm) {
  this.options = {
    component,
    defaultValue: {}
  };
}

const setters = [ 'component', 'defaultValue', 'fields', 'render', 'supplier' ];

setters.forEach(fieldName => {
  KbForm.prototype[fieldName] = function(value) {
    this.options[fieldName] = value;
    return this;
  };
});

KbForm.prototype.set = function(fieldName, value) {
  this.options[fieldName] = value;
  return this;
};

KbForm.prototype._render = function(modelOrId, onSubmit, onChange) {
  const RenderComponent = _.defaultTo(this.options.render, this.options.component);
  let model = _.isPlainObject(modelOrId) ? modelOrId : undefined;
  if (_.isUndefined(model) && _.isString(modelOrId) && !_.isUndefined(this.options.supplier)) {
    return (<SuppliedForm component={RenderComponent} model={modelOrId} options={this.options} onSubmit={onSubmit} onChange={onChange} />);
  }
  model = _.defaultTo(model, this.options.defaultValue);
  return (<RenderComponent options={this.options} model={model} onSubmit={onSubmit} onChange={onChange} />);
};

export default (component) => new KbForm(component);
<commit_msg>Adding default onSubmit handler for supplied forms<commit_after>import React from 'react';
import _ from 'lodash';

import SuppliedForm from './SuppliedForm';

import LabeledForm from './LabeledForm'

function KbForm(component = LabeledForm) {
  this.options = {
    component,
    defaultValue: {}
  };
}

const setters = [ 'component', 'defaultValue', 'fields', 'render', 'supplier' ];

setters.forEach(fieldName => {
  KbForm.prototype[fieldName] = function(value) {
    this.options[fieldName] = value;
    return this;
  };
});

KbForm.prototype.set = function(fieldName, value) {
  this.options[fieldName] = value;
  return this;
};

KbForm.prototype._render = function(modelOrId, onSubmit, onChange) {
  const RenderComponent = _.defaultTo(this.options.render, this.options.component),
      supplier = this.options.supplier;
  let model = _.isPlainObject(modelOrId) ? modelOrId : undefined;
  if (!_.isUndefined(supplier)) {
    onSubmit = _.defaultTo(onSubmit, supplier.save);
  }
  if (_.isUndefined(model) && _.isString(modelOrId) && !_.isUndefined(supplier)) {
    return (<SuppliedForm component={RenderComponent} model={modelOrId} options={this.options} onSubmit={onSubmit} onChange={onChange} />);
  }
  model = _.defaultTo(model, this.options.defaultValue);
  return (<RenderComponent options={this.options} model={model} onSubmit={onSubmit} onChange={onChange} />);
};

export default (component) => new KbForm(component);
<|endoftext|>


<commit_before>Vps.EyeCandy.List.Plugins.ActiveListener.LargeContent = Ext.extend(Vps.EyeCandy.List.Plugins.Abstract, {
    largeContentSelector: '.largeContent',
    largeContainerSelector: '.listSwitchLargeContent',
    transition: 'fade',
    //transitionConfig: {},
    init: function() {
        this.list.on('activeChanged', function(item) {
            console.log('activeChanged', item);
            this._activate(item);
        }, this);

        this.largeContainer = this.list.el.child(this.largeContainerSelector);
        this.largeContainer.select('*').each(function(i) { i.remove(); }, this);

        this.largeContent = {};
        this.list.getItems().each(function(i) {
            var largeContent = i.el.child(this.largeContentSelector);
            this.largeContainer.appendChild(largeContent);
            largeContent.enableDisplayMode('block');
            largeContent.hide();
            this.largeContent[i.id] = largeContent;
        }, this);
    },

    render: function() {
        this.list.setActiveItem(this.list.getFirstItem());
    },

    _activate: function(item)
    {
        var activeEl = null;
        if (this.activeItem) activeEl = this.largeContent[this.activeItem.id];
        var nextEl = this.largeContent[item.id];

        if (!activeEl) {
            //first, no fx
            nextEl.show();
        } else {
            if (this.transition == 'fade') {
                activeEl.dom.style.zIndex = 2;
                activeEl.fadeOut(Ext.applyIf({
                    useDisplay: true
                }, this.transitionConfig));

                nextEl.dom.style.zIndex = 1;
                nextEl.fadeIn(Ext.applyIf({
                    useDisplay: true
                }, this.transitionConfig));
            } else if (this.transition == 'slide') {
                activeEl.slideOut(
                    this.activeItem.listIndex < item.listIndex ? 'l' : 'r',
                    Ext.applyIf({
                      remove: false,
                      useDisplay: true
                    }, this.transitionConfig)
                );
                nextEl.slideIn(
                    this.activeItem.listIndex < item.listIndex ? 'r' : 'l',
                    Ext.applyIf({
                      remove: false,
                      useDisplay: true
                    }, this.transitionConfig)
                );
            } else {
                //default, no fx; switch hard
                activeEl.hide();
                nextEl.show();
            }
        }

        this.activeItem = item;
    }
});
<commit_msg>silence<commit_after>Vps.EyeCandy.List.Plugins.ActiveListener.LargeContent = Ext.extend(Vps.EyeCandy.List.Plugins.Abstract, {
    largeContentSelector: '.largeContent',
    largeContainerSelector: '.listSwitchLargeContent',
    transition: 'fade',
    //transitionConfig: {},
    init: function() {
        this.list.on('activeChanged', function(item) {
            this._activate(item);
        }, this);

        this.largeContainer = this.list.el.child(this.largeContainerSelector);
        this.largeContainer.select('*').each(function(i) { i.remove(); }, this);

        this.largeContent = {};
        this.list.getItems().each(function(i) {
            var largeContent = i.el.child(this.largeContentSelector);
            this.largeContainer.appendChild(largeContent);
            largeContent.enableDisplayMode('block');
            largeContent.hide();
            this.largeContent[i.id] = largeContent;
        }, this);
    },

    render: function() {
        this.list.setActiveItem(this.list.getFirstItem());
    },

    _activate: function(item)
    {
        var activeEl = null;
        if (this.activeItem) activeEl = this.largeContent[this.activeItem.id];
        var nextEl = this.largeContent[item.id];

        if (!activeEl) {
            //first, no fx
            nextEl.show();
        } else {
            if (this.transition == 'fade') {
                activeEl.dom.style.zIndex = 2;
                activeEl.fadeOut(Ext.applyIf({
                    useDisplay: true
                }, this.transitionConfig));

                nextEl.dom.style.zIndex = 1;
                nextEl.fadeIn(Ext.applyIf({
                    useDisplay: true
                }, this.transitionConfig));
            } else if (this.transition == 'slide') {
                activeEl.slideOut(
                    this.activeItem.listIndex < item.listIndex ? 'l' : 'r',
                    Ext.applyIf({
                      remove: false,
                      useDisplay: true
                    }, this.transitionConfig)
                );
                nextEl.slideIn(
                    this.activeItem.listIndex < item.listIndex ? 'r' : 'l',
                    Ext.applyIf({
                      remove: false,
                      useDisplay: true
                    }, this.transitionConfig)
                );
            } else {
                //default, no fx; switch hard
                activeEl.hide();
                nextEl.show();
            }
        }

        this.activeItem = item;
    }
});
<|endoftext|>


<commit_before>const pg = require('pg');

pg.defaults.ssl = true;
const db = new pg.Pool({
  host: process.env.DATABASE_URL,
});

class Predicate {
  constructor(key, operator, value) {
    this.key = key;
    this.operator = operator;
    this.value = value;
    this.adjoined = [];
  }

  and(other) {
    this.adjoined.push({
      conj: 'AND',
      obj: other,
    });
    return other;
  }

  or(other) {
    this.adjoined.push({
      conj: 'OR',
      obj: other,
    });
    return other;
  }

  compile() {
    let strVal = `&$${this.operator}$&$`;
    const params = [this.key, this.value];
    for (const adjoined of this.adjoined) {
      const compiled = adjoined.compile();
      if (adjoined.obj.adjoined.length > 0) {
        strVal += ` ${adjoined.conj} (${compiled.strVal})`;
      } else {
        strVal += ` ${adjoined.conj} ${compiled.strVal}}`;
      }
      for (const param of compiled.params) {
        params.push(param);
      }
    }
    return {
      strVal: strVal,
      params: params,
      source: this,
    };
  }
}

class QueryBuilder {
  constructor(table, fields) {
    this.table = table;
    this.fields = fields;
    this.predicate = null;
  }

  where(predicate) {
    this.predicate = predicate;
    return this;
  }

  execute() {
    let query = `SELECT ${this.fields.map((f, i) => `$${i}`).join(', ')}` +
        ` FROM ${this.table.name}`;
    if (this.predicate) {
      const compiled = this.predicate.compile();
      for (const param of compiled) {
        this.fields.push(param);
      }
      let i = this.fields.length + 1;
      compiled.strVal = compiled.strVal.replace('&$', () => i++);
      query += ` WHERE ${compiled.strVal}`;
    }
    return this.table.db.query(query, this.fields);
  }
}

class Table {
  constructor(db, name) {
    this.db = db;
    this.name = name;
  }

  select(fields) {
    return new QueryBuilder(this, fields);
  }

  insert(values) {
    return this.db.query(`INSERT INTO ${this.name}` +
      ` VALUES(${values.map((p, i) => `$${i}`).join(', ')})`, values);
  }
}

function getTable(name) {
  return new Table(db, name);
}

const tables = ['users', 'sets', 'notes'].reduce((acc, cur) => {
  acc[cur] = getTable(cur);
  return acc;
}, {});

module.exports = {
  Table: Table,
  QueryBuilder: QueryBuilder,
  Predicate: Predicate,
  tables: tables,
  init: db.connect,
};
<commit_msg>Pass connection string instead of host<commit_after>const pg = require('pg');

pg.defaults.ssl = true;
const db = new pg.Pool({
  connectionString: process.env.DATABASE_URL,
});

class Predicate {
  constructor(key, operator, value) {
    this.key = key;
    this.operator = operator;
    this.value = value;
    this.adjoined = [];
  }

  and(other) {
    this.adjoined.push({
      conj: 'AND',
      obj: other,
    });
    return other;
  }

  or(other) {
    this.adjoined.push({
      conj: 'OR',
      obj: other,
    });
    return other;
  }

  compile() {
    let strVal = `&$${this.operator}$&$`;
    const params = [this.key, this.value];
    for (const adjoined of this.adjoined) {
      const compiled = adjoined.compile();
      if (adjoined.obj.adjoined.length > 0) {
        strVal += ` ${adjoined.conj} (${compiled.strVal})`;
      } else {
        strVal += ` ${adjoined.conj} ${compiled.strVal}}`;
      }
      for (const param of compiled.params) {
        params.push(param);
      }
    }
    return {
      strVal: strVal,
      params: params,
      source: this,
    };
  }
}

class QueryBuilder {
  constructor(table, fields) {
    this.table = table;
    this.fields = fields;
    this.predicate = null;
  }

  where(predicate) {
    this.predicate = predicate;
    return this;
  }

  execute() {
    let query = `SELECT ${this.fields.map((f, i) => `$${i}`).join(', ')}` +
        ` FROM ${this.table.name}`;
    if (this.predicate) {
      const compiled = this.predicate.compile();
      for (const param of compiled) {
        this.fields.push(param);
      }
      let i = this.fields.length + 1;
      compiled.strVal = compiled.strVal.replace('&$', () => i++);
      query += ` WHERE ${compiled.strVal}`;
    }
    return this.table.db.query(query, this.fields);
  }
}

class Table {
  constructor(db, name) {
    this.db = db;
    this.name = name;
  }

  select(fields) {
    return new QueryBuilder(this, fields);
  }

  insert(values) {
    return this.db.query(`INSERT INTO ${this.name}` +
      ` VALUES(${values.map((p, i) => `$${i}`).join(', ')})`, values);
  }
}

function getTable(name) {
  return new Table(db, name);
}

const tables = ['users', 'sets', 'notes'].reduce((acc, cur) => {
  acc[cur] = getTable(cur);
  return acc;
}, {});

module.exports = {
  Table: Table,
  QueryBuilder: QueryBuilder,
  Predicate: Predicate,
  tables: tables,
  init: db.connect,
};
<|endoftext|>


<commit_before>const { DebuggerClient } = require("devtools-sham/shared/client/main");
const { DebuggerTransport } = require("devtools-sham/transport/transport");
const WebSocketDebuggerTransport = require("devtools/shared/transport/websocket-transport");
const { TargetFactory } = require("devtools-sham/client/framework/target");
const defer = require("../utils/defer");
const { getValue } = require("../feature");
const { Tab } = require("../types");
const { setupCommands, clientCommands } = require("./firefox/commands");
const { setupEvents, clientEvents } = require("./firefox/events");

let debuggerClient = null;
let threadClient = null;
let tabTarget = null;

function getThreadClient() {
  return threadClient;
}

function setThreadClient(client) {
  threadClient = client;
}

function getTabTarget() {
  return tabTarget;
}

function setTabTarget(target) {
  tabTarget = target;
}

function lookupTabTarget(tab) {
  const options = { client: debuggerClient, form: tab, chrome: false };
  return TargetFactory.forRemoteTab(options);
}

function createTabs(tabs) {
  return tabs.map(tab => {
    return Tab({
      title: tab.title,
      url: tab.url,
      id: tab.actor,
      tab,
      browser: "firefox"
    });
  });
}

function connectClient() {
  const deferred = defer();
  let isConnected = false;
  const useProxy = !getValue("firefox.webSocketConnection");
  const portPref = useProxy ? "firefox.proxyPort" : "firefox.webSocketPort";
  const webSocketPort = getValue(portPref);

  const socket = new WebSocket(`ws://${document.location.hostname}:${webSocketPort}`);
  const transport = useProxy ?
    new DebuggerTransport(socket) : new WebSocketDebuggerTransport(socket);
  debuggerClient = new DebuggerClient(transport);

  // TODO: the timeout logic should be moved to DebuggerClient.connect.
  setTimeout(() => {
    if (isConnected) {
      return;
    }

    deferred.resolve([]);
  }, 1000);

  debuggerClient.connect().then(() => {
    isConnected = true;
    return debuggerClient.listTabs().then(response => {
      deferred.resolve(createTabs(response.tabs));
    });
  }).catch(err => {
    console.log(err);
    deferred.reject();
  });

  return deferred.promise;
}

function connectTab(tab) {
  return new Promise((resolve, reject) => {
    window.addEventListener("beforeunload", () => {
      getTabTarget() && getTabTarget().destroy();
    });

    lookupTabTarget(tab).then(target => {
      tabTarget = target;
      target.activeTab.attachThread({}, (res, _threadClient) => {
        threadClient = _threadClient;
        threadClient.resume();
        resolve();
      });
    });
  });
}

function initPage(actions) {
  tabTarget = getTabTarget();
  threadClient = getThreadClient();

  setupCommands({ threadClient, tabTarget });

  tabTarget.on("will-navigate", actions.willNavigate);
  tabTarget.on("navigate", actions.navigate);

  // Listen to all the requested events.
  setupEvents({ threadClient, actions });
  Object.keys(clientEvents).forEach(eventName => {
    threadClient.addListener(eventName, clientEvents[eventName]);
  });

  // In Firefox, we need to initially request all of the sources which
  // makes the server iterate over them and fire individual
  // `newSource` notifications. We don't need to do anything with the
  // response since `newSource` notifications are fired.
  threadClient.getSources();
}

module.exports = {
  connectClient,
  connectTab,
  clientCommands,
  getThreadClient,
  setThreadClient,
  getTabTarget,
  setTabTarget,
  initPage
};
<commit_msg>Disable source maps + blackboxing (#490)<commit_after>const { DebuggerClient } = require("devtools-sham/shared/client/main");
const { DebuggerTransport } = require("devtools-sham/transport/transport");
const WebSocketDebuggerTransport = require("devtools/shared/transport/websocket-transport");
const { TargetFactory } = require("devtools-sham/client/framework/target");
const defer = require("../utils/defer");
const { getValue } = require("../feature");
const { Tab } = require("../types");
const { setupCommands, clientCommands } = require("./firefox/commands");
const { setupEvents, clientEvents } = require("./firefox/events");

let debuggerClient = null;
let threadClient = null;
let tabTarget = null;

function getThreadClient() {
  return threadClient;
}

function setThreadClient(client) {
  threadClient = client;
}

function getTabTarget() {
  return tabTarget;
}

function setTabTarget(target) {
  tabTarget = target;
}

function lookupTabTarget(tab) {
  const options = { client: debuggerClient, form: tab, chrome: false };
  return TargetFactory.forRemoteTab(options);
}

function createTabs(tabs) {
  return tabs.map(tab => {
    return Tab({
      title: tab.title,
      url: tab.url,
      id: tab.actor,
      tab,
      browser: "firefox"
    });
  });
}

function connectClient() {
  const deferred = defer();
  let isConnected = false;
  const useProxy = !getValue("firefox.webSocketConnection");
  const portPref = useProxy ? "firefox.proxyPort" : "firefox.webSocketPort";
  const webSocketPort = getValue(portPref);

  const socket = new WebSocket(`ws://${document.location.hostname}:${webSocketPort}`);
  const transport = useProxy ?
    new DebuggerTransport(socket) : new WebSocketDebuggerTransport(socket);
  debuggerClient = new DebuggerClient(transport);

  // TODO: the timeout logic should be moved to DebuggerClient.connect.
  setTimeout(() => {
    if (isConnected) {
      return;
    }

    deferred.resolve([]);
  }, 1000);

  debuggerClient.connect().then(() => {
    isConnected = true;
    return debuggerClient.listTabs().then(response => {
      deferred.resolve(createTabs(response.tabs));
    });
  }).catch(err => {
    console.log(err);
    deferred.reject();
  });

  return deferred.promise;
}

function connectTab(tab) {
  return new Promise((resolve, reject) => {
    window.addEventListener("beforeunload", () => {
      getTabTarget() && getTabTarget().destroy();
    });

    lookupTabTarget(tab).then(target => {
      tabTarget = target;
      target.activeTab.attachThread({}, (res, _threadClient) => {
        threadClient = _threadClient;
        threadClient.resume();
        resolve();
      });
    });
  });
}

function initPage(actions) {
  tabTarget = getTabTarget();
  threadClient = getThreadClient();

  setupCommands({ threadClient, tabTarget });

  tabTarget.on("will-navigate", actions.willNavigate);
  tabTarget.on("navigate", actions.navigate);

  // Listen to all the requested events.
  setupEvents({ threadClient, actions });
  Object.keys(clientEvents).forEach(eventName => {
    threadClient.addListener(eventName, clientEvents[eventName]);
  });

  threadClient.reconfigure({
    "useSourceMaps": false,
    "autoBlackBox": false
  });

  // In Firefox, we need to initially request all of the sources which
  // makes the server iterate over them and fire individual
  // `newSource` notifications. We don't need to do anything with the
  // response since `newSource` notifications are fired.
  threadClient.getSources();
}

module.exports = {
  connectClient,
  connectTab,
  clientCommands,
  getThreadClient,
  setThreadClient,
  getTabTarget,
  setTabTarget,
  initPage
};
<|endoftext|>


<commit_before>//= require "codemirror"
//= require "mobileCodeMirror"
//= require "library"
//= require "unsaved"
//= require "panel"
//= require "../render/live"
//= require "../render/console"
//= require "keycontrol"
//= require "../processors/processor"

var panels = {};

panels.getVisible = function () {
  var panels = this.panels,
      visible = [];
  for (var panel in panels) {
    if (panels[panel].visible) visible.push(panels[panel]);
  }
  return visible;
};

panels.save = function () {
  var visible = this.getVisible(),
      state = {},
      panel,
      left = '',
      width = window.innerWidth;

  for (var i = 0; i < visible.length; i++) {
    panel = visible[i];
    left = panel.$el.css('left');
    if (left.indexOf('%') === -1) {
      // convert the pixel to relative - this is because jQuery pulls
      // % for Webkit based, but px for Firefox & Opera. Cover our bases
      left = (parseFloat(left)  / width * 100) + '%';
    }
    state[panel.name] = left;
  }

  localStorage.setItem('jsbin.panels', JSON.stringify(state));
}

panels.restore = function () {
  // if there are panel names on the hash (v2 of jsbin) or in the jquery (v3)
  // then restore those specific panels and evenly distribute them.
  var open = [],
      location = window.location,
      search = location.search.substring(1),
      hash = location.hash.substring(1),
      toopen = search || hash ? (search || hash).split(',') : jsbin.settings.panels || [],
      state = JSON.parse(localStorage.getItem('jsbin.panels') || 'null'),
      name = '',
      i = 0,
      panel = null,
      init = [],
      panelURLValue = '',
      openWithSameDimensions = false,
      width = window.innerWidth,
      deferredCodeInsert = '',
      focused = !!sessionStorage.getItem('panel');

  if (history.replaceState && location.pathname.indexOf('/edit') !== -1) {
    history.replaceState(null, '', jsbin.getURL() + (jsbin.getURL() === jsbin.root ? '' : '/edit'));
  }

  // otherwise restore the user's regular settings
  // also set a flag indicating whether or not we should save the panel settings
  // this is based on whether they're on jsbin.com or if they're on an existing
  // bin. Also, if they hit save - *always* save their layout.
  if (location.pathname && location.pathname !== '/') {
    panels.saveOnExit = false;
  } else {
    panels.saveOnExit = true;
  }

  // TODO decide whether the above code I'm trying too hard.

  /* Boot code */
  // then allow them to view specific panels based on comma separated hash fragment
  if (toopen.length) {
    for (name in state) {
      if (toopen.indexOf(name) !== -1) {
        i++;
      }
    }

    if (i === toopen.length) openWithSameDimensions = true;

    for (i = 0; i < toopen.length; i++) {
      panelURLValue = '';
      name = toopen[i];

      // if name contains an `=` it means we also need to set that particular panel to that code
      if (name.indexOf('=') !== -1) {
        panelURLValue = name.substring(name.indexOf('=') + 1);
        name = name.substring(0, name.indexOf('='));
      }

      if (panels.panels[name]) {
        panel = panels.panels[name];
        // console.log(name, 'width', state[name], width * parseFloat(state[name]) / 100);
        if (panel.editor && panelURLValue) {
          panel.setCode(decodeURIComponent(panelURLValue));
        }

        if (openWithSameDimensions && toopen.length > 1) {
          panel.show(width * parseFloat(state[name]) / 100);
        } else {
          panel.show();
        }
        init.push(panel);
      } else if (name && panelURLValue) { // TODO support any varible insertion
        (function (name, panelURLValue) {
          var todo = ['html', 'javascript', 'css'];

          var deferredInsert = function (event, data) {
            var code, parts, panel = panels.panels[data.panelId] || {};

            if (data.panelId && panel.editor && panel.ready === true) {
              todo.splice(todo.indexOf(data.panelId), 1);
              try {
                code = panel.getCode();
              } catch (e) {
                // this really shouldn't happen
                // console.error(e);
              }
              if (code.indexOf('%' + name + '%') !== -1) {
                parts = code.split('%' + name + '%');
                code = parts[0] + decodeURIComponent(panelURLValue) + parts[1];
                panel.setCode(code);
                $document.unbind('codeChange', deferredInsert);
              }
            }

            if (todo.length === 0) {
              $document.unbind('codeChange', deferredInsert);
            }
          };

          $document.bind('codeChange', deferredInsert);
        }(name, panelURLValue));
      }
    }

    // support the old jsbin v1 links directly to the preview
    if (toopen.length === 1 && toopen[0] === 'preview') {
      panels.panels.live.show();
    }

    if (!openWithSameDimensions) this.distribute();
  } else {
    for (name in state) {
      panels.panels[name].show(width * parseFloat(state[name]) / 100);
    }
  }

  // now restore any data from sessionStorage
  // TODO add default templates somewhere
  // var template = {};
  // for (name in this.panels) {
  //   panel = this.panels[name];
  //   if (panel.editor) {
  //     // panel.setCode(sessionStorage.getItem('jsbin.content.' + name) || template[name]);
  //   }
  // }

  for (i = 0; i < init.length; i++) {
    init[i].init();
  }

  var visible = panels.getVisible();
  if (visible.length) {
    $body.addClass('panelsVisible');
    if (!focused) {
      visible[0].show();
    }
  }

};

panels.savecontent = function () {
  // loop through each panel saving it's content to sessionStorage
  var name, panel;
  for (name in this.panels) {
    panel = this.panels[name];
    if (panel.editor) sessionStorage.setItem('jsbin.content.' + name, panel.getCode());
  }
};

panels.focus = function (panel) {
  this.focused = panel;
  if (panel) {
    $('.panel').removeClass('focus').filter('.' + panel.id).addClass('focus');
  }
}

// evenly distribute the width of all the visible panels
panels.distribute = function () {
  var visible = $('#source .panelwrapper:visible'),
      width = 100,
      height = 0,
      innerW = window.innerWidth - (visible.length - 1), // to compensate for border-left
      innerH = $('#source').outerHeight(),
      left = 0,
      right = 0,
      top = 0,
      panel,
      nestedPanels = [];

  if (visible.length) {
    $body.addClass('panelsVisible');

    // visible = visible.sort(function (a, b) {
    //   return a.order < b.order ? -1 : 1;
    // });

    width = 100 / visible.length;
    for (var i = 0; i < visible.length; i++) {
      panel = $.data(visible[i], 'panel');
      right = 100 - (width * (i+1));
      panel.$el.css({ top: 0, bottom: 0, left: left + '%', right: right + '%' });
      panel.splitter.trigger('init', innerW * left/100);
      panel.splitter[i == 0 ? 'hide' : 'show']();
      left += width;

      nestedPanels = $(visible[i]).find('.panel');
      if (nestedPanels.length > 1) {
        top = 0;
        nestedPanels = nestedPanels.filter(':visible');
        height = 100 / nestedPanels.length;
        nestedPanels.each(function (i) {
          bottom = 100 - (height * (i+1));
          var panel = jsbin.panels.panels[$.data(this, 'name')];
          // $(this).css({ top: top + '%', bottom: bottom + '%' });
          $(this).css('top', top + '%');
          $(this).css('bottom', bottom + '%' );
          if (panel.splitter.hasClass('vertical')) {
            panel.splitter.trigger('init', innerH * top/100);
            panel.splitter[i == 0 ? 'hide' : 'show']();
          }
          top += height;
        });
      }
    }
  } else {
    $('#history').show();
    setTimeout(function () {
      $body.removeClass('panelsVisible');
    }, 100); // 100 is on purpose to add to the effect of the reveal
  }
};

panels.show = function (panelId) {
  this.panels[panelId].show();
  if (this.panels[panelId].editor) {
    this.panels[panelId].editor.focus();
  }
  this.panels[panelId].focus();
}

panels.hideAll = function () {
  var visible = panels.getVisible(),
      i = visible.length;
  while (i--) {
    visible[i].hide();
  }
}

// dirty, but simple
Panel.prototype.distribute = function () {
  panels.distribute();
};

jsbin.panels = panels;

var ignoreDuringLive = /^\s*(while|do|for)[\s*|$]/;

var panelInit = {
  html: function () {
    return new Panel('html', { editor: true, label: 'HTML' });
  },
  css: function () {
    return new Panel('css', { editor: true, label: 'CSS' });
  },
  javascript: function () {
    return new Panel('javascript', { editor: true, label: 'JavaScript' });
  },
  console: function () {
    // hide and show callbacks registered in console.js
    return new Panel('console', { label: 'Console' });
  },
  live: function () {
    function show() {
      // var panel = this;
      if (panels.ready) {
        renderLivePreview();
      }
    }

    function hide() {
      // detroy the iframe if we hide the panel
      // note: $live is defined in live.js
      if (panels.panels.console.visible === false) {
        $live.find('iframe').remove();
      }
    }

    return new Panel('live', { label: 'Output', show: show, hide: hide });
  }
};

var editors = panels.panels = {};

// show all panels (change the order to control the panel order)
editors.html = panelInit.html();
editors.css = panelInit.css();
editors.javascript = panelInit.javascript();
editors.console = panelInit.console();
upgradeConsolePanel(editors.console);
editors.live = panelInit.live();

// jsconsole.init(); // sets up render functions etc.
editors.live.settings.render = function (showAlerts) {
  if (panels.ready) {
    renderLivePreview(showAlerts);
    editors.console.render();
  }
};

// IMPORTANT this is nasty, but the sequence is important, because the
// show/hide method is being called as the panels are being called as
// the panel is setup - so we hook these handlers on *afterwards*.
panels.update = function () {
  var visiblePanels = panels.getVisible(),
      visible = [],
      i = 0;
  for (i = 0; i < visiblePanels.length; i++) {
    visible.push(visiblePanels[i].name);
  }

  // if (history.replaceState) {
  //   history.replaceState(null, null, '?' + visible.join(','));
  // } else {
  //   // :( this will break jquery mobile - but we're talking IE only at this point, right?
  //   location.hash = '#' + visible.join(',');
  // }
}

Panel.prototype._show = Panel.prototype.show;
Panel.prototype.show = function () {
  this._show.apply(this, arguments);
  panels.update();
}

Panel.prototype._hide = Panel.prototype.hide;
Panel.prototype.hide = function () {
  this._hide.apply(this, arguments);
  panels.update();
}

panels.allEditors = function (fn) {
  var panelId, panel;
  for (panelId in panels.panels) {
    panel = panels.panels[panelId];
    if (panel.editor) fn(panel);
  }
};

panels.restore();
panels.focus(panels.getVisible()[0] || null);

// allow panels to be reordered - TODO re-enable
(function () {
  return; // disabled for now

  var panelsEl = document.getElementById('panels'),
      moving = null;

  panelsEl.ondragstart = function (e) {
    if (e.target.nodeName == 'A') {
      moving = e.target;
    } else {
      return false;
    }
  };

  panelsEl.ondragover = function (e) {
    return false;
  };

  panelsEl.ondragend = function () {
    moving = false;
    return false;
  };

  panelsEl.ondrop = function (e) {
    if (moving) {

    }
    return false;
  };

});

var editorsReady = setInterval(function () {
  var ready = true,
      resizeTimer = null,
      panel,
      panelId;

  for (panelId in panels.panels) {
    panel = panels.panels[panelId];
    if (panel.visible && !panel.ready) ready = false;
  }

  panels.ready = ready;

  if (ready) {
    clearInterval(editorsReady);
    // panels.ready = true;
    // if (typeof editors.onReady == 'function') editors.onReady();
    // panels.distribute();

    // if live is visible, render it
    if (panels.panels.live.visible) {
      panels.panels.live.render(true);
    }

    if (panels.panels.console.visible) {
      panels.panels.console.render();
    }

    $(window).resize(function () {
      clearTimeout(resizeTimer);
      resizeTimer = setTimeout(function () {
        $document.trigger('sizeeditors');
      }, 100);
    });

    $document.trigger('sizeeditors');
    $document.trigger('jsbinReady');
  }
}, 100);
<commit_msg>Fixed IE8 window restore bug<commit_after>//= require "codemirror"
//= require "mobileCodeMirror"
//= require "library"
//= require "unsaved"
//= require "panel"
//= require "../render/live"
//= require "../render/console"
//= require "keycontrol"
//= require "../processors/processor"

var panels = {};

var $window = $(window);

panels.getVisible = function () {
  var panels = this.panels,
      visible = [];
  for (var panel in panels) {
    if (panels[panel].visible) visible.push(panels[panel]);
  }
  return visible;
};

panels.save = function () {
  var visible = this.getVisible(),
      state = {},
      panel,
      left = '',
      width = $window.width();

  for (var i = 0; i < visible.length; i++) {
    panel = visible[i];
    left = panel.$el.css('left');
    if (left.indexOf('%') === -1) {
      // convert the pixel to relative - this is because jQuery pulls
      // % for Webkit based, but px for Firefox & Opera. Cover our bases
      left = (parseFloat(left)  / width * 100) + '%';
    }
    state[panel.name] = left;
  }

  localStorage.setItem('jsbin.panels', JSON.stringify(state));
}

panels.restore = function () {
  // if there are panel names on the hash (v2 of jsbin) or in the jquery (v3)
  // then restore those specific panels and evenly distribute them.
  var open = [],
      location = window.location,
      search = location.search.substring(1),
      hash = location.hash.substring(1),
      toopen = search || hash ? (search || hash).split(',') : jsbin.settings.panels || [],
      state = JSON.parse(localStorage.getItem('jsbin.panels') || 'null'),
      name = '',
      i = 0,
      panel = null,
      init = [],
      panelURLValue = '',
      openWithSameDimensions = false,
      width = $window.width(),
      deferredCodeInsert = '',
      focused = !!sessionStorage.getItem('panel');

  if (history.replaceState && location.pathname.indexOf('/edit') !== -1) {
    history.replaceState(null, '', jsbin.getURL() + (jsbin.getURL() === jsbin.root ? '' : '/edit'));
  }

  // otherwise restore the user's regular settings
  // also set a flag indicating whether or not we should save the panel settings
  // this is based on whether they're on jsbin.com or if they're on an existing
  // bin. Also, if they hit save - *always* save their layout.
  if (location.pathname && location.pathname !== '/') {
    panels.saveOnExit = false;
  } else {
    panels.saveOnExit = true;
  }

  // TODO decide whether the above code I'm trying too hard.

  /* Boot code */
  // then allow them to view specific panels based on comma separated hash fragment
  if (toopen.length) {
    for (name in state) {
      if (toopen.indexOf(name) !== -1) {
        i++;
      }
    }

    if (i === toopen.length) openWithSameDimensions = true;

    for (i = 0; i < toopen.length; i++) {
      panelURLValue = '';
      name = toopen[i];

      // if name contains an `=` it means we also need to set that particular panel to that code
      if (name.indexOf('=') !== -1) {
        panelURLValue = name.substring(name.indexOf('=') + 1);
        name = name.substring(0, name.indexOf('='));
      }

      if (panels.panels[name]) {
        panel = panels.panels[name];
        // console.log(name, 'width', state[name], width * parseFloat(state[name]) / 100);
        if (panel.editor && panelURLValue) {
          panel.setCode(decodeURIComponent(panelURLValue));
        }

        if (openWithSameDimensions && toopen.length > 1) {
          panel.show(width * parseFloat(state[name]) / 100);
        } else {
          panel.show();
        }
        init.push(panel);
      } else if (name && panelURLValue) { // TODO support any varible insertion
        (function (name, panelURLValue) {
          var todo = ['html', 'javascript', 'css'];

          var deferredInsert = function (event, data) {
            var code, parts, panel = panels.panels[data.panelId] || {};

            if (data.panelId && panel.editor && panel.ready === true) {
              todo.splice(todo.indexOf(data.panelId), 1);
              try {
                code = panel.getCode();
              } catch (e) {
                // this really shouldn't happen
                // console.error(e);
              }
              if (code.indexOf('%' + name + '%') !== -1) {
                parts = code.split('%' + name + '%');
                code = parts[0] + decodeURIComponent(panelURLValue) + parts[1];
                panel.setCode(code);
                $document.unbind('codeChange', deferredInsert);
              }
            }

            if (todo.length === 0) {
              $document.unbind('codeChange', deferredInsert);
            }
          };

          $document.bind('codeChange', deferredInsert);
        }(name, panelURLValue));
      }
    }

    // support the old jsbin v1 links directly to the preview
    if (toopen.length === 1 && toopen[0] === 'preview') {
      panels.panels.live.show();
    }

    if (!openWithSameDimensions) this.distribute();
  } else {
    for (name in state) {
      panels.panels[name].show(width * parseFloat(state[name]) / 100);
    }
  }

  // now restore any data from sessionStorage
  // TODO add default templates somewhere
  // var template = {};
  // for (name in this.panels) {
  //   panel = this.panels[name];
  //   if (panel.editor) {
  //     // panel.setCode(sessionStorage.getItem('jsbin.content.' + name) || template[name]);
  //   }
  // }

  for (i = 0; i < init.length; i++) {
    init[i].init();
  }

  var visible = panels.getVisible();
  if (visible.length) {
    $body.addClass('panelsVisible');
    if (!focused) {
      visible[0].show();
    }
  }

};

panels.savecontent = function () {
  // loop through each panel saving it's content to sessionStorage
  var name, panel;
  for (name in this.panels) {
    panel = this.panels[name];
    if (panel.editor) sessionStorage.setItem('jsbin.content.' + name, panel.getCode());
  }
};

panels.focus = function (panel) {
  this.focused = panel;
  if (panel) {
    $('.panel').removeClass('focus').filter('.' + panel.id).addClass('focus');
  }
}

// evenly distribute the width of all the visible panels
panels.distribute = function () {
  var visible = $('#source .panelwrapper:visible'),
      width = 100,
      height = 0,
      innerW = $window.width() - (visible.length - 1), // to compensate for border-left
      innerH = $('#source').outerHeight(),
      left = 0,
      right = 0,
      top = 0,
      panel,
      nestedPanels = [];

  if (visible.length) {
    $body.addClass('panelsVisible');

    // visible = visible.sort(function (a, b) {
    //   return a.order < b.order ? -1 : 1;
    // });

    width = 100 / visible.length;
    for (var i = 0; i < visible.length; i++) {
      panel = $.data(visible[i], 'panel');
      right = 100 - (width * (i+1));
      panel.$el.css({ top: 0, bottom: 0, left: left + '%', right: right + '%' });
      panel.splitter.trigger('init', innerW * left/100);
      panel.splitter[i == 0 ? 'hide' : 'show']();
      left += width;

      nestedPanels = $(visible[i]).find('.panel');
      if (nestedPanels.length > 1) {
        top = 0;
        nestedPanels = nestedPanels.filter(':visible');
        height = 100 / nestedPanels.length;
        nestedPanels.each(function (i) {
          bottom = 100 - (height * (i+1));
          var panel = jsbin.panels.panels[$.data(this, 'name')];
          // $(this).css({ top: top + '%', bottom: bottom + '%' });
          $(this).css('top', top + '%');
          $(this).css('bottom', bottom + '%' );
          if (panel.splitter.hasClass('vertical')) {
            panel.splitter.trigger('init', innerH * top/100);
            panel.splitter[i == 0 ? 'hide' : 'show']();
          }
          top += height;
        });
      }
    }
  } else {
    $('#history').show();
    setTimeout(function () {
      $body.removeClass('panelsVisible');
    }, 100); // 100 is on purpose to add to the effect of the reveal
  }
};

panels.show = function (panelId) {
  this.panels[panelId].show();
  if (this.panels[panelId].editor) {
    this.panels[panelId].editor.focus();
  }
  this.panels[panelId].focus();
}

panels.hideAll = function () {
  var visible = panels.getVisible(),
      i = visible.length;
  while (i--) {
    visible[i].hide();
  }
}

// dirty, but simple
Panel.prototype.distribute = function () {
  panels.distribute();
};

jsbin.panels = panels;

var ignoreDuringLive = /^\s*(while|do|for)[\s*|$]/;

var panelInit = {
  html: function () {
    return new Panel('html', { editor: true, label: 'HTML' });
  },
  css: function () {
    return new Panel('css', { editor: true, label: 'CSS' });
  },
  javascript: function () {
    return new Panel('javascript', { editor: true, label: 'JavaScript' });
  },
  console: function () {
    // hide and show callbacks registered in console.js
    return new Panel('console', { label: 'Console' });
  },
  live: function () {
    function show() {
      // var panel = this;
      if (panels.ready) {
        renderLivePreview();
      }
    }

    function hide() {
      // detroy the iframe if we hide the panel
      // note: $live is defined in live.js
      if (panels.panels.console.visible === false) {
        $live.find('iframe').remove();
      }
    }

    return new Panel('live', { label: 'Output', show: show, hide: hide });
  }
};

var editors = panels.panels = {};

// show all panels (change the order to control the panel order)
editors.html = panelInit.html();
editors.css = panelInit.css();
editors.javascript = panelInit.javascript();
editors.console = panelInit.console();
upgradeConsolePanel(editors.console);
editors.live = panelInit.live();

// jsconsole.init(); // sets up render functions etc.
editors.live.settings.render = function (showAlerts) {
  if (panels.ready) {
    renderLivePreview(showAlerts);
    editors.console.render();
  }
};

// IMPORTANT this is nasty, but the sequence is important, because the
// show/hide method is being called as the panels are being called as
// the panel is setup - so we hook these handlers on *afterwards*.
panels.update = function () {
  var visiblePanels = panels.getVisible(),
      visible = [],
      i = 0;
  for (i = 0; i < visiblePanels.length; i++) {
    visible.push(visiblePanels[i].name);
  }

  // if (history.replaceState) {
  //   history.replaceState(null, null, '?' + visible.join(','));
  // } else {
  //   // :( this will break jquery mobile - but we're talking IE only at this point, right?
  //   location.hash = '#' + visible.join(',');
  // }
}

Panel.prototype._show = Panel.prototype.show;
Panel.prototype.show = function () {
  this._show.apply(this, arguments);
  panels.update();
}

Panel.prototype._hide = Panel.prototype.hide;
Panel.prototype.hide = function () {
  this._hide.apply(this, arguments);
  panels.update();
}

panels.allEditors = function (fn) {
  var panelId, panel;
  for (panelId in panels.panels) {
    panel = panels.panels[panelId];
    if (panel.editor) fn(panel);
  }
};

panels.restore();
panels.focus(panels.getVisible()[0] || null);

// allow panels to be reordered - TODO re-enable
(function () {
  return; // disabled for now

  var panelsEl = document.getElementById('panels'),
      moving = null;

  panelsEl.ondragstart = function (e) {
    if (e.target.nodeName == 'A') {
      moving = e.target;
    } else {
      return false;
    }
  };

  panelsEl.ondragover = function (e) {
    return false;
  };

  panelsEl.ondragend = function () {
    moving = false;
    return false;
  };

  panelsEl.ondrop = function (e) {
    if (moving) {

    }
    return false;
  };

});

var editorsReady = setInterval(function () {
  var ready = true,
      resizeTimer = null,
      panel,
      panelId;

  for (panelId in panels.panels) {
    panel = panels.panels[panelId];
    if (panel.visible && !panel.ready) ready = false;
  }

  panels.ready = ready;

  if (ready) {
    clearInterval(editorsReady);
    // panels.ready = true;
    // if (typeof editors.onReady == 'function') editors.onReady();
    // panels.distribute();

    // if live is visible, render it
    if (panels.panels.live.visible) {
      panels.panels.live.render(true);
    }

    if (panels.panels.console.visible) {
      panels.panels.console.render();
    }

    $(window).resize(function () {
      clearTimeout(resizeTimer);
      resizeTimer = setTimeout(function () {
        $document.trigger('sizeeditors');
      }, 100);
    });

    $document.trigger('sizeeditors');
    $document.trigger('jsbinReady');
  }
}, 100);
<|endoftext|>