var height = 175,
    width = 500;

// ref [1]
var colors = {
         red: "rgb(255,59,48)",
      orange: "rgb(255,149,0)", 
      yellow: "rgb(255,204,0)",
       green: "rgb(76,217,100)",
   teal_blue: "rgb(90,200,250)",
        blue: "rgb(0,122,255)",
      purple: "rgb(88,86,214)",
        pink: "rgb(255,45,85)" 
};

// position color rects
var yScaleRect = d3.scaleBand()
                   .domain(Object.keys(colors))
                   .rangeRound([0, width])
                   .paddingInner([0.1])
                   .paddingOuter([0.1]);

// fill color of background rect dependent on mouse x coords
var scaleBW = d3.scaleLinear()
                .domain([176, 675])
                .range(["rgb(255,255,255)", "rgb(0,0,0)"]);

// interpolate rgb for transition on load
// ref [3] for '1e-6' instead of '0'
var i = d3.interpolateRound(255, 1e-6);

svg = d3.select("#block")
        .append("svg")
        .attr("height", height)
        .attr("width", width);

var rect_bckgrnd = svg.append("rect")
                      .attr("x", 0)
                      .attr("y", 0)
                      .attr("width", width)
                      .attr("height", height)
                      .attr("rx", 10)
                      .attr("ry", 10)
                      .on("mousemove", () => {
                          rect_bckgrnd.call(updateFill, d3.event.x);
                      });

// transition background rect from white to black
rect_bckgrnd.style("fill", "rgb(255,255,255)")
            .transition(["onload_w_to_b"])
            .duration(2500)
            .style("fill", "rgb(0,0,0)");

//update text of rgb value during rect transition; ref [2] 
d3.transition(["onload_w_to_b"])
  .duration(2500)
  .tween("text", () => {
      return function(t) { 
          d3.select("#rgb_value")
            .text("rgb(" + i(t) + ", " + i(t) + ", " + i(t) + ")"); 
      };
  });

var color = svg.append("g")
               .selectAll("rect")
               .data(Object.keys(colors))
               .enter()
               .append("rect")
               .attr("class", "color")
               .attr("x", d => yScaleRect(d))
               .attr("y", 60)
               .attr("width", yScaleRect.bandwidth())
               .attr("height", yScaleRect.bandwidth())
               .attr("rx", 10)
               .attr("ry", 10)
               .style("fill", d => colors[d]);

function updateFill(selection, x) {

    selection.style("fill", scaleBW(x));

    // update text with rgb value
    d3.select("#rgb_value")
      .text(scaleBW(x));
}

// references
// [1] https://developer.apple.com/ios/human-interface-guidelines/visual-design/color/
// [2] http://bl.ocks.org/mbostock/7004f92cac972edef365
// [3] https://github.com/d3/d3-interpolate/blob/master/README.md#interpolateNumber