Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
Expand Up @@ -60,6 +60,31 @@ describe("metric timeseries presentations", () => {
expect(screen.getByText("Grand total")).toBeInTheDocument();
});

it("pins the totals to the foot of the box, with an edge over the rows", () => {
// A table long enough to scroll hides the rows that summarise it behind
// exactly the scrolling its length forces. The edge matters as much as the
// pinning: without it the block reads as the end of the table, and the
// reader stops at a summary that is only sitting on top of more 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 left edge is wherever the first group
// is — off-screen on a table wide enough to scroll, which is the normal
// case once there are several groups. Left-aligned inside that cell, the
// one row summarising the whole table scrolled away and left its sticky
// label sitting next to nothing. It has to stick past the label column.
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,70 @@ import type { MetricTimeseriesTableConfig } from "@/lib/metrics/timeseries-table
export interface MetricTimeseriesTableProps {
model: MetricTimeseriesModel;
config?: MetricTimeseriesTableConfig;
/**
* Whether the rows overrun the box vertically — the card above offers to
* let the table out to full height, and only when that would do anything.
* The fact travels up rather than the node: the card has no use for the
* element, and passing a ref back into a child's ref merge is what the
* immutability rule forbids.
*/
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,
};

/**
* Where each arrow sits and what it says.
*
* The vertical pair is offset from the centre rather than on it: the sticky
* header carries the group names and the sticky footer carries the totals, and
* a control parked over either would hide the thing that row exists for. The
* horizontal pair is centred because the rows it crosses are cells, and one
* cell behind a button costs nothing — the button is small and the value is a
* scroll away.
*
* The chevrons flip in RTL, which is why they are written as logical sides
* rather than left and right.
*/
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 +167,7 @@ function MetricTableValue({
export function MetricTimeseriesTable({
model,
config,
onVerticalOverflow,
onEvidence,
}: MetricTimeseriesTableProps) {
const tableColumns = resolveMetricTimeseriesTableColumns(model, config);
Expand All @@ -116,11 +184,109 @@ export function MetricTimeseriesTable({
)
);

const boxRef = useRef<HTMLDivElement | null>(null);
// Which way there is more, and whether the rows overrun the box. The table
// routinely runs several times the width of its frame, and nothing says so:
// the platform's overlay scrollbar stays hidden until a scroll begins, so at
// first sight there is no affordance, and a column cut through the middle
// reads as a rendering fault. A fade at the edge was tried and does not
// work — it hides content to suggest more, and over a pale table whose edge
// cells are often empty there is nothing to hide.
const [more, setMore] = useState(NOTHING_MORE);
const measure = useCallback(() => {
const box = boxRef.current;
if (!box) return;
// `scrollLeft` runs negative in RTL, so the distance travelled is its
// magnitude either way.
const across = Math.abs(box.scrollLeft);
const acrossRoom = box.scrollWidth - box.clientWidth;
const downRoom = box.scrollHeight - box.clientHeight;
const next = {
start: across > 1,
end: across < acrossRoom - 1,
up: box.scrollTop > 1,
down: box.scrollTop < downRoom - 1,
};
// A fresh object every call made this a loop once: state changed, the
// effect re-ran, it measured, and set state again.
setMore((prev) =>
SIDES.every((side) => prev[side] === next[side]) ? prev : next
);
onVerticalOverflow?.(downRoom > 1);
}, [onVerticalOverflow]);
useEffect(() => {
measure();
const box = boxRef.current;
if (!box) return;
// A native listener rather than `onScroll`: what scrolls is the container
// the ui table owns, and it takes no props of its own.
box.addEventListener("scroll", measure, { passive: true });
// The observer watches the TABLE, not the box: the box is what gets
// capped, so its own size does not change when columns or rows arrive, and
// observing it would never fire on the change that matters.
const inner =
typeof ResizeObserver === "undefined" ? null : box.querySelector("table");
const observer = inner ? new ResizeObserver(measure) : null;
if (inner && observer) observer.observe(inner);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return () => {
box.removeEventListener("scroll", measure);
observer?.disconnect();
};
// Deliberately NOT re-run per model: the model is rebuilt on every render,
// so depending on it would tear the listener down and put it back on each
// one. A change in the data resizes the table, which the observer sees.
}, [measure]);

function page(side: Side): void {
const box = boxRef.current;
if (!box) return;
// Just under a full frame, so the row or column at the edge stays on
// screen and the reader keeps their place instead of landing among
// unfamiliar ones.
const forward = side === "end" || side === "down";
if (side === "up" || side === "down") {
const step = box.clientHeight * 0.8;
box.scrollBy({ top: forward ? step : -step, behavior: "smooth" });
return;
}
const step = box.clientWidth * 0.8;
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">
{SIDES.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(
// Over the table rather than beside it — the box is already as
// wide as the card, and taking a strip for the controls would
// narrow the thing they exist to reveal. Opaque, so they stay
// legible over whatever cell they land on.
"absolute z-40 rounded-full bg-card shadow-md",
place,
more[side] ? "opacity-100" : "pointer-events-none opacity-0"
)}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
>
<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 +402,16 @@ export function MetricTimeseriesTable({
</TableRow>
))}
</TableBody>
<TableFooter>
{/* Pinned to the foot of the box, so the totals survive scrolling down
the way the sticky first column survives scrolling across. A long
table otherwise hides the two rows that summarise it behind exactly
the scrolling its length forces, and the reader has to travel to the
end to learn what the whole thing came to.

The top edge is what says the rows continue underneath: without it
the pinned block reads as the end of the table, and a reader stops
scrolling at a summary that is only sitting on top of more rows. */}
<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 +449,15 @@ 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">
{/* Pinned beside the label, not to the cell.
The cell spans every group, so its left edge sits wherever
the first group is — which, on a table wide enough to scroll,
is off-screen. The totals were still rendered there: scroll
one group across and the summary of the whole table became a
sticky "Grand total" label with nothing next to it. Sticking
the content past the label column keeps it where the label
is, at every scroll position. */}
<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 +479,8 @@ export function MetricTimeseriesTable({
</TableCell>
</TableRow>
) : null}
</TableFooter>
</Table>
</TableFooter>
</Table>
</div>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,53 @@ describe("MetricTimeseriesView", () => {
expect(screen.getByText("Commits & Lines added")).toBeInTheDocument();
});

it("lets a table size itself while holding a chart to a fixed box", async () => {
// Both presentations shared one fixed height, which only the chart needs —
// it has nothing of its own to be. A table does, and short ones sat above
// a slab of empty card. The figure survives as a ceiling so a long table
// scrolls rather than pushing the rest of the page down.
const user = userEvent.setup();
const { container } = render(
<MetricTimeseriesView
id="sized"
entityId={ENTITY_ID}
range={RANGE}
metricKeys={["git.commits", "git.lines_added"]}
groupBy={{ default: "repository" }}
/>
);
const body = () => container.querySelector('[data-slot="card-content"]')!;
expect(body().className).toContain("h-96");
expect(body().className).not.toContain("max-h-96");

await user.click(screen.getByRole("button", { name: "Table view" }));
expect(body().className).toContain("max-h-96");
});

it("names a grouped table by its grouping, with how many groups there are", async () => {
// The metric selector is chart-only and the plain heading needs a single
// metric, so a grouped multi-metric table used to render an empty header —
// the largest block on the screen was the only unlabelled one. The count
// belongs with it: such a table is routinely wider than the viewport, and
// three visible groups beside a grand total covering eleven is a reader
// looking at numbers that do not add up with no way to see why.
const user = userEvent.setup();
render(
<MetricTimeseriesView
id="by-repo"
entityId={ENTITY_ID}
range={RANGE}
metricKeys={["git.commits", "git.lines_added"]}
groupBy={{ default: "repository" }}
/>
);
await user.click(screen.getByRole("button", { name: "Table view" }));
const heading = screen.getByRole("heading", { name: /By repository/ });
expect(heading).toHaveTextContent("By repository");
expect(heading).toHaveTextContent("2");
expect(screen.queryByLabelText("Metric")).not.toBeInTheDocument();
});

it("uses visible group controls and supports selecting multiple filters", async () => {
const user = userEvent.setup();
const options = timeseriesByKey();
Expand Down
Loading
Loading