diff --git a/src/frontend/src/components/portal/metric-groups-view.tsx b/src/frontend/src/components/portal/metric-groups-view.tsx index 16cc5d2446..b4b58420d5 100644 --- a/src/frontend/src/components/portal/metric-groups-view.tsx +++ b/src/frontend/src/components/portal/metric-groups-view.tsx @@ -1,9 +1,11 @@ -import { useState } from "react"; +import { useMemo, useState } from "react"; +import { useViewer } from "@/auth"; import { CenteredSpinner } from "@/components/widgets/centered-spinner"; import { ComingSoon } from "@/components/widgets/coming-soon"; import { GroupDrilldownSheet } from "@/components/widgets/dashboard/group-drilldown-sheet"; import { IcNeedsAttention } from "@/components/widgets/dashboard/ic-needs-attention"; +import { PersonCoverage } from "@/components/widgets/dashboard/person-coverage"; import { KpiTile } from "@/components/widgets/dashboard/kpi-tile"; import { previousPeriodRange } from "@/api/period-to-date-range"; import { usePortalPeriod } from "@/hooks/use-portal-period"; @@ -14,7 +16,12 @@ import { orderAttentionItems, } from "@/lib/insight/attention"; import { typicalPeerPool } from "@/lib/insight/peer-pool"; -import { KPI_ROW_COLLECTION, GROUPS, type GroupId } from "@/lib/insight/groups"; +import { + KPI_ROW, + KPI_ROW_COLLECTION, + GROUPS, + type GroupId, +} from "@/lib/insight/groups"; import { metricKpiTiles } from "@/lib/insight/kpi-row"; import { injectCohortPeer } from "@/lib/insight/within-team-peer"; import { @@ -25,6 +32,14 @@ import { normalizePersonId } from "@/lib/metrics/entity"; import { cn } from "@/lib/utils"; import { useCohortLabel } from "@/lib/portal/use-cohort-label"; import { usePersonCohort } from "@/lib/portal/use-person-cohort"; +import { + personTrendPoints, + runningBucketStart, + TREND_BUCKETS, + trendBucket, + trendRange, +} from "@/lib/portal/person-trend"; +import { usePersonSectionStandings } from "@/lib/portal/use-person-sections"; import { collectionSetPending, useMetricCollection, @@ -77,11 +92,6 @@ export interface MetricGroupsViewProps { * modal. Passing it also suppresses the modal sheets entirely. */ onSelectGroup?: (id: GroupId) => void; - /** - * Render the per-group section cards. Off ⇒ a general glance (KPI row + - * needs-attention only) with sections reached from the sidebar instead. - */ - showSections?: boolean; } /** @@ -95,12 +105,15 @@ export function MetricGroupsView({ groupIds, showKpis = false, onSelectGroup, - showSections = true, }: MetricGroupsViewProps) { const cohortLabel = useCohortLabel(); const { period, dateRange } = usePortalPeriod(); const { focusMode } = useSettings(); const entityId = normalizePersonId(personId); + // Whose page this is. A person reading their own page and a manager + // reading it want different things first — see `orderAttentionItems`. + const { personId: viewerPersonId } = useViewer(); + const isSelf = normalizePersonId(viewerPersonId ?? "") === entityId; const entity = { type: "person" as const, ids: [entityId] }; const defs = GROUPS.filter((d) => groupIds.includes(d.id)); @@ -159,6 +172,27 @@ export function MetricGroupsView({ dateRange ); + const sectionStandings = usePersonSectionStandings(personId); + + // Deliberately outside every loading and error gate below: the tiles render + // from the current period, and the line appears when it arrives. A first + // screen must not wait on decoration. + const bucket = trendBucket(period); + const trendCollection = useMemo( + () => ({ + metrics: KPI_ROW.map((key) => ({ + key, + views: [{ view: "timeseries" as const, bucket }], + })), + }), + [bucket] + ); + const trendData = useMetricCollection( + showKpis ? trendCollection : EMPTY_COLLECTION, + showKpis ? entity : CLOSED_ENTITY, + trendRange(dateRange.to, bucket) + ); + const [openGroup, setOpenGroup] = useState(null); // With `onSelectGroup` a card/alert navigates to the section inline; without // it, it opens the drilldown modal. @@ -255,6 +289,16 @@ export function MetricGroupsView({ // What the row actually rendered — the block skips exactly those, no more. const headlineKeys = new Set(tiles.map((t) => t.key)); + // Sections with no reading at all, split by whose fault the blank is: a + // pool that reads means the measurement works and this person is absent + // from it, an empty pool means nobody here is measured. A page that shows + // only what it can see otherwise reads as a whole picture of a person. + const blank = showKpis + ? sectionStandings.filter((st) => !st.isPending && !st.hasData) + : []; + const unmeasured = blank.filter((st) => !st.peersHaveData).map((st) => st.title); + const inactive = blank.filter((st) => st.peersHaveData).map((st) => st.title); + // Deduped across groups, not within one: a metric and the wider metric that // contains it need not live in the same section. // Thinned across groups AND against the row above: a metric and the one it @@ -271,7 +315,8 @@ export function MetricGroupsView({ headlineKeys ) ), - headlineKeys + headlineKeys, + isSelf ) : []; @@ -280,6 +325,11 @@ export function MetricGroupsView({
{showKpis ? ( <> + {/* Before the numbers, not after them. On a person's own page the + first question is what this thing knows about them, and a page + that answers it only at the bottom has already been read as a + complete picture by then. */} +

At a glance @@ -292,15 +342,12 @@ export function MetricGroupsView({ · compared with {peerPool} people in the same {cohortLabel} ) : null} - {/* Each tile carries TWO comparisons — a badge against the - person's own last period, a line against the cohort — and - neither said which was which, so "-13%" could be read as - either. Named once here rather than on every tile: the - grammar is the same for all of them, and a tile is 13rem - wide. */} + {/* The lines carry no axis and no labels — a tile has room for + neither — so the one thing they cannot say for themselves + is said once, here: what a line spans. */} - · badges show the change since the previous{" "} - {PERIOD_NOUN[period]} + · lines cover the last {TREND_BUCKETS}{" "} + {bucket === "week" ? "weeks" : "months"}

{/* A counted column grid, not auto-fit: auto-fit packs in as many @@ -323,6 +370,12 @@ export function MetricGroupsView({ ))} @@ -336,7 +389,13 @@ export function MetricGroupsView({ ) : null}
- {onSelectGroup || !showSections + {/* A click on a number is answered here, with the evidence behind it. + This used to be gated on a `showSections` flag that also hid the + per-group cards — and those cards moved to the navigation long ago, + so the flag survived only to make clicks land nowhere. Only a caller + that routes clicks elsewhere (`onSelectGroup`) has no use for the + drilldowns. */} + {onSelectGroup ? null : defs.map((def) => ( g.id); /** - * Person zone: one specific person (like the reporting tool's Person page). - * The second sidebar level lists the person's sections; selecting a section - * expands it into the full content area inline (rich drilldown) — no modal. - * "At a glance" is a health dashboard: KPI row + needs-attention + per-section - * status cards, all routing into the relevant section inline so a problem - * points straight at its section. + * Person zone: one specific person. + * + * The second sidebar level lists the person's sections and carries a mark + * beside each saying which is worth opening; selecting one expands it into the + * content area inline, with no modal. "At a glance" is the overview: the + * headline row and what needs attention, both routing into the section that + * owns the number. + * + * The per-section status cards this page used to carry are gone — they said + * again, in the middle of the page, what the navigation says on its left edge. */ export function PersonView({ person }: { person: string }) { - const { setItem } = usePortalNavActions(); const item = usePortalItem(); - const isSection = item != null && (PERSON_GROUP_IDS as string[]).includes(item); + const { setItem } = usePortalNavActions(); + const isSection = + item != null && (PERSON_GROUP_IDS as string[]).includes(item); return ( <> @@ -28,9 +30,12 @@ export function PersonView({ person }: { person: string }) { {isSection ? ( ) : ( - // "At a glance" — a health dashboard: general KPIs + needs-attention + - // per-section status cards. Everything routes into the relevant section - // inline (no modal), so a problem points you straight at its section. + // "At a glance" — the headline row and what needs attention. + // + // A tile or an alert opens the SECTION that owns it, the same one the + // navigation lists: the number is the way in, and the section is where + // it is explained. No modal — a problem points you straight at the + // screen that covers it. ; /** Demo story for the Storybook UI (not a test — no `test` tag). */ export const Default: Story = { - args: { tile: makeTile() }, + args: { tile: makeTile(), periodNoun: "month" }, }; /** Component test: the display-ready tile input drives every element. */ export const TestOkTile: Story = { tags: ["test"], - args: { tile: makeTile() }, + args: { tile: makeTile(), periodNoun: "month" }, play: async ({ canvas }) => { // Singular `getByText` (throws on >1 match) doubles as a guard that the // preview decorators wrap the story exactly once — a double-applied // decorator would render two s and fail here. await expect(canvas.getByText("Bugs Fixed")).toBeInTheDocument(); await expect(canvas.getByText("12")).toBeInTheDocument(); - await expect(canvas.getByText("+9%")).toBeInTheDocument(); - await expect(canvas.getByText(/median 6/i)).toBeInTheDocument(); + // The change now names what it is measured against — a bare "+9%" was + // readable as either of the tile's two comparisons. + await expect(canvas.getByText(/\+9% since last month/)).toBeInTheDocument(); + await expect(canvas.getByText(/team median 6/i)).toBeInTheDocument(); }, }; @@ -92,6 +94,7 @@ export const TestNoPeers: Story = { tags: ["test"], args: { tile: makeTile({ gapStatus: "neutral", medianLabel: null, delta: null }), + periodNoun: "month", }, play: async ({ canvas }) => { await expect(canvas.getByText("Bugs Fixed")).toBeInTheDocument(); diff --git a/src/frontend/src/components/widgets/dashboard/kpi-tile.test.tsx b/src/frontend/src/components/widgets/dashboard/kpi-tile.test.tsx index d0ba3d2622..2dac42c058 100644 --- a/src/frontend/src/components/widgets/dashboard/kpi-tile.test.tsx +++ b/src/frontend/src/components/widgets/dashboard/kpi-tile.test.tsx @@ -32,49 +32,84 @@ function tile(overrides: Partial = {}): KpiTileData { describe("KpiTile", () => { it("renders the display-ready value, delta, median, and context", () => { - render(); + render(); expect(screen.getByText("14")).toBeInTheDocument(); - expect(screen.getByText("+17%")).toBeInTheDocument(); - expect(screen.getByText(/median 11/)).toBeInTheDocument(); + // The change now says what it is measured against, in the line under the + // value — a bare "+17%" was readable as either comparison. + expect(screen.getByText(/\+17% since last month/)).toBeInTheDocument(); + expect(screen.getByText(/Team median 11/)).toBeInTheDocument(); expect( - screen.getByText("Days with any AI tool activity"), + screen.getByText("Days with any AI tool activity") ).toBeInTheDocument(); }); it("shows the divergence gap next to the median", () => { render( , + /> ); - expect(screen.getByText(/3\.5× vs median 3,563/)).toBeInTheDocument(); + expect(screen.getByText(/Team median 3,563 · 3\.5×/)).toBeInTheDocument(); }); it("falls back to 'No peer data' without a median label", () => { - render(); + render(); expect(screen.getByText("No peer data")).toBeInTheDocument(); }); it("omits the delta badge when delta is null", () => { - render(); + render(); expect(screen.queryByText("+17%")).not.toBeInTheDocument(); }); it("navigates to its group on click", async () => { const onOpenGroup = vi.fn(); - render(); + render( + + ); await userEvent.click( - screen.getByRole("button", { name: "Open Active AI days details" }), + screen.getByRole("button", { name: "Open Active AI days details" }) ); expect(onOpenGroup).toHaveBeenCalledWith("ai_adoption"); }); + it("shows the line only once the readings arrive, never waiting on them", () => { + // The request for readings sits outside every loading gate: the numbers + // are the page, and a tile that held them back until a second request + // landed would trade the first screen for a decoration. + const { container, rerender } = render( + + ); + expect(screen.getByText("14")).toBeInTheDocument(); + expect(container.querySelector('[data-slot="sparkline"]')).toBeNull(); + + rerender(); + expect(screen.getByText("14")).toBeInTheDocument(); + expect(container.querySelector('[data-slot="sparkline"]')).not.toBeNull(); + }); + + it("draws no line when there is nothing worth drawing", () => { + // `personTrendPoints` returns null below its minimum; the tile must take + // that as "no line", not fall back to something of its own. + const { container } = render( + + ); + expect(container.querySelector('[data-slot="sparkline"]')).toBeNull(); + }); + it("is not interactive without a group id", () => { - render(); + render( + + ); expect(screen.queryByRole("button")).not.toBeInTheDocument(); }); }); @@ -89,7 +124,7 @@ describe("KpiTilePlaceholder", () => { // The number alone is not readable: a viewer meeting "14" has no way to // learn what it counts. The tile itself is the trigger, so the answer is // one pointer-rest away instead of one more icon per tile. - render(); + render(); await userEvent.hover(screen.getByRole("button")); const tip = await screen.findByTestId("metric-help"); expect(tip).toHaveTextContent("Days with any AI tool activity"); @@ -97,7 +132,13 @@ describe("KpiTilePlaceholder", () => { }); it("opens nothing for a metric the catalog says nothing about", async () => { - render(); + render( + + ); await userEvent.hover(screen.getByRole("button")); expect(screen.queryByTestId("metric-help")).not.toBeInTheDocument(); }); @@ -105,8 +146,13 @@ describe("KpiTilePlaceholder", () => { it("says where the value sits when it is exactly at the median", () => { // "median 22,774" alone breaks the pattern every other tile follows and // reads as a stray label rather than a comparison. - render(); - expect(screen.getByText(/at median 11/)).toBeInTheDocument(); + render( + + ); + expect(screen.getByText("Team median 11")).toBeInTheDocument(); }); it("does not raise an alarm over a change of one percent", () => { @@ -114,10 +160,11 @@ describe("KpiTilePlaceholder", () => { // teach the reader that the colour means nothing. render( , + /> ); - const badge = screen.getByText("-1%").closest("span")!; - expect(badge.className).not.toMatch(/text-destructive|text-success/); + const line = screen.getByText(/-1% since last month/); + expect(line.className).not.toMatch(/text-destructive|text-success/); }); }); diff --git a/src/frontend/src/components/widgets/dashboard/kpi-tile.tsx b/src/frontend/src/components/widgets/dashboard/kpi-tile.tsx index 404cddfe91..a30cab22c3 100644 --- a/src/frontend/src/components/widgets/dashboard/kpi-tile.tsx +++ b/src/frontend/src/components/widgets/dashboard/kpi-tile.tsx @@ -6,8 +6,8 @@ import { TrendingUpIcon, } from "lucide-react"; -import { Badge } from "@/components/ui/badge"; import { MetricHelpTooltip } from "@/components/widgets/metric-help-tooltip"; +import { Sparkline } from "@/components/widgets/dashboard/sparkline"; import { Card, CardDescription, @@ -18,11 +18,19 @@ import { import { useSettings } from "@/hooks/use-settings"; import type { KpiTileData } from "@/lib/insight/kpi-row"; import type { GroupId } from "@/lib/insight/groups"; -import { STATUS_BG_CLASS, STATUS_TEXT_CLASS } from "@/lib/status"; +import { STATUS_TEXT_CLASS } from "@/lib/status"; import { cn } from "@/lib/utils"; export interface KpiTileProps { tile: KpiTileData; + /** "month" / "week" — names what the change is measured against. */ + periodNoun: string; + /** + * Finished readings, oldest first; absent while they load or when there are + * too few to draw. Never blocks the tile — the numbers are the page, and the + * line is what the page grows once it can. + */ + trend?: (number | null)[] | null; onOpenGroup?: (id: GroupId) => void; } @@ -32,7 +40,12 @@ const CARD_SURFACE = "@container/card"; * Presentational KPI tile: everything display-ready arrives on `tile` * (selectors in `lib/insight/kpi-row.ts` own formatting and scoring). */ -export function KpiTile({ tile, onOpenGroup }: KpiTileProps) { +export function KpiTile({ + tile, + periodNoun, + trend, + onOpenGroup, +}: KpiTileProps) { const { showExplanations } = useSettings(); const primaryGroup = onOpenGroup ? tile.groupId : null; const interactive = primaryGroup != null; @@ -79,13 +92,9 @@ export function KpiTile({ tile, onOpenGroup }: KpiTileProps) { {tile.help?.description} ) : null} - {/* The delta rides WITH the value, not up beside the label: it is a - statement about this number ("−1 pp since last period"), and read - from the label row it looked like a second, unrelated figure. - Pinned to the right edge so the badges line up down a row of tiles - — a column the eye can scan instead of chasing each value's end. - Plain ink, always: the number states a quantity, and the verdict - on it belongs to the line that explains the comparison. */} + {/* Plain ink, and the badge is gone: its content moved into the + line below, where it can say what it is comparing against + instead of leaving "-13%" to be read as either comparison. */} {tile.value} - {tile.delta ? ( - - {tile.delta.status === "neutral" ? ( - - ) : tile.delta.down ? ( - - ) : ( - - )} - {tile.delta.text} - + {/* Beside the number it describes, not in a block of its own: the + question "and before that?" is asked here, and an answer one + scroll away is an answer nobody reads. + Pinned to the right edge rather than trailing the value — the + values are of different widths, so a line that starts where + each one ends leaves four lines at four x-positions. On the + edge they form a column the eye can read down. Absent until + the readings arrive: the page does not wait for it. */} + {trend ? ( + ) : null} @@ -117,29 +119,39 @@ export function KpiTile({ tile, onOpenGroup }: KpiTileProps) { even when one of them wraps its badge onto a second line; the two-line reserve keeps a wrapped comparison from changing the card's height. */} - - {tile.medianLabel ? ( - - {/* The standing, on the sentence that states it — and marked by - a dot as well as a colour, so it survives being read by - someone who cannot tell the two colours apart. */} - {tile.gapStatus !== "neutral" ? ( - - ) : null} - - {tile.gapText ? `${tile.gapText} vs ` : "at "} - {tile.medianLabel} - + + {/* The person's own change first, and the only line carrying a + verdict. This is their page: their own last period is the one + comparison they can act on. */} + {tile.delta ? ( + + {tile.delta.status === "neutral" ? ( + + ) : tile.delta.down ? ( + + ) : ( + + )} + {tile.delta.text} since last {periodNoun} ) : ( - "No peer data" + + no earlier {periodNoun} to compare + )} + {/* The cohort, stated and not judged: the reader did not choose these + people, cannot see who they are, and cannot decide that their + median is the right target. */} + + {tile.medianLabel + ? `Team ${tile.medianLabel}${tile.gapText ? ` · ${tile.gapText}` : ""}` + : "No peer data"} + diff --git a/src/frontend/src/components/widgets/dashboard/person-coverage.test.tsx b/src/frontend/src/components/widgets/dashboard/person-coverage.test.tsx new file mode 100644 index 0000000000..5f1744054d --- /dev/null +++ b/src/frontend/src/components/widgets/dashboard/person-coverage.test.tsx @@ -0,0 +1,49 @@ +// @vitest-environment jsdom +/** + * The one line on a person's page that says what the page cannot see. + * + * Its whole job is to keep two claims apart, so the tests are about which + * sentence each blank section gets — not about layout. + */ +import { render, screen } from "@testing-library/react"; +import { describe, expect, it } from "vitest"; + +import { PersonCoverage } from "./person-coverage"; + +describe("PersonCoverage", () => { + it("says nothing when every section reads", () => { + const { container } = render( + + ); + expect(container).toBeEmptyDOMElement(); + }); + + it("blames the instrument only where the pool is empty too", () => { + render(); + expect( + screen.getByText(/No data reaches us for Task delivery/) + ).toBeTruthy(); + }); + + it("blames nobody where the measurement works and the person is absent", () => { + // The failure this guards: telling a reader their tracker is broken while + // their colleagues' numbers for that same section sit on the next screen. + render( + + ); + expect( + screen.getByText(/Nothing recorded in Git output and Wiki this period/) + ).toBeTruthy(); + expect(screen.queryByText(/reaches us/)).toBeNull(); + }); + + it("carries both reasons at once, each with its own sentence", () => { + render( + + ); + expect( + screen.getByText(/No data reaches us for Task delivery/) + ).toBeTruthy(); + expect(screen.getByText(/Nothing recorded in Wiki/)).toBeTruthy(); + }); +}); diff --git a/src/frontend/src/components/widgets/dashboard/person-coverage.tsx b/src/frontend/src/components/widgets/dashboard/person-coverage.tsx new file mode 100644 index 0000000000..cd0a70461a --- /dev/null +++ b/src/frontend/src/components/widgets/dashboard/person-coverage.tsx @@ -0,0 +1,43 @@ +export interface PersonCoverageProps { + /** Sections nobody is measured in — the pool has no readings either. */ + unmeasured: string[]; + /** Sections that measure fine and hold nothing for this person. */ + inactive: string[]; +} + +function list(titles: string[]): string { + if (titles.length < 3) return titles.join(" and "); + return `${titles.slice(0, -1).join(", ")} and ${titles[titles.length - 1]}`; +} + +/** + * What this page cannot see, and why. + * + * Without it the screen reads as a whole picture of a person, and for someone + * whose work leaves few traces in the connected systems that picture is mostly + * their chat and their calendar. Naming the gap costs one line and no request + * — the standings behind it are the ones the navigation already asked for. + * + * The two reasons a section is blank must not share a sentence. "No data + * reaches us" is a claim about the instrument; "nothing recorded" is a claim + * about the person. Saying the first where the second is true tells a reader + * their tracker is broken when their colleagues' numbers sit on the next + * screen; saying the second where the first is true blames a person for a + * connector nobody has wired. The pool decides which one is honest. + */ +export function PersonCoverage({ unmeasured, inactive }: PersonCoverageProps) { + if (unmeasured.length === 0 && inactive.length === 0) return null; + return ( +

+ {unmeasured.length > 0 ? ( + <> + No data reaches us for {list(unmeasured)} — this page shows what is + measured, not everything this person does.{" "} + + ) : null} + {inactive.length > 0 ? ( + <>Nothing recorded in {list(inactive)} this period. + ) : null} +

+ ); +} diff --git a/src/frontend/src/components/widgets/dashboard/sparkline.test.tsx b/src/frontend/src/components/widgets/dashboard/sparkline.test.tsx new file mode 100644 index 0000000000..f59f9fe821 --- /dev/null +++ b/src/frontend/src/components/widgets/dashboard/sparkline.test.tsx @@ -0,0 +1,67 @@ +// @vitest-environment jsdom +/** + * The line beside a headline number. + * + * It says only which way and how steadily, so what these tests pin is what it + * must never say: that a period with no reading was a period with none of the + * thing, or that a flat series is a shape. + */ +import { render } from "@testing-library/react"; +import { describe, expect, it } from "vitest"; + +import { Sparkline } from "./sparkline"; + +function paths(container: HTMLElement) { + return [...container.querySelectorAll("path")]; +} + +describe("Sparkline", () => { + it("draws nothing that cannot be scaled", () => { + // One reading has no range and no direction; the caller decides what is + // worth drawing, and this only keeps the maths safe. + expect(render().container).toBeEmptyDOMElement(); + expect( + render().container + ).toBeEmptyDOMElement(); + }); + + it("breaks the line at a gap instead of dropping it to the floor", () => { + // One continuous path across the gap would draw a dive to zero and back — + // a month with no data read as a month with none of the thing. + const { container } = render(); + expect(paths(container)).toHaveLength(1); + + const split = render(); + expect(paths(split.container)).toHaveLength(2); + }); + + it("survives a series that never moves", () => { + // A flat run has zero range; scaling to it must not divide by it. + const { container } = render(); + const d = paths(container)[0]?.getAttribute("d") ?? ""; + expect(d).toMatch(/^M/); + expect(d).not.toMatch(/NaN|Infinity/); + }); + + it("marks the end of the line, and marks the last reading when it ends in a gap", () => { + const { container } = render(); + expect(container.querySelectorAll("circle")).toHaveLength(1); + + const trailing = render(); + const dot = trailing.container.querySelector("circle"); + // The dot says "this is now"; parked at the gap it would say the series + // ended lower than its last reading. + expect(dot).not.toBeNull(); + expect(Number(dot?.getAttribute("cx"))).toBeLessThan(72); + }); + + it("keeps its baseline out of the reading of values", () => { + // The rule under the line spans the window so the line does not float. It + // is drawn at a fixed depth, NOT at zero — the line is scaled to its own + // range, and a zero baseline would be a lie for a percentage. + const { container } = render(); + const rule = container.querySelector("line"); + expect(rule?.getAttribute("x1")).toBe("0"); + expect(rule?.getAttribute("x2")).toBe("72"); + }); +}); diff --git a/src/frontend/src/components/widgets/dashboard/sparkline.tsx b/src/frontend/src/components/widgets/dashboard/sparkline.tsx new file mode 100644 index 0000000000..9d87c511d2 --- /dev/null +++ b/src/frontend/src/components/widgets/dashboard/sparkline.tsx @@ -0,0 +1,113 @@ +import { cn } from "@/lib/utils"; + +export interface SparklineProps { + /** Readings oldest first; null is a gap, never a zero. */ + points: (number | null)[]; + className?: string; +} + +const W = 72; +const H = 16; + +/** + * Where a number has been, drawn beside where it is now. + * + * Scaled to its own range rather than to zero or to any shared axis: the tile + * already carries the magnitude in figures, so the only thing left for the + * line to say is which way and how steadily. A missing reading breaks the line + * instead of dropping it to the floor — a month with no data must not be + * readable as a month with none of the thing. + */ +export function Sparkline({ points, className }: SparklineProps) { + // What is worth drawing is the caller's call (`personTrendPoints`); this + // guard only keeps the maths safe for a series that cannot be scaled. + const values = points.filter((v) => v != null); + if (values.length < 2) return null; + + const min = Math.min(...values); + const max = Math.max(...values); + const span = max - min || 1; + const x = (i: number) => (i / (points.length - 1)) * W; + const y = (v: number) => H - ((v - min) / span) * H; + + const segments: string[] = []; + let run: string[] = []; + points.forEach((v, i) => { + if (v == null) { + if (run.length > 1) segments.push(run.join(" ")); + run = []; + return; + } + run.push(`${run.length ? "L" : "M"}${x(i).toFixed(1)},${y(v).toFixed(1)}`); + }); + if (run.length > 1) segments.push(run.join(" ")); + + const lastIndex = points.findLastIndex((v) => v != null); + const lastValue = points[lastIndex]; + + return ( + + {/* A rule under the line, spanning the whole window. + Without it the line floats: nothing says where the span starts or + ends, so a reader cannot tell a line covering the window from one + that happens to sit at that angle. It claims no VALUE — the line is + scaled to its own range, and a baseline at zero would be a lie for a + percentage — only the extent of time. */} + + {/* Ticks at the ends, so the span reads as a span. */} + + + {segments.map((d) => ( + + ))} + {/* The end of the line marked, so the eye knows which end is now. */} + {lastValue != null ? ( + + ) : null} + + ); +} diff --git a/src/frontend/src/lib/insight/attention.test.ts b/src/frontend/src/lib/insight/attention.test.ts index bfbab0581f..733085b68f 100644 --- a/src/frontend/src/lib/insight/attention.test.ts +++ b/src/frontend/src/lib/insight/attention.test.ts @@ -433,4 +433,22 @@ describe("orderAttentionItems", () => { ); expect(ordered).toEqual([]); }); + + it("leads with what changed when the reader is looking at their own page", () => { + // A standing is the larger claim and leads by default — what a manager + // scanning someone else needs. On your own page what moved this period is + // what you can still act on; what has been true for months you have + // already lived through. Nothing is hidden either way. + const items = [ + row({ key: "standing", kind: "behind" }), + row({ key: "change", kind: "fell" }), + ]; + expect(orderAttentionItems(items, new Set()).map((i) => i.key)).toEqual([ + "standing", + "change", + ]); + expect( + orderAttentionItems(items, new Set(), true).map((i) => i.key) + ).toEqual(["change", "standing"]); + }); }); diff --git a/src/frontend/src/lib/insight/attention.ts b/src/frontend/src/lib/insight/attention.ts index 4ed5fcc2f4..ff2f59e6fa 100644 --- a/src/frontend/src/lib/insight/attention.ts +++ b/src/frontend/src/lib/insight/attention.ts @@ -220,11 +220,26 @@ export function metricAttentionItems( */ export function orderAttentionItems( items: readonly AttentionItem[], - headlineKeys: ReadonlySet + headlineKeys: ReadonlySet, + /** + * Put what CHANGED first — for a reader looking at their own page. + * + * A standing is the larger claim and leads by default, which is what a + * manager scanning someone else needs. On your own page the order inverts: + * what moved this period is what you can still do something about, while + * what has been true for months you have already lived through. + * + * Neither order hides anything — both kinds are always listed. + */ + changesFirst = false ): AttentionItem[] { + const leads = (item: AttentionItem) => + changesFirst + ? Number(item.kind === "fell") + : Number(item.kind === "behind"); const ranked = [...items].sort( (a, b) => - Number(b.kind === "behind") - Number(a.kind === "behind") || + leads(b) - leads(a) || (a.kind === "behind" ? b.relGap - a.relGap : b.spreadGap - a.spreadGap) || b.relGap - a.relGap ); diff --git a/src/frontend/src/lib/insight/group-data.ts b/src/frontend/src/lib/insight/group-data.ts index 3cc6d6ceec..49b9f6f5f0 100644 --- a/src/frontend/src/lib/insight/group-data.ts +++ b/src/frontend/src/lib/insight/group-data.ts @@ -26,6 +26,33 @@ export function groupHasData( } +/** + * Whether anyone in the comparison pool has a reading for this section. + * + * The difference between "this source does not reach us" and "this person did + * none of that work" is not visible in the person's own row — both arrive as + * a null. It IS visible in the pool: a peer view counts the entities that had + * a reading, so a pool of zero across every metric of a section means nobody + * is measured here, while a pool with readings and an empty own row means the + * measurement works and this person is simply absent from it. + * + * Not proof — a section whose whole cohort was idle looks the same. It fails + * toward the weaker claim, which is the safe direction: saying "no activity" + * where a connector is in fact missing understates what we know, while saying + * "no data reaches us" of a working source is plainly false to anyone whose + * colleagues' numbers are on the next screen. + */ +export function groupPeersHaveData( + def: MetricGroup, + byKey: Map, + entityId: string, +): boolean { + return def.collection.metrics.some((m) => { + const metric = byKey.get(m.key); + return metric != null && (forEntity(metric, entityId).peer?.n ?? 0) > 0; + }); +} + /** Worst standing first — the row a card leads with is the one to look at. */ const HEADLINE_TIER: Record = { bottom: 3, diff --git a/src/frontend/src/lib/portal/person-trend.test.ts b/src/frontend/src/lib/portal/person-trend.test.ts new file mode 100644 index 0000000000..a038397abc --- /dev/null +++ b/src/frontend/src/lib/portal/person-trend.test.ts @@ -0,0 +1,188 @@ +/** + * The readings a tile's line is drawn from. + * + * Three of the rules here exist to refuse to draw something, and each refusal + * looks like a missing feature from the outside — which is exactly why they + * need tests. Left untested, "why is there no line here" gets fixed by + * deleting the rule, and the screen goes back to inventing a collapse out of + * the calendar. + */ +import { describe, expect, it } from "vitest"; + +import type { MetricResult } from "@/api/metric-results-client"; +import { normalizeMetricResults } from "@/lib/metrics/collection"; +import { + TREND_BUCKETS, + personTrendPoints, + runningBucketStart, + trendBucket, + trendRange, +} from "./person-trend"; + +const ME = "019e27bc-dec0-7626-81a9-c5524662a6a9"; + +/** One metric carrying a timeseries of `[bucket_start, value]` readings. */ +function withSeries(points: [string, number | null][]) { + const result = { + metric_key: "git.commits", + label: "Commits", + unit: null, + format: "integer", + computation: "sum", + direction: "higher_is_better", + views: [ + { + view: "timeseries", + bucket: "month", + series: [ + { + entity_id: ME, + dimensions: [], + points: points.map(([bucket_start, value]) => ({ + bucket_start, + value, + })), + }, + ], + }, + ], + } as unknown as MetricResult; + return normalizeMetricResults([result]).get("git.commits"); +} + +describe("trendBucket", () => { + it("draws the line in the unit the reader picked", () => { + // Anything else asks them to convert in their head on every glance. + expect(trendBucket("week")).toBe("week"); + expect(trendBucket("month")).toBe("month"); + expect(trendBucket("quarter")).toBe("month"); + expect(trendBucket("year")).toBe("month"); + }); +}); + +describe("runningBucketStart", () => { + it("finds the first of the month", () => { + expect(runningBucketStart("2026-03-18", "month")).toBe("2026-03-01"); + }); + + it("finds the Monday of the week, including from a Sunday", () => { + // A Sunday is the case a naive "subtract getUTCDay()" gets wrong: it + // would jump forward a week and drop six finished days. + expect(runningBucketStart("2026-03-18", "week")).toBe("2026-03-16"); + expect(runningBucketStart("2026-03-22", "week")).toBe("2026-03-16"); + expect(runningBucketStart("2026-03-16", "week")).toBe("2026-03-16"); + }); +}); + +describe("trendRange", () => { + it("asks for the finished buckets plus the running one", () => { + const { from, to } = trendRange("2026-03-18", "month"); + expect(to).toBe("2026-03-18"); + const days = (Date.parse(to) - Date.parse(from)) / 86_400_000; + expect(days).toBeGreaterThan(31 * TREND_BUCKETS); + }); +}); + +describe("personTrendPoints", () => { + const running = "2026-03-01"; + + it("drops the running bucket", () => { + // A month four days old holds four days of work; drawn beside finished + // months it reads as a collapse the calendar invented. + const points = personTrendPoints( + withSeries([ + ["2025-12-01", 10], + ["2026-01-01", 12], + ["2026-02-01", 11], + ["2026-03-01", 1], + ]), + ME, + running + ); + expect(points).toEqual([10, 12, 11]); + }); + + it("draws nothing below three readings", () => { + // Two points always draw a straight line, and a straight line reads as a + // steady trend — but two is also what a metric has when it has only just + // started being measured. + expect( + personTrendPoints( + withSeries([ + ["2026-01-01", 10], + ["2026-02-01", 12], + ]), + ME, + running + ) + ).toBeNull(); + }); + + it("keeps a gap as a gap rather than a zero", () => { + // A month with no data must not become a month with none of the thing. + expect( + personTrendPoints( + withSeries([ + ["2025-11-01", 10], + ["2025-12-01", null], + ["2026-01-01", 12], + ["2026-02-01", 11], + ]), + ME, + running + ) + ).toEqual([10, null, 12, 11]); + }); + + it("counts only real readings towards the minimum", () => { + // Four buckets, three of them empty: a gap must not buy its way past the + // threshold that exists to stop two points being drawn as a trend. + expect( + personTrendPoints( + withSeries([ + ["2025-11-01", 10], + ["2025-12-01", null], + ["2026-01-01", null], + ["2026-02-01", 11], + ]), + ME, + running + ) + ).toBeNull(); + }); + + it("keeps the most recent window, oldest first", () => { + // More finished buckets than the line holds: the oldest fall off the + // left, not the newest off the right. + const extra = 4; + const many = Array.from( + { length: TREND_BUCKETS + extra }, + (_, i): [string, number] => [`${2020 + i}-01-01`, i] + ); + const points = personTrendPoints( + withSeries(many), + ME, + `${2020 + TREND_BUCKETS + extra}-01-01` + ); + expect(points).toHaveLength(TREND_BUCKETS); + expect(points?.[0]).toBe(extra); + expect(points?.at(-1)).toBe(TREND_BUCKETS + extra - 1); + }); + + it("orders by bucket, not by arrival", () => { + const points = personTrendPoints( + withSeries([ + ["2026-02-01", 11], + ["2025-12-01", 10], + ["2026-01-01", 12], + ]), + ME, + running + ); + expect(points).toEqual([10, 12, 11]); + }); + + it("has nothing to draw for a metric that never arrived", () => { + expect(personTrendPoints(undefined, ME, running)).toBeNull(); + }); +}); diff --git a/src/frontend/src/lib/portal/person-trend.ts b/src/frontend/src/lib/portal/person-trend.ts new file mode 100644 index 0000000000..1c030eb6ae --- /dev/null +++ b/src/frontend/src/lib/portal/person-trend.ts @@ -0,0 +1,87 @@ +import type { DateRange } from "@/api/period-to-date-range"; +import type { MetricBucket } from "@/api/metric-results-client"; +import type { PeriodValue } from "@/types/insight"; +import { + forEntity, + type NormalizedMetricResult, +} from "@/lib/metrics/collection"; + +/** How many finished buckets a tile's line shows. */ +export const TREND_BUCKETS = 8; + +/** + * The unit the line is drawn in — the same one the reader picked. + * + * The number above the line is a month's number when the reader chose months, + * so the line has to be months too. Anything else asks them to convert in + * their head on every glance. + */ +export function trendBucket(period: PeriodValue): MetricBucket { + return period === "week" ? "week" : "month"; +} + +const BUCKET_DAYS: Record = { + day: 1, + week: 7, + month: 31, +}; + +/** The window to ask for: the finished buckets, plus the running one. */ +export function trendRange(today: string, bucket: MetricBucket): DateRange { + const span = BUCKET_DAYS[bucket] * (TREND_BUCKETS + 1); + const from = new Date(Date.parse(`${today}T00:00:00Z`) - span * 86_400_000) + .toISOString() + .slice(0, 10); + return { from, to: today }; +} + +/** First day of the bucket `today` falls in — the one still being filled. */ +export function runningBucketStart( + today: string, + bucket: MetricBucket +): string { + if (bucket === "month") return `${today.slice(0, 7)}-01`; + if (bucket === "week") { + const d = new Date(`${today}T00:00:00Z`); + // ISO weeks start on Monday; `getUTCDay` calls Sunday 0. + const back = (d.getUTCDay() + 6) % 7; + return new Date(d.getTime() - back * 86_400_000).toISOString().slice(0, 10); + } + return today; +} + +/** Fewest readings that can bend, and so the fewest worth drawing. */ +const MIN_READINGS = 3; + +/** + * A metric's finished readings, oldest first — or null when there is no line + * worth drawing. + * + * The running bucket is dropped, and that is the point of this function. A + * month four days old holds four days of work; drawn beside finished months it + * reads as a collapse, and the screen would have invented a decline out of the + * calendar. Nothing on a tile could tell the reader that the last point means + * something different from every other point. + * + * Null below three readings. Two points always draw a straight line, and a + * straight line reads as a steady trend — but two is also exactly what a + * metric has when it has only just started being measured, and "we have just + * begun looking at this" must not be drawn as "this has been rising evenly". + * Three is the fewest that can bend, and so the fewest that can be read as a + * shape rather than as a direction the drawing invented. + */ +export function personTrendPoints( + metric: NormalizedMetricResult | undefined, + entityId: string, + runningStart: string +): (number | null)[] | null { + if (!metric) return null; + // One series per entity; a person's own is the only one requested. + const series = forEntity(metric, entityId).series[0]?.points ?? []; + const points = series + .filter((p) => p.bucket_start < runningStart) + .sort((a, b) => a.bucket_start.localeCompare(b.bucket_start)) + .slice(-TREND_BUCKETS) + .map((p) => p.value ?? null); + return points.filter((v) => v != null).length >= MIN_READINGS ? points : null; +} diff --git a/src/frontend/src/lib/portal/use-person-sections.test.tsx b/src/frontend/src/lib/portal/use-person-sections.test.tsx index 06f968bb05..e69244ee08 100644 --- a/src/frontend/src/lib/portal/use-person-sections.test.tsx +++ b/src/frontend/src/lib/portal/use-person-sections.test.tsx @@ -59,7 +59,8 @@ const ME = "019e27bc-dec0-7626-81a9-c5524662a6a9"; function metric( key: string, value: number | null, - median: number + median: number, + n = 9 ): MetricResult { return { metric_key: key, @@ -81,7 +82,7 @@ function metric( p75: median + 2, min: 0, max: median + 5, - n: 9, + n, }, ], }, @@ -120,6 +121,20 @@ describe("usePersonSectionStandings", () => { expect(git.phrase).toBe("no peer data"); }); + it("separates a section this person is absent from one nobody is measured in", () => { + // Both arrive as a null own value, and the page says different things + // about them: a pool that reads means the measurement works. + mocks.byKey = normalizeMetricResults([metric("git.commits", null, 20)]); + expect(standings().find((s) => s.id === "git_output")!.peersHaveData).toBe( + true + ); + + mocks.byKey = normalizeMetricResults([metric("git.commits", null, 20, 0)]); + expect(standings().find((s) => s.id === "git_output")!.peersHaveData).toBe( + false + ); + }); + it("stays pending while the queries are, so the nav shows no mark yet", () => { // A section still loading must not be drawn as one with nothing: the // reader would take the grey mark for an answer. diff --git a/src/frontend/src/lib/portal/use-person-sections.ts b/src/frontend/src/lib/portal/use-person-sections.ts index 71d5dbe04b..65af9d5a69 100644 --- a/src/frontend/src/lib/portal/use-person-sections.ts +++ b/src/frontend/src/lib/portal/use-person-sections.ts @@ -1,5 +1,5 @@ import { GROUPS, type GroupId } from "@/lib/insight/groups"; -import { groupHasData } from "@/lib/insight/group-data"; +import { groupHasData, groupPeersHaveData } from "@/lib/insight/group-data"; import { injectCohortPeer } from "@/lib/insight/within-team-peer"; import { gradeSectionStanding, @@ -23,6 +23,12 @@ export interface SectionStanding { phrase: string; /** False when no metric of the section has a value for this period. */ hasData: boolean; + /** + * Whether anyone in the comparison pool reads here. With `hasData` false it + * separates a section this person is absent from (pool reads) from one + * nobody is measured in (pool empty). + */ + peersHaveData: boolean; isPending: boolean; } @@ -97,6 +103,7 @@ export function usePersonSectionStandings(personId: string): SectionStanding[] { status: gradeSectionStanding(counts), phrase: sectionStandingPhrase(counts), hasData: groupHasData(def, byKey, entityId), + peersHaveData: groupPeersHaveData(def, byKey, entityId), isPending: result?.isPending ?? true, }; }); diff --git a/src/frontend/src/screens/dashboard.tsx b/src/frontend/src/screens/dashboard.tsx index 8723e6f1b7..da3ab8898c 100644 --- a/src/frontend/src/screens/dashboard.tsx +++ b/src/frontend/src/screens/dashboard.tsx @@ -207,6 +207,7 @@ export function DashboardScreen({ personId }: DashboardScreenProps) { ))