All files / components GapChart.tsx

0% Statements 0/65
0% Branches 0/95
0% Functions 0/23
0% Lines 0/64

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 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
import React, { FC, useRef, useState, useMemo, useEffect } from "react";
import styled from "styled-components";
import { ChartMetadata } from "src/types/data";
import Title from "./shared/Title";
import XaxisLinear from "./shared/XaxisLinear";
import YaxisBand from "./shared/YaxisBand";
import LoadingIndicator from "./shared/LoadingIndicator";
import { useChartContext } from "./MichiVzProvider";
import { useDisplayIsNodata } from "./hooks/useDisplayIsNodata";
import { useGapChartData } from "./hooks/gapChart/useGapChartData";
import { useGapChartScales } from "./hooks/gapChart/useGapChartScales";
import { useGapChartColors } from "./hooks/gapChart/useGapChartColors";
import { useGapChartTooltip } from "./hooks/gapChart/useGapChartTooltip";
import { useGapChartShapes } from "./hooks/gapChart/useGapChartShapes";
import { useGapChartRenderer } from "./hooks/gapChart/useGapChartRenderer";
import { useGapChartLegend } from "./hooks/gapChart/useGapChartLegend";
import { useGapChartMetadata } from "./hooks/gapChart/useGapChartMetadata";
import { useGapChartAnimation } from "./hooks/gapChart/useGapChartAnimation";
 
const DEFAULT_WIDTH = 1000;
const DEFAULT_HEIGHT = 500;
const DEFAULT_MARGIN = { top: 50, right: 150, bottom: 100, left: 150 };
 
const GapChartStyled = styled.div<{ $enableTransitions: boolean }>`
  position: relative;
 
  .gap-bar {
    /* Transitions are now handled inline based on animation state */
  }
 
  .gap-line {
    stroke-width: 2;
    fill: none;
    /* Transitions are now handled inline based on animation state */
  }
 
  .gap-marker {
    /* Transitions are now handled inline based on animation state */
  }
 
  .tooltip {
    position: absolute;
    background: white;
    border: 1px solid #ccc;
    border-radius: 4px;
    padding: 8px;
    pointer-events: none;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    font-size: 12px;
    z-index: 10;
 
    &.sticky {
      pointer-events: auto;
      cursor: default;
      border-color: #666;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
    }
  }
`;
 
interface DataItem {
  label: string;
  code?: string;
  value1: number;
  value2: number;
  difference: number; // sugggest formula to calculate difference is value1 - value2, we use this property for sorting items (when the filter property is defined)
  date: string;
}
 
interface Filter {
  limit: number;
  date: number | string;
  criteria: string;
  sortingDir: "asc" | "desc";
}
 
interface LegendItem {
  type: "value1" | "value2" | "gap";
  label: string;
  color?: string;
  shape?: "circle" | "square" | "triangle";
}
 
interface GapChartProps {
  dataSet: DataItem[];
  title: string;
  colors?: string[];
  colorsMapping?: Record<string, string>; // predefined colors mapping for specific labels, if not defined, the colors array will be to use generated colors, and generated colors will be cached so that the color of a specific label will not change between renders
  colorMode?: "label" | "shape"; // whether to assign colors by label (default) or by shape
  shapeColorsMapping?: {
    value1?: string;
    value2?: string;
    gap?: string;
  }; // explicit color mapping for shapes when colorMode is "shape"
  highlightItems?: string[]; // items to highlight, if not defined, all items will be highlighted
  disabledItems?: string[]; // items to disable (not being rendered), if not defined, all items will be showed
  tooltipFormatter?: (data: DataItem) => string;
  filter: Filter | undefined;
  shapeValue1: "circle" | "square" | "triangle";
  shapeValue2: "circle" | "square" | "triangle";
  shapesLabelsMapping?: {
    value1?: string;
    value2?: string;
    gap?: string;
  };
  legendFormatter?: (items: LegendItem[]) => LegendItem[];
  xAxisDataType: "number" | "date_annual" | "date_monthly";
  yAxisFormat?: (d: number) => string;
  xAxisFormat?: (d: number) => string;
  ticks?: number;
  width: number;
  height: number;
  margin: { top: number; right: number; bottom: number; left: number };
  tickHtmlWidth?: number;
  onHighlightItem?: (item: DataItem) => void;
  onDisabledItem?: (item: DataItem) => void;
  onColorChange?: (item: DataItem, color: string) => void;
  onChartDataProcessed?: (metadata: ChartMetadata) => void;
  isNodata?: boolean | ((dataSet: DataItem[]) => boolean);
  isNodataComponent?: React.ReactNode;
  isLoading?: boolean;
  isLoadingComponent?: React.ReactNode;
  enableTransitions?: boolean;
  legendAlign?: "left" | "center" | "right";
  squareRadius?: number; // border radius for square shapes (default: 2)
}
 
const GapChart: FC<GapChartProps> = ({
  dataSet,
  title,
  colors = [
    "#1f77b4",
    "#ff7f0e",
    "#2ca02c",
    "#d62728",
    "#9467bd",
    "#8c564b",
    "#e377c2",
    "#7f7f7f",
    "#bcbd22",
    "#17becf",
  ],
  colorsMapping,
  colorMode = "label",
  shapeColorsMapping,
  highlightItems: propsHighlightItems,
  disabledItems: propsDisabledItems,
  tooltipFormatter,
  filter,
  shapeValue1,
  shapeValue2,
  shapesLabelsMapping,
  legendFormatter,
  xAxisDataType,
  yAxisFormat,
  xAxisFormat,
  ticks = 5,
  width = DEFAULT_WIDTH,
  height = DEFAULT_HEIGHT,
  margin = DEFAULT_MARGIN,
  tickHtmlWidth,
  onHighlightItem,
  onChartDataProcessed,
  isNodata,
  isNodataComponent,
  isLoading,
  isLoadingComponent,
  enableTransitions = true,
  legendAlign = "left",
  squareRadius = 2,
}) => {
  const svgRef = useRef<SVGSVGElement | null>(null);
  const containerRef = useRef<HTMLDivElement | null>(null);
  const [hoveredYItem, setHoveredYItem] = useState<string | null>(null);
  const [isRendering, setIsRendering] = useState(false);
 
  const { highlightItems: contextHighlightItems, disabledItems: contextDisabledItems } =
    useChartContext();
  const highlightItems = propsHighlightItems || contextHighlightItems || [];
  const disabledItems = propsDisabledItems || contextDisabledItems || [];
 
  // Process data and get domains
  const { processedDataSet, yAxisDomain, xAxisDomain } = useGapChartData(
    dataSet,
    filter,
    disabledItems
  );
 
  // Get scales
  const { xScale, yScale } = useGapChartScales(
    xAxisDomain,
    yAxisDomain,
    width,
    height,
    margin,
    xAxisDataType,
    tickHtmlWidth
  );
 
  // Get color function
  const { getColor, getShapeColor } = useGapChartColors(
    yAxisDomain,
    colors,
    colorsMapping,
    colorMode,
    shapeColorsMapping
  );
 
  // Get tooltip handlers
  const { tooltip, handleMouseOver, handleMouseOut, handleChartElementClick, handleTooltipClick } =
    useGapChartTooltip(svgRef, containerRef, onHighlightItem);
 
  // Get shape generation function
  const { getShapePath, getSquareDimensions } = useGapChartShapes();
 
  // Get animation state
  const { animationState, getItemOpacity, getItemTransform, renderDataSet, shouldTransition } =
    useGapChartAnimation(processedDataSet, enableTransitions);
 
  // Get render data with animation support
  const renderData = useGapChartRenderer({
    processedDataSet: renderDataSet,
    xScale,
    yScale,
    getColor,
    getShapeColor,
    colorMode,
    highlightItems,
    shapeValue1,
    shapeValue2,
    hoveredYItem,
    animationState,
    getItemOpacity,
    getItemTransform,
    shouldTransition,
  });
 
  // Get legend items
  const { legendItems } = useGapChartLegend({
    shapesLabelsMapping,
    shapeValue1,
    shapeValue2,
    colorMode,
    shapeColorsMapping,
    legendFormatter,
  });
 
  // Handle metadata
  useGapChartMetadata({
    processedDataSet,
    xAxisDomain,
    onChartDataProcessed,
  });
 
  // Track when data is being re-rendered
  useEffect(() => {
    setIsRendering(true);
    // Set a small delay to ensure the axis hides before shapes start rendering
    const timer = setTimeout(() => {
      setIsRendering(false);
    }, 100);
 
    return () => clearTimeout(timer);
  }, [processedDataSet, xScale, yScale, yAxisFormat]);
 
  // Check if no data
  const displayIsNodata = useDisplayIsNodata({
    dataSet,
    isLoading,
    isNodataComponent,
    isNodata,
  });
 
  // Render gap bars and shapes in layers
  const renderGapBars = useMemo(() => {
    const { elements, squares, nonSquares } = renderData;
 
    return (
      <>
        {/* First layer: Render all gap bars and lines */}
        {elements.map(
          ({
            d,
            i,
            y,
            barHeight,
            gapColor,
            x1,
            x2,
            barWidth,
            barOpacity,
            markerOpacity,
            hasTransition,
          }) => (
            <g key={`gap-base-${d.label}-${i}`}>
              {/* Gap bar */}
              <rect
                className="gap-bar"
                x={x1}
                y={y + barHeight / 2 - 4}
                width={barWidth}
                height={8}
                fill={gapColor}
                opacity={barOpacity}
                rx={4}
                ry={4}
                onMouseOver={e => handleMouseOver(d, e)}
                onMouseOut={handleMouseOut}
                onClick={e => handleChartElementClick(d, e)}
                style={{
                  cursor: "pointer",
                  transition:
                    enableTransitions && hasTransition
                      ? "x 0.3s ease-out, y 0.3s ease-out, width 0.3s ease-out, opacity 0.3s ease-out"
                      : "none",
                }}
              />
 
              {/* Connecting line */}
              <line
                className="gap-line"
                x1={x1}
                y1={y + barHeight / 2}
                x2={x2}
                y2={y + barHeight / 2}
                stroke="white"
                strokeDasharray={d.difference < 0 ? "4,2" : "0"}
                opacity={markerOpacity}
                style={{
                  transition: enableTransitions && hasTransition ? "opacity 0.3s ease-out" : "none",
                }}
              />
            </g>
          )
        )}
 
        {/* Second layer: Render all square shapes */}
        {squares.map(
          ({ d, i, y, barHeight, value1Color, value2Color, markerOpacity, hasTransition }) => (
            <g key={`gap-squares-${d.label}-${i}`}>
              {shapeValue1 === "square" &&
                (() => {
                  const dims = getSquareDimensions();
                  return (
                    <rect
                      className="gap-marker value1-marker"
                      x={xScale(d.value1) + dims.x}
                      y={y + barHeight / 2 + dims.y}
                      width={dims.width}
                      height={dims.height}
                      fill={value1Color}
                      opacity={markerOpacity}
                      rx={squareRadius}
                      ry={squareRadius}
                      onMouseOver={e => handleMouseOver(d, e)}
                      onMouseOut={handleMouseOut}
                      onClick={e => handleChartElementClick(d, e)}
                      style={{
                        cursor: "pointer",
                        transition:
                          enableTransitions && hasTransition ? "opacity 0.3s ease-out" : "none",
                      }}
                    />
                  );
                })()}
              {shapeValue2 === "square" &&
                (() => {
                  const dims = getSquareDimensions();
                  return (
                    <rect
                      className="gap-marker value2-marker"
                      x={xScale(d.value2) + dims.x}
                      y={y + barHeight / 2 + dims.y}
                      width={dims.width}
                      height={dims.height}
                      fill={value2Color}
                      opacity={markerOpacity}
                      rx={2}
                      ry={2}
                      onMouseOver={e => handleMouseOver(d, e)}
                      onMouseOut={handleMouseOut}
                      onClick={e => handleChartElementClick(d, e)}
                      style={{
                        cursor: "pointer",
                        transition:
                          enableTransitions && hasTransition ? "opacity 0.3s ease-out" : "none",
                      }}
                    />
                  );
                })()}
            </g>
          )
        )}
 
        {/* Third layer: Render all circle and triangle shapes */}
        {nonSquares.map(
          ({
            d,
            i,
            y,
            barHeight,
            value1Color,
            value2Color,
            markerOpacity,
            itemTransform,
            hasTransition,
          }) => (
            <g key={`gap-nonSquares-${d.label}-${i}`}>
              {shapeValue1 !== "square" && (
                <path
                  className="gap-marker value1-marker"
                  d={getShapePath(shapeValue1) || ""}
                  transform={`translate(${xScale(d.value1)}, ${y + barHeight / 2}) ${itemTransform}`}
                  fill={value1Color}
                  opacity={markerOpacity}
                  onMouseOver={e => handleMouseOver(d, e)}
                  onMouseOut={handleMouseOut}
                  onClick={e => handleChartElementClick(d, e)}
                  style={{
                    cursor: "pointer",
                    transition:
                      enableTransitions && hasTransition ? "opacity 0.3s ease-out" : "none",
                  }}
                />
              )}
              {shapeValue2 !== "square" && (
                <path
                  className="gap-marker value2-marker"
                  d={getShapePath(shapeValue2) || ""}
                  transform={`translate(${xScale(d.value2)}, ${y + barHeight / 2}) ${itemTransform}`}
                  fill={value2Color}
                  opacity={markerOpacity}
                  onMouseOver={e => handleMouseOver(d, e)}
                  onMouseOut={handleMouseOut}
                  onClick={e => handleChartElementClick(d, e)}
                  style={{
                    cursor: "pointer",
                    transition:
                      enableTransitions && hasTransition ? "opacity 0.3s ease-out" : "none",
                  }}
                />
              )}
            </g>
          )
        )}
      </>
    );
  }, [
    renderData,
    xScale,
    shapeValue1,
    shapeValue2,
    handleMouseOver,
    handleMouseOut,
    handleChartElementClick,
    getShapePath,
  ]);
 
  return (
    <GapChartStyled ref={containerRef} $enableTransitions={enableTransitions}>
      <svg ref={svgRef} width={width} height={height} style={{ overflow: "visible" }}>
        <Title x={width / 2} y={margin.top / 2}>
          {title}
        </Title>
 
        <XaxisLinear
          xScale={xScale}
          height={height}
          margin={margin}
          xAxisFormat={xAxisFormat}
          xAxisDataType={xAxisDataType}
          ticks={ticks}
          showGrid={true}
          showZeroLine={true}
        />
 
        <YaxisBand
          yScale={yScale}
          width={width}
          margin={margin}
          yAxisFormat={yAxisFormat}
          showGrid={true}
          onHover={setHoveredYItem}
          hoveredItem={hoveredYItem}
          tickHtmlWidth={tickHtmlWidth}
          enableTransitions={enableTransitions}
          isRendering={isRendering}
        />
 
        <g className="gap-chart-content">{renderGapBars}</g>
 
        {/* Legend */}
        {shapesLabelsMapping && legendItems.length > 0 && (
          <g
            transform={`translate(${
              legendAlign === "left"
                ? margin.left
                : legendAlign === "right"
                  ? width - margin.right
                  : width / 2
            }, ${height - margin.bottom / 2 + 20})`}
          >
            {/* Create a flex-like layout for legend items */}
            {(() => {
              const items = [];
              const itemWidth = 180;
              const itemSpacing = 40;
              const shapeOffset = 15;
 
              // Calculate total width needed
              const activeItems = legendItems.length;
 
              const totalWidth = activeItems * itemWidth + (activeItems - 1) * itemSpacing;
              let currentX =
                legendAlign === "left"
                  ? 0
                  : legendAlign === "right"
                    ? -totalWidth
                    : -totalWidth / 2;
 
              // Render legend items based on the processed array
              legendItems.forEach(legendItem => {
                if (legendItem.type === "gap") {
                  items.push(
                    <g key={legendItem.type} transform={`translate(${currentX}, 0)`}>
                      <rect
                        x={-10}
                        y={-5}
                        width={20}
                        height={10}
                        fill={legendItem.color || "#999"}
                        opacity={0.7}
                        rx={2}
                        ry={2}
                      />
                      <foreignObject
                        x={shapeOffset + 5}
                        y={-10}
                        width={itemWidth - shapeOffset - 10}
                        height={20}
                      >
                        <div
                          style={{
                            fontSize: "12px",
                            color: legendItem.color || "#666",
                            whiteSpace: "nowrap",
                            overflow: "hidden",
                            textOverflow: "ellipsis",
                            paddingLeft: "5px",
                          }}
                          title={legendItem.label}
                        >
                          {legendItem.label}
                        </div>
                      </foreignObject>
                    </g>
                  );
                } else {
                  // Value1 or Value2 shape items
                  const shape = legendItem.shape || shapeValue1;
                  items.push(
                    <g key={legendItem.type} transform={`translate(${currentX}, 0)`}>
                      {shape === "square" ? (
                        (() => {
                          const dims = getSquareDimensions(12);
                          return (
                            <rect
                              x={dims.x}
                              y={dims.y}
                              width={dims.width}
                              height={dims.height}
                              fill={legendItem.color || "#666"}
                              rx={2}
                              ry={2}
                            />
                          );
                        })()
                      ) : (
                        <path d={getShapePath(shape, 12) || ""} fill={legendItem.color || "#666"} />
                      )}
                      <foreignObject
                        x={shapeOffset}
                        y={-10}
                        width={itemWidth - shapeOffset - 5}
                        height={20}
                      >
                        <div
                          style={{
                            fontSize: "12px",
                            color: legendItem.color || "#666",
                            whiteSpace: "nowrap",
                            overflow: "hidden",
                            textOverflow: "ellipsis",
                            paddingLeft: "5px",
                          }}
                          title={legendItem.label}
                        >
                          {legendItem.label}
                        </div>
                      </foreignObject>
                    </g>
                  );
                }
                currentX += itemWidth + itemSpacing;
              });
 
              return items;
            })()}
          </g>
        )}
      </svg>
 
      {tooltip && (
        <div
          className={`tooltip ${tooltip.isSticky ? "sticky" : ""}`}
          style={{
            left: `${tooltip.x + 10}px`,
            top: `${tooltip.y - 10}px`,
          }}
          onClick={handleTooltipClick}
        >
          {tooltipFormatter ? (
            tooltipFormatter(tooltip.data)
          ) : (
            <div>
              <strong>{tooltip.data.label}</strong>
              <br />
              Value 1: {tooltip.data.value1}
              <br />
              Value 2: {tooltip.data.value2}
              <br />
              Difference: {tooltip.data.difference}
            </div>
          )}
          {!tooltip.isSticky && (
            <div style={{ fontSize: "10px", marginTop: "4px", color: "#666", fontStyle: "italic" }}>
              Click chart or tooltip to pin
            </div>
          )}
        </div>
      )}
 
      {isLoading && (isLoadingComponent || <LoadingIndicator />)}
      {displayIsNodata && isNodataComponent}
    </GapChartStyled>
  );
};
 
export default GapChart;