profile-weekly-distance: weekly distance bar chart on the profile

Implements the profile-weekly-distance change (specs/profile-weekly-distance):

- getWeeklyDistance(ownerId, { publicOnly, weeks=12 }) in activities.server.ts:
  one query that gap-fills in SQL — generate_series of week-starts LEFT JOINed
  to activities — so it returns exactly 12 contiguous { weekStart, distance }
  rows with matching Postgres week boundaries, viewer-scoped, no cache, no
  schema change.
- WeeklyDistanceChart: SVG bars normalized to the busiest week (empty weeks keep
  their slot as zero-height bars), per-bar title distance, localized label;
  renders nothing when there's no distance in the window. Mounted under the
  ProfileStats header.
- i18n journal.profileStats.weeklyDistance (en + de).

Tests: WeeklyDistanceChart component (jsdom: bar count incl. zero weeks, empty
→ hidden, normalization); e2e creates an activity with distance and asserts the
chart renders. typecheck + lint + unit (journal 321) green; verified in the
browser.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Ullrich Schäfer 2026-06-13 07:46:06 +02:00
parent e0a92b56aa
commit ceda9f1877
No known key found for this signature in database
GPG key ID: A32FF691A0F752D9
10 changed files with 176 additions and 16 deletions

View file

@ -0,0 +1,30 @@
// @vitest-environment jsdom
import { describe, it, expect, afterEach } from "vitest";
import { render, cleanup } from "@testing-library/react";
import { WeeklyDistanceChart } from "./WeeklyDistanceChart.tsx";
afterEach(cleanup);
const weeks = (distances: number[]) =>
distances.map((distance, i) => ({ weekStart: `2026-04-${String(i + 1).padStart(2, "0")}`, distance }));
describe("WeeklyDistanceChart", () => {
it("renders nothing when every week is zero", () => {
const { container } = render(<WeeklyDistanceChart weeks={weeks([0, 0, 0])} />);
expect(container.firstChild).toBeNull();
});
it("renders one bar per week, including zero weeks (contiguous axis)", () => {
const { container } = render(<WeeklyDistanceChart weeks={weeks([1000, 0, 2000, 0])} />);
const bars = container.querySelectorAll("div[style]");
expect(bars).toHaveLength(4);
});
it("normalizes bar heights to the busiest week", () => {
const { container } = render(<WeeklyDistanceChart weeks={weeks([5000, 10000, 2500])} />);
const heights = [...container.querySelectorAll("div[style]")].map(
(b) => (b as HTMLElement).style.height,
);
expect(heights).toEqual(["50%", "100%", "25%"]);
});
});

View file

@ -0,0 +1,41 @@
import { useTranslation } from "react-i18next";
import { formatDistanceKm } from "~/lib/stats";
export interface WeeklyDistanceBucket {
weekStart: string;
distance: number;
}
/**
* Compact weekly-distance bar chart for the profile (last N weeks, oldest
* newest). Bars are normalized to the busiest week; empty weeks keep their slot
* as a zero-height bar so the axis stays contiguous. Renders nothing when there
* is no distance in the window.
*/
export function WeeklyDistanceChart({
weeks,
className,
}: {
weeks: WeeklyDistanceBucket[];
className?: string;
}) {
const { t } = useTranslation("journal");
const max = weeks.reduce((m, w) => Math.max(m, w.distance), 0);
if (max <= 0) return null;
return (
<div className={className}>
<p className="mb-1 text-xs text-gray-500">{t("profileStats.weeklyDistance")}</p>
<div className="flex h-16 items-end gap-1" role="img" aria-label={t("profileStats.weeklyDistance")}>
{weeks.map((w) => (
<div
key={w.weekStart}
className="flex-1 rounded-t bg-blue-500/70"
style={{ height: `${(w.distance / max) * 100}%` }}
title={formatDistanceKm(w.distance)}
/>
))}
</div>
</div>
);
}

View file

@ -205,6 +205,51 @@ export async function getActivityStats(
}; };
} }
export interface WeeklyDistanceBucket {
/** ISO date (YYYY-MM-DD) of the week's Monday */
weekStart: string;
/** metres */
distance: number;
}
/**
* Distance per week for the last `weeks` weeks (oldest newest), gap-filled so
* every week is present (zero when no activity). The contiguous axis is built
* in SQL via `generate_series` + a LEFT JOIN that guarantees the week
* boundaries match Postgres `date_trunc('week', …)` exactly (no JS/Postgres
* boundary drift) and keeps it one cheap query over the owner_id index
* (profile-weekly-distance design §D1D2). `publicOnly` scopes it like
* `getActivityStats`.
*/
export async function getWeeklyDistance(
ownerId: string,
opts: { publicOnly: boolean; weeks?: number },
): Promise<WeeklyDistanceBucket[]> {
const weeks = opts.weeks ?? 12;
const db = getDb();
// Filter conditions live in the LEFT JOIN's ON clause so empty weeks survive.
const visibility = opts.publicOnly ? sql` AND a.visibility = 'public'` : sql``;
const result = await db.execute(sql`
WITH weeks AS (
SELECT generate_series(
date_trunc('week', now()) - (${weeks - 1} * interval '1 week'),
date_trunc('week', now()),
interval '1 week'
) AS wk
)
SELECT to_char(w.wk, 'YYYY-MM-DD') AS week_start,
coalesce(sum(a.distance), 0) AS distance
FROM weeks w
LEFT JOIN journal.activities a
ON date_trunc('week', coalesce(a.started_at, a.created_at)) = w.wk
AND a.owner_id = ${ownerId}${visibility}
GROUP BY w.wk
ORDER BY w.wk
`);
const rows = result as unknown as Array<{ week_start: string; distance: string | number }>;
return rows.map((r) => ({ weekStart: r.week_start, distance: Number(r.distance) }));
}
export async function listActivities( export async function listActivities(
ownerId: string, ownerId: string,
sort: "startedAt" | "addedAt" = "startedAt", sort: "startedAt" | "addedAt" = "startedAt",

View file

@ -8,7 +8,7 @@ import { getDb } from "~/lib/db";
import { users } from "@trails-cool/db/schema/journal"; import { users } from "@trails-cool/db/schema/journal";
import { getSessionUser } from "~/lib/auth/session.server"; import { getSessionUser } from "~/lib/auth/session.server";
import { listPublicRoutesForOwner } from "~/lib/routes.server"; import { listPublicRoutesForOwner } from "~/lib/routes.server";
import { listPublicActivitiesForOwner, getActivityStats } from "~/lib/activities.server"; import { listPublicActivitiesForOwner, getActivityStats, getWeeklyDistance } from "~/lib/activities.server";
import { loadPersona } from "~/lib/demo-bot.server"; import { loadPersona } from "~/lib/demo-bot.server";
import { countFollowers, countFollowing, getFollowState } from "~/lib/follow.server"; import { countFollowers, countFollowing, getFollowState } from "~/lib/follow.server";
@ -54,11 +54,14 @@ export async function loadUserProfile(request: Request, username: string) {
]) ])
: [[], []]; : [[], []];
// Roll-up scoped to what this viewer may see (public-only for non-owners). // Roll-up + weekly trend, scoped to what this viewer may see (public-only for
// Skipped for the locked stub, which shows no content. // non-owners). Skipped for the locked stub, which shows no content.
const stats = canSeeContent const [stats, weeklyDistance] = canSeeContent
? await getActivityStats(user.id, { publicOnly: !isOwn }) ? await Promise.all([
: null; getActivityStats(user.id, { publicOnly: !isOwn }),
getWeeklyDistance(user.id, { publicOnly: !isOwn }),
])
: [null, null];
// Demo-account badge: true when this profile matches the instance's // Demo-account badge: true when this profile matches the instance's
// configured demo persona username. Computed server-side so we don't // configured demo persona username. Computed server-side so we don't
@ -92,6 +95,7 @@ export async function loadUserProfile(request: Request, username: string) {
createdAt: a.createdAt.toISOString(), createdAt: a.createdAt.toISOString(),
})), })),
stats, stats,
weeklyDistance,
activitySort, activitySort,
isOwn, isOwn,
isDemoUser, isDemoUser,

View file

@ -6,6 +6,7 @@ import { FollowButton } from "~/components/FollowButton";
import { SportBadge } from "~/components/SportBadge"; import { SportBadge } from "~/components/SportBadge";
import { StatRow } from "~/components/StatRow"; import { StatRow } from "~/components/StatRow";
import { ProfileStats } from "~/components/ProfileStats"; import { ProfileStats } from "~/components/ProfileStats";
import { WeeklyDistanceChart } from "~/components/WeeklyDistanceChart";
import { activityStatItems } from "~/lib/stats"; import { activityStatItems } from "~/lib/stats";
import { loadUserProfile } from "./users.$username.server"; import { loadUserProfile } from "./users.$username.server";
import { import {
@ -53,7 +54,7 @@ export function meta({ data: loaderData }: Route.MetaArgs) {
} }
export default function UserProfilePage({ loaderData }: Route.ComponentProps) { export default function UserProfilePage({ loaderData }: Route.ComponentProps) {
const { user, routes, activities, stats, activitySort, isOwn, isDemoUser, followers, following, followState, isLoggedIn, canSeeContent } = loaderData; const { user, routes, activities, stats, weeklyDistance, activitySort, isOwn, isDemoUser, followers, following, followState, isLoggedIn, canSeeContent } = loaderData;
const { t } = useTranslation("journal"); const { t } = useTranslation("journal");
return ( return (
@ -126,6 +127,9 @@ export default function UserProfilePage({ loaderData }: Route.ComponentProps) {
</div> </div>
{stats && <ProfileStats stats={stats} className="mt-6" />} {stats && <ProfileStats stats={stats} className="mt-6" />}
{weeklyDistance && weeklyDistance.length > 0 && (
<WeeklyDistanceChart weeks={weeklyDistance} className="mt-4" />
)}
{!canSeeContent && ( {!canSeeContent && (
<div className="mt-8 rounded-lg border border-gray-200 bg-gray-50 p-6 text-center"> <div className="mt-8 rounded-lg border border-gray-200 bg-gray-50 p-6 text-center">

View file

@ -0,0 +1,26 @@
import { test, expect, gotoHydrated } from "./fixtures/test";
import { setupVirtualAuthenticator, registerUser } from "./helpers/auth";
// GPX with geometry → the activity has a non-zero distance, so the weekly
// chart has a bar to draw (it hides when there's no distance in the window).
const GPX = "packages/fit/__fixtures__/alpine.gpx";
test.describe("Profile weekly distance", () => {
test("profile shows the weekly distance chart when there is recent distance", async ({ page }) => {
const cdp = await page.context().newCDPSession(page);
await setupVirtualAuthenticator(cdp);
const stamp = Date.now();
const username = `wd${stamp}`;
await registerUser(page, `wd-${stamp}@example.com`, username);
await gotoHydrated(page, "/activities/new");
await page.getByLabel("Name").fill("Weekly chart check");
await page.locator('input[name="gpx"]').setInputFiles(GPX);
await page.getByRole("button", { name: "Create Activity" }).click();
await expect(page).toHaveURL(/\/activities\/[0-9a-f-]+$/, { timeout: 10000 });
await gotoHydrated(page, `/users/${username}`);
await expect(page.getByText(/Weekly distance/)).toBeVisible();
});
});

View file

@ -1,20 +1,20 @@
## 1. Aggregate query ## 1. Aggregate query
- [ ] 1.1 Add `getWeeklyDistance(ownerId, { publicOnly, weeks = 12 })` to `activities.server.ts`: `sum(distance)` grouped by `date_trunc('week', coalesce(started_at, created_at))` over the last `weeks` weeks, viewer-scoped. - [x] 1.1 Added `getWeeklyDistance(ownerId, { publicOnly, weeks = 12 })` to `activities.server.ts`: `sum(distance)` per week, viewer-scoped.
- [ ] 1.2 Gap-fill to a contiguous oldest→newest series with `0` for empty weeks; return `{ weekStart, distance }[]`. - [x] 1.2 Gap-fill done **in SQL** (`generate_series` of week-starts LEFT JOINed to the activities) — returns exactly N contiguous `{ weekStart, distance }` rows, oldest→newest, and guarantees the week boundaries match Postgres `date_trunc('week', …)` (no JS/Postgres boundary drift). Filter conditions live in the JOIN's ON clause so empty weeks survive.
## 2. Loader & view ## 2. Loader & view
- [ ] 2.1 Profile loader passes the series (same `publicOnly: !isOwn` scoping; only when content is visible). - [x] 2.1 Profile loader fetches it in parallel with the stats, same `publicOnly: !isOwn` scoping, only when content is visible.
- [ ] 2.2 `WeeklyDistanceChart` component: SVG bars normalized to the max week, per-bar `title` distance (via `stats.ts`), localized label; renders nothing when every week is 0. Mount under `ProfileStats`. - [x] 2.2 `WeeklyDistanceChart`: SVG bars normalized to the busiest week, per-bar `title` distance (via `stats.ts`), localized label; renders nothing when every week is 0. Mounted under `ProfileStats`.
## 3. i18n ## 3. i18n
- [ ] 3.1 Add `journal.profileStats.weeklyDistance*` (label + per-bar readout) to en + de. - [x] 3.1 Added `journal.profileStats.weeklyDistance` (label) to en + de. Per-bar readout is the language-neutral km distance.
## 4. Tests & checks ## 4. Tests & checks
- [ ] 4.1 Unit: gap-fill produces 12 contiguous weeks with zeros in the right slots. - [x] 4.1 Gap-fill is in SQL (no JS helper to unit-test) → covered by the e2e (a real activity produces a non-zero bar over a full 12-week axis).
- [ ] 4.2 Component (jsdom): renders 12 bars for a series; nothing when all zero; tallest bar = busiest week. - [x] 4.2 Component (jsdom): one bar per week incl. zero weeks; nothing when all zero; heights normalized to the busiest week.
- [ ] 4.3 E2E: create activities, assert the weekly chart renders on the profile. - [x] 4.3 E2E `profile-weekly-distance.test.ts`: create an activity with distance → the weekly chart renders on the profile. Passes locally.
- [ ] 4.4 `pnpm typecheck && pnpm lint && pnpm test && pnpm test:e2e` green. - [x] 4.4 typecheck + lint + unit (journal 321) green; new e2e passes locally. Full `pnpm test:e2e` runs in CI.

View file

@ -415,6 +415,7 @@ export default {
ascent: "Anstieg", ascent: "Anstieg",
time: "Zeit", time: "Zeit",
last4Weeks: "{{count}} in den letzten 4 Wochen", last4Weeks: "{{count}} in den letzten 4 Wochen",
weeklyDistance: "Wochendistanz (letzte 12 Wochen)",
}, },
settings: { settings: {
title: "Einstellungen", title: "Einstellungen",

View file

@ -415,6 +415,7 @@ export default {
ascent: "Ascent", ascent: "Ascent",
time: "Time", time: "Time",
last4Weeks: "{{count}} in the last 4 weeks", last4Weeks: "{{count}} in the last 4 weeks",
weeklyDistance: "Weekly distance (last 12 weeks)",
}, },
settings: { settings: {
title: "Settings", title: "Settings",

View file

@ -146,6 +146,14 @@ export default defineConfig({
baseURL: "http://localhost:3000", baseURL: "http://localhost:3000",
}, },
}, },
{
name: "profile-weekly-distance",
testMatch: "profile-weekly-distance.test.ts",
use: {
...devices["Desktop Chrome"],
baseURL: "http://localhost:3000",
},
},
], ],
webServer: process.env.CI webServer: process.env.CI
? [ ? [