Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ export function TimeseriesBody({
selectedMetricKey,
multiMetric,
table,
onVerticalOverflow,
onEvidence,
}: {
isPending: boolean;
Expand All @@ -138,6 +139,7 @@ export function TimeseriesBody({
selectedMetricKey: string;
multiMetric: MetricTimeseriesChartConfig["multiMetric"];
table?: MetricTimeseriesTableConfig;
onVerticalOverflow?: (overflows: boolean) => void;
onEvidence?: (
metricKey: string,
columnKey: string,
Expand Down Expand Up @@ -169,6 +171,7 @@ export function TimeseriesBody({
<MetricTimeseriesTable
model={model}
config={table}
onVerticalOverflow={onVerticalOverflow}
onEvidence={onEvidence}
/>
) : (
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { render, screen, within } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { fireEvent, render, screen, within } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";

import { MetricTimeseriesChart } from "@/components/widgets/metric-views/metric-timeseries-chart";
import {
Expand Down Expand Up @@ -33,6 +33,52 @@ const COMPOSED_TABLE = {
],
} satisfies MetricTimeseriesTableConfig;

/**
* jsdom has no layout engine and no ResizeObserver, so every dimension reads
* zero and the table concludes that nothing overflows. Supplying the geometry
* is what lets the real decisions run — which side holds more, how far a page
* moves — rather than a stand-in for them.
*/
afterEach(() => vi.unstubAllGlobals());

/** Scoped to the tests that need it: charts here measure themselves and a
* no-op observer leaves them with nothing to draw. */
function stubResizeObserver(): void {
vi.stubGlobal(
"ResizeObserver",
class {
observe() {}
disconnect() {}
}
);
}

function giveGeometry(
container: HTMLElement,
box: Partial<
Record<
| "clientWidth"
| "scrollWidth"
| "clientHeight"
| "scrollHeight"
| "scrollLeft"
| "scrollTop",
number
>
>
): HTMLElement & { scrollBy: ReturnType<typeof vi.fn> } {
const el = container.querySelector<HTMLElement>(
'[data-slot="table-container"]'
)!;
for (const [key, value] of Object.entries(box)) {
Object.defineProperty(el, key, { value, configurable: true });
}
const scrollBy = vi.fn();
Object.defineProperty(el, "scrollBy", { value: scrollBy, configurable: true });
fireEvent.scroll(el);
return el as HTMLElement & { scrollBy: typeof scrollBy };
}

describe("metric timeseries presentations", () => {
it("renders grouped metrics in a multi-level table", () => {
render(<MetricTimeseriesTable model={groupedTimeseriesModel()} />);
Expand Down Expand Up @@ -60,6 +106,90 @@ describe("metric timeseries presentations", () => {
expect(screen.getByText("Grand total")).toBeInTheDocument();
});

it("offers no paging control towards a side with nothing on it", () => {
// Nothing overflows here: jsdom reports every dimension as zero.
render(<MetricTimeseriesTable model={groupedTimeseriesModel()} />);
expect(
screen.queryByRole("button", { name: /Show (earlier|later)/ })
).toBeNull();
});

it("offers a control for each side that still holds something", () => {
stubResizeObserver();
const { container } = render(
<MetricTimeseriesTable model={groupedTimeseriesModel()} />
);
giveGeometry(container, {
clientWidth: 400,
scrollWidth: 1200,
clientHeight: 200,
scrollHeight: 600,
scrollLeft: 0,
scrollTop: 0,
});
// Sitting at both starts: only the two forward controls have anywhere to go.
expect(screen.getByRole("button", { name: "Show later columns" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Show later rows" })).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Show earlier columns" })).toBeNull();
expect(screen.queryByRole("button", { name: "Show earlier rows" })).toBeNull();
});

it("pages by just under a frame, away from the edge it points at", () => {
stubResizeObserver();
const { container } = render(
<MetricTimeseriesTable model={groupedTimeseriesModel()} />
);
const box = giveGeometry(container, {
clientWidth: 400,
scrollWidth: 1200,
clientHeight: 200,
scrollHeight: 600,
scrollLeft: 500,
scrollTop: 300,
});

fireEvent.click(screen.getByRole("button", { name: "Show later columns" }));
expect(box.scrollBy).toHaveBeenLastCalledWith({
left: 320,
behavior: "smooth",
});

fireEvent.click(screen.getByRole("button", { name: "Show earlier columns" }));
expect(box.scrollBy).toHaveBeenLastCalledWith({
left: -320,
behavior: "smooth",
});

fireEvent.click(screen.getByRole("button", { name: "Show later rows" }));
expect(box.scrollBy).toHaveBeenLastCalledWith({
top: 160,
behavior: "smooth",
});

fireEvent.click(screen.getByRole("button", { name: "Show earlier rows" }));
expect(box.scrollBy).toHaveBeenLastCalledWith({
top: -160,
behavior: "smooth",
});
});

it("pins the totals to the foot of the box, with an edge over the rows", () => {
render(<MetricTimeseriesTable model={groupedTimeseriesModel()} />);
const foot = screen.getByText("Grand total").closest("tfoot")!;
expect(foot.className).toContain("sticky");
expect(foot.className).toContain("bottom-0");
expect(foot.className).toContain("inset_0_1px_0_0");
});

it("keeps the grand total beside its label when the table is scrolled", () => {
// The cell spans every group, so its own start edge scrolls away.
render(<MetricTimeseriesTable model={groupedTimeseriesModel()} />);
const row = screen.getByText("Grand total").closest("tr")!;
const totals = row.querySelectorAll("td")[1]!.querySelector("span")!;
expect(totals.className).toContain("sticky");
expect(totals.className).toContain("start-28");
});

it("hides the grand-total row when every total is missing", () => {
const grouped = groupedTimeseriesModel();
const model = {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
import { useCallback, useEffect, useRef, useState } from "react";
import {
ChevronDown,
ChevronLeft,
ChevronRight,
ChevronUp,
} from "lucide-react";

import { Button } from "@/components/ui/button";

import { formatMetricNumber } from "@/lib/format";
import { cn } from "@/lib/utils";
import {
Expand All @@ -19,13 +29,65 @@ import type { MetricTimeseriesTableConfig } from "@/lib/metrics/timeseries-table
export interface MetricTimeseriesTableProps {
model: MetricTimeseriesModel;
config?: MetricTimeseriesTableConfig;
/**
* Whether the rows overrun the box — the card above offers to let the table
* out to full height, and only when that would do anything.
*/
Comment thread
aleksdotbar marked this conversation as resolved.
Resolved
onVerticalOverflow?: (overflows: boolean) => void;
onEvidence?: (
metricKey: string,
columnKey: string,
bucketStart: string | null
) => void;
}

type Side = "start" | "end" | "up" | "down";

const SIDES: readonly Side[] = ["start", "end", "up", "down"];
const NOTHING_MORE: Record<Side, boolean> = {
start: false,
end: false,
up: false,
down: false,
};

/** Sub-pixel scroll offsets are noise, not a side with content on it. */
const EDGE_SLACK_PX = 1;

/** A page that leaves the edge row or column on screen to keep the reader's place. */
const NEARLY_A_FRAME = 0.8;

/**
* The vertical pair is offset toward the end rather than centred: the sticky
* header carries the group names and the sticky footer the totals, and a
* control parked over either hides what that row is pinned for.
*/
const SIDE_CHROME: Record<
Side,
{ icon: typeof ChevronLeft; label: string; place: string }
> = {
start: {
icon: ChevronLeft,
label: "Show earlier columns",
place: "start-1 top-1/2 -translate-y-1/2 rtl:rotate-180",
},
end: {
icon: ChevronRight,
label: "Show later columns",
place: "end-1 top-1/2 -translate-y-1/2 rtl:rotate-180",
},
up: {
icon: ChevronUp,
label: "Show earlier rows",
place: "top-1 end-10",
},
down: {
icon: ChevronDown,
label: "Show later rows",
place: "bottom-1 end-10",
},
};

const BUCKET_LABEL = {
day: "Day",
week: "Week",
Expand Down Expand Up @@ -100,6 +162,7 @@ function MetricTableValue({
export function MetricTimeseriesTable({
model,
config,
onVerticalOverflow,
onEvidence,
}: MetricTimeseriesTableProps) {
const tableColumns = resolveMetricTimeseriesTableColumns(model, config);
Expand All @@ -116,11 +179,93 @@ export function MetricTimeseriesTable({
)
);

const boxRef = useRef<HTMLDivElement | null>(null);
const [more, setMore] = useState(NOTHING_MORE);
const measure = useCallback(() => {
const box = boxRef.current;
if (!box) return;
// `scrollLeft` is negative in RTL.
const across = Math.abs(box.scrollLeft);
const acrossRoom = box.scrollWidth - box.clientWidth;
const downRoom = box.scrollHeight - box.clientHeight;
const next = {
start: across > EDGE_SLACK_PX,
end: across < acrossRoom - EDGE_SLACK_PX,
up: box.scrollTop > EDGE_SLACK_PX,
down: box.scrollTop < downRoom - EDGE_SLACK_PX,
};
// Keeping the object identity where the answer is unchanged; a new one per
// scroll event re-renders on every frame of a drag.
setMore((prev) =>
SIDES.every((side) => prev[side] === next[side]) ? prev : next
);
onVerticalOverflow?.(downRoom > EDGE_SLACK_PX);
}, [onVerticalOverflow]);
useEffect(() => {
measure();
const box = boxRef.current;
if (!box) return;
// `onScroll` would land on the table; the container is what scrolls, and
// it takes no props of its own.
box.addEventListener("scroll", measure, { passive: true });
const observer =
typeof ResizeObserver === "undefined" ? null : new ResizeObserver(measure);
// Both sides of the comparison move: the box with the window, the table
// with its data.
observer?.observe(box);
const inner = box.querySelector("table");
if (inner) observer?.observe(inner);
return () => {
box.removeEventListener("scroll", measure);
observer?.disconnect();
};
// `model` is rebuilt every render, so it must stay out of the deps.
}, [measure]);

function page(side: Side): void {
const box = boxRef.current;
if (!box) return;
const forward = side === "end" || side === "down";
if (side === "up" || side === "down") {
const step = box.clientHeight * NEARLY_A_FRAME;
box.scrollBy({ top: forward ? step : -step, behavior: "smooth" });
return;
}
const step = box.clientWidth * NEARLY_A_FRAME;
const rtl = getComputedStyle(box).direction === "rtl";
const delta = forward ? step : -step;
box.scrollBy({ left: rtl ? -delta : delta, behavior: "smooth" });
}

return (
<Table
className="min-w-max text-xs"
containerClassName="h-full overflow-auto"
>
<div className="relative h-full">
{/* Rendered, not hidden: opacity would leave them in the tab order. */}
{SIDES.filter((side) => more[side]).map((side) => {
const { icon: Icon, label, place } = SIDE_CHROME[side];
return (
<Button
key={side}
type="button"
variant="outline"
size="icon-sm"
aria-label={label}
title={label}
onClick={() => page(side)}
className={cn(
// Opaque, so they stay legible over whatever cell they land on.
"absolute z-40 rounded-full bg-card shadow-md",
place
)}
>
<Icon className="size-4" />
</Button>
);
})}
<Table
className="min-w-max text-xs"
containerClassName="h-full overflow-auto"
containerRef={boxRef}
>
<TableHeader className="[&_tr]:border-b-0">
{model.dimensions.length === 0 ? (
<TableRow>
Expand Down Expand Up @@ -236,7 +381,9 @@ export function MetricTimeseriesTable({
</TableRow>
))}
</TableBody>
<TableFooter>
{/* The top edge is what says the rows continue underneath; without it
the pinned block reads as the end of the table. */}
<TableFooter className="sticky bottom-0 z-20 shadow-[inset_0_1px_0_0_var(--border)]">
<TableRow>
<TableCell className="sticky left-0 z-10 w-28 max-w-28 min-w-28 bg-muted px-2 py-1 font-semibold after:absolute after:inset-y-0 after:right-0 after:w-px after:bg-border">
Total
Expand Down Expand Up @@ -274,7 +421,9 @@ export function MetricTimeseriesTable({
colSpan={model.columns.length * tableColumns.length}
className="bg-muted px-2 pt-1 pb-5 text-left font-semibold tabular-nums"
>
<span className="inline-flex flex-wrap items-center gap-1.5">
{/* Stuck past the label column, since the cell spans every group
and its own start edge scrolls away. */}
<span className="sticky start-28 inline-flex flex-wrap items-center gap-1.5">
{tableColumns.map((tableColumn, index) => (
<span
key={tableColumn.key}
Expand All @@ -296,7 +445,8 @@ export function MetricTimeseriesTable({
</TableCell>
</TableRow>
) : null}
</TableFooter>
</Table>
</TableFooter>
</Table>
</div>
);
}
Loading
Loading