JSFiddle - React, Tailwind, and code Playground

by emepyc

HTML

<script src="http://d3js.org/d3.v3.min.js"></script>
<div id="myvis"></div>

JavaScript

var old_genes = [];

var genes = [
    {"id": "gene1", "x":100, "width":100},
    {"id" : "gene2", "x":150, "width":150},
    {"id" : "very_long_gene_name", "x":250, "width":20},
    {"id" : "gene4", "x":290, "width":50},
    {"id" : "cagada", "x":151, "width":200} 
];

var slot = {
    slot_height : 30,
    gene_height : 10,
    show_label  : true    
};
    
var width = 600;
var height = 100;
var max_slots = ~~(height / slot.slot_height);

var kept_genes = slot_keeper(genes, old_genes);
var needed_slots = collition_resolver(genes);
if (needed_slots > max_slots) {
    shrink_slots(genes, height, needed_slots);
}
console.log("SLOTIZED GENES:");
console.log(genes);

var vis = d3.select("#myvis")
    .append("svg")
    .attr("width", width)
    .attr("height", height )
    .append("g")
    .attr("class","myg")

var vis_genes = vis.selectAll(".gene")
    .data(genes, function (d) { return d.id });

var new_genes = vis_genes
    .enter()
    .append("g")
    .attr("class", "gene");

new_genes
    .append("rect")
    .attr("x", function (d) { return d.x } )
    .attr("y", function (d) { return d.slot * slot.slot_height} ) 
    .attr("width", function (d) { return d.width } )
    .attr("height",  slot.gene_height)
    .attr("stroke", "black")
    .attr("fill", "red");

new_genes
    .append("text")
    .attr("x", function (d) { return d.x } )
    .attr("y", function(d) { return (d.slot * 30) + 25 } ) 
    .text(function (d) { if (slot.show_label === true) return d.id } );

vis_genes
    .exit()
    .remove();

function slot_keeper (genes, old_genes) {
    var old_genes_slots = genes2slots(old_genes);
    for (var i = 0; i < genes.length; i++) {
        if (old_genes_slots[genes[i].id] !== undefined) {
            genes[i].slot = old_genes_slot[genes[i].id];
        }
    }
}

/* Only genes with slots here */
function genes2slots (genes_array) {
    var hash = {};
    for (var i = 0; i < genes_array.length; i++) {
        var gene = genes_array[i];
        hash[gene.id]...