Skip to content

a 13-week activity heatmap on the workouts screen - #222

Merged
abdulsaheel merged 6 commits into
OpenStrap:mainfrom
svssathvik7:feat/workouts-activity-heatmap
Aug 9, 2026
Merged

a 13-week activity heatmap on the workouts screen#222
abdulsaheel merged 6 commits into
OpenStrap:mainfrom
svssathvik7:feat/workouts-activity-heatmap

Conversation

@svssathvik7

@svssathvik7 svssathvik7 commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

What

A 13-week activity heatmap above the workouts feed, shaded by the calories burned in logged workouts.

The session feed is reverse-chronological, so it shows you what you did but never the shape of a quarter — where the gaps are, and whether the rhythm is holding. That's the question this answers.

Before / after

Before, the Workouts screen went straight from the range selector to the feed. Now:

Ember on Paper Ember on Char

iPhone 17 Pro, iOS 26. The workout data in these shots is synthetic — 54 seeded sessions, since a simulator has no band to pair with.

Tapping a day swaps the header to that day's readout; tapping again releases. An animated preview of the interaction and the four micro-animations is committed at docs/calorie-heatmap-preview.svg (open it in a browser — it re-themes to your system setting).

Why these choices

Independent of the range selector. The board stays a fixed 13-week reference while the feed below it filters. On the Today tab you still see the quarter's rhythm rather than only an empty state.

Shade scales to your own 90th-percentile day (floored at 250 kcal) rather than fixed thresholds, which would leave a beginner's grid permanently cold and an endurance athlete's permanently maxed. Using the percentile rather than the max stops one exceptional session flattening everything else. The (i) discloses this.

getSessions() with an explicit window, not getWorkouts(range: 'quarter'). That range tops out at 90 days; a Monday-aligned 13-week grid needs up to 97, so the oldest column would have been silently short of data. Unconfirmed auto-detections and live sessions are filtered out, so the grid agrees with the feed and with TrainingSummaryCard instead of shading a day the feed omits.

Future days render as nothing, not as empty wells — an empty well reads as a day you skipped.

The ramp's interpolation factors differ per palette. coralSoft sits close to coral on paper and far below it on char, so one shared set of factors produced a visibly lopsided ramp on dark — 2.48:1 between levels 0–1 against 1.29:1 between 3–4. Both palettes are now inside a 1.55 spread, pinned by test.

How I verified it

34 tests, written before the code:

  • Calendar layer — DST transitions (the grid steps via DateTime(y, m, d + i), not Duration(days: 1), which loses or repeats a day across a clock change), local-day bucketing, multi-session days, streak edges including the "ends yesterday" allowance.
  • Ramp — monotonic luminance and a minimum step between every adjacent pair, in both palettes, in the spirit of zone_contrast_test.dart.
  • Widget — tap-to-readout, rest-day copy, future-day suppression, narrow-phone layout, and a reduced-motion guard. That last one I mutation-tested: removing the !reduce gate makes it fail, so it isn't vacuous.

Full suite passes. One unrelated pre-existing flake in workout_reliability_test.dart (DeriveScheduler) fails only under parallel load and passes in isolation.

Known gaps

  • The card is hidden entirely until there's at least one logged workout in the window — an all-empty board says nothing.
  • Not verified against real band data; the onboarding/pairing path can't be exercised on a simulator.

Summary by CodeRabbit

  • New Features
    • Added a 13-week calorie heatmap to the workouts screen.
    • View daily calorie intensity, workout sessions, duration, monthly labels, and activity streaks.
    • Select days to see detailed workout readouts.
    • Heatmap adapts to screen size and app theme, highlights future days, and supports reduced-motion preferences.
    • Heatmap remains available independently of the selected workout date range.
    • Improved workout data handling to distinguish saved workouts from automatically detected activity.

The session feed is reverse-chronological, so it can show you what you did
but never the shape of a quarter: where the gaps are, and whether the rhythm
is holding. This adds a Monday-aligned day grid above the feed, shaded by the
calories burned in logged workouts.

Notes on the choices that aren't obvious:

- The board is deliberately independent of the Today/Week/Month/3M selector.
  It stays a fixed 13-week reference while the feed below it filters, so on
  the Today tab you still see the quarter instead of only an empty state.

- Shade is scaled to the user's own 90th-percentile day (floored at 250 kcal)
  rather than fixed thresholds, which would leave a beginner's grid
  permanently cold and an endurance athlete's permanently maxed. The
  percentile rather than the max keeps one exceptional session from
  flattening everything else.

- Data comes from getSessions() with an explicit window, not
  getWorkouts(range: 'quarter'): that tops out at 90 days and a Monday-aligned
  13-week grid needs up to 97, which would leave the oldest column silently
  short. Unconfirmed auto-detections and live sessions are filtered out so the
  grid agrees with the feed and the training summary.

- Days after today render as nothing rather than empty wells, because an empty
  well reads as a day you skipped.

- The ramp's interpolation factors differ per palette. coralSoft sits close to
  coral on paper and far below it on char, so one shared set of factors
  produced a lopsided ramp on dark (2.48:1 between levels 0-1 vs 1.29:1
  between 3-4). Both are now within a 1.55 spread, asserted by test.

Verification: 34 tests covering the calendar layer (DST transitions, local-day
bucketing, streak edges), the ramp (monotonic luminance and minimum step in
both palettes), and the widget. Run on an iPhone 17 Pro simulator in both
themes -- screenshots in the PR. Simulator data is synthetic.
@coderabbitai

coderabbitai Bot commented Aug 9, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@abdulsaheel, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 23 minutes

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 4091870d-3eb2-49ed-be27-56fb25459132

📥 Commits

Reviewing files that changed from the base of the PR and between 5ffa07f and ce501ea.

📒 Files selected for processing (3)
  • lib/ui/workouts/calorie_heatmap.dart
  • lib/ui/workouts/workouts_screen.dart
  • test/calorie_heatmap_test.dart
📝 Walkthrough

Walkthrough

Adds a 13-week calorie heatmap with local-day aggregation, intensity levels, streaks, responsive rendering, selection, animation controls, and workout-screen integration. Adds session filtering support, unit and widget tests, and generated-file ignore rules.

Changes

Workout calorie heatmap

Layer / File(s) Summary
Session filtering contract and implementation
lib/data/local_repository.dart, lib/data/local_repository_impl.dart, test/ai_briefing_test.dart, test/get_sessions_merge_test.dart
Adds includeDetected to getSessions. Disabled detection returns saved sessions without loading derived day bundles.
Heatmap data and calendar calculations
lib/ui/workouts/calorie_heatmap.dart, test/calorie_heatmap_test.dart
Adds HeatDay, session filtering, local-date aggregation, percentile-based intensity scaling, streak calculation, month labels, formatting helpers, and related tests.
Heatmap card and interaction behavior
lib/ui/workouts/calorie_heatmap.dart, test/calorie_heatmap_test.dart
Adds the responsive card, summary values, day selection, future-day handling, animated cells, reduced-motion behavior, legends, and widget tests.
Workout screen integration
lib/ui/workouts/workouts_screen.dart
Loads a 105-day saved-session window and displays the heatmap independently of the selected workout range. Heatmap loading failures do not replace existing data.

Generated preview exclusions

Layer / File(s) Summary
Generated file ignore rules
.gitignore
Ignores .codegraph/ and rendered GIF or MP4 documentation previews.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant WorkoutsScreen
  participant LocalRepository
  participant loggedForHeatmap
  participant buildHeatDays
  participant CalorieHeatmapCard

  WorkoutsScreen->>LocalRepository: getSessions(105-day window, includeDetected=false)
  LocalRepository-->>WorkoutsScreen: saved session records
  WorkoutsScreen->>loggedForHeatmap: session records
  loggedForHeatmap-->>WorkoutsScreen: logged sessions
  WorkoutsScreen->>buildHeatDays: logged sessions and today
  buildHeatDays-->>WorkoutsScreen: 13-week HeatDay list
  WorkoutsScreen->>CalorieHeatmapCard: days and today
  CalorieHeatmapCard-->>WorkoutsScreen: rendered heatmap and selection events
Loading

Possibly related PRs

  • OpenStrap/edge#189: Extends the workout session retrieval and display flows in local_repository.dart, local_repository_impl.dart, and workouts_screen.dart.
  • OpenStrap/edge#217: Establishes calorie data nullability and availability semantics used by the heatmap.
  • OpenStrap/edge#150: Modifies workout session handling and auto-detected session behavior in workouts_screen.dart.

Suggested labels: Review effort 4/5

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: adding a 13-week activity heatmap to the workouts screen.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@lib/ui/workouts/calorie_heatmap.dart`:
- Line 522: Update CalorieHeatmapCard’s grid construction and header to handle
lists whose length is not a multiple of seven: guard each days[col * 7 + row]
access so missing cells are skipped or rendered safely, and derive the displayed
week count from weeks instead of hardcoding “13 weeks.”
- Around line 643-648: Update the AnimatedBuilder around the cell builder so its
animation listenables include pulse only when isPeak is true; non-peak cells
must subscribe solely to reveal while preserving the existing pulse.value glow
behavior for the peak cell.
- Around line 654-657: Update the tappable cell built by GestureDetector and
_cellKey to wrap its subtree in a Semantics node with a descriptive day readout,
button role, and enabled tap action, and ensure the wrapper is closed at the
matching subtree end. Expand the cell’s effective hit target to at least 44
logical pixels while preserving the existing onTap behavior.

In `@lib/ui/workouts/workouts_screen.dart`:
- Around line 174-192: Update _load to accept a refreshHeat flag and skip the
getSessions heatmap fetch when it is false, retaining the existing _heat value.
In the SegmentedControl onChanged handler, call _load(refreshHeat: false); keep
normal loads refreshing heatmap data.
- Around line 308-314: Store the anchor day captured during _load alongside
_heat, then pass that stored value to CalorieHeatmapCard instead of calling
DateTime.now() during build. Ensure the heatmap data, today marker, future-cell
handling, and currentStreak all use the same captured day.

In `@test/calorie_heatmap_test.dart`:
- Around line 504-513: Update the test setup around CalorieHeatmapCard to derive
the reduced-motion MediaQueryData from the ambient MediaQuery rather than
replacing all inherited fields with a bare const value. Preserve the ambient
size, textScaler, padding, platformBrightness, and other fields while overriding
only disableAnimations to true.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 1a33f38d-d703-448c-b4d4-fc91471cff44

📥 Commits

Reviewing files that changed from the base of the PR and between 1f8a685 and ea53592.

⛔ Files ignored due to path filters (3)
  • docs/calorie-heatmap-ios-dark.png is excluded by !**/*.png
  • docs/calorie-heatmap-ios-light.png is excluded by !**/*.png
  • docs/calorie-heatmap-preview.svg is excluded by !**/*.svg
📒 Files selected for processing (4)
  • .gitignore
  • lib/ui/workouts/calorie_heatmap.dart
  • lib/ui/workouts/workouts_screen.dart
  • test/calorie_heatmap_test.dart

Comment thread lib/ui/workouts/calorie_heatmap.dart
Comment thread lib/ui/workouts/calorie_heatmap.dart
Comment on lines +654 to +657
child: GestureDetector(
key: ValueKey(_cellKey(d.date)),
behavior: HitTestBehavior.opaque,
onTap: () => onTap(d),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Add a semantics node for each tappable cell.

The cell exposes no label and no button role, so a screen reader announces nothing and the day readout is unreachable without sight. The tap target is also 9..26 logical pixels, well below the 44/48 minimum.

♿ Proposed fix
-            child: GestureDetector(
-              key: ValueKey(_cellKey(d.date)),
-              behavior: HitTestBehavior.opaque,
-              onTap: () => onTap(d),
-              child: AnimatedScale(
+            child: Semantics(
+              button: true,
+              selected: isSelected,
+              label: '${_readoutDate(d.date)}, '
+                  '${d.kcal > 0 ? '${d.kcal} kcal' : 'no workout'}',
+              child: GestureDetector(
+                key: ValueKey(_cellKey(d.date)),
+                behavior: HitTestBehavior.opaque,
+                onTap: () => onTap(d),
+                child: AnimatedScale(

Close the extra Semantics at the matching end of the subtree.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/ui/workouts/calorie_heatmap.dart` around lines 654 - 657, Update the
tappable cell built by GestureDetector and _cellKey to wrap its subtree in a
Semantics node with a descriptive day readout, button role, and enabled tap
action, and ensure the wrapper is closed at the matching subtree end. Expand the
cell’s effective hit target to at least 44 logical pixels while preserving the
existing onTap behavior.

Comment thread lib/ui/workouts/workouts_screen.dart
Comment thread lib/ui/workouts/workouts_screen.dart Outdated
Comment thread test/calorie_heatmap_test.dart
The workouts feed's filter empty-state landed next to where the board
inserts, so the two hunks collide. Both are kept: the board sits above the
feed, and the feed still explains an empty list caused by the filter rather
than by having trained nothing.
The board filtered out anything with source 'auto', but that field records
where a workout came from, not whether it is still a proposal — it stays
'auto' after you confirm a suggestion. So a workout sitting in the feed with
an auto tag, counted by the training summary, painted as a rest day on the
grid: the exact disagreement the filter exists to prevent, pointing the other
way. Someone whose training is mostly detected-then-confirmed got a mostly
empty board, or none at all, since the card stays hidden until a day has
calories on it. Status alone is the test — only an unconfirmed bout is ever
'detected'. The old case set source and status together on one row, so it
passed either way and never pinned the thing it was named for.

The board's fetch also pulled every recent day's bundle. getSessions builds
its detected half by decoding each day's payload — hr_curve, hypnogram, HRV,
tens of KB a day — and the grid threw all of it away a line later, on every
load and every pull-to-refresh. It asks for saved sessions only now.

Cells carry a label too. Colour is the entire content of a heatmap, so
without one the board was silent to a screen reader.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
lib/ui/workouts/workouts_screen.dart (1)

105-112: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Guard the screen context after closing the sheet.

After Line 106 pops the sheet, check context.mounted before Line 107 uses the screen context to push the interval timer. The screen can be disposed during navigation.

Proposed fix
         onTap: () {
           Navigator.pop(ctx);
+          if (!context.mounted) return;
           Navigator.of(context).push(

As per coding guidelines: "After await or navigation, guard context and UI operations with mounted checks; do not use context or Provider lookups after unmount or in dispose."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@lib/ui/workouts/workouts_screen.dart` around lines 105 - 112, After
Navigator.pop(ctx) in the onTap callback, check context.mounted before calling
Navigator.of(context).push for IntervalTimerScreen. Keep the existing
themedRoute configuration and avoid using the screen context when it is no
longer mounted.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@lib/ui/workouts/workouts_screen.dart`:
- Around line 105-112: After Navigator.pop(ctx) in the onTap callback, check
context.mounted before calling Navigator.of(context).push for
IntervalTimerScreen. Keep the existing themedRoute configuration and avoid using
the screen context when it is no longer mounted.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 055f8124-baf9-4574-8aa0-5957f5050c52

📥 Commits

Reviewing files that changed from the base of the PR and between ea53592 and 3888f81.

📒 Files selected for processing (7)
  • lib/data/local_repository.dart
  • lib/data/local_repository_impl.dart
  • lib/ui/workouts/calorie_heatmap.dart
  • lib/ui/workouts/workouts_screen.dart
  • test/ai_briefing_test.dart
  • test/calorie_heatmap_test.dart
  • test/get_sessions_merge_test.dart

The peak day's pulse repeats for as long as the card is mounted, and every
one of the 91 cells had merged it into its AnimatedBuilder — so the entire
grid rebuilt every frame, indefinitely, reallocating an Opacity, Transform,
AnimatedScale, Container and BoxDecoration each time, to animate the single
cell that actually reads the value. Only the peak subscribes now; the reveal
stops notifying once it settles, so the rest go quiet after the intro.

The grid also took its column count from a rounded-up week count, so a list
that wasn't whole weeks indexed past the end, and the header announced 13
weeks whatever it had been handed. Both come off the list it was given now.

Changing the range selector no longer refetches the board either. Its window
is fixed and independent of that control, so the read could not have changed
a cell.
@abdulsaheel

Copy link
Copy Markdown
Collaborator

Went through the review. Three of the five were real and are fixed in 5ffa07f.

The pulse subscription was the one that mattered. Every cell had the repeating
pulse merged into its AnimatedBuilder, so the whole board rebuilt every frame
for as long as the card was mounted, to breathe the one square that reads the
value. Only the peak subscribes now.

The part-week indexing and the hardcoded 13 weeks are both fixed, and pinned
by a test — days is a constructor argument, so neither could be reasoned away
by what buildHeatDays happens to emit. The range-selector refetch is gone too,
though the cost cited for it was already stale: the board stopped reading the
day bundles in the previous commit, so what was left was one indexed query.

The semantics finding was already implemented in the commit under review — the
cells have carried a label and a button role since 3888f81. The 9–26px tap
target is real and I've left it: it's the shape of a 13x7 board on a phone, and
the readout it opens is reachable from the feed.

Not touching the context.mounted guard in the breathing sheet. It's a fair
point but it's pre-existing code this branch never goes near, so it wants its
own change rather than riding along in a heatmap PR.

@abdulsaheel

Copy link
Copy Markdown
Collaborator

@CodeRabbit review

@coderabbitai

coderabbitai Bot commented Aug 9, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

The grid was built against the clock read inside the load, but the card was
handed a fresh one at build time. They agree until the next local midnight,
and a screen left open across it got a board describing yesterday under
today's clock: the new day still carried its future flag so no cell was drawn
for it, the today ring matched nothing, and the streak was counted against a
day the board did not contain. The anchor is stored beside the grid now and
the two only ever move together.

The reduced-motion test built its MediaQueryData from scratch, which resets
size to zero and drops text scale, padding and brightness. It reads from the
ambient one instead, so it keeps describing a real device.
Skipping the board's read on a range-selector tap traded a correctness
property for a query that was already cheap. The window doesn't depend on the
selector but the table does, and the tap is one of the few things that
re-reads at all: confirming a suggestion from the pushed "did you work out?"
screen never reloads the workouts screen, so the next tap refreshed the feed
and left the board still calling that day a rest day. The expensive part of
the read was the day-bundle decode, and that had already gone.

The derived week count also read "1 weeks" for any span under a fortnight,
which is the derivation announcing itself in the one place it was added to
help.
@abdulsaheel

Copy link
Copy Markdown
Collaborator

Two more from the earlier review that I'd missed on a first pass, plus one I
caused myself.

The board was built against the clock read inside the load but handed a fresh
one at build time. Past local midnight those disagree, and the new day still
carried its future flag: no cell drawn for it, the today ring on nothing, the
streak counted against a day the board didn't contain. The anchor is stored
beside the grid now and they only move together.

Then the one I introduced. Skipping the board's read on a range tap was wrong,
and the reasoning in that commit message was wrong with it — the window doesn't
depend on the selector, but the table does. Confirming a suggestion from the
pushed "did you work out?" screen never reloads this screen, so the next range
tap refreshed the feed and left the board still calling that day a rest day:
the same feed-versus-board split this branch started out fixing, arriving from
the caching side. It reads every load again. What that saves was never the
expensive part — the day-bundle decode was, and that had already gone.

Deriving the week count turned out to print "1 weeks" for any span under a
fortnight. Pluralised, with the singular pinned.

Leaving the ragged day-label gutter alone. It only misaligns below seven days,
which no caller produces and the guard exists purely so a hand-built list can't
crash. Also leaving the tap-target size — that's the shape of a 13x7 board on a
phone, and everything it opens is reachable from the feed.

@abdulsaheel
abdulsaheel merged commit 51b1ebc into OpenStrap:main Aug 9, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants