From e3bd365add147c991a05f75d4aa68a26372ad593 Mon Sep 17 00:00:00 2001 From: rob Date: Wed, 11 Nov 2026 14:15:08 +0000 Subject: [PATCH] Complete TASK-005 dated notes and daily body weight --- docs/CURRENT_STATE.md | 15 ++++ docs/DECISIONS.md | 7 ++ docs/HANDOFF.md | 20 +++-- docs/PROJECT_OVERVIEW.md | 4 +- docs/SPEC.md | 12 +++ docs/TASK-005_UI.md | 23 ++++++ docs/TASKS.md | 19 ++++- src/App.jsx | 10 +++ src/WorkoutDetailAsync.test.jsx | 49 +++++++++++++ src/WorkoutDetailEditor.jsx | 71 ++++++++++++++++++ src/WorkoutDetailEditor.test.jsx | 94 ++++++++++++++++++++++++ src/backupStorage.js | 12 ++- src/localDatabase.js | 4 +- src/performanceStorage.test.js | 4 +- src/styles.css | 17 +++++ src/workoutDetailStorage.js | 51 +++++++++++++ src/workoutDetailStorage.test.js | 122 +++++++++++++++++++++++++++++++ 17 files changed, 512 insertions(+), 22 deletions(-) create mode 100644 docs/TASK-005_UI.md create mode 100644 src/WorkoutDetailAsync.test.jsx create mode 100644 src/WorkoutDetailEditor.jsx create mode 100644 src/WorkoutDetailEditor.test.jsx create mode 100644 src/workoutDetailStorage.js create mode 100644 src/workoutDetailStorage.test.js diff --git a/docs/CURRENT_STATE.md b/docs/CURRENT_STATE.md index 900a666..e532b4c 100644 --- a/docs/CURRENT_STATE.md +++ b/docs/CURRENT_STATE.md @@ -9,6 +9,16 @@ Code/configuration take precedence over this summary. +## 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. + +Candidate adds optional session notes by date/period, exercise notes by date/period/exercise and one daily positive decimal kg body-weight value shared across periods. Explicit independent Save; Clear changes only the draft and Save removes the saved value. Plain text max 4000 characters, read/error/retry states, saved/unsaved feedback, context-isolated async read/save behavior. No performance completion or previous-session changes. Optional disclosures preserve dark/compact/responsive conventions, including empty stretch sessions. + +TASK-005 storage is IndexedDB v4, adding workoutDetails while retaining all old records. Backup exports v4 and imports v1–v4 atomically; old-format replacement preserves observations absent from old files. Previous app builds cannot open v4 databases/read v4 backups; no downgrade path claimed. Details/design/decision are in candidate SPEC, TASK-005_UI.md and ADR-022. Integrated home schema is now v4; JSON exports use envelope v4 with v1–v4 imports. + +Fresh validation: 206/206 tests across 18 files with one worker, lint/final build, source preflight 005, context/whitespace and base diff review pass. No independent browser/visual/keyboard pass or runner/browser/server/manual snapshot launch claimed. Captain acceptance is now recorded; no further acceptance gate remains for this candidate. Captain subsequently explicitly instructed “commit and merge”; acceptance alone was not treated as Git authority. Test command and prior evidence remain in HANDOFF. + ## Accepted TASK-019 reconstruction — 2026-11-11 Captain requested finishing TASK-019. New implementation is in persistent `.task-worktrees/task-019`, branch `task/019-previous-availability-rebuild`, based on codex `6ea3f7b`. Status: Complete following Captain acceptance and explicit commit/local codex merge authorization. The original `/tmp` source remains missing; this is a rebuild, not recovery. Captain authorized integration of the candidate into local codex; verify resulting commit/refs with Git. @@ -78,3 +88,8 @@ All available completed application work is integrated in local codex. Every exi ## TASK-019 completion integration — 2026-11-11 Captain explicitly accepted TASK-019 and authorized its commit/local codex merge. The current persistent source contains the validated replacement for the lost implementation. All available completed task application/tooling work is integrated after this merge; no uncommitted candidate work remains. Three safety stashes preserve only duplicate/older tooling/context from earlier integrations, including home's pre-acceptance 019 context. Missing original `/tmp` registrations and all persistent implementation worktrees remain untouched. Earlier audit notes that TASK-019 was missing/rebuild-required are historical and superseded by this accepted reconstruction. Future implementation remains limited to explicitly accepted tasks. + + +## TASK-005 local integration — 2026-11-11 + +Captain authorized committing/merging the accepted TASK-005 candidate. Base be0ff2b; source task/005-notes-bodyweight in persistent .task-worktrees/task-005. All available completed task work is integrated after this merge, with clean source/home expected (verify Git). The pre-merge duplicate home task/current-state/handoff copies are preserved in a fourth named safety stash; no unique implementation is left only in stashes. All original missing /tmp registrations and persistent worktrees remain untouched. No push, deployment or Captain-session cleanup. diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index b52fd90..56dfd1d 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -374,3 +374,10 @@ For exercises with per-side reps or durations, show one measurement input per se ### Compatibility Retain the current left/right storage fields and historical semantics. Explicit edits to the shared input set both values; browsing and untouched Save preserve unequal or partial historical values, displayed as read-only text rather than choosing one silently. No migration or fabricated historical values. + + +## ADR-022: Optional dated notes and daily body weight + +- 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. diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index e1fbb17..fb365f4 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -3,26 +3,24 @@ > Replaceable snapshot; repository code and maintained context take precedence. - Updated: 2026-11-11. -- TASK-019: Complete. Captain explicitly stated “task-019 complete. commit and merge”, accepting the reconstruction and authorizing local integration. -- Source: `.task-worktrees/task-019`, branch `task/019-previous-availability-rebuild`, base codex `6ea3f7b`; target local `codex`. Verify final commit/refs with Git. +- 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. ## Delivered and validated -Previous-session action is offered only for compatible earlier completed data, across regular reps/holds/hang, aggregate EMOM and original minute-history editors. Unknown, empty or failed lookups stay hidden. Shared keyed/cancellable results use the loaded saved definition/format and owning parent context; separate failure/retry preserves typed values. Existing compatibility, explicit click, Save/completion, zero/blank/draft handling, populated-entry protection and historical isolation remain unchanged. +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. -180/180 tests across 15 files pass with `npm test -- --maxWorkers=1`; lint/build, no-launch source preflight, context validation (0 warnings), whitespace and diff review against `6ea3f7b` pass. Includes real IndexedDB read-only/eligibility/data-preservation cases and controlled asynchronous race/retry/parent-context checks. Captain acceptance is recorded without claiming an independent agent browser/console/network review. Application implementation is unchanged during acceptance/commit preparation, so tests are not rerun solely for completion text. +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. -No storage/schema, compatibility-policy, seed/programme, layout/theme or dependency changes. This is a reconstruction, not byte-identical recovery of the missing original source. +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. + +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. ## Git state and retained evidence -TASK-016 dark theme and reconstructed TASK-018 compact inputs were integrated in `0cf0515`; TASK-020 completion in `6ea3f7b`. TASK-019 completion is integrated from its persistent dedicated branch. Home and all persistent task worktrees should be clean; verify Git before new work. - -Three named safety stashes retain duplicate/older context/tooling: home before TASK-016 integration, old TASK-020 worktree copies before reconciliation, and home's pre-acceptance TASK-019 context. They contain no unique pending application changes. Applying them wholesale would reintroduce stale documentation; retain pending Captain cleanup authority. - -Original missing `/tmp` registrations remain prunable evidence. No branches, worktrees, stashes or snapshots are removed, and no Captain testing sessions are stopped. No remote push or deployment. +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. ## Testtask -Captain alone runs/stops real sessions. From project home, `./scripts/testtask.sh 019` selects the persistent 019 source and Node automatically. `--check 019` validates without launch. Snapshots are exact-state test evidence under the source's `.test-worktrees`, never editing sources; completion documentation may require the supported runner to refresh on Captain's next launch. +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. diff --git a/docs/PROJECT_OVERVIEW.md b/docs/PROJECT_OVERVIEW.md index 5c5bd12..1ecd820 100644 --- a/docs/PROJECT_OVERVIEW.md +++ b/docs/PROJECT_OVERVIEW.md @@ -8,11 +8,11 @@ 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. Exercise details expose available 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/progress screens, routine editing, backup interface and offline reload remain separate tasks. SPEC defines behavior and WORKOUT_ROUTINE the authoritative initial programme. ## Technology and architecture -The application foundation now uses React, Vite, and React-Bootstrap. IndexedDB v3 stores the hanging-goal override, legacy strength records and new detailed performance in separate stores behind adapters. JSON backup/import is implemented at adapter level with version validation and atomic transactions; TASK-009 owns its UI. Native IndexedDB is used at runtime; fake-indexeddb is a test-only dependency. The application has no backend, authentication, or cloud dependency. +The application foundation now uses React, Vite, and React-Bootstrap. IndexedDB v4 preserves the hanging-goal override, legacy strength records and detailed performance stores, adding independent workoutDetails records for optional dated notes and body weight behind a storage adapter. JSON backup/import is implemented at adapter level with v4 exports, v1/v2/v3/v4 validation/read compatibility and atomic transactions; TASK-009 owns its UI. Native IndexedDB is used at runtime; fake-indexeddb is a test-only dependency. The application has no backend, authentication, or cloud dependency. The design keeps routine templates, exercise definitions, historical workout records, and UI state separate. The initial routine is bundled as versioned seed data; subsequent user edits are local data and must not be overwritten by updates. A storage adapter separates React components from IndexedDB. A service worker and locally bundled assets are required for offline reload in the release scope. diff --git a/docs/SPEC.md b/docs/SPEC.md index c27a408..32c3bbf 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -354,3 +354,15 @@ Adapter exports now use JSON envelope v3 and continue importing v1/v2 as well as ### TASK-017 side-input correction Every per-side exercise, including Single-arm preacher curls over a chair, uses one Reps (each side) or Seconds (each side) input per set. Entering or clearing the input changes both stored side values together. Equipment inputs and prescription guidance remain unchanged. Existing unequal/partial side values are shown as read-only text with a blank shared replacement input; browsing or untouched Save does not choose a side or rewrite either value. Storage shapes, snapshots and per-side volume semantics remain unchanged. + + +## TASK-005 dated observations contract — 2026-11-11 + +This current contract supersedes earlier database/backup version descriptions for the TASK-005 candidate. Existing performance schemaVersion 1 and all original storage semantics remain unchanged. + +- Session notes are optional plain text by local date and Morning/Afternoon period. Exercise notes are optional plain text by date/period/exercise ID, independent of aggregate/minute/legacy representation. These are dated observations, not permanent exercise-library instructions, per-set/minute notes or automatic previous-session suggestions. Limit 4000 characters; preserve entered text, treating blank/whitespace-only Save as removal. +- Body weight is an optional finite positive decimal kg measurement once per local date, shared across both periods; blank Save removes it. It does not contribute external-load volume and is never copied from targets or previous sessions. +- Each field has an independent explicit Save. Clear edits only its draft; Save confirms removal. Saving observations never saves/completes sets. Navigation follows existing discard-of-unsaved-draft behavior; late reads/save feedback cannot enter another date/period/exercise editor. Read failures disable overwriting and offer retry; write failures preserve drafts. +- 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. diff --git a/docs/TASK-005_UI.md b/docs/TASK-005_UI.md new file mode 100644 index 0000000..6325598 --- /dev/null +++ b/docs/TASK-005_UI.md @@ -0,0 +1,23 @@ +# TASK-005 design and implementation brief + +2026-11-11. Extend the approved dark theme, typography, compact input widths, date/period navigation and workout editors. Captain invoked Frontend UI Design → Webapp Feature and engaged the previously briefed scope: session notes, dated exercise notes, optional daily body weight. + +## Composition + +Routine heading/guidance → collapsed **Session notes and body weight** → existing exercise list. The disclosure remains available on empty stretch sessions. Its contents use existing Bootstrap Form/Button semantics: a labelled optional session-note textarea, and an optional Body weight (kg) field. Desktop/tablet >=768px groups them in two bounded columns; narrow widths stack them with wrapping labels/help/errors. Body weight retains compact 5.25rem numeric sizing. Textareas fill available width, resize vertically and have no horizontal overflow. + +Each exercise card retains current performance editor, goal and exercise-details content. Add a separate collapsed **Your notes** disclosure with a textarea labelled using the exercise name. Notes are dated exercise-session observations, not permanent exercise-library instructions or per-set/minute notes. A single exercise note applies to that date/period/exercise independently of legacy/detailed performance representations. No notes copied by previous-session suggestions. + +## Actions and states + +Each field has its own explicit Save and secondary Clear action. Clear changes only the draft; Save confirms removal. No confirmation modal for editing a single optional field. Plain text, max 4000 characters. Body weight accepts a finite positive decimal number in kg; blank means no measurement, never assumed zero. One body-weight record per date, shared across Morning/Afternoon, no volume contribution. Session notes are separate per date/period; exercise notes additionally by exercise ID. + +Loading disables controls; unavailable/invalid saved data disables Save and offers Retry loading. Validation/write failure retains input and surfaces an associated alert; successful Save announces saved/removed status in that form. Edits announce unsaved changes. Date/period/identity changes remount the owning form to prevent late reads/writes displaying in another context. Navigation follows the existing discard-of-unsaved-draft convention; browsing never writes. Saving notes/body weight never completes or modifies performance records. Persistent controls use visible labels, unique IDs, help/error associations, semantic forms/details/summary, 44px actions, dark native controls and offset keyboard focus. No hover-only actions. + +## Storage and backup handoff + +Add one independent workoutDetails store via additive IndexedDB v4 upgrade; leave all three original stores/records untouched. Records are schemaVersion 1 with explicit kind/date and applicable period/exercise identity; validated keys distinguish session-note, exercise-note and body-weight. Save empty text/weight deletes only that matching optional record. Backup envelope v4 includes this store and continues reading v1/v2/v3. Older envelopes omit it and must not erase it during an old-format replacement. New v4 replacements cover all stores atomically. No import/export UI (TASK-009). + +## Verification + +Automated migration from prior versions, literal old-data preservation, backup round trips/rollback/old imports, input validation, explicit clear/save, save/reload/date/period isolation, empty sessions, read/write failures and late read/save context changes. Full tests (one worker), lint/build, context, whitespace/base-diff and no-launch testtask preflight. Captain alone runs `./scripts/testtask.sh 005` for desktop/320px, keyboard/focus, disclosures and save/reload acceptance. No independent browser pass claimed. diff --git a/docs/TASKS.md b/docs/TASKS.md index 313fe52..92d1cc5 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-005 and TASK-008 are Accepted. 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 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. ### TASK-001: Application foundation and responsive shell @@ -52,7 +52,7 @@ Reconciled with `docs/SPEC.md` and `docs/WORKOUT_ROUTINE.md`. TASK-001–003, TA ### TASK-005: Extended workout recording -- Status: Accepted +- Status: Complete — Captain explicitly stated “task complete” on 2026-11-11, satisfying the acceptance gate. Source `.task-worktrees/task-005`, branch `task/005-notes-bodyweight`, base codex `be0ff2b`. Captain subsequently explicitly authorized “commit and merge”; local codex integration includes the accepted notes/body-weight scope and documentation. - Objective: Extend the initial dated rep/weight records from TASK-014 with other requested performance details while preserving partial and historical records. - Scope: Storage migrations building on the existing hang-goal override and TASK-014 strength entries; additional load variants or counts when needed beyond TASK-014's exercise-specific strength fields; hangs, untimed hold checkoffs, notes, optional body weight, previous-session suggestions, and error states. No timer-derived workout or break duration, per-round EMOM logging, or volume-per-minute rate. - Acceptance criteria: Additional performance details and hang attempts survive reload and remain distinguishable from prescribed targets; multiple hang attempts are distinct; edits/reseeding do not rewrite history; browsing alone writes no workout; storage failures are surfaced. TASK-014's EMOM total, regular per-set reps/weight, and legacy total-weight records remain available. @@ -61,6 +61,8 @@ Reconciled with `docs/SPEC.md` and `docs/WORKOUT_ROUTINE.md`. TASK-001–003, TA - Non-goals: Progress charts, routine editor, backup UI. - Dependencies or blockers: TASK-014 and TASK-015. TASK-015 now owns metadata-driven load/count/side/duration/hang recording, completion and previous-session suggestions. TASK-005 retains notes, optional body weight and other extended recording without duplicating TASK-015. +- Engaged remaining scope: session notes by date/period, dated exercise notes by date/period/exercise and optional body weight once per date (kg, shared across periods). Separate explicit Save/Clear draft actions, additive storage and backup compatibility. Existing recording capabilities are preserved, not rebuilt. UI/contract brief: `docs/TASK-005_UI.md`. + ### TASK-006: Timers during and between exercises - Status: Superseded by TASK-014 @@ -370,3 +372,16 @@ Reconciled with `docs/SPEC.md` and `docs/WORKOUT_ROUTINE.md`. TASK-001–003, TA - TASK-019 completion (2026-11-11): Captain explicitly stated “task-019 complete. commit and merge”, satisfying the acceptance gate and authorizing commit/local codex integration of the validated persistent reconstruction. Existing 180/180 tests across 15 files with one worker, lint/build, source preflight and base diff review remain valid; completion changes only context. No independent agent browser review claimed. All completed available task work is integrated after this merge. Home's duplicate pre-acceptance context is saved in a safety stash rather than overwritten. No push/deploy, worktree/branch/stash removal, registration pruning or Captain-session cleanup authorized. + + +#### TASK-005 implementation evidence — 2026-11-11 + +- Delivered remaining accepted scope: optional date/period session notes, dated exercise observations and optional date-only positive decimal kg body weight shared across periods. Separate optional disclosures/forms reuse the existing dark theme and compact numeric width; explicit Save, Clear-draft/Save removal, unsaved/saved/error/retry states. No note/body-weight action modifies or completes performance. Existing navigation discards unsaved drafts; keyed forms/cancelled reads prevent stale-date/period feedback. +- Additive IndexedDB v4 adds workoutDetails without rewriting goal, legacy or detailed stores. Strict schemaVersion 1 observation validation; JSON v4 export and v1–v4 import. Old-format replacement preserves new observations absent from old files; v4 replacement/import atomicity and rollback tested. Old app builds cannot open the upgraded database/read new backups; no downgrade claimed. No new dependencies. +- UI/design and contract are recorded in TASK-005_UI.md, SPEC's TASK-005 contract and ADR-022. Existing measurement/load/hang/Save/suggestion behavior retained; no history/plan/backup UI, illustration work, timers, programme changes or unrelated refactor. +- Validation: 206/206 tests across 18 files with `npm test -- --maxWorkers=1`, lint, final build, no-launch home `--check 005`, context validation (0 warnings), whitespace and base diff review against `be0ff2b` pass. New tests cover upgrades from older DBs and blocked connections, literal history preservation, valid/invalid input, backup round trips/old imports/rollback, save/clear/reload, isolation, empty sessions, read/write failures and async read/save races. Original storage tests retain preservation checks with v4 expectations. +- Captain alone runs `./scripts/testtask.sh 005`. Desktop/320px, keyboard/focus, disclosures, decimal/native controls, save/reload and period/date isolation require Captain acceptance before Complete. No independent agent browser/console/network pass, runner/server/browser/manual snapshot launch or session cleanup claimed. No task commit/merge/push/deploy authorized. + +- 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. diff --git a/src/App.jsx b/src/App.jsx index 5eb28ce..40b7169 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -4,6 +4,7 @@ import { exerciseDefinitions, initialRoutine } from './data/index.js' import { addCalendarDays, localCalendarDate, localDateKey, prescriptionLabel, restLabel, routineForDate, startOfWeek } from './routineView.js' import HangGoalEditor from './HangGoalEditor.jsx' import PerformanceEditor from './PerformanceEditor.jsx' +import WorkoutDetailEditor from './WorkoutDetailEditor.jsx' import { equipmentLabels } from './performanceModel.js' import { readDailyHangGoal, writeDailyHangGoal } from './hangGoalStorage.js' @@ -59,6 +60,9 @@ function ExerciseList({ exercises, dateKey, period, hangGoalSeconds, hangGoalLoa

Target: {prescriptionLabel(target).replace(/^Goal: /, '')}{isHang ? ' continuous' : ''}

{definition.equipment.map((equipment) => equipmentLabels[equipment]).join(' + ')}{rest ? ` · ${restLabel(rest)}` : ''}

+
Your notes + +
{isHang && }
Exercise details {notes &&

{notes}

} @@ -137,6 +141,12 @@ function RoutineView({ selectedDate, setSelectedDate, period, setPeriod, setActi {session.exercises.length > 0 && {session.exercises.length} exercises} {session.targetEffortRpe &&

Target effort: RPE {session.targetEffortRpe.min}–{session.targetEffortRpe.max} · One round to start; a second round only if recovery remains good.

} +
Session notes and body weight +
+ + +
+
{session.exercises.length > 0 && } diff --git a/src/WorkoutDetailAsync.test.jsx b/src/WorkoutDetailAsync.test.jsx new file mode 100644 index 0000000..01f6996 --- /dev/null +++ b/src/WorkoutDetailAsync.test.jsx @@ -0,0 +1,49 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +const storage = vi.hoisted(() => ({ read: vi.fn(), save: vi.fn() })) +vi.mock('./workoutDetailStorage.js', async (original) => ({ ...await original(), readWorkoutDetail: storage.read, saveWorkoutDetail: storage.save })) +import WorkoutDetailEditor from './WorkoutDetailEditor.jsx' +const identity = { kind: 'session-note', date: '2026-11-11', period: 'morning' } +const props = { identity, label: 'Session notes', saveLabel: 'Save notes', help: 'For this session.' } +function deferred() { let resolve; const promise = new Promise((yes) => { resolve = yes }); return { promise, resolve } } +beforeEach(() => { vi.resetAllMocks(); storage.read.mockResolvedValue(null); storage.save.mockResolvedValue(undefined) }) +afterEach(cleanup) +const field = () => screen.getByRole('textbox') +const ready = () => waitFor(() => expect(field().disabled).toBe(false)) +it('ignores late reads after date navigation', async () => { + const old = deferred(); const next = deferred() + storage.read.mockReturnValueOnce(old.promise).mockReturnValueOnce(next.promise) + const view = render() + view.rerender() + await act(async () => { next.resolve({ text: 'New day' }); await next.promise }) + expect(field().value).toBe('New day') + await act(async () => { old.resolve({ text: 'Old day' }); await old.promise }) + expect(field().value).toBe('New day') + expect(storage.save).not.toHaveBeenCalled() +}) +it('keeps an old in-flight save scoped to its original period without changing the new draft', async () => { + const job = deferred(); storage.save.mockReturnValueOnce(job.promise) + const view = render(); await ready() + fireEvent.change(field(), { target: { value: 'Morning observation' } }) + fireEvent.submit(screen.getByRole('form', { name: props.label })) + fireEvent.submit(screen.getByRole('form', { name: props.label })) + expect(storage.save).toHaveBeenCalledTimes(1) + expect(storage.save).toHaveBeenCalledWith(identity, 'Morning observation') + view.rerender(); await ready() + fireEvent.change(field(), { target: { value: 'Afternoon draft' } }) + await act(async () => { job.resolve(); await job.promise }) + expect(field().value).toBe('Afternoon draft') + expect(screen.getByRole('status').textContent).toBe('Unsaved changes.') +}) +it('keeps a note draft after write failure and retries without another read', async () => { + storage.save.mockRejectedValueOnce(new Error('Quota exceeded')) + render(); await ready() + fireEvent.change(field(), { target: { value: 'Keep my draft' } }) + fireEvent.click(screen.getByRole('button', { name: 'Save notes' })) + await screen.findByRole('alert') + expect(field().value).toBe('Keep my draft') + expect(screen.getByRole('button', { name: 'Save notes' }).disabled).toBe(false) + fireEvent.click(screen.getByRole('button', { name: 'Save notes' })) + await screen.findByText('Session notes saved.') + expect(storage.read).toHaveBeenCalledTimes(1) +}) diff --git a/src/WorkoutDetailEditor.jsx b/src/WorkoutDetailEditor.jsx new file mode 100644 index 0000000..afc2245 --- /dev/null +++ b/src/WorkoutDetailEditor.jsx @@ -0,0 +1,71 @@ +import { useEffect, useId, useRef, useState } from 'react' +import { Button, Form } from 'react-bootstrap' +import { detailKey, noteLimit, readWorkoutDetail, saveWorkoutDetail } from './workoutDetailStorage.js' + +function DetailForm({ identity, label, saveLabel, help }) { + const id = useId() + const key = detailKey(identity) + const weight = identity.kind === 'body-weight' + const [draft, setDraft] = useState('') + const [loading, setLoading] = useState(true) + const [readFailed, setReadFailed] = useState(false) + const [saving, setSaving] = useState(false) + const [retry, setRetry] = useState(0) + const [error, setError] = useState('') + const [notice, setNotice] = useState('') + const active = useRef(false) + const inFlight = useRef(false) + useEffect(() => { + let current = true + active.current = true + setLoading(true); setReadFailed(false); setError('') + readWorkoutDetail(identity).then((record) => { + if (!current) return + setDraft(record ? String(weight ? record.weightKg : record.text) : '') + setLoading(false) + }).catch((failure) => { + if (current) { setReadFailed(true); setError(failure.message); setLoading(false) } + }) + return () => { current = false; active.current = false } + }, [key, retry]) + function change(value) { setDraft(value); setNotice('Unsaved changes.'); setError('') } + async function save(event) { + event.preventDefault() + if (loading || readFailed || inFlight.current) return + const value = weight ? draft.trim() === '' ? null : Number(draft) : draft + if (weight && value !== null && (!Number.isFinite(value) || value <= 0)) { setError('Enter body weight in kg above zero.'); return } + if (!weight && draft.length > noteLimit) { setError(`Use no more than ${noteLimit} characters.`); return } + inFlight.current = true + setSaving(true); setError(''); setNotice('') + try { + await saveWorkoutDetail(identity, value) + if (active.current) { + const empty = weight ? value === null : !draft.trim() + setDraft(empty ? '' : String(value)) + setNotice(empty ? `${label} removed.` : `${label} saved.`) + } + } catch (failure) { if (active.current) setError(failure.message) } + finally { inFlight.current = false; if (active.current) setSaving(false) } + } + const disabled = loading || readFailed || saving + return
+ {label} (optional) + change(event.target.value)} + aria-describedby={`${id}-help${error ? ` ${id}-error` : ''}`} aria-invalid={Boolean(error)} /> +

{help} Clear, then Save to remove a saved value.

+
+ + + {readFailed && } +
+

{loading ? `Loading ${label.toLowerCase()}…` : notice}

+ {error && } + +} + +export default function WorkoutDetailEditor(props) { + // Every identity has independent draft/read/save state, including during navigation. + return +} diff --git a/src/WorkoutDetailEditor.test.jsx b/src/WorkoutDetailEditor.test.jsx new file mode 100644 index 0000000..1d4974c --- /dev/null +++ b/src/WorkoutDetailEditor.test.jsx @@ -0,0 +1,94 @@ +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 WorkoutDetailEditor from './WorkoutDetailEditor.jsx' +import App from './App.jsx' +import { readWorkoutDetail, saveWorkoutDetail } from './workoutDetailStorage.js' +import { exportBackup } from './backupStorage.js' +const identity = { kind: 'session-note', date: '2026-11-11', period: 'morning' } +const noteProps = { identity, label: 'Morning session notes', saveLabel: 'Save session notes', help: 'This session only.' } +const weightProps = { identity: { kind: 'body-weight', date: identity.date }, label: 'Body weight (kg)', saveLabel: 'Save body weight', help: 'Shared across periods.' } +const field = (label) => screen.getByLabelText(label, { exact: false, selector: 'input,textarea' }) +const ready = (label) => waitFor(() => expect(field(label).disabled).toBe(false)) +const fill = (label, value) => fireEvent.change(field(label), { target: { value } }) +beforeEach(() => { vi.stubGlobal('indexedDB', new IDBFactory()); window.localStorage.clear() }) +afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.unstubAllGlobals(); vi.useRealTimers() }) +it.each([noteProps, weightProps])('saves and reloads $label only on explicit Save; Clear remains a draft', async (p) => { + const value = p === noteProps ? 'Felt comfortable\nKeep this context' : '73.25' + const before = await exportBackup() + const view = render(); await ready(p.label) + fill(p.label, value) + expect(await exportBackup()).toBe(before) + fireEvent.click(screen.getByRole('button', { name: p.saveLabel })) + await screen.findByText(`${p.label} saved.`) + view.unmount(); render(); await ready(p.label) + expect(field(p.label).value).toBe(value) + fireEvent.click(screen.getByRole('button', { name: 'Clear', exact: true })) + expect(await readWorkoutDetail(p.identity)).not.toBeNull() + fireEvent.click(screen.getByRole('button', { name: p.saveLabel })) + await screen.findByText(`${p.label} removed.`) + expect(await readWorkoutDetail(p.identity)).toBeNull() +}) +it('rejects zero weight and preserves typed input after a failed save', async () => { + render(); await ready(weightProps.label) + fill(weightProps.label, '0') + fireEvent.click(screen.getByRole('button', { name: 'Save body weight' })) + await screen.findByText('Enter body weight in kg above zero.') + expect(await readWorkoutDetail(weightProps.identity)).toBeNull() + fill(weightProps.label, '73.5') + vi.spyOn(indexedDB, 'open').mockImplementation(() => { throw new Error('Write unavailable') }) + fireEvent.click(screen.getByRole('button', { name: 'Save body weight' })) + await screen.findByText('Write unavailable') + expect(field(weightProps.label).value).toBe('73.5') + expect(screen.queryByText(/saved\./)).toBeNull() +}) +it('offers recovery after an unavailable read without enabling overwrite', async () => { + vi.stubGlobal('indexedDB', undefined) + render() + await screen.findByRole('alert') + expect(screen.getByRole('button', { name: 'Save session notes' }).disabled).toBe(true) + vi.stubGlobal('indexedDB', new IDBFactory()) + fireEvent.click(screen.getByRole('button', { name: 'Retry loading' })); await ready(noteProps.label) + expect(screen.queryByRole('alert')).toBeNull() +}) +it('isolates note drafts across date and period changes', async () => { + await saveWorkoutDetail(identity, 'Saved morning') + const view = render(); await ready(noteProps.label) + fill(noteProps.label, 'Unsaved morning') + view.rerender() + await ready('Afternoon session notes') + expect(field(/Afternoon session notes/).value).toBe('') + view.rerender(); await ready(noteProps.label) + expect(field(/Morning session notes/).value).toBe('Saved morning') +}) +it('integrates notes on empty sessions and shares body weight across periods without creating performance', async () => { + vi.useFakeTimers({ toFake: ['Date'] }); vi.setSystemTime(new Date(2026, 10, 9, 12)) + render() + expect(screen.getByText('Full body stretch routine')).toBeTruthy() + const session = screen.getByText('Session notes and body weight').closest('details') + session.open = true + await ready('Morning session notes'); await ready('Body weight (kg)') + fill('Morning session notes', 'Easy stretch'); fill('Body weight (kg)', '74.2') + fireEvent.click(within(session).getByRole('button', { name: 'Save session notes' })) + await screen.findByText('Morning session notes saved.') + fireEvent.click(within(session).getByRole('button', { name: 'Save body weight' })) + await screen.findByText('Body weight (kg) saved.') + fireEvent.click(screen.getByRole('button', { name: 'Afternoon', exact: true })) + await ready('Afternoon session notes') + expect(field(/Afternoon session notes/).value).toBe('') + expect(field(/Body weight \(kg\)/).value).toBe('74.2') + const exercise = screen.getByText('Daily hanging practice').closest('.exercise-card') + within(exercise).getByText('Your notes').closest('details').open = true + await ready('Daily hanging practice notes') + fill('Daily hanging practice notes', 'Grip felt good') + fireEvent.click(within(exercise).getByRole('button', { name: 'Save exercise notes' })) + await screen.findByText('Daily hanging practice notes saved.') + const backup = JSON.parse(await exportBackup()) + expect(backup.stores.performanceEntries).toEqual([]) + expect(backup.stores.strengthEntries).toEqual([]) + expect(backup.stores.workoutDetails).toHaveLength(3) + fireEvent.click(screen.getByRole('button', { name: 'Next week' })) + await ready('Afternoon session notes'); await ready('Body weight (kg)') + expect(field(/Body weight \(kg\)/).value).toBe('') + expect(field(/Afternoon session notes/).value).toBe('') +}) diff --git a/src/backupStorage.js b/src/backupStorage.js index 38606f7..3812062 100644 --- a/src/backupStorage.js +++ b/src/backupStorage.js @@ -3,8 +3,9 @@ import { initialRoutine, exerciseDefinitions } from './data/index.js' import { openLocalDatabase } from './localDatabase.js' import { performanceError } from './performanceModel.js' import { performanceKey } from './performanceStorage.js' +import { detailError, detailKey } from './workoutDetailStorage.js' import { validEntry } from './strengthStorage.js' -const stores = ['routineOverrides', 'strengthEntries', 'performanceEntries'] +const stores = ['routineOverrides', 'strengthEntries', 'performanceEntries', 'workoutDetails'] function validJSON(value) { if (value === null || typeof value === 'string' || typeof value === 'boolean') return true @@ -15,16 +16,19 @@ export function parseBackup(input) { let backup try { backup = typeof input === 'string' ? JSON.parse(input) : structuredClone(input) } catch { throw new Error('Invalid backup JSON.') } - if (backup?.format !== 'workout-tracker' || ![1, 2, 3].includes(backup.version) || !backup.stores || typeof backup.stores !== 'object' || Array.isArray(backup.stores)) throw new Error('Unsupported backup schema.') + if (backup?.format !== 'workout-tracker' || ![1, 2, 3, 4].includes(backup.version) || !backup.stores || typeof backup.stores !== 'object' || Array.isArray(backup.stores)) throw new Error('Unsupported backup schema.') if (Object.keys(backup.stores).some((store) => !stores.includes(store))) throw new Error('Unsupported backup store.') + if (backup.version < 4 && Object.hasOwn(backup.stores, 'workoutDetails')) throw new Error('Unsupported backup store for this version.') // Version 1 is the legacy adapter envelope with the two original stores. for (const store of stores) { + if (store === 'workoutDetails' && backup.version < 4) continue if (backup.version === 1 && store === 'performanceEntries' && backup.stores[store] == null) backup.stores[store] = [] if (!Array.isArray(backup.stores[store])) throw new Error(`Missing backup store: ${store}.`) const keys = new Set() for (const entry of backup.stores[store]) { if (!entry || typeof entry.key !== 'string' || keys.has(entry.key) || !validJSON(entry.value)) throw new Error('Invalid or duplicate backup entry.') keys.add(entry.key) + if (store === 'workoutDetails' && (detailError(entry.value) || entry.key !== detailKey(entry.value))) throw new Error('Invalid notes or body-weight entry.') if (store === 'strengthEntries' && (!/^\d{4}-\d{2}-\d{2}:.+/.test(entry.key) || !validEntry(entry.value))) throw new Error('Invalid legacy strength entry.') if (store === 'performanceEntries' && (performanceError(entry.value) || entry.key !== performanceKey(entry.value.date, entry.value.period, entry.value.exerciseId, entry.value.format))) throw new Error('Invalid detailed performance entry.') if (store === 'routineOverrides' && entry.key === 'dailyHangGoalSec' && (!Number.isSafeInteger(entry.value) || entry.value <= 0)) throw new Error('Invalid hanging goal.') @@ -43,7 +47,7 @@ export async function exportBackup() { if (cursor.result) { data[name].push({ key: cursor.result.key, value: cursor.result.value }); cursor.result.continue() } } } - tx.oncomplete = () => { db.close(); resolve(JSON.stringify({ format: 'workout-tracker', version: 3, reference: { exerciseDefinitions, initialRoutine }, stores: data })) } + tx.oncomplete = () => { db.close(); resolve(JSON.stringify({ format: 'workout-tracker', version: 4, reference: { exerciseDefinitions, initialRoutine }, stores: data })) } tx.onerror = tx.onabort = () => { db.close(); reject(new Error('Could not export local data.')) } }) } @@ -54,6 +58,8 @@ export async function importBackup(input, { replace = false } = {}) { const tx = db.transaction(stores, 'readwrite') try { for (const name of stores) { + // Old backups never represented observations; replacing them must not erase new data. + if (name === 'workoutDetails' && backup.version < 4) continue const store = tx.objectStore(name) if (replace) store.clear() for (const { key, value } of backup.stores[name]) store.add(value, key) diff --git a/src/localDatabase.js b/src/localDatabase.js index d004a32..5e9af1d 100644 --- a/src/localDatabase.js +++ b/src/localDatabase.js @@ -1,5 +1,5 @@ const DATABASE_NAME = 'workout-tracker' -const DATABASE_VERSION = 3 +const DATABASE_VERSION = 4 export function openLocalDatabase() { return new Promise((resolve, reject) => { @@ -15,7 +15,7 @@ export function openLocalDatabase() { const store = request.result.createObjectStore('performanceEntries') store.createIndex('exercisePeriodFormat', ['exerciseId', 'period', 'format']) } - for (const store of ['routineOverrides', 'strengthEntries']) { + for (const store of ['routineOverrides', 'strengthEntries', 'workoutDetails']) { if (!request.result.objectStoreNames.contains(store)) request.result.createObjectStore(store) } } diff --git a/src/performanceStorage.test.js b/src/performanceStorage.test.js index 9699b6f..20a3fa3 100644 --- a/src/performanceStorage.test.js +++ b/src/performanceStorage.test.js @@ -31,8 +31,8 @@ function seedDatabase(version) { it.each([1, 2])('upgrades v%i additively and preserves existing data verbatim', async (version) => { await seedDatabase(version) const db = await openLocalDatabase() - expect(db.version).toBe(3) - expect([...db.objectStoreNames]).toEqual(['performanceEntries', 'routineOverrides', 'strengthEntries']) + expect(db.version).toBe(4) + expect([...db.objectStoreNames]).toEqual(['performanceEntries', 'routineOverrides', 'strengthEntries', 'workoutDetails']) expect(db.transaction('performanceEntries').objectStore('performanceEntries').indexNames.contains('exercisePeriodFormat')).toBe(true) db.close() expect(await readDailyHangGoal()).toBe(180) diff --git a/src/styles.css b/src/styles.css index faee7c3..39398b5 100644 --- a/src/styles.css +++ b/src/styles.css @@ -234,3 +234,20 @@ h1 { margin: .25rem 0 .55rem; font-size: clamp(2.2rem, 4vw, 3.25rem); line-heigh } .strength-actions, .strength-fields, .strength-set { flex-wrap: wrap; } .performance-head span, .performance-row label, .emom-total-fields label { overflow-wrap: anywhere; } + +/* TASK-005 optional observations extend the existing disclosure/form language. */ +.workout-details { margin-top: .8rem; border-top: 1px solid var(--border-subtle); font-size: .85rem; overflow-wrap: anywhere; } +.workout-details summary { padding-block: .65rem; color: var(--accent); cursor: pointer; } +.session-detail-fields { display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 1fr); gap: 1rem; } +.workout-detail-form { min-width: 0; padding-block: .4rem; } +.workout-detail-form .form-label { color: var(--text-secondary); font-weight: 650; } +.workout-detail-form .form-control { min-height: 44px; background: var(--surface-input); color: var(--text-primary); border-color: var(--border-control); } +.workout-detail-form textarea { resize: vertical; } +.workout-detail-form .body-weight-input { width: var(--numeric-width); max-width: 100%; padding: .3rem .4rem; font-variant-numeric: tabular-nums; } +.workout-detail-form .form-control:disabled { background: var(--surface-panel); color: var(--text-secondary); } +.workout-detail-form .form-control:focus-visible, .workout-details summary:focus-visible { outline: 3px solid var(--focus); outline-offset: 3px; box-shadow: none; } +.optional-field, .detail-help, .detail-status { color: var(--text-secondary); font-size: .8rem; } +.detail-help, .detail-status { margin: .4rem 0; } +.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); } } diff --git a/src/workoutDetailStorage.js b/src/workoutDetailStorage.js new file mode 100644 index 0000000..db462a9 --- /dev/null +++ b/src/workoutDetailStorage.js @@ -0,0 +1,51 @@ +import { openLocalDatabase } from './localDatabase.js' +import { validDate } from './performanceModel.js' + +export const noteLimit = 4000 +export function detailKey({ kind, date, period, exerciseId }) { + if (!validDate(date)) throw new Error('Invalid observation date.') + if (kind === 'body-weight') return `${date}:body-weight` + if (!['morning', 'afternoon'].includes(period)) throw new Error('Invalid observation period.') + if (kind === 'session-note') return `${date}:${period}:session-note` + if (kind === 'exercise-note' && typeof exerciseId === 'string' && /^[a-z0-9][a-z0-9-]*$/.test(exerciseId)) return `${date}:${period}:${exerciseId}:exercise-note` + throw new Error('Invalid observation identity.') +} +export function detailError(record) { + try { detailKey(record) } catch { return 'Invalid observation identity.' } + if (record.schemaVersion !== 1) return 'Unsupported observation schema.' + const weight = record.kind === 'body-weight' + const keys = ['schemaVersion', 'kind', 'date', ...(weight ? ['weightKg'] : ['period', 'text', ...(record.kind === 'exercise-note' ? ['exerciseId'] : [])])] + if (Object.keys(record).length !== keys.length || Object.keys(record).some((key) => !keys.includes(key))) return 'Invalid observation fields.' + if (weight) { + if (typeof record.weightKg !== 'number' || !Number.isFinite(record.weightKg) || record.weightKg <= 0) return 'Enter body weight in kg above zero.' + } else if (typeof record.text !== 'string' || !record.text.trim() || record.text.length > noteLimit) return `Enter a note of up to ${noteLimit} characters.` + return null +} +async function transact(mode, action) { + const db = await openLocalDatabase() + return new Promise((resolve, reject) => { + const tx = db.transaction('workoutDetails', mode) + let value + try { + const request = action(tx.objectStore('workoutDetails')) + request.onsuccess = () => { value = request.result } + } catch { tx.abort() } + tx.oncomplete = () => { db.close(); resolve(value ?? null) } + tx.onerror = tx.onabort = () => { db.close(); reject(new Error('Could not access notes or body weight. Your changes were not saved.')) } + }) +} +export async function readWorkoutDetail(identity) { + const key = detailKey(identity) + const record = await transact('readonly', (store) => store.get(key)) + if (record !== null && (detailError(record) || detailKey(record) !== key)) throw new Error('Saved notes or body weight are invalid or unsupported. Your saved data was not changed.') + return record +} +export async function saveWorkoutDetail(identity, value) { + const key = detailKey(identity) + const empty = identity.kind === 'body-weight' ? value === null : typeof value === 'string' && !value.trim() + if (empty) { await transact('readwrite', (store) => store.delete(key)); return } + const record = { schemaVersion: 1, ...identity, ...(identity.kind === 'body-weight' ? { weightKg: value } : { text: value }) } + const error = detailError(record) + if (error) throw new Error(error) + await transact('readwrite', (store) => store.put(record, key)) +} diff --git a/src/workoutDetailStorage.test.js b/src/workoutDetailStorage.test.js new file mode 100644 index 0000000..417fa2b --- /dev/null +++ b/src/workoutDetailStorage.test.js @@ -0,0 +1,122 @@ +import { IDBFactory } from 'fake-indexeddb' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { detailKey, readWorkoutDetail, saveWorkoutDetail } from './workoutDetailStorage.js' +import { exportBackup, importBackup, parseBackup } from './backupStorage.js' +import { openLocalDatabase } from './localDatabase.js' +import { newPerformance } from './performanceModel.js' +import { exerciseDefinitions } from './data/index.js' + +const day = '2026-11-11' +const identities = [ + [{ kind: 'session-note', date: day, period: 'morning' }, 'Session observation'], + [{ kind: 'exercise-note', date: day, period: 'morning', exerciseId: 'front-plank' }, 'Use a mat'], + [{ kind: 'body-weight', date: day }, 73.25], +] +beforeEach(() => vi.stubGlobal('indexedDB', new IDBFactory())) +afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals() }) +it.each(identities)('saves, reloads and explicitly clears $kind observations only', async (identity, value) => { + const before = await exportBackup() + expect(await readWorkoutDetail(identity)).toBeNull() + expect(await exportBackup()).toBe(before) + await saveWorkoutDetail(identity, value) + expect(await readWorkoutDetail(identity)).toEqual({ schemaVersion: 1, ...identity, ...(identity.kind === 'body-weight' ? { weightKg: value } : { text: value }) }) + expect(await readWorkoutDetail({ ...identity, date: '2026-11-12' })).toBeNull() + if (identity.period) expect(await readWorkoutDetail({ ...identity, period: 'afternoon' })).toBeNull() + if (identity.exerciseId) expect(await readWorkoutDetail({ ...identity, exerciseId: 'side-plank' })).toBeNull() + await saveWorkoutDetail(identity, identity.kind === 'body-weight' ? null : '') + expect(await exportBackup()).toBe(before) +}) +it.each([0, -1, NaN, Infinity, '73', undefined])('rejects invalid body weight %s without mutation', async (value) => { + const [identity] = identities[2] + await saveWorkoutDetail(identity, 70) + const before = await exportBackup() + await expect(saveWorkoutDetail(identity, value)).rejects.toThrow() + expect(await exportBackup()).toBe(before) +}) +it('rejects invalid notes, identities and corrupt saved observations', async () => { + await expect(saveWorkoutDetail(identities[0][0], 'x'.repeat(4001))).rejects.toThrow(/4000/) + await expect(saveWorkoutDetail({ ...identities[0][0], date: '2026-02-30' }, 'x')).rejects.toThrow(/date/) + await expect(saveWorkoutDetail({ ...identities[0][0], period: 'night' }, 'x')).rejects.toThrow(/period/) + await expect(saveWorkoutDetail({ ...identities[1][0], exerciseId: 'bad:id' }, 'x')).rejects.toThrow(/identity/) + const db = await openLocalDatabase() + await new Promise((resolve) => { + const tx = db.transaction('workoutDetails', 'readwrite') + tx.objectStore('workoutDetails').put(false, detailKey(identities[0][0])) + tx.oncomplete = resolve + }) + db.close() + await expect(readWorkoutDetail(identities[0][0])).rejects.toThrow(/invalid or unsupported/) +}) +it('upgrades a v3 database without changing original goals, legacy or detailed records', async () => { + const definition = exerciseDefinitions.find((d) => d.id === 'pull-up') + const performance = newPerformance(day, 'morning', definition, { kind: 'emom', rounds: 10 }, 'emom-total') + performance.rows[0] = { values: { reps: 35 }, load: { vestKg: 6 }, completed: true } + const legacy = { kind: 'emom', totalReps: 33, externalKg: 8 } + await new Promise((resolve, reject) => { + const request = indexedDB.open('workout-tracker', 3) + request.onupgradeneeded = () => { + request.result.createObjectStore('routineOverrides').put(180, 'dailyHangGoalSec') + request.result.createObjectStore('strengthEntries').put(legacy, `${day}:pull-up`) + const store = request.result.createObjectStore('performanceEntries') + store.createIndex('exercisePeriodFormat', ['exerciseId', 'period', 'format']) + store.put(performance, `${day}:morning:pull-up:emom-total`) + } + request.onsuccess = () => { request.result.close(); resolve() } + request.onerror = () => reject(request.error) + }) + await readWorkoutDetail(identities[0][0]) + const db = await openLocalDatabase(); expect(db.version).toBe(4); db.close() + const backup = JSON.parse(await exportBackup()) + expect(backup.stores.routineOverrides).toEqual([{ key: 'dailyHangGoalSec', value: 180 }]) + expect(backup.stores.strengthEntries).toEqual([{ key: `${day}:pull-up`, value: legacy }]) + expect(backup.stores.performanceEntries).toEqual([{ key: `${day}:morning:pull-up:emom-total`, value: performance }]) + expect(backup.stores.workoutDetails).toEqual([]) +}) +it('round trips v4 observations and rejects a duplicate import atomically', async () => { + for (const [identity, value] of identities) await saveWorkoutDetail(identity, value) + const before = await exportBackup() + expect(JSON.parse(before).version).toBe(4) + vi.stubGlobal('indexedDB', new IDBFactory()) + await importBackup(before) + expect(await exportBackup()).toBe(before) + const duplicate = JSON.parse(before) + duplicate.stores.routineOverrides.push({ key: 'dailyHangGoalSec', value: 999 }) + await expect(importBackup(duplicate)).rejects.toThrow(/Import failed/) + expect(await exportBackup()).toBe(before) +}) +it.each([1, 2, 3])('imports old v%i backups without erasing new observations even with replacement', async (version) => { + for (const [identity, value] of identities) await saveWorkoutDetail(identity, value) + const prior = JSON.parse(await exportBackup()).stores.workoutDetails + const backup = { format: 'workout-tracker', version, stores: { routineOverrides: [], strengthEntries: [], ...(version > 1 ? { performanceEntries: [] } : {}) } } + await importBackup(backup, { replace: true }) + expect(JSON.parse(await exportBackup()).stores.workoutDetails).toEqual(prior) +}) +it('replaces observations explicitly with v4 and validates every incoming record before mutation', async () => { + await saveWorkoutDetail(...identities[0]) + const backup = JSON.parse(await exportBackup()) + backup.stores.workoutDetails = [{ key: detailKey(identities[2][0]), value: { schemaVersion: 1, ...identities[2][0], weightKg: 72 } }] + await importBackup(backup, { replace: true }) + expect(await readWorkoutDetail(identities[0][0])).toBeNull() + const before = await exportBackup() + for (const mutate of [ + (b) => { b.version = 999 }, + (b) => { b.stores.workoutDetails[0].value.weightKg = -1 }, + (b) => { b.stores.workoutDetails[0].key = 'wrong-key' }, + (b) => { b.stores.workoutDetails[0].value.schemaVersion = 2 }, + (b) => { b.stores.workoutDetails.push(b.stores.workoutDetails[0]) }, + (b) => { delete b.stores.workoutDetails }, + ]) { + const invalid = JSON.parse(before); mutate(invalid) + await expect(importBackup(invalid, { replace: true })).rejects.toThrow() + expect(await exportBackup()).toBe(before) + } + const badNote = JSON.parse(before) + badNote.stores.workoutDetails[0] = { key: detailKey(identities[0][0]), value: { schemaVersion: 1, ...identities[0][0], text: 'x'.repeat(4001) } } + expect(() => parseBackup(badNote)).toThrow(/notes/) +}) +it('reports a blocked upgrade and succeeds after the old connection closes', async () => { + const old = await new Promise((resolve) => { const request = indexedDB.open('workout-tracker', 3); request.onsuccess = () => resolve(request.result) }) + await expect(readWorkoutDetail(identities[0][0])).rejects.toThrow(/blocked/) + old.close() + expect(await readWorkoutDetail(identities[0][0])).toBeNull() +})