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 | import React, { FC, useRef, useCallback, useMemo, useLayoutEffect } from "react";
import { ScaleTime, ScaleLinear } from "d3-scale";
import * as d3 from "d3";
interface Props {
xScale: ScaleTime<number, number> | ScaleLinear<number, number>;
height: number;
margin: { top: number; right: number; bottom: number; left: number };
xAxisFormat?: (d: number | { valueOf(): number } | string) => string;
xAxisDataType?: "number" | "date_annual" | "date_monthly";
ticks?: number;
showGrid?: boolean;
showZeroLine?: boolean;
position?: "top" | "bottom";
isLoading?: boolean;
isEmpty?: boolean;
tickValues?: (number | Date)[]; // <-- new prop
}
const checkIsTimeScale = (
scale: ScaleTime<number, number> | ScaleLinear<number, number>,
xAxisDataType?: "number" | "date_annual" | "date_monthly"
): scale is ScaleTime<number, number> => {
if (xAxisDataType === "date_annual" || xAxisDataType === "date_monthly") {
return true;
}
if ("ticks" in scale && "domain" in scale && "range" in scale) {
const timeScale = scale as ScaleTime<number, number>;
return (
timeScale.ticks !== undefined &&
timeScale.domain instanceof Array &&
timeScale.range instanceof Array &&
((typeof timeScale.domain[0] === "number" && typeof timeScale.range[0] === "number") ||
(timeScale.domain[0] instanceof Date && timeScale.range[0] instanceof Date))
);
}
return false;
};
const XaxisLinear: FC<Props> = ({
xScale = d3.scaleLinear().domain([0, 100]),
height,
margin,
xAxisFormat,
xAxisDataType = "number",
ticks = 5,
showGrid = false,
showZeroLine = false,
position = "bottom",
isLoading = false,
isEmpty = false,
tickValues: tickValuesProp, // <-- new prop
}) => {
const ref = useRef<SVGGElement>(null);
const isTimeScale = checkIsTimeScale(xScale, xAxisDataType);
// Memoize the default formatter
const defaultFormatter = useCallback(
(d: number | Date | { valueOf(): number }) => {
if (isTimeScale) {
const value = d instanceof Date ? d : new Date(d.valueOf());
// Format specifically for annual data
if (xAxisDataType === "date_annual") {
return `${value.getFullYear()}`;
}
// Format for monthly data
if (xAxisDataType === "date_monthly") {
const month = value.toLocaleString("en-US", { month: "short" });
const year = value.getFullYear();
return `${month} ${year}`;
}
// Default date formatting
return value.toLocaleDateString("en-US", {
year: "numeric",
month: "short",
});
}
// For numeric values
return String(d.valueOf());
},
[isTimeScale, xAxisDataType]
);
// Generate evenly spaced tick values that always include first and last
const tickValues = useMemo(() => {
if (tickValuesProp) return tickValuesProp;
// Don't generate ticks if loading or empty
if (isLoading || isEmpty) {
return [];
}
const domain = xScale.domain();
const first = domain[0];
const last = domain[1];
// Always include first and last
const result = [];
// Limit to exactly 5 ticks (or fewer if domain is smaller)
const targetTickCount = Math.min(5, ticks);
if (targetTickCount <= 2) {
return [first, last];
}
// For annual dates, handle specially to ensure years align properly
if (isTimeScale && xAxisDataType === "date_annual") {
const firstYear =
first instanceof Date ? first.getFullYear() : new Date(+first).getFullYear();
const lastYear = last instanceof Date ? last.getFullYear() : new Date(+last).getFullYear();
const yearCount = lastYear - firstYear + 1;
// If we have a reasonable number of years, show all of them
if (yearCount <= 10) {
for (let year = firstYear; year <= lastYear; year++) {
result.push(new Date(`${year}-01-01`));
}
return result;
}
// For many years, pick a sensible spacing
// Always include first and last years
result.push(new Date(`${firstYear}-01-01`));
// Calculate step size based on available space
const stepSize = Math.max(1, Math.ceil(yearCount / 10));
// Add intermediate years at regular intervals
for (let year = firstYear + stepSize; year < lastYear; year += stepSize) {
result.push(new Date(`${year}-01-01`));
}
// Add the last year if not already included
if (result[result.length - 1].getFullYear() !== lastYear) {
result.push(new Date(`${lastYear}-01-01`));
}
return result;
}
// For numeric scales or other time scales
result.push(first);
const valueRange = +last - +first;
const step = valueRange / (targetTickCount - 1);
for (let i = 1; i < targetTickCount - 1; i++) {
const value = +first + i * step;
if (isTimeScale) {
result.push(new Date(value));
} else {
result.push(value);
}
}
result.push(last);
if (
!isTimeScale &&
showZeroLine &&
!result.includes(0) &&
((+first < 0 && 0 < +last) || (+last < 0 && 0 < +first))
// Ensure 0 is included if it's within the domain
) {
result.push(0);
result.sort((a, b) => b - a);
}
return result;
}, [xScale, ticks, isTimeScale, isLoading, isEmpty, tickValuesProp, xAxisDataType, showZeroLine]);
useLayoutEffect(() => {
const g = d3.select(ref.current);
if (!g) return;
// Clear any existing axis elements to prevent duplicates
g.selectAll("*").remove();
// Create the axis and use our calculated tickValues
const axisBottom = d3
.axisBottom(xScale)
.tickValues(tickValues)
.tickFormat((domainValue: number | Date | { valueOf(): number }) =>
xAxisFormat
? xAxisFormat(domainValue instanceof Date ? domainValue : domainValue.valueOf())
: defaultFormatter(domainValue)
)
.tickSize(6); // Control tick size
// Initial setup
g.attr("class", "x-axis x-axis-linear").attr(
"style",
position === "top"
? `transform:translate(0, ${margin.top}px)`
: `transform:translate(0, ${height - margin.bottom}px)`
);
// Call the axis
g.call(axisBottom)
// Style the domain line (horizontal axis line)
.call(g => g.select(".domain").attr("stroke", "lightgray").attr("stroke-width", 1))
// Style the tick lines
.call(g => g.selectAll(".tick line").attr("stroke", "lightgray").attr("stroke-opacity", 0.5))
// Style the text
.call(g =>
g
.selectAll(".tick text")
.attr("fill", "#666")
.attr("font-size", "12px")
.attr("text-anchor", "middle")
.attr("dy", "1em")
)
// Add class for tick at 0
.call(g => {
g.selectAll(".tick").each(function (d) {
const tickValue = d instanceof Date ? d.valueOf() : +d;
if (tickValue === 0) {
d3.select(this).classed("tick-zero", true);
}
});
});
// Ensure the first and last ticks align with data points by moving them to exact edge positions
if (tickValues.length >= 2) {
const range = xScale.range();
const firstTickSelector = g.select(".tick:first-child");
const lastTickSelector = g.select(".tick:last-child");
if (!firstTickSelector.empty()) {
firstTickSelector.attr("transform", `translate(${range[0]}, 0)`);
}
if (!lastTickSelector.empty()) {
lastTickSelector.attr("transform", `translate(${range[1]}, 0)`);
}
}
// Add grid lines if requested
if (showGrid) {
g.selectAll(".tick")
.append("line")
.attr("class", "grid-line")
.attr("x1", 0)
.attr("y1", 0)
.attr("x2", 0)
.attr(
"y2",
position === "top"
? height - margin.top - margin.bottom
: -(height - margin.top - margin.bottom)
)
.attr("stroke", "lightgray")
.attr("stroke-width", 0.5)
.attr("stroke-dasharray", "3,3")
.attr("opacity", 0.5);
}
// Cleanup function
return () => {
g.selectAll("*").interrupt();
};
}, [
xScale,
height,
margin,
xAxisFormat,
xAxisDataType,
tickValues,
defaultFormatter,
position,
showGrid,
]);
return <g className="x-axis-container" ref={ref} />;
};
export default XaxisLinear;
|