| 
 | 1 | +import {create} from "d3";  | 
 | 2 | +import {Mark} from "../plot.js";  | 
 | 3 | +import {number} from "../options.js";  | 
 | 4 | +import {applyDirectStyles, applyIndirectStyles, applyTransform, offset} from "../style.js";  | 
 | 5 | +import {sqrt4_3} from "../symbols.js";  | 
 | 6 | + | 
 | 7 | +const defaults = {  | 
 | 8 | +  ariaLabel: "hexgrid",  | 
 | 9 | +  fill: "none",  | 
 | 10 | +  stroke: "currentColor",  | 
 | 11 | +  strokeOpacity: 0.1  | 
 | 12 | +};  | 
 | 13 | + | 
 | 14 | +export function hexgrid(options) {  | 
 | 15 | +  return new Hexgrid(options);  | 
 | 16 | +}  | 
 | 17 | + | 
 | 18 | +export class Hexgrid extends Mark {  | 
 | 19 | +  constructor({radius = 10, clip = true, ...options} = {}) {  | 
 | 20 | +    super(undefined, undefined, {clip, ...options}, defaults);  | 
 | 21 | +    this.radius = number(radius);  | 
 | 22 | +  }  | 
 | 23 | +  render(index, scales, channels, dimensions) {  | 
 | 24 | +    const {dx, dy, radius: rx} = this;  | 
 | 25 | +    const {marginTop, marginRight, marginBottom, marginLeft, width, height} = dimensions;  | 
 | 26 | +    const x0 = marginLeft, x1 = width - marginRight, y0 = marginTop, y1 = height - marginBottom;  | 
 | 27 | +    const ry = rx * sqrt4_3, hy = ry / 2, wx = rx * 2, wy = ry * 1.5;  | 
 | 28 | +    const path = `m0,${-ry}l${rx},${hy}v${ry}l${-rx},${hy}`;  | 
 | 29 | +    const i0 = Math.floor(x0 / wx), i1 = Math.ceil(x1 / wx);  | 
 | 30 | +    const j0 = Math.floor((y0 + hy) / wy), j1 = Math.ceil((y1 - hy) / wy) + 1;  | 
 | 31 | +    const m = [];  | 
 | 32 | +    for (let j = j0; j < j1; ++j) {  | 
 | 33 | +      for (let i = i0; i < i1; ++i) {  | 
 | 34 | +        m.push(`M${i * wx + (j & 1) * rx},${j * wy}${path}`);  | 
 | 35 | +      }  | 
 | 36 | +    }  | 
 | 37 | +    return create("svg:g")  | 
 | 38 | +        .call(applyIndirectStyles, this, dimensions)  | 
 | 39 | +        .call(g => g.append("path")  | 
 | 40 | +          .call(applyDirectStyles, this)  | 
 | 41 | +          .call(applyTransform, null, null, offset + dx, offset + dy)  | 
 | 42 | +          .attr("d", m.join("")))  | 
 | 43 | +      .node();  | 
 | 44 | +  }  | 
 | 45 | +}  | 
0 commit comments