mirror of
https://github.com/we-promise/sure.git
synced 2026-07-12 21:05:20 +00:00
* fix(charts): restyle hover tooltips with soft shadow + larger radius Match the elevation pattern of DS::Select dropdown (shadow-lg + shadow-border-xs) and increase radius (rounded-lg → rounded-xl) + padding (p-2 → p-3) for better breathing. Drops the hard border in favour of the soft drop shadow. time_series_chart_controller: - p-2 → p-3, rounded-lg → rounded-xl - remove border border-secondary - add shadow-lg shadow-border-xs (theme-aware drop + border-edge) - add explicit text-primary (was missing per #2011's drift note) - add z-50 (matches goal_projection + sankey controllers) sankey_chart_controller: - bg-gray-700 text-white → bg-container text-primary (theme-aware; was broken in light mode after dark-bg flip) - p-2 rounded → p-3 rounded-xl - add shadow-lg shadow-border-xs - add font-sans for consistency with the other chart tooltips - add privacy-sensitive class (was missing — sankey money values were rendered in the clear with privacy mode on) DS::Tooltip (icon-trigger help, bg-inverse) is intentionally a different primitive and is not touched. Refs #2011 — className consolidation into a shared module is tracked separately and intentionally not closed by this PR; the new string applies to two of the three call sites today (time_series, sankey). The third (goal_projection_chart_controller) lives on the feat/goals-v2-architecture branch and will adopt the same string when goals v2 merges. * fix(charts): align every chart tooltip on the borderless soft-shadow card One visual contract for all three D3 tooltip surfaces, matching the design reference: p-4, rounded-2xl, shadow-xl, no edge ring in light mode. Dark mode keeps a 1px alpha-white ring since a shadow alone disappears against dark surfaces. - goal_projection_chart_controller drops its hand-copied class string (it still carried the old bordered recipe — the drift this util exists to prevent) and builds its two lines through the shared factory: secondary date line, tabular value line. - New content conventions exported alongside the container contract: context line = text-xs text-secondary, values = font-medium tabular-nums. Time-series and sankey adopt them. - Sankey node titles now escape before .html(); user-named categories were previously interpolated raw into the tooltip markup. * fix(charts): match the tooltip surface to the design reference exactly The previous pass approximated the reference with utility guesses (rounded-2xl, p-4, shadow-xl, dark ring). The actual spec is a hairline border ring composed with a soft 0 8px 24px drop shadow, 10px radius, 12x14 padding, and an 80ms left/top glide. Tailwind shadow utilities can't compose a ring with a custom drop shadow, so the surface moves into the design system as .chart-tooltip (theme-aware: dark swaps the ring to alpha-white and lets it carry the edge). Money/numeric figures also pick up the reference's mono treatment: font-mono + tabular-nums on every value across time-series, sankey, and goal-projection, so digits don't jitter while the scrubber moves. * fix(charts): tighten tooltip padding to 10x12 * feat(charts): give sankey and goal tooltips their missing context rows Chart tooltips answer three stacked questions: context (what am I looking at), value (how much), relation (vs what). Time-series already had all three; the other two were missing rows. - Sankey links showed a bare "$X (Y%)" with no indication of which flow was hovered. Links now lead with a swatch-dotted "Source → Target" context line; nodes get the same dot + name treatment, tying the card to the ribbon color. The context builder escapes node names centrally (they're user-named categories). - Goal projection adds a tertiary relation line — "52% of $20K target" — computed from the payload the chart already carries, for both the saved and projected segments. Hidden when the goal has no positive target. Template is i18n-wired like the existing tooltip strings (goals.show.projection.tooltip_target_relation). Verified with Playwright against the running app: all three surfaces pass computed-style and content assertions. * fix(charts): drop the color dot from sankey tooltip context The hover highlight on the diagram already identifies the ribbon; the swatch repeated it inside the card. Names alone keep the context line quieter. * fix(charts): use the app's sans money treatment in tooltips, not mono font-mono in this codebase marks code, keys, and admin surfaces; money is sans + tabular-nums everywhere else (cards, KPIs, tables). Keep the tabular figures for scrub stability, drop the mono. * fix(charts): address review — glide opt-in, no shadowed var, truncate cap - The 80ms left/top transition moved out of .chart-tooltip: it eased the snap-positioned goal tooltip but made cursor-following tooltips (sankey, time-series) trail the pointer by a frame. Goal projection opts back in via inline style; the component comment documents the split. - setRelation reuses _draw()'s targetAmount const instead of declaring a local 'target' that shadowed the target-date const. - Sankey context line gets max-w-64 so truncate has a constraint to fire against on deep flows. - Component comment now says 10x12 padding, matching the declaration. * Revert `schema.rb` changes --------- Co-authored-by: Juan José Mata <jjmata@jjmata.com>
593 lines
17 KiB
JavaScript
593 lines
17 KiB
JavaScript
import { Controller } from "@hotwired/stimulus";
|
|
import * as d3 from "d3";
|
|
import { CHART_TOOLTIP_CLASSES } from "utils/chart_tooltip";
|
|
|
|
const parseLocalDate = d3.timeParse("%Y-%m-%d");
|
|
|
|
export default class extends Controller {
|
|
static values = {
|
|
data: Object,
|
|
strokeWidth: { type: Number, default: 2 },
|
|
useLabels: { type: Boolean, default: true },
|
|
useTooltip: { type: Boolean, default: true },
|
|
};
|
|
|
|
_d3SvgMemo = null;
|
|
_d3GroupMemo = null;
|
|
_d3Tooltip = null;
|
|
_d3InitialContainerWidth = 0;
|
|
_d3InitialContainerHeight = 0;
|
|
_normalDataPoints = [];
|
|
_resizeObserver = null;
|
|
|
|
connect() {
|
|
this._install();
|
|
document.addEventListener("turbo:load", this._reinstall);
|
|
this._setupResizeObserver();
|
|
}
|
|
|
|
disconnect() {
|
|
this._teardown();
|
|
document.removeEventListener("turbo:load", this._reinstall);
|
|
this._resizeObserver?.disconnect();
|
|
}
|
|
|
|
_reinstall = () => {
|
|
this._teardown();
|
|
this._install();
|
|
};
|
|
|
|
_teardown() {
|
|
this._d3SvgMemo = null;
|
|
this._d3GroupMemo = null;
|
|
this._d3Tooltip = null;
|
|
this._normalDataPoints = [];
|
|
|
|
this._d3Container.selectAll("*").remove();
|
|
}
|
|
|
|
_install() {
|
|
this._normalizeDataPoints();
|
|
this._rememberInitialContainerSize();
|
|
this._draw();
|
|
}
|
|
|
|
_normalizeDataPoints() {
|
|
this._normalDataPoints = (this.dataValue.values || []).map((d) => ({
|
|
date: parseLocalDate(d.date),
|
|
date_formatted: d.date_formatted,
|
|
value: d.value,
|
|
trend: d.trend,
|
|
}));
|
|
}
|
|
|
|
_rememberInitialContainerSize() {
|
|
this._d3InitialContainerWidth = this._d3Container.node().clientWidth;
|
|
this._d3InitialContainerHeight = this._d3Container.node().clientHeight;
|
|
}
|
|
|
|
_draw() {
|
|
// Guard against invalid dimensions (e.g., when container is collapsed or not yet rendered)
|
|
const minWidth = 50;
|
|
const minHeight = 50;
|
|
|
|
if (
|
|
this._d3ContainerWidth < minWidth ||
|
|
this._d3ContainerHeight < minHeight
|
|
) {
|
|
// Skip rendering if dimensions are invalid
|
|
return;
|
|
}
|
|
|
|
if (this._normalDataPoints.length < 2) {
|
|
this._drawEmpty();
|
|
} else {
|
|
this._drawChart();
|
|
}
|
|
}
|
|
|
|
_drawEmpty() {
|
|
this._d3Svg.selectAll(".tick").remove();
|
|
this._d3Svg.selectAll(".domain").remove();
|
|
|
|
this._drawDashedLineEmptyState();
|
|
this._drawCenteredCircleEmptyState();
|
|
}
|
|
|
|
_drawDashedLineEmptyState() {
|
|
this._d3Svg
|
|
.append("line")
|
|
.attr("x1", this._d3InitialContainerWidth / 2)
|
|
.attr("y1", 0)
|
|
.attr("x2", this._d3InitialContainerWidth / 2)
|
|
.attr("y2", this._d3InitialContainerHeight)
|
|
.attr("stroke", "var(--color-gray-300)")
|
|
.attr("stroke-dasharray", "4, 4");
|
|
}
|
|
|
|
_drawCenteredCircleEmptyState() {
|
|
this._d3Svg
|
|
.append("circle")
|
|
.attr("cx", this._d3InitialContainerWidth / 2)
|
|
.attr("cy", this._d3InitialContainerHeight / 2)
|
|
.attr("r", 4)
|
|
.attr("class", "text-subdued")
|
|
.style("fill", "currentColor");
|
|
}
|
|
|
|
_drawChart() {
|
|
this._drawTrendline();
|
|
|
|
if (this.useLabelsValue) {
|
|
this._drawXAxisLabels();
|
|
this._drawGradientBelowTrendline();
|
|
}
|
|
|
|
if (this.useTooltipValue) {
|
|
this._drawTooltip();
|
|
this._trackMouseForShowingTooltip();
|
|
}
|
|
}
|
|
|
|
_drawTrendline() {
|
|
this._installTrendlineSplit();
|
|
|
|
this._d3Group
|
|
.append("path")
|
|
.datum(this._normalDataPoints)
|
|
.attr("fill", "none")
|
|
.attr("stroke", `url(#${this.element.id}-split-gradient)`)
|
|
.attr("d", this._d3Line)
|
|
.attr("stroke-linejoin", "round")
|
|
.attr("stroke-linecap", "round")
|
|
// A flat series (no variation across the period — a single valuation or an
|
|
// unchanged balance) otherwise renders as a full-bleed near-black rule
|
|
// bisecting the hero card. Draw it as a faint hairline so it reads as
|
|
// "no change", consistent across light and dark (#2137).
|
|
.attr("stroke-width", this._isFlatSeries ? 1 : this.strokeWidthValue)
|
|
.attr("stroke-opacity", this._isFlatSeries ? 0.4 : 1);
|
|
}
|
|
|
|
get _isFlatSeries() {
|
|
const min = d3.min(this._normalDataPoints, this._getDatumValue);
|
|
const max = d3.max(this._normalDataPoints, this._getDatumValue);
|
|
return min === max;
|
|
}
|
|
|
|
_installTrendlineSplit() {
|
|
const gradient = this._d3Svg
|
|
.append("defs")
|
|
.append("linearGradient")
|
|
.attr("id", `${this.element.id}-split-gradient`)
|
|
.attr("gradientUnits", "userSpaceOnUse")
|
|
.attr("x1", this._d3XScale.range()[0])
|
|
.attr("x2", this._d3XScale.range()[1]);
|
|
|
|
// First stop - solid trend color
|
|
gradient
|
|
.append("stop")
|
|
.attr("class", "start-color")
|
|
.attr("offset", "0%")
|
|
.attr("stop-color", this.dataValue.trend.color);
|
|
|
|
// Second stop - trend color right before split
|
|
gradient
|
|
.append("stop")
|
|
.attr("class", "split-before")
|
|
.attr("offset", "100%")
|
|
.attr("stop-color", this.dataValue.trend.color);
|
|
|
|
// Third stop - gray color right after split
|
|
gradient
|
|
.append("stop")
|
|
.attr("class", "split-after")
|
|
.attr("offset", "100%")
|
|
.attr("stop-color", "var(--color-gray-400)");
|
|
|
|
// Fourth stop - solid gray to end
|
|
gradient
|
|
.append("stop")
|
|
.attr("class", "end-color")
|
|
.attr("offset", "100%")
|
|
.attr("stop-color", "var(--color-gray-400)");
|
|
}
|
|
|
|
_setTrendlineSplitAt(percent) {
|
|
const position = percent * 100;
|
|
|
|
// Update both stops at the split point
|
|
this._d3Svg
|
|
.select(`#${this.element.id}-split-gradient`)
|
|
.select(".split-before")
|
|
.attr("offset", `${position}%`);
|
|
|
|
this._d3Svg
|
|
.select(`#${this.element.id}-split-gradient`)
|
|
.select(".split-after")
|
|
.attr("offset", `${position}%`);
|
|
|
|
this._d3Svg
|
|
.select(`#${this.element.id}-trendline-gradient-rect`)
|
|
.attr("width", this._d3ContainerWidth * percent);
|
|
}
|
|
|
|
_drawXAxisLabels() {
|
|
// Add ticks
|
|
this._d3Group
|
|
.append("g")
|
|
.attr("transform", `translate(0,${this._d3ContainerHeight})`)
|
|
.call(
|
|
d3
|
|
.axisBottom(this._d3XScale)
|
|
.tickValues([
|
|
this._normalDataPoints[0].date,
|
|
this._normalDataPoints[this._normalDataPoints.length - 1].date,
|
|
])
|
|
.tickSize(0)
|
|
.tickFormat(d3.timeFormat("%b %d, %Y")),
|
|
)
|
|
.select(".domain")
|
|
.remove();
|
|
|
|
// Style ticks
|
|
this._d3Group
|
|
.selectAll(".tick text")
|
|
.attr("class", "text-secondary")
|
|
.style("font-size", "12px")
|
|
.style("font-weight", "500")
|
|
.attr("text-anchor", "middle")
|
|
.attr("dx", (_d, i) => {
|
|
// We know we only have 2 values
|
|
return i === 0 ? "5em" : "-5em";
|
|
})
|
|
.attr("dy", "0em");
|
|
}
|
|
|
|
_drawGradientBelowTrendline() {
|
|
// Define gradient
|
|
const gradient = this._d3Group
|
|
.append("defs")
|
|
.append("linearGradient")
|
|
.attr("id", `${this.element.id}-trendline-gradient`)
|
|
.attr("gradientUnits", "userSpaceOnUse")
|
|
.attr("x1", 0)
|
|
.attr("x2", 0)
|
|
.attr(
|
|
"y1",
|
|
this._d3YScale(d3.max(this._normalDataPoints, this._getDatumValue)),
|
|
)
|
|
.attr("y2", this._d3ContainerHeight);
|
|
|
|
gradient
|
|
.append("stop")
|
|
.attr("offset", 0)
|
|
.attr("stop-color", this._trendColor)
|
|
.attr("stop-opacity", 0.06);
|
|
|
|
gradient
|
|
.append("stop")
|
|
.attr("offset", 0.5)
|
|
.attr("stop-color", this._trendColor)
|
|
.attr("stop-opacity", 0);
|
|
|
|
// Clip path makes gradient start at the trendline
|
|
this._d3Group
|
|
.append("clipPath")
|
|
.attr("id", `${this.element.id}-clip-below-trendline`)
|
|
.append("path")
|
|
.datum(this._normalDataPoints)
|
|
.attr(
|
|
"d",
|
|
d3
|
|
.area()
|
|
.x((d) => this._d3XScale(d.date))
|
|
.y0(this._d3ContainerHeight)
|
|
.y1((d) => this._d3YScale(this._getDatumValue(d))),
|
|
);
|
|
|
|
// Apply the gradient + clip path
|
|
this._d3Group
|
|
.append("rect")
|
|
.attr("id", `${this.element.id}-trendline-gradient-rect`)
|
|
.attr("width", this._d3ContainerWidth)
|
|
.attr("height", this._d3ContainerHeight)
|
|
.attr("clip-path", `url(#${this.element.id}-clip-below-trendline)`)
|
|
.style("fill", `url(#${this.element.id}-trendline-gradient)`);
|
|
}
|
|
|
|
_drawTooltip() {
|
|
this._d3Tooltip = d3
|
|
.select(`#${this.element.id}`)
|
|
.append("div")
|
|
// Shared visual contract + this chart's initial-hidden / positioning classes.
|
|
.attr("class", `${CHART_TOOLTIP_CLASSES} opacity-0 top-0`);
|
|
}
|
|
|
|
_trackMouseForShowingTooltip() {
|
|
const bisectDate = d3.bisector((d) => d.date).left;
|
|
|
|
this._d3Group
|
|
.append("rect")
|
|
.attr("class", "bg-container")
|
|
.attr("width", this._d3ContainerWidth)
|
|
.attr("height", this._d3ContainerHeight)
|
|
.attr("fill", "none")
|
|
.attr("pointer-events", "all")
|
|
.on("mousemove", (event) => {
|
|
const estimatedTooltipWidth = 250;
|
|
const pageWidth = document.body.clientWidth;
|
|
const tooltipX = event.pageX + 10;
|
|
const overflowX = tooltipX + estimatedTooltipWidth - pageWidth;
|
|
const adjustedX =
|
|
overflowX > 0 ? event.pageX - overflowX - 20 : tooltipX;
|
|
|
|
const [xPos] = d3.pointer(event);
|
|
const x0 = bisectDate(
|
|
this._normalDataPoints,
|
|
this._d3XScale.invert(xPos),
|
|
1,
|
|
);
|
|
const d0 = this._normalDataPoints[x0 - 1];
|
|
const d1 = this._normalDataPoints[x0];
|
|
const d =
|
|
xPos - this._d3XScale(d0.date) > this._d3XScale(d1.date) - xPos
|
|
? d1
|
|
: d0;
|
|
const xPercent = this._d3XScale(d.date) / this._d3ContainerWidth;
|
|
|
|
this._setTrendlineSplitAt(xPercent);
|
|
|
|
// Reset
|
|
this._d3Group.selectAll(".data-point-circle").remove();
|
|
this._d3Group.selectAll(".guideline").remove();
|
|
|
|
// Guideline
|
|
this._d3Group
|
|
.append("line")
|
|
.attr("class", "guideline text-subdued")
|
|
.attr("x1", this._d3XScale(d.date))
|
|
.attr("y1", 0)
|
|
.attr("x2", this._d3XScale(d.date))
|
|
.attr("y2", this._d3ContainerHeight)
|
|
.attr("stroke", "currentColor")
|
|
.attr("stroke-dasharray", "4, 4");
|
|
|
|
// Big circle
|
|
this._d3Group
|
|
.append("circle")
|
|
.attr("class", "data-point-circle")
|
|
.attr("cx", this._d3XScale(d.date))
|
|
.attr("cy", this._d3YScale(this._getDatumValue(d)))
|
|
.attr("r", 10)
|
|
.attr("fill", this._trendColor)
|
|
.attr("fill-opacity", "0.1")
|
|
.attr("pointer-events", "none");
|
|
|
|
// Small circle
|
|
this._d3Group
|
|
.append("circle")
|
|
.attr("class", "data-point-circle")
|
|
.attr("cx", this._d3XScale(d.date))
|
|
.attr("cy", this._d3YScale(this._getDatumValue(d)))
|
|
.attr("r", 5)
|
|
.attr("fill", this._trendColor)
|
|
.attr("pointer-events", "none");
|
|
|
|
// Render tooltip
|
|
this._d3Tooltip
|
|
.html(this._tooltipTemplate(d))
|
|
.style("opacity", 1)
|
|
.style("z-index", 999)
|
|
.style("left", `${adjustedX}px`)
|
|
.style("top", `${event.pageY - 10}px`);
|
|
})
|
|
.on("mouseout", (event) => {
|
|
const hoveringOnGuideline =
|
|
event.toElement?.classList.contains("guideline");
|
|
|
|
if (!hoveringOnGuideline) {
|
|
this._d3Group.selectAll(".guideline").remove();
|
|
this._d3Group.selectAll(".data-point-circle").remove();
|
|
this._d3Tooltip.style("opacity", 0);
|
|
this._setTrendlineSplitAt(1);
|
|
}
|
|
});
|
|
}
|
|
|
|
_tooltipTemplate(datum) {
|
|
return `
|
|
<div class="text-xs text-secondary mb-1">
|
|
${datum.date_formatted}
|
|
</div>
|
|
<div class="flex items-center gap-4">
|
|
<div class="flex items-center gap-2 text-primary font-medium tabular-nums">
|
|
<div class="flex items-center justify-center h-4 w-4">
|
|
${this._getTrendIcon(datum)}
|
|
</div>
|
|
${this._extractFormattedValue(datum.trend.current)}
|
|
</div>
|
|
|
|
${
|
|
datum.trend.value === 0
|
|
? `<span class="w-20"></span>`
|
|
: `
|
|
<span class="tabular-nums" style="color: ${datum.trend.color};">
|
|
${this._extractFormattedValue(datum.trend.value)} (${datum.trend.percent_formatted})
|
|
</span>
|
|
`
|
|
}
|
|
</div>
|
|
`;
|
|
}
|
|
|
|
_getTrendIcon(datum) {
|
|
const isIncrease =
|
|
Number(datum.trend.previous.amount) < Number(datum.trend.current.amount);
|
|
const isDecrease =
|
|
Number(datum.trend.previous.amount) > Number(datum.trend.current.amount);
|
|
|
|
if (isIncrease) {
|
|
return `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="${datum.trend.color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-arrow-up-right-icon lucide-arrow-up-right"><path d="M7 7h10v10"/><path d="M7 17 17 7"/></svg>`;
|
|
}
|
|
|
|
if (isDecrease) {
|
|
return `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="${datum.trend.color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-arrow-down-right-icon lucide-arrow-down-right"><path d="m7 7 10 10"/><path d="M17 7v10H7"/></svg>`;
|
|
}
|
|
|
|
return `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="${datum.trend.color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-minus-icon lucide-minus"><path d="M5 12h14"/></svg>`;
|
|
}
|
|
|
|
_getDatumValue = (datum) => {
|
|
return this._extractNumericValue(datum.value);
|
|
};
|
|
|
|
_extractNumericValue = (numeric) => {
|
|
if (typeof numeric === "object" && "amount" in numeric) {
|
|
return Number(numeric.amount);
|
|
}
|
|
return Number(numeric);
|
|
};
|
|
|
|
_extractFormattedValue = (numeric) => {
|
|
if (typeof numeric === "object" && "formatted" in numeric) {
|
|
return numeric.formatted;
|
|
}
|
|
return numeric;
|
|
};
|
|
|
|
_createMainSvg() {
|
|
return this._d3Container
|
|
.append("svg")
|
|
.attr("width", this._d3InitialContainerWidth)
|
|
.attr("height", this._d3InitialContainerHeight)
|
|
.attr("viewBox", [
|
|
0,
|
|
0,
|
|
this._d3InitialContainerWidth,
|
|
this._d3InitialContainerHeight,
|
|
]);
|
|
}
|
|
|
|
_createMainGroup() {
|
|
return this._d3Svg
|
|
.append("g")
|
|
.attr("transform", `translate(${this._margin.left},${this._margin.top})`);
|
|
}
|
|
|
|
get _d3Svg() {
|
|
if (!this._d3SvgMemo) {
|
|
this._d3SvgMemo = this._createMainSvg();
|
|
}
|
|
return this._d3SvgMemo;
|
|
}
|
|
|
|
get _d3Group() {
|
|
if (!this._d3GroupMemo) {
|
|
this._d3GroupMemo = this._createMainGroup();
|
|
}
|
|
return this._d3GroupMemo;
|
|
}
|
|
|
|
get _margin() {
|
|
if (this.useLabelsValue) {
|
|
return { top: 20, right: 0, bottom: 10, left: 0 };
|
|
}
|
|
return { top: 0, right: 0, bottom: 0, left: 0 };
|
|
}
|
|
|
|
get _d3ContainerWidth() {
|
|
return (
|
|
this._d3InitialContainerWidth - this._margin.left - this._margin.right
|
|
);
|
|
}
|
|
|
|
get _d3ContainerHeight() {
|
|
return (
|
|
this._d3InitialContainerHeight - this._margin.top - this._margin.bottom
|
|
);
|
|
}
|
|
|
|
get _d3Container() {
|
|
return d3.select(this.element);
|
|
}
|
|
|
|
get _trendColor() {
|
|
return this.dataValue.trend.color;
|
|
}
|
|
|
|
get _d3Line() {
|
|
return d3
|
|
.line()
|
|
.x((d) => this._d3XScale(d.date))
|
|
.y((d) => this._d3YScale(this._getDatumValue(d)));
|
|
}
|
|
|
|
get _d3XScale() {
|
|
return d3
|
|
.scaleTime()
|
|
.rangeRound([0, this._d3ContainerWidth])
|
|
.domain(d3.extent(this._normalDataPoints, (d) => d.date));
|
|
}
|
|
|
|
get _d3YScale() {
|
|
const dataMin = d3.min(this._normalDataPoints, this._getDatumValue);
|
|
const dataMax = d3.max(this._normalDataPoints, this._getDatumValue);
|
|
|
|
// Handle edge case where all values are the same
|
|
if (dataMin === dataMax) {
|
|
const padding = dataMax === 0 ? 100 : Math.abs(dataMax) * 0.5;
|
|
return d3
|
|
.scaleLinear()
|
|
.rangeRound([this._d3ContainerHeight, 0])
|
|
.domain([dataMin - padding, dataMax + padding]);
|
|
}
|
|
|
|
const dataRange = dataMax - dataMin;
|
|
const avgValue = (dataMax + dataMin) / 2;
|
|
|
|
// Calculate relative change as a percentage
|
|
const relativeChange = avgValue !== 0 ? dataRange / Math.abs(avgValue) : 1;
|
|
|
|
// Dynamic baseline calculation
|
|
let yMin;
|
|
let yMax;
|
|
|
|
// For small relative changes (< 10%), use a tighter scale
|
|
if (relativeChange < 0.1 && dataMin > 0) {
|
|
// Start axis at a percentage below the minimum, not at 0
|
|
const baselinePadding = dataRange * 2; // Show 2x the data range below min
|
|
yMin = Math.max(0, dataMin - baselinePadding);
|
|
yMax = dataMax + dataRange * 0.5; // Add 50% padding above
|
|
} else {
|
|
// For larger changes or when data crosses zero, use more context
|
|
// Always include 0 when data is negative or close to 0
|
|
if (dataMin < 0 || (dataMin >= 0 && dataMin < avgValue * 0.1)) {
|
|
yMin = Math.min(0, dataMin * 1.1);
|
|
} else {
|
|
// Otherwise use dynamic baseline
|
|
yMin = dataMin - dataRange * 0.3;
|
|
}
|
|
yMax = dataMax + dataRange * 0.1;
|
|
}
|
|
|
|
// Adjust padding for labels if needed
|
|
if (this.useLabelsValue) {
|
|
const extraPadding = (yMax - yMin) * 0.1;
|
|
yMin -= extraPadding;
|
|
yMax += extraPadding;
|
|
}
|
|
|
|
return d3
|
|
.scaleLinear()
|
|
.rangeRound([this._d3ContainerHeight, 0])
|
|
.domain([yMin, yMax]);
|
|
}
|
|
|
|
_setupResizeObserver() {
|
|
this._resizeObserver = new ResizeObserver(() => {
|
|
this._reinstall();
|
|
});
|
|
this._resizeObserver.observe(this.element);
|
|
}
|
|
}
|