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 | import * as d3 from "d3";
import React, { useEffect, useMemo, useRef, useLayoutEffect } from "react";
import { useChartContext } from "../components/MichiVzProvider";
import Title from "../components/shared/Title";
import { useDisplayIsNodata } from "./hooks/useDisplayIsNodata";
import LoadingIndicator from "./shared/LoadingIndicator";
import XaxisLinear from "./shared/XaxisLinear";
import YaxisBand from "./shared/YaxisBand";
import useDeepCompareEffect from "use-deep-compare-effect";
interface DataPoint {
label: string;
color?: string;
value1: number;
value2: number;
}
const MARGIN = { top: 50, right: 50, bottom: 50, left: 50 };
const WIDTH = 900 - MARGIN.left - MARGIN.right;
const HEIGHT = 480 - MARGIN.top - MARGIN.bottom;
interface LineChartProps {
dataSet: DataPoint[];
width: number;
height: number;
margin: { top: number; right: number; bottom: number; left: number };
xAxisFormat?: (d: number | { valueOf(): number }) => string;
xAxisDataType: "number" | "date_annual" | "date_monthly";
yAxisFormat?: (d: number | string) => string;
title?: string;
tooltipFormatter?: (
d: DataPoint | undefined,
dataSet?: {
label: string;
color: string;
series: DataPoint[];
}[]
) => string;
children?: React.ReactNode;
isLoading?: boolean;
isLoadingComponent?: React.ReactNode;
isNodataComponent?: React.ReactNode;
isNodata?: boolean | ((dataSet: DataPoint[]) => boolean);
filter?: {
limit: number; // new; replaces top
criteria: "valueBased" | "valueCompared"; // sorting criteria
sortingDir: "asc" | "desc";
};
onChartDataProcessed?: (metadata: ChartMetadata) => void;
onHighlightItem?: (labels: string[]) => void;
tickHtmlWidth?: number;
}
interface ChartMetadata {
xAxisDomain: string[];
yAxisDomain: [number, number];
visibleItems: string[];
renderedData: { [key: string]: DataPoint[] };
chartType: "dual-horizontal-bar-chart";
}
const DualHorizontalBarChart: React.FC<LineChartProps> = ({
dataSet,
filter,
title,
width = WIDTH,
height = HEIGHT,
margin = MARGIN,
yAxisFormat,
xAxisFormat,
xAxisDataType = "number",
tooltipFormatter,
children,
isLoading = false,
isLoadingComponent,
isNodataComponent,
isNodata,
onChartDataProcessed,
onHighlightItem,
tickHtmlWidth,
}) => {
const [tooltip, setTooltip] = React.useState<{
x: number;
y: number;
data: DataPoint;
} | null>(null);
const { colorsMapping, colorsBasedMapping, highlightItems, disabledItems, visibleItems } =
useChartContext();
const svgRef = useRef<SVGSVGElement | null>(null);
const renderCompleteRef = useRef(false);
const prevChartDataRef = useRef<ChartMetadata | null>(null);
useLayoutEffect(() => {
renderCompleteRef.current = true;
}, []);
// New: compute filteredDataSet
const filteredDataSet = useMemo(() => {
// First filter out disabled items
let result = dataSet.filter(d => !disabledItems.includes(d.label));
// Then apply filter logic if filter exists
if (filter) {
result = result
.slice() // copy array to avoid mutating original during sort
.sort((a, b) => {
const aVal = a[filter.criteria] ?? 0;
const bVal = b[filter.criteria] ?? 0;
return filter.sortingDir === "desc" ? bVal - aVal : aVal - bVal;
})
.slice(0, filter.limit);
}
return result;
}, [dataSet, filter, disabledItems]);
const yAxisDomain = useMemo(
() => filteredDataSet.filter(d => !disabledItems.includes(d.label)).map(d => d.label),
[filteredDataSet]
);
const xAxisDomain = useMemo(() => {
const flattenedValues = filteredDataSet
.filter(d => !disabledItems.includes(d.label))
.map(d => [d.value1, d.value2])
.flat();
if (xAxisDataType === "number") {
return [Math.max(...flattenedValues), 0];
}
if (xAxisDataType === "date_annual" || xAxisDataType === "date_monthly") {
return [
new Date(Math.max(...flattenedValues), 1, 1),
new Date(0, 1, 1), // Assuming the minimum date is January 1, 1900
];
}
return [];
}, [filteredDataSet, disabledItems, xAxisDataType]);
const yAxisScale = d3
.scaleBand()
.domain(yAxisDomain)
.range([margin.top, height - margin.bottom]);
const xAxis1Scale = d3
.scaleLinear()
.domain(xAxisDomain)
.range([width - margin.right, width / 2])
.clamp(true)
.nice(1);
const xAxis2Scale = d3
.scaleLinear()
.domain(xAxisDomain)
.range([margin.left, width / 2])
.clamp(true)
.nice(1);
const handleMouseOver = (d: DataPoint, event: React.MouseEvent<SVGRectElement, MouseEvent>) => {
if (svgRef.current) {
const mousePoint = d3.pointer(event.nativeEvent, svgRef.current);
setTooltip(() => ({
x: mousePoint[0],
y: mousePoint[1],
data: d,
}));
}
};
const handleMouseOut = () => {
setTooltip(null);
};
useEffect(() => {
d3.select(svgRef.current).select(".bar").attr("opacity", 0.3);
highlightItems.forEach(item => {
d3.select(svgRef.current)
.select(`.bar-${item.replaceAll(" ", "-").replaceAll(",", "")}`)
.attr("opacity", 1);
});
}, [highlightItems]);
const displayIsNodata = useDisplayIsNodata({
dataSet: dataSet,
isLoading: isLoading,
isNodataComponent: isNodataComponent,
isNodata: isNodata,
});
// Replace useEffect with useDeepCompareEffect for metadata comparison
useDeepCompareEffect(() => {
if (renderCompleteRef.current && onChartDataProcessed) {
// Ensure unique labels
const uniqueLabels = [...new Set(yAxisDomain)];
const currentMetadata: ChartMetadata = {
xAxisDomain: uniqueLabels,
yAxisDomain: [Number(yAxisScale.domain()[0]), Number(yAxisScale.domain()[1])],
visibleItems: visibleItems,
renderedData: {
[uniqueLabels[0]]: filteredDataSet,
},
chartType: "dual-horizontal-bar-chart",
};
// Check if data has actually changed
const hasChanged =
!prevChartDataRef.current ||
JSON.stringify(prevChartDataRef.current.xAxisDomain) !==
JSON.stringify(currentMetadata.xAxisDomain) ||
JSON.stringify(prevChartDataRef.current.yAxisDomain) !==
JSON.stringify(currentMetadata.yAxisDomain) ||
JSON.stringify(prevChartDataRef.current.visibleItems) !==
JSON.stringify(currentMetadata.visibleItems) ||
JSON.stringify(Object.keys(prevChartDataRef.current.renderedData).sort()) !==
JSON.stringify(Object.keys(currentMetadata.renderedData).sort());
// Only call callback if data has changed
if (hasChanged) {
// Update ref before calling callback
prevChartDataRef.current = currentMetadata;
// Call callback with slight delay to ensure DOM updates are complete
const timeoutId = setTimeout(() => {
onChartDataProcessed(currentMetadata);
}, 0);
return () => clearTimeout(timeoutId);
}
}
}, [yAxisDomain, xAxisDomain, visibleItems, filteredDataSet, onChartDataProcessed]);
return (
<div style={{ position: "relative" }}>
<svg
width={width}
height={height}
ref={svgRef}
style={{ overflow: "visible" }}
onMouseOut={event => {
event.stopPropagation();
event.preventDefault();
onHighlightItem([]);
}}
>
{children}
<Title x={width / 2} y={margin.top / 2}>
{title}
</Title>
{filteredDataSet.length > 0 && !isLoading && (
<>
<XaxisLinear
xScale={xAxis1Scale}
height={height}
margin={margin}
xAxisFormat={xAxisFormat}
xAxisDataType={xAxisDataType}
/>
<XaxisLinear
xScale={xAxis2Scale}
height={height}
margin={margin}
xAxisFormat={xAxisFormat}
xAxisDataType={xAxisDataType}
/>
<YaxisBand
yScale={yAxisScale}
width={width}
margin={margin}
yAxisFormat={yAxisFormat}
tickHtmlWidth={tickHtmlWidth}
/>
</>
)}
{filteredDataSet
.filter(d => !disabledItems.includes(d.label))
.map((d, i) => {
const x1 = xAxis1Scale(d.value1) - width / 2; // Corrected width calculation
const x2 = xAxis2Scale(0) - xAxis2Scale(d.value2); // Corrected width calculation
const y = yAxisScale(d.label) || 0;
const standardHeight = yAxisScale.bandwidth();
return (
<g
className={`bar bar-${d.label.replaceAll(" ", "-").replaceAll(",", "")}`}
key={i}
style={{
opacity:
highlightItems.includes(d.label) || highlightItems.length === 0 ? 1 : 0.3,
}}
onMouseOver={() => onHighlightItem([d.label])}
onMouseOut={() => onHighlightItem([])}
>
<rect
x={width / 2}
// y should be aligned to the center of the bandwidth's unit with height = 30
y={y + (standardHeight - 30) / 2}
width={x1}
height={30}
fill={colorsBasedMapping[d.label]}
rx={5}
ry={5}
onMouseOver={event => handleMouseOver(d, event)}
onMouseOut={handleMouseOut}
stroke={"#fff"}
/>
<rect
x={width / 2 - x2}
y={y + (standardHeight - 30) / 2}
width={x2}
height={30}
fill={colorsMapping[d.label]}
opacity={0.8}
rx={3}
ry={3}
onMouseOver={event => handleMouseOver(d, event)}
onMouseOut={handleMouseOut}
stroke={"#fff"}
/>
{!d.value1 && !d.value2 && (
<>
<rect
x={width / 2 - 5}
// y should be aligned to the center of the bandwidth's unit with height = 30
y={y + (standardHeight - 30) / 2}
width={10}
height={30}
fill={colorsBasedMapping[d.label]}
rx={3}
ry={3}
onMouseOver={event => handleMouseOver(d, event)}
onMouseOut={handleMouseOut}
/>
<text
x={width / 2 + 15}
y={y + (standardHeight - 30) / 2 + 20}
fill="black"
fontSize="12px"
fontWeight="bold"
>
N/A
</text>
</>
)}
</g>
);
})}
</svg>
{tooltip && (
<div
style={{
position: "absolute",
left: `${tooltip?.x}px`,
top: `${tooltip?.y}px`,
background: "white",
padding: "5px",
pointerEvents: "none",
}}
>
{!tooltipFormatter && (
<div>
${tooltip?.data?.label}: ${tooltip?.data?.value1} - ${tooltip?.data?.value2}
</div>
)}
{tooltipFormatter && tooltipFormatter(tooltip?.data)}
</div>
)}
{isLoading && isLoadingComponent && <>{isLoadingComponent}</>}
{isLoading && !isLoadingComponent && <LoadingIndicator />}
{displayIsNodata && <>{isNodataComponent}</>}
</div>
);
};
export default DualHorizontalBarChart;
|