Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <h1 id='title'>Video Game Sales</h1>
<h2 id='description'>100 Most Sold Video Games, grouped by platform</h2>
<div id='container'>
  <div id='legend'></div>
  <svg id='svg' preserveAspectRatio='xMidYMid meet'></svg>
</div>
              
            
!

CSS

              
                body{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

#container {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  width: 100%;
}


h2{
  font-size: 20px;
  font-weight: normal;
}

svg {
  transition: 500ms;
  transform-origin: 50% 50%;
  * {
    transition: opacity 500ms;
  }
}

.leaf-text{
  text-anchor: middle;
}

#legend {
  display: flex;
  flex-direction: column;
  p {
    padding: 0 10px;
    font-size: 14px;
    margin: 5px 0;
  }
}

.legend-item {
  display: flex;
  flex-direction: row;
  justify-content: start;
  align-items: center;
  padding: 0 5px;
  *{
    pointer-events: none;
  }
  &:hover {background-color: #e0e0e0;}
}

.legend-color {
  height: 10px;
  width: 20px;
}
@media screen and (max-width: 700px), screen and (max-height: 700px){
  #container {
    flex-direction: column-reverse;
  }
  #legend {
    flex-direction: row;
    flex-wrap: wrap;
    padding: 0;
    p{
      font-size: 12px;
    }
  }
}
circle {
  cursor: pointer;
}

text,
tspan {
  pointer-events: none;
}

.over {
  stroke-width: 3px;
  stroke: silver;
}
              
            
!

JS

              
                const DATA_URL='https://cdn.rawgit.com/freeCodeCamp/testable-projects-fcc/a80ce8f9/src/data/tree_map/video-game-sales-data.json';

function get(url){
  return new Promise((resolve,reject)=>{
    var req=new XMLHttpRequest();
    req.open('GET',url,true);
    req.onload=()=>{
      if(req.status==200) resolve(JSON.parse(req.response));
      else reject(Error(req.statusText));
    };
    req.onerror=()=>{
      reject(Error("Network Error"));
    };
    req.send();
  });
}

get(DATA_URL).then(response=>build(response));

function build(data){
  var clickState='standby';
  const w=600;
  const h=600;
  const padding=10;
  //identifiers
  let svg = d3.select('svg')
    .attr('width',w)
    .attr('height',h)
    .attr('viewBox','0 0 '+w+' '+h)
    //.style('height',window.innerWidth<window.innerHeight?'80vw':'80vh')
    //.style('width',window.innerWidth<window.innerHeight?'80vw':'80vh')
  
  document.addEventListener('click',()=>{
    if (clickState==='clicked') clickState='zoomed';
    else if (clickState=='zoomed') {
      clickState='standby';
      d3.select('svg').attr('viewBox','0 0 '+w+' '+h);
    }
  })
  //hierarchy
  let root=d3.hierarchy(data);
  let layout=d3.pack();
  layout
    .size([w,h])
  //must apply sum() to hierarchy before passing to layout
  root.sum(d => d.value);
  //pass hierarchy to layout
  layout(root);
  //draw
  svg.selectAll('g')
    .data(root.descendants())
    .enter()
    .append('g')
    .attr('class',d=>'platform-'+(d.data.category?d.data.category:d.data.name))
    .classed('hasText',d=>(d.children===undefined)) //only children show text
    .attr('transform',d=>'translate('+[d.x,d.y]+')')
    .append('circle')
    .attr('class',d=>'platform-'+(d.data.category?d.data.category+' leaf':d.data.name+' category'))
    .style('fill',d=>color(d.data))
    .attr('r',d=>d.r)
    .on('mouseenter',function(d){
      let cat=d3.select(this).attr('class').split(' ')[0];
      d3.select('g.'+cat+':not(.hasText)').classed('over',true);
      d3.select('#legend')
        .select('.'+cat)
        .style('background-color','#e0e0e0');
    })
    .on('mouseleave',function(d){
      let cat=d3.select(this).attr('class').split(' ')[0];
      let trans=d3.select('g.'+cat+':not(.hasText)').attr('transform').split(' ')[0];
      d3.select('g.'+cat+':not(.hasText)').classed('over',false)
      d3.select('#legend')
        .select('.'+cat)
        .style('background-color','transparent');
    })
    .on('click',function(){
      if (clickState==='standby'){
        clickState='clicked';
        let category=d3.select(this).attr('class').split(' ')[0];
        let bbox=d3.select('circle.'+category+':not(.hasText)')
          .node().getBoundingClientRect();
        let svgBox=svg.node().getBoundingClientRect();
        svg.attr('viewBox',[
          bbox.x-svgBox.x-bbox.width/4,
          bbox.y-svgBox.y-bbox.height/4,
          bbox.width*1.5,
          bbox.height*1.5
        ].join(' '));
      }
    })
  //only children have text
  svg.selectAll('g.hasText')
    .classed('tile',true)
    .attr('data-name',d=>d.data.name)
    .attr('data-category',d=>d.data.category)
    .attr('data-value',d=>d.data.value)
    .append('text')
    .attr('y',d=>textYPos(d.data.name,textSize(d.data.name,d.r))-1)
    .attr('class',d=>'platform-'+d.data.category)
    .style('font-size',d=>textSize(d.data.name,d.r)+'px')
    .style('pointer-events','none')
    .selectAll('tspan')
    .data(d=>textWrap(d.data.name, textSize(d.data.name,d.r), d.data.category))
    .enter()
    .append('tspan')
    .attr('class',d=>'platform-'+d.platform)
    .classed('leaf-text', true)
    .attr('x',0)
    .attr('dy',d=>d.size)
    .text(d=>d.text);
  
  //markup legend
  let entries = d3.select('#legend')
    .selectAll('div')
    .data(root.children)
    .enter()
    .append('div')
    .attr('class',d=>'platform-'+d.data.name)
    .classed('legend-item',true)
    .on('mouseenter',function(d){
      svg.selectAll(':not(.platform-'+d.data.name+')')
        .style('opacity','0.4')
    })
    .on('mouseleave',function(d){
      svg.selectAll(':not(.platform-'+d.data.name+')')
        .style('opacity','1')
    });
  
  entries.append('div')
    .classed('legend-color',true)
    .style('background-color',d=>color(d.data));
  entries.append('p')
    .classed('legend-text',true)
    .html(d=>d.data.name);

}
// y position offset of text block
function textYPos(text,size){
  let textArray=textWrap(text);
  return (textArray.length*(size/2))*-1;
}
//scale font-size with radius and number of tspan lines
function textSize(text,radius){
  let textArray=textWrap(text);
  let multiplier = textArray.length > 4 ? 4.5/textArray.length : 1;
  return (radius/3)*multiplier;
}
//wrap text -- complex
function textWrap(str,size,platform){
  return round(format(str,size,platform));
  
  //use regex to format str into tspans
  function format(str,size,platform){
    if (/\s/g.test(str)){
      return str
        .replace(/\s+/g, ' ') //first remove redundant spaces to clean data
        //refine split rules
        .replace(/(\b\S{1,4}\b)\s(\b\S{1,3}\b)/g,'$1%%$2')
        //4w 3w
        .replace(/([^%]{2})(\b.{1,3}\b)\s(\b\S{1,4}\b)/g,'$1$2%%$3')
        //3w 4w
        .replace(/(\b[\w\d]{1,6}\b)\s(\d)/g, '$1%%$2')
        //single digits after space
        .replace(/(\b[\w\d]+\b)%%(\b[\w\d]+\b)%%(\b[\w\d]+\b)/g,'$1%%$2 $3')
        //stop multiple breaks
        .replace(/(\b[\w\d]+\b\/)(\b[\w\d]{4,}\b)/g, '$1 $2')
        // split after slash
        .replace(/(\b[\w\d]{5,}\b)([\w\d]{5,})\b/g, '$1- $2')
        //split long words
        .replace(/:%%/g, ': ')
        .split(' ')
        .map((d,i)=>({
          y: i*15,
          text: d.replace(/%%/g,' '),
          size: size,
          value: 1,
          platform: platform
        }));
    } 
    else return [{
      y: 0,
      text: str,
      size: size,
      platform: platform
    }];
  }
  //round out the tspan lengths to fit the circle
  function round(data){
    if(data.length<6) return data; //only check texts longer than six words
    let lowest = findLowest(data); //find index of smallest tspan
    if(data[lowest].text.length>5) return data; // do nothing if smallest tspan is big
    return round(merge(data,lowest,compareNeighbors(data,lowest-1,lowest+1)));

    function findLowest(data){
      var indexLowest=1;
      for(let i=1;i<data.length-1;i++){
        if(data[i].text.length<data[indexLowest].text.length){
          indexLowest = i;
        }
      }
      return indexLowest;
    }    
    function compareNeighbors(data,prev,next){
      if (data[prev].value < data[next].value) return prev;
      else if (data[prev].value > data[next].value) return next;
      else {
        if (data[prev].text.length < data[next].text.length) return prev;
        else if(data[prev].text.length > data[next].text.length) return next;
        else {
          if (prev < data.length/2) return next;
          else return prev;
        }
      }
    }
    function merge(data,base,merger){
      var i;
      var next;
      if(merger<base){
        i=merger;
        next=base;
      } else {
        i=base;
        next=merger;
      }
      data[i].value += 1;
      data[i].text = data[i].text.concat(' '+data[next].text);
      data.splice(next,1);
      return data;
    }
    
  }
  
}
//color switch based on console string
function color(data){
  var f=360/19;
  return data.category ? check(data.category) : check(data.name);
  function check(str){
    switch (str) {
      case "Video Game Sales Data Top 100":
        return 'none';
      case "2600":
        return hslColor(f*2);
      case "Wii":
        return hslColor(f*3);
      case "NES":
        return hslColor(f*4);
      case "GB":
        return hslColor(f*5);
      case "DS":
        return hslColor(f*6);
      case "X360":
        return hslColor(f*7);
      case "PS3":
        return hslColor(f*8);
      case "PS2":
        return hslColor(f*9);
      case "SNES":
        return hslColor(f*10);
      case "GBA":
        return hslColor(f*11);
      case "PS4":
        return hslColor(f*12);
      case "3DS":
        return hslColor(f*13);
      case "N64":
        return hslColor(f*14);
      case "PS":
        return hslColor(f*15);
      case "XB":
        return hslColor(f*16);
      case "PC":
        return hslColor(f*17);
      case "PSP":
        return hslColor(f*18);
      case "XOne":
        return hslColor(f*19);
      default:
        return false;
    }
  }
  function hslColor(hue){
    return 'hsl('+(hue-1)+',70%,'+(data.category?'60%':'80%')+')'
  }
}
              
            
!
999px

Console