chore(release): v1.4.29

A targeted performance + polish patch. The headline is a faster
dashboard on data-rich accounts: the pulse chart drops up to
~5 000 raw rows per range tab in favour of one row per day, the
duplicate `/api/dashboard/widgets` fetch on every mount collapses
to one, and three long-running analytics reads are bounded to
the trailing window the tile path actually needs. Two production
regressions close — the `aggregate=daily|weekly|monthly` path on
`/api/measurements` 500'd for every grain, and the same path
averaged cumulative step counts instead of summing.
This commit is contained in:
Marc-André Bombeck authored and GitHub committed 2026-05-16 10:59:42 +02:00
1 parent 232ea43d99
commit d76c0b56e7
25 files changed
+3250 -65

No files matched your search

+24 -3
View File
@@ -183,9 +183,21 @@ export const GET = apiHandler(async () => {
// `BpReading[]` shape the existing helper expects. The
// `analytics.bp_in_target.row_count` wide-event meta lets ops
// attribute slow requests to specific outlier users.
// v1.4.29 M1 — bound the BP-in-target reads to the trailing
// 365 days. `computeBpInTargetWindows` only needs the last
// year (the longest sub-window it computes is `priorYear`);
// pre-bound, each chunked walk pulled the entire BP history
// every dashboard mount.
const bpInTargetSince = new Date(
now.getTime() - 365 * 24 * 60 * 60 * 1000,
);
const [sysData, diaData] = await Promise.all([
fetchMeasurementSeriesChunked(user.id, "BLOOD_PRESSURE_SYS"),
fetchMeasurementSeriesChunked(user.id, "BLOOD_PRESSURE_DIA"),
fetchMeasurementSeriesChunked(user.id, "BLOOD_PRESSURE_SYS", {
since: bpInTargetSince,
}),
fetchMeasurementSeriesChunked(user.id, "BLOOD_PRESSURE_DIA", {
since: bpInTargetSince,
}),
]);
annotate({
@@ -210,8 +222,17 @@ export const GET = apiHandler(async () => {
}
// Per-context glucose summaries (canonical mg/dL).
//
// v1.4.29 H2 — bound to the trailing 30 days. The dashboard tile
// path only reads the trailing window; pre-bound this query
// walked every persisted BG row a multi-year user has written.
const glucoseSince = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
const glucoseRows = await prisma.measurement.findMany({
where: { userId: user.id, type: "BLOOD_GLUCOSE" },
where: {
userId: user.id,
type: "BLOOD_GLUCOSE",
measuredAt: { gte: glucoseSince },
},
orderBy: { measuredAt: "asc" },
select: { value: true, measuredAt: true, glucoseContext: true },
});
+29 -4
View File
@@ -18,6 +18,7 @@ import {
BUCKET_CAP,
type AggregateGrain,
} from "@/lib/measurements/range-aggregation";
import { CUMULATIVE_HK_TYPES } from "@/lib/measurements/apple-health-mapping";
import { withIdempotency } from "@/lib/idempotency";
import { NextRequest } from "next/server";
import type {
@@ -74,20 +75,44 @@ export const GET = apiHandler(async (request: NextRequest) => {
if (aggregate && aggregate !== "raw" && from && to) {
const grain: AggregateGrain = aggregate;
const cap = Math.min(limit, BUCKET_CAP[grain]);
const truncUnit = grain === "daily" ? "day" : grain;
// Postgres `date_trunc` requires the unit argument to be a SQL
// literal — it cannot be supplied as a prepared-statement parameter.
// The previous `${truncUnit}` (bound) interpolation 500'd in
// production for every grain; the grain string is restricted to
// the `AggregateGrain` enum upstream via the Zod schema, so
// injecting the mapped unit via `Prisma.raw` is safe. The mapping
// also fixes the "weekly"/"monthly" passthrough — Postgres expects
// the singular forms `week`/`month`.
const TRUNC_UNIT: Record<Exclude<AggregateGrain, "raw">, string> = {
daily: "day",
weekly: "week",
monthly: "month",
};
const truncUnit = TRUNC_UNIT[grain];
const truncUnitLiteral = Prisma.raw(`'${truncUnit}'`);
// Cumulative HK types (steps, active energy, flights, distance,
// daylight) are partial-day increments — averaging across the day
// understates the daily total by the per-bucket sample count.
// SUM for those; AVG for spot metrics (BP, weight, pulse, BG,
// body fat, mood, sleep). See R-A finding 2.
const useSum =
type != null && CUMULATIVE_HK_TYPES.has(type as MeasurementType);
const aggregator = useSum
? Prisma.raw(`SUM(m."value")::double precision`)
: Prisma.raw(`AVG(m."value")::double precision`);
const buckets = await prisma.$queryRaw<
Array<{ type: string; bucket_start: Date; avg: number; cnt: number }>
>`
SELECT
m."type"::text AS type,
date_trunc(${truncUnit}, m."measured_at") AS bucket_start,
AVG(m."value")::double precision AS avg,
date_trunc(${truncUnitLiteral}, m."measured_at") AS bucket_start,
${aggregator} AS avg,
COUNT(*)::int AS cnt
FROM measurements m
WHERE m."user_id" = ${user.id}
AND m."measured_at" >= ${from}
AND m."measured_at" <= ${to}
${type ? Prisma.sql`AND m."type" = ${type}::"MeasurementType"` : Prisma.empty}
${type ? Prisma.sql`AND m."type" = ${type}::measurement_type` : Prisma.empty}
GROUP BY m."type", bucket_start
ORDER BY bucket_start ASC
LIMIT ${cap}
+22 -1
View File
@@ -191,6 +191,16 @@ export default function DashboardPage() {
useState<HTMLDivElement | null>(null);
const [moodFooterEl, setMoodFooterEl] = useState<HTMLDivElement | null>(null);
// v1.4.29 M5 — the three inline dashboard queries default to a
// 0-ms `staleTime`, so a tab-focus-and-return triggered a refetch
// storm. None of these are real-time data; minute-scale staleness
// is fine and the dashboard's chart queries already match this
// cadence.
const DASHBOARD_QUERY_OPTS = {
staleTime: 60_000,
refetchOnWindowFocus: false,
} as const;
const { data } = useQuery({
queryKey: queryKeys.analytics(),
queryFn: async () => {
@@ -200,6 +210,7 @@ export default function DashboardPage() {
return json.data as AnalyticsData;
},
enabled: isAuthenticated,
...DASHBOARD_QUERY_OPTS,
});
const { data: layoutData } = useQuery({
@@ -211,6 +222,7 @@ export default function DashboardPage() {
return json.data as DashboardLayout;
},
enabled: isAuthenticated,
...DASHBOARD_QUERY_OPTS,
});
const { data: moodData } = useQuery({
@@ -225,6 +237,7 @@ export default function DashboardPage() {
};
},
enabled: isAuthenticated,
...DASHBOARD_QUERY_OPTS,
});
// v1.4.27 B1 — the dashboard's `<InsightsCardPreview>` retired (it
@@ -1211,6 +1224,14 @@ export default function DashboardPage() {
// branch above `sm:`.
className={cn(
"flex snap-x snap-mandatory gap-3 overflow-x-auto pb-2",
// v1.4.29 — fixed mobile tile height contract.
// At `<sm` every tile pins to 140 px via the
// `--tile-h` CSS custom property so divergent
// content (callout on / off, sub-row wrap / no
// wrap) cannot drift sibling heights. `sm:`
// releases to `auto` where `grid auto-rows-fr`
// already enforces equal heights.
"[--tile-h:140px] sm:[--tile-h:auto]",
"sm:grid sm:snap-none sm:auto-rows-fr sm:overflow-visible",
"sm:[grid-template-columns:repeat(auto-fit,minmax(min(100%,9rem),1fr))]",
)}
@@ -1221,7 +1242,7 @@ export default function DashboardPage() {
{trendCards.map((entry) => (
<div
key={entry.id}
className="flex min-w-[10rem] shrink-0 snap-start sm:min-w-0 sm:shrink"
className="flex h-[var(--tile-h)] min-w-[10rem] shrink-0 snap-start sm:h-auto sm:min-w-0 sm:shrink"
>
{entry.node}
</div>
@@ -84,6 +84,36 @@ describe("<HealthChart> — bounded range fetch", () => {
expect(measurementsUrl!).toMatch(/type=PULSE/);
// Guard against the legacy unbounded paginator returning.
expect(measurementsUrl!).not.toMatch(/offset=/);
// v1.4.29 C3 — the default 30-day window must request server-
// side daily aggregation so the client doesn't pay for ~5000
// raw pulse rows on every range-tab change.
expect(measurementsUrl!).toMatch(/aggregate=daily/);
});
it("omits aggregate=daily on windows of 7 days or fewer", async () => {
// v1.4.29 C3 — short windows keep raw fetching so the user can
// see hour-by-hour detail on the 7-day view.
const { I18nProvider } = await import("@/lib/i18n/context");
const { HealthChart } = await import("../health-chart");
renderToStaticMarkup(
<I18nProvider initialLocale="en">
<HealthChart
types={["PULSE"]}
title="Pulse"
unit="bpm"
windowOverride="last7days"
/>
</I18nProvider>,
);
await new Promise((resolve) => setTimeout(resolve, 0));
const measurementsUrl = fetchCalls.find((u) =>
u.includes("/api/measurements"),
);
expect(measurementsUrl).toBeDefined();
expect(measurementsUrl!).not.toMatch(/aggregate=daily/);
});
it("re-keys the query when the range window changes", async () => {
@@ -0,0 +1,65 @@
import { describe, it, expect } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { Activity } from "lucide-react";
import { TrendCard } from "../trend-card";
import { I18nProvider } from "@/lib/i18n/context";
/**
* v1.4.29 — mobile tile equal-height contract.
*
* On `<sm` viewports each dashboard tile pins to `--tile-h: 140px`
* via the strip wrapper. The tile-internal callout slot reserves
* `min-h-[18px]` even when no callout is rendered, and the sub-row
* pair switches to `flex-nowrap overflow-hidden` so a narrow tile
* cannot grow vertically.
*
* Per R-C §6 this contract pins regardless of which combination of
* `compareDelta` / `trend7Delta` / sub-rows the tile is rendering.
*/
const RISING = { slope: 0.5, direction: "up" as const, confidence: 0.8 };
function render(node: React.ReactNode) {
return renderToStaticMarkup(
<I18nProvider initialLocale="en">{node}</I18nProvider>,
);
}
describe("<TrendCard> mobile tile equal-height contract", () => {
const baseProps = {
label: "Pulse",
latest: 72,
unit: "bpm",
avg7: 70,
avg30: 71,
icon: Activity,
slope30: RISING,
};
it("renders the callout slot with min-h-[18px] reserved", () => {
const html = render(<TrendCard {...baseProps} />);
// The callout slot wrapper sits between value row + sub-rows and
// reserves a fixed minimum height so sibling tiles don't drift
// when the callout is absent.
expect(html).toContain("min-h-[18px]");
});
it("clamps the comparison callout to one line at <sm", () => {
const html = render(
<TrendCard
{...baseProps}
compareBaseline="lastMonth"
compareDelta={1.2}
/>,
);
expect(html).toContain("line-clamp-1");
expect(html).toContain('data-slot="tile-compare-delta"');
});
it("renders the sub-row pair with flex-nowrap + overflow-hidden", () => {
const html = render(<TrendCard {...baseProps} />);
expect(html).toContain("flex-nowrap");
expect(html).toContain("overflow-hidden");
});
});
+17 -3
View File
@@ -41,7 +41,7 @@ import type {
import { ChartOverlayControls } from "./chart-overlay-controls";
import { useChartOverlayPrefs } from "@/hooks/use-chart-overlay-prefs";
import { useViewportWidth } from "@/hooks/use-viewport-width";
import { chooseTickInterval } from "@/lib/charts/x-axis-density";
import { computeTickPositions } from "@/lib/charts/x-axis-density";
const TIME_RANGES_KEYS = [
{
@@ -577,6 +577,15 @@ export function HealthChart({
typeParams.set("from", fetchWindow.from);
typeParams.set("to", fetchWindow.to);
typeParams.set("limit", "5000");
// v1.4.29 C3 — windows over 7 days ask the server to bucket
// daily. Caps the chart's per-type payload at ~365 rows
// instead of ~5 000 for high-density types (pulse), and drops
// Recharts paint cost ~50× on continuous-monitoring accounts.
// Short windows keep raw fetching so hour-by-hour detail
// stays visible.
if (fetchWindow.windowDays > 7) {
typeParams.set("aggregate", "daily");
}
const res = await fetch(`/api/measurements?${typeParams}`);
if (!res.ok) return;
@@ -1272,8 +1281,13 @@ export function HealthChart({
),
)
}
interval={chooseTickInterval(
chartData?.length ?? 0,
// v1.4.29 — Recharts ignores `interval` on numeric
// axes (`type="number"`). Hand explicit tick
// positions through the `ticks` prop so the legacy
// day-aware density policy stays effective on the
// pulse chart.
ticks={computeTickPositions(
chartData ?? [],
viewportWidth,
)}
padding={{ left: 10, right: 10 }}
+5 -3
View File
@@ -36,7 +36,7 @@ import type {
import { ChartOverlayControls } from "./chart-overlay-controls";
import { useChartOverlayPrefs } from "@/hooks/use-chart-overlay-prefs";
import { useViewportWidth } from "@/hooks/use-viewport-width";
import { chooseTickInterval } from "@/lib/charts/x-axis-density";
import { computeTickPositions } from "@/lib/charts/x-axis-density";
import { CHART_HEIGHT_PX } from "@/lib/charts/constants";
import { moodLabelKeyForScore } from "@/lib/mood/labels";
@@ -748,8 +748,10 @@ export function MoodChart({
),
)
}
interval={chooseTickInterval(
chartData?.length ?? 0,
// v1.4.29 — Recharts ignores `interval` on numeric
// axes; pass explicit tick positions instead.
ticks={computeTickPositions(
chartData ?? [],
viewportWidth,
)}
padding={{ left: 10, right: 10 }}
+15 -6
View File
@@ -265,11 +265,16 @@ export function TrendCard({
flex-wrap on the sibling row + this callout's `mt-1`
horizontal-row layout absorb the overflow without crowding
the headline value above. */}
{compareBaseline !== "none" && compareDelta != null && (
<div className="mt-1">
{/* v1.4.29 — clamp the callout to one line at `<sm` so the
tile's overall height stays inside the 140-px contract.
`min-h-[18px]` reserves the slot when no callout is being
rendered so the sub-row pair below pins to the same y
across every tile. `sm:` releases both bounds. */}
<div className="mt-1 min-h-[18px] sm:min-h-0">
{compareBaseline !== "none" && compareDelta != null && (
<span
className={cn(
"inline-block max-w-full text-xs leading-snug font-medium [overflow-wrap:anywhere] tabular-nums",
"line-clamp-1 inline-block max-w-full text-xs leading-snug font-medium tabular-nums sm:line-clamp-none sm:[overflow-wrap:anywhere]",
comparisonDeltaColor,
)}
data-slot="tile-compare-delta"
@@ -286,10 +291,14 @@ export function TrendCard({
: "comparison.captionLastYear",
)}`}
</span>
</div>
)}
)}
</div>
<TooltipProvider>
<div className="text-muted-foreground mt-auto flex min-w-0 flex-wrap gap-x-3 gap-y-1 pt-1 text-xs leading-snug">
{/* v1.4.29 — sub-row pair clips rather than wraps at `<sm`
so a narrow tile cannot grow vertically beyond the
140-px contract. `sm:` releases back to the original
wrap behaviour. */}
<div className="text-muted-foreground mt-auto flex min-w-0 flex-nowrap items-baseline gap-x-3 overflow-hidden pt-1 text-xs leading-snug sm:flex-wrap sm:gap-y-1">
<span className="max-w-full min-w-0 [overflow-wrap:anywhere]">
{t(avg7LabelKey)}:{" "}
{avg7Hint ? (
@@ -252,15 +252,23 @@ export function DashboardLayoutSection({ id }: { id: string }) {
chart in the lower row. the maintainer wanted independent control
of the two surfaces (per feedback_dashboard_top_tiles
_selectable.md). */}
<div className="text-muted-foreground flex items-center gap-3 px-3 pb-1 text-[10px] font-medium tracking-wide uppercase">
<span className="w-11" aria-hidden="true" />
<span className="flex-1" />
{/* v1.4.29 — column-header alignment for the new
horizontal arrow pair on the trailing edge. The
right-hand spacer reserves the width of two
size-11/sm:size-9 buttons so the Tile / Chart column
headers continue to line up with the switches below. */}
<div className="text-muted-foreground flex items-center gap-2 px-3 pb-1 text-[10px] font-medium tracking-wide uppercase">
<span className="flex-1" aria-hidden="true" />
<span className="w-12 text-center">
{t("dashboard.layoutTileColumn")}
</span>
<span className="w-12 text-center">
{t("dashboard.layoutChartColumn")}
</span>
<span
className="w-22 sm:w-18"
aria-hidden="true"
/>
</div>
{[...layout.widgets]
.sort((a, b) => a.order - b.order)
@@ -271,37 +279,24 @@ export function DashboardLayoutSection({ id }: { id: string }) {
? widget.tileVisible
: widget.visible;
return (
// v1.4.29 — drag-list row compactness. The legacy
// vertical 44+44-px arrow stack inflated each row
// to ~116 px; the horizontal arrow pair on the
// trailing edge drops the row to 48 px (`min-h-12`)
// while preserving the 44-px mobile tap target
// (`size-11`). `sm:size-9` shrinks the buttons
// visually on desktop where pointer accuracy is
// higher.
<div
key={widget.id}
className="border-border bg-background/30 flex items-center gap-3 rounded-md border p-3"
className="border-border bg-background/30 flex min-h-12 items-center gap-2 rounded-md border px-3 py-2"
>
<div className="flex flex-col gap-1">
<Button
type="button"
variant="ghost"
size="icon"
className="size-11"
onClick={() => move(widget.id, -1)}
disabled={index === 0 || saveMutation.isPending}
aria-label={t("dashboard.moveUp")}
>
<ArrowUp className="h-4 w-4" />
</Button>
<Button
type="button"
variant="ghost"
size="icon"
className="size-11"
onClick={() => move(widget.id, 1)}
disabled={
index === arr.length - 1 || saveMutation.isPending
}
aria-label={t("dashboard.moveDown")}
>
<ArrowDown className="h-4 w-4" />
</Button>
</div>
<span className="flex-1 text-sm">{t(labelKey)}</span>
<span
className="flex-1 truncate text-sm"
title={t(labelKey)}
>
{t(labelKey)}
</span>
<div className="flex w-12 justify-center">
<Switch
checked={tileChecked}
@@ -320,6 +315,30 @@ export function DashboardLayoutSection({ id }: { id: string }) {
data-slot="widget-chart-switch"
/>
</div>
<Button
type="button"
variant="ghost"
size="icon"
className="size-11 sm:size-9"
onClick={() => move(widget.id, -1)}
disabled={index === 0 || saveMutation.isPending}
aria-label={t("dashboard.moveUp")}
>
<ArrowUp className="h-4 w-4" />
</Button>
<Button
type="button"
variant="ghost"
size="icon"
className="size-11 sm:size-9"
onClick={() => move(widget.id, 1)}
disabled={
index === arr.length - 1 || saveMutation.isPending
}
aria-label={t("dashboard.moveDown")}
>
<ArrowDown className="h-4 w-4" />
</Button>
</div>
);
})}
+25 -12
View File
@@ -10,16 +10,22 @@ import {
type ChartOverlayPrefsMap,
type DashboardLayout,
} from "@/lib/dashboard-layout";
import { queryKeys } from "@/lib/query-keys";
/**
* v1.4.18 — TanStack Query hook that returns a single chart's overlay
* prefs and a setter that persists them via the new
* `PUT /api/dashboard/chart-overlay-prefs` endpoint.
*
* Reads from the existing dashboard-widgets cache (queryKey
* `["dashboard-layout"]`) so a chart on the dashboard doesn't fire a
* second network request — the layout already lands once on initial
* dashboard render.
* Reads from the existing dashboard-widgets cache so a chart on the
* dashboard doesn't fire a second network request — the layout
* already lands once on initial dashboard render.
*
* v1.4.29 C4 — share the same `queryKeys.dashboardWidgets()` slot
* the dashboard page + Settings → Dashboard already consume.
* Pre-fix the hook keyed under `["dashboard-layout"]`, splitting the
* cache into two slots for the same endpoint and firing
* `/api/dashboard/widgets` twice on dashboard mount.
*
* The mutation is optimistic: we update the cached layout immediately
* so the chart re-renders with the new toggle state before the network
@@ -36,7 +42,7 @@ export function useChartOverlayPrefs(
const queryClient = useQueryClient();
const { data: layout } = useQuery({
queryKey: ["dashboard-layout"],
queryKey: queryKeys.dashboardWidgets(),
queryFn: async (): Promise<DashboardLayout> => {
const res = await fetch("/api/dashboard/widgets");
if (!res.ok) throw new Error("Failed to load dashboard layout");
@@ -73,10 +79,12 @@ export function useChartOverlayPrefs(
},
onMutate: async (next) => {
if (!chartKey) return { previous: undefined };
await queryClient.cancelQueries({ queryKey: ["dashboard-layout"] });
const previous = queryClient.getQueryData<DashboardLayout>([
"dashboard-layout",
]);
await queryClient.cancelQueries({
queryKey: queryKeys.dashboardWidgets(),
});
const previous = queryClient.getQueryData<DashboardLayout>(
queryKeys.dashboardWidgets(),
);
if (previous) {
const nextLayout: DashboardLayout = {
...previous,
@@ -85,18 +93,23 @@ export function useChartOverlayPrefs(
[chartKey]: next,
} as ChartOverlayPrefsMap,
};
queryClient.setQueryData(["dashboard-layout"], nextLayout);
queryClient.setQueryData(queryKeys.dashboardWidgets(), nextLayout);
}
return { previous };
},
onError: (_err, _next, ctx) => {
const context = ctx as { previous?: DashboardLayout } | undefined;
if (context?.previous) {
queryClient.setQueryData(["dashboard-layout"], context.previous);
queryClient.setQueryData(
queryKeys.dashboardWidgets(),
context.previous,
);
}
},
onSettled: () => {
queryClient.invalidateQueries({ queryKey: ["dashboard-layout"] });
queryClient.invalidateQueries({
queryKey: queryKeys.dashboardWidgets(),
});
},
});
@@ -1,6 +1,10 @@
import { describe, expect, it } from "vitest";
import { chooseTickInterval, resolveTargetTickCount } from "../x-axis-density";
import {
chooseTickInterval,
computeTickPositions,
resolveTargetTickCount,
} from "../x-axis-density";
describe("resolveTargetTickCount (v1.4.19 legacy cap helper)", () => {
it("caps Galaxy Fold compact (≤360px) at 4 ticks", () => {
@@ -107,3 +111,55 @@ describe("chooseTickInterval (v1.4.25 W3b day-aware policy)", () => {
});
});
});
describe("computeTickPositions (v1.4.29 numeric-axis helper)", () => {
// Recharts ignores `interval` on `type="number"` axes; the pulse +
// mood charts switched to numeric axes and silently lost the
// density policy. `computeTickPositions` translates the policy
// into explicit indices the numeric axis can consume.
it("returns every index when the chart has fewer points than the bucket threshold", () => {
const data = Array.from({ length: 5 }, (_, i) => ({ timestamp: i }));
expect(computeTickPositions(data, 393)).toEqual([0, 1, 2, 3, 4]);
});
it("returns [0] for a single-point chart", () => {
expect(computeTickPositions([{ timestamp: 0 }], 393)).toEqual([0]);
});
it("returns [] for an empty chart", () => {
expect(computeTickPositions([], 393)).toEqual([]);
});
it("caps ticks to ~12 for a 365-point series", () => {
const data = Array.from({ length: 365 }, (_, i) => ({ timestamp: i }));
const ticks = computeTickPositions(data, 393);
expect(ticks.length).toBeLessThanOrEqual(13);
expect(ticks.length).toBeGreaterThanOrEqual(6);
// First + last indices always present.
expect(ticks[0]).toBe(0);
expect(ticks[ticks.length - 1]).toBe(364);
});
it("hits a weekly-rhythm cadence on a 30-day chart at mobile width", () => {
const data = Array.from({ length: 30 }, (_, i) => ({ timestamp: i }));
const ticks = computeTickPositions(data, 393);
// 30 points / 7-day skip → 5 ticks (0, 7, 14, 21, 28) + last (29).
expect(ticks.length).toBeGreaterThanOrEqual(4);
expect(ticks.length).toBeLessThanOrEqual(6);
expect(ticks[0]).toBe(0);
expect(ticks[ticks.length - 1]).toBe(29);
});
it("never returns duplicate or out-of-bounds indices", () => {
for (const length of [2, 7, 14, 30, 90, 180, 365]) {
const data = Array.from({ length }, (_, i) => ({ timestamp: i }));
const ticks = computeTickPositions(data, 393);
expect(new Set(ticks).size).toBe(ticks.length);
for (const t of ticks) {
expect(t).toBeGreaterThanOrEqual(0);
expect(t).toBeLessThan(length);
}
}
});
});
+55
View File
@@ -160,3 +160,58 @@ export function getViewportWidth(): number {
// viewport, not the visual one. Fall back to innerWidth.
return window.innerWidth ?? 1280;
}
/**
* v1.4.29 — Recharts ignores the `interval` prop on a numeric
* `<XAxis type="number" />`. The pulse + mood charts switched to
* numeric axes in v1.4.25 to support multi-band rendering; the
* legacy `interval` value silently degraded to "every tick" on
* those charts.
*
* `computeTickPositions` returns explicit tick indices the numeric
* axis can consume via the `ticks` prop. The skip count comes from
* `chooseTickInterval` so the day-aware policy stays in one place.
* The result is clamped to at least 3 ticks (when the chart has
* enough data) and at most ~12, so the user always sees calendar
* landmarks without overcrowding.
*
* Returns an empty array for zero-length data and `[0]` for a
* single-point chart.
*/
export function computeTickPositions(
chartData: ReadonlyArray<{ timestamp: number } | unknown>,
viewportWidth: number,
): number[] {
const length = chartData?.length ?? 0;
if (length <= 0) return [];
if (length === 1) return [0];
const lastIndex = length - 1;
const interval = chooseTickInterval(length, viewportWidth);
// `interval === 0` means "render every tick". Cap the visible tick
// count so dense series (e.g. 365-row pulse) never blow past ~12
// labels — pick a step that hits ~6 ticks if the policy would
// otherwise produce too many.
const TARGET_MAX_TICKS = 12;
let step = interval > 0 ? interval + 1 : 1;
if (length / step > TARGET_MAX_TICKS) {
step = Math.ceil(length / TARGET_MAX_TICKS);
}
// Floor on visible tick count — never fewer than 3 ticks unless
// the data simply doesn't have that many points.
const minTicks = Math.min(3, length);
if (length / step < minTicks) {
step = Math.max(1, Math.floor(length / minTicks));
}
const ticks: number[] = [];
for (let i = 0; i <= lastIndex; i += step) {
ticks.push(i);
}
// Always include the last index so the chart's right edge keeps a
// tick label.
if (ticks[ticks.length - 1] !== lastIndex) {
ticks.push(lastIndex);
}
return ticks;
}
@@ -287,6 +287,29 @@ export const APPLE_HEALTH_TYPE_MAP: Record<string, AppleHealthMapping> = {
},
};
/**
* v1.4.29 — MeasurementTypes whose `aggregate=daily|weekly|monthly`
* grain on `GET /api/measurements` must reduce with `SUM`, not `AVG`.
*
* These are the cumulative-quantity HealthKit types where every row
* is a partial-day increment (steps for one minute, kilocalories for
* one workout, metres for one walk). Averaging across the day
* silently understates the daily total by the per-bucket sample
* count. Spot metrics (BP, weight, pulse, mood, BG, body fat, sleep)
* stay on `AVG`.
*
* Used by `src/app/api/measurements/route.ts` when picking the SQL
* aggregator. Mirrors the canonical list documented in
* `.planning/research/v15-r-a-step-aggregation.md` §6.
*/
export const CUMULATIVE_HK_TYPES: ReadonlySet<MeasurementType> = new Set<MeasurementType>([
"ACTIVITY_STEPS",
"ACTIVE_ENERGY_BURNED",
"FLIGHTS_CLIMBED",
"WALKING_RUNNING_DISTANCE",
"TIME_IN_DAYLIGHT",
]);
/**
* HK identifiers the iOS app may emit that HealthLog deliberately does
* NOT map yet. Listing them here means the batch route can log a