| 1 | import config from '../config'; |
| 2 | |
| 3 | export default function addLegend(parent, { |
| 4 | items, position, unxkcdify, parentWidth, parentHeight, strokeColor, backgroundColor, |
| 5 | }) { |
| 6 | const filter = !unxkcdify ? 'url(#xkcdify)' : null; |
| 7 | |
| 8 | const legend = parent.append('svg'); |
| 9 | const backgroundLayer = legend.append('svg'); |
| 10 | const textLayer = legend.append('svg'); |
| 11 | |
| 12 | items.forEach((item, i) => { |
| 13 | textLayer.append('rect') |
| 14 | .style('fill', item.color) |
| 15 | .attr('width', 8) |
| 16 | .attr('height', 8) |
| 17 | .attr('filter', filter) |
| 18 | .attr('rx', 2) |
| 19 | .attr('ry', 2) |
| 20 | .attr('x', 15) |
| 21 | .attr('y', 17 + 20 * i); |
| 22 | |
| 23 | textLayer.append('text') |
| 24 | .style('font-size', '15') |
| 25 | .style('fill', strokeColor) |
| 26 | .attr('x', 15 + 12) |
| 27 | .attr('y', 17 + 20 * i + 8) |
| 28 | .text(item.text); |
| 29 | }); |
| 30 | |
| 31 | // wait for textLayer to render, a bit wired |
| 32 | setTimeout(() => { |
| 33 | const bbox = textLayer.node().getBBox(); |
| 34 | const backgroundWidth = bbox.width + 15; |
| 35 | const backgroundHeight = bbox.height + 10; |
| 36 | |
| 37 | let legendX = 0; |
| 38 | let legendY = 0; |
| 39 | if ( |
| 40 | position === config.positionType.downLeft |
| 41 | || position === config.positionType.downRight |
| 42 | ) { |
| 43 | legendY = parentHeight - backgroundHeight - 13; |
| 44 | } |
| 45 | if ( |
| 46 | position === config.positionType.upRight |
| 47 | || position === config.positionType.downRight |
| 48 | ) { |
| 49 | legendX = parentWidth - backgroundWidth - 13; |
| 50 | } |
| 51 | |
| 52 | // add background |
| 53 | backgroundLayer.append('rect') |
| 54 | .style('fill', backgroundColor) |
| 55 | .attr('filter', filter) |
| 56 | .attr('fill-opacity', 0.85) |
| 57 | .attr('stroke', strokeColor) |
| 58 | .attr('stroke-width', 2) |
| 59 | .attr('width', backgroundWidth) |
| 60 | .attr('height', backgroundHeight) |