mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-19 08:12:52 +00:00
The final functional web release before the iOS native client lands.
Headline work: a streaming Apple Health `export.zip` importer for
prospective iOS-migrating accounts, a server-side aggregation cache
that collapses the three hottest dashboard reads onto in-process LRU
slots with single-flight coalescing and per-user invalidation, a
broader compliance classifier with a dedicated `early` bucket so
ahead-of-window doses count as compliant, the Coach launch surface
hoisted onto every authed page with a dashboard-hero CTA, and a
trimmer Settings shelf that folds Sources into Targets. The release
also lights up the `cache.<name>.outcome` annotation on the active
wide event so production logs carry the cache hit-ratio signal
without leaking userIds.
### Added
- **Server-side aggregation cache.** A new `ServerCache<T>` primitive
(`src/lib/cache/server-cache.ts`) extends the v1.4.33 Coach snapshot
LRU shape into a reusable per-route layer with TTL expiry,
capacity-bounded LRU eviction, single-flight read coalescing, and
per-instance hit / miss / eviction / stampede counters. Wires the
three hottest dashboard reads — `/api/analytics` (slim + default),
`/api/gamification/achievements`, `/api/medications/intake?scope=compliance`
— and bolts per-user invalidation onto every measurement / mood /
medication / workout / dashboard-widget write endpoint so the next
read paints fresh data instead of waiting out the TTL. Every cache
hit / miss surfaces on the active wide event as
`cache.<name>.outcome` + `cache.<name>.key_hash` so production logs
carry the hit-ratio signal without leaking userIds.
- **Apple Health `export.zip` import.** New endpoint
`POST /api/import/apple-health-export` (synchronous multipart
upload, asynchronous ingest via a dedicated pg-boss
`apple-health-import` worker, per-`MeasurementType` ingestion
stats). Streams the upload straight to disk so a multi-gigabyte
export never lands in V8 heap, hashes the bytes inline for
content-based idempotency, and unpacks `apple_health_export/export.xml`
with a hand-rolled ZIP central-directory walker that handles Zip64
for archives past the 4 GB barrier. The parser folds every
`<Record>`, `<Workout>`, `<Correlation>`, and `<ClinicalRecord>`
into the existing `Measurement` and `Workout` row shapes — spot
rows keyed by `HKMetadataKeyExternalUUID` (or a deterministic
`sample:<sha256>` fallback), cumulative HK types collapsed into
one `stats:<HKType>:<YYYY-MM-DD>` row per user-local day to match
the iOS daily-aggregation convention. Live per-stage progress
surfaces through `GET /api/import/apple-health-export/{jobId}/status`.
An admin variant at `POST /api/admin/import-apple-health-export`
imports on behalf of a target user (cookie-only `requireAdmin()`
gate; Bearer tokens never elevate).
- **`ImportJob` schema model + migration.** New Prisma model captures
the per-upload state machine (`queued | unpacking | parsing |
upserting | done | failed`), the content-hash for idempotency
short-circuits, and the per-`MeasurementType` ingestion counters
the status route surfaces back to the client.
- **`lastSeenByType` on `/api/analytics`.** Both the slim
(`?slice=summaries`) and default slices return a per-type
`{ lastSeenAt, daysAgo }` map. The dashboard trend tiles wire 12
mounts to a new `tileStaleDays()` helper so an "X days / weeks /
months ago" hint paints under any per-metric tile whose last
sample crosses the 7-day floor. Six locales gained additive
week / month plural keys; Polish uses the genitive-plural form
that covers every non-1 count the bucket math can produce.
- **Dashboard "Ask the coach" hero CTA.** A new pill next to the
existing "Hinzufügen" / "Add" launches the Coach drawer directly
from the dashboard hero. The `<CoachLaunchProvider>` hoisted from
the insights layout to the auth shell so the drawer is reachable
from every authed route; the floating action button stays scoped
to `/insights/**` so it cannot distract on the dashboard.
- **Shared achievements query hook.** `useAchievementsQuery()`
centralises the three previous consumers — recent-achievements
card, the `/achievements` mother page, and the unlock notifier —
onto one TanStack queryKey + cache slot so dashboard cold mount
fires the endpoint once instead of twice.
- **Typed authed Cache-Control presets.** New
`src/lib/http/cache-headers.ts` module exports
`NO_STORE_BUT_BFCACHE = "private, max-age=0, must-revalidate"`,
`SHORT_LIVED_PUBLIC`, and an `applyAuthedHeaders()` helper. The
presets land at the framework level via a `next.config.ts`
`headers()` rule that stamps the bfcache-friendly directive on
every authed HTML response, restoring Chromium bfcache eligibility
for in-app back / forward navigation.
- **`scripts/print-bundle-report.mjs`.** Restores the at-a-glance
"top client chunks by parsed size" signal Turbopack dropped from
`next build`; reads `.next/analyze/client.json` (written by
`@next/bundle-analyzer` when `pnpm analyze` runs with `ANALYZE=1`)
and prints a sorted table plus totals.
### Changed
- **Settings sidebar: "Sources" folded into "Targets & Sources".**
Per-metric threshold ranges and per-metric source priority now
share one `/settings/thresholds` page so the same metric's
threshold and device-source preference sit together instead of
one sidebar entry away. `/settings/sources` keeps a
`permanentRedirect` so external bookmarks and docs links follow
through unchanged. Section count: 11 → 10.
- **Insights tab strip: vital pills collapse under a "Vitals"
parent.** Five vital pills (HRV, Resting HR, Oxygen, Body
Temperature, Active Energy) hide behind one parent pill that
opens a popover sub-list. Parent-pill active state mirrors the
URL so spatial orientation survives the collapse; each sub-page
keeps its own URL and bookmark resolves unchanged. Strip
footprint: 14 → 10 entries when every metric has data.
- **Coolify env-var audit.** `mcp__coolify-apps01__env_vars`
inspection captured the section-1 / section-2 duplicates that
have accumulated under apps-01 since v1.3.1. Audit pinned at
`.planning/round-v1434-iwa-coolify-env-audit.md`; no env-var
deletes performed (operator action).
### Fixed
- **Compliance classifier: early intakes count as compliant.** The
classifier picked up a dedicated `early` bucket (window-start
minus three hours through window-start), the `on_time` post-window
tolerance widened from one hour to three hours, and the `late`
band sits between the new `on_time` ceiling and the configurable
`lateMinutes` knob. Heatmap consumers route the new bucket
through the compliant path; the dedicated `early` counter rides
on `DailyComplianceEntry` for downstream consumers that want to
distinguish ahead-of-window from on-window intakes.
- **Compliance heatmap fallback retired.** The v1.4.33 defensive
`looksClassifierBug` fallthrough is gone now that the underlying
classifier widening removes the every-dose-very-late mode the
fallback covered.
### Performance
- **`/api/gamification/achievements` consumer collapse.** Two of
three previous consumers shared the same TanStack queryKey
literal; the third carried a per-user discriminator so the cache
treated it as a fresh slot. Dashboard cold mount fired the
endpoint twice. Collapsing onto the shared hook trims that to a
single request; with the new server-side cache slot warm, the
duplicate-mount worst case rides single-flight coalescing.
- **GHCR build fires once per release tag.** The
`docker-publish.yml` workflow lost its `push.branches: [main]`
trigger; the `:latest` raw-tag enable rule moved onto the tag
ref so each release produces exactly one multi-arch build that
refreshes both the semver tags and the `:latest` alias.
- **NFT-trace warnings silenced.** `next.config.ts` gained an
`outputFileTracingExcludes` block that narrows the Turbopack
tracer away from the `MAXMIND_LICENSE_KEY` env-access path so
the trace-report no longer warns on every dependent route file.
### Refactor
- **Dashboard analytics consumers.** The two cards that previously
decided their own freshness copy now lean on the typed
`tileStaleDays()` helper and the additive `lastSeenByType` field
on the analytics response. Mood and BD-Zielbereich tiles keep the
default `null` because they have no underlying per-type freshness
signal.
### Accessibility
- **Dashboard hero CTA hits the WCAG 2.5.5 touch-target floor.**
The new "Ask the coach" pill carries `min-h-11` on mobile and
the matching `sm:min-h-9` desktop floor so the touch target
stays above 44 px on the Pixel 5 boundary.
- **Insights tab-strip Vitals parent reads correctly to assistive
tech.** Parent pill carries `aria-current="page"` whenever the
current URL matches one of its child vital sub-pages, plus a
`data-slot="insights-tab-strip-group"` hook for visual-regression
testing.
### Internal
- **Two e2e flake windows tightened.** `onboarding-flicker` swapped
its 12-sample 50 ms poll loop for a single Playwright
auto-retrying `toBeHidden({ timeout: 700 })` assertion so the
1-2 ms race window between the analytics-pending shell and
`useAuth().user` resolving collapses to a single retry slot.
`mobile-viewport` dropped `nav a[href]` from the touch-target
sweep (the bottom-nav owns its own WCAG spec) and gated the
44-px floor on `matchMedia('(min-width: 640px)').matches === false`
so the Pixel 5 viewport never tripped into the `sm:` tier during
WebKit render commits.
- **Server-cache observability.** Every `cached()` invocation passes
an `annotate` callback that lands two keys on the wide event:
`cache.<name>.outcome` ∈ `{ hit | miss | stampede }` and
`cache.<name>.key_hash` (non-reversible djb2 32-bit hash). Ops
can grep `cache.analytics.outcome` over any time window to
compute the hit ratio per deployment.
- **AASA followups verified.** The v1.4.33 `/.well-known/apple-app-site-association`
handler serves a direct 200 on every fronting origin; Apple's
CDN has ingested matching bodies for all three domains.
### Web freeze
v1.4.34 marks the last functional release of the web codebase before
the iOS native client launches. Subsequent v1.4.x tags carry security
fixes, dependency bumps, and hotfix-only corrections. New feature work
is paused until the iOS app clears Apple review, at which point a
v1.5.0 version-bump-only release tags the milestone. The Prisma
schema head comment and `.planning/v15-strategic-plan.md` §5
decision-log row pin the freeze trigger in-tree.
635 lines
25 KiB
TypeScript
635 lines
25 KiB
TypeScript
"use client";
|
|
|
|
/**
|
|
* v1.4.25 W5e — Settings → Sources.
|
|
*
|
|
* Per-metric-class source priority. When more than one ingest source
|
|
* records the same metric for the same day, the analytics aggregator
|
|
* picks ONE canonical source per day (for cumulative metrics like
|
|
* steps / sleep duration) or surfaces a "preferred" source (for point
|
|
* measurements like weight / BP). Non-picked rows stay in the DB as an
|
|
* audit trail.
|
|
*
|
|
* Today (v1.4.25) only WITHINGS + MANUAL coexist; the cumulative-metric
|
|
* aggregator no-ops because no user has two ingest paths reporting the
|
|
* same daily total. The UI lands now so v1.5's Apple Health passthrough
|
|
* drops onto a known foundation — every user's preferences carry
|
|
* straight into iOS-era analytics without an extra migration step.
|
|
*
|
|
* v1.4.25 W8c — two-axis extension. The same screen now hosts three
|
|
* vertically-stacked sections (Marc no-split directive):
|
|
* 1. Global default ladder per metric class (existing).
|
|
* 2. Per-metric override expander — collapsed by default; an
|
|
* explicit knob for power users (the global ladder already lives
|
|
* above and most users never open this).
|
|
* 3. Device-type override expander — collapsed by default; one
|
|
* global ladder ("watch beats phone beats scale") with optional
|
|
* per-metric overrides.
|
|
*/
|
|
|
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
import { useMemo, useState } from "react";
|
|
import { toast } from "sonner";
|
|
import {
|
|
ArrowDown,
|
|
ArrowUp,
|
|
ChevronDown,
|
|
Layers,
|
|
Loader2,
|
|
RotateCcw,
|
|
} from "lucide-react";
|
|
|
|
import { Button } from "@/components/ui/button";
|
|
import { Skeleton } from "@/components/ui/skeleton";
|
|
import { useTranslations } from "@/lib/i18n/context";
|
|
import { queryKeys } from "@/lib/query-keys";
|
|
import {
|
|
DEFAULT_DEVICE_TYPE_PRIORITY,
|
|
DEFAULT_SOURCE_PRIORITY,
|
|
type DeviceType,
|
|
type DeviceTypePriority,
|
|
type MetricPriority,
|
|
SOURCE_PRIORITY_METRIC_KEYS,
|
|
type SourcePriorityMetricKey,
|
|
} from "@/lib/validations/source-priority";
|
|
|
|
/**
|
|
* Resolved shape returned by `GET /api/auth/me/source-priority`. Mirrors
|
|
* `parseSourcePriority()`'s return: every metric ladder is defaulted,
|
|
* the two-axis containers are present (possibly empty).
|
|
*/
|
|
interface ResolvedPriority extends Required<MetricPriority> {
|
|
metricPriority: Required<MetricPriority>;
|
|
deviceTypePriority: DeviceTypePriority;
|
|
}
|
|
|
|
const METRIC_LABEL_KEYS: Record<SourcePriorityMetricKey, string> = {
|
|
steps: "settings.sections.sources.metrics.steps",
|
|
activeEnergy: "settings.sections.sources.metrics.activeEnergy",
|
|
walkingRunningDistance:
|
|
"settings.sections.sources.metrics.walkingRunningDistance",
|
|
flightsClimbed: "settings.sections.sources.metrics.flightsClimbed",
|
|
sleep: "settings.sections.sources.metrics.sleep",
|
|
weight: "settings.sections.sources.metrics.weight",
|
|
bloodPressure: "settings.sections.sources.metrics.bloodPressure",
|
|
pulse: "settings.sections.sources.metrics.pulse",
|
|
bodyFat: "settings.sections.sources.metrics.bodyFat",
|
|
bodyTemperature: "settings.sections.sources.metrics.bodyTemperature",
|
|
spo2: "settings.sections.sources.metrics.spo2",
|
|
hrv: "settings.sections.sources.metrics.hrv",
|
|
restingHeartRate: "settings.sections.sources.metrics.restingHeartRate",
|
|
vo2Max: "settings.sections.sources.metrics.vo2Max",
|
|
};
|
|
|
|
const SOURCE_LABEL_KEYS: Record<string, string> = {
|
|
WITHINGS: "settings.sections.sources.sourceLabels.WITHINGS",
|
|
APPLE_HEALTH: "settings.sections.sources.sourceLabels.APPLE_HEALTH",
|
|
MANUAL: "settings.sections.sources.sourceLabels.MANUAL",
|
|
IMPORT: "settings.sections.sources.sourceLabels.IMPORT",
|
|
};
|
|
|
|
const DEVICE_TYPE_LABEL_KEYS: Record<DeviceType, string> = {
|
|
watch: "settings.sections.sources.deviceLabels.watch",
|
|
band: "settings.sections.sources.deviceLabels.band",
|
|
ring: "settings.sections.sources.deviceLabels.ring",
|
|
phone: "settings.sections.sources.deviceLabels.phone",
|
|
scale: "settings.sections.sources.deviceLabels.scale",
|
|
other: "settings.sections.sources.deviceLabels.other",
|
|
unknown: "settings.sections.sources.deviceLabels.unknown",
|
|
};
|
|
|
|
/**
|
|
* v1.4.34 IW-D — section presentation mode.
|
|
* - `"standalone"` (default) renders the page-level header (h1 +
|
|
* subtitle) and keeps the section's own aria-labelledby wiring.
|
|
* - `"embedded"` drops the header because a parent surface
|
|
* (`<ThresholdsSection>` on `/settings/thresholds`) already names
|
|
* the page. The section becomes a `<div>` instead of a
|
|
* `<section>` so the assistive-tech reading order stays one
|
|
* combined surface.
|
|
*
|
|
* `/settings/sources` no longer renders this component directly — it
|
|
* permanently redirects to `/settings/thresholds`, which uses the
|
|
* `embedded` mode. The default keeps backward compatibility for any
|
|
* test/storybook that still mounts `<SourcesSection />` standalone.
|
|
*/
|
|
export interface SourcesSectionProps {
|
|
mode?: "standalone" | "embedded";
|
|
}
|
|
|
|
export function SourcesSection({ mode = "standalone" }: SourcesSectionProps = {}) {
|
|
const { t } = useTranslations();
|
|
const queryClient = useQueryClient();
|
|
|
|
const { data: remote, isLoading } = useQuery({
|
|
queryKey: queryKeys.sourcePriority(),
|
|
queryFn: async () => {
|
|
const res = await fetch("/api/auth/me/source-priority");
|
|
if (!res.ok) throw new Error("failed");
|
|
const json = await res.json();
|
|
return json.data as ResolvedPriority;
|
|
},
|
|
});
|
|
|
|
// Local draft state — same pattern as `<DashboardLayoutSection>`. The
|
|
// user reorders sources via the up/down arrows; nothing hits the
|
|
// network until they click Save.
|
|
const [draft, setDraft] = useState<ResolvedPriority | null>(null);
|
|
const priority = draft ?? remote ?? null;
|
|
|
|
const [showPerMetric, setShowPerMetric] = useState(false);
|
|
const [showDeviceType, setShowDeviceType] = useState(false);
|
|
|
|
const saveMutation = useMutation({
|
|
mutationFn: async (next: ResolvedPriority) => {
|
|
// PUT the W8c-canonical shape: nested `metricPriority` +
|
|
// `deviceTypePriority` together. The server's
|
|
// `parseSourcePriority` echoes the resolved shape back so the
|
|
// optimistic update is just a `setQueryData`.
|
|
const body = {
|
|
metricPriority: next.metricPriority,
|
|
deviceTypePriority: next.deviceTypePriority,
|
|
};
|
|
const res = await fetch("/api/auth/me/source-priority", {
|
|
method: "PUT",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify(body),
|
|
});
|
|
if (!res.ok) throw new Error("save failed");
|
|
return (await res.json()).data as ResolvedPriority;
|
|
},
|
|
onSuccess: (saved) => {
|
|
queryClient.setQueryData(queryKeys.sourcePriority(), saved);
|
|
// The analytics aggregator folds source priority into per-day
|
|
// canonical-row picks — flush its cache so the charts re-paint
|
|
// with the new picker on the next mount.
|
|
queryClient.invalidateQueries({ queryKey: queryKeys.analytics() });
|
|
setDraft(null);
|
|
toast.success(t("settings.sections.sources.saveSuccess"));
|
|
},
|
|
onError: () => toast.error(t("settings.sections.sources.saveError")),
|
|
});
|
|
|
|
const resetMutation = useMutation({
|
|
mutationFn: async () => {
|
|
// Sending the empty W8c shape clears every per-user override; the
|
|
// server's `parseSourcePriority` then returns the constant
|
|
// defaults verbatim. Keeps the wire payload tiny.
|
|
const res = await fetch("/api/auth/me/source-priority", {
|
|
method: "PUT",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({}),
|
|
});
|
|
if (!res.ok) throw new Error("reset failed");
|
|
return (await res.json()).data as ResolvedPriority;
|
|
},
|
|
onSuccess: (saved) => {
|
|
queryClient.setQueryData(queryKeys.sourcePriority(), saved);
|
|
queryClient.invalidateQueries({ queryKey: queryKeys.analytics() });
|
|
setDraft(null);
|
|
toast.success(t("settings.sections.sources.resetSuccess"));
|
|
},
|
|
});
|
|
|
|
/**
|
|
* Shared adjacent-swap for both ladder buckets. Returns a copy of
|
|
* `list` with `index` and `index+delta` swapped, or `null` when the
|
|
* target index falls outside the array. The helper deliberately stays
|
|
* generic (typed via `T`) so both the source ladder (string[]) and
|
|
* the device-type ladder (DeviceType[]) share one implementation —
|
|
* the previous moveSource + moveDeviceType pair drifted apart twice
|
|
* during W8c before they were re-aligned.
|
|
*/
|
|
function reorderLadder<T>(
|
|
list: readonly T[],
|
|
index: number,
|
|
delta: -1 | 1,
|
|
): T[] | null {
|
|
const targetIdx = index + delta;
|
|
if (targetIdx < 0 || targetIdx >= list.length) return null;
|
|
const next = [...list];
|
|
[next[index], next[targetIdx]] = [next[targetIdx], next[index]];
|
|
return next;
|
|
}
|
|
|
|
function moveSource(
|
|
metric: SourcePriorityMetricKey,
|
|
index: number,
|
|
delta: -1 | 1,
|
|
) {
|
|
if (!priority) return;
|
|
const current =
|
|
priority.metricPriority[metric] ?? DEFAULT_SOURCE_PRIORITY[metric];
|
|
const list = reorderLadder(current, index, delta);
|
|
if (!list) return;
|
|
const nextMetric = { ...priority.metricPriority, [metric]: list };
|
|
setDraft({
|
|
...priority,
|
|
...nextMetric,
|
|
metricPriority: nextMetric,
|
|
});
|
|
}
|
|
|
|
function moveDeviceType(
|
|
/** `null` for the global ladder, MeasurementType-enum string otherwise. */
|
|
bucket: string | null,
|
|
index: number,
|
|
delta: -1 | 1,
|
|
) {
|
|
if (!priority) return;
|
|
const key = bucket ?? "default";
|
|
const current =
|
|
priority.deviceTypePriority[key] ?? DEFAULT_DEVICE_TYPE_PRIORITY;
|
|
const list = reorderLadder(current, index, delta);
|
|
if (!list) return;
|
|
const nextDevicePriority: DeviceTypePriority = {
|
|
...priority.deviceTypePriority,
|
|
[key]: list,
|
|
};
|
|
setDraft({ ...priority, deviceTypePriority: nextDevicePriority });
|
|
}
|
|
|
|
function resetMetricToDefault(metric: SourcePriorityMetricKey) {
|
|
if (!priority) return;
|
|
const nextMetric: Required<MetricPriority> = {
|
|
...priority.metricPriority,
|
|
[metric]: [...DEFAULT_SOURCE_PRIORITY[metric]],
|
|
};
|
|
setDraft({
|
|
...priority,
|
|
...nextMetric,
|
|
metricPriority: nextMetric,
|
|
});
|
|
}
|
|
|
|
function resetDeviceTypeAxis() {
|
|
if (!priority) return;
|
|
setDraft({ ...priority, deviceTypePriority: {} });
|
|
}
|
|
|
|
const dirty = draft !== null && priority !== null;
|
|
|
|
// The per-metric expander shows every metric whose ladder has been
|
|
// overridden, plus a hint when none has. Counter lives next to the
|
|
// expander label so the section "asks" for attention proportional
|
|
// to its setting.
|
|
const overriddenMetrics = useMemo(() => {
|
|
if (!priority) return [] as SourcePriorityMetricKey[];
|
|
return SOURCE_PRIORITY_METRIC_KEYS.filter((metric) => {
|
|
const list = priority.metricPriority[metric];
|
|
const defaultList = DEFAULT_SOURCE_PRIORITY[metric];
|
|
if (!list || list.length !== defaultList.length) return true;
|
|
return list.some((s, i) => s !== defaultList[i]);
|
|
});
|
|
}, [priority]);
|
|
|
|
// Count distinct overrides the user has set on the device-type axis.
|
|
// `default` counts as one if present; every per-metric override
|
|
// (`WEIGHT`, `ACTIVITY_STEPS`, …) counts as one more. The number drives
|
|
// the expander label so the section is self-explanatory at a glance.
|
|
const deviceTypeOverrideCount = useMemo(() => {
|
|
if (!priority) return 0;
|
|
return Object.keys(priority.deviceTypePriority).length;
|
|
}, [priority]);
|
|
|
|
// v1.4.34 IW-D — `embedded` mode skips the section header because the
|
|
// parent surface (`<ThresholdsSection>`) already names the page.
|
|
const isStandalone = mode === "standalone";
|
|
const Wrapper = isStandalone ? "section" : "div";
|
|
const wrapperProps = isStandalone
|
|
? {
|
|
"aria-labelledby": "settings-section-sources-title",
|
|
className: "space-y-6",
|
|
}
|
|
: { className: "space-y-6" };
|
|
|
|
return (
|
|
<Wrapper {...wrapperProps}>
|
|
{isStandalone && (
|
|
<header className="space-y-1">
|
|
<h1
|
|
id="settings-section-sources-title"
|
|
className="text-2xl font-semibold tracking-tight"
|
|
>
|
|
{t("settings.sections.sources.title")}
|
|
</h1>
|
|
<p className="text-muted-foreground text-sm">
|
|
{t("settings.sections.sources.description")}
|
|
</p>
|
|
</header>
|
|
)}
|
|
|
|
<div className="bg-card border-border space-y-4 rounded-xl border p-6">
|
|
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-3">
|
|
<div className="flex items-center gap-2">
|
|
<Layers className="text-primary h-5 w-5" />
|
|
<h2 className="text-lg font-semibold">
|
|
{t("settings.sections.sources.cardTitle")}
|
|
</h2>
|
|
</div>
|
|
<Button
|
|
variant="ghost"
|
|
size="sm"
|
|
onClick={() => resetMutation.mutate()}
|
|
disabled={resetMutation.isPending || saveMutation.isPending}
|
|
className="self-end sm:self-auto"
|
|
>
|
|
<RotateCcw className="mr-2 h-3.5 w-3.5" />
|
|
{t("settings.sections.sources.resetDefaults")}
|
|
</Button>
|
|
</div>
|
|
|
|
<p className="text-muted-foreground text-xs">
|
|
{t("settings.sections.sources.help")}
|
|
</p>
|
|
|
|
{isLoading || !priority ? (
|
|
<SourcesSkeletonList />
|
|
) : (
|
|
<div className="space-y-3">
|
|
{SOURCE_PRIORITY_METRIC_KEYS.map((metric) => {
|
|
const list =
|
|
priority.metricPriority[metric] ??
|
|
DEFAULT_SOURCE_PRIORITY[metric];
|
|
return (
|
|
<div
|
|
key={metric}
|
|
className="border-border bg-background/30 space-y-2 rounded-md border p-3"
|
|
>
|
|
<div className="flex items-center justify-between">
|
|
<span className="text-sm font-medium">
|
|
{t(METRIC_LABEL_KEYS[metric])}
|
|
</span>
|
|
</div>
|
|
<ul className="space-y-1">
|
|
{list.map((source, index) => (
|
|
<li
|
|
key={`${metric}-${source}-${index}`}
|
|
className="border-border bg-card flex items-center gap-2 rounded-md border px-2 py-1.5"
|
|
>
|
|
<span className="text-muted-foreground w-5 text-xs font-medium tabular-nums">
|
|
{index + 1}.
|
|
</span>
|
|
<span className="flex-1 text-sm">
|
|
{t(SOURCE_LABEL_KEYS[source] ?? source)}
|
|
</span>
|
|
{/* v1.4.27 R3d MB2 — stack up/down vertically on
|
|
narrow viewports so each button keeps the
|
|
44 px floor without crowding the row. From
|
|
`sm:` up the two buttons sit side-by-side
|
|
again to preserve the desktop layout. */}
|
|
<div className="flex flex-col gap-1 sm:flex-row sm:gap-2">
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="icon"
|
|
className="h-11 w-11"
|
|
onClick={() => moveSource(metric, index, -1)}
|
|
disabled={index === 0 || saveMutation.isPending}
|
|
aria-label={t("settings.sections.sources.moveUp")}
|
|
>
|
|
<ArrowUp className="h-4 w-4" />
|
|
</Button>
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="icon"
|
|
className="h-11 w-11"
|
|
onClick={() => moveSource(metric, index, 1)}
|
|
disabled={
|
|
index === list.length - 1 || saveMutation.isPending
|
|
}
|
|
aria-label={t("settings.sections.sources.moveDown")}
|
|
>
|
|
<ArrowDown className="h-4 w-4" />
|
|
</Button>
|
|
</div>
|
|
</li>
|
|
))}
|
|
</ul>
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
)}
|
|
|
|
{/* ── v1.4.25 W8c — per-metric override expander ──
|
|
Collapsed by default. The global ladder above already
|
|
covers every metric; this section lets a power user reset
|
|
a single metric back to the constant default in one click. */}
|
|
{priority && (
|
|
<div className="border-border space-y-2 border-t pt-4">
|
|
<button
|
|
type="button"
|
|
onClick={() => setShowPerMetric((prev) => !prev)}
|
|
aria-expanded={showPerMetric}
|
|
aria-controls="sources-per-metric-panel"
|
|
className="text-foreground hover:text-primary flex items-center gap-2 text-sm font-medium transition-colors"
|
|
>
|
|
<ChevronDown
|
|
className={`h-4 w-4 transition-transform ${
|
|
showPerMetric ? "rotate-180" : ""
|
|
}`}
|
|
/>
|
|
{t("settings.sections.sources.perMetricToggle", {
|
|
count: overriddenMetrics.length,
|
|
})}
|
|
</button>
|
|
{showPerMetric && (
|
|
<div
|
|
id="sources-per-metric-panel"
|
|
role="region"
|
|
className="bg-background/30 border-border space-y-3 rounded-md border p-3"
|
|
>
|
|
<p className="text-muted-foreground text-xs">
|
|
{t("settings.sections.sources.perMetricHelp")}
|
|
</p>
|
|
{overriddenMetrics.length === 0 ? (
|
|
<p className="text-muted-foreground text-xs italic">
|
|
{t("settings.sections.sources.perMetricEmpty")}
|
|
</p>
|
|
) : (
|
|
<ul className="space-y-2">
|
|
{overriddenMetrics.map((metric) => (
|
|
<li
|
|
key={metric}
|
|
className="border-border bg-card flex items-center justify-between gap-3 rounded-md border px-3 py-2"
|
|
>
|
|
<span className="text-sm">
|
|
{t(METRIC_LABEL_KEYS[metric])}
|
|
</span>
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="sm"
|
|
onClick={() => resetMetricToDefault(metric)}
|
|
disabled={saveMutation.isPending}
|
|
>
|
|
{t("settings.sections.sources.resetMetric")}
|
|
</Button>
|
|
</li>
|
|
))}
|
|
</ul>
|
|
)}
|
|
</div>
|
|
)}
|
|
</div>
|
|
)}
|
|
|
|
{/* ── v1.4.25 W8c — device-type override expander ──
|
|
One global ladder ("watch beats phone beats scale"). When
|
|
multiple device-types stream the same source's metric
|
|
(Apple Watch + iPhone → APPLE_HEALTH steps), the higher-
|
|
ranked device-type wins. Collapsed by default. */}
|
|
{priority && (
|
|
<div className="border-border space-y-2 border-t pt-4">
|
|
<button
|
|
type="button"
|
|
onClick={() => setShowDeviceType((prev) => !prev)}
|
|
aria-expanded={showDeviceType}
|
|
aria-controls="sources-device-type-panel"
|
|
className="text-foreground hover:text-primary flex items-center gap-2 text-sm font-medium transition-colors"
|
|
>
|
|
<ChevronDown
|
|
className={`h-4 w-4 transition-transform ${
|
|
showDeviceType ? "rotate-180" : ""
|
|
}`}
|
|
/>
|
|
{t("settings.sections.sources.deviceTypeToggle", {
|
|
count: deviceTypeOverrideCount,
|
|
})}
|
|
</button>
|
|
{showDeviceType && (
|
|
<div
|
|
id="sources-device-type-panel"
|
|
role="region"
|
|
className="bg-background/30 border-border space-y-3 rounded-md border p-3"
|
|
>
|
|
<p className="text-muted-foreground text-xs">
|
|
{t("settings.sections.sources.deviceTypeHelp")}
|
|
</p>
|
|
<div className="flex items-center justify-between">
|
|
<span className="text-sm font-medium">
|
|
{t("settings.sections.sources.deviceTypeDefault")}
|
|
</span>
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="sm"
|
|
onClick={resetDeviceTypeAxis}
|
|
disabled={saveMutation.isPending}
|
|
>
|
|
<RotateCcw className="mr-1 h-3 w-3" />
|
|
{t("settings.sections.sources.resetDeviceTypes")}
|
|
</Button>
|
|
</div>
|
|
<ul className="space-y-1">
|
|
{(
|
|
priority.deviceTypePriority.default ??
|
|
DEFAULT_DEVICE_TYPE_PRIORITY
|
|
).map((deviceType, index, list) => (
|
|
<li
|
|
key={`device-default-${deviceType}-${index}`}
|
|
className="border-border bg-card flex items-center gap-2 rounded-md border px-2 py-1.5"
|
|
>
|
|
<span className="text-muted-foreground w-5 text-xs font-medium tabular-nums">
|
|
{index + 1}.
|
|
</span>
|
|
<span className="flex-1 text-sm">
|
|
{t(DEVICE_TYPE_LABEL_KEYS[deviceType])}
|
|
</span>
|
|
{/* v1.4.27 R3d MB2 — same stacked-on-mobile shape
|
|
as the metric source rows above. */}
|
|
<div className="flex flex-col gap-1 sm:flex-row sm:gap-2">
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="icon"
|
|
className="h-11 w-11"
|
|
onClick={() =>
|
|
moveDeviceType(null, index, -1)
|
|
}
|
|
disabled={index === 0 || saveMutation.isPending}
|
|
aria-label={t("settings.sections.sources.moveUp")}
|
|
>
|
|
<ArrowUp className="h-4 w-4" />
|
|
</Button>
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="icon"
|
|
className="h-11 w-11"
|
|
onClick={() => moveDeviceType(null, index, 1)}
|
|
disabled={
|
|
index === list.length - 1 || saveMutation.isPending
|
|
}
|
|
aria-label={t("settings.sections.sources.moveDown")}
|
|
>
|
|
<ArrowDown className="h-4 w-4" />
|
|
</Button>
|
|
</div>
|
|
</li>
|
|
))}
|
|
</ul>
|
|
</div>
|
|
)}
|
|
</div>
|
|
)}
|
|
|
|
{dirty && priority && (
|
|
<div className="flex flex-col gap-2 sm:flex-row sm:justify-end">
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
onClick={() => setDraft(null)}
|
|
disabled={saveMutation.isPending}
|
|
>
|
|
{t("common.cancel")}
|
|
</Button>
|
|
<Button
|
|
type="button"
|
|
onClick={() => saveMutation.mutate(priority)}
|
|
disabled={saveMutation.isPending}
|
|
>
|
|
{saveMutation.isPending && (
|
|
<Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />
|
|
)}
|
|
{t("common.save")}
|
|
</Button>
|
|
</div>
|
|
)}
|
|
</div>
|
|
</Wrapper>
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Skeleton placeholder rendered while `/api/auth/me/source-priority`
|
|
* is in flight. Reserves one row per `SOURCE_PRIORITY_METRIC_KEYS`
|
|
* entry at roughly the loaded height so the page does not jump when
|
|
* the fetched ladder list swaps in. The pulsing animation honours
|
|
* `prefers-reduced-motion` via Tailwind's `motion-reduce:animate-none`.
|
|
*/
|
|
function SourcesSkeletonList() {
|
|
return (
|
|
<div
|
|
className="space-y-3"
|
|
data-testid="sources-skeleton"
|
|
aria-hidden="true"
|
|
>
|
|
{SOURCE_PRIORITY_METRIC_KEYS.map((metric) => (
|
|
<div
|
|
key={metric}
|
|
className="border-border bg-background/30 space-y-2 rounded-md border p-3"
|
|
>
|
|
<Skeleton className="h-4 w-40" />
|
|
<div className="space-y-1">
|
|
<Skeleton className="h-9 w-full rounded-md" />
|
|
<Skeleton className="h-9 w-full rounded-md" />
|
|
</div>
|
|
</div>
|
|
))}
|
|
</div>
|
|
);
|
|
}
|