All files / components/shared YaxisBand.tsx

0% Statements 0/53
0% Branches 0/31
0% Functions 0/13
0% Lines 0/51

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159                                                                                                                                                                                                                                                                                                                             
import React, { FC, useLayoutEffect, useRef, useMemo, useCallback } from "react";
import { ScaleBand } from "d3-scale";
import * as d3 from "d3";
 
// Simple text width estimation (average character width ~7px for 12px font)
const estimateTextWidth = (text: string): number => {
  return text.length * 7;
};
 
interface Props {
  yScale: ScaleBand<string>;
  width: number;
  margin: { top: number; right: number; bottom: number; left: number };
  yAxisFormat?: (d: number | string) => string;
  showGrid?: boolean;
  onHover?: (label: string | null) => void;
  hoveredItem?: string | null;
  tickHtmlWidth?: number;
  enableTransitions?: boolean;
  isRendering?: boolean;
}
 
const YaxisBand: FC<Props> = ({
  yScale,
  width,
  margin,
  yAxisFormat,
  showGrid,
  onHover,
  hoveredItem,
  tickHtmlWidth = 100,
  enableTransitions = true,
  isRendering = false,
}) => {
  const ref = useRef<SVGGElement>(null);
  const renderedRef = useRef(false);
 
  // Memoize the axis generator
  const axisGenerator = useMemo(() => {
    return d3
      .axisLeft(yScale)
      .tickFormat(d => (yAxisFormat ? yAxisFormat(d) : d))
      .tickSize(0);
  }, [yScale, yAxisFormat]);
 
  // Memoize the grid width calculation with dynamic adjustment
  const gridWidth = useMemo(() => {
    // Calculate the maximum label width
    const domain = yScale.domain();
    const maxLabelWidth = Math.max(...domain.map(d => {
      const formatValue = yAxisFormat ? yAxisFormat(d) : String(d);
      return estimateTextWidth(formatValue);
    }));
    
    // Calculate adjusted grid width: full width minus label overlap
    const labelOverlapBuffer = 10; // 10px buffer
    const adjustedGridWidth = Math.max(
      width - margin.left - margin.right - Math.max(0, maxLabelWidth - tickHtmlWidth + labelOverlapBuffer),
      50 // Minimum grid line length
    );
    
    return adjustedGridWidth;
  }, [width, margin, yScale, yAxisFormat, tickHtmlWidth]);
 
  const updateAxis = useCallback(() => {
    if (!ref.current) return;
 
    const g = d3.select(ref.current);
 
    // Clear previous content
    g.selectAll("*").remove();
 
    // Add the y-axis with ticks
    g.attr("class", "y-axis")
      .attr("transform", "translate(" + margin.left + ",0)")
      .call(axisGenerator);
 
    // Remove domain line and tick lines
    g.select(".domain").remove();
    g.selectAll(".tick line").remove();
 
    // Remove existing text labels
    g.selectAll(".tick *").remove();
 
    // Remove existing tick lines
    g.selectAll(".tick-line").remove();
 
    // Append foreignObject for HTML content
    g.selectAll(".tick")
      .append("foreignObject")
      .attr("class", "tick-html")
      .attr("x", -100)
      .attr("y", -10)
      .attr("width", tickHtmlWidth)
      .attr("height", 20)
      .html(
        d =>
          `<div style="display:flex;align-items:center;height:100%;cursor:pointer" title="${d}"><span>${d}</span></div>`
      )
      .on("mouseenter", function (_, d) {
        if (onHover) {
          onHover(d as string);
        }
      })
      .on("mouseleave", function () {
        if (onHover) {
          onHover(null);
        }
      });
 
    // Add dashed lines on each tick
    g.selectAll(".tick")
      .append("line")
      .attr("class", "tick-line")
      .attr("x1", 0)
      .attr("x2", gridWidth)
      .attr("y1", 0)
      .attr("y2", 0)
      .style("stroke-dasharray", "1.5")
      .style("stroke", showGrid ? "lightgray" : "transparent");
  }, [axisGenerator, margin.left, showGrid, gridWidth, onHover]);
 
  useLayoutEffect(() => {
    if (!renderedRef.current) {
      // First render with transition
      if (ref.current && enableTransitions) {
        const g = d3.select(ref.current);
        g.selectAll(".tick").attr("opacity", 0).transition().duration(500).attr("opacity", 1);
      }
      renderedRef.current = true;
    }
    updateAxis();
  }, [updateAxis, enableTransitions]);
 
  // Separate effect for hover state changes and rendering state
  useLayoutEffect(() => {
    if (!ref.current) return;
    const g = d3.select(ref.current);
 
    g.selectAll(".tick-html").each(function (d) {
      const element = d3.select(this);
      let opacity = 0;
 
      if (!isRendering) {
        opacity = hoveredItem === null ? 1 : d === hoveredItem ? 1 : 0.3;
      }
 
      element.style("opacity", opacity);
      if (enableTransitions) {
        element.style("transition", "opacity 0.2s ease-in-out");
      }
    });
  }, [hoveredItem, isRendering, enableTransitions]);
 
  return <g ref={ref} />;
};
 
export default YaxisBand;