<commit_before>/**
 * Created by Pjer on 10/3/2016.
 *
 *  haha
 */
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

var status_jump = "local";

function auto_input() {
    if (status_jump =="local"){

        var seq = $('#sequence')[0];
        seq.value = "acaagatacattgtatgaaaatacaagaaa";
        Materialize.updateTextFields();
    }
}

function blast_req(){
    var s_data = ($('#form_bl').serializeObject());
    //console.log(s_data);
    var  dictPost  =  {"plugin":"BLAST","seq":s_data["sequence"]};
    myLoader();
    //console.log(dictPost);
    if(dictPost.seq.length>0) {
        $("#result_blast")[0].innerHTML="";
        $.ajax({
            type: "POST",
            url: "/plugin/",
            data: dictPost,
            success: function (response) {
                var Jr = JSON.parse(response);
                if (Jr['success'] == true) {

                    d3.selectAll('svg_blast_ct').remove();
                    d3.selectAll('#svg_blast').remove();
                    var data_res = Jr['result'];
                    var res_width = 500;
                    var res_height = 500;
                    var svg_container = d3.select('#result_blast').append('svg')
                        .attr('width', res_width + 280)
                        .attr('height', res_height + 120)
                        .attr("id","svg_blast")
                        .attr("class","svg_blast_ct");

                    var svg = svg_container.append("g")
                        .attr("transform", "translate(" + res_width / 2 + "," + res_height / 2 + ")");
                    glo_draw(svg,data_res.slice(0,22),s_data["sequence"].length);

                    //get the result ready for everyone
                    console.log("successfully request")
                }
                else {
                    Materialize.toast(Jr['error'], 3000, 'rounded');
                }
            }
        })
    }else {
        alert("input a codon sequence to BLAST")
    }
}

// initial blast data (should be from serve)

var raw_data={"q_length":46,"blast_result":[]};

console.log(raw_data);
result = raw_data["blast_result"];
q_len = raw_data["q_length"];
sample = result[0];

var text_start;
var text_end;
var radius;
var arc_k;
var color;
var root_text;
var text_info;
var text_benchmark;

var draw_arcs = function(svg,target_id,q_start,q_end,hit_start,hit_end){

    color = d3.scale.linear()
        .range(["hsl(-180,60%,50%)", "hsl(180,60%,50%)"])
        .interpolate(function(a, b) { var i = d3.interpolateString(a, b); return function(t) { return d3.hsl(i(t)); }; });

    var deg2arc  = function (arc){
        return arc*Math.PI/180
    };
    var res_width = 500;
    var res_height = 500;

    var radius = Math.min(res_width, res_height) / 1.9;

    var arc_root = d3.svg.arc()
        //.startAngle(deg2arc(0.5))
        //.endAngle(deg2arc(359.5))
        .innerRadius(0.78 * radius)
        .outerRadius(0.50 * radius)
        .cornerRadius(10);

    arc_k = d3.svg.arc()
        //.startAngle(deg2arc(360*hit_start/(q_end-q_start+1)))
        //.endAngle(deg2arc(360*hit_end/(q_end-q_start+1)))
        .innerRadius(0.9 * radius)
        .outerRadius(0.8 * radius)
        .cornerRadius(9);

    var total = raw_data["q_length"];

    svg.append("path")
        .datum({endAngle:deg2arc(359),startAngle:deg2arc(1)})
        .attr("d",arc_root)
        .attr("fill",function (d) {
            return color(0.4)
        })
        .attr("id","root_path");

    root_text=svg.append("text")
        .attr("dy", "3.35em")
        .attr("dx", ".75em")
        .style("text-anchor", "start")
        .append("textPath")
        .attr("startOffset", "0%")
        .attr("class", "arc-text")
        .attr("xlink:href", "#root_path")
        .text( "Original  Sequence VS "+target_id)
        .attr("style","font-size:24px;font-family:consolas")
        .attr("fill","white");

    text_info=svg.append("text")
        .attr("dy", "3.35em")
        .attr("dx", ".75em")
        .style("text-anchor", "start")
        .attr("x",-220)
        .attr("y",250);

    text_benchmark=svg.append("text")
        .attr("dy", "3.35em")
        .attr("dx", ".75em")
        .style("text-anchor", "start")
        .attr("x",-50)
        .attr("y",-20);

    svg.append("text")
        .attr("dy", "1.35em")
        .attr("dx", ".75em")
        .style("text-anchor", "start")
        .append("textPath")
        .attr("startOffset", "1.2%")
        .attr("class", "arc-text")
        .attr("xlink:href", "#root_path")
        .text( "start point")
        .attr("style","font-size:14px;font-family:consolas")
        .attr("fill","white");

    svg.append("text")
        .attr("dy", "1.35em")
        .attr("dx", ".75em")
        .style("text-anchor", "start")
        .append("textPath")
        .attr("startOffset", "52%")
        .attr("class", "arc-text")
        .attr("xlink:href", "#root_path")
        .text( "end point")
        .attr("style","font-size:14px;font-family:consolas")
        .attr("fill","white");

    var arc_ret=svg.append("path")
        .datum({endAngle:deg2arc(360*hit_end/(q_end-q_start+1)),startAngle:deg2arc(360*hit_start/(q_end-q_start+1))})
        .attr("d",arc_k)
        .attr("fill",function (d) {
            return color(0.99)
        })
        .attr("id","hit_path");

    text_start = svg.append("text")
        .attr("dy", "1.15em")
        .attr("dx", ".75em")
        .style("text-anchor", "start")
        .append("textPath")
        .attr("startOffset", "0%")
        .attr("class", "arc-text")
        .attr("xlink:href", "#hit_path")
        .text(hit_start)
        .attr("style","font-size:14px;font-family:consolas")
        .attr("fill","white");

    text_end = svg.append("text")
        .attr("dy", "1.15em")
        .attr("dx", "2.15em")
        .style("text-anchor", "end")
        .append("textPath")
        .attr("startOffset", "53.2301%")
        .attr("class", "arc-text")
        .attr("xlink:href", "#hit_path")
        .text(hit_end)
        .attr("style","font-size:14px;font-family:consolas")
        .attr("fill","white");

    var c_start = svg.append("circle")
        .attr("cx",17)
        .attr("cy",-0.72*radius)
        .attr("r",8)
        .attr("fill","black");

    var e_start = svg.append("circle")
        .attr("cx",-17)
        .attr("cy",-0.72*radius)
        .attr("r",8)
        .attr("fill","black");

    return arc_ret

};

function arcTween(start_n,end_n) {
    return function(d) {
        var interpolate_end = d3.interpolate(d.endAngle, end_n);
        var interpolate_begin = d3.interpolate(d.startAngle, start_n);
        return function(t) {
            d.endAngle = interpolate_end(t);
            d.startAngle = interpolate_begin(t);
            return arc_k(d);
        }
    }
}

function glo_draw(svg,data_result,ori_length) {

    ori_length = ori_length+0.0001;
    var current_data = data_result[0];
    var current_start = data_result[0].query_start;
    var current_end = data_result[0].query_end;

    var arc_ret = draw_arcs(svg,current_data.ID,0,ori_length,current_start,current_end);

    var res_data_enter = svg.append("g").selectAll("text")
        .data(data_result)
        .enter();

    var rec = res_data_enter.append("rect")
        .attr("rx", 6)
        .attr("ry", 6)
        .attr("x",250)
        .attr("y", function (d,i) {
            return i*24-255
        })
        .attr("width", 215)
        .attr("height", 20)
        .attr("fill",function (d) {
            console.log(color((d.query_end-d.query_start)/ori_length));
            return color((d.query_end-d.query_start)/ori_length)
        })
        .attr("id",function (d,i) {
            return "rectangle_" + i;
        })
        .on("mouseover", function(d,i){
                renew_graph(d,i);
                renew_label(d,i)
            }
        ).on("mouseout",function (d,i) {
            flash_label(d,i)
        }).attr("stroke","white").attr("stroke-width",3);;

    var text = res_data_enter.append("text")
        .text(function (d) {return d.ID})
        .attr("x",260)
        .attr("y",function (d,i) {
            return i*24-240
        })
        .attr("pointer-events", "none")
        .classed('noselcect',true);

    function flash_label(d,i) {
        d3.selectAll("#rectangle_"+i).attr("stroke","white").attr("stroke-width",3);
        d3.selectAll("#rectangle_"+i)
            .transition().duration(200).attrTween("width",function (d,i,a) {
            return d3.interpolate(a,215);

        });
    }

    function renew_label(d,i) {
        d3.selectAll("#rectangle_"+i).attr("stroke","yellow").attr("stroke-width",3);
        d3.selectAll("#rectangle_"+i)
            .transition().duration(200).attrTween("width",function (d,i,a) {
            return d3.interpolate(a,240)
        });

    }

    function renew_graph(d) {
        arc_ret.transition().duration(300)
            .attrTween("d", arcTween(d.query_start*Math.PI*2/ori_length,d.query_end*Math.PI*2/ori_length)).each("end",function () {
            text_end.text(d.query_end);
            text_start.text(d.query_start);
            root_text.text("Original Sequence VS" + d.ID);
            text_info.text("Description : "+d.description);
            text_benchmark.text("E-value"+d.evalue);
            arc_ret.attr("fill", color((d.query_end-d.query_start)/ori_length))
        })

    }

}

function loader(config) {
    return function() {
        var radius = Math.min(config.width, config.height) / 2;
        var tau = 2 * Math.PI;

        var arc = d3.svg.arc()
            .innerRadius(radius*0.6)
            .outerRadius(radius*0.9)
            .cornerRadius(10)
            .startAngle(0);

        var svg = d3.select(config.container).append("svg")
            .attr("id", config.id)
            .attr("width", config.width)
            .attr("height", config.height)
            .append("g")
            .attr("transform", "translate(" + config.width / 2 + "," + config.height / 2 + ")")

        var background = svg.append("path")
            .datum({endAngle: 0.33*tau})
            .style("fill", "#4a9c47")
            .attr("d", arc)
            .call(spin, 1500);

        function spin(selection, duration) {
            selection.transition()
                .ease("linear")
                .duration(duration)
                .attrTween("transform", function() {
                    return d3.interpolateString("rotate(0)", "rotate(360)");
                });

            setTimeout(function() { spin(selection, duration); }, duration);
        }

        function transitionFunction(path) {
            path.transition()
                .duration(7500)
                .attrTween("stroke-dasharray", tweenDash)
                .each("end", function() { d3.select(this).call(transition); });
        }

    };
}

var myLoader = loader({width: 500, height: 500, container: "#result_blast", id: "svg_blast"});

window.onload=(function () {

        //console.log(raw_data);

        var res_width = 500;
        var res_height = 500;
        var svg_container = d3.select('#result_blast').append('svg')
            .attr('width', res_width + 280)
            .attr('height', res_height + 180)
            .attr("id","svg_blast");

        var svg = svg_container.append("g")
            .attr("transform", "translate(" + res_width / 2 + "," + res_height / 2 + ")");

        svg_container.remove();

    }
);

<commit_msg>fix loader<commit_after>/**
 * Created by Pjer on 10/3/2016.
 *
 *  haha
 */
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

var status_jump = "local";

function auto_input() {
    if (status_jump =="local"){

        var seq = $('#sequence')[0];
        seq.value = "acaagatacattgtatgaaaatacaagaaa";
        Materialize.updateTextFields();
    }
}

function blast_req(){
    var s_data = ($('#form_bl').serializeObject());
    //console.log(s_data);
    var  dictPost  =  {"plugin":"BLAST","seq":s_data["sequence"]};

    $("#result_blast")[0].innerHTML="";
    myLoader();
    //console.log(dictPost);
    if(dictPost.seq.length>0) {
        $.ajax({
            type: "POST",
            url: "/plugin/",
            data: dictPost,
            success: function (response) {
                var Jr = JSON.parse(response);
                if (Jr['success'] == true) {

                    d3.selectAll('svg_blast_ct').remove();
                    d3.selectAll('#svg_blast').remove();
                    var data_res = Jr['result'];
                    var res_width = 500;
                    var res_height = 500;
                    var svg_container = d3.select('#result_blast').append('svg')
                        .attr('width', res_width + 280)
                        .attr('height', res_height + 120)
                        .attr("id","svg_blast")
                        .attr("class","svg_blast_ct");

                    var svg = svg_container.append("g")
                        .attr("transform", "translate(" + res_width / 2 + "," + res_height / 2 + ")");
                    glo_draw(svg,data_res.slice(0,22),s_data["sequence"].length);

                    //get the result ready for everyone
                    console.log("successfully request")
                }
                else {
                    Materialize.toast(Jr['error'], 3000, 'rounded');
                }
            }
        })
    }else {
        alert("input a codon sequence to BLAST")
    }
}

// initial blast data (should be from serve)

var raw_data={"q_length":46,"blast_result":[]};

console.log(raw_data);
result = raw_data["blast_result"];
q_len = raw_data["q_length"];
sample = result[0];

var text_start;
var text_end;
var radius;
var arc_k;
var color;
var root_text;
var text_info;
var text_benchmark;

var draw_arcs = function(svg,target_id,q_start,q_end,hit_start,hit_end){

    color = d3.scale.linear()
        .range(["hsl(-180,60%,50%)", "hsl(180,60%,50%)"])
        .interpolate(function(a, b) { var i = d3.interpolateString(a, b); return function(t) { return d3.hsl(i(t)); }; });

    var deg2arc  = function (arc){
        return arc*Math.PI/180
    };
    var res_width = 500;
    var res_height = 500;

    var radius = Math.min(res_width, res_height) / 1.9;

    var arc_root = d3.svg.arc()
        //.startAngle(deg2arc(0.5))
        //.endAngle(deg2arc(359.5))
        .innerRadius(0.78 * radius)
        .outerRadius(0.50 * radius)
        .cornerRadius(10);

    arc_k = d3.svg.arc()
        //.startAngle(deg2arc(360*hit_start/(q_end-q_start+1)))
        //.endAngle(deg2arc(360*hit_end/(q_end-q_start+1)))
        .innerRadius(0.9 * radius)
        .outerRadius(0.8 * radius)
        .cornerRadius(9);

    var total = raw_data["q_length"];

    svg.append("path")
        .datum({endAngle:deg2arc(359),startAngle:deg2arc(1)})
        .attr("d",arc_root)
        .attr("fill",function (d) {
            return color(0.4)
        })
        .attr("id","root_path");

    root_text=svg.append("text")
        .attr("dy", "3.35em")
        .attr("dx", ".75em")
        .style("text-anchor", "start")
        .append("textPath")
        .attr("startOffset", "0%")
        .attr("class", "arc-text")
        .attr("xlink:href", "#root_path")
        .text( "Original  Sequence VS "+target_id)
        .attr("style","font-size:24px;font-family:consolas")
        .attr("fill","white");

    text_info=svg.append("text")
        .attr("dy", "3.35em")
        .attr("dx", ".75em")
        .style("text-anchor", "start")
        .attr("x",-220)
        .attr("y",250);

    text_benchmark=svg.append("text")
        .attr("dy", "3.35em")
        .attr("dx", ".75em")
        .style("text-anchor", "start")
        .attr("x",-50)
        .attr("y",-20);

    svg.append("text")
        .attr("dy", "1.35em")
        .attr("dx", ".75em")
        .style("text-anchor", "start")
        .append("textPath")
        .attr("startOffset", "1.2%")
        .attr("class", "arc-text")
        .attr("xlink:href", "#root_path")
        .text( "start point")
        .attr("style","font-size:14px;font-family:consolas")
        .attr("fill","white");

    svg.append("text")
        .attr("dy", "1.35em")
        .attr("dx", ".75em")
        .style("text-anchor", "start")
        .append("textPath")
        .attr("startOffset", "52%")
        .attr("class", "arc-text")
        .attr("xlink:href", "#root_path")
        .text( "end point")
        .attr("style","font-size:14px;font-family:consolas")
        .attr("fill","white");

    var arc_ret=svg.append("path")
        .datum({endAngle:deg2arc(360*hit_end/(q_end-q_start+1)),startAngle:deg2arc(360*hit_start/(q_end-q_start+1))})
        .attr("d",arc_k)
        .attr("fill",function (d) {
            return color(0.99)
        })
        .attr("id","hit_path");

    text_start = svg.append("text")
        .attr("dy", "1.15em")
        .attr("dx", ".75em")
        .style("text-anchor", "start")
        .append("textPath")
        .attr("startOffset", "0%")
        .attr("class", "arc-text")
        .attr("xlink:href", "#hit_path")
        .text(hit_start)
        .attr("style","font-size:14px;font-family:consolas")
        .attr("fill","white");

    text_end = svg.append("text")
        .attr("dy", "1.15em")
        .attr("dx", "2.15em")
        .style("text-anchor", "end")
        .append("textPath")
        .attr("startOffset", "53.2301%")
        .attr("class", "arc-text")
        .attr("xlink:href", "#hit_path")
        .text(hit_end)
        .attr("style","font-size:14px;font-family:consolas")
        .attr("fill","white");

    var c_start = svg.append("circle")
        .attr("cx",17)
        .attr("cy",-0.72*radius)
        .attr("r",8)
        .attr("fill","black");

    var e_start = svg.append("circle")
        .attr("cx",-17)
        .attr("cy",-0.72*radius)
        .attr("r",8)
        .attr("fill","black");

    return arc_ret

};

function arcTween(start_n,end_n) {
    return function(d) {
        var interpolate_end = d3.interpolate(d.endAngle, end_n);
        var interpolate_begin = d3.interpolate(d.startAngle, start_n);
        return function(t) {
            d.endAngle = interpolate_end(t);
            d.startAngle = interpolate_begin(t);
            return arc_k(d);
        }
    }
}

function glo_draw(svg,data_result,ori_length) {

    ori_length = ori_length+0.0001;
    var current_data = data_result[0];
    var current_start = data_result[0].query_start;
    var current_end = data_result[0].query_end;

    var arc_ret = draw_arcs(svg,current_data.ID,0,ori_length,current_start,current_end);

    var res_data_enter = svg.append("g").selectAll("text")
        .data(data_result)
        .enter();

    var rec = res_data_enter.append("rect")
        .attr("rx", 6)
        .attr("ry", 6)
        .attr("x",250)
        .attr("y", function (d,i) {
            return i*24-255
        })
        .attr("width", 215)
        .attr("height", 20)
        .attr("fill",function (d) {
            console.log(color((d.query_end-d.query_start)/ori_length));
            return color((d.query_end-d.query_start)/ori_length)
        })
        .attr("id",function (d,i) {
            return "rectangle_" + i;
        })
        .on("mouseover", function(d,i){
                renew_graph(d,i);
                renew_label(d,i)
            }
        ).on("mouseout",function (d,i) {
            flash_label(d,i)
        }).attr("stroke","white").attr("stroke-width",3);;

    var text = res_data_enter.append("text")
        .text(function (d) {return d.ID})
        .attr("x",260)
        .attr("y",function (d,i) {
            return i*24-240
        })
        .attr("pointer-events", "none")
        .classed('noselcect',true);

    function flash_label(d,i) {
        d3.selectAll("#rectangle_"+i).attr("stroke","white").attr("stroke-width",3);
        d3.selectAll("#rectangle_"+i)
            .transition().duration(200).attrTween("width",function (d,i,a) {
            return d3.interpolate(a,215);

        });
    }

    function renew_label(d,i) {
        d3.selectAll("#rectangle_"+i).attr("stroke","yellow").attr("stroke-width",3);
        d3.selectAll("#rectangle_"+i)
            .transition().duration(200).attrTween("width",function (d,i,a) {
            return d3.interpolate(a,240)
        });

    }

    function renew_graph(d) {
        arc_ret.transition().duration(300)
            .attrTween("d", arcTween(d.query_start*Math.PI*2/ori_length,d.query_end*Math.PI*2/ori_length)).each("end",function () {
            text_end.text(d.query_end);
            text_start.text(d.query_start);
            root_text.text("Original Sequence VS" + d.ID);
            text_info.text("Description : "+d.description);
            text_benchmark.text("E-value"+d.evalue);
            arc_ret.attr("fill", color((d.query_end-d.query_start)/ori_length))
        })

    }

}

function loader(config) {
    return function() {
        var radius = Math.min(config.width, config.height) / 2;
        var tau = 2 * Math.PI;

        var arc = d3.svg.arc()
            .innerRadius(radius*0.6)
            .outerRadius(radius*0.9)
            .cornerRadius(10)
            .startAngle(0);

        var svg = d3.select(config.container).append("svg")
            .attr("id", config.id)
            .attr("width", config.width)
            .attr("height", config.height)
            .append("g")
            .attr("transform", "translate(" + config.width / 2 + "," + config.height / 2 + ")")

        var background = svg.append("path")
            .datum({endAngle: 0.33*tau})
            .style("fill", "#4a9c47")
            .attr("d", arc)
            .call(spin, 1500);

        function spin(selection, duration) {
            selection.transition()
                .ease("linear")
                .duration(duration)
                .attrTween("transform", function() {
                    return d3.interpolateString("rotate(0)", "rotate(360)");
                });

            setTimeout(function() { spin(selection, duration); }, duration);
        }

        function transitionFunction(path) {
            path.transition()
                .duration(7500)
                .attrTween("stroke-dasharray", tweenDash)
                .each("end", function() { d3.select(this).call(transition); });
        }

    };
}

var myLoader = loader({width: 500, height: 500, container: "#result_blast", id: "svg_blast"});

window.onload=(function () {

        //console.log(raw_data);

        var res_width = 500;
        var res_height = 500;
        var svg_container = d3.select('#result_blast').append('svg')
            .attr('width', res_width + 280)
            .attr('height', res_height + 180)
            .attr("id","svg_blast");

        var svg = svg_container.append("g")
            .attr("transform", "translate(" + res_width / 2 + "," + res_height / 2 + ")");

        svg_container.remove();

    }
);

<|endoftext|>


<commit_before>define(function (require) {

    var zrUtil = require('zrender/core/util');
    var symbolCreator = require('../../util/symbol');
    var graphic = require('../../util/graphic');
    var listComponentHelper = require('../helper/listComponent');

    var curry = zrUtil.curry;

    function dispatchSelectAction(name, api) {
        api.dispatchAction({
            type: 'legendToggleSelect',
            name: name
        });
    }

    function dispatchHighlightAction(seriesModel, dataName, api) {
        seriesModel.get('legendHoverLink') && api.dispatchAction({
            type: 'highlight',
            seriesName: seriesModel.name,
            name: dataName
        });
    }

    function dispatchDownplayAction(seriesModel, dataName, api) {
        seriesModel.get('legendHoverLink') && api.dispatchAction({
            type: 'downplay',
            seriesName: seriesModel.name,
            name: dataName
        });
    }

    return require('../../echarts').extendComponentView({

        type: 'legend',

        init: function () {
            this._symbolTypeStore = {};
        },

        render: function (legendModel, ecModel, api) {
            var group = this.group;
            group.removeAll();

            if (!legendModel.get('show')) {
                return;
            }

            var selectMode = legendModel.get('selectedMode');
            var itemAlign = legendModel.get('align');

            if (itemAlign === 'auto') {
                itemAlign = (legendModel.get('left') === 'right'
                    && legendModel.get('orient') === 'vertical')
                    ? 'right' : 'left';
            }

            var legendDrawedMap = {};

            zrUtil.each(legendModel.getData(), function (itemModel) {
                var name = itemModel.get('name');

                // Use empty string or \n as a newline string
                if (name === '' || name === '\n') {
                    group.add(new graphic.Group({
                        newline: true
                    }));
                    return;
                }

                var seriesModel = ecModel.getSeriesByName(name)[0];

                if (legendDrawedMap[name]) {
                    // Series not exists
                    return;
                }

                // Series legend
                if (seriesModel) {
                    var data = seriesModel.getData();
                    var color = data.getVisual('color');

                    // If color is a callback function
                    if (typeof color === 'function') {
                        // Use the first data
                        color = color(seriesModel.getDataParams(0));
                    }

                    // Using rect symbol defaultly
                    var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
                    var symbolType = data.getVisual('symbol');

                    var itemGroup = this._createItem(
                        name, itemModel, legendModel,
                        legendSymbolType, symbolType,
                        itemAlign, color,
                        selectMode
                    );

                    itemGroup.on('click', curry(dispatchSelectAction, name, api))
                        .on('mouseover', curry(dispatchHighlightAction, seriesModel, '', api))
                        .on('mouseout', curry(dispatchDownplayAction, seriesModel, '', api));

                    legendDrawedMap[name] = true;
                }
                else {
                    // Data legend of pie, funnel
                    ecModel.eachRawSeries(function (seriesModel) {
                        // In case multiple series has same data name
                        if (legendDrawedMap[name]) {
                            return;
                        }
                        if (seriesModel.legendDataProvider) {
                            var data = seriesModel.legendDataProvider();
                            var idx = data.indexOfName(name);
                            if (idx < 0) {
                                return;
                            }

                            var color = data.getItemVisual(idx, 'color');

                            var legendSymbolType = 'roundRect';

                            var itemGroup = this._createItem(
                                name, itemModel, legendModel,
                                legendSymbolType, null,
                                itemAlign, color,
                                selectMode
                            );

                            itemGroup.on('click', curry(dispatchSelectAction, name, api))
                                // FIXME Should not specify the series name
                                .on('mouseover', curry(dispatchHighlightAction, seriesModel, name, api))
                                .on('mouseout', curry(dispatchDownplayAction, seriesModel, name, api));

                            legendDrawedMap[name] = true;
                        }
                    }, this);
                }
            }, this);

            listComponentHelper.layout(group, legendModel, api);
            // Render background after group is layout
            // FIXME
            listComponentHelper.addBackground(group, legendModel);
        },

        _createItem: function (
            name, itemModel, legendModel,
            legendSymbolType, symbolType,
            itemAlign, color, selectMode
        ) {
            var itemWidth = legendModel.get('itemWidth');
            var itemHeight = legendModel.get('itemHeight');
            var inactiveColor = legendModel.get('inactiveColor');

            var isSelected = legendModel.isSelected(name);
            var itemGroup = new graphic.Group();

            var textStyleModel = itemModel.getModel('textStyle');

            var itemIcon = itemModel.get('icon');

            // Use user given icon first
            legendSymbolType = itemIcon || legendSymbolType;
            itemGroup.add(symbolCreator.createSymbol(
                legendSymbolType, 0, 0, itemWidth, itemHeight, isSelected ? color : inactiveColor
            ));

            // Compose symbols
            // PENDING
            if (!itemIcon && symbolType
                // At least show one symbol, can't be all none
                && ((symbolType !== legendSymbolType) || symbolType == 'none')
            ) {
                var size = itemHeight * 0.8;
                if (symbolType === 'none') {
                    symbolType = 'circle';
                }
                // Put symbol in the center
                itemGroup.add(symbolCreator.createSymbol(
                    symbolType, (itemWidth - size) / 2, (itemHeight - size) / 2, size, size,
                    isSelected ? color : inactiveColor
                ));
            }

            // Text
            var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
            var textAlign = itemAlign;

            var formatter = legendModel.get('formatter');
            if (typeof formatter === 'string' && formatter) {
                name = formatter.replace('{name}', name);
            }
            else if (typeof formatter === 'function') {
                name = formatter(name);
            }

            var text = new graphic.Text({
                style: {
                    text: name,
                    x: textX,
                    y: itemHeight / 2,
                    fill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
                    textFont: textStyleModel.getFont(),
                    textAlign: textAlign,
                    textVerticalAlign: 'middle'
                }
            });
            itemGroup.add(text);

            // Add a invisible rect to increase the area of mouse hover
            itemGroup.add(new graphic.Rect({
                shape: itemGroup.getBoundingRect(),
                invisible: true
            }));

            itemGroup.eachChild(function (child) {
                child.silent = !selectMode;
            });

            this.group.add(itemGroup);

            graphic.setHoverStyle(itemGroup);

            return itemGroup;
        }
    });
});<commit_msg>Disable legendHoverLink when use hoverLayer<commit_after>define(function (require) {

    var zrUtil = require('zrender/core/util');
    var symbolCreator = require('../../util/symbol');
    var graphic = require('../../util/graphic');
    var listComponentHelper = require('../helper/listComponent');

    var curry = zrUtil.curry;

    function dispatchSelectAction(name, api) {
        api.dispatchAction({
            type: 'legendToggleSelect',
            name: name
        });
    }

    function dispatchHighlightAction(seriesModel, dataName, api) {
        // If element hover will move to a hoverLayer.
        var el = api.getZr().storage.getDisplayList()[0];
        if (!(el && el.useHoverLayer)) {
            seriesModel.get('legendHoverLink') && api.dispatchAction({
                type: 'highlight',
                seriesName: seriesModel.name,
                name: dataName
            });
        }
    }

    function dispatchDownplayAction(seriesModel, dataName, api) {
        // If element hover will move to a hoverLayer.
        var el = api.getZr().storage.getDisplayList()[0];
        if (!(el && el.useHoverLayer)) {
            seriesModel.get('legendHoverLink') && api.dispatchAction({
                type: 'downplay',
                seriesName: seriesModel.name,
                name: dataName
            });
        }
    }

    return require('../../echarts').extendComponentView({

        type: 'legend',

        init: function () {
            this._symbolTypeStore = {};
        },

        render: function (legendModel, ecModel, api) {
            var group = this.group;
            group.removeAll();

            if (!legendModel.get('show')) {
                return;
            }

            var selectMode = legendModel.get('selectedMode');
            var itemAlign = legendModel.get('align');

            if (itemAlign === 'auto') {
                itemAlign = (legendModel.get('left') === 'right'
                    && legendModel.get('orient') === 'vertical')
                    ? 'right' : 'left';
            }

            var legendDrawedMap = {};

            zrUtil.each(legendModel.getData(), function (itemModel) {
                var name = itemModel.get('name');

                // Use empty string or \n as a newline string
                if (name === '' || name === '\n') {
                    group.add(new graphic.Group({
                        newline: true
                    }));
                    return;
                }

                var seriesModel = ecModel.getSeriesByName(name)[0];

                if (legendDrawedMap[name]) {
                    // Series not exists
                    return;
                }

                // Series legend
                if (seriesModel) {
                    var data = seriesModel.getData();
                    var color = data.getVisual('color');

                    // If color is a callback function
                    if (typeof color === 'function') {
                        // Use the first data
                        color = color(seriesModel.getDataParams(0));
                    }

                    // Using rect symbol defaultly
                    var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
                    var symbolType = data.getVisual('symbol');

                    var itemGroup = this._createItem(
                        name, itemModel, legendModel,
                        legendSymbolType, symbolType,
                        itemAlign, color,
                        selectMode
                    );

                    itemGroup.on('click', curry(dispatchSelectAction, name, api))
                        .on('mouseover', curry(dispatchHighlightAction, seriesModel, '', api))
                        .on('mouseout', curry(dispatchDownplayAction, seriesModel, '', api));

                    legendDrawedMap[name] = true;
                }
                else {
                    // Data legend of pie, funnel
                    ecModel.eachRawSeries(function (seriesModel) {
                        // In case multiple series has same data name
                        if (legendDrawedMap[name]) {
                            return;
                        }
                        if (seriesModel.legendDataProvider) {
                            var data = seriesModel.legendDataProvider();
                            var idx = data.indexOfName(name);
                            if (idx < 0) {
                                return;
                            }

                            var color = data.getItemVisual(idx, 'color');

                            var legendSymbolType = 'roundRect';

                            var itemGroup = this._createItem(
                                name, itemModel, legendModel,
                                legendSymbolType, null,
                                itemAlign, color,
                                selectMode
                            );

                            itemGroup.on('click', curry(dispatchSelectAction, name, api))
                                // FIXME Should not specify the series name
                                .on('mouseover', curry(dispatchHighlightAction, seriesModel, name, api))
                                .on('mouseout', curry(dispatchDownplayAction, seriesModel, name, api));

                            legendDrawedMap[name] = true;
                        }
                    }, this);
                }
            }, this);

            listComponentHelper.layout(group, legendModel, api);
            // Render background after group is layout
            // FIXME
            listComponentHelper.addBackground(group, legendModel);
        },

        _createItem: function (
            name, itemModel, legendModel,
            legendSymbolType, symbolType,
            itemAlign, color, selectMode
        ) {
            var itemWidth = legendModel.get('itemWidth');
            var itemHeight = legendModel.get('itemHeight');
            var inactiveColor = legendModel.get('inactiveColor');

            var isSelected = legendModel.isSelected(name);
            var itemGroup = new graphic.Group();

            var textStyleModel = itemModel.getModel('textStyle');

            var itemIcon = itemModel.get('icon');

            // Use user given icon first
            legendSymbolType = itemIcon || legendSymbolType;
            itemGroup.add(symbolCreator.createSymbol(
                legendSymbolType, 0, 0, itemWidth, itemHeight, isSelected ? color : inactiveColor
            ));

            // Compose symbols
            // PENDING
            if (!itemIcon && symbolType
                // At least show one symbol, can't be all none
                && ((symbolType !== legendSymbolType) || symbolType == 'none')
            ) {
                var size = itemHeight * 0.8;
                if (symbolType === 'none') {
                    symbolType = 'circle';
                }
                // Put symbol in the center
                itemGroup.add(symbolCreator.createSymbol(
                    symbolType, (itemWidth - size) / 2, (itemHeight - size) / 2, size, size,
                    isSelected ? color : inactiveColor
                ));
            }

            // Text
            var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
            var textAlign = itemAlign;

            var formatter = legendModel.get('formatter');
            if (typeof formatter === 'string' && formatter) {
                name = formatter.replace('{name}', name);
            }
            else if (typeof formatter === 'function') {
                name = formatter(name);
            }

            var text = new graphic.Text({
                style: {
                    text: name,
                    x: textX,
                    y: itemHeight / 2,
                    fill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
                    textFont: textStyleModel.getFont(),
                    textAlign: textAlign,
                    textVerticalAlign: 'middle'
                }
            });
            itemGroup.add(text);

            // Add a invisible rect to increase the area of mouse hover
            itemGroup.add(new graphic.Rect({
                shape: itemGroup.getBoundingRect(),
                invisible: true
            }));

            itemGroup.eachChild(function (child) {
                child.silent = !selectMode;
            });

            this.group.add(itemGroup);

            graphic.setHoverStyle(itemGroup);

            return itemGroup;
        }
    });
});<|endoftext|>


<commit_before>
var gatherer = require('../lib/gatherer')
var db = require('mongo-promise')
var _ = require('lodash')
var rsvp = require('rsvp')

module.exports = {

  warmMany: function(arr) {
    console.log('warming ', arr.length)
    var obj = arr[0]
    if (!obj) return
    console.log('and warming first ')
    this.warm(obj).then(function() { setTimeout(this.warmMany.bind(this, arr.slice(1)), 2000) }.bind(this))
  },

  // takes entity or cache
  warm: function(obj) {

    // skip warming if we are using a mock object
    if (obj.mock) return new rsvp.Promise(function(res) { res() })

    var gather = function(obj) {
      console.log('gathering ', obj)
      return gatherer.gather({
        refs: obj.refs,
        adapters: this.adapters
      }).then(function(data) {
        data._entityId = obj._id.toString()
        data._refs = obj.refs
        console.log('saving warmed data ', data)
        return db[this.collection].findAndModify({ _entityId: data._entityId }, null, data, { upsert: true, 'new':true }).then(function(doc) {
          console.log('save success')
          return doc
        }, function() { console.log('save fail') })
      }.bind(this), function() { console.log('ERROR: ', arguments) })
    }.bind(this)

    // if given a cache
    if (!obj.refs) {
      return db.entities.findById(obj._entityId).then(function(cache) {
        console.log('findbyid', obj._entityId, cache)
        gather(cache)
      }, console.log)
    } else {
      return gather(obj)
    }
  },

  // takes cache
  isOutdated: function(obj) {
    console.log('is outdated?', obj)
    if (!obj._meta || !obj._meta.fields) return true

    var now = Date.now() / 1000
    var expiries = _.pluck(_.flatten(_.values(obj._meta.fields)), 'expires')
    console.log('fields: ', _.values(_.flatten(obj._meta.fields)))
    console.log('now: ', now)
    console.log('expiries: ', expiries)
    return _.any(expiries, function(exp) { return exp < now })
  },

  search: function(params) {

    var fields = params.fields
    var query = this.buildQuery(params.q || {})
    var opts = { skip: parseInt(params.skip || 0), limit: parseInt(params.limit || 500) }

    console.log('searching')
    return db[this.collection].find(query, fields, opts).then(function(results) {
      //_.filter(results, this.isOutdated).forEach(this.warm.bind(this))
      return results
    }.bind(this))
  },

  validateRefs: function(refs) {
    return refs.map(function(ref) {
      if (!this.adapters[ref.adapter] || !this.adapters[ref.adapter].canUse(ref.id)) {
        ref.status = 'broken'
      }
      return ref
    }, this)
  }
}
<commit_msg>fix warmMany<commit_after>
var gatherer = require('../lib/gatherer')
var db = require('mongo-promise')
var _ = require('lodash')
var rsvp = require('rsvp')

module.exports = {

  warmMany: function(arr) {
    console.log('warming ', arr.length)
    var obj = arr[0]
    if (!obj) return
    console.log('and warming first ')
    setTimeout(function() {
      console.log('delayed 2000 ms')
      this.warmMany(arr.slice(1))
    }.bind(this), 2000)
  },

  // takes entity or cache
  warm: function(obj) {

    console.log('going to warm something', obj)
    // skip warming if we are using a mock object
    if (obj.mock) return new rsvp.Promise(function(res) { res() })

    var gather = function(obj) {
      console.log('gathering ', obj)
      return gatherer.gather({
        refs: obj.refs,
        adapters: this.adapters
      }).then(function(data) {
        data._entityId = obj._id.toString()
        data._refs = obj.refs
        console.log('saving warmed data ', data)
        return db[this.collection].findAndModify({ _entityId: data._entityId }, null, data, { upsert: true, 'new':true }).then(function(doc) {
          console.log('save success')
          return doc
        }, function() { console.log('save fail') })
      }.bind(this), function() { console.log('ERROR: ', arguments) })
    }.bind(this)

    // if given a cache
    if (!obj.refs) {
      return db.entities.findById(obj._entityId).then(function(cache) {
        console.log('findbyid', obj._entityId, cache)
        gather(cache)
      }, console.log)
    } else {
      return gather(obj)
    }
  },

  // takes cache
  isOutdated: function(obj) {
    console.log('is outdated?', obj)
    if (!obj._meta || !obj._meta.fields) return true

    var now = Date.now() / 1000
    var expiries = _.pluck(_.flatten(_.values(obj._meta.fields)), 'expires')
    console.log('fields: ', _.values(_.flatten(obj._meta.fields)))
    console.log('now: ', now)
    console.log('expiries: ', expiries)
    return _.any(expiries, function(exp) { return exp < now })
  },

  search: function(params) {

    var fields = params.fields
    var query = this.buildQuery(params.q || {})
    var opts = { skip: parseInt(params.skip || 0), limit: parseInt(params.limit || 500) }

    console.log('searching')
    return db[this.collection].find(query, fields, opts).then(function(results) {
      //_.filter(results, this.isOutdated).forEach(this.warm.bind(this))
      return results
    }.bind(this))
  },

  validateRefs: function(refs) {
    return refs.map(function(ref) {
      if (!this.adapters[ref.adapter] || !this.adapters[ref.adapter].canUse(ref.id)) {
        ref.status = 'broken'
      }
      return ref
    }, this)
  }
}
<|endoftext|>


<commit_before>// Copy-pasted from https://github.com/mui-org/material-ui/pull/10665

/* eslint-disable */
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import withStyles from 'material-ui/styles/withStyles';
import ButtonBase from 'material-ui/ButtonBase';
import { fade } from 'material-ui/styles/colorManipulator';

export const style = theme => {
  const commonTransitionsOptions = {
    duration: theme.transitions.duration.short,
    easing: theme.transitions.easing.easeOut,
  };

  const commonTransitionsProperty = [
    'width',
    'height',
    'box-shadow',
    'left',
    'top',
    'background-color',
  ];

  const commonTransitions = theme.transitions.create(
    commonTransitionsProperty,
    commonTransitionsOptions,
  );

  const colors = {
    primary: theme.palette.primary.main,
    secondary: '#bdbdbd',
    focused: '#9e9e9e',
    disabled: '#bdbdbd',
  };

  return {
    /* Styles for wrapper container */
    container: {
      position: 'relative',
      width: '100%',
      padding: '16px 0',
      '&$reverse': {
        transform: 'scaleX(-1)',
      },
      '&$vertical': {
        position: 'relative',
        height: '100%',
        padding: '0 16px',
        '&$reverse': {
          transform: 'scaleY(-1)',
        },
      },
    },
    /* Tracks styles */
    track: {
      position: 'absolute',
      transform: 'translate(0, -50%)',
      top: '50%',
      height: 2,
      '&$vertical': {
        transform: 'translate(-50%, 0)',
        left: '50%',
        top: 'initial',
        width: 2,
      },
      '&$disabled': {
        backgroundColor: colors.secondary,
      },
    },
    trackBefore: {
      left: 0,
      backgroundColor: colors.primary,
      transition: commonTransitions,
      '&$vertical': {
        top: 0,
      },
    },
    trackAfter: {
      right: 0,
      backgroundColor: colors.secondary,
      transition: commonTransitions,
      '&$vertical': {
        bottom: 0,
      },
      '&$active': {
        backgroundColor: colors.focused,
      },
    },
    /* Thumb styles  */
    thumb: {
      position: 'absolute',
      zIndex: 1,
      transform: 'translate(-50%, -50%)',
      width: 12,
      height: 12,
      borderRadius: '50%',
      transition: commonTransitions,
      backgroundColor: colors.primary,
      '&:focus': {
        boxShadow: `0px 0px 0px 10px ${fade(colors.primary, 0.3)}`,
      },
      '&$active': {
        width: 18,
        height: 18,
        '&:focus': {
          boxShadow: 'none',
        },
        '&$initial': {
          border: `2px solid ${colors.focused}`,
        },
      },
      '&$disabled': {
        width: 10,
        height: 10,
        cursor: 'no-drop',
        backgroundColor: colors.disabled,
        '&:focus': {
          border: `2px solid ${colors.disabled}`,
          boxShadow: 'none',
        },
      },
      '&$initial': {
        border: `2px solid ${colors.disabled}`,
        backgroundColor: 'transparent',
        '&:focus': {
          border: `2px solid ${colors.focused}`,
          boxShadow: `0px 0px 0px 10px ${fade(colors.disabled, 0.3)}`,
        },
      },
    },
    initial: {},
    vertical: {},
    disabled: {},
    focus: {},
    active: {},
    reverse: {},
  };
};

const KEY_CODES = {
  ARROW_LEFT: 37,
  ARROW_UP: 38,
  ARROW_RIGHT: 39,
  ARROW_DOWN: 40,
  HOME: 36,
  END: 35,
};

function normalizeValue(value, min = 0, max = 100) {
  return Math.min(Math.max(value, min), max);
}

const percentToValue = ({ percent, max, min }) => {
  return (max - min) * percent / 100 + min;
};

const roundToStep = ({ currentValue, newValue, step }) => {
  const diff = newValue - currentValue;

  if (Math.abs(diff) < step / 2) {
    return currentValue;
  }

  const remainder = diff > 0 ? step - newValue % step : -newValue % step;

  return newValue + remainder;
};

function getRelativeOffset(event) {
  const { scrollY, scrollX } = global;
  const { changedTouches, currentTarget } = event;
  const { pageX, pageY } = (changedTouches && changedTouches[0]) || event;
  const { left, top } = currentTarget.getBoundingClientRect();

  return {
    top: pageY - top - scrollY,
    left: pageX - left - scrollX,
  };
}

const calculatePercent = (event, vertical) => {
  const { currentTarget } = event;
  const { width, height } = currentTarget.getBoundingClientRect();

  const offset = getRelativeOffset(event);

  const position = vertical ? offset.top : offset.left;
  const size = vertical ? height : width;

  return position / (size / 100);
};

const timeout = delay => () => new Promise(resolve => setTimeout(resolve, delay));

class Slider extends React.Component {
  state = { isMove: false, isActive: false, isFocus: false };

  componentDidMount() {
    global.addEventListener('touchstart', this.touchStart, { passive: false });
  }

  componentWillReceiveProps(nextProps) {
    // If the value changes, then start the animation of thumb
    if (this.props.value !== nextProps.value && !this.state.isFocus) {
      this.activate()
        .then(timeout(this.props.theme.transitions.duration.complex))
        .then(this.deActivate);
    }
  }

  componentWillUnmount() {
    global.removeEventListener('touchstart', this.touchStart, { passive: false });
  }

  touchStart = event => {
    if (this.props.disabled || !this.state.isMove) {
      return;
    }

    event.preventDefault();
  };

  activate = () =>
    new Promise(resolve => {
      this.setState({ isActive: true }, resolve);
    });

  deActivate = () =>
    new Promise(resolve => {
      this.setState({ isActive: false }, resolve);
    });

  handleFocus = () => {
    this.setState({ isFocus: true }, () => {
      if (this.timeout) {
        clearTimeout(this.timeout);
      }

      this.activate()
        .then(() => timeout(this.props.theme.transitions.duration.short))
        .then(this.deActivate);
    });
  };

  handleBlur = () => {
    this.setState({ isFocus: false });
  };

  handleClick = event => {
    if (this.props.disabled) {
      return;
    }

    const { min, max, step, value, reverse, vertical } = this.props;

    const percent = normalizeValue(
      reverse
        ? 100 - calculatePercent(event, vertical)
        : calculatePercent(event, vertical),
      min, max);

    const newValue = roundToStep({
      currentValue: value,
      newValue: percentToValue({ percent, max, min }),
      step,
    });

    if (typeof this.props.onChange === 'function' && value !== newValue) {
      this.props.onChange(event, newValue);
    }
  };

  handleKeyboard = event => {
    if (this.props.disabled) {
      return;
    }

    if (!Object.values(KEY_CODES).includes(event.keyCode)) {
      return;
    }

    event.preventDefault(); // Prevent scroll page by arrows

    const { ARROW_LEFT, ARROW_UP, HOME, END } = KEY_CODES;
    const { min, max, value, step, reverse } = this.props;

    if (event.keyCode === HOME) {
      this.props.onChange(event, min);
      return;
    }

    if (event.keyCode === END) {
      this.props.onChange(event, max);
      return;
    }

    const direction = [ARROW_LEFT, ARROW_UP].includes(event.keyCode) ? -1 : 1;
    const diff = step * direction * (reverse ? -1 : 1);
    const newValue = normalizeValue(value + diff, min, max);

    if (typeof this.props.onChange === 'function' && value !== newValue) {
      this.props.onChange(event, newValue);
    }
  };

  handleMouseDown = event => {
    if (this.props.disabled) {
      return;
    }

    this.setState({ isMove: true, isActive: true });
    document.body.addEventListener('mouseup', this.handleMouseUp);

    if (typeof this.props.onDragEnd === 'function') {
      this.props.onDragStart(event);
    }
  };

  handleMouseUp = event => {
    if (this.props.disabled) {
      return;
    }

    document.body.removeEventListener('mouseup', this.handleMouseUp);

    this.setState({ isMove: false, isActive: false });

    if (typeof this.props.onDragEnd === 'function') {
      this.props.onDragEnd(event);
    }
  };

  handleMouseMove = event => {
    if (this.props.disabled || !this.state.isMove) {
      return;
    }

    const { min, max, step, value, reverse, vertical } = this.props;

    const percent = normalizeValue(
      reverse
        ? 100 - calculatePercent(event, vertical)
        : calculatePercent(event, vertical),
      min, max);

    const newValue = roundToStep({
      currentValue: value,
      newValue: percentToValue({ percent, max, min }),
      step,
    });

    if (typeof this.props.onChange === 'function' && value !== newValue) {
      this.props.onChange(event, newValue);
    }
  };

  render() {
    const { isActive, isFocus, isMove } = this.state;
    const {
      component: Component,
      classes,
      min,
      max,
      value,
      disabled,
      vertical,
      reverse,
      ...other
    } = this.props;

    const ariaProps = Object.keys(other).reduce((props, key) => {
      if (/aria-*/.test(key)) {
        Object.assign(props, {
          [key]: other[key],
        });
      }

      return props;
    }, {});

    const percent = normalizeValue((value - min) * 100 / (max - min));

    const containerClasses = classNames(classes.container, {
      [classes.vertical]: vertical,
      [classes.reverse]: reverse,
    });

    const trackBeforeClasses = classNames(classes.track, classes.trackBefore, {
      [classes.vertical]: vertical,
      [classes.disabled]: disabled,
    });

    const trackAfterClasses = classNames(classes.track, classes.trackAfter, {
      [classes.vertical]: vertical,
      [classes.active]: (isActive || isMove || isFocus) && !disabled,
      [classes.disabled]: disabled,
    });

    const thumbClasses = classNames(classes.thumb, {
      [classes.initial]: percent === 0,
      [classes.active]: isActive || isMove,
      [classes.disabled]: disabled,
    });

    const trackBeforeSize = `calc(${percent}% - ${disabled ? '7px' : '0px'})`;
    const trackAfterSize = `calc(${100 - percent}% - ${
      disabled || isActive || isMove ? '7px' : '5px'
    })`;
    const thumbPosition = `${percent}%`;

    const inlineTrackBeforeStyles = vertical
      ? { height: trackBeforeSize }
      : { width: trackBeforeSize };

    const inlineTrackAfterStyles = vertical
      ? { height: trackAfterSize }
      : { width: trackAfterSize };

    const inlineThumbStyles = vertical ? { top: thumbPosition } : { left: thumbPosition };

    return (
      <Component
        role="slider"
        className={containerClasses}
        aria-valuenow={value}
        aria-valuemin={min}
        aria-valuemax={max}
        aria-orientation={vertical ? 'vertical' : 'horizontal'}
        onClick={this.handleClick}
        onKeyDown={this.handleKeyboard}
        onMouseMove={this.handleMouseMove}
        onTouchMove={this.handleMouseMove}
        onTouchEnd={this.handleMouseUp}
        onMouseUp={this.handleMouseUp}
        {...ariaProps}
      >

        <ButtonBase
          className={thumbClasses}
          disableRipple
          style={inlineThumbStyles}
          onMouseDown={this.handleMouseDown}
          onTouchStart={this.handleMouseDown}
          onFocus={this.handleFocus}
          onBlur={this.handleBlur}
        />

      </Component>
    );
  }
}

Slider.propTypes = {
  /**
   * Useful to extend the style applied to components.
   */
  classes: PropTypes.object.isRequired,
  /**
   * @ignore
   */
  component: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
  /**
   * If `true`, the slider will be disabled.
   */
  disabled: PropTypes.bool,
  /**
   * The maximum allowed value of the slider.
   * Should not be equal to min.
   */
  max: PropTypes.number,
  /**
   * The minimum allowed value of the slider.
   * Should not be equal to max.
   */
  min: PropTypes.number,
  /**
   * Callback function that is fired when the slider's value changed.
   */
  onChange: PropTypes.func,
  /**
   * Callback function that is fired when the slide has stopped moving.
   */
  onDragEnd: PropTypes.func,
  /**
   * Callback function that is fired when the slider has begun to move.
   */
  onDragStart: PropTypes.func,
  /**
   * If `true`, the slider will be reversed.
   */
  reverse: PropTypes.bool,
  /**
   * The granularity the slider can step through values.
   */
  step: PropTypes.number,
  /**
   * @ignore
   */
  theme: PropTypes.object.isRequired,
  /**
   * The value of the slider.
   */
  value: PropTypes.number,
  /**
   * If `true`, the slider will be vertical.
   */
  vertical: PropTypes.bool,
};

Slider.defaultProps = {
  min: 0,
  max: 1,
  value: 0,
  step: 0.1,
  component: 'div',
};

export default withStyles(style, { name: 'MuiSlider', withTheme: true })(Slider);
<commit_msg>Update Slider from the material-ui PR (#881)<commit_after>// Copy-pasted from https://github.com/mui-org/material-ui/pull/10665

/* eslint-disable */
import React from 'react';
import { findDOMNode } from 'react-dom';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import withStyles from 'material-ui/styles/withStyles';
import ButtonBase from 'material-ui/ButtonBase';
import { fade } from 'material-ui/styles/colorManipulator';
import clamp from 'lodash/clamp';

export const style = theme => {
  const commonTransitionsOptions = {
    duration: theme.transitions.duration.short,
    easing: theme.transitions.easing.easeOut,
  };

  const commonTransitionsProperty = ['width', 'height', 'box-shadow', 'left', 'top'];

  const commonTransitions = theme.transitions.create(
    commonTransitionsProperty,
    commonTransitionsOptions,
  );

  const colors = {
    primary: theme.palette.primary.main,
    secondary: theme.palette.grey[400],
    focused: theme.palette.grey[500],
    disabled: theme.palette.grey[400],
  };

  return {
    /* Styles for wrapper container */
    container: {
      position: 'relative',
      width: '100%',
      margin: '10px 0',
      padding: '6px 0',
      cursor: 'pointer',
      '-webkit-tap-highlight-color': 'transparent',
      '&$disabled': {
        cursor: 'no-drop',
      },
      '&$vertical': {
        height: '100%',
        margin: '0 10px',
        padding: '0 6px',
      },
      '&$reverse': {
        transform: 'scaleX(-1)',
      },
      '&$vertical$reverse': {
        transform: 'scaleY(-1)',
      },
    },
    /* Tracks styles */
    track: {
      position: 'absolute',
      transform: 'translate(0, -50%)',
      top: '50%',
      height: 2,
      '&$focused, &$activated': {
        transition: 'none',
        backgroundColor: colors.focused,
      },
      '&$disabled': {
        backgroundColor: colors.secondary,
      },
      '&$vertical': {
        transform: 'translate(-50%, 0)',
        left: '50%',
        top: 'initial',
        width: 2,
      },
      '&$jumped': {
        backgroundColor: colors.focused,
      },
    },
    trackBefore: {
      zIndex: 1,
      left: 0,
      backgroundColor: colors.primary,
      transition: commonTransitions,
      '&$focused, &$activated, &$jumped': {
        backgroundColor: colors.primary,
      },
    },
    trackAfter: {
      right: 0,
      backgroundColor: colors.secondary,
      transition: commonTransitions,
      '&$vertical': {
        bottom: 0,
      },
    },
    /* Thumb styles  */
    thumb: {
      position: 'absolute',
      zIndex: 2,
      transform: 'translate(-50%, -50%)',
      width: 12,
      height: 12,
      borderRadius: '50%',
      transition: commonTransitions,
      backgroundColor: colors.primary,
      '&$focused': {
        boxShadow: `0px 0px 0px 9px ${fade(colors.primary, 0.16)}`,
      },
      '&$activated': {
        width: 17,
        height: 17,
        transition: 'none',
      },
      '&$disabled': {
        cursor: 'no-drop',
        width: 9,
        height: 9,
        backgroundColor: colors.disabled,
      },
      '&$zero': {
        border: `2px solid ${colors.disabled}`,
        backgroundColor: 'transparent',
      },
      '&$focused$zero': {
        border: `2px solid ${colors.focused}`,
        backgroundColor: fade(colors.focused, 0.34),
        boxShadow: `0px 0px 0px 9px ${fade(colors.focused, 0.34)}`,
      },
      '&$activated$zero': {
        border: `2px solid ${colors.focused}`,
      },
      '&$jumped': {
        width: 17,
        height: 17,
      },
    },
    focused: {},
    activated: {},
    disabled: {},
    zero: {},
    vertical: {},
    reverse: {},
    jumped: {},
  };
};

const KEY_CODES = {
  PAGE_UP: 33,
  PAGE_DOWN: 34,
  END: 35,
  HOME: 36,
  ARROW_LEFT: 37,
  ARROW_UP: 38,
  ARROW_RIGHT: 39,
  ARROW_DOWN: 40,
};

function addEventListener(node, event, handler, capture) {
  node.addEventListener(event, handler, capture);
  return {
    remove: function remove() {
      node.removeEventListener(event, handler, capture);
    },
  };
}

function percentToValue(percent, min, max) {
  return (max - min) * percent / 100 + min;
}

function roundToStep(number, step) {
  return Math.round(number / step) * step;
}

function getOffset(node) {
  const { scrollY, scrollX } = global;
  const { left, top } = node.getBoundingClientRect();

  return {
    top: top + scrollY,
    left: left + scrollX,
  };
}

function getMousePosition(event) {
  if (event.changedTouches && event.changedTouches[0]) {
    return {
      x: event.changedTouches[0].pageX,
      y: event.changedTouches[0].pageY,
    };
  }

  return {
    x: event.pageX,
    y: event.pageY,
  };
}

const calculatePercent = (node, event, isVertical, isReverted) => {
  const { width, height } = node.getBoundingClientRect();
  const { top, left } = getOffset(node);
  const { x, y } = getMousePosition(event);

  const value = isVertical ? y - top : x - left;
  const onePercent = (isVertical ? height : width) / 100;

  return isReverted ? 100 - clamp(value / onePercent) : clamp(value / onePercent);
};

function preventPageScrolling(event) {
  event.preventDefault();
}

function getAriaProps(props) {
  return Object.keys(props).reduce((result, key) => {
    if (/aria-*/.test(key)) {
      Object.assign(result, { [key]: props[key] });
    }

    return result;
  }, {});
}

class Slider extends React.Component {
  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.disabled) {
      return { currentState: 'disabled' };
    }

    if (!nextProps.disabled && prevState.currentState === 'disabled') {
      return { currentState: 'normal' };
    }

    return null;
  }

  state = { currentState: 'initial' };

  componentDidMount() {
    if (this.container) {
      this.container.addEventListener('touchstart', preventPageScrolling, { passive: false });
    }
  }

  componentWillUnmount() {
    this.container.removeEventListener('touchstart', preventPageScrolling, { passive: false });
  }

  emitChange(event, rawValue, callback) {
    const { min, max, value: previousValue, onChange } = this.props;

    const step = this.props.step || Math.abs((max - min) / 100);
    const value = roundToStep(rawValue, step);

    if (typeof onChange === 'function' && value !== previousValue) {
      onChange(event, value);

      if (typeof callback === 'function') {
        callback();
      }
    }
  }

  calculateTrackAfterStyles(percent) {
    const { currentState } = this.state;

    switch (currentState) {
      case 'activated':
        return `calc(100% - ${percent === 0 ? 7 : 5}px)`;
      case 'disabled':
        return `calc(${100 - percent}% - 6px)`;
      default:
        return 'calc(100% - 5px)';
    }
  }

  calculateTrackBeforeStyles(percent) {
    const { currentState } = this.state;

    switch (currentState) {
      case 'disabled':
        return `calc(${percent}% - 6px)`;
      default:
        return `${percent}%`;
    }
  }

  handleKeyDown = event => {
    const isSupportedKey = Object.values(KEY_CODES).includes(event.keyCode);
    if (!isSupportedKey) {
      return;
    }

    event.preventDefault();

    const { min, max, value: currentValue } = this.props;

    const onePercent = Math.abs((max - min) / 100);
    const step = this.props.step || onePercent;
    let value;

    switch (event.keyCode) {
      case KEY_CODES.HOME:
        value = min;
        break;
      case KEY_CODES.END:
        value = max;
        break;
      case KEY_CODES.PAGE_UP:
        value = currentValue + onePercent * 10;
        break;
      case KEY_CODES.PAGE_DOWN:
        value = currentValue - onePercent * 10;
        break;
      case KEY_CODES.ARROW_RIGHT:
      case KEY_CODES.ARROW_UP:
        value = currentValue + step;
        break;
      case KEY_CODES.ARROW_LEFT:
      case KEY_CODES.ARROW_DOWN:
        value = currentValue - step;
        break;
      default:
        break;
    }

    value = clamp(value, min, max);

    this.emitChange(event, value);
  };

  handleFocus = () => {
    this.setState({ currentState: 'focused' });
  };

  handleBlur = () => {
    this.setState({ currentState: 'normal' });
  };

  handleClick = event => {
    const { min, max, vertical, reverse } = this.props;
    const percent = calculatePercent(this.container, event, vertical, reverse);
    const value = percentToValue(percent, min, max);

    this.emitChange(event, value, () => {
      this.playJumpAnimation();
    });
  };

  handleTouchStart = event => {
    this.setState({ currentState: 'activated' });

    this.globalMouseUpListener = addEventListener(document, 'touchend', this.handleMouseUp);

    if (typeof this.props.onDragEnd === 'function') {
      this.props.onDragStart(event);
    }
  };

  handleMouseDown = event => {
    this.setState({ currentState: 'activated' });

    this.globalMouseUpListener = addEventListener(document, 'mouseup', this.handleMouseUp);
    this.globalMouseMoveListener = addEventListener(document, 'mousemove', this.handleMouseMove);

    if (typeof this.props.onDragEnd === 'function') {
      this.props.onDragStart(event);
    }
  };

  handleMouseUp = event => {
    this.setState({ currentState: 'normal' });

    if (this.globalMouseUpListener) {
      this.globalMouseUpListener.remove();
    }

    if (this.globalMouseMoveListener) {
      this.globalMouseMoveListener.remove();
    }

    if (typeof this.props.onDragEnd === 'function') {
      this.props.onDragEnd(event);
    }
  };

  handleMouseMove = event => {
    const { min, max, vertical, reverse } = this.props;
    const percent = calculatePercent(this.container, event, vertical, reverse);
    const value = percentToValue(percent, min, max);

    this.emitChange(event, value);
  };

  playJumpAnimation() {
    this.setState({ currentState: 'jumped' }, () => {
      setTimeout(() => {
        this.setState({ currentState: 'normal' });
      }, this.props.theme.transitions.duration.complex);
    });
  }

  render() {
    const { currentState } = this.state;
    const {
      component: Component,
      classes,
      value,
      min,
      max,
      vertical,
      reverse,
      disabled,
    } = this.props;

    const percent = clamp((value - min) * 100 / (max - min));

    const commonClasses = {
      [classes.disabled]: disabled,
      [classes.jumped]: !disabled && currentState === 'jumped',
      [classes.focused]: !disabled && currentState === 'focused',
      [classes.activated]: !disabled && currentState === 'activated',
    };

    const containerClasses = classNames(classes.container, {
      [classes.vertical]: vertical,
      [classes.reverse]: reverse,
      [classes.disabled]: disabled,
    });

    const trackBeforeClasses = classNames(classes.track, classes.trackBefore, commonClasses, {
      [classes.vertical]: vertical,
    });

    const trackAfterClasses = classNames(classes.track, classes.trackAfter, commonClasses, {
      [classes.vertical]: vertical,
    });

    const thumbClasses = classNames(classes.thumb, commonClasses, {
      [classes.zero]: percent === 0,
    });

    const trackProperty = vertical ? 'height' : 'width';
    const thumbProperty = vertical ? 'top' : 'left';
    const inlineTrackBeforeStyles = { [trackProperty]: this.calculateTrackBeforeStyles(percent) };
    const inlineTrackAfterStyles = { [trackProperty]: this.calculateTrackAfterStyles(percent) };
    const inlineThumbStyles = { [thumbProperty]: `${percent}%` };

    const ariaProps = getAriaProps(this.props);

    return (
      <Component
        role="slider"
        className={containerClasses}
        aria-valuenow={value}
        aria-valuemin={min}
        aria-valuemax={max}
        aria-orientation={vertical ? 'vertical' : 'horizontal'}
        onClick={this.handleClick}
        ref={node => {
          this.container = findDOMNode(node);
        }}
        {...ariaProps}
      >

        <ButtonBase
          className={thumbClasses}
          disableRipple
          style={inlineThumbStyles}
          onBlur={this.handleBlur}
          onKeyDown={this.handleKeyDown}
          onMouseDown={this.handleMouseDown}
          onTouchStartCapture={this.handleTouchStart}
          onTouchMove={this.handleMouseMove}
          onKeyboardFocus={this.handleFocus}
        />

      </Component>
    );
  }
}

Slider.propTypes = {
  /**
   * Useful to extend the style applied to components.
   */
  classes: PropTypes.object.isRequired,
  /**
   * @ignore
   */
  component: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
  /**
   * If `true`, the slider will be disabled.
   */
  disabled: PropTypes.bool,
  /**
   * The maximum allowed value of the slider.
   * Should not be equal to min.
   */
  max: PropTypes.number,
  /**
   * The minimum allowed value of the slider.
   * Should not be equal to max.
   */
  min: PropTypes.number,
  /**
   * Callback function that is fired when the slider's value changed.
   */
  onChange: PropTypes.func,
  /**
   * Callback function that is fired when the slide has stopped moving.
   */
  onDragEnd: PropTypes.func,
  /**
   * Callback function that is fired when the slider has begun to move.
   */
  onDragStart: PropTypes.func,
  /**
   * If `true`, the slider will be reversed.
   */
  reverse: PropTypes.bool,
  /**
   * The granularity the slider can step through values.
   */
  step: PropTypes.number,
  /**
   * @ignore
   */
  theme: PropTypes.object.isRequired,
  /**
   * The value of the slider.
   */
  value: PropTypes.number,
  /**
   * If `true`, the slider will be vertical.
   */
  vertical: PropTypes.bool,
};

Slider.defaultProps = {
  min: 0,
  max: 100,
  value: 50,
  component: 'div',
};

export default withStyles(style, { name: 'MuiSlider', withTheme: true })(Slider);
<|endoftext|>


<commit_before>var fs = require("fs")
var Path = require("path")
var placeholder = "{3vot}"
var local = "//localhost:3000";
var production = "//3vot.com"
var Log = require("3vot-cloud/utils/log")

var cheerio = require("cheerio")
var Transform = { local: toLocal, sf: toSf, index: transformIndex, _3vot: transform3VOT, production: toProduction }

//Transforms everything to Localhost
function toLocal( body, transformOptions ){
	var route = (transformOptions.host || local )
	body = replaceAll(body, transformOptions.placeholder || placeholder, route);
	return body;
}

function toProduction(body, transformOptions){
	var route = ""
	if(transformOptions.package.threevot.domain ) route = transformOptions.package.threevot.domain
	else route = production + "/" + transformOptions.user.user_name + "/" + transformOptions.package.name;

	if( !transformOptions.promptValues.publish ) route += "_" + transformOptions.package.threevot.version

	body = replaceAll(body, transformOptions.placeholder || placeholder, route);
	return body;
}

//Removes all {3vot} tags from internal js and css since they are not needed Static Resource uses relative paths
function toSf( body, transformOptions ){
	body = replaceAll(body, transformOptions.placeholder || placeholder + "/", "");
	return body;
}

//THIS IS NOT INJECT CLAY
function injectClay(body, pck, production){

	var cheerio = require('cheerio'),
  $ = cheerio.load(body);

	//lr = '<script src="https://localhost:35729/livereload.js?snipver=1"></script>'
	//$("body").append( lr );

	return $.xml();
}

//Transforms Index.html into an Visualforce Page
function transformIndex(body, transformOptions, production){
	if(!transformOptions) transformOptions = {};

	var name = transformOptions.name;
	if( production == false ) name += "_" + transformOptions.threevot.version

	if(production == null || production == undefined) production=true;
	var clay = '<script>'
	clay += 'window.clay = { path: "{!URLFOR($Resource.' + name + ')}" };'
	clay += '\n window.clay.path = window.clay.path.split("?")[0]';
	clay +='</script>'
	if(!production){
		clay = '<script>window.clay.path = "https://localhost:3000";</script>'
	}

	//body = replaceAll(body, "{3vot}", "" )
	var cheerio = require('cheerio'),
  $ = cheerio.load(body,  { xmlMode: true });

	$('head').append(clay);

	$("link").each(function(i, elem) {
		var el = $(this)
		var url = el.attr("href");
		if(url && url.indexOf("{3vot}") > -1 ){
			url = url.replace("{3vot}", "");
			var transformed = "{!URLFOR($Resource." + name + ", '" +url +"')}"
			el.attr("href", transformed);
		}
	});

	$("script").each(function(i, elem) {
		var el = $(this)
		var url = el.attr("src");
		if(url && url.indexOf("{3vot}") > -1 ){
			url = url.replace("{3vot}", "");
			var transformed = "{!URLFOR($Resource." + name + ", '" +url +"')}"
			el.attr("src", transformed);
			el.html(";");
		}
	});

	return $.xml();

}

function transform3VOT(body,transformOptions){
	if(!transformOptions) transformOptions = {}
	body = body.replace('"{3vot}/"', "window.clay.path + '/' "   );
	return body;
}

function readByType(path, transform, transformOptions){
	var body;
	var ext = Path.extname(path)
  if( path.indexOf(".js") > -1 || path.indexOf(".css") > -1 || path.indexOf(".html") > -1 || transformOptions.package.threevot.extensions.indexOf(ext) > -1 ){
  	Log.debug2("Transforming Path " + path )
  	body = fs.readFileSync(path,"utf-8")
  	if(transform) body = Transform[transform](body, transformOptions)
  }
  else body = fs.readFileSync(path)
  return body;
}

 function replaceAll(str, find, replace) {
    return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
  }

module.exports = {
	toLocal: toLocal,
	transformIndex: transformIndex,
	injectClay: injectClay,
	toSf: toSf,
	readByType: readByType
}<commit_msg>adjut transformation on production<commit_after>var fs = require("fs")
var Path = require("path")
var placeholder = "{3vot}"
var local = "//localhost:3000";
var production = "//3vot.com"
var Log = require("3vot-cloud/utils/log")

var cheerio = require("cheerio")
var Transform = { local: toLocal, sf: toSf, index: transformIndex, _3vot: transform3VOT, production: toProduction }

//Transforms everything to Localhost
function toLocal( body, transformOptions ){
	var route = (transformOptions.host || local )
	body = replaceAll(body, transformOptions.placeholder || placeholder, route);
	return body;
}

function toProduction(body, transformOptions){
	var route = ""
	if(transformOptions.package.threevot.domain ) route = transformOptions.package.threevot.domain
	else route = production + "/" + transformOptions.user.user_name + "/" + transformOptions.package.name;

	if( !transformOptions.promptValues.publish ) route += "_" + transformOptions.package.threevot.version

	body = replaceAll(body, transformOptions.placeholder || placeholder, route);
	return body;
}

//Removes all {3vot} tags from internal js and css since they are not needed Static Resource uses relative paths
function toSf( body, transformOptions ){
	body = replaceAll(body, transformOptions.placeholder || placeholder + "/", "");
	return body;
}

//THIS IS NOT INJECT CLAY
function injectClay(body, pck, production){

	var cheerio = require('cheerio'),
  $ = cheerio.load(body);

	//lr = '<script src="https://localhost:35729/livereload.js?snipver=1"></script>'
	//$("body").append( lr );

	return $.xml();
}

//Transforms Index.html into an Visualforce Page
function transformIndex(body, transformOptions, production){
	if(!transformOptions) transformOptions = {};

	var name = transformOptions.name;
	if( production == false ) name += "_" + transformOptions.threevot.version

	if(production == null || production == undefined) production=true;
	var clay = '<script>'
	clay += 'var clayPath = "{!URLFOR($Resource.' + name + ')}" ;'
	clay += '\n window.clay.path = clayPath.split("?")[0]';
	clay +='</script>'
	if(!production){
		clay = '<script>window.clay.path = "https://localhost:3000";</script>'
	}

	//body = replaceAll(body, "{3vot}", "" )
	var cheerio = require('cheerio'),
  $ = cheerio.load(body,  { xmlMode: true });

	$('head').append(clay);

	$("link").each(function(i, elem) {
		var el = $(this)
		var url = el.attr("href");
		if(url && url.indexOf("{3vot}") > -1 ){
			url = url.replace("{3vot}", "");
			var transformed = "{!URLFOR($Resource." + name + ", '" +url +"')}"
			el.attr("href", transformed);
		}
	});

	$("script").each(function(i, elem) {
		var el = $(this)
		var url = el.attr("src");
		if(url && url.indexOf("{3vot}") > -1 ){
			url = url.replace("{3vot}", "");
			var transformed = "{!URLFOR($Resource." + name + ", '" +url +"')}"
			el.attr("src", transformed);
			el.html(";");
		}
	});

	return $.xml();

}

function transform3VOT(body,transformOptions){
	if(!transformOptions) transformOptions = {}
	body = body.replace('"{3vot}/"', "window.clay.path + '/' "   );
	return body;
}

function readByType(path, transform, transformOptions){
	var body;
	var ext = Path.extname(path)
  if( path.indexOf(".js") > -1 || path.indexOf(".css") > -1 || path.indexOf(".html") > -1 || transformOptions.package.threevot.extensions.indexOf(ext) > -1 ){
  	Log.debug2("Transforming Path " + path )
  	body = fs.readFileSync(path,"utf-8")
  	if(transform) body = Transform[transform](body, transformOptions)
  }
  else body = fs.readFileSync(path)
  return body;
}

 function replaceAll(str, find, replace) {
    return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
  }

module.exports = {
	toLocal: toLocal,
	transformIndex: transformIndex,
	injectClay: injectClay,
	toSf: toSf,
	readByType: readByType
}<|endoftext|>


<commit_before>import React, { Component } from "react";
import { Link } from "react-router-dom";

export function LessonList() {

    return (

            Lesson plans are categorized as follows: {'\n'}
            K-2, 3-5, 6-8, and 9-12 {'\n'}

            K-2:
                Who is Neil Armstrong? {'\n'}
                Tech
                Practical/Activities

            3-5:
            History
            Tech
            Practical/Activities

            6-8:
            History
            Tech
            Practical/Activities

            9-12:
            History
            Tech
            Practical/Activities

    );

}<commit_msg>commit on oct 13 2020<commit_after>import React, { Component } from "react";
import { Link } from "react-router-dom";

export function LessonList() {

    return (

            Lesson plans are categorized as follows:

            K-2, 3-5, 6-8, and 9-12

            K-2:
                Who is Neil Armstrong?
                Tech
                Practical/Activities

            3-5:
            History
            Tech
            Practical/Activities

            6-8:
            History
            Tech
            Practical/Activities

            9-12:
            History
            Tech
            Practical/Activities

    );

}<|endoftext|>


<commit_before>/** @jsx jsx */

import React, { useEffect } from 'react' //eslint-disable-line
import { jsx, Styled, Flex } from 'theme-ui'
import styled from '@emotion/styled'
import PropTypes from 'prop-types'

const Modal = styled.div`
  content: 'butts';
  border-radius: 0.5rem;
  transition: all 0.3s;
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  flex-direction: column;
  z-index: 2;
  background: rgba(var(--base), 1);
  opacity: ${props => (props.visible ? '1' : '0')};
  visibility: ${props => (props.visible ? 'visible' : 'hidden')};
  section {
    p {
      line-height: 1.6;
      margin: 0 0 2em 0;
      text-align: center;
    }
  }
`

const Form = styled.form`
  width: 100%;
  margin: 0;
  &::invalid {
    box-shadow: none;
  }
  &::required {
    box-shadow: none;
  }
  &::optional {
    box-shadow: none;
  }
  @media screen and (min-width: ${props => props.theme.responsive.medium}) {
    width: 60%;
  }
`

const Email = styled.input`
  margin: 0;
  width: 100%;
  background: ${props => props.theme.colors.secondary};
  color: ${props => props.theme.colors.text};
`

const Submit = styled.input`
  cursor: pointer;
  transition: 0.2s;
  width: 100%;
  font-weight: bold;
  background: ${props => props.theme.colors.secondary};
  color: ${props => props.theme.colors.text};
`

class EmailCapture extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      name: '',
      email: '',
      message: '',
      showModal: false,
    }
  }

  handleInputChange = event => {
    const target = event.target
    const value = target.value
    const email = target.name
    this.setState({
      [email]: value,
    })
  }

  componentDidMount() {
    this.handleSubmit = event => {
      event.preventDefault()
      this.handleSuccess()
      window.analytics.identify('Subscribed', {
        email: this.state.email,
      })
    }
  }

  handleSuccess = () => {
    this.setState({
      email: '',
      showModal: true,
    })
  }

  closeModal = () => {
    this.setState({ showModal: false })
  }

  render(props) {
    return (
      <Flex
        sx={{
          border: '1px solid',
          borderColor: 'text',
          alignItems: 'center',
          mb: 3,
          flexWrap: ['wrap', 'nowrap'],
        }}
      >

          <Modal visible={this.state.showModal}>

Thanks for subscribing!

See you in your inbox sometime soon.

          </Modal>

        <Form
          name="subscribe"
          onSubmit={this.handleSubmit}
          overlay={this.state.visible}
          onClick={this.closeModal}
          sx={{ p: 3 }}
        >
          <Email
            name="email"
            type="email"
            placeholder="Email"
            value={this.state.email}
            onChange={this.handleInputChange}
            required
            sx={{
              background: 'secondary',
              border: '1px solid',
              borderColor: 'text',
              p: 3,
              mb: 3,
            }}
          />
          <Email
            name="name"
            type="name"
            placeholder="Name"
            value={this.state.email}
            onChange={this.handleInputChange}
            required
            sx={{
              background: 'secondary',
              border: '1px solid',
              borderColor: 'text',
              p: 3,
              mb: 3,
            }}
          />
          <Submit
            className="button"
            name="submit"
            type="submit"
            value="Send"
            sx={{
              p: 3,
            }}
          />
        </Form>
      </Flex>
    )
  }
}

EmailCapture.propTypes = {
  data: PropTypes.object,
}

export default EmailCapture
<commit_msg>Header size<commit_after>/** @jsx jsx */

import React, { useEffect } from 'react' //eslint-disable-line
import { jsx, Styled, Flex } from 'theme-ui'
import styled from '@emotion/styled'
import PropTypes from 'prop-types'

const Modal = styled.div`
  content: 'butts';
  border-radius: 0.5rem;
  transition: all 0.3s;
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  flex-direction: column;
  z-index: 2;
  background: rgba(var(--base), 1);
  opacity: ${props => (props.visible ? '1' : '0')};
  visibility: ${props => (props.visible ? 'visible' : 'hidden')};
  section {
    p {
      line-height: 1.6;
      margin: 0 0 2em 0;
      text-align: center;
    }
  }
`

const Form = styled.form`
  width: 100%;
  margin: 0;
  &::invalid {
    box-shadow: none;
  }
  &::required {
    box-shadow: none;
  }
  &::optional {
    box-shadow: none;
  }
  @media screen and (min-width: ${props => props.theme.responsive.medium}) {
    width: 60%;
  }
`

const Email = styled.input`
  margin: 0;
  width: 100%;
  background: ${props => props.theme.colors.secondary};
  color: ${props => props.theme.colors.text};
`

const Submit = styled.input`
  cursor: pointer;
  transition: 0.2s;
  width: 100%;
  font-weight: bold;
  background: ${props => props.theme.colors.secondary};
  color: ${props => props.theme.colors.text};
`

class EmailCapture extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      name: '',
      email: '',
      message: '',
      showModal: false,
    }
  }

  handleInputChange = event => {
    const target = event.target
    const value = target.value
    const email = target.name
    this.setState({
      [email]: value,
    })
  }

  componentDidMount() {
    this.handleSubmit = event => {
      event.preventDefault()
      this.handleSuccess()
      window.analytics.identify('Subscribed', {
        email: this.state.email,
      })
    }
  }

  handleSuccess = () => {
    this.setState({
      email: '',
      showModal: true,
    })
  }

  closeModal = () => {
    this.setState({ showModal: false })
  }

  render(props) {
    return (
      <Flex
        sx={{
          border: '1px solid',
          borderColor: 'text',
          alignItems: 'center',
          mb: 3,
          flexWrap: ['wrap', 'nowrap'],
        }}
      >

          <Modal visible={this.state.showModal}>

Thanks for subscribing!

See you in your inbox sometime soon.

          </Modal>

        <Form
          name="subscribe"
          onSubmit={this.handleSubmit}
          overlay={this.state.visible}
          onClick={this.closeModal}
          sx={{ p: 3 }}
        >
          <Email
            name="email"
            type="email"
            placeholder="Email"
            value={this.state.email}
            onChange={this.handleInputChange}
            required
            sx={{
              background: 'secondary',
              border: '1px solid',
              borderColor: 'text',
              p: 3,
              mb: 3,
            }}
          />
          <Email
            name="name"
            type="name"
            placeholder="Name"
            value={this.state.email}
            onChange={this.handleInputChange}
            required
            sx={{
              background: 'secondary',
              border: '1px solid',
              borderColor: 'text',
              p: 3,
              mb: 3,
            }}
          />
          <Submit
            className="button"
            name="submit"
            type="submit"
            value="Send"
            sx={{
              p: 3,
            }}
          />
        </Form>
      </Flex>
    )
  }
}

EmailCapture.propTypes = {
  data: PropTypes.object,
}

export default EmailCapture
<|endoftext|>


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

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

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

    componentWillReceiveProps(nextProps) {
        if (nextProps.hue !== this.props.hue) {
            const { color } = this.cubeMaterial;
            const newColor = new THREE.Color();
            newColor.setHSL(nextProps.hue, this.colorSaturation, this.colorLightness);
            const tween = new TWEEN.Tween(color)
                    .to(newColor, 1000)
                    .easing(TWEEN.Easing.Quadratic.Out)
                    .start();
        }
    }

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

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

        this.addCubesToScene();

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

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

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

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

        this.renderAnimation();
    }

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

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

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

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

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

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

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

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

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

Orthofloat.defaultProps = {
    hue: 0.35714285714285715
};<commit_msg>making a commit for window resizing and resetting renderer size before I break something<commit_after>import React, { Component, PropTypes } from 'react';
import THREE from 'three';
import TWEEN from 'tween.js';

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

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

    componentWillReceiveProps(nextProps) {
        if (nextProps.hue !== this.props.hue) {
            const { color } = this.cubeMaterial;
            const newColor = new THREE.Color();
            newColor.setHSL(nextProps.hue, this.colorSaturation, this.colorLightness);
            const tween = new TWEEN.Tween(color)
                    .to(newColor, 1000)
                    .easing(TWEEN.Easing.Quadratic.Out)
                    .start();
        }
    }

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

    initializeScene() {
        this.setWindowHeightAndWidth();

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

        this.initializeCubes();

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

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

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

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

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

    setWindowHeightAndWidth() {
        this.windowHeight = window.innerHeight;
        this.windowWidth = window.innerWidth;
    }

    onWindowResize() {
        this.setWindowHeightAndWidth();
        this.renderer.setSize(this.windowWidth, this.windowHeight);

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

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

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

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

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

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

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

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

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

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

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