all files / src/visualizations/ word_cloud.js

18.75% Statements 6/32
0% Branches 0/4
0% Functions 0/11
20.69% Lines 6/29
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64                                                                                                                   
/* eslint-disable  no-use-before-define */
import d3 from 'd3';
import cloudLayout from 'd3-cloud';
import { getColorFromScheme } from '../modules/colors';
 
function wordCloudChart(slice, payload) {
  const chart = d3.select(slice.selector);
  const data = payload.data;
  const fd = slice.formData;
  const range = [
    fd.size_from,
    fd.size_to,
  ];
  const rotation = fd.rotation;
  let fRotation;
  if (rotation === 'square') {
    fRotation = () => Math.floor((Math.random() * 2) * 90);
  } else if (rotation === 'flat') {
    fRotation = () => 0;
  } else {
    fRotation = () => Math.floor(((Math.random() * 6) - 3) * 30);
  }
  const size = [slice.width(), slice.height()];
 
  const scale = d3.scale.linear()
  .range(range)
  .domain(d3.extent(data, function (d) {
    return d.size;
  }));
 
  function draw(words) {
    chart.selectAll('*').remove();
 
    chart.append('svg')
    .attr('width', layout.size()[0])
    .attr('height', layout.size()[1])
    .append('g')
    .attr('transform', `translate(${layout.size()[0] / 2},${layout.size()[1] / 2})`)
    .selectAll('text')
    .data(words)
    .enter()
    .append('text')
    .style('font-size', d => d.size + 'px')
    .style('font-family', 'Impact')
    .style('fill', d => getColorFromScheme(d.text, fd.color_scheme))
    .attr('text-anchor', 'middle')
    .attr('transform', d => `translate(${d.x}, ${d.y}) rotate(${d.rotate})`)
    .text(d => d.text);
  }
 
  const layout = cloudLayout()
  .size(size)
  .words(data)
  .padding(5)
  .rotate(fRotation)
  .font('serif')
  .fontSize(d => scale(d.size))
  .on('end', draw);
 
  layout.start();
}
 
module.exports = wordCloudChart;