createGrid = config => {
config = {
data: null,
columnLength: null,
squareSize: width / 5 - 5,
squareCol: '#66ab56',
strokeCol: '#fff',
strokeWidth: 2,
textFill: '#000',
...config,
}
const { data, squareSize, squareCol, strokeCol, strokeWidth, textFill, columnLength } = config
const dataLength = data.length
const size = squareSize + (strokeWidth * 2)
const columns = (columnLength !== null && columnLength > 1 ) ? columnLength : Math.round(width / size)
const height = Math.ceil(Math.ceil(dataLength / columns) * size)
console.info('squareSize', squareSize)
console.info('size', size)
console.info('columns', columns)
console.log('height', height)
const svg = DOM.svg(width, height)
const sel = d3.select(svg)
const scaleCol = d3.scaleLinear()
.domain([0, columns])
.range([0, columns * size])
const scaleRow = d3.scaleLinear()
.domain([0, Math.ceil(dataLength / columns)])
.range([0, height])
const join = sel.selectAll('g')
.data(data)
.enter().append('g')
.attr('transform', (d, i) => {
const x = i % columns
const y = Math.floor(i / columns)
return `translate(${scaleCol(x)}, ${scaleRow(y)})`
})
join.append('rect')
.attr('x', 0)
.attr('y', 0)
.attr('width', squareSize)
.attr('height', squareSize)
.attr('stroke-width', strokeWidth)
.attr('stroke', strokeCol)
.attr('fill', d => {
return d3.rgb(d.rgb[0], d.rgb[1], d.rgb[2]);
})
join.append('rect')
.attr('x', 10)
.attr('y', squareSize - 30)
.attr('width', squareSize - 20)
.attr('height', 20)
.attr('stroke-width', strokeWidth)
.attr('stroke', strokeCol)
.style('opacity', '0.4')
.attr('fill', '#fff')
join.append('text')
.attr('x', squareSize / 2 )
.attr('y', squareSize - 30)
.attr('dy', 15)
.attr('text-anchor', 'middle')
.style('font-size', '13px')
.style('letter-spacing', '1px')
.style('fill', textFill)
.style('user-select', 'none')
.text(d => d.name)
join.append('text')
.attr('x', squareSize / 2 )
.attr('y', squareSize - 65)
.attr('dy', -25)
.attr('text-anchor', 'middle')
.style('font-size', '11px')
.style('letter-spacing', '1px')
.style('fill', textFill)
.text(d => d.index)
join.append('text')
.attr('x', squareSize / 2 )
.attr('y', squareSize - 65)
.attr('dy', -5)
.attr('text-anchor', 'middle')
.style('font-size', '11px')
.style('letter-spacing', '1px')
.style('fill', textFill)
.text(d => d3.rgb(d.rgb[0], d.rgb[1], d.rgb[2]))
join.append('text')
.attr('x', squareSize / 2 )
.attr('y', squareSize - 65)
.attr('dy', 15)
.attr('text-anchor', 'middle')
.style('font-size', '11px')
.style('letter-spacing', '1px')
.style('fill', textFill)
.text(d => d.hex)
return svg
}