renderRects = (data, width, size, top) => {
const area = Math.pow(size, 2)
const perRow = width / size
let masterY = top ? 0 : height - size
let soFar = 0
const render = _.map(data, ({total, color, text}) => {
const numCubes = Math.ceil(total / area)
const rects = _.times(numCubes, i => {
i += soFar
return {
x: (i % perRow) * size,
y: masterY + (top ? 1 : -1) * Math.floor(i / perRow) * size
}
})
const rows = Math.floor(numCubes / perRow)
soFar += numCubes - rows * perRow
masterY += (top ? 1 : -1) * rows * size
const {x, y} = _.last(rects)
return {color, rects, text, x, y}
})
console.log(render)
const svg = d3.select(DOM.svg(width, height))
const candidates = svg.append('g')
.selectAll('g')
.data(render).join('g')
.attr('fill', d => d.color)
candidates.selectAll('rect')
.data(d => d.rects).join('rect')
.attr('x', d => d.x)
.attr('y', d => d.y)
.attr('width', d => size)
.attr('height', d => size)
svg.append('g').selectAll('text')
.data(render).join('text')
.attr('transform', d => `translate(${d.x + size - 2}, ${d.y + size / 2})`)
.attr('fill', '#fff')
.text(d => d.text)
return svg.node()
}