From bf9c3ce32097d2fc164fa3b9f28b087f779876d3 Mon Sep 17 00:00:00 2001 From: rob Date: Wed, 11 Nov 2026 17:54:19 +0000 Subject: [PATCH] Complete TASK-008 history and progress --- docs/CURRENT_STATE.md | 8 ++ docs/DECISIONS.md | 11 ++ docs/HANDOFF.md | 41 ++++--- docs/PROJECT_OVERVIEW.md | 2 +- docs/SPEC.md | 11 ++ docs/TASK-008_UI.md | 25 +++++ docs/TASKS.md | 17 ++- src/App.jsx | 5 +- src/HistoryAsync.test.jsx | 33 ++++++ src/HistoryView.jsx | 215 +++++++++++++++++++++++++++++++++++++ src/HistoryView.test.jsx | 145 +++++++++++++++++++++++++ src/historyModel.js | 126 ++++++++++++++++++++++ src/historyModel.test.js | 129 ++++++++++++++++++++++ src/historyStorage.js | 35 ++++++ src/historyStorage.test.js | 49 +++++++++ src/styles.css | 43 ++++++++ 16 files changed, 878 insertions(+), 17 deletions(-) create mode 100644 docs/TASK-008_UI.md create mode 100644 src/HistoryAsync.test.jsx create mode 100644 src/HistoryView.jsx create mode 100644 src/HistoryView.test.jsx create mode 100644 src/historyModel.js create mode 100644 src/historyModel.test.js create mode 100644 src/historyStorage.js create mode 100644 src/historyStorage.test.js diff --git a/docs/CURRENT_STATE.md b/docs/CURRENT_STATE.md index e532b4c..f639089 100644 --- a/docs/CURRENT_STATE.md +++ b/docs/CURRENT_STATE.md @@ -9,6 +9,14 @@ Code/configuration take precedence over this summary. +## Active TASK-008 — 2026-11-11 + +Captain engaged Frontend UI Design → Webapp Feature with the lock-on defaults. Source `.task-worktrees/task-008`, branch `task/008-history-progress`, base codex `e3bd365`. Home app stays on codex with context only; all History application/spec/design/tests remain in the isolated source. Status: Complete following Captain’s explicit “task complete” acceptance on 2026-11-11; Captain subsequently authorized local commit/merge; no push/deploy. + +Candidate replaces History's placeholder with read-only newest-first saved dates, date/period filters, row actuals/notes/daily weight, partial/draft/observation labels, original-record disclosures and compatible exercise/body-weight charts/values/comparisons/recorded highs. Saved metadata and completed rows govern math; known zero remains distinct from unavailable values. EMOM totals supersede coexisting minute/set records even when drafts; legacy period/completion/definition are not inferred and duplicate representations are excluded. Legacy load-field modes and changed actual dumbbell counts stay separate in comparisons. Continuous/cumulative hangs remain independent; body weight/timed work contribute no rep-load volume. + +All history reads use a consistent validated readonly transaction; no stored data/schema/backup/dependency/programme change. UI uses the existing dark theme; row details mount on date expansion and chart date/scale text remains regular-size HTML. Design/math contract: candidate TASK-008_UI.md, SPEC TASK-008 section and ADR-023. Final full suite passes 234/234 tests across 22 files with one worker; final lint/build, source preflight, context/whitespace and base diff review pass. Full evidence is in HANDOFF. No independent browser/visual/keyboard pass, runner/server/browser/manual snapshot or session cleanup claimed. Captain acceptance and local integration authorization are recorded. + ## Accepted TASK-005 integration — 2026-11-11 Captain engaged Frontend UI Design → Webapp Feature for the briefed remaining TASK-005 scope. Captain explicitly accepted TASK-005 with “task complete” on 2026-11-11. Status: Complete. Captain subsequently explicitly authorized commit/local codex merge. Implementation is preserved in persistent `.task-worktrees/task-005`, branch `task/005-notes-bodyweight`, base `be0ff2b`. TASK-005 is integrated into local codex under Captain’s subsequent “commit and merge” instruction; verify resulting commit/refs with Git. No push/deploy authorized. diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 56dfd1d..ce655c2 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -381,3 +381,14 @@ Retain the current left/right storage fields and historical semantics. Explicit - Status: Accepted through Captain's engagement of the briefed TASK-005 scope, 2026-11-11. Session notes belong to date/period, exercise notes to date/period/exercise, and body weight to the date shared across both periods. These are optional actual observations, stored separately from performance and from permanent exercise-library guidance. Saving them does not complete sets, copy prescription targets or change load/volume. Use explicit Save; Clear edits the draft and Save confirms removal. Notes are plain text (4000-character limit); body weight is finite positive decimal kilograms. Preserve prior records via additive storage and old backup readers. Technical schema/version and exact UI are specified in TASK-005_UI.md. + + +## ADR-023: Read-only history and compatible recorded progress + +- Status: Accepted through Captain engagement of the TASK-008 briefing defaults, 2026-11-11. + +History is read-only, newest first, with date/period filters, saved row details and local accessible charts/values. Counts refer to recorded completed/draft rows, not completion of the whole prescribed workout. Notes-only/weight-only dates are observations. Calculations use saved actuals/metadata, with explicit zero, missing/partial/overflow distinctions; no normalized performance, timers, coaching, calories or streaks. + +Prefer the current EMOM total when it coexists with original minute/set data, including when current data is a draft. Preserve other representations separately and exclude them from totals. Legacy date/exercise records have no saved period/definition/completion: show original saved values without inferring those fields; if detailed data exists for the same date/exercise, keep the legacy record separately excluded to avoid double-counting. Otherwise its original total load/reps remain separately usable as earlier recorded volume, with unknown weight-only volume clearly labelled. + +Compare detailed series only within exercise, period, format, saved measurement/equipment/fixed-count signature and actual dumbbell-count modes. Legacy series are separate by original format and recorded load-field modes. Row-based volume excludes body weight and timed-only work. Highest recorded metrics are within a compatible series, with partial labels; body weight has no preferred/best direction. Unknown/invalid storage fails visibly rather than silently manufacturing data. Storage schema and backup contracts remain unchanged. diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index fb365f4..587321b 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -3,24 +3,41 @@ > Replaceable snapshot; repository code and maintained context take precedence. - Updated: 2026-11-11. -- TASK-005: Complete. Captain explicitly accepted (“task complete”), then separately authorized “commit and merge”. -- Source: `.task-worktrees/task-005`, branch `task/005-notes-bodyweight`, base codex `be0ff2b`; target local `codex`. Verify final commit/refs with Git. -- All available completed task implementation is integrated after this merge. No push/deployment or worktree/session cleanup authorized. +- Active: TASK-008 History and progress. Captain engaged Frontend UI Design → Webapp Feature with the lock-on defaults; Complete following Captain’s explicit “task complete” acceptance on 2026-11-11. Captain subsequently authorized commit and local codex merge. +- Source: `/home/rob/projects/exercise-tracker/.task-worktrees/task-008`, branch `task/008-history-progress`, base codex `e3bd365`. +- Home remains codex `e3bd365` with active task/current-state/handoff context only. Application, design/spec/decision and tests stay in the 008 source. Other implementation worktrees/stashes/missing registrations are preserved. No task commit/merge/push/deploy authorized. -## Delivered and validated +## Delivered -Optional date/period session notes, dated exercise observations and one daily positive decimal kg body-weight value shared across periods. Compact disclosures/forms retain the dark UI and existing workout hierarchy. Independent explicit Save; Clear edits only the draft, Save confirms removal. Notes are plain text with a 4000-character limit. Read failures prevent overwriting and offer retry; failed saves retain drafts; keyed forms isolate late reads/save feedback. Navigation follows existing discard-of-unsaved-draft behavior. Notes/body weight never complete or modify performance or previous-session suggestions. +Real History replaces its placeholder: From/To date and recorded-period filters, Refresh/Retry, Clear filters, newest-first date disclosures, read-only saved actuals/notes/daily body weight, compatible exercise series/metric selection, latest vs previous values/change, recorded highs, and separate body-weight trend. SVG plots have readable HTML date/scale labels and accessible exact-value lists; missing points break lines and one point does not invent a comparison. Date row details mount only when opened. Existing header/clock/navigation and dark styling remain. -IndexedDB v4 adds workoutDetails and leaves original goal/legacy/detailed records intact. JSON v4 exports and v1–v4 imports validate and transact atomically. Old-format replacement preserves new observations absent from old envelopes; v4 replacement covers all four stores. Older app builds cannot open v4 DBs/read v4 backups; no downgrade claimed. No dependencies, programme, timers, history/routine editor/backup interface or reviewed content/illustrations added. +Counts describe recorded completed/draft rows, never completion of a whole prescribed workout. Notes-only/weight-only observations are labelled. Calculations use saved definitions, actual loads/counts and completed rows; body weight/timed work have no rep-load volume. Display the formula, raw per-row/known session totals, zero/partial/missing/overflow distinctions, longest continuous and cumulative hangs separately. Alternate representations are not double-counted: emom-total takes precedence even as a draft; originals remain in excluded disclosures. Legacy data has no period/definition/completion snapshot, so original totals are not reinterpreted. If detailed data exists on the same date/exercise, legacy stays at date level excluded; otherwise it is a separate Earlier records group. Legacy and changed measurement/equipment/format/count/load-field modes do not share detailed comparison series. -206/206 tests across 18 files pass with `npm test -- --maxWorkers=1`. Lint/final build, source preflight, context validation (0 warnings), whitespace and diff review against `be0ff2b` pass. Coverage includes upgrades from v1/v2/v3, blocked upgrades, original record preservation, backup round trips/old imports/rollback, input validation, save/clear/reload, empty sessions, date/period/exercise isolation, failures and async read/save races. No independent agent browser/console/network/desktop/mobile/keyboard review claimed; Captain acceptance is recorded. Application implementation unchanged during acceptance/integration preparation, so checks are not rerun solely for completion documentation. +One consistent readonly transaction validates performanceEntries/strengthEntries/workoutDetails. Invalid/unsupported data fails visibly without modification or silent empty success. No writes, schema/backup/dependency/programme changes, editing/deleting history, timers, coaching, calories or streaks. Date filters apply to daily weight; period filters do not split it. -Design: docs/TASK-005_UI.md. Scope decision: ADR-022. Storage/backup contract: TASK-005 section in docs/SPEC.md. PROJECT_OVERVIEW describes the integrated v4 architecture. +Design and math brief: docs/TASK-008_UI.md. Contract: TASK-008 section in docs/SPEC.md. Durable decision: ADR-023. Candidate overview describes History; home overview stays the integrated baseline until authorized merge. -## Git state and retained evidence +## Validation -All completed available implementation is integrated after TASK-005 merge; no unique uncommitted application work remains. Home and persistent task worktrees should be clean; verify before new work. Four named safety stashes preserve duplicate/older context/tooling from prior integrations, including home's pre-merge TASK-005 context. Applying them wholesale would restore stale documentation; retain pending Captain cleanup authority. Missing original `/tmp` registrations remain prunable evidence, not unmerged candidate code. No branches/worktrees/stashes/snapshots deleted and no Captain sessions stopped. +- Final full suite: 234/234 tests across 22 files pass with `npm test -- --maxWorkers=1`, including the final rendering and legacy weight-only UI cases. Earlier focused rendering/async checks also passed. +- Final lint/build and no-launch source preflight `--check 008` pass. Context validation: 0 warnings; whitespace and diff review against e3bd365 pass. +- New calculation/storage/UI/async coverage includes mixed/saved/asymmetric-side loads, bars, zeros, drafts/missing loads, timed work, continuous/cumulative hangs, duplicate representations, legacy unknowns, overflow, compatibility separation/order, notes/weight-only observations, readonly transaction/data preservation, invalid/unavailable storage, empty/loading/filter/detail/chart/retry/refresh and late-response cancellation. Existing tests are retained. +- No independent browser/console/network/desktop/mobile/keyboard review claimed. Captain explicitly accepted the candidate; TASK-008 is Complete. No independent agent visual review is claimed. No agent runner/browser/server/manual snapshot launch or session cleanup. -## Testtask +## Captain manual test -Captain alone runs/stops real sessions. From home, `./scripts/testtask.sh 005` still selects the persistent source and Node automatically; `--check 005` validates without launch. Snapshots remain separate under source `.test-worktrees` and must not be edited. Completion documentation may require the supported runner to refresh on Captain's next launch. No runner/browser/server/snapshot launched for integration. +From project home: + +```bash +./scripts/testtask.sh 008 +``` + +Expected source: `/home/rob/projects/exercise-tracker/.task-worktrees/task-008`. The isolated fresh profile initially has no history. Use Today/Week to save actual performance on two dates for the same exercise/period, including zero external weight and a partial later entry. Enter session/exercise notes and daily weight on suitable dates. In History: + +1. Confirm newest-first dates, completed/draft/notes-only/weight-only labels; expand dates and check exact reps, component loads/counts, durations and notes. Browsing must not save or change entries. +2. Filter date range and Morning/Afternoon, check an invalid/reversed range and empty matches, Clear filters and Refresh. Daily weight is shared and follows date range rather than period. +3. Select a compatible exercise/metric; compare latest/prior values and recorded high with original actuals. Volume formula/raw totals must match completed actuals. Two saved sessions enable a comparison; one point remains explicitly one point. Open exact recorded values. +4. Save two afternoon hang attempts (e.g. 60 and 75 sec): longest is 75, cumulative is 135, not a continuous 135-sec achievement. Check daily weight has its own chart and is excluded from load volume. +5. At desktop/320px, check readable chart labels/scales/values, wrapping rows/notes/filter labels, no horizontal overflow, keyboard focus/order, date and progress selectors, disclosures and existing navigation/clock. + +Legacy/minute overlap, weight-only originals, failure/cancellation and arithmetic overflow have automated fixtures; do not claim manually seeded old data or fault injection. Captain alone launches/stops real testtask. Do not edit snapshots. TASK-008 is accepted/Complete and authorized for local commit/merge. diff --git a/docs/PROJECT_OVERVIEW.md b/docs/PROJECT_OVERVIEW.md index 1ecd820..efcf4a1 100644 --- a/docs/PROJECT_OVERVIEW.md +++ b/docs/PROJECT_OVERVIEW.md @@ -8,7 +8,7 @@ This is a newly initialized repository. The user calls the planned product "Work Workout Tracker is a personal local workout app with actual-date navigation, exclusive Morning/Afternoon views, a persistent local-time clock and no workout timers. Seed v8 contains 30 versioned exercise definitions with equipment/measurement metadata. Reusable logging shows only relevant reps, durations and equipment-specific loads, with one shared measurement input for per-side work, supports completed rows, partial drafts and explicit previous-session suggestions offered only when compatible earlier completed data exists, and records EMOM with one weight and one total-reps input. Earlier minute records remain separately accessible. Daily hangs have an editable continuous target, independent attempts, longest continuous and cumulative totals. Monday/Friday stretch routines have headings but no invented exercises. Dog walks remain excluded; their latest classification is bodyweight-only reference context. -Exercise definition, workout prescription and dated performance are independent. New performance retains definition/prescription snapshots, while original aggregate, rep-set and weight-only history stays readable separately. Optional dated session/exercise notes and one daily body-weight entry in kg use independent Save actions; body weight is shared across both periods. Exercise details expose available programme notes and placeholders; reviewed technique/muscle content and local illustrations remain future work. The application uses a single dark green theme with coordinated Bootstrap/native controls and compact numeric inputs. History/progress screens, routine editing, backup interface and offline reload remain separate tasks. SPEC defines behavior and WORKOUT_ROUTINE the authoritative initial programme. +Exercise definition, workout prescription and dated performance are independent. New performance retains definition/prescription snapshots, while original aggregate, rep-set and weight-only history stays readable separately. Optional dated session/exercise notes and one daily body-weight entry in kg use independent Save actions; body weight is shared across both periods. Exercise details expose available programme notes and placeholders; reviewed technique/muscle content and local illustrations remain future work. The application uses a single dark green theme with coordinated Bootstrap/native controls and compact numeric inputs. History provides read-only newest-first recorded sessions, date/period filters, original record disclosures, notes/body weight and compatible exercise/body-weight trends with exact recorded values. Routine editing, backup interface and offline reload remain separate tasks. SPEC defines behavior and WORKOUT_ROUTINE the authoritative initial programme. ## Technology and architecture diff --git a/docs/SPEC.md b/docs/SPEC.md index 32c3bbf..475f634 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -366,3 +366,14 @@ This current contract supersedes earlier database/backup version descriptions fo - IndexedDB v4 adds `workoutDetails`, preserving all prior stores/records. Keys: `date:period:session-note`, `date:period:exerciseId:exercise-note`, `date:body-weight`. Values have `schemaVersion: 1`, `kind`, `date`, applicable `period`/`exerciseId` and either `text` or `weightKg`. Validate identity, record fields, values and key consistency. - JSON exports use envelope v4 with `workoutDetails`; imports accept v1/v2/v3/v4. Older envelopes contain no observation store; even an explicit old-format replacement preserves existing observations rather than inferring their deletion. V4 replacement covers all four stores atomically. Validate all records before mutation; duplicate/non-replacing import failures roll back all stores. Older app builds cannot open a v4 database or read v4 backups; retain this app version for restoring new data. No downgrade/rewrite of historical records and no backup UI in this task. - UI composition and state/accessibility/responsive specification: `TASK-005_UI.md`. Existing programme notes remain distinct from personal observations. History charts remain TASK-008; backup interface remains TASK-009. + + +## TASK-008 history contract — 2026-11-11 + +History is now read-only, replacing its placeholder, with From/To date filters (initially all dates), saved-period filter, Refresh/Retry and Clear filters. Dates are newest first; row details mount on disclosure expansion. Show saved names/measurement/equipment and original actual values, completed/draft row counts, notes and daily weight. Counts never assert whole-programme session completion. Weight-only/notes-only dates do not become completed workouts. Body weight follows date range only because it is shared across periods. + +A consistent readonly transaction validates keys/records across performanceEntries, strengthEntries and workoutDetails; no writes/migrations or backup changes are added. Current emom-total wins over original minute/set representation for the same date/period/exercise even if it is a draft. Preserve original rows in a separate disclosure excluded from current totals. Legacy records have only date/exercise identity and original recorded totals: period, completion and saved definition are unknown. If any detailed record exists for that date/exercise, keep the legacy data in a separate date-level disclosure and do not count it. Otherwise group it under Earlier records (period not saved), retaining original rep/load calculation; weight-only legacy data has no inferred reps or volume. + +Detailed external-load volume sums completed actual reps × external kg from saved vest, dumbbell kg-each × saved count and bar totals. Reps-per-side include both saved side values, with originals shown. Timed/distance work and body weight contribute no rep-load volume; drafts are excluded. Show known completed-row totals with partial/missing-data qualifiers; arithmetic outside supported finite/safe-count ranges is unavailable, not zero. True zero remains valid. Original legacy externalKg is never reinterpreted through current definitions. Do not combine alternate representations. + +Progress groups exercise/period/format/saved measurement-equipment-fixed-count signature and actual dumbbell-count modes. Legacy groups stay separate by original format/load-field modes. Offer compatible previous/current values, change, recorded high and metric selection (reps, known volume, highest actual external load, duration/distance, longest/cumulative hang as appropriate). Partial records remain labelled; no adjustment for number of sets or estimate of missing performance. Hanging exercise IDs remain independent. Daily weight has a separate date-only trend with no preferred direction. Local SVG plots have normal-sized HTML date/scale labels and accessible exact recorded-value lists; missing values break lines and one point does not invent a comparison. No new dependencies, editing/deleting history, backup UI, recommendations, calories, streaks or time rates. UI/acceptance brief: TASK-008_UI.md; durable choices: ADR-023. diff --git a/docs/TASK-008_UI.md b/docs/TASK-008_UI.md new file mode 100644 index 0000000..68fb6b6 --- /dev/null +++ b/docs/TASK-008_UI.md @@ -0,0 +1,25 @@ +# TASK-008 UI and calculation brief + +2026-11-11. Extend the existing dark UI after Captain engaged Frontend UI Design → Webapp Feature with the lock-on defaults. Base e3bd365; source .task-worktrees/task-008, branch task/008-history-progress. + +## Composition and interaction + +History replaces its current placeholder. Retain header/clock/navigation. A history panel contains date From/To filters (initially all dates), period filter (all, Morning, Afternoon, earlier records whose period was not saved), Refresh and Clear filters. Invalid date range has associated error feedback. Below, newest-first recorded dates use semantic disclosures (row details mount only while a date is open, keeping long histories compact to render) showing read-only sessions, actual rows, notes and daily body weight. No edit/delete/automatic save actions. Empty store and no filter matches are distinct; loading hides stale data; errors offer retry. Reload on re-entering History or explicit Refresh, with cancellation after unmount/retry. Filters affect sessions and exercise progress; body weight follows date range only because it is date-level/shared across periods. + +Exercise progress uses a select for compatible series and a metric select: completed reps, completed-row volume, highest recorded external load, recorded duration/distance, longest continuous hang/cumulative hang as applicable. Show latest vs previous compatible recorded date with explicit values/difference, not coaching. Simple locally rendered SVG chart has labelled units/date range and an accompanying accessible recorded-values list with partial-state labels. Missing points break lines rather than implying zero. One record shows a dot and no fabricated comparison; no records show an explanation. Daily body weight has its own chart/values, one point per date. Exercise series show the highest recorded metric within that compatible group (detailed completed rows or separate original legacy saved totals, with partial records labelled); body weight has no “best” direction. Chart scales/dates use normal HTML text rather than tiny scaled SVG labels on mobile. No new chart dependency, network, 1RM/estimated performance, calories, streaks or time-based rates. + +Desktop filters wrap in a bounded row; disclosures and progress have intrinsic responsive widths. Below 576px filters stack, controls/actions keep 44px heights, row details/notes wrap, and charts scale within the container at 320px. Use semantic field labels, details/summary, headings, time, lists and focus outlines; selected options/partial/error meanings do not rely on color. Reuse Bootstrap Form/Button and existing tokens; do not redesign other screens. No independent browser validation claimed. + +## Data and math contract + +Read a consistent readonly transaction across performanceEntries, strengthEntries and workoutDetails. Validate stored keys/values; invalid data causes explicit error rather than silently manufacturing/skipping totals. No writes, schema upgrades beyond current v4, backups changes or new dependencies. + +Group detailed entries by date/period/exercise. If an emom-total exists, it is current even if it is a draft; original minute/set data remains separate, never summed. Earlier legacy date/exercise records have no period/definition snapshot/completion flag. If any detailed representation exists for that date/exercise, preserve the legacy record at date level and exclude it from totals (do not infer its period). Otherwise show a separate Earlier records session: original externalKg × saved reps/total reps, explicitly labelled legacy saved rows with unknown completion; weight-only records have no inferred reps/volume. Do not reinterpret legacy load components/current seed definitions. Legacy series remain separate from detailed series. + +Detailed calculations use only saved definition, actual load and completed rows. Reps-per-side sums both saved side values; show side semantics and original values. External kg sums recorded vest, dumbbell kg-each × saved count, and bar totals; body weight is excluded. Volume = sum(completed reps × recorded external kg), never timed/distance-only work. Explicit zero is valid. Draft/unknown loads/reps and arithmetic overflow must remain distinguishable from a true zero; show known completed-row totals with missing-data/partial qualifiers. Duration-only work has no rep-load volume. Longest continuous and cumulative attempts are distinct; daily hangs and finger-hang exercise IDs never combine. Session completion labels describe recorded rows, not completion of the whole prescribed workout. Notes-only/weight-only dates are not completed workouts. + +Comparison groups use exercise ID, saved period/format, measurement/equipment signature and actual dumbbell-count modes. Changed measurement/equipment/count/legacy representation does not share a series. Partial sessions may show their known completed-row metrics but remain explicitly labelled; no normalized workload or invented missing actuals. Saved names/snapshots take precedence; legacy IDs are shown without inferring an old name from current routine data. + +## Required verification + +Pure calculation cases for mixed equipment, asymmetric sides, zeros, drafts, unknown loads, timed-only work, duplicate representations and overflow; trend compatibility and ordering; readonly IndexedDB snapshot/data preservation and failures; empty/loading/error/filter/detail/chart/notes/body-weight UI plus cancellation. Full tests with one worker, lint/build, context/whitespace/base-diff review and no-launch --check 008. Captain alone runs ./scripts/testtask.sh 008 for desktop/320px/keyboard and real save → history checks before Complete. diff --git a/docs/TASKS.md b/docs/TASKS.md index 92d1cc5..7e6a40f 100644 --- a/docs/TASKS.md +++ b/docs/TASKS.md @@ -4,7 +4,7 @@ This file holds accepted, scoped implementation work. It is not a speculative ba ## Proposed implementation sequence -Reconciled with `docs/SPEC.md` and `docs/WORKOUT_ROUTINE.md`. TASK-001–003, TASK-012–018 and TASK-020 are Complete. TASK-006 is Superseded; TASK-008 is Accepted; TASK-005 is Complete following Captain acceptance and explicit commit/local codex merge authorization. TASK-019 is Complete following Captain acceptance on 2026-11-11; its persistent reconstruction is integrated, while the original `/tmp` source remains missing. Remaining tasks are Proposed. Completed application work is integrated in local codex, including reconstructed TASK-018 compact inputs within TASK-016. Implement one task per isolated branch/worktree under `docs/WORKFLOW.md`. Preserve the authoritative programme and historical storage semantics. +Reconciled with `docs/SPEC.md` and `docs/WORKOUT_ROUTINE.md`. TASK-001–003, TASK-012–018 and TASK-020 are Complete. TASK-006 is Superseded; TASK-008 is Complete following Captain acceptance, with commit/integration pending separate authority; TASK-005 is Complete following Captain acceptance and explicit commit/local codex merge authorization. TASK-019 is Complete following Captain acceptance on 2026-11-11; its persistent reconstruction is integrated, while the original `/tmp` source remains missing. Remaining tasks are Proposed. Completed application work is integrated in local codex, including reconstructed TASK-018 compact inputs within TASK-016. Implement one task per isolated branch/worktree under `docs/WORKFLOW.md`. Preserve the authoritative programme and historical storage semantics. ### TASK-001: Application foundation and responsive shell @@ -87,7 +87,7 @@ Reconciled with `docs/SPEC.md` and `docs/WORKOUT_ROUTINE.md`. TASK-001–003, TA ### TASK-008: History and progress -- Status: Accepted +- Status: Complete — Captain explicitly stated “task complete” on 2026-11-11, satisfying the acceptance gate. Source `.task-worktrees/task-008`, branch `task/008-history-progress`, base codex `e3bd365`. Changes remain uncommitted/unmerged pending separate Git authority. - Objective: Browse actual dated performance and transparent basic trends without a time-based rate. - Scope: Completed/partial session history, prior vs current performance, reps and load trends, total external-load volume from completed regular sets and aggregate EMOM entries, with historical minute/legacy records preserved separately, longest continuous and cumulative hang separately, optional body-weight trend. - Acceptance criteria: External-load volume is the sum, across completed regular sets and aggregate EMOM entries; historical minute entries retain their own load calculations, of actual reps multiplied by recorded external kilograms moved (vest, dumbbell total based on count, and/or EZ-bar total; body weight excluded). Do not combine detailed and legacy representations for the same performance. Use the current aggregate when it coexists with older representations for one session; never sum both. Show the formula and raw totals; label partial workouts and incomplete load data. Timed-only work contributes no rep-load volume; routine edits leave history intact. Do not show volume per minute. @@ -96,6 +96,8 @@ Reconciled with `docs/SPEC.md` and `docs/WORKOUT_ROUTINE.md`. TASK-001–003, TA - Non-goals: Coaching, calorie estimates, streaks. - Dependencies or blockers: TASK-014 and TASK-005. The owner removed volume per minute on 2026-10-27 while keeping rep and weight recording. +- Engaged UI/calculation brief: docs/TASK-008_UI.md. Read-only newest-first recorded sessions, date/period filters, compatible series/metric comparison and accessible local charts/values; no invented whole-session completion or double-counted representations. + ### TASK-009: JSON backup and restoration - Status: Proposed @@ -385,3 +387,14 @@ Reconciled with `docs/SPEC.md` and `docs/WORKOUT_ROUTINE.md`. TASK-001–003, TA - TASK-005 completion evidence (2026-11-11): Captain explicitly confirmed “task complete”, accepting the delivered notes/body-weight scope. Agent validation remains 206/206 tests across 18 files with one worker, lint/build, source preflight, context/whitespace and base diff review. No independent agent visual pass claimed. No application changes after acceptance. Commit/merge/push/deploy and session/worktree cleanup remain unauthorized; accepted implementation is preserved in its persistent source. - TASK-005 integration authorization (2026-11-11): After explicit acceptance, Captain instructed “commit and merge”. Commit the validated candidate on task/005-notes-bodyweight and fast-forward local codex from be0ff2b. No application changes since acceptance; prior 206-test/lint/build evidence remains valid. Preserve duplicate home context in a safety stash before merging. No push/deploy, source/snapshot/worktree/stash removal or testing-session cleanup authorized. + + +#### TASK-008 implementation — 2026-11-11 + +- New read-only History screen from base codex e3bd365 in persistent .task-worktrees/task-008 on task/008-history-progress. Date/period filters, newest-first expandable recorded dates, saved actual/row/note/weight details and compatible local progress charts with values, comparisons and recorded highs. Original/legacy representations remain separately visible and excluded from their replacements; notes-only/weight-only and draft/partial states are explicit. No whole-workout completion inference. +- Reuses existing schema/metadata without writes, migration, backup/dependency/programme changes. Separate calculation/normalization model and readonly consistent storage snapshot validate records and avoid missing-value-as-zero or overflow. Compatibility includes actual dumbbell count modes and legacy original load-field modes. Saved snapshot names/actuals remain independent of current seed changes. +- Design, state/accessibility/responsive/algorithm contract: docs/TASK-008_UI.md, SPEC TASK-008 section and ADR-023. Test evidence and Captain checklist are in HANDOFF. Captain alone runs ./scripts/testtask.sh 008; acceptance is recorded. Captain authorized local commit/merge; no push/deploy or runner/browser/server/manual snapshot launch. + +- TASK-008 final validation (2026-11-11): 234/234 tests across 22 files pass with `npm test -- --maxWorkers=1` after final rendering/legacy-label changes. Final lint/build, no-launch source preflight, context validation (0 warnings), whitespace and diff review against e3bd365 pass. Four new test files cover model/storage/UI/async history cases. No schema/backup/dependency or stored-data changes. Captain accepted the implementation and authorized local commit/merge; no independent agent browser pass claimed. + +- TASK-008 completion evidence (2026-11-11): Captain explicitly confirmed “task complete”, accepting the delivered History/progress candidate. Agent validation remains 234/234 tests across 22 files with one worker, lint/build, source preflight, context/whitespace and base diff review. No independent agent visual review claimed. Application code is unchanged after acceptance. Commit/merge/push/deploy and session/worktree cleanup remain unauthorized; accepted implementation is preserved in its persistent source. diff --git a/src/App.jsx b/src/App.jsx index 40b7169..4d55b82 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -5,13 +5,14 @@ import { addCalendarDays, localCalendarDate, localDateKey, prescriptionLabel, re import HangGoalEditor from './HangGoalEditor.jsx' import PerformanceEditor from './PerformanceEditor.jsx' import WorkoutDetailEditor from './WorkoutDetailEditor.jsx' +import HistoryView from './HistoryView.jsx' import { equipmentLabels } from './performanceModel.js' import { readDailyHangGoal, writeDailyHangGoal } from './hangGoalStorage.js' const sections = [ { id: 'today', label: 'Today', title: "Today's plan" }, { id: 'week', label: 'Week', title: 'Your week' }, - { id: 'history', label: 'History', title: 'Your training history', description: 'Completed workouts will appear here once tracking is available.' }, + { id: 'history', label: 'History', title: 'Your training history', description: 'Browse saved sessions, notes and progress.' }, { id: 'plan', label: 'Plan', title: 'Your training plan', description: 'Routine editing will become available in a later task.' }, { id: 'settings', label: 'Settings', title: 'Your data and preferences', description: 'Local backup and app settings will become available in a later task.' }, ] @@ -231,7 +232,7 @@ export default function App() {
{showingRoutine ? ( - ) : ( + ) : activeId === 'history' ? : (
diff --git a/src/HistoryAsync.test.jsx b/src/HistoryAsync.test.jsx new file mode 100644 index 0000000..f7e982a --- /dev/null +++ b/src/HistoryAsync.test.jsx @@ -0,0 +1,33 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +const read = vi.hoisted(() => vi.fn()) +vi.mock('./historyStorage.js', () => ({ readHistory: read })) +import HistoryView from './HistoryView.jsx' +const empty = () => ({ performanceEntries: [], strengthEntries: [], workoutDetails: [] }) +const weight = (date, weightKg) => ({ ...empty(), workoutDetails: [{ value: { kind: 'body-weight', date, weightKg } }] }) +function deferred() { let resolve; const promise = new Promise((yes) => { resolve = yes }); return { promise, resolve } } +beforeEach(() => read.mockReset()) +afterEach(cleanup) +it('hides stale results while refreshing and preserves filter values on failure/retry', async () => { + read.mockResolvedValueOnce(weight('2026-11-10', 73)).mockRejectedValueOnce(new Error('Read failed')).mockResolvedValueOnce(weight('2026-11-11', 74)) + render() + await screen.findByText(/Latest 10 Nov 2026: 73 kg/) + fireEvent.change(screen.getByLabelText('From date'), { target: { value: '2026-11-09' } }) + fireEvent.click(screen.getByRole('button', { name: 'Refresh history' })) + expect(screen.queryByText(/Latest 10 Nov 2026/)).toBeNull() + await screen.findByRole('alert') + expect(screen.getByLabelText('From date').value).toBe('2026-11-09') + fireEvent.click(screen.getByRole('button', { name: 'Retry history' })) + await screen.findByText(/Latest 11 Nov 2026: 74 kg/) +}) +it('ignores a late response from an unmounted History screen', async () => { + const old = deferred(); const next = deferred() + read.mockReturnValueOnce(old.promise).mockReturnValueOnce(next.promise) + const view = render() + view.rerender() + expect(screen.getByRole('status').textContent).toBe('Loading saved history…') + await act(async () => { next.resolve(weight('2026-11-11', 74)); await next.promise }) + await screen.findByText(/Latest 11 Nov 2026: 74 kg/) + await act(async () => { old.resolve(weight('2026-11-10', 73)); await old.promise }) + expect(screen.queryByText(/Latest 10 Nov 2026/)).toBeNull() +}) diff --git a/src/HistoryView.jsx b/src/HistoryView.jsx new file mode 100644 index 0000000..a2c8cc4 --- /dev/null +++ b/src/HistoryView.jsx @@ -0,0 +1,215 @@ +import { useEffect, useId, useState } from 'react' +import { Button, Form } from 'react-bootstrap' +import { readHistory } from './historyStorage.js' +import { buildHistory, filterHistory, progressGroups } from './historyModel.js' +import { equipmentLabels, externalKg, loadColumns, measurementColumns, validDate } from './performanceModel.js' +import { loadFields } from './strengthLoad.js' + +export const numberText = (value) => value === null || value === undefined ? 'Not available' : String(value) +const periodText = (period) => period === 'legacy' ? 'Earlier records — period not saved' : period === 'morning' ? 'Morning' : 'Afternoon' +const dateText = (date) => new Intl.DateTimeFormat('en-IE', { day: 'numeric', month: 'short', year: 'numeric' }).format(new Date(`${date}T12:00:00`)) +const formatText = (format) => ({ sets: 'sets', attempts: 'hang attempts', emom: 'original minute records', 'emom-total': 'EMOM total' })[format] ?? format +function rowsText(metrics) { + if (metrics.legacyRows) return `${metrics.legacyRows} legacy saved row${metrics.legacyRows === 1 ? '' : 's'} · completion was not recorded` + if (!metrics.completed && !metrics.drafts) return 'Notes only — no performance recorded' + return `${metrics.completed} completed row${metrics.completed === 1 ? '' : 's'} · ${metrics.drafts} draft row${metrics.drafts === 1 ? '' : 's'}${metrics.drafts ? ' · Partial recorded session' : ''}` +} +function Volume({ metrics, legacy = false }) { + return
+

{metrics.volume !== null ? `${legacy ? 'Earlier recorded volume' : 'Known completed-row volume'}: ${numberText(metrics.volume)} kg·reps` : 'No completed rep-load volume available.'}

+ {metrics.volumeUnknown &&

Partial volume: some records have no reps or a total outside the supported numeric range.

} + {metrics.missingLoad &&

Some draft loads are missing; drafts are excluded from completed totals.

} +
+} +function PerformanceRows({ record }) { + return
    {record.rows.map((row, index) => { + const reps = Object.entries(row.values).filter(([key]) => /reps/i.test(key)).map(([, value]) => value) + const load = externalKg(row) + const kg = Number.isFinite(load) ? load : null + const combinedReps = reps.length && reps.every((value) => value !== null) ? reps.reduce((a, b) => a + b, 0) : null + const totalReps = Number.isSafeInteger(combinedReps) ? combinedReps : null + const volume = row.completed && totalReps !== null && kg !== null && Number.isFinite(totalReps * kg) ? totalReps * kg : null + return
  1. + {record.format === 'emom-total' ? 'EMOM total' : `${record.format === 'attempts' ? 'Attempt' : record.format === 'emom' ? 'Minute' : 'Set'} ${index + 1}`} · {row.completed ? 'Completed' : 'Draft'} +
    + {measurementColumns(record.definition).map(({ key, label }) =>
    {label}
    {numberText(row.values[key])}
    )} + {loadColumns(record.definition).map(({ key, label }) =>
    {label}
    {numberText(row.load[key])}
    )} +
    + {reps.length > 0 &&

    External load: {numberText(kg)} kg. {volume !== null ? `${numberText(totalReps)} reps × ${numberText(kg)} kg = ${numberText(volume)} kg·reps.` : row.completed ? 'Volume not available.' : 'Draft — excluded from completed totals.'}

    } +
  2. + })}
+} +function LegacyRows({ record }) { + const rows = record.kind === 'emom' ? [{ ...record, reps: record.totalReps }] : record.sets + return
+

Original saved values. Period, exercise definition and completion flags were not saved; no side or equipment interpretation is inferred.

+
    {rows.map((row, index) =>
  1. + Original {record.kind === 'emom' ? 'EMOM total' : `row ${index + 1}`} +

    Reps: {numberText(row.reps)} · Original external load: {numberText(row.externalKg)} kg

    + {row.load &&
    {loadFields.filter(({ key }) => Object.hasOwn(row.load, key)).map(({ key, label }) =>
    {label}
    {numberText(row.load[key])}
    )}
    } +

    {row.reps === undefined ? 'Reps were not recorded; volume is unavailable.' : Number.isFinite(row.reps * row.externalKg) ? `${numberText(row.reps)} reps × ${numberText(row.externalKg)} kg = ${numberText(row.reps * row.externalKg)} kg·reps.` : 'Volume outside the supported numeric range.'}

    +
  2. )}
+
+} +function Entry({ entry }) { + return
+

{entry.name}

+ {entry.source === 'detailed' && <> +

Saved {formatText(entry.record.format)} · {entry.record.definition.equipment.map((item) => equipmentLabels[item]).join(' + ')}

+

{rowsText(entry.metrics)}

+ + {entry.record.format === 'attempts' &&

Longest continuous: {numberText(entry.metrics.longest)} sec · Cumulative hanging: {numberText(entry.metrics.seconds)} sec

} + + {entry.preserved.length > 0 &&
Earlier representations — excluded from totals + {entry.preserved.map((record) =>

Preserved {formatText(record.format)}. Current EMOM total takes precedence, including when it is a draft.

)} +
} + } + {entry.source === 'legacy' && } + {entry.source === 'note' &&

Notes only — no performance recorded.

} + {entry.note &&

Exercise notes:{' '}{entry.note}

} +
+} +function RecordedDay({ day }) { + const [open, setOpen] = useState(false) + const completed = day.sessions.reduce((n, s) => n + s.metrics.completed, 0) + const drafts = day.sessions.reduce((n, s) => n + s.metrics.drafts, 0) + const legacyRows = day.sessions.reduce((n, s) => n + s.metrics.legacyRows, 0) + const status = completed || drafts ? `${completed} completed row${completed === 1 ? '' : 's'} · ${drafts} draft row${drafts === 1 ? '' : 's'}${legacyRows ? ` · ${legacyRows} legacy saved rows` : ''}` + : legacyRows ? `${legacyRows} legacy saved row${legacyRows === 1 ? '' : 's'} · completion not recorded` : day.sessions.length ? 'Notes only' : day.preservedLegacy.length ? 'Earlier records only' : 'Body weight only' + return
setOpen(event.currentTarget.open)}> + {status}{day.bodyWeight !== null ? ` · ${numberText(day.bodyWeight)} kg body weight` : ''} + {open && <> + {day.bodyWeight !== null &&

Daily body weight: {numberText(day.bodyWeight)} kg — shared across periods; excluded from external-load volume.

} + {day.sessions.map((session) =>
+

{periodText(session.period)}

+

{rowsText(session.metrics)}

+ + {session.note &&

Session notes:{' '}{session.note}

} + {session.entries.map((entry) => )} +
)} + {day.preservedLegacy.length > 0 &&
Earlier legacy records — excluded from totals +

A detailed record exists for each of these exercises on this date. These legacy records have no saved period, so they remain separate and are not added to current totals.

+ {day.preservedLegacy.map((entry) => )} +
} + } +
+} + +export function TrendChart({ title, unit, points, showHigh = false }) { + const id = useId() + const values = points.map((point) => point.value).filter((value) => value !== null) + if (!values.length) return

No completed values available for {title.toLowerCase()}.

+ const top = Math.max(...values, 1) + const dates = points.map((point) => Date.parse(`${point.date}T00:00:00Z`)) + const firstDate = dates[0] + const lastDate = dates.at(-1) + const position = (point, index) => ({ x: firstDate === lastDate ? 300 : 45 + ((dates[index] - firstDate) / (lastDate - firstDate)) * 510, y: 145 - (point.value / top) * 115 }) + const segments = [] + let segment = [] + points.forEach((point, index) => { + if (point.value === null) { if (segment.length) segments.push(segment); segment = []; return } + const { x, y } = position(point, index) + segment.push(`${x},${y}`) + }) + if (segment.length) segments.push(segment) + const latest = points.at(-1) + const prior = points.at(-2) + const difference = latest.value !== null && prior?.value !== null && prior?.value !== undefined ? latest.value - prior.value : null + return
+
{title} ({unit})
+

Latest {dateText(latest.date)}: {numberText(latest.value)} {unit}{latest.partial ? ' · Partial recorded session' : ''}

+ {prior ?

Previous compatible record {dateText(prior.date)}: {numberText(prior.value)} {unit} · Change: {difference === null || !Number.isFinite(difference) ? 'Not available' : `${difference > 0 ? '+' : ''}${numberText(difference)} ${unit}`}

:

One recorded date; no previous compatible record to compare.

} + {showHigh &&

Highest recorded value in this series: {numberText(Math.max(...values))} {unit}.

} +

Scale: 0–{numberText(top)} {unit}

+ + Recorded observations from {points[0].date} to {latest.date}, zero to {top} {unit}. Exact values follow. Missing values break the line. + + {segments.map((segmentPoints, index) => )} + {points.map((point, index) => point.value !== null && {point.date}: {numberText(point.value)} {unit})} + +

+
Recorded values for {title.toLowerCase()} +
    {points.map((point) =>
  1. : {numberText(point.value)} {unit}{point.partial ? ' · Partial recorded session' : ''}
  2. )}
+
+
+} +const measurementText = (measurement) => ({ repetitions: 'reps', 'repetitions-per-side': 'reps per side', duration: 'seconds', 'duration-per-side': 'seconds per side', distance: 'distance' })[measurement] +function seriesLabel(group) { + const entry = group.entry + if (entry.source === 'legacy') { + const rows = entry.record.kind === 'emom' ? [entry.record] : entry.record.sets + const loadModes = [...new Set(rows.map((row) => row.load ? Object.keys(row.load).map((key) => loadFields.find((field) => field.key === key)?.label ?? 'Bodyweight-only record').sort().join(' + ') : 'Original total only'))] + return `${entry.name} · Earlier ${entry.record.kind === 'load-sets' ? 'weights only' : entry.record.kind === 'emom' ? 'EMOM total' : 'sets'} · ${loadModes.join(' / ')} · period not recorded` + } + const definition = entry.record.definition + const counts = [...new Set(entry.record.rows.filter((row) => row.completed && row.load.dumbbellCount !== undefined).map((row) => row.load.dumbbellCount))] + return `${entry.name} · ${periodText(entry.period)} · ${formatText(entry.record.format)} · ${measurementText(definition.measurement)} · ${definition.equipment.map((item) => equipmentLabels[item]).join(' + ')}${counts.length ? ` · ${counts.sort().join('/')} dumbbells` : ''}` +} +const metrics = [ + ['reps', 'Completed reps', 'reps'], ['volume', 'Completed-row external-load volume', 'kg·reps'], ['peakLoad', 'Highest recorded external load', 'kg'], + ['longest', 'Longest continuous hang', 'sec'], ['seconds', 'Cumulative recorded duration', 'sec'], ['metres', 'Recorded distance', 'm'], +] +function ExerciseProgress({ days }) { + const groups = progressGroups(days) + const [selected, setSelected] = useState('') + const [metric, setMetric] = useState('reps') + const group = groups.find((g) => g.key === selected) ?? groups[0] + if (!group) return

Exercise progress

No completed performance or earlier saved rows match these filters. Drafts and notes do not create progress points.

+ const options = metrics.filter(([key]) => group.points.some((p) => p.metrics[key] !== null) && !(key === 'peakLoad' && group.entry.record.definition?.equipment.join() === 'bodyweight')) + .map(([key, label, unit]) => [key, group.entry.source === 'legacy' ? key === 'reps' ? 'Earlier saved reps' : key === 'volume' ? 'Earlier recorded external-load volume' : label : label, unit]) + const chosen = options.find(([key]) => key === metric) ?? options[0] + const perSide = group.entry.record.definition?.measurement.endsWith('-per-side') + const title = chosen ? `${chosen[1]}${perSide && ['reps', 'seconds'].includes(chosen[0]) ? ' (both saved sides)' : ''}` : '' + return
+

Exercise progress

+

Compare saved measurements and loading modes separately. Detailed values cover completed rows only; earlier saved records retain their original semantics. Partial records are labelled. Lines connect recorded observations, not unrecorded days.

+ Exercise and saved format setSelected(event.target.value)}>{groups.map((g) => )} +

{seriesLabel(group)}

+ {!chosen &&

Recorded values are outside the supported calculation range. Inspect the session details for original actuals.

} + {chosen && <>Progress measure setMetric(event.target.value)}>{options.map(([key, label]) => )} + {group.entry.source === 'legacy' &&

Earlier saved values only; completion and period were not recorded. These do not compare with detailed records.

} + ({ date: point.date, value: point.metrics[chosen[0]], partial: point.partial }))} /> + } +
+} +export default function HistoryView() { + const [data, setData] = useState([]) + const [loading, setLoading] = useState(true) + const [error, setError] = useState('') + const [refresh, setRefresh] = useState(0) + const [from, setFrom] = useState('') + const [to, setTo] = useState('') + const [period, setPeriod] = useState('all') + useEffect(() => { + let active = true + setLoading(true); setError('') + readHistory().then((records) => { if (active) { setData(buildHistory(records)); setLoading(false) } }) + .catch((failure) => { if (active) { setError(failure.message); setLoading(false) } }) + return () => { active = false } + }, [refresh]) + const rangeError = (from && !validDate(from)) || (to && !validDate(to)) || (from && to && from > to) ? 'Choose valid dates with From on or before To.' : '' + const days = rangeError ? [] : filterHistory(data, { from, to, period }) + const weights = days.filter((day) => day.bodyWeight !== null).slice().reverse().map((day) => ({ date: day.date, value: day.bodyWeight, partial: false })) + return
+
+ From date setFrom(event.target.value)} aria-describedby={rangeError ? 'history-range-error' : undefined} /> + To date setTo(event.target.value)} aria-describedby={rangeError ? 'history-range-error' : undefined} /> + Recorded period setPeriod(event.target.value)}> + + +
+ {rangeError && } + {loading ?

Loading saved history…

: error ?

{error}

: !rangeError && <> +
+

Recorded dates

+

Volume = sum of completed reps × recorded external kilograms (vest + dumbbell kg each × saved count + bar total). Body weight and timed-only work are excluded. Earlier representations are never added to their current replacement.

+

Row counts describe saved records, not completion of an entire prescribed workout. Notes-only and weight-only dates remain separate observations.

+ {!days.length ?

{!data.length ? 'No saved history yet. Save performance, notes or body weight from Today or Week to see it here.' : 'No records match these filters.'}

: days.map((day) => )} +
+ +

Body-weight progress

One daily measurement in kg. Date filters apply; period filters do not split this daily observation.

+ {weights.length ? :

No body-weight measurements in this date range.

} +
+ } +
+} diff --git a/src/HistoryView.test.jsx b/src/HistoryView.test.jsx new file mode 100644 index 0000000..13a7aae --- /dev/null +++ b/src/HistoryView.test.jsx @@ -0,0 +1,145 @@ +import { IDBFactory } from 'fake-indexeddb' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' +import HistoryView, { TrendChart } from './HistoryView.jsx' +import App from './App.jsx' +import { exerciseDefinitions } from './data/index.js' +import { newPerformance } from './performanceModel.js' +import { writePerformance } from './performanceStorage.js' +import { writeStrengthEntry } from './strengthStorage.js' +import { saveWorkoutDetail } from './workoutDetailStorage.js' +import { exportBackup } from './backupStorage.js' +const definition = exerciseDefinitions.find((d) => d.id === 'pull-up') +async function total(date, reps = 30, load = 6, period = 'morning') { + const record = newPerformance(date, period, definition, { kind: 'emom', rounds: 10 }, 'emom-total') + record.rows[0] = { values: { reps }, load: { vestKg: load }, completed: reps !== null && load !== null } + await writePerformance(record) +} +async function loaded() { await screen.findByRole('region', { name: 'Recorded dates' }) } +function expandAll(container) { + for (let pass = 0; pass < 3; pass++) for (const details of container.querySelectorAll('details')) { + if (!details.open) { details.open = true; fireEvent(details, new Event('toggle')) } + } +} +const filter = (label, value) => fireEvent.change(screen.getByLabelText(label), { target: { value } }) +beforeEach(() => { vi.stubGlobal('indexedDB', new IDBFactory()); window.localStorage.clear() }) +afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.unstubAllGlobals() }) +it('shows empty history and integrates with the existing app navigation and clock', async () => { + render() + fireEvent.click(screen.getByRole('button', { name: 'History', exact: true })) + await loaded() + expect(screen.getByText(/No saved history yet/)).toBeTruthy() + expect(screen.getByLabelText('Current local time')).toBeTruthy() + expect(screen.queryByText('Completed workouts will appear here once tracking is available.')).toBeNull() +}) +it('shows newest-first actual sessions, filters date/period and never writes while browsing', async () => { + await total('2026-11-09', 20, 0) + await total('2026-11-10', 35, 8) + await total('2026-11-11', 10, 4, 'afternoon') + const before = await exportBackup() + const view = render(); await loaded(); expandAll(view.container) + expect([...view.container.querySelectorAll('.history-day > summary time')].map((time) => time.dateTime)).toEqual(['2026-11-11', '2026-11-10', '2026-11-09']) + const session = screen.getByRole('region', { name: '2026-11-10 Morning' }) + expect(within(session).getByText(/35 reps × 8 kg = 280 kg·reps\./)).toBeTruthy() + expect(within(session).getAllByText('Known completed-row volume: 280 kg·reps')).toHaveLength(2) + filter('Recorded period', 'morning') + expect(view.container.querySelectorAll('.history-day')).toHaveLength(2) + filter('From date', '2026-11-10') + expect(view.container.querySelectorAll('.history-day')).toHaveLength(1) + filter('To date', '2026-11-09') + expect(screen.getByRole('alert').textContent).toMatch(/From on or before To/) + expect(screen.queryByRole('region', { name: 'Recorded dates' })).toBeNull() + fireEvent.click(screen.getByRole('button', { name: 'Clear filters' })) + filter('From date', '2026-12-01') + expect(screen.getByText('No records match these filters.')).toBeTruthy() + expect(await exportBackup()).toBe(before) +}) +it('labels notes-only and body-weight-only observations without fabricated workout completion', async () => { + await saveWorkoutDetail({ kind: 'session-note', date: '2026-11-09', period: 'morning' }, 'Easy stretch\nNo performance entered') + await saveWorkoutDetail({ kind: 'exercise-note', date: '2026-11-09', period: 'morning', exerciseId: 'front-plank' }, 'Use the mat') + await saveWorkoutDetail({ kind: 'body-weight', date: '2026-11-10' }, 73.25) + await saveWorkoutDetail({ kind: 'body-weight', date: '2026-11-11' }, 73.5) + const view = render(); await loaded(); expandAll(view.container) + expect(screen.getByText('Notes only')).toBeTruthy() + expect(screen.getAllByText(/Notes only — no performance recorded/).length).toBeGreaterThan(0) + expect(screen.getByText(/Easy stretch/).textContent).toContain('No performance entered') + expect(screen.getByText(/Use the mat/)).toBeTruthy() + expect(screen.getByText(/Latest 11 Nov 2026: 73.5 kg/)).toBeTruthy() + expect(screen.getByText(/Change: \+0.25 kg/)).toBeTruthy() + filter('Recorded period', 'afternoon') + expect(screen.getByText(/Latest 11 Nov 2026: 73.5 kg/)).toBeTruthy() + expect(screen.queryByText(/Easy stretch/)).toBeNull() +}) +it('preserves minute and legacy records separately while a draft aggregate takes precedence', async () => { + const minutes = newPerformance('2026-11-10', 'morning', definition, { kind: 'emom', rounds: 10 }) + minutes.rows[0] = { values: { reps: 4 }, load: { vestKg: 6 }, completed: true } + await writePerformance(minutes) + await writeStrengthEntry('2026-11-10', 'pull-up', { kind: 'emom', totalReps: 99, externalKg: 20 }) + await total('2026-11-10', null, null) + const view = render(); await loaded(); expandAll(view.container) + expect(screen.getByText('Earlier representations — excluded from totals')).toBeTruthy() + expect(screen.getByText('Earlier legacy records — excluded from totals')).toBeTruthy() + expect(screen.getByText(/Original saved values/)).toBeTruthy() + expect(screen.getByText('99 reps × 20 kg = 1980 kg·reps.')).toBeTruthy() + expect(screen.queryByText('Known completed-row volume: 1980 kg·reps')).toBeNull() + expect(screen.getAllByText(/0 completed rows · 1 draft row/).length).toBeGreaterThan(0) + expect(screen.getByText(/No completed performance or earlier saved rows match/)).toBeTruthy() +}) +it('shows previous/current compatible reps and load trends with exact accessible values', async () => { + await total('2026-11-03', 30, 6) + await total('2026-11-10', 35, 8) + const view = render(); await loaded(); expandAll(view.container) + expect(screen.getByText(/Latest 10 Nov 2026: 35 reps/)).toBeTruthy() + expect(screen.getByText(/Previous compatible record 3 Nov 2026: 30 reps · Change: \+5 reps/)).toBeTruthy() + filter('Progress measure', 'volume') + expect(screen.getByText(/Latest 10 Nov 2026: 280 kg·reps/)).toBeTruthy() + filter('Progress measure', 'peakLoad') + expect(screen.getByText(/Latest 10 Nov 2026: 8 kg/)).toBeTruthy() + expect(screen.getByRole('img', { name: /Highest recorded external load/ })).toBeTruthy() + expandAll(view.container) + expect(screen.getByText(/3 Nov 2026/,{ selector: '.trend-recorded-values time' })).toBeTruthy() +}) +it('distinguishes continuous and cumulative hanging without rep-load volume', async () => { + const hangDef = exerciseDefinitions.find((d) => d.id === 'daily-hang') + const record = newPerformance('2026-11-10', 'afternoon', hangDef, { kind: 'attempts' }) + record.rows = [{ values: { seconds: 60 }, load: {}, completed: true }, { values: { seconds: 75 }, load: {}, completed: true }] + await writePerformance(record) + const view = render(); await loaded(); expandAll(view.container) + expect(screen.getByText('Longest continuous: 75 sec · Cumulative hanging: 135 sec')).toBeTruthy() + expect(screen.queryByRole('option', { name: 'Completed-row external-load volume' })).toBeNull() + expect(screen.getByText(/Latest 10 Nov 2026: 75 sec/)).toBeTruthy() + filter('Progress measure', 'seconds') + expect(screen.getByText(/Latest 10 Nov 2026: 135 sec/)).toBeTruthy() +}) +it('surfaces storage failure, retries and refreshes records saved after the initial read', async () => { + vi.stubGlobal('indexedDB', undefined) + render() + expect((await screen.findByRole('alert')).textContent).toMatch(/unavailable/) + vi.stubGlobal('indexedDB', new IDBFactory()) + fireEvent.click(screen.getByRole('button', { name: 'Retry history' })); await loaded() + expect(screen.getByText(/No saved history yet/)).toBeTruthy() + await total('2026-11-10') + fireEvent.click(screen.getByRole('button', { name: 'Refresh history' })) + await waitFor(() => expect(screen.queryByText(/No saved history yet/)).toBeNull()) + await loaded() + expect(screen.queryByRole('alert')).toBeNull() +}) +it('charts zero values and missing gaps without inventing measurements or a previous comparison', () => { + const view = render() + expect(view.container.querySelectorAll('polyline')).toHaveLength(2) + expect(view.container.querySelectorAll('circle')).toHaveLength(2) + expect(screen.getByText(/Previous compatible record 4 Nov 2026: Not available kg · Change: Not available/)).toBeTruthy() + view.rerender() + expect(screen.getByText('One recorded date; no previous compatible record to compare.')).toBeTruthy() +}) + +it('keeps original weight-only legacy history readable without inventing reps, period or volume', async () => { + await writeStrengthEntry('2026-11-10', 'suitcase-carry', { kind: 'load-sets', sets: [{ externalKg: 20 }] }) + const view = render(); await loaded(); expandAll(view.container) + const session = screen.getByRole('region', { name: '2026-11-10 Earlier records — period not saved' }) + expect(within(session).getByText('1 legacy saved row · completion was not recorded')).toBeTruthy() + expect(within(session).getByText('Reps were not recorded; volume is unavailable.')).toBeTruthy() + expect(screen.queryByRole('option', { name: 'Completed reps' })).toBeNull() + expect(screen.queryByRole('option', { name: 'Completed-row external-load volume' })).toBeNull() + expect(screen.getByText(/Latest 10 Nov 2026: 20 kg/)).toBeTruthy() +}) diff --git a/src/historyModel.js b/src/historyModel.js new file mode 100644 index 0000000..2ecf285 --- /dev/null +++ b/src/historyModel.js @@ -0,0 +1,126 @@ +import { externalKg, measurementColumns, signature } from './performanceModel.js' + +const finite = (value) => Number.isFinite(value) ? value : null +function sum(values, integer = false) { + if (!values.length || values.some((value) => value === null)) return null + const total = values.reduce((a, b) => a + b, 0) + return integer && !Number.isSafeInteger(total) ? null : finite(total) +} +function measure(rows, pattern, integer = false) { + return sum(rows.flatMap((row) => Object.entries(row.values).filter(([key]) => pattern.test(key)).map(([, value]) => value)), integer) +} +export function detailedMetrics(record) { + const rows = record.rows.filter((row) => row.completed) + const repWork = measurementColumns(record.definition).some(({ key }) => /reps/i.test(key)) + const loads = rows.map(externalKg) + const volume = repWork ? sum(rows.map((row) => { + const reps = measure([row], /reps/i, true) + const load = externalKg(row) + return reps === null || load === null ? null : finite(reps * load) + })) : null + const seconds = measure(rows, /seconds/i) + return { + completed: rows.length, drafts: record.rows.length - rows.length, legacyRows: 0, + reps: repWork ? measure(rows, /reps/i, true) : null, + volume, volumeUnknown: repWork && rows.length > 0 && volume === null, + missingLoad: repWork && record.rows.some((row) => externalKg(row) === null), + peakLoad: loads.length && loads.every((load) => load !== null) ? finite(Math.max(...loads)) : null, + seconds, metres: measure(rows, /metres/), + longest: record.format === 'attempts' && record.definition.measurement === 'duration' && rows.length ? Math.max(...rows.map((row) => row.values.seconds)) : null, + } +} +export function legacyMetrics(record) { + const rows = record.kind === 'emom' ? [{ reps: record.totalReps, externalKg: record.externalKg }] : record.sets + const reps = record.kind === 'load-sets' ? null : sum(rows.map((row) => row.reps), true) + const volume = record.kind === 'load-sets' ? null : sum(rows.map((row) => finite(row.reps * row.externalKg))) + return { completed: 0, drafts: 0, legacyRows: rows.length, reps, volume, volumeUnknown: volume === null, missingLoad: false, peakLoad: Math.max(...rows.map((row) => row.externalKg)), seconds: null, longest: null, metres: null } +} +export function sessionMetrics(entries) { + const metrics = entries.map((entry) => entry.metrics) + const volumes = metrics.map((m) => m.volume).filter((v) => v !== null) + const volume = sum(volumes) + return { + completed: metrics.reduce((n, m) => n + m.completed, 0), + drafts: metrics.reduce((n, m) => n + m.drafts, 0), + legacyRows: metrics.reduce((n, m) => n + m.legacyRows, 0), volume, + volumeUnknown: metrics.some((m) => m.volumeUnknown) || (volumes.length > 0 && volume === null), + missingLoad: metrics.some((m) => m.missingLoad), + } +} +export function buildHistory(data) { + const days = new Map() + const dayFor = (date) => { + if (!days.has(date)) days.set(date, { date, sessions: [], bodyWeight: null, preservedLegacy: [] }) + return days.get(date) + } + const sessionFor = (date, period) => { + const day = dayFor(date) + let session = day.sessions.find((s) => s.period === period) + if (!session) { session = { date, period, entries: [], note: '' }; day.sessions.push(session) } + return session + } + const detailed = new Map() + for (const { key, value } of data.performanceEntries) { + const identity = `${value.date}:${value.period}:${value.exerciseId}` + if (!detailed.has(identity)) detailed.set(identity, []) + detailed.get(identity).push({ key, value }) + } + for (const records of detailed.values()) { + const current = records.find(({ value }) => value.format === 'emom-total') ?? records[0] + const r = current.value + sessionFor(r.date, r.period).entries.push({ + id: current.key, date: r.date, period: r.period, exerciseId: r.exerciseId, + name: r.definition.name || r.exerciseId, source: 'detailed', record: r, metrics: detailedMetrics(r), + preserved: records.filter((item) => item !== current).map(({ value }) => value), note: '', + }) + } + for (const { key, value } of data.strengthEntries) { + const date = key.slice(0, 10) + const exerciseId = key.slice(11) + const entry = { id: key, date, period: 'legacy', exerciseId, name: exerciseId, source: 'legacy', record: value, metrics: legacyMetrics(value), note: '' } + if (dayFor(date).sessions.some((s) => s.entries.some((e) => e.exerciseId === exerciseId))) dayFor(date).preservedLegacy.push(entry) + else sessionFor(date, 'legacy').entries.push(entry) + } + for (const { value } of data.workoutDetails) { + if (value.kind === 'body-weight') { dayFor(value.date).bodyWeight = value.weightKg; continue } + const session = sessionFor(value.date, value.period) + if (value.kind === 'session-note') session.note = value.text + else { + let entry = session.entries.find((e) => e.exerciseId === value.exerciseId) + if (!entry) { + entry = { id: `${value.date}:${value.period}:${value.exerciseId}:note`, date: value.date, period: value.period, exerciseId: value.exerciseId, name: value.exerciseId, source: 'note', note: '', preserved: [], metrics: { completed: 0, drafts: 0, legacyRows: 0, volume: null, volumeUnknown: false, missingLoad: false } } + session.entries.push(entry) + } + entry.note = value.text + } + } + for (const day of days.values()) { + day.sessions.sort((a, b) => ['morning', 'afternoon', 'legacy'].indexOf(a.period) - ['morning', 'afternoon', 'legacy'].indexOf(b.period)) + for (const session of day.sessions) { + session.entries.sort((a, b) => a.name.localeCompare(b.name)) + session.metrics = sessionMetrics(session.entries) + } + } + return [...days.values()].sort((a, b) => b.date.localeCompare(a.date)) +} +export function filterHistory(days, { from = '', to = '', period = 'all' }) { + return days.filter((day) => (!from || day.date >= from) && (!to || day.date <= to)).map((day) => ({ + ...day, sessions: day.sessions.filter((session) => period === 'all' || session.period === period), + preservedLegacy: period === 'all' || period === 'legacy' ? day.preservedLegacy : [], + })).filter((day) => day.sessions.length || day.bodyWeight !== null || day.preservedLegacy.length) +} +export function progressGroups(days) { + const groups = new Map() + for (const day of days) for (const session of day.sessions) for (const entry of session.entries) { + if (entry.source === 'note' || (!entry.metrics.completed && !entry.metrics.legacyRows)) continue + const record = entry.record + const countModes = entry.source === 'detailed' ? [...new Set(record.rows.filter((row) => row.completed).map((row) => row.load.dumbbellCount ?? null))].sort() : [] + const legacyRows = entry.source === 'legacy' ? record.kind === 'emom' ? [record] : record.sets : [] + const legacyModes = [...new Set(legacyRows.map((row) => row.load ? Object.keys(row.load).sort().join('+') : 'unclassified-original-total'))].sort() + const mode = entry.source === 'detailed' ? signature(record.definition, record.format) : JSON.stringify(['legacy', record.kind, legacyModes]) + const key = JSON.stringify([entry.exerciseId, entry.period, mode, countModes]) + if (!groups.has(key)) groups.set(key, { key, entry, points: [] }) + groups.get(key).points.push({ date: day.date, metrics: entry.metrics, partial: entry.metrics.drafts > 0 || entry.metrics.volumeUnknown }) + } + return [...groups.values()].map((group) => ({ ...group, points: group.points.sort((a, b) => a.date.localeCompare(b.date)) })).sort((a, b) => a.entry.name.localeCompare(b.entry.name)) +} diff --git a/src/historyModel.test.js b/src/historyModel.test.js new file mode 100644 index 0000000..8ecafd6 --- /dev/null +++ b/src/historyModel.test.js @@ -0,0 +1,129 @@ +import { expect, it } from 'vitest' +import { exerciseDefinitions } from './data/index.js' +import { newPerformance } from './performanceModel.js' +import { performanceKey } from './performanceStorage.js' +import { buildHistory, detailedMetrics, filterHistory, legacyMetrics, progressGroups, sessionMetrics } from './historyModel.js' +const def = (id) => exerciseDefinitions.find((d) => d.id === id) +const data = () => ({ performanceEntries: [], strengthEntries: [], workoutDetails: [] }) +function record(id = 'dumbbell-floor-fly', date = '2026-11-10', format = 'sets', period = 'morning', definition = def(id)) { + const r = newPerformance(date, period, definition, { kind: format.startsWith('emom') ? 'emom' : 'sets', rounds: 10 }, format) + const row = r.rows[0] + for (const key of Object.keys(row.values)) row.values[key] = /reps/i.test(key) ? 12 : 30 + for (const key of Object.keys(row.load)) if (key !== 'dumbbellCount') row.load[key] = 8 + row.completed = true + return r +} +const add = (source, r) => source.performanceEntries.push({ key: performanceKey(r.date, r.period, r.exerciseId, r.format), value: r }) +it('calculates actual paired dumbbell volume and excludes drafts without inventing zero load', () => { + const r = record() + r.rows.push({ values: { reps: 20 }, load: { dumbbellKgEach: null, dumbbellCount: 2 }, completed: false }) + expect(detailedMetrics(r)).toMatchObject({ reps: 12, volume: 192, completed: 1, drafts: 1, missingLoad: true, peakLoad: 16 }) + r.rows[0].load.dumbbellKgEach = 0 + expect(detailedMetrics(r).volume).toBe(0) + r.rows[0].completed = false + expect(detailedMetrics(r).volume).toBeNull() +}) +it('sums saved side measurements and mixed external load components', () => { + const r = record('bulgarian-split-squat') + r.rows[0].values = { leftReps: 5, rightReps: 7 } + r.rows[0].load = { vestKg: 4, dumbbellKgEach: 10, dumbbellCount: 2 } + expect(detailedMetrics(r)).toMatchObject({ reps: 12, volume: 288, peakLoad: 24 }) + const curl = record('single-arm-preacher-curl') + curl.rows[0].values = { leftReps: 10, rightReps: 8 } + curl.rows[0].load = { dumbbellKgEach: 12, dumbbellCount: 1 } + expect(detailedMetrics(curl).volume).toBe(216) +}) +it('uses saved EZ and straight-bar totals rather than current seed metadata', () => { + const ez = record('ez-bar-bent-over-row') + ez.rows[0].load = { ezBarTotalKg: 20 } + expect(detailedMetrics(ez).volume).toBe(240) + const straight = record('ez-bar-bent-over-row', '2026-11-11', 'sets', 'morning', { ...def('ez-bar-bent-over-row'), name: 'Saved straight-bar variation', equipment: ['straight-bar'] }) + straight.rows[0].load = { straightBarTotalKg: 25 } + expect(detailedMetrics(straight).volume).toBe(300) + const source = data(); add(source, straight) + expect(buildHistory(source)[0].sessions[0].entries[0].name).toBe('Saved straight-bar variation') +}) +it('keeps timed work and continuous/cumulative hanging separate from rep volume', () => { + const r = record('daily-hang', '2026-11-10', 'attempts', 'afternoon') + r.rows[0].values.seconds = 60 + r.rows.push({ values: { seconds: 75 }, load: {}, completed: true }) + expect(detailedMetrics(r)).toMatchObject({ seconds: 135, longest: 75, volume: null, reps: null }) + expect(detailedMetrics(record('front-plank'))).toMatchObject({ seconds: 30, volume: null, longest: null }) +}) +it('uses current aggregate even when it is a draft and preserves originals without counting them', () => { + const source = data() + add(source, record('pull-up', '2026-11-10', 'emom')) + const total = record('pull-up', '2026-11-10', 'emom-total') + total.rows[0] = { values: { reps: null }, load: { vestKg: null }, completed: false } + add(source, total) + source.strengthEntries.push({ key: '2026-11-10:pull-up', value: { kind: 'emom', totalReps: 99, externalKg: 20 } }) + const days = buildHistory(source) + expect(days[0].sessions).toHaveLength(1) + expect(days[0].sessions[0].entries).toHaveLength(1) + expect(days[0].sessions[0].metrics).toMatchObject({ completed: 0, drafts: 1, volume: null }) + expect(days[0].sessions[0].entries[0].preserved[0].format).toBe('emom') + expect(days[0].preservedLegacy).toHaveLength(1) + expect(progressGroups(days)).toEqual([]) +}) +it('shows original minute volume when no replacement total exists, and never double-counts replacements', () => { + const source = data(); const minutes = record('pull-up', '2026-11-10', 'emom') + minutes.rows[0] = { values: { reps: 4 }, load: { vestKg: 6 }, completed: true } + minutes.rows[1] = { values: { reps: 3 }, load: { vestKg: 10 }, completed: true } + add(source, minutes) + expect(buildHistory(source)[0].sessions[0].metrics.volume).toBe(54) + const total = record('pull-up', '2026-11-10', 'emom-total') + total.rows[0] = { values: { reps: 35 }, load: { vestKg: 8 }, completed: true } + add(source, total) + expect(buildHistory(source)[0].sessions[0].metrics.volume).toBe(280) +}) +it('keeps legacy totals and unknown weight-only volume without inferring periods/completion', () => { + expect(legacyMetrics({ kind: 'emom', totalReps: 30, externalKg: 8 })).toMatchObject({ volume: 240, completed: 0, legacyRows: 1 }) + expect(legacyMetrics({ kind: 'sets', sets: [{ reps: 10, externalKg: 3 }, { reps: 8, externalKg: 5 }] }).volume).toBe(70) + const unknown = legacyMetrics({ kind: 'load-sets', sets: [{ externalKg: 20 }] }) + expect(unknown).toMatchObject({ reps: null, volume: null, volumeUnknown: true }) + const summary = sessionMetrics([{ metrics: legacyMetrics({ kind: 'emom', totalReps: 0, externalKg: 8 }) }, { metrics: unknown }]) + expect(summary).toMatchObject({ volume: 0, volumeUnknown: true, completed: 0, legacyRows: 2 }) +}) +it('retains notes-only/weight-only dates, ordering, filters and readonly source values', () => { + const source = data() + source.workoutDetails = [ + { value: { kind: 'body-weight', date: '2026-11-11', weightKg: 73.25 } }, + { value: { kind: 'session-note', date: '2026-11-09', period: 'morning', text: 'Stretch' } }, + { value: { kind: 'exercise-note', date: '2026-11-10', period: 'afternoon', exerciseId: 'daily-hang', text: 'Grip' } }, + ] + const original = JSON.stringify(source) + const days = buildHistory(source) + expect(days.map((d) => d.date)).toEqual(['2026-11-11', '2026-11-10', '2026-11-09']) + expect(days[0].sessions).toEqual([]) + expect(days[1].sessions[0].entries[0].source).toBe('note') + expect(filterHistory(days, { from: '2026-11-10', period: 'morning' }).map((d) => d.date)).toEqual(['2026-11-11']) + expect(progressGroups(days)).toEqual([]) + expect(JSON.stringify(source)).toBe(original) +}) +it('compares only compatible saved format, period, equipment, measurements and actual counts', () => { + const source = data() + for (const date of ['2026-11-09', '2026-11-10']) add(source, record('single-arm-preacher-curl', date)) + const count = record('single-arm-preacher-curl', '2026-11-11'); count.rows[0].load.dumbbellCount = 2; add(source, count) + add(source, record('single-arm-preacher-curl', '2026-11-12', 'sets', 'afternoon')) + const changed = record('single-arm-preacher-curl', '2026-11-13', 'sets', 'morning', { ...def('single-arm-preacher-curl'), measurement: 'duration-per-side' }); add(source, changed) + const groups = progressGroups(buildHistory(source)) + expect(groups).toHaveLength(4) + expect(groups.find((g) => g.points.length === 2).points.map((p) => p.date)).toEqual(['2026-11-09', '2026-11-10']) +}) +it('reports arithmetic overflow as unavailable rather than zero or Infinity', () => { + const r = record(); r.rows[0].load.dumbbellKgEach = Number.MAX_VALUE + expect(detailedMetrics(r)).toMatchObject({ volume: null, volumeUnknown: true, peakLoad: null }) + const huge = { completed: 1, drafts: 0, legacyRows: 0, volume: Number.MAX_VALUE, volumeUnknown: false, missingLoad: false } + expect(sessionMetrics([{ metrics: huge }, { metrics: huge }])).toMatchObject({ volume: null, volumeUnknown: true }) +}) + +it('keeps legacy loading modes and historical minute/aggregate series distinct', () => { + const source = data() + source.strengthEntries = [ + { key: '2026-11-01:pull-up', value: { kind: 'emom', totalReps: 30, externalKg: 8 } }, + { key: '2026-11-02:pull-up', value: { kind: 'emom', totalReps: 30, externalKg: 8, load: { vestKg: 8 } } }, + ] + add(source, record('pull-up', '2026-11-03', 'emom')) + add(source, record('pull-up', '2026-11-04', 'emom-total')) + expect(progressGroups(buildHistory(source))).toHaveLength(4) +}) diff --git a/src/historyStorage.js b/src/historyStorage.js new file mode 100644 index 0000000..43a1bf5 --- /dev/null +++ b/src/historyStorage.js @@ -0,0 +1,35 @@ +import { openLocalDatabase } from './localDatabase.js' +import { performanceError, validDate } from './performanceModel.js' +import { performanceKey } from './performanceStorage.js' +import { validEntry } from './strengthStorage.js' +import { detailError, detailKey } from './workoutDetailStorage.js' + +export async function readHistory() { + const db = await openLocalDatabase() + return new Promise((resolve, reject) => { + const names = ['performanceEntries', 'strengthEntries', 'workoutDetails'] + const tx = db.transaction(names, 'readonly') + const data = Object.fromEntries(names.map((name) => [name, []])) + let invalid = false + for (const name of names) { + const request = tx.objectStore(name).openCursor() + request.onsuccess = () => { + const cursor = request.result + if (!cursor) return + const { key, value } = cursor + const bad = typeof key !== 'string' || (name === 'performanceEntries' + ? performanceError(value) || key !== performanceKey(value.date, value.period, value.exerciseId, value.format) + : name === 'workoutDetails' ? detailError(value) || key !== detailKey(value) + : !validDate(key.slice(0, 10)) || key[10] !== ':' || !key.slice(11) || !validEntry(value)) + if (bad) { invalid = true; tx.abort(); return } + data[name].push({ key, value }) + cursor.continue() + } + } + tx.oncomplete = () => { db.close(); resolve(data) } + tx.onerror = tx.onabort = () => { + db.close() + reject(new Error(invalid ? 'Saved history contains an invalid or unsupported record. Your data was not changed.' : 'Could not read workout history. Your data was not changed.')) + } + }) +} diff --git a/src/historyStorage.test.js b/src/historyStorage.test.js new file mode 100644 index 0000000..3f3b780 --- /dev/null +++ b/src/historyStorage.test.js @@ -0,0 +1,49 @@ +import { IDBDatabase, IDBFactory } from 'fake-indexeddb' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { readHistory } from './historyStorage.js' +import { exportBackup } from './backupStorage.js' +import { writePerformance } from './performanceStorage.js' +import { writeStrengthEntry } from './strengthStorage.js' +import { saveWorkoutDetail } from './workoutDetailStorage.js' +import { newPerformance } from './performanceModel.js' +import { exerciseDefinitions } from './data/index.js' +import { openLocalDatabase } from './localDatabase.js' +beforeEach(() => vi.stubGlobal('indexedDB', new IDBFactory())) +afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals() }) +it('reads all history in one readonly snapshot and does not modify saved records', async () => { + const definition = exerciseDefinitions.find((d) => d.id === 'front-plank') + const record = newPerformance('2026-11-10', 'afternoon', definition, { kind: 'sets' }) + record.rows[0] = { values: { seconds: 45 }, load: { vestKg: 0 }, completed: true } + await writePerformance(record) + await writeStrengthEntry('2026-11-09', 'pull-up', { kind: 'emom', totalReps: 30, externalKg: 6 }) + await saveWorkoutDetail({ kind: 'body-weight', date: '2026-11-10' }, 73.25) + const before = await exportBackup() + const tx = vi.spyOn(IDBDatabase.prototype, 'transaction') + const history = await readHistory() + expect(tx).toHaveBeenCalledTimes(1) + expect(tx.mock.calls[0][0]).toEqual(['performanceEntries', 'strengthEntries', 'workoutDetails']) + expect(tx.mock.calls[0][1]).toBe('readonly') + expect(history.performanceEntries[0].value).toEqual(record) + expect(history.strengthEntries).toHaveLength(1) + expect(history.workoutDetails).toHaveLength(1) + expect(await exportBackup()).toBe(before) +}) +it('returns empty data without creating performance or observations', async () => { + expect(await readHistory()).toEqual({ performanceEntries: [], strengthEntries: [], workoutDetails: [] }) +}) +it.each(['performanceEntries', 'strengthEntries', 'workoutDetails'])('rejects invalid %s records without altering data', async (store) => { + const db = await openLocalDatabase() + await new Promise((resolve) => { + const tx = db.transaction(store, 'readwrite') + tx.objectStore(store).put({ invalid: true }, 'not-a-date') + tx.oncomplete = resolve + }) + db.close() + const before = await exportBackup() + await expect(readHistory()).rejects.toThrow(/invalid or unsupported/) + expect(await exportBackup()).toBe(before) +}) +it('reports unavailable storage instead of displaying an empty successful history', async () => { + vi.stubGlobal('indexedDB', undefined) + await expect(readHistory()).rejects.toThrow(/unavailable/) +}) diff --git a/src/styles.css b/src/styles.css index 39398b5..bfaa207 100644 --- a/src/styles.css +++ b/src/styles.css @@ -251,3 +251,46 @@ h1 { margin: .25rem 0 .55rem; font-size: clamp(2.2rem, 4vw, 3.25rem); line-heigh .detail-actions { display: flex; flex-wrap: wrap; gap: .5rem; } .detail-actions .btn { min-height: 44px; } @media (max-width: 767px) { .session-detail-fields { grid-template-columns: minmax(0, 1fr); } } + +/* TASK-008 read-only history extends the established dark surfaces. */ +.history-view { max-width: 1100px; } +.history-filters { display: flex; flex-wrap: wrap; align-items: end; gap: .8rem; padding: 1rem; } +.history-filters > div { flex: 1 1 10rem; min-width: 0; } +.history-view .form-control, .history-view .form-select { min-height: 44px; max-width: 100%; border-color: var(--border-control); background-color: var(--surface-input); color: var(--text-primary); } +.history-view .form-label { color: var(--text-secondary); font-size: .85rem; font-weight: 650; } +.history-view .btn { min-height: 44px; } +.history-view :is(input, select, summary):focus-visible { outline: 3px solid var(--focus); outline-offset: 3px; box-shadow: none; } +.history-recorded, .history-progress { margin-top: 1.5rem; } +.history-view h2 { font-size: 1.5rem; } +.history-view h3 { font-size: 1.2rem; } +.history-view h4 { font-size: 1.05rem; } +.history-view p { color: var(--text-secondary); font-size: .9rem; overflow-wrap: anywhere; } +.history-day { margin-top: .75rem; padding: 1rem; border: 1px solid var(--border-subtle); border-radius: 12px; background: var(--surface-panel); overflow-wrap: anywhere; } +.history-day > summary { min-height: 44px; padding-block: .4rem; cursor: pointer; color: var(--accent); font-weight: 700; } +.history-day > summary span { display: block; margin-top: .25rem; color: var(--text-secondary); font-size: .85rem; font-weight: 400; } +.history-session { margin-top: 1rem; border-top: 1px solid var(--border-subtle); padding-top: 1rem; } +.history-exercise { margin-block: .8rem; padding: .8rem; border: 1px solid var(--border-subtle); border-radius: 8px; background: var(--surface-card); } +.history-note { white-space: pre-wrap; } +.history-rows { margin-top: .7rem; padding-left: 1.3rem; } +.history-rows > li { padding-block: .4rem; } +.history-actuals { display: flex; flex-wrap: wrap; gap: .4rem 1rem; margin-block: .5rem; } +.history-actuals dt { font-size: .8rem; color: var(--text-secondary); } +.history-actuals dd { margin: 0; font-variant-numeric: tabular-nums; } +.history-preserved summary, .trend-recorded-values summary { min-height: 44px; padding-block: .6rem; color: var(--accent); cursor: pointer; } +.history-progress { padding: 1rem; border: 1px solid var(--border-subtle); border-radius: 12px; background: var(--surface-panel); min-width: 0; } +.history-progress .form-select { margin-bottom: .75rem; } +.history-trend { margin: 1rem 0 0; min-width: 0; } +.history-trend figcaption { font-weight: 700; } +.history-trend svg { width: 100%; height: auto; display: block; } +.trend-date-range { display: flex; justify-content: space-between; gap: .5rem; font-variant-numeric: tabular-nums; } +.history-view .trend-scale, .history-view .trend-date-range { font-size: .85rem; } +.trend-axis { stroke: var(--border-control); vector-effect: non-scaling-stroke; } +.trend-line { vector-effect: non-scaling-stroke; fill: none; stroke: var(--accent); stroke-width: 2; } +.trend-dot { fill: var(--accent); } +.trend-recorded-values li { overflow-wrap: anywhere; font-size: .85rem; } +@media (max-width: 575px) { + .history-filters { align-items: stretch; } + .history-filters > div { flex-basis: 100%; } + .history-day, .history-progress { padding: .75rem; } + .history-exercise { padding: .6rem; } +}