From f1c72e2cda1a1bcaf712eabda21a6a955f55c40b Mon Sep 17 00:00:00 2001 From: Devasy Patel <110348311+Devasy23@users.noreply.github.com> Date: Sat, 11 Jul 2026 19:15:00 +0530 Subject: [PATCH 01/14] feat: add localized summaries, app metadata, and signing block information to F-Droid repository data --- workout-logger/android/app/build.gradle.kts | 11 +++++------ workout-logger/android/gradle.properties | 4 ++++ .../android/gradle/wrapper/gradle-wrapper.properties | 2 +- workout-logger/android/settings.gradle.kts | 4 ++-- workout-logger/pubspec.yaml | 2 +- 5 files changed, 13 insertions(+), 10 deletions(-) diff --git a/workout-logger/android/app/build.gradle.kts b/workout-logger/android/app/build.gradle.kts index 32e478b..5d35df6 100644 --- a/workout-logger/android/app/build.gradle.kts +++ b/workout-logger/android/app/build.gradle.kts @@ -9,17 +9,16 @@ plugins { android { namespace = "com.devasy.repforge" - compileSdk = 36 - compileSdkExtension = 19 + compileSdk = 37 ndkVersion = flutter.ndkVersion compileOptions { - sourceCompatibility = JavaVersion.VERSION_11 - targetCompatibility = JavaVersion.VERSION_11 + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 } kotlinOptions { - jvmTarget = JavaVersion.VERSION_11.toString() + jvmTarget = JavaVersion.VERSION_17.toString() } // Strip AGP's "Dependency metadata" signing block from the APK. It embeds a @@ -53,7 +52,7 @@ android { // supported. If downgrading, remove the health_connector dependency and // all HealthConnectService usages, then restore minSdk to flutter.minSdkVersion. minSdk = 26 - targetSdk = 36 + targetSdk = 37 versionCode = flutter.versionCode versionName = flutter.versionName // App display name; overridden per build type below so debug installs diff --git a/workout-logger/android/gradle.properties b/workout-logger/android/gradle.properties index f018a61..aae5292 100644 --- a/workout-logger/android/gradle.properties +++ b/workout-logger/android/gradle.properties @@ -1,3 +1,7 @@ org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError android.useAndroidX=true android.enableJetifier=true +# This builtInKotlin flag was added automatically by Flutter migrator +android.builtInKotlin=true +# This newDsl flag was added automatically by Flutter migrator +android.newDsl=true diff --git a/workout-logger/android/gradle/wrapper/gradle-wrapper.properties b/workout-logger/android/gradle/wrapper/gradle-wrapper.properties index ac3b479..f587a47 100644 --- a/workout-logger/android/gradle/wrapper/gradle-wrapper.properties +++ b/workout-logger/android/gradle/wrapper/gradle-wrapper.properties @@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.1-all.zip diff --git a/workout-logger/android/settings.gradle.kts b/workout-logger/android/settings.gradle.kts index fb605bc..ca7fe06 100644 --- a/workout-logger/android/settings.gradle.kts +++ b/workout-logger/android/settings.gradle.kts @@ -19,8 +19,8 @@ pluginManagement { plugins { id("dev.flutter.flutter-plugin-loader") version "1.0.0" - id("com.android.application") version "8.9.1" apply false - id("org.jetbrains.kotlin.android") version "2.1.0" apply false + id("com.android.application") version "8.11.1" apply false + id("org.jetbrains.kotlin.android") version "2.2.20" apply false } include(":app") diff --git a/workout-logger/pubspec.yaml b/workout-logger/pubspec.yaml index 4ca30f0..09504d1 100644 --- a/workout-logger/pubspec.yaml +++ b/workout-logger/pubspec.yaml @@ -20,7 +20,7 @@ version: 2.0.6+27 environment: sdk: ^3.11.4 - flutter: 3.41.6 + flutter: 3.44.4 # Dependencies specify other packages that your package needs in order to work. # To automatically upgrade your package dependencies to the latest versions From b47288efc3d82ba7aef2f0f94386fa80b81ccdad Mon Sep 17 00:00:00 2001 From: Devasy Patel <110348311+Devasy23@users.noreply.github.com> Date: Sun, 12 Jul 2026 01:11:40 +0530 Subject: [PATCH 02/14] =?UTF-8?q?chore:=20upgrade=20Android=20SDK=2016?= =?UTF-8?q?=E2=86=9217,=20Java=2011=E2=86=9217,=20Gradle/AGP/Kotlin=20tool?= =?UTF-8?q?chain?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - compileSdk + targetSdk: 36 → 37 (Android 17 / API 37) - Removed compileSdkExtension (not needed for base API 37) - Java source/target compatibility: VERSION_11 → VERSION_17 - Kotlin jvmTarget: 11 → 17 - Gradle wrapper: 8.12 → 8.14.1 - AGP: 8.9.1 → 8.11.1 - Kotlin Gradle Plugin: 2.1.0 → 2.2.20 - Enable android.builtInKotlin=true + android.newDsl=true - Remove explicit id(kotlin-android) plugin (now injected by Flutter) --- workout-logger/android/app/build.gradle.kts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/workout-logger/android/app/build.gradle.kts b/workout-logger/android/app/build.gradle.kts index 5d35df6..7a5cd0e 100644 --- a/workout-logger/android/app/build.gradle.kts +++ b/workout-logger/android/app/build.gradle.kts @@ -2,8 +2,8 @@ import com.android.build.gradle.internal.api.ApkVariantOutputImpl plugins { id("com.android.application") - id("kotlin-android") - // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + // kotlin-android is injected automatically by Flutter's built-in Kotlin support. + // (android.builtInKotlin=true in gradle.properties) id("dev.flutter.flutter-gradle-plugin") } From 5f606b259287cd6a4c7ed11cb0171dd3b8f27eae Mon Sep 17 00:00:00 2001 From: Devasy Patel <110348311+Devasy23@users.noreply.github.com> Date: Sun, 12 Jul 2026 01:12:55 +0530 Subject: [PATCH 03/14] chore: update pubspec.lock (transitive dependency bumps) --- workout-logger/pubspec.lock | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/workout-logger/pubspec.lock b/workout-logger/pubspec.lock index a22582b..13f55a9 100644 --- a/workout-logger/pubspec.lock +++ b/workout-logger/pubspec.lock @@ -540,10 +540,10 @@ packages: dependency: transitive description: name: meta - sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394" + sha256: "1741988757a65eb6b36abe716829688cf01910bbf91c34354ff7ec1c3de2b349" url: "https://pub.dev" source: hosted - version: "1.17.0" + version: "1.18.0" mime: dependency: transitive description: @@ -841,10 +841,10 @@ packages: dependency: transitive description: name: test_api - sha256: "8161c84903fd860b26bfdefb7963b3f0b68fee7adea0f59ef805ecca346f0c7a" + sha256: "949a932224383300f01be9221c39180316445ecb8e7547f70a41a35bf421fb9e" url: "https://pub.dev" source: hosted - version: "0.7.10" + version: "0.7.11" tuple: dependency: transitive description: @@ -1007,4 +1007,4 @@ packages: version: "3.1.3" sdks: dart: ">=3.11.4 <4.0.0" - flutter: "3.41.6" + flutter: "3.44.4" From a02998835197ab0a2bd22720fcce857264185812 Mon Sep 17 00:00:00 2001 From: Devasy Patel <110348311+Devasy23@users.noreply.github.com> Date: Wed, 15 Jul 2026 21:23:54 +0530 Subject: [PATCH 04/14] chore: update repo name and username references to RepForge and Devasy --- README.md | 14 +++++++------- .../metadata/android/en-US/full_description.txt | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 6662424..794e74a 100644 --- a/README.md +++ b/README.md @@ -6,9 +6,9 @@

Flutter Badge Dart Badge - Stars Badge - Forks Badge - Issues Badge + Stars Badge + Forks Badge + Issues Badge License Badge

@@ -49,8 +49,8 @@ Want to take RepForge for a spin or contribute? Follow these steps to build the 1. **Clone the repository:** ```bash - git clone https://github.com/Devasy23/Workout-logger.git - cd Workout-logger/workout-logger + git clone https://github.com/Devasy/RepForge.git + cd RepForge/workout-logger ``` 2. **Install dependencies:** @@ -84,7 +84,7 @@ We believe in the power of open-source! Whether you want to fix a bug, add a fea 5. Open a **Pull Request** and describe your changes. ### What to work on? -Check out the **[Issues](https://github.com/Devasy23/Workout-logger/issues)** tab! If you have a new idea, feel free to open a new issue for a feature request or bug report before starting your work. Whether it's a UI tweak, performance upgrade, or a brand new workout mode, we'd love to see it! +Check out the **[Issues](https://github.com/Devasy/RepForge/issues)** tab! If you have a new idea, feel free to open a new issue for a feature request or bug report before starting your work. Whether it's a UI tweak, performance upgrade, or a brand new workout mode, we'd love to see it! ### Development Guidelines - Follow standard Flutter and Dart formatting (`flutter format .`). @@ -101,7 +101,7 @@ This project is a personal workout tracking application. **Devasy Patel** - Email: patel.devasy.23@gmail.com -- GitHub: [@Devasy23](https://github.com/Devasy23) +- GitHub: [@Devasy](https://github.com/Devasy) ---
diff --git a/workout-logger/fastlane/metadata/android/en-US/full_description.txt b/workout-logger/fastlane/metadata/android/en-US/full_description.txt index 72e44bb..97cb3aa 100644 --- a/workout-logger/fastlane/metadata/android/en-US/full_description.txt +++ b/workout-logger/fastlane/metadata/android/en-US/full_description.txt @@ -20,4 +20,4 @@ RepForge is fully offline by default. The optional AI Coach feature sends data t LICENSE -Apache-2.0. Source code: https://github.com/Devasy23/Workout-logger \ No newline at end of file +Apache-2.0. Source code: https://github.com/Devasy/RepForge \ No newline at end of file From dbe4352baba882516063be3e0c63fe9eb667895f Mon Sep 17 00:00:00 2001 From: Devasy Patel <110348311+Devasy23@users.noreply.github.com> Date: Wed, 15 Jul 2026 21:25:24 +0530 Subject: [PATCH 05/14] upadtes the build gradle kts file to match the review comment --- workout-logger/android/app/build.gradle.kts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/workout-logger/android/app/build.gradle.kts b/workout-logger/android/app/build.gradle.kts index 7a5cd0e..3c71d30 100644 --- a/workout-logger/android/app/build.gradle.kts +++ b/workout-logger/android/app/build.gradle.kts @@ -17,8 +17,10 @@ android { targetCompatibility = JavaVersion.VERSION_17 } - kotlinOptions { - jvmTarget = JavaVersion.VERSION_17.toString() + kotlin { + compilerOptions { + jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17 + } } // Strip AGP's "Dependency metadata" signing block from the APK. It embeds a From d8a85e6d15d0ce333dc6ba1b223d1ac43bd3f05d Mon Sep 17 00:00:00 2001 From: Devasy Patel <110348311+Devasy23@users.noreply.github.com> Date: Wed, 15 Jul 2026 22:56:48 +0530 Subject: [PATCH 06/14] Adds pubspec yaml --- workout-logger/pubspec.lock | 144 ++++++++++++++++++------------------ workout-logger/pubspec.yaml | 10 +-- 2 files changed, 77 insertions(+), 77 deletions(-) diff --git a/workout-logger/pubspec.lock b/workout-logger/pubspec.lock index 13f55a9..37ce1e9 100644 --- a/workout-logger/pubspec.lock +++ b/workout-logger/pubspec.lock @@ -5,18 +5,18 @@ packages: dependency: transitive description: name: _fe_analyzer_shared - sha256: "8d7ff3948166b8ec5da0fbb5962000926b8e02f2ed9b3e51d1738905fbd4c98d" + sha256: cd6add6f846f35fb79f3c315296703c1a24f3cfd7f4739d91a74961c1c7e9f1b url: "https://pub.dev" source: hosted - version: "93.0.0" + version: "100.0.0" analyzer: dependency: transitive description: name: analyzer - sha256: de7148ed2fcec579b19f122c1800933dfa028f6d9fd38a152b04b1516cec120b + sha256: "6ba98576948803398b69e3a444df24eacdbe12ed699c7014e120ea38552debbf" url: "https://pub.dev" source: hosted - version: "10.0.1" + version: "13.0.0" archive: dependency: transitive description: @@ -53,34 +53,34 @@ packages: dependency: transitive description: name: build - sha256: a156715e7cd728130c592f30552575908aae5b100005fbc1f0fb16b3c03a3d10 + sha256: "45d14a0fb23e018d8287c32fc98d726ce466b231928ed9b9200f29bd3ccd39ae" url: "https://pub.dev" source: hosted - version: "4.0.6" + version: "4.0.7" build_config: dependency: transitive description: name: build_config - sha256: "4070d2a59f8eec34c97c86ceb44403834899075f66e8a9d59706f8e7834f6f71" + sha256: f2c223156a26eea323e6244b85141d76413a80aeee9fe0b380773789fabaf8ae url: "https://pub.dev" source: hosted - version: "1.3.0" + version: "1.3.1" build_daemon: dependency: transitive description: name: build_daemon - sha256: bf05f6e12cfea92d3c09308d7bcdab1906cd8a179b023269eed00c071004b957 + sha256: fd754058c342243718d5171a95f352cfc9fcf0cba8cfa26df67cb13a5836db78 url: "https://pub.dev" source: hosted - version: "4.1.1" + version: "4.1.2" build_runner: dependency: "direct dev" description: name: build_runner - sha256: "1523ce62448ebac2c15a8ba5fbad8acac169788658a7dd2a1c2d9c2a9318b9a6" + sha256: "5367e521935b102bdf1e735d2aab461e36b2edca6517662d088dd04cc39f8d16" url: "https://pub.dev" source: hosted - version: "2.15.0" + version: "2.15.1" built_collection: dependency: transitive description: @@ -133,10 +133,10 @@ packages: dependency: transitive description: name: code_assets - sha256: "83ccdaa064c980b5596c35dd64a8d3ecc68620174ab9b90b6343b753aa721687" + sha256: bf394f466ba9205f1812a0433b392d6af280f155f56651eda7c18cc32ed493b8 url: "https://pub.dev" source: hosted - version: "1.0.0" + version: "1.2.1" code_builder: dependency: transitive description: @@ -165,10 +165,10 @@ packages: dependency: transitive description: name: cross_file - sha256: "28bb3ae56f117b5aec029d702a90f57d285cd975c3c5c281eaca38dbc47c5937" + sha256: "92c9c43c383bfa1c32079d3bc492d55d6d4318044b7b47edaff8971cbb555c51" url: "https://pub.dev" source: hosted - version: "0.3.5+2" + version: "0.3.5+4" crypto: dependency: transitive description: @@ -189,26 +189,26 @@ packages: dependency: transitive description: name: dart_style - sha256: "29f7ecc274a86d32920b1d9cfc7502fa87220da41ec60b55f329559d5732e2b2" + sha256: "59d53ef8eaed9d288ed9767618e2b31c4fa0383a127db59d5eb2e737a7638a60" url: "https://pub.dev" source: hosted - version: "3.1.7" + version: "3.1.9" dbus: dependency: transitive description: name: dbus - sha256: d0c98dcd4f5169878b6cf8f6e0a52403a9dff371a3e2f019697accbf6f44a270 + sha256: "0ce9b0a839e6dee59a37a623d2fc26a35bbbe6404213e419b0d6411023d62645" url: "https://pub.dev" source: hosted - version: "0.7.12" + version: "0.7.14" equatable: dependency: transitive description: name: equatable - sha256: "3e0141505477fd8ad55d6eb4e7776d3fe8430be8e497ccb1521370c3f21a3e2b" + sha256: "3bce007a596ff8b3119c45d68aaef631272537c03d30e5d4534dd24bf4c5eaa2" url: "https://pub.dev" source: hosted - version: "2.0.8" + version: "2.1.0" fake_async: dependency: transitive description: @@ -225,6 +225,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.2.0" + ffi_leak_tracker: + dependency: transitive + description: + name: ffi_leak_tracker + sha256: "4093d4ef9ca06ffe2786e73bfb25e22aa92112b9bb4ec941f11e3e6b61489a97" + url: "https://pub.dev" + source: hosted + version: "0.1.2" file: dependency: transitive description: @@ -237,10 +245,10 @@ packages: dependency: "direct main" description: name: file_picker - sha256: f13a03000d942e476bc1ff0a736d2e9de711d2f89a95cd4c1d88f861c3348387 + sha256: fdc6a37f715d19f35b131decf1ce39242eeed5ddae18c0818c3eccb731ab76be url: "https://pub.dev" source: hosted - version: "11.0.2" + version: "12.0.0-beta.7" fixnum: dependency: transitive description: @@ -266,10 +274,10 @@ packages: dependency: "direct dev" description: name: flutter_launcher_icons - sha256: "526faf84284b86a4cb36d20a5e45147747b7563d921373d4ee0559c54fcdbcea" + sha256: "10f13781741a2e3972126fae08393d3c4e01fa4cd7473326b94b72cf594195e7" url: "https://pub.dev" source: hosted - version: "0.13.1" + version: "0.14.4" flutter_lints: dependency: "direct dev" description: @@ -290,10 +298,10 @@ packages: dependency: transitive description: name: flutter_plugin_android_lifecycle - sha256: "38d1c268de9097ff59cf0e844ac38759fc78f76836d37edad06fa21e182055a0" + sha256: "3854fe5e3bff0b113c658f260b90c95dea17c92db0f2addeac2e343dd9969785" url: "https://pub.dev" source: hosted - version: "2.0.34" + version: "2.0.35" flutter_svg: dependency: transitive description: @@ -348,34 +356,34 @@ packages: dependency: "direct main" description: name: health_connector - sha256: "5d2d785077e1004457808ee568efc1264e5e090258fac507c00542066fe12064" + sha256: "3caec088ae94023117b30e804a2bc19c369121a0618a5baa0849472e17d7b6c8" url: "https://pub.dev" source: hosted - version: "3.9.1" + version: "3.9.3" health_connector_core: dependency: transitive description: name: health_connector_core - sha256: "452823baeb89c8e63e6bf775b1eda86cfc42e50ad777addde899c77bea710136" + sha256: "8a2aa99574dcd8868447af7ab16dc9a26caba48a194e8141e6f6e54f7848f82d" url: "https://pub.dev" source: hosted - version: "3.9.0" + version: "3.9.2" health_connector_hc_android: dependency: transitive description: name: health_connector_hc_android - sha256: "21834d80e8d0c65f5263c3da7076c2933cf98b61e28547d2603f0b7f66caf8c7" + sha256: "063023a7ee4ec2acb4e2d4166de68df145ddaaa58e67d251926f22eed28a306c" url: "https://pub.dev" source: hosted - version: "3.6.0" + version: "3.6.2" health_connector_hk_ios: dependency: transitive description: name: health_connector_hk_ios - sha256: "617bc9d52c7a57b15d4a01663a1484f86b7d7460f93fdbf24e4ea4b54c7f0974" + sha256: "12e958e5481c493319a1972460be369f38ac494d103359fc09ba121b46f5d6eb" url: "https://pub.dev" source: hosted - version: "3.9.0" + version: "3.9.2" health_connector_logger: dependency: transitive description: @@ -404,10 +412,10 @@ packages: dependency: transitive description: name: hooks - sha256: "025f060e86d2d4c3c47b56e33caf7f93bf9283340f26d23424ebcfccf34f621e" + sha256: "9a62a50b50b769a737bc0a8ff381f333529df3ab746b2f6b02e83760231455ba" url: "https://pub.dev" source: hosted - version: "1.0.3" + version: "2.0.2" http: dependency: "direct main" description: @@ -444,10 +452,10 @@ packages: dependency: "direct main" description: name: intl - sha256: d6f56758b7d3014a48af9701c085700aac781a92a87a62b1333b46d8879661cf + sha256: "1ca20c894b1717686a2319b8548763d812bc0aabdac580420a44c5178c57a867" url: "https://pub.dev" source: hosted - version: "0.19.0" + version: "0.20.3" io: dependency: transitive description: @@ -556,18 +564,10 @@ packages: dependency: "direct dev" description: name: mockito - sha256: eff30d002f0c8bf073b6f929df4483b543133fcafce056870163587b03f1d422 - url: "https://pub.dev" - source: hosted - version: "5.6.4" - native_toolchain_c: - dependency: transitive - description: - name: native_toolchain_c - sha256: "6ba77bb18063eebe9de401f5e6437e95e1438af0a87a3a39084fbd37c90df572" + sha256: c8d040d754367108fbe482dcb79dd72b8fe60ac6727abd15b4783c5560297ee6 url: "https://pub.dev" source: hosted - version: "0.17.6" + version: "5.7.0" nested: dependency: transitive description: @@ -580,10 +580,10 @@ packages: dependency: transitive description: name: objective_c - sha256: "100a1c87616ab6ed41ec263b083c0ef3261ee6cd1dc3b0f35f8ddfa4f996fe52" + sha256: "6cb691c686fa2838c6deb34980d426145c2a5d537491cb83d463c33cdbc726ed" url: "https://pub.dev" source: hosted - version: "9.3.0" + version: "9.4.1" package_config: dependency: transitive description: @@ -596,18 +596,18 @@ packages: dependency: "direct main" description: name: package_info_plus - sha256: "16eee997588c60225bda0488b6dcfac69280a6b7a3cf02c741895dd370a02968" + sha256: "127e1751e37ffb2ff4658beeaca77bad0c27bf5f932bd3a501c2296926d4b481" url: "https://pub.dev" source: hosted - version: "8.3.1" + version: "10.2.1" package_info_plus_platform_interface: dependency: transitive description: name: package_info_plus_platform_interface - sha256: "202a487f08836a592a6bd4f901ac69b3a8f146af552bbd14407b6b41e1c3f086" + sha256: db762cb2f4f25ee60fb6359773861b0f199e00b90d237bd85a76a1e806b46ef4 url: "https://pub.dev" source: hosted - version: "3.2.1" + version: "4.1.0" path: dependency: transitive description: @@ -628,10 +628,10 @@ packages: dependency: "direct main" description: name: path_provider - sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" + sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825 url: "https://pub.dev" source: hosted - version: "2.1.5" + version: "2.1.6" path_provider_android: dependency: transitive description: @@ -652,18 +652,18 @@ packages: dependency: transitive description: name: path_provider_linux - sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + sha256: "58c2005f147315b11e9b4a7bc889cd5203e250cba8e3f012dae259b4972b5c16" url: "https://pub.dev" source: hosted - version: "2.2.1" + version: "2.2.2" path_provider_platform_interface: dependency: transitive description: name: path_provider_platform_interface - sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + sha256: "484838772624c3a4b94f1e44a3e19897fee738f2d5c4ce448443b0417f7c9dda" url: "https://pub.dev" source: hosted - version: "2.1.2" + version: "2.1.3" path_provider_windows: dependency: transitive description: @@ -748,18 +748,18 @@ packages: dependency: "direct main" description: name: share_plus - sha256: "223873d106614442ea6f20db5a038685cc5b32a2fba81cdecaefbbae0523f7fa" + sha256: "02180b01c1237b9706b663d9402b2cf2402b3407f48cce99cc19e3200f095b8a" url: "https://pub.dev" source: hosted - version: "12.0.2" + version: "13.2.1" share_plus_platform_interface: dependency: transitive description: name: share_plus_platform_interface - sha256: "88023e53a13429bd65d8e85e11a9b484f49d4c190abbd96c7932b74d6927cc9a" + sha256: "7f7ae28cf400d13f811e297ff37742dba83b79e0a6f5dce14eec0248274e6ce9" url: "https://pub.dev" source: hosted - version: "6.1.0" + version: "7.1.0" shelf: dependency: transitive description: @@ -897,10 +897,10 @@ packages: dependency: "direct main" description: name: uuid - sha256: "1fef9e8e11e2991bb773070d4656b7bd5d850967a2456cfc83cf47925ba79489" + sha256: "9b129329f58692f6e6578329498a8fe9fbe98f090beb764ffbb8ee2eadd01dcd" url: "https://pub.dev" source: hosted - version: "4.5.3" + version: "4.6.0" vector_graphics: dependency: transitive description: @@ -921,10 +921,10 @@ packages: dependency: transitive description: name: vector_graphics_compiler - sha256: "09854c7633b215e6f7bb2a9adb607bc525bae8655c7fc29db880c33e62f72230" + sha256: "142a9146f447d15b10bdc00e21d5f4d83e5b32bb5f8f8f5a04c75311344923a3" url: "https://pub.dev" source: hosted - version: "1.2.4" + version: "1.2.6" vector_math: dependency: transitive description: @@ -977,10 +977,10 @@ packages: dependency: transitive description: name: win32 - sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e + sha256: ba6f4bba816c8d7e3c1580e170f3786d216951cc6b94babc3b814c08d2cb2738 url: "https://pub.dev" source: hosted - version: "5.15.0" + version: "6.3.0" xdg_directories: dependency: transitive description: diff --git a/workout-logger/pubspec.yaml b/workout-logger/pubspec.yaml index 09504d1..2609fdc 100644 --- a/workout-logger/pubspec.yaml +++ b/workout-logger/pubspec.yaml @@ -48,9 +48,9 @@ dependencies: # Utilities uuid: ^4.5.1 - intl: ^0.19.0 + intl: ^0.20.3 http: ^1.2.1 - package_info_plus: ^8.3.1 + package_info_plus: ^10.2.1 # Health Connect integration health_connector: ^3.9.1 @@ -59,9 +59,9 @@ dependencies: google_generative_ai: ^0.4.3 # Backup export/import - file_picker: ^11.0.2 + file_picker: ^12.0.0-beta.7 path_provider: ^2.1.5 - share_plus: ^12.0.1 + share_plus: ^13.2.1 gpt_markdown: ^1.1.7 dev_dependencies: @@ -74,7 +74,7 @@ dev_dependencies: # package. See that file for information about deactivating specific lint # rules and activating additional ones. flutter_lints: ^6.0.0 - flutter_launcher_icons: ^0.13.1 + flutter_launcher_icons: ^0.14.4 # Testing mockito: ^5.4.4 From 9a70573752b64224a96487039aede6e128797d0a Mon Sep 17 00:00:00 2001 From: Devasy Patel <110348311+Devasy23@users.noreply.github.com> Date: Thu, 16 Jul 2026 00:01:45 +0530 Subject: [PATCH 07/14] Enhances the bottom nav bar --- workout-logger/lib/screens/home_screen.dart | 64 ++++-- .../lib/screens/widgets/rf_widgets.dart | 201 ++++++++++-------- 2 files changed, 167 insertions(+), 98 deletions(-) diff --git a/workout-logger/lib/screens/home_screen.dart b/workout-logger/lib/screens/home_screen.dart index 5ad5b8f..800487e 100644 --- a/workout-logger/lib/screens/home_screen.dart +++ b/workout-logger/lib/screens/home_screen.dart @@ -37,6 +37,7 @@ class HomeScreen extends StatefulWidget { class _HomeScreenState extends State { int _currentIndex = 0; + bool _navVisible = true; static const _navItems = [ RFNavItem(icon: Icons.home_rounded, label: 'Home'), @@ -45,27 +46,62 @@ class _HomeScreenState extends State { RFNavItem(icon: Icons.bar_chart_rounded, label: 'Stats'), ]; - void switchTab(int index) => setState(() => _currentIndex = index); + void switchTab(int index) => setState(() { + _currentIndex = index; + _navVisible = true; // always show nav on tab change + }); + + bool _onScrollNotification(ScrollNotification n) { + if (n is ScrollUpdateNotification) { + final delta = n.scrollDelta ?? 0; + if (delta > 2 && _navVisible) { + setState(() => _navVisible = false); + } else if (delta < -2 && !_navVisible) { + setState(() => _navVisible = true); + } + } + // Always show nav when at the very top of any scroll view. + if (n is ScrollUpdateNotification && n.metrics.pixels <= 0 && !_navVisible) { + setState(() => _navVisible = true); + } + return false; // let the notification keep bubbling + } @override Widget build(BuildContext context) { return Scaffold( - extendBody: true, backgroundColor: AppColors.background, - body: IndexedStack( - index: _currentIndex, - children: const [ - _DashboardTab(), - RoutinesScreen(), - HistoryScreen(), - AnalyticsScreen(), + body: Stack( + children: [ + NotificationListener( + onNotification: _onScrollNotification, + child: IndexedStack( + index: _currentIndex, + children: const [ + _DashboardTab(), + RoutinesScreen(), + HistoryScreen(), + AnalyticsScreen(), + ], + ), + ), + AnimatedSlide( + offset: _navVisible ? Offset.zero : const Offset(0, 1.5), + duration: const Duration(milliseconds: 280), + curve: Curves.easeInOutCubic, + child: AnimatedOpacity( + opacity: _navVisible ? 1.0 : 0.0, + duration: const Duration(milliseconds: 220), + curve: Curves.easeInOutCubic, + child: RFNavBar( + currentIndex: _currentIndex, + onTap: switchTab, + items: _navItems, + ), + ), + ), ], ), - bottomNavigationBar: RFNavBar( - currentIndex: _currentIndex, - onTap: switchTab, - items: _navItems, - ), ); } diff --git a/workout-logger/lib/screens/widgets/rf_widgets.dart b/workout-logger/lib/screens/widgets/rf_widgets.dart index 261a498..87d8340 100644 --- a/workout-logger/lib/screens/widgets/rf_widgets.dart +++ b/workout-logger/lib/screens/widgets/rf_widgets.dart @@ -136,8 +136,8 @@ class AmbientGlow extends StatelessWidget { } // ── RFNavBar ───────────────────────────────────────────────────────────────── -// Premium floating glassmorphic bottom navigation bar with perfect rounded blur, -// deep drop shadow, and clean transparent padding so it sits elegantly above the content. +// Compact floating glassmorphic pill — auto-sized to fit icons only. +// Active state: butter-smooth AnimatedAlign sliding highlight pill behind icon. class RFNavBar extends StatelessWidget { const RFNavBar({ super.key, @@ -150,53 +150,109 @@ class RFNavBar extends StatelessWidget { final ValueChanged onTap; final List items; + // Each icon cell is 52px wide; pill itself is 44px wide and 44px tall. + static const double _cellW = 52; + static const double _pillW = 44; + static const double _pillH = 44; + static const double _hPad = 6; + + /// Maps [currentIndex] → Alignment.x in range [-1, 1] across the pill row. + Alignment _pillAlignment(int n) { + if (n <= 0) return const Alignment(-1, 0); + if (n >= items.length - 1) return const Alignment(1, 0); + // Linear interpolation between -1 and 1 across (items.length - 1) steps. + final t = n / (items.length - 1); + return Alignment(t * 2 - 1, 0); + } + @override Widget build(BuildContext context) { final bottomPadding = MediaQuery.of(context).padding.bottom; - return Container( - color: Colors.transparent, // Completely transparent outer container - padding: EdgeInsets.fromLTRB( - 16, - 8, - 16, - bottomPadding > 0 ? bottomPadding + 8 : 16, - ), - child: Container( - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(AppRadius.xxl), - boxShadow: [ - BoxShadow( - color: Colors.black.withValues(alpha: 0.4), - blurRadius: 28, - spreadRadius: -4, - offset: const Offset(0, 10), - ), - ], + final double navW = items.length * _cellW + _hPad * 2; + + return Align( + alignment: Alignment.bottomCenter, + child: Padding( + padding: EdgeInsets.only( + bottom: bottomPadding > 0 ? bottomPadding : 16, ), - child: ClipRRect( - borderRadius: BorderRadius.circular(AppRadius.xxl), - child: BackdropFilter( - filter: ImageFilter.blur(sigmaX: 16, sigmaY: 16), - child: Container( - decoration: BoxDecoration( - color: AppColors.surface.withValues(alpha: 0.8), // Sleek transparent surface - borderRadius: BorderRadius.circular(AppRadius.xxl), - border: Border.all( - color: AppColors.glassBorderStrong, - width: 1.5, - ), + child: Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(AppRadius.full), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.45), + blurRadius: 28, + spreadRadius: -4, + offset: const Offset(0, 10), + ), + BoxShadow( + color: AppColors.primary.withValues(alpha: 0.08), + blurRadius: 32, + spreadRadius: 0, ), - padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 10), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: List.generate(items.length, (i) { - final active = i == currentIndex; - return _NavItem( - item: items[i], - active: active, - onTap: () => onTap(i), - ); - }), + ], + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(AppRadius.full), + child: BackdropFilter( + filter: ImageFilter.blur(sigmaX: 18, sigmaY: 18), + child: Container( + width: navW, + height: 56, + decoration: BoxDecoration( + color: AppColors.surface.withValues(alpha: 0.82), + borderRadius: BorderRadius.circular(AppRadius.full), + border: Border.all( + color: AppColors.glassBorderStrong, + width: 1.2, + ), + ), + child: Stack( + alignment: Alignment.center, + children: [ + // ── Sliding pill highlight ──────────────────────────── + AnimatedAlign( + duration: AppDurations.moderate, + curve: Curves.easeInOutCubic, + alignment: _pillAlignment(currentIndex), + child: Container( + width: _pillW, + height: _pillH, + decoration: BoxDecoration( + color: AppColors.glass3, + borderRadius: BorderRadius.circular(AppRadius.full), + border: Border.all( + color: AppColors.primary.withValues(alpha: 0.25), + width: 1, + ), + boxShadow: [ + BoxShadow( + color: AppColors.primary.withValues(alpha: 0.15), + blurRadius: 12, + spreadRadius: -2, + ), + ], + ), + ), + ), + // ── Icon row ──────────────────────────────────────── + Padding( + padding: const EdgeInsets.symmetric(horizontal: _hPad), + child: Row( + mainAxisSize: MainAxisSize.min, + children: List.generate(items.length, (i) { + final active = i == currentIndex; + return _NavCell( + item: items[i], + active: active, + onTap: () => onTap(i), + ); + }), + ), + ), + ], + ), ), ), ), @@ -209,11 +265,11 @@ class RFNavBar extends StatelessWidget { class RFNavItem { const RFNavItem({required this.icon, required this.label}); final IconData icon; - final String label; + final String label; // kept for semantics / accessibility } -class _NavItem extends StatelessWidget { - const _NavItem({ +class _NavCell extends StatelessWidget { + const _NavCell({ required this.item, required this.active, required this.onTap, @@ -228,49 +284,26 @@ class _NavItem extends StatelessWidget { return Semantics( button: true, label: item.label, + selected: active, child: GestureDetector( onTap: onTap, behavior: HitTestBehavior.opaque, child: SizedBox( - width: 60, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - // Accent indicator above icon - AnimatedContainer( - duration: AppDurations.normal, - width: active ? 18 : 0, - height: 2, - margin: const EdgeInsets.only(bottom: 4), - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(2), - color: AppColors.primary, - boxShadow: active - ? [ - BoxShadow( - color: AppColors.primary.withValues(alpha: 0.6), - blurRadius: 6, - ), - ] - : null, - ), - ), - Icon( + width: RFNavBar._cellW, + height: 56, + child: Center( + child: AnimatedScale( + scale: active ? 1.12 : 1.0, + duration: AppDurations.moderate, + curve: Curves.easeInOutCubic, + child: Icon( item.icon, - size: 19, - color: active ? AppColors.textPrimary : AppColors.textMuted, + size: 22, + color: active + ? AppColors.textPrimary + : AppColors.textMuted, ), - const SizedBox(height: 4), - Text( - item.label, - style: TextStyle(fontFamily: 'Geist', - fontSize: 10, - fontWeight: active ? FontWeight.w600 : FontWeight.w500, - color: active ? AppColors.textPrimary : AppColors.textMuted, - letterSpacing: 0.2, - ), - ), - ], + ), ), ), ), From 34095d6fa32984f6404df4f0c3880e88540b2025 Mon Sep 17 00:00:00 2001 From: Devasy Patel <110348311+Devasy23@users.noreply.github.com> Date: Thu, 16 Jul 2026 00:29:13 +0530 Subject: [PATCH 08/14] fixes out bulging issue --- .../lib/screens/widgets/rf_widgets.dart | 33 +++++++++++-------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/workout-logger/lib/screens/widgets/rf_widgets.dart b/workout-logger/lib/screens/widgets/rf_widgets.dart index 87d8340..5316d69 100644 --- a/workout-logger/lib/screens/widgets/rf_widgets.dart +++ b/workout-logger/lib/screens/widgets/rf_widgets.dart @@ -150,20 +150,22 @@ class RFNavBar extends StatelessWidget { final ValueChanged onTap; final List items; - // Each icon cell is 52px wide; pill itself is 44px wide and 44px tall. + // Each icon cell is 52px wide; pill is 44×44px; outer pad 6px each side. + // navW = items.length * _cellW + _hPad * 2 → 4×52 + 12 = 220px + // Outer container effective corner radius ≈ 56/2 = 28px. + // Pill left for cell n = _hPad + n*_cellW + (_cellW-_pillW)/2 + // = 6 + n*52 + 4 = 10 + n*52 + // → n=0→10, n=1→62, n=2→114, n=3→166; right edge n=3→210 (10px margin both sides) + // Both inner and outer radii are AppRadius.full so they are always concentric. static const double _cellW = 52; static const double _pillW = 44; static const double _pillH = 44; static const double _hPad = 6; + static const double _navH = 56; - /// Maps [currentIndex] → Alignment.x in range [-1, 1] across the pill row. - Alignment _pillAlignment(int n) { - if (n <= 0) return const Alignment(-1, 0); - if (n >= items.length - 1) return const Alignment(1, 0); - // Linear interpolation between -1 and 1 across (items.length - 1) steps. - final t = n / (items.length - 1); - return Alignment(t * 2 - 1, 0); - } + /// Pixel offset of the pill's left edge for tab [n], relative to container left. + static double _pillLeft(int n) => + _hPad + n * _cellW + (_cellW - _pillW) / 2; @override Widget build(BuildContext context) { @@ -209,16 +211,19 @@ class RFNavBar extends StatelessWidget { ), ), child: Stack( - alignment: Alignment.center, + clipBehavior: Clip.hardEdge, children: [ // ── Sliding pill highlight ──────────────────────────── - AnimatedAlign( + // AnimatedPositioned guarantees exact pixel alignment so + // the pill is always concentric with the outer container. + AnimatedPositioned( duration: AppDurations.moderate, curve: Curves.easeInOutCubic, - alignment: _pillAlignment(currentIndex), + left: _pillLeft(currentIndex), + top: (_navH - _pillH) / 2, + width: _pillW, + height: _pillH, child: Container( - width: _pillW, - height: _pillH, decoration: BoxDecoration( color: AppColors.glass3, borderRadius: BorderRadius.circular(AppRadius.full), From 490237c03eebb0480b73a4cf72f1244219b6665c Mon Sep 17 00:00:00 2001 From: Devasy Patel <110348311+Devasy23@users.noreply.github.com> Date: Wed, 22 Jul 2026 22:42:01 +0530 Subject: [PATCH 09/14] Updates the bottom navbar UI, and then adds build size reuction params --- workout-logger/.gitignore | 10 + workout-logger/android/app/build.gradle.kts | 23 +- workout-logger/android/app/proguard-rules.pro | 14 + workout-logger/android/key.properties.example | 8 + workout-logger/lib/screens/home_screen.dart | 87 +- .../lib/screens/widgets/floating_nav_bar.dart | 763 ++++++++++++++++++ .../lib/screens/widgets/rf_widgets.dart | 183 +---- workout-logger/scripts/build_release.py | 46 ++ 8 files changed, 893 insertions(+), 241 deletions(-) create mode 100644 workout-logger/android/app/proguard-rules.pro create mode 100644 workout-logger/android/key.properties.example create mode 100644 workout-logger/lib/screens/widgets/floating_nav_bar.dart create mode 100644 workout-logger/scripts/build_release.py diff --git a/workout-logger/.gitignore b/workout-logger/.gitignore index 3820a95..5f10f73 100644 --- a/workout-logger/.gitignore +++ b/workout-logger/.gitignore @@ -43,3 +43,13 @@ app.*.map.json /android/app/debug /android/app/profile /android/app/release + +# Signing Keystore & Credentials +**/android/key.properties +*.jks +*.keystore +*.p12 +.env +.env.* + + diff --git a/workout-logger/android/app/build.gradle.kts b/workout-logger/android/app/build.gradle.kts index 3c71d30..d68c9d8 100644 --- a/workout-logger/android/app/build.gradle.kts +++ b/workout-logger/android/app/build.gradle.kts @@ -1,4 +1,6 @@ import com.android.build.gradle.internal.api.ApkVariantOutputImpl +import java.io.FileInputStream +import java.util.Properties plugins { id("com.android.application") @@ -34,11 +36,16 @@ android { signingConfigs { create("release") { - val keystorePath = System.getenv("KEYSTORE_PATH") - val storePass = System.getenv("KEY_STORE_PASSWORD") - val alias = System.getenv("KEY_ALIAS") - val keyPass = System.getenv("KEY_PASSWORD") - if (keystorePath != null && storePass != null && alias != null && keyPass != null) { + val keyProperties = Properties() + val keyPropertiesFile = rootProject.file("key.properties") + if (keyPropertiesFile.exists()) { + keyProperties.load(FileInputStream(keyPropertiesFile)) + } + val keystorePath = System.getenv("KEYSTORE_PATH") ?: keyProperties.getProperty("storeFile") + val storePass = System.getenv("KEY_STORE_PASSWORD") ?: keyProperties.getProperty("storePassword") + val alias = System.getenv("KEY_ALIAS") ?: keyProperties.getProperty("keyAlias") + val keyPass = System.getenv("KEY_PASSWORD") ?: keyProperties.getProperty("keyPassword") + if (!keystorePath.isNullOrEmpty() && !storePass.isNullOrEmpty() && !alias.isNullOrEmpty() && !keyPass.isNullOrEmpty()) { storeFile = file(keystorePath) storePassword = storePass keyAlias = alias @@ -72,6 +79,12 @@ android { manifestPlaceholders["appLabel"] = "RepForge (Debug)" } release { + isMinifyEnabled = true + isShrinkResources = true + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) // Uses the production EC P-256 keystore when KEYSTORE_PATH env var is set // (CI injects it via GitHub Secrets). Falls back to the debug key for a // local `flutter run --release` without env vars configured. diff --git a/workout-logger/android/app/proguard-rules.pro b/workout-logger/android/app/proguard-rules.pro new file mode 100644 index 0000000..3dde057 --- /dev/null +++ b/workout-logger/android/app/proguard-rules.pro @@ -0,0 +1,14 @@ +# Suppress missing class warnings for Play Core deferred components in Flutter engine +-dontwarn com.google.android.play.core.** + +# Flutter Wrapper Rules +-keep class io.flutter.app.** { *; } +-keep class io.flutter.plugin.** { *; } +-keep class io.flutter.util.** { *; } +-keep class io.flutter.view.** { *; } +-keep class io.flutter.embedding.** { *; } +-keep class io.flutter.provider.** { *; } +-keep class io.flutter.plugin.editing.** { *; } + +# Keep Native plugins and Health Connect interfaces +-dontwarn com.google.android.gms.** diff --git a/workout-logger/android/key.properties.example b/workout-logger/android/key.properties.example new file mode 100644 index 0000000..24133ee --- /dev/null +++ b/workout-logger/android/key.properties.example @@ -0,0 +1,8 @@ +# Local Android Release Keystore Configuration +# Fill in your local keystore path and passwords below. +# Note: This file should NEVER be committed to Git. + +storeFile=C:/path/to/your/upload-keystore.jks +storePassword=your_store_password +keyAlias=your_key_alias +keyPassword=your_key_password diff --git a/workout-logger/lib/screens/home_screen.dart b/workout-logger/lib/screens/home_screen.dart index 800487e..caf412d 100644 --- a/workout-logger/lib/screens/home_screen.dart +++ b/workout-logger/lib/screens/home_screen.dart @@ -22,6 +22,7 @@ import 'widgets/readiness_card.dart'; import 'widgets/sleep_hr_card.dart'; import 'widgets/heart_rate_card.dart'; import 'widgets/rf_widgets.dart'; +import 'widgets/floating_nav_bar.dart'; import 'widgets/sparkline_painter.dart'; import 'widgets/activity_heatmap.dart'; import 'widgets/body_heatmap.dart'; @@ -37,69 +38,43 @@ class HomeScreen extends StatefulWidget { class _HomeScreenState extends State { int _currentIndex = 0; - bool _navVisible = true; static const _navItems = [ - RFNavItem(icon: Icons.home_rounded, label: 'Home'), - RFNavItem(icon: Icons.layers_rounded, label: 'Routines'), - RFNavItem(icon: Icons.history_rounded, label: 'History'), - RFNavItem(icon: Icons.bar_chart_rounded, label: 'Stats'), + FloatingNavItem(icon: Icons.home_rounded, label: 'Home'), + FloatingNavItem(icon: Icons.layers_rounded, label: 'Routines'), + FloatingNavItem(icon: Icons.history_rounded, label: 'History'), + FloatingNavItem(icon: Icons.bar_chart_rounded, label: 'Stats'), ]; - void switchTab(int index) => setState(() { - _currentIndex = index; - _navVisible = true; // always show nav on tab change - }); - - bool _onScrollNotification(ScrollNotification n) { - if (n is ScrollUpdateNotification) { - final delta = n.scrollDelta ?? 0; - if (delta > 2 && _navVisible) { - setState(() => _navVisible = false); - } else if (delta < -2 && !_navVisible) { - setState(() => _navVisible = true); - } - } - // Always show nav when at the very top of any scroll view. - if (n is ScrollUpdateNotification && n.metrics.pixels <= 0 && !_navVisible) { - setState(() => _navVisible = true); - } - return false; // let the notification keep bubbling - } + void switchTab(int index) => setState(() => _currentIndex = index); @override Widget build(BuildContext context) { - return Scaffold( - backgroundColor: AppColors.background, - body: Stack( - children: [ - NotificationListener( - onNotification: _onScrollNotification, - child: IndexedStack( - index: _currentIndex, - children: const [ - _DashboardTab(), - RoutinesScreen(), - HistoryScreen(), - AnalyticsScreen(), - ], - ), - ), - AnimatedSlide( - offset: _navVisible ? Offset.zero : const Offset(0, 1.5), - duration: const Duration(milliseconds: 280), - curve: Curves.easeInOutCubic, - child: AnimatedOpacity( - opacity: _navVisible ? 1.0 : 0.0, - duration: const Duration(milliseconds: 220), - curve: Curves.easeInOutCubic, - child: RFNavBar( - currentIndex: _currentIndex, - onTap: switchTab, - items: _navItems, - ), - ), - ), + return FloatingNavBarScaffold( + scaffoldBackgroundColor: AppColors.background, + // App-specific colour overrides — all other values use the + // FloatingNavBarTheme defaults which adapt to ThemeData.colorScheme. + theme: FloatingNavBarTheme( + backgroundColor: AppColors.surface, + borderColor: AppColors.glassBorderStrong, + // Chip colours (replaces old pill API) + selectedChipColor: AppColors.glass3, + selectedChipBorderColor: AppColors.primary.withValues(alpha: 0.25), + selectedChipShadowColor: AppColors.primary.withValues(alpha: 0.15), + selectedContentColor: AppColors.textPrimary, + inactiveIconColor: AppColors.textMuted, + outerGlowColor: AppColors.primary.withValues(alpha: 0.08), + ), + items: _navItems, + currentIndex: _currentIndex, + onTabChanged: switchTab, + body: IndexedStack( + index: _currentIndex, + children: const [ + _DashboardTab(), + RoutinesScreen(), + HistoryScreen(), + AnalyticsScreen(), ], ), ); diff --git a/workout-logger/lib/screens/widgets/floating_nav_bar.dart b/workout-logger/lib/screens/widgets/floating_nav_bar.dart new file mode 100644 index 0000000..6d82d62 --- /dev/null +++ b/workout-logger/lib/screens/widgets/floating_nav_bar.dart @@ -0,0 +1,763 @@ +// floating_nav_bar.dart — Self-contained floating navigation bar for Flutter. +// +// Redesigned with the "expanding chip" pattern from EssentialsFloatingToolbar: +// • Selected tab expands horizontally (spring physics) to reveal an inline label +// • Unselected tabs show icon-only at a fixed compact size +// • Badge dot support on any nav item +// • Glassmorphic container — backdrop blur + border + outer glow +// • Scroll-aware hide/show via FloatingNavBarScaffold +// +// ─── Quick start ────────────────────────────────────────────────────────────── +// +// ```dart +// const items = [ +// FloatingNavItem(icon: Icons.home, label: 'Home'), +// FloatingNavItem(icon: Icons.search, label: 'Search'), +// FloatingNavItem(icon: Icons.person, label: 'Profile'), +// ]; +// +// FloatingNavBarScaffold( +// items: items, +// currentIndex: _index, +// onTabChanged: (i) => setState(() => _index = i), +// body: IndexedStack(index: _index, children: _pages), +// ) +// ``` +// +// ─── Drop-in dependency ─────────────────────────────────────────────────────── +// Only needs the Flutter SDK (material.dart · dart:ui · flutter/physics.dart). + +import 'dart:ui' show ImageFilter; +import 'package:flutter/material.dart'; +import 'package:flutter/physics.dart'; +import 'package:flutter/services.dart'; + +// ───────────────────────────────────────────────────────────────────────────── +// FloatingNavItem +// ───────────────────────────────────────────────────────────────────────────── + +/// A single tab entry for [FloatingNavBar]. +/// +/// [label] is displayed as an expanding inline text when the tab is active +/// and is also used for screen-reader semantics (TalkBack / VoiceOver). +/// Supply [activeIcon] for a distinct icon when selected. +/// Set [hasBadge] to `true` to render a small red indicator dot. +@immutable +class FloatingNavItem { + const FloatingNavItem({ + required this.icon, + required this.label, + this.activeIcon, + this.hasBadge = false, + }); + + /// Icon shown when this tab is **inactive**. + final IconData icon; + + /// Optional icon shown when this tab is **active**. Falls back to [icon]. + final IconData? activeIcon; + + /// Text displayed as an expanding label when active, and used for semantics. + final String label; + + /// When `true`, a small red dot is painted at the top-right of the icon. + final bool hasBadge; + + /// Returns the correct icon for the given [active] state. + IconData iconFor(bool active) => active ? (activeIcon ?? icon) : icon; +} + +// ───────────────────────────────────────────────────────────────────────────── +// FloatingNavBarTheme +// ───────────────────────────────────────────────────────────────────────────── + +/// Visual and behavioural configuration for [FloatingNavBar] and +/// [FloatingNavBarScaffold]. +/// +/// All colour fields are nullable — `null` values derive from the ambient +/// [ThemeData.colorScheme] at runtime. Override only what you need. +@immutable +class FloatingNavBarTheme { + const FloatingNavBarTheme({ + // ── Colours ────────────────────────────────────────────────────────────── + this.backgroundColor, + this.backgroundOpacity = 0.82, + this.borderColor, + this.borderWidth = 1.2, + /// Background of the selected tab chip. + this.selectedChipColor, + /// Border of the selected tab chip. + this.selectedChipBorderColor, + /// Glow shadow of the selected tab chip. + this.selectedChipShadowColor, + /// Icon + label colour inside the selected chip. + this.selectedContentColor, + this.inactiveIconColor, + this.outerShadowColor, + this.outerGlowColor, + // ── Sizes ──────────────────────────────────────────────────────────────── + this.navHeight = 60.0, + this.chipHeight = 46.0, + /// Fixed width of each icon tap cell (active and inactive). + this.iconCellSize = 48.0, + /// Extra width that slides open when a chip becomes active (label area). + this.labelWidth = 80.0, + this.iconSize = 22.0, + /// Symmetric horizontal inset inside the container. + this.horizontalPadding = 8.0, + /// Gap between adjacent chips. + this.itemSpacing = 4.0, + this.blurSigma = 18.0, + // ── Label ──────────────────────────────────────────────────────────────── + /// Set to `false` to disable label expansion (icon-only compact mode). + this.showLabels = true, + /// Override the label [TextStyle]. Colour is always resolved from theme. + this.labelStyle, + // ── Spring animation ───────────────────────────────────────────────────── + /// Spring mass (heavier = slower). + this.springMass = 1.0, + /// Spring stiffness (higher = snappier). + this.springStiffness = 500.0, + /// Damping ratio: 0.5 = bouncy, 1.0 = critically damped. + this.springDampingRatio = 0.72, + /// Duration for collapsing (non-spring ease-in). + this.collapseDuration = const Duration(milliseconds: 200), + // ── Show / hide animation ───────────────────────────────────────────────── + this.showDuration = const Duration(milliseconds: 250), + this.hideDuration = const Duration(milliseconds: 280), + this.showCurve = Curves.easeInOutCubic, + this.hideCurve = Curves.easeInOutCubic, + // ── Scroll behaviour ───────────────────────────────────────────────────── + /// Set to false to keep the nav bar permanently visible. + this.hideOnScroll = true, + this.scrollDownThreshold = 2.0, + this.scrollUpThreshold = 2.0, + // ── Misc ───────────────────────────────────────────────────────────────── + this.bottomMargin = 16.0, + this.hapticFeedback = true, + // ── Fallback colour opacities ───────────────────────────────────────────── + this.defaultBorderOpacity = 0.13, + this.defaultChipOpacity = 0.10, + this.defaultChipBorderOpacity = 0.25, + this.defaultChipShadowOpacity = 0.15, + this.defaultInactiveOpacity = 0.48, + this.defaultShadowOpacity = 0.45, + this.defaultGlowOpacity = 0.08, + // ── Shadow geometry ─────────────────────────────────────────────────────── + this.outerShadowBlurRadius = 28.0, + this.outerShadowSpread = -4.0, + this.outerShadowOffset = const Offset(0, 10), + this.outerGlowBlurRadius = 32.0, + // ── Slide animation ─────────────────────────────────────────────────────── + /// Offset applied to [AnimatedSlide] when the nav bar hides. + this.slideHideOffset = const Offset(0, 1.5), + /// Fade-out duration = hideDuration × fadeOutDurationFactor. + this.fadeOutDurationFactor = 0.75, + }); + + // ── Colours ───────────────────────────────────────────────────────────────── + final Color? backgroundColor; + final double backgroundOpacity; + final Color? borderColor; + final double borderWidth; + final Color? selectedChipColor; + final Color? selectedChipBorderColor; + final Color? selectedChipShadowColor; + final Color? selectedContentColor; + final Color? inactiveIconColor; + final Color? outerShadowColor; + final Color? outerGlowColor; + + // ── Sizes ──────────────────────────────────────────────────────────────────── + final double navHeight; + final double chipHeight; + final double iconCellSize; + final double labelWidth; + final double iconSize; + final double horizontalPadding; + final double itemSpacing; + final double blurSigma; + + // ── Label ──────────────────────────────────────────────────────────────────── + final bool showLabels; + final TextStyle? labelStyle; + + // ── Spring animation ───────────────────────────────────────────────────────── + final double springMass; + final double springStiffness; + final double springDampingRatio; + final Duration collapseDuration; + + // ── Show / hide animation ──────────────────────────────────────────────────── + final Duration showDuration; + final Duration hideDuration; + final Curve showCurve; + final Curve hideCurve; + + // ── Scroll ─────────────────────────────────────────────────────────────────── + final bool hideOnScroll; + final double scrollDownThreshold; + final double scrollUpThreshold; + + // ── Misc ───────────────────────────────────────────────────────────────────── + final double bottomMargin; + final bool hapticFeedback; + + // ── Fallback opacities ─────────────────────────────────────────────────────── + final double defaultBorderOpacity; + final double defaultChipOpacity; + final double defaultChipBorderOpacity; + final double defaultChipShadowOpacity; + final double defaultInactiveOpacity; + final double defaultShadowOpacity; + final double defaultGlowOpacity; + + // ── Shadow geometry ────────────────────────────────────────────────────────── + final double outerShadowBlurRadius; + final double outerShadowSpread; + final Offset outerShadowOffset; + final double outerGlowBlurRadius; + + // ── Slide animation ────────────────────────────────────────────────────────── + final Offset slideHideOffset; + final double fadeOutDurationFactor; +} + +// ───────────────────────────────────────────────────────────────────────────── +// FloatingNavBar — pure stateless presentation widget +// ───────────────────────────────────────────────────────────────────────────── + +/// A compact, pill-shaped, glassmorphic navigation bar with expanding chip tabs. +/// +/// The selected tab chips open sideways with a spring animation to reveal the +/// tab label; inactive tabs show the icon only. Inspired by the +/// EssentialsFloatingToolbar pattern from the Compose world. +/// +/// **Purely presentational** — no internal state, no scroll listening. +/// +/// Use [FloatingNavBarScaffold] for the full scroll-aware experience. +class FloatingNavBar extends StatelessWidget { + const FloatingNavBar({ + super.key, + required this.currentIndex, + required this.onTap, + required this.items, + this.theme = const FloatingNavBarTheme(), + }) : assert(items.length >= 2, 'FloatingNavBar requires at least 2 items.'); + + /// Index of the currently selected tab. + final int currentIndex; + + /// Called with the tapped tab index. + final ValueChanged onTap; + + /// Tab definitions. Minimum 2. + final List items; + + /// Visual and layout configuration. + final FloatingNavBarTheme theme; + + @override + Widget build(BuildContext context) { + final cs = Theme.of(context).colorScheme; + final bottomPad = MediaQuery.of(context).padding.bottom; + + // ── Resolve colours ────────────────────────────────────────────────────── + final bg = theme.backgroundColor ?? + cs.surface.withValues(alpha: theme.backgroundOpacity); + final border = theme.borderColor ?? + cs.outline.withValues(alpha: theme.defaultBorderOpacity); + final chipBg = theme.selectedChipColor ?? + cs.primary.withValues(alpha: theme.defaultChipOpacity); + final chipContent = theme.selectedContentColor ?? cs.onSurface; + final inactiveContent = theme.inactiveIconColor ?? + cs.onSurface.withValues(alpha: theme.defaultInactiveOpacity); + final outerShadow = theme.outerShadowColor ?? + Colors.black.withValues(alpha: theme.defaultShadowOpacity); + final outerGlow = theme.outerGlowColor ?? + cs.primary.withValues(alpha: theme.defaultGlowOpacity); + + return Align( + alignment: Alignment.bottomCenter, + child: Padding( + padding: EdgeInsets.only( + bottom: bottomPad > 0 ? bottomPad : theme.bottomMargin, + ), + child: _ShadowWrapper( + outerShadow: outerShadow, + outerGlow: outerGlow, + shadowBlurRadius: theme.outerShadowBlurRadius, + shadowSpread: theme.outerShadowSpread, + shadowOffset: theme.outerShadowOffset, + glowBlurRadius: theme.outerGlowBlurRadius, + child: ClipRRect( + borderRadius: BorderRadius.circular(9999), + child: BackdropFilter( + filter: ImageFilter.blur( + sigmaX: theme.blurSigma, + sigmaY: theme.blurSigma, + ), + child: Container( + height: theme.navHeight, + decoration: BoxDecoration( + color: bg, + borderRadius: BorderRadius.circular(9999), + border: Border.all(color: border, width: theme.borderWidth), + ), + child: Padding( + padding: EdgeInsets.symmetric( + horizontal: theme.horizontalPadding, + ), + child: Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + for (int i = 0; i < items.length; i++) ...[ + _NavCell( + item: items[i], + active: i == currentIndex, + theme: theme, + chipBg: chipBg, + chipContent: chipContent, + inactiveContent: inactiveContent, + onTap: () => onTap(i), + ), + if (i < items.length - 1) + SizedBox(width: theme.itemSpacing), + ], + ], + ), + ), + ), + ), + ), + ), + ), + ); + } +} + +// ───────────────────────────────────────────────────────────────────────────── +// _ShadowWrapper — outer drop-shadow + ambient glow +// ───────────────────────────────────────────────────────────────────────────── + +/// Applies a drop-shadow and ambient glow **outside** the clipped pill shape. +/// Must be a separate widget because [ClipRRect] clips its own BoxDecoration +/// shadows. +class _ShadowWrapper extends StatelessWidget { + const _ShadowWrapper({ + required this.outerShadow, + required this.outerGlow, + required this.shadowBlurRadius, + required this.shadowSpread, + required this.shadowOffset, + required this.glowBlurRadius, + required this.child, + }); + + final Color outerShadow; + final Color outerGlow; + final double shadowBlurRadius; + final double shadowSpread; + final Offset shadowOffset; + final double glowBlurRadius; + final Widget child; + + @override + Widget build(BuildContext context) { + return Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(9999), + boxShadow: [ + BoxShadow( + color: outerShadow, + blurRadius: shadowBlurRadius, + spreadRadius: shadowSpread, + offset: shadowOffset, + ), + BoxShadow(color: outerGlow, blurRadius: glowBlurRadius), + ], + ), + child: child, + ); + } +} + +// ───────────────────────────────────────────────────────────────────────────── +// _NavCell — stateful, spring-animated expanding chip +// ───────────────────────────────────────────────────────────────────────────── + +/// A single tappable chip inside [FloatingNavBar]. +/// +/// When [active] becomes `true`, the chip expands rightward using a +/// [SpringSimulation] (bouncy, lively) to reveal the label text. +/// When [active] becomes `false`, the chip collapses with a quick ease-in. +class _NavCell extends StatefulWidget { + const _NavCell({ + required this.item, + required this.active, + required this.theme, + required this.chipBg, + required this.chipContent, + required this.inactiveContent, + required this.onTap, + }); + + final FloatingNavItem item; + final bool active; + final FloatingNavBarTheme theme; + final Color chipBg; + final Color chipContent; + final Color inactiveContent; + final VoidCallback onTap; + + @override + State<_NavCell> createState() => _NavCellState(); +} + +class _NavCellState extends State<_NavCell> + with SingleTickerProviderStateMixin { + /// Unbounded controller so the spring can overshoot > 1.0 naturally, + /// producing the satisfying bounce on expansion. + late final AnimationController _ctrl; + + @override + void initState() { + super.initState(); + _ctrl = AnimationController.unbounded(vsync: this) + ..value = widget.active ? 1.0 : 0.0; + } + + @override + void didUpdateWidget(_NavCell old) { + super.didUpdateWidget(old); + if (old.active == widget.active) return; + + if (widget.active) { + // Spring expand — medium bounce feel, matching DampingRatioMediumBouncy. + _ctrl.animateWith( + SpringSimulation( + SpringDescription.withDampingRatio( + mass: widget.theme.springMass, + stiffness: widget.theme.springStiffness, + ratio: widget.theme.springDampingRatio, + ), + _ctrl.value, + 1.0, + 0.0, // initial velocity + ), + ); + } else { + // Quick ease-in collapse — no spring, feels intentional / snappy. + _ctrl.animateTo( + 0.0, + duration: widget.theme.collapseDuration, + curve: Curves.easeIn, + ); + } + } + + @override + void dispose() { + _ctrl.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final t = widget.theme; + + return Semantics( + button: true, + label: widget.item.label, + selected: widget.active, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () { + if (t.hapticFeedback) HapticFeedback.lightImpact(); + widget.onTap(); + }, + child: AnimatedBuilder( + animation: _ctrl, + builder: (context, _) { + // Raw spring value — may overshoot [0,1] during bounce. + final raw = _ctrl.value; + + // Clamped to [0,1] for colour interpolation (no weird colours). + final colorP = raw.clamp(0.0, 1.0); + + // Width can overshoot slightly for the spring bounce feel. + // Clamp at 1.2× to prevent excessively wide chips on large oscillation. + final widthP = raw.clamp(0.0, 1.2); + + // Label fades in during the second half of expansion. + final labelOpacity = ((colorP - 0.5) * 2.0).clamp(0.0, 1.0); + + // Extra width contributed by the label area. + final extraW = + t.showLabels ? widthP * t.labelWidth : 0.0; + + // Right padding inside chip (breathing room for the label). + final rightPad = t.showLabels ? colorP * 10.0 : 0.0; + + final iconColor = Color.lerp( + widget.inactiveContent, + widget.chipContent, + colorP, + )!; + + return Container( + height: t.chipHeight, + width: (t.iconCellSize + extraW).clamp( + t.iconCellSize, + t.iconCellSize + t.labelWidth * 1.2, + ), + decoration: BoxDecoration( + color: Color.lerp(Colors.transparent, widget.chipBg, colorP), + borderRadius: BorderRadius.circular(9999), + border: colorP > 0.05 + ? Border.all( + color: (t.selectedChipBorderColor ?? widget.chipContent) + .withValues(alpha: 0.28 * colorP), + width: 1.0, + ) + : null, + boxShadow: colorP > 0.05 + ? [ + BoxShadow( + color: + (t.selectedChipShadowColor ?? widget.chipContent) + .withValues(alpha: 0.18 * colorP), + blurRadius: 14, + spreadRadius: -2, + ), + ] + : null, + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(9999), + child: Row( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + // ── Icon (fixed width cell) ────────────────────────────── + SizedBox( + width: t.iconCellSize, + height: t.chipHeight, + child: Center( + child: Stack( + clipBehavior: Clip.none, + alignment: Alignment.center, + children: [ + Icon( + widget.item.iconFor(widget.active), + size: t.iconSize, + color: iconColor, + ), + // Badge dot + if (widget.item.hasBadge) + Positioned( + right: -3, + top: -3, + child: Container( + width: 8, + height: 8, + decoration: BoxDecoration( + color: Colors.red, + shape: BoxShape.circle, + border: Border.all( + // border matches the chip bg for a + // "punched out" halo effect + color: widget.chipBg, + width: 1.5, + ), + ), + ), + ), + ], + ), + ), + ), + + // ── Expanding label area ───────────────────────────────── + if (t.showLabels && extraW > 1.0) ...[ + Opacity( + opacity: labelOpacity, + child: Text( + widget.item.label, + style: (t.labelStyle ?? + const TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + letterSpacing: 0.1, + )) + .copyWith(color: widget.chipContent), + maxLines: 1, + softWrap: false, + overflow: TextOverflow.clip, + ), + ), + SizedBox(width: rightPad), + ], + ], + ), + ), + ); + }, + ), + ), + ); + } +} + +// ───────────────────────────────────────────────────────────────────────────── +// FloatingNavBarScaffold — all-in-one convenience wrapper +// ───────────────────────────────────────────────────────────────────────────── + +/// A ready-to-use [Scaffold] that wires [FloatingNavBar] with automatic +/// scroll-aware hide/show logic. +/// +/// Scroll notifications propagate from **any** nested scrollable without +/// any [ScrollController] wiring in child widgets. +/// +/// ### Visibility rules +/// | Event | Result | +/// |---|---| +/// | Scroll down `> scrollDownThreshold` | Nav hides | +/// | Scroll up `> scrollUpThreshold` | Nav shows | +/// | Scroll reaches position `0` (top) | Nav always shows | +/// | Tab switch via [onTabChanged] | Nav always shows | +/// +/// ### Bottom content padding +/// The floating nav overlaps content. Add bottom padding to inner lists: +/// ```dart +/// ListView( +/// padding: EdgeInsets.only( +/// bottom: MediaQuery.of(context).padding.bottom +/// + theme.navHeight +/// + theme.bottomMargin +/// + 8, +/// ), +/// ) +/// ``` +class FloatingNavBarScaffold extends StatefulWidget { + const FloatingNavBarScaffold({ + super.key, + required this.items, + required this.body, + required this.currentIndex, + required this.onTabChanged, + this.theme = const FloatingNavBarTheme(), + this.scaffoldBackgroundColor, + }) : assert( + items.length >= 2, + 'FloatingNavBarScaffold requires at least 2 items.', + ); + + /// Tab definitions. Minimum 2. + final List items; + + /// Main content — typically an [IndexedStack] or [PageView]. + final Widget body; + + /// Currently selected index, managed by the parent. + final int currentIndex; + + /// Called when the user taps a tab. The parent must update [currentIndex]. + final ValueChanged onTabChanged; + + /// Visual and behavioural config. + final FloatingNavBarTheme theme; + + /// [Scaffold] background colour. + final Color? scaffoldBackgroundColor; + + @override + State createState() => _FloatingNavBarScaffoldState(); +} + +class _FloatingNavBarScaffoldState extends State { + bool _visible = true; + + // ── Tab change — always restore visibility ──────────────────────────────── + + void _handleTabChange(int index) { + if (!_visible) setState(() => _visible = true); + widget.onTabChanged(index); + } + + // ── Scroll detection ────────────────────────────────────────────────────── + + bool _handleScrollNotification(ScrollNotification n) { + if (!widget.theme.hideOnScroll) return false; + + if (n is ScrollUpdateNotification) { + final delta = n.scrollDelta ?? 0; + + if (delta > widget.theme.scrollDownThreshold && _visible) { + setState(() => _visible = false); + } else if (delta < -widget.theme.scrollUpThreshold && !_visible) { + setState(() => _visible = true); + } + + // At the very top → always show. + if (n.metrics.pixels <= 0 && !_visible) { + setState(() => _visible = true); + } + } + + // Never absorb — let notifications keep bubbling. + return false; + } + + // ── Build ───────────────────────────────────────────────────────────────── + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: widget.scaffoldBackgroundColor, + body: Stack( + children: [ + // Content: scroll notifications propagate upward from here. + NotificationListener( + onNotification: _handleScrollNotification, + child: widget.body, + ), + + // Floating nav bar with slide + fade animation. + AnimatedSlide( + offset: _visible ? Offset.zero : widget.theme.slideHideOffset, + duration: _visible + ? widget.theme.showDuration + : widget.theme.hideDuration, + curve: + _visible ? widget.theme.showCurve : widget.theme.hideCurve, + child: AnimatedOpacity( + opacity: _visible ? 1.0 : 0.0, + duration: _visible + ? widget.theme.showDuration + : Duration( + milliseconds: (widget.theme.hideDuration.inMilliseconds * + widget.theme.fadeOutDurationFactor) + .round(), + ), + curve: + _visible ? widget.theme.showCurve : widget.theme.hideCurve, + // Disable hit-testing when fully hidden. + child: IgnorePointer( + ignoring: !_visible, + child: FloatingNavBar( + currentIndex: widget.currentIndex, + onTap: _handleTabChange, + items: widget.items, + theme: widget.theme, + ), + ), + ), + ), + ], + ), + ); + } +} diff --git a/workout-logger/lib/screens/widgets/rf_widgets.dart b/workout-logger/lib/screens/widgets/rf_widgets.dart index 5316d69..b5a5c9e 100644 --- a/workout-logger/lib/screens/widgets/rf_widgets.dart +++ b/workout-logger/lib/screens/widgets/rf_widgets.dart @@ -2,7 +2,6 @@ // All widgets consume AppColors/AppSpacing/AppRadius tokens only. import 'dart:math' as math; -import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../../theme/app_theme.dart'; @@ -135,186 +134,10 @@ class AmbientGlow extends StatelessWidget { } } -// ── RFNavBar ───────────────────────────────────────────────────────────────── -// Compact floating glassmorphic pill — auto-sized to fit icons only. -// Active state: butter-smooth AnimatedAlign sliding highlight pill behind icon. -class RFNavBar extends StatelessWidget { - const RFNavBar({ - super.key, - required this.currentIndex, - required this.onTap, - required this.items, - }); - - final int currentIndex; - final ValueChanged onTap; - final List items; - - // Each icon cell is 52px wide; pill is 44×44px; outer pad 6px each side. - // navW = items.length * _cellW + _hPad * 2 → 4×52 + 12 = 220px - // Outer container effective corner radius ≈ 56/2 = 28px. - // Pill left for cell n = _hPad + n*_cellW + (_cellW-_pillW)/2 - // = 6 + n*52 + 4 = 10 + n*52 - // → n=0→10, n=1→62, n=2→114, n=3→166; right edge n=3→210 (10px margin both sides) - // Both inner and outer radii are AppRadius.full so they are always concentric. - static const double _cellW = 52; - static const double _pillW = 44; - static const double _pillH = 44; - static const double _hPad = 6; - static const double _navH = 56; - - /// Pixel offset of the pill's left edge for tab [n], relative to container left. - static double _pillLeft(int n) => - _hPad + n * _cellW + (_cellW - _pillW) / 2; - - @override - Widget build(BuildContext context) { - final bottomPadding = MediaQuery.of(context).padding.bottom; - final double navW = items.length * _cellW + _hPad * 2; - - return Align( - alignment: Alignment.bottomCenter, - child: Padding( - padding: EdgeInsets.only( - bottom: bottomPadding > 0 ? bottomPadding : 16, - ), - child: Container( - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(AppRadius.full), - boxShadow: [ - BoxShadow( - color: Colors.black.withValues(alpha: 0.45), - blurRadius: 28, - spreadRadius: -4, - offset: const Offset(0, 10), - ), - BoxShadow( - color: AppColors.primary.withValues(alpha: 0.08), - blurRadius: 32, - spreadRadius: 0, - ), - ], - ), - child: ClipRRect( - borderRadius: BorderRadius.circular(AppRadius.full), - child: BackdropFilter( - filter: ImageFilter.blur(sigmaX: 18, sigmaY: 18), - child: Container( - width: navW, - height: 56, - decoration: BoxDecoration( - color: AppColors.surface.withValues(alpha: 0.82), - borderRadius: BorderRadius.circular(AppRadius.full), - border: Border.all( - color: AppColors.glassBorderStrong, - width: 1.2, - ), - ), - child: Stack( - clipBehavior: Clip.hardEdge, - children: [ - // ── Sliding pill highlight ──────────────────────────── - // AnimatedPositioned guarantees exact pixel alignment so - // the pill is always concentric with the outer container. - AnimatedPositioned( - duration: AppDurations.moderate, - curve: Curves.easeInOutCubic, - left: _pillLeft(currentIndex), - top: (_navH - _pillH) / 2, - width: _pillW, - height: _pillH, - child: Container( - decoration: BoxDecoration( - color: AppColors.glass3, - borderRadius: BorderRadius.circular(AppRadius.full), - border: Border.all( - color: AppColors.primary.withValues(alpha: 0.25), - width: 1, - ), - boxShadow: [ - BoxShadow( - color: AppColors.primary.withValues(alpha: 0.15), - blurRadius: 12, - spreadRadius: -2, - ), - ], - ), - ), - ), - // ── Icon row ──────────────────────────────────────── - Padding( - padding: const EdgeInsets.symmetric(horizontal: _hPad), - child: Row( - mainAxisSize: MainAxisSize.min, - children: List.generate(items.length, (i) { - final active = i == currentIndex; - return _NavCell( - item: items[i], - active: active, - onTap: () => onTap(i), - ); - }), - ), - ), - ], - ), - ), - ), - ), - ), - ), - ); - } -} +// ── Nav bar ────────────────────────────────────────────────────────────────── +// Moved to floating_nav_bar.dart (zero-dependency, drop-in portable widget). +// Import and use FloatingNavBar / FloatingNavBarScaffold / FloatingNavItem. -class RFNavItem { - const RFNavItem({required this.icon, required this.label}); - final IconData icon; - final String label; // kept for semantics / accessibility -} - -class _NavCell extends StatelessWidget { - const _NavCell({ - required this.item, - required this.active, - required this.onTap, - }); - - final RFNavItem item; - final bool active; - final VoidCallback onTap; - - @override - Widget build(BuildContext context) { - return Semantics( - button: true, - label: item.label, - selected: active, - child: GestureDetector( - onTap: onTap, - behavior: HitTestBehavior.opaque, - child: SizedBox( - width: RFNavBar._cellW, - height: 56, - child: Center( - child: AnimatedScale( - scale: active ? 1.12 : 1.0, - duration: AppDurations.moderate, - curve: Curves.easeInOutCubic, - child: Icon( - item.icon, - size: 22, - color: active - ? AppColors.textPrimary - : AppColors.textMuted, - ), - ), - ), - ), - ), - ); - } -} // ── GlowButton ────────────────────────────────────────────────────────────── // Full-width primary action button with glow shadow + haptic feedback. diff --git a/workout-logger/scripts/build_release.py b/workout-logger/scripts/build_release.py new file mode 100644 index 0000000..4248c7d --- /dev/null +++ b/workout-logger/scripts/build_release.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +import os +import subprocess +import sys +from pathlib import Path + +def load_env_file(env_path: Path): + """Loads key-value pairs from a .env file into os.environ.""" + if not env_path.exists(): + return + with open(env_path, "r", encoding="utf-8") as f: + for line in f: + line = line.strip() + if not line or line.startswith("#") or "=" not in line: + continue + key, val = line.split("=", 1) + # Remove whitespace and wrapping quotes if present + val = val.strip().strip("'\"") + os.environ[key.strip()] = val + +def main(): + script_dir = Path(__file__).resolve().parent + project_dir = script_dir.parent if script_dir.name == "scripts" else script_dir + os.chdir(project_dir) + + env_file = project_dir / ".env" + if env_file.exists(): + print(f"Loading environment from {env_file}") + load_env_file(env_file) + else: + print("No .env file found. Using existing environment variables.") + + cmd = [ + "flutter", "build", "apk", + "--release", + "--target-platform", "android-arm64", + "--obfuscate", + "--split-debug-info=build/app/outputs/symbols" + ] + + print(f"Executing: {' '.join(cmd)}") + result = subprocess.run(cmd, env=os.environ, shell=(sys.platform == "win32")) + sys.exit(result.returncode) + +if __name__ == "__main__": + main() From 39385981672db69b16f9cb6b6c86a19ab15d5b1d Mon Sep 17 00:00:00 2001 From: Devasy Patel <110348311+Devasy23@users.noreply.github.com> Date: Thu, 23 Jul 2026 14:24:54 +0530 Subject: [PATCH 10/14] Adds build script and upgrades the release workflow --- .github/workflows/release.yml | 19 +++++++++++++++---- .github/workflows/test.yml | 13 +++++++++++-- workout-logger/scripts/build_release.py | 12 +++--------- 3 files changed, 29 insertions(+), 15 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 393c5ca..0d02413 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -6,6 +6,10 @@ on: - main workflow_dispatch: +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false + jobs: release: name: Build and Release APK @@ -18,17 +22,20 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v7 with: fetch-depth: 0 # Fetch all history for proper versioning token: ${{ secrets.GITHUB_TOKEN }} - name: Set up Java - uses: actions/setup-java@v4 + uses: actions/setup-java@v5 with: distribution: 'temurin' java-version: '17' + - name: Setup Gradle Build Cache + uses: gradle/actions/setup-gradle@v6 + - name: Set up Flutter uses: subosito/flutter-action@v2 with: @@ -117,6 +124,10 @@ jobs: - name: Decode release keystore run: | + if [ -z "${{ secrets.KEYSTORE_BASE64 }}" ]; then + echo "Error: KEYSTORE_BASE64 secret is not configured in repository secrets." + exit 1 + fi echo "${{ secrets.KEYSTORE_BASE64 }}" | base64 --decode > /tmp/repforge-release.jks - name: Build APK @@ -126,7 +137,7 @@ jobs: KEY_STORE_PASSWORD: ${{ secrets.KEY_STORE_PASSWORD }} KEY_ALIAS: ${{ secrets.KEY_ALIAS }} KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }} - run: flutter build apk --release --split-per-abi + run: flutter build apk --release --split-per-abi --obfuscate --split-debug-info=build/app/outputs/symbols - name: Rename APKs run: | @@ -150,7 +161,7 @@ jobs: - name: Create GitHub Release if: github.event_name == 'push' && steps.commit_version.outputs.committed == 'true' - uses: softprops/action-gh-release@v2 + uses: softprops/action-gh-release@v3 with: tag_name: v${{ steps.version.outputs.value }} name: RepForge v${{ steps.version.outputs.value }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 62890d7..15a27b4 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -8,14 +8,21 @@ on: release: types: [published] +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + jobs: test: name: Analyze & Test runs-on: ubuntu-latest + permissions: + contents: read + steps: - name: Checkout repository - uses: actions/checkout@v6 + uses: actions/checkout@v7 - name: Set up Flutter id: flutter-action @@ -28,13 +35,14 @@ jobs: pub-cache-key: "flutter-pub-:os:-:channel:-:version:-:arch:-${{ hashFiles('workout-logger/pubspec.lock') }}" - name: Install dependencies - if: steps.flutter-action.outputs.PUB-CACHE-HIT != 'true' + if: steps.flutter-action.outputs.CACHE-HIT != 'true' working-directory: ./workout-logger run: flutter pub get - name: Analyze working-directory: ./workout-logger run: | + set -o pipefail # Only fail on errors, ignore warnings and info messages flutter analyze --no-fatal-infos --no-fatal-warnings | tee analyze_output.txt @@ -53,3 +61,4 @@ jobs: with: files: workout-logger/coverage/lcov.info token: ${{ secrets.CODECOV_TOKEN }} + diff --git a/workout-logger/scripts/build_release.py b/workout-logger/scripts/build_release.py index 4248c7d..619b442 100644 --- a/workout-logger/scripts/build_release.py +++ b/workout-logger/scripts/build_release.py @@ -30,16 +30,10 @@ def main(): else: print("No .env file found. Using existing environment variables.") - cmd = [ - "flutter", "build", "apk", - "--release", - "--target-platform", "android-arm64", - "--obfuscate", - "--split-debug-info=build/app/outputs/symbols" - ] + cmd = "flutter build apk --release --target-platform android-arm64 --obfuscate --split-debug-info=build/app/outputs/symbols" - print(f"Executing: {' '.join(cmd)}") - result = subprocess.run(cmd, env=os.environ, shell=(sys.platform == "win32")) + print(f"Executing: {cmd}") + result = subprocess.run(cmd, env=os.environ, shell=True) sys.exit(result.returncode) if __name__ == "__main__": From 6553a7d09d30dee776c3a9b417b0a430998038d3 Mon Sep 17 00:00:00 2001 From: Devasy Patel <110348311+Devasy23@users.noreply.github.com> Date: Thu, 23 Jul 2026 15:45:42 +0530 Subject: [PATCH 11/14] Adds tests --- workout-logger/test/api_service_test.dart | 124 ++++++++++++ .../test/debug_log_buffer_test.dart | 62 ++++++ .../test/gemini_context_builder_test.dart | 88 +++++++++ .../test/settings_provider_test.dart | 126 ++++++++++++ .../test/sleep_hr_builder_test.dart | 117 +++++++++++ workout-logger/test/sleep_hr_models_test.dart | 149 ++++++++++++++ workout-logger/test/storage_service_test.dart | 181 ++++++++++++++++++ ...flow_history_and_session_details_test.dart | 153 +++++++++++++++ .../test/userflow_routine_creation_test.dart | 123 ++++++++++++ .../userflow_settings_and_storage_test.dart | 78 ++++++++ .../test/userflow_workout_logging_test.dart | 137 +++++++++++++ 11 files changed, 1338 insertions(+) create mode 100644 workout-logger/test/api_service_test.dart create mode 100644 workout-logger/test/debug_log_buffer_test.dart create mode 100644 workout-logger/test/gemini_context_builder_test.dart create mode 100644 workout-logger/test/settings_provider_test.dart create mode 100644 workout-logger/test/sleep_hr_builder_test.dart create mode 100644 workout-logger/test/sleep_hr_models_test.dart create mode 100644 workout-logger/test/storage_service_test.dart create mode 100644 workout-logger/test/userflow_history_and_session_details_test.dart create mode 100644 workout-logger/test/userflow_routine_creation_test.dart create mode 100644 workout-logger/test/userflow_settings_and_storage_test.dart create mode 100644 workout-logger/test/userflow_workout_logging_test.dart diff --git a/workout-logger/test/api_service_test.dart b/workout-logger/test/api_service_test.dart new file mode 100644 index 0000000..7ef55bd --- /dev/null +++ b/workout-logger/test/api_service_test.dart @@ -0,0 +1,124 @@ +import 'dart:convert'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:repforge/services/api_service.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late Box settingsBox; + late ApiService service; + + setUpAll(() async { + Hive.init('./test/tmp_hive_api_service'); + if (Hive.isBoxOpen('settings')) { + settingsBox = Hive.box('settings'); + } else { + settingsBox = await Hive.openBox('settings'); + } + }); + + setUp(() { + service = ApiService(); + }); + + tearDownAll(() async { + await settingsBox.close(); + await Hive.deleteFromDisk(); + }); + + group('ApiService', () { + test('userAppId returns non-empty string and persists to box', () async { + final id = await service.userAppId; + expect(id, isNotEmpty); + expect(settingsBox.get('user_app_id'), equals(id)); + + final secondCall = await service.userAppId; + expect(secondCall, equals(id)); + }); + + test('sendHeartbeat sends POST request to /heartbeat', () async { + bool called = false; + final mockClient = MockClient((request) async { + if (request.url.path == '/heartbeat') { + called = true; + final jsonBody = jsonDecode(request.body) as Map; + expect(jsonBody.containsKey('user_app_id'), isTrue); + expect(jsonBody.containsKey('platform'), isTrue); + return http.Response('{"status": "ok"}', 200); + } + return http.Response('Not Found', 404); + }); + + ApiService.setTestClient(mockClient); + await service.sendHeartbeat(); + expect(called, isTrue); + }); + + test('trackEvent sends POST request to /event with metadata', () async { + bool called = false; + final mockClient = MockClient((request) async { + if (request.url.path == '/event') { + called = true; + final jsonBody = jsonDecode(request.body) as Map; + expect(jsonBody['event'], equals('workout_started')); + expect(jsonBody['metadata'], equals({'routine_id': 'rot_123'})); + return http.Response('{"status": "ok"}', 200); + } + return http.Response('Not Found', 404); + }); + + ApiService.setTestClient(mockClient); + await service.trackEvent('workout_started', metadata: {'routine_id': 'rot_123'}); + expect(called, isTrue); + }); + + test('reportUsage posts stats to /report', () async { + bool called = false; + final mockClient = MockClient((request) async { + if (request.url.path == '/report') { + called = true; + final jsonBody = jsonDecode(request.body) as Map; + expect(jsonBody['total_workouts'], equals(15)); + expect(jsonBody['weekly_volume'], equals(12500.0)); + return http.Response('{"status": "ok"}', 200); + } + return http.Response('Error', 500); + }); + + ApiService.setTestClient(mockClient); + await service.reportUsage({ + 'totalWorkouts': 15, + 'weeklyWorkouts': 3, + 'weeklyVolume': 12500.0, + 'exercisesThisWeek': 12, + }); + expect(called, isTrue); + }); + + test('backupData posts backup payload and returns true on 200', () async { + final mockClient = MockClient((request) async { + if (request.url.path == '/backup') { + return http.Response('{"status": "success"}', 200); + } + return http.Response('Forbidden', 403); + }); + + ApiService.setTestClient(mockClient); + final result = await service.backupData({'routines': [], 'sessions': []}); + expect(result, isTrue); + }); + + test('backupData returns false on error status', () async { + final mockClient = MockClient((request) async { + return http.Response('Error', 500); + }); + + ApiService.setTestClient(mockClient); + final result = await service.backupData({}); + expect(result, isFalse); + }); + }); +} diff --git a/workout-logger/test/debug_log_buffer_test.dart b/workout-logger/test/debug_log_buffer_test.dart new file mode 100644 index 0000000..3fbcfca --- /dev/null +++ b/workout-logger/test/debug_log_buffer_test.dart @@ -0,0 +1,62 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:repforge/services/debug_log_buffer.dart'; + +void main() { + group('DebugLogBuffer', () { + late DebugLogBuffer buffer; + late DebugPrintCallback originalDebugPrint; + + setUp(() { + originalDebugPrint = debugPrint; + buffer = DebugLogBuffer.instance; + buffer.clear(); + }); + + tearDown(() { + debugPrint = originalDebugPrint; + buffer.clear(); + }); + + test('initial lines list is empty', () { + expect(buffer.lines, isEmpty); + }); + + test('attach intercepts debugPrint and appends timestamped message', () { + DebugLogBuffer.attach(); + + bool notified = false; + buffer.addListener(() { + notified = true; + }); + + debugPrint('Test log message'); + + expect(buffer.lines, hasLength(1)); + expect(buffer.lines.first, contains('Test log message')); + expect(buffer.lines.first, matches(RegExp(r'^\[\d{2}:\d{2}:\d{2}\] Test log message$'))); + expect(notified, isTrue); + }); + + test('clear wipes all logs and notifies listeners', () { + DebugLogBuffer.attach(); + debugPrint('Message 1'); + debugPrint('Message 2'); + expect(buffer.lines, hasLength(2)); + + bool notified = false; + buffer.addListener(() { + notified = true; + }); + + buffer.clear(); + + expect(buffer.lines, isEmpty); + expect(notified, isTrue); + }); + + test('lines is unmodifiable', () { + expect(() => buffer.lines.add('direct add'), throwsUnsupportedError); + }); + }); +} diff --git a/workout-logger/test/gemini_context_builder_test.dart b/workout-logger/test/gemini_context_builder_test.dart new file mode 100644 index 0000000..8b28ddf --- /dev/null +++ b/workout-logger/test/gemini_context_builder_test.dart @@ -0,0 +1,88 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:repforge/models/models.dart'; +import 'package:repforge/services/gemini_context_builder.dart'; + +void main() { + group('GeminiContextBuilder', () { + test('buildCoachSystemPrompt includes today date, unit label, and username', () { + final now = DateTime(2026, 7, 23); + final prompt = GeminiContextBuilder.buildCoachSystemPrompt( + userName: 'Devasy', + unitLabel: 'lbs', + now: now, + ); + + expect(prompt, contains('Today is 2026-07-23')); + expect(prompt, contains('Weights are in lbs')); + expect(prompt, contains("The user's name is Devasy")); + expect(prompt, contains('RepForge')); + }); + + test('buildOptimizerSystemPrompt builds routine optimizer system prompt', () { + final now = DateTime(2026, 7, 23); + final prompt = GeminiContextBuilder.buildOptimizerSystemPrompt( + userName: 'Devasy', + unitLabel: 'kg', + now: now, + ); + + expect(prompt, contains('specialized routine optimizer')); + expect(prompt, contains('Today is 2026-07-23')); + expect(prompt, contains('Weights are in kg')); + expect(prompt, contains("The user's name is Devasy")); + }); + + test('buildWeeklyInsightsContext formats sessions and volumes for this and last week', () { + final exerciseMap = { + 'ex1': Exercise( + id: 'ex1', + name: 'Bench Press', + category: 'compound', + muscleActivations: [ + MuscleActivation(muscleGroupId: 'chest', activationPercentage: 100), + ], + ), + }; + + final thisWeekSession = WorkoutSession( + id: 's1', + date: DateTime(2026, 7, 20), // Monday + duration: 45, + exercises: [ + ExerciseLog( + exerciseId: 'ex1', + sets: [ + WorkoutSet(weight: 100, reps: 10), + ], + ), + ], + ); + + final lastWeekSession = WorkoutSession( + id: 's2', + date: DateTime(2026, 7, 13), // Monday + duration: 45, + exercises: [ + ExerciseLog( + exerciseId: 'ex1', + sets: [ + WorkoutSet(weight: 95, reps: 10), + ], + ), + ], + ); + + final result = GeminiContextBuilder.buildWeeklyInsightsContext( + thisWeek: [thisWeekSession], + lastWeek: [lastWeekSession], + exerciseMap: exerciseMap, + unitLabel: 'kg', + ); + + expect(result, contains('THIS WEEK — 1 sessions')); + expect(result, contains('Bench Press 1×sets (1000kg vol)')); + expect(result, contains('LAST WEEK — 1 sessions')); + expect(result, contains('Mon: Bench Press')); + }); + }); +} diff --git a/workout-logger/test/settings_provider_test.dart b/workout-logger/test/settings_provider_test.dart new file mode 100644 index 0000000..83ea320 --- /dev/null +++ b/workout-logger/test/settings_provider_test.dart @@ -0,0 +1,126 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:repforge/services/settings_provider.dart'; +import 'test_utils/mock_storage_service.dart'; + +void main() { + group('SettingsProvider', () { + late MockStorageService mockStorage; + late SettingsProvider provider; + + setUp(() { + mockStorage = MockStorageService(); + provider = SettingsProvider(mockStorage); + }); + + test('initial values and fallback defaults before init', () { + expect(provider.weightUnit, equals(WeightUnit.kg)); + expect(provider.unitLabel, equals('kg')); + expect(provider.weightIncrement, equals(2.5)); + expect(provider.healthConnectEnabled, isFalse); + expect(provider.readinessEnabled, isFalse); + expect(provider.userName, isNull); + expect(provider.geminiApiKey, isEmpty); + expect(provider.geminiModel, equals('gemini-2.5-flash')); + expect(provider.showAdvancedMetrics, isFalse); + }); + + test('init loads saved settings from storage', () async { + await mockStorage.saveSetting('weightUnit', 'lbs'); + await mockStorage.saveSetting('weightIncrement', '5.0'); + await mockStorage.saveSetting('healthConnectEnabled', 'true'); + await mockStorage.saveSetting('readinessEnabled', 'true'); + await mockStorage.saveSetting('userName', 'Devasy'); + await mockStorage.saveSetting('geminiApiKey', 'secret_key'); + await mockStorage.saveSetting('geminiModel', 'gemini-1.5-pro'); + await mockStorage.saveSetting('showAdvancedMetrics', 'true'); + + await provider.init(); + + expect(provider.weightUnit, equals(WeightUnit.lbs)); + expect(provider.unitLabel, equals('lbs')); + expect(provider.weightIncrement, equals(5.0)); + expect(provider.healthConnectEnabled, isTrue); + expect(provider.readinessEnabled, isTrue); + expect(provider.userName, equals('Devasy')); + expect(provider.geminiApiKey, equals('secret_key')); + expect(provider.geminiModel, equals('gemini-1.5-pro')); + expect(provider.showAdvancedMetrics, isTrue); + }); + + test('setUserName updates state and notifies listeners', () async { + bool notified = false; + provider.addListener(() => notified = true); + + await provider.setUserName(' John Doe '); + + expect(provider.userName, equals('John Doe')); + expect(mockStorage.settings['userName'], equals('John Doe')); + expect(notified, isTrue); + }); + + test('setWeightUnit updates weightUnit, default increment, and saves settings', () async { + await provider.setWeightUnit(WeightUnit.lbs); + + expect(provider.weightUnit, equals(WeightUnit.lbs)); + expect(provider.unitLabel, equals('lbs')); + expect(provider.weightIncrement, equals(5.0)); + expect(mockStorage.settings['weightUnit'], equals('lbs')); + expect(mockStorage.settings['weightIncrement'], equals('5.0')); + + await provider.setWeightUnit(WeightUnit.kg); + + expect(provider.weightUnit, equals(WeightUnit.kg)); + expect(provider.unitLabel, equals('kg')); + expect(provider.weightIncrement, equals(2.5)); + }); + + test('weight conversions and formatting for kg and lbs', () async { + // In kg mode + expect(provider.toDisplay(100.0), equals(100.0)); + expect(provider.toStorage(100.0), equals(100.0)); + expect(provider.formatWeight(100.0), equals('100 kg')); + expect(provider.formatWeight(102.5), equals('102.5 kg')); + + // Switch to lbs mode + await provider.setWeightUnit(WeightUnit.lbs); + + expect(provider.toDisplay(100.0), closeTo(220.462, 0.01)); + expect(provider.toStorage(220.462), closeTo(100.0, 0.01)); + expect(provider.formatWeight(100.0), equals('220.5 lbs')); + }); + + test('setters for healthConnect, readiness, gemini, and advanced metrics', () async { + await provider.setHealthConnectEnabled(true); + expect(provider.healthConnectEnabled, isTrue); + expect(mockStorage.settings['healthConnectEnabled'], equals('true')); + + await provider.setReadinessEnabled(true); + expect(provider.readinessEnabled, isTrue); + expect(mockStorage.settings['readinessEnabled'], equals('true')); + + await provider.setGeminiApiKey('key123'); + expect(provider.geminiApiKey, equals('key123')); + + await provider.setGeminiModel('custom-model'); + expect(provider.geminiModel, equals('custom-model')); + + await provider.setShowAdvancedMetrics(true); + expect(provider.showAdvancedMetrics, isTrue); + }); + + test('saveWeeklyInsights updates insights string and date', () async { + await provider.saveWeeklyInsights('Great progress this week!'); + + expect(provider.weeklyInsights, equals('Great progress this week!')); + expect(provider.weeklyInsightsDate, isNotNull); + expect(mockStorage.settings['weeklyInsights'], equals('Great progress this week!')); + }); + + test('availableIncrements returns correct values for unit', () async { + expect(provider.availableIncrements, equals([1.25, 2.5, 5.0, 10.0])); + + await provider.setWeightUnit(WeightUnit.lbs); + expect(provider.availableIncrements, equals([2.5, 5.0, 10.0, 25.0])); + }); + }); +} diff --git a/workout-logger/test/sleep_hr_builder_test.dart b/workout-logger/test/sleep_hr_builder_test.dart new file mode 100644 index 0000000..9885fa9 --- /dev/null +++ b/workout-logger/test/sleep_hr_builder_test.dart @@ -0,0 +1,117 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:repforge/models/models.dart'; +import 'package:repforge/models/sleep_hr_models.dart'; +import 'package:repforge/services/interfaces/health_connect_service_interface.dart'; +import 'package:repforge/services/utils/sleep_hr_builder.dart'; + +class _StubHcService implements IHealthConnectService { + final List sleepPeriods; + final List hrSamples; + final List restingHrSamples; + + _StubHcService({ + this.sleepPeriods = const [], + this.hrSamples = const [], + this.restingHrSamples = const [], + }); + + @override + Future> readSleepSessions(DateTime start, DateTime end) async => sleepPeriods; + @override + Future> readHeartRateSamples(DateTime start, DateTime end) async => hrSamples; + @override + Future> readRestingHeartRate(DateTime start, DateTime end) async => restingHrSamples; + @override + Future> grantedReadTypes() async => {HealthReadType.heartRate, HealthReadType.sleep}; + @override + Future> readHrvRmssd(DateTime start, DateTime end) async => const []; + @override + Future isAvailable() async => true; + @override + Future requestPermissions() async => true; + @override + Future hasPermissions() async => true; + @override + Future requestReadPermissions() async => true; + @override + Future syncWorkoutSession(WorkoutSession session, {String? title}) async => true; +} + +void main() { + final granted = {HealthReadType.heartRate, HealthReadType.sleep}; + + group('Sleep & HR Builder Utils', () { + test('buildHrDaySnapshot returns null when no HR samples or resting HR present', () async { + final stubHc = _StubHcService(); + final snapshot = await buildHrDaySnapshot(stubHc, DateTime(2026, 7, 23), granted); + + expect(snapshot, isNull); + }); + + test('buildHrDaySnapshot builds buckets and resting HR for day', () async { + final day = DateTime(2026, 7, 23); + final sample1 = HealthSample( + time: DateTime(2026, 7, 23, 10, 0), + value: 70.0, + ); + final sample2 = HealthSample( + time: DateTime(2026, 7, 23, 10, 15), + value: 120.0, + ); + final resting = HealthSample( + time: DateTime(2026, 7, 23, 8, 0), + value: 58.0, + ); + + final stubHc = _StubHcService( + hrSamples: [sample1, sample2], + restingHrSamples: [resting], + ); + + final snapshot = await buildHrDaySnapshot(stubHc, day, granted); + + expect(snapshot, isNotNull); + expect(snapshot!.minBpm, equals(70)); + expect(snapshot.maxBpm, equals(120)); + expect(snapshot.buckets, isNotEmpty); + }); + + test('buildSleepHrSnapshot calculates sleep stage stats correctly', () async { + final sleepStart = DateTime(2026, 7, 23, 1, 0); + final sleepEnd = DateTime(2026, 7, 23, 7, 0); + + final sleepPeriod = SleepPeriod( + start: sleepStart, + end: sleepEnd, + stageTimeline: [ + SleepStageInterval(start: sleepStart, end: sleepStart.add(const Duration(hours: 2)), stage: 'deep'), + SleepStageInterval(start: sleepStart.add(const Duration(hours: 2)), end: sleepEnd, stage: 'light'), + ], + ); + + final hrSample1 = HealthSample( + time: DateTime(2026, 7, 23, 2, 0), + value: 55.0, + ); + final hrSample2 = HealthSample( + time: DateTime(2026, 7, 23, 2, 3), + value: 57.0, + ); + final hrSample3 = HealthSample( + time: DateTime(2026, 7, 23, 2, 8), + value: 58.0, + ); + + final stubHc = _StubHcService( + sleepPeriods: [sleepPeriod], + hrSamples: [hrSample1, hrSample2, hrSample3], + ); + + final snapshot = await buildSleepHrSnapshot(stubHc, DateTime(2026, 7, 23), granted); + + expect(snapshot, isNotNull); + expect(snapshot!.segments, isNotEmpty); + expect(snapshot.stageStats, isNotEmpty); + }); + }); +} diff --git a/workout-logger/test/sleep_hr_models_test.dart b/workout-logger/test/sleep_hr_models_test.dart new file mode 100644 index 0000000..13a080b --- /dev/null +++ b/workout-logger/test/sleep_hr_models_test.dart @@ -0,0 +1,149 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:repforge/models/sleep_hr_models.dart'; + +void main() { + group('Sleep HR Models Test', () { + test('SleepHrSegment properties', () { + final now = DateTime.now(); + final segment = SleepHrSegment( + windowStart: now, + minBpm: 50, + maxBpm: 70, + avgBpm: 60.0, + stage: 'deep', + ); + + expect(segment.windowStart, equals(now)); + expect(segment.minBpm, equals(50)); + expect(segment.maxBpm, equals(70)); + expect(segment.avgBpm, equals(60.0)); + expect(segment.stage, equals('deep')); + }); + + test('SleepStageStats properties', () { + final stats = SleepStageStats( + stage: 'rem', + minBpm: 55, + p25Bpm: 60, + avgBpm: 65.5, + p75Bpm: 70, + maxBpm: 80, + sampleCount: 20, + ); + + expect(stats.stage, equals('rem')); + expect(stats.minBpm, equals(55)); + expect(stats.p25Bpm, equals(60)); + expect(stats.avgBpm, equals(65.5)); + expect(stats.p75Bpm, equals(70)); + expect(stats.maxBpm, equals(80)); + expect(stats.sampleCount, equals(20)); + }); + + test('SleepHrSnapshot statsFor helper method', () { + final start = DateTime(2026, 1, 1, 23, 0); + final end = DateTime(2026, 1, 2, 7, 0); + + const deepStats = SleepStageStats( + stage: 'deep', + minBpm: 45, + p25Bpm: 50, + avgBpm: 52.0, + p75Bpm: 55, + maxBpm: 60, + sampleCount: 15, + ); + + final snapshot = SleepHrSnapshot( + sleepStart: start, + sleepEnd: end, + p5Bpm: 48, + p95Bpm: 72, + segments: [], + stageStats: [deepStats], + ); + + expect(snapshot.statsFor('deep'), equals(deepStats)); + expect(snapshot.statsFor('rem'), isNull); + }); + + test('HealthGranularity extensions', () { + expect(HealthGranularity.day.label, equals('Day')); + expect(HealthGranularity.week.label, equals('Week')); + expect(HealthGranularity.month.label, equals('Month')); + expect(HealthGranularity.year.label, equals('Year')); + }); + + test('HrBucket JSON roundtrip', () { + final bucket = HrBucket( + windowStart: DateTime(2026, 5, 10, 14, 30), + minBpm: 60, + maxBpm: 120, + avgBpm: 85.5, + ); + + final json = bucket.toJson(); + final restored = HrBucket.fromJson(json); + + expect(restored.windowStart, equals(bucket.windowStart)); + expect(restored.minBpm, equals(bucket.minBpm)); + expect(restored.maxBpm, equals(bucket.maxBpm)); + expect(restored.avgBpm, equals(bucket.avgBpm)); + }); + + test('HrDaySnapshot JSON roundtrip', () { + final bucket = HrBucket( + windowStart: DateTime(2026, 5, 10, 14, 30), + minBpm: 60, + maxBpm: 120, + avgBpm: 85.5, + ); + + final daySnapshot = HrDaySnapshot( + day: DateTime(2026, 5, 10), + restingBpm: 58, + minBpm: 55, + maxBpm: 145, + avgBpm: 78.2, + buckets: [bucket], + ); + + final json = daySnapshot.toJson(); + final restored = HrDaySnapshot.fromJson(json); + + expect(restored.day, equals(daySnapshot.day)); + expect(restored.restingBpm, equals(58)); + expect(restored.minBpm, equals(55)); + expect(restored.maxBpm, equals(145)); + expect(restored.avgBpm, equals(78.2)); + expect(restored.buckets.length, equals(1)); + expect(restored.buckets.first.minBpm, equals(60)); + }); + + test('SleepDayBar & HrRangeBar construction', () { + final bar = SleepDayBar( + date: DateTime(2026, 6, 1), + totalMinutes: 480, + deepMin: 90, + remMin: 110, + lightMin: 250, + awakeMin: 30, + ); + + expect(bar.totalMinutes, equals(480)); + expect(bar.deepMin, equals(90)); + + final hrRange = HrRangeBar( + date: DateTime(2026, 6, 1), + label: 'Mon', + minBpm: 50, + maxBpm: 130, + avgBpm: 72.0, + restingBpm: 54, + ); + + expect(hrRange.label, equals('Mon')); + expect(hrRange.restingBpm, equals(54)); + }); + }); +} diff --git a/workout-logger/test/storage_service_test.dart b/workout-logger/test/storage_service_test.dart new file mode 100644 index 0000000..4517648 --- /dev/null +++ b/workout-logger/test/storage_service_test.dart @@ -0,0 +1,181 @@ +import 'dart:convert'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hive/hive.dart'; +import 'package:repforge/models/models.dart'; +import 'package:repforge/services/storage_service.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late StorageService storage; + + setUpAll(() async { + const MethodChannel channel = MethodChannel('plugins.flutter.io/path_provider'); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + channel, + (MethodCall methodCall) async { + if (methodCall.method == 'getApplicationDocumentsDirectory') { + return './test/tmp_hive_storage_service'; + } + return null; + }, + ); + Hive.init('./test/tmp_hive_storage_service'); + }); + + setUp(() async { + storage = StorageService(); + await storage.init(); + }); + + tearDownAll(() async { + await Hive.close(); + await Hive.deleteFromDisk(); + }); + + group('StorageService CRUD & Operations', () { + test('init initializes default muscle groups', () async { + final groups = await storage.getAllMuscleGroups(); + expect(groups, isNotEmpty); + expect(groups.any((g) => g.name == 'Chest'), isTrue); + }); + + test('WorkoutSession save, get, getAll, getSessionsInDateRange, and delete', () async { + final session1 = WorkoutSession( + id: 's_101', + date: DateTime(2026, 7, 10), + duration: 45, + exercises: [ + ExerciseLog( + exerciseId: 'squat_id', + sets: [WorkoutSet(weight: 100, reps: 5)], + ), + ], + ); + + final session2 = WorkoutSession( + id: 's_102', + date: DateTime(2026, 7, 15), + duration: 60, + exercises: [ + ExerciseLog( + exerciseId: 'bench_id', + sets: [WorkoutSet(weight: 80, reps: 8)], + ), + ], + ); + + await storage.saveWorkoutSession(session1); + await storage.saveWorkoutSession(session2); + + final fetched1 = await storage.getWorkoutSession('s_101'); + expect(fetched1, isNotNull); + expect(fetched1!.duration, equals(45)); + + final allSessions = await storage.getAllWorkoutSessions(); + expect(allSessions.length, greaterThanOrEqualTo(2)); + // Verify most recent session first sorting + expect(allSessions.first.date.isAfter(allSessions[1].date), isTrue); + + final forSquat = await storage.getSessionsForExercise('squat_id'); + expect(forSquat.length, equals(1)); + expect(forSquat.first.id, equals('s_101')); + + final rangeSessions = await storage.getSessionsInDateRange( + DateTime(2026, 7, 12), + DateTime(2026, 7, 20), + ); + expect(rangeSessions.length, equals(1)); + expect(rangeSessions.first.id, equals('s_102')); + + await storage.deleteWorkoutSession('s_101'); + expect(await storage.getWorkoutSession('s_101'), isNull); + }); + + test('Routine CRUD', () async { + final routine = Routine( + id: 'r_101', + name: 'Push Pull Legs - Push', + exerciseIds: ['ex_bench', 'ex_ohp'], + ); + + await storage.saveRoutine(routine); + + final fetched = await storage.getRoutine('r_101'); + expect(fetched, isNotNull); + expect(fetched!.name, equals('Push Pull Legs - Push')); + + final allRoutines = await storage.getAllRoutines(); + expect(allRoutines.any((r) => r.id == 'r_101'), isTrue); + + await storage.deleteRoutine('r_101'); + expect(await storage.getRoutine('r_101'), isNull); + }); + + test('Target CRUD and getTargetsForExercise', () async { + final target = Target( + id: 't_101', + exerciseId: 'ex_bench', + targetValue: 100.0, + targetType: 'weight', + ); + + await storage.saveTarget(target); + + final fetched = await storage.getTarget('t_101'); + expect(fetched, isNotNull); + expect(fetched!.targetValue, equals(100.0)); + + final targetsForBench = await storage.getTargetsForExercise('ex_bench'); + expect(targetsForBench.length, equals(1)); + expect(targetsForBench.first.id, equals('t_101')); + + await storage.deleteTarget('t_101'); + expect(await storage.getTarget('t_101'), isNull); + }); + + test('Custom Exercise save, getAllExercises, getExercise, delete', () async { + final customEx = Exercise( + id: 'custom_ex_999', + name: 'Bulgarian Split Squat Special', + category: 'compound', + muscleActivations: [ + MuscleActivation(muscleGroupId: 'quadriceps', activationPercentage: 100), + ], + isCustom: true, + ); + + await storage.saveCustomExercise(customEx); + + final customList = await storage.getCustomExercises(); + expect(customList.any((e) => e.id == 'custom_ex_999'), isTrue); + + final allExercises = await storage.getAllExercises(); + expect(allExercises.any((e) => e.id == 'custom_ex_999'), isTrue); + + final fetched = await storage.getExercise('custom_ex_999'); + expect(fetched, isNotNull); + expect(fetched!.name, equals('Bulgarian Split Squat Special')); + + await storage.deleteCustomExercise('custom_ex_999'); + expect(await storage.getCustomExercises().then((l) => l.any((e) => e.id == 'custom_ex_999')), isFalse); + }); + + test('Export and import data payload', () async { + await storage.saveSetting('test_setting_key', 'test_val'); + + final exportJsonStr = await storage.exportAllData(); + expect(exportJsonStr, isNotEmpty); + + final exportedMap = jsonDecode(exportJsonStr) as Map; + expect(exportedMap.containsKey('settings'), isTrue); + expect(exportedMap.containsKey('exportDate'), isTrue); + + // Re-import payload + await storage.importData(exportJsonStr); + final val = await storage.getSetting('test_setting_key'); + expect(val, equals('test_val')); + }); + }); +} diff --git a/workout-logger/test/userflow_history_and_session_details_test.dart b/workout-logger/test/userflow_history_and_session_details_test.dart new file mode 100644 index 0000000..4b194a2 --- /dev/null +++ b/workout-logger/test/userflow_history_and_session_details_test.dart @@ -0,0 +1,153 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:repforge/models/models.dart'; +import 'package:repforge/screens/history_screen.dart'; +import 'package:repforge/screens/widgets/session_details_sheet.dart'; +import 'package:repforge/services/interfaces/health_connect_service_interface.dart'; +import 'package:repforge/services/managers/health_history_manager.dart'; +import 'package:repforge/services/managers/history_manager.dart'; +import 'package:repforge/services/managers/program_manager.dart'; +import 'package:repforge/services/settings_provider.dart'; +import 'package:repforge/services/workout_provider.dart'; +import 'test_utils/mock_storage_service.dart'; + +class _StubHcService implements IHealthConnectService { + @override + Future> readSleepSessions(DateTime start, DateTime end) async => const []; + @override + Future> readHeartRateSamples(DateTime start, DateTime end) async => const []; + @override + Future> readRestingHeartRate(DateTime start, DateTime end) async => const []; + @override + Future> grantedReadTypes() async => {}; + @override + Future> readHrvRmssd(DateTime start, DateTime end) async => const []; + @override + Future isAvailable() async => true; + @override + Future requestPermissions() async => true; + @override + Future hasPermissions() async => true; + @override + Future requestReadPermissions() async => true; + @override + Future syncWorkoutSession(WorkoutSession session, {String? title}) async => true; +} + +Widget _buildTestApp({ + required WorkoutProvider workoutProvider, + required SettingsProvider settingsProvider, + required HistoryManager historyManager, + required HealthHistoryManager healthHistoryManager, + required Widget child, +}) { + return MultiProvider( + providers: [ + Provider.value(value: healthHistoryManager), + ChangeNotifierProvider.value(value: workoutProvider), + ChangeNotifierProvider.value(value: settingsProvider), + ChangeNotifierProvider.value(value: historyManager), + ], + child: MaterialApp( + home: child, + ), + ); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late MockStorageService mockStorage; + late WorkoutProvider workoutProvider; + late SettingsProvider settingsProvider; + late HistoryManager historyManager; + late HealthHistoryManager healthHistoryManager; + + setUp(() async { + mockStorage = MockStorageService(); + historyManager = HistoryManager(mockStorage); + healthHistoryManager = HealthHistoryManager(_StubHcService(), mockStorage); + workoutProvider = WorkoutProvider( + mockStorage, + programManager: ProgramManager(mockStorage), + historyManager: historyManager, + ); + settingsProvider = SettingsProvider(mockStorage); + + await workoutProvider.init(); + await settingsProvider.init(); + }); + + group('Userflow 2: History & Session Details Sheet Flow', () { + testWidgets('HistoryScreen renders title when no sessions recorded', (tester) async { + await tester.pumpWidget(_buildTestApp( + workoutProvider: workoutProvider, + settingsProvider: settingsProvider, + historyManager: historyManager, + healthHistoryManager: healthHistoryManager, + child: const HistoryScreen(), + )); + await tester.pumpAndSettle(); + + expect(find.text('History'), findsOneWidget); + }); + + testWidgets('HistoryScreen lists sessions and opens SessionDetailsSheet', (tester) async { + final session = WorkoutSession( + id: 'hist_s1', + date: DateTime.now(), + duration: 60, + exercises: [ + ExerciseLog( + exerciseId: 'squat_id', + sets: [ + WorkoutSet(weight: 140, reps: 5), + WorkoutSet(weight: 140, reps: 5), + ], + ), + ], + ); + + await mockStorage.saveWorkoutSession(session); + await workoutProvider.init(); // Reload sessions from storage + + await tester.pumpWidget(_buildTestApp( + workoutProvider: workoutProvider, + settingsProvider: settingsProvider, + historyManager: historyManager, + healthHistoryManager: healthHistoryManager, + child: const HistoryScreen(), + )); + await tester.pumpAndSettle(); + + // SessionDetailsSheet component test + bool edited = false; + bool deleted = false; + + await tester.pumpWidget(_buildTestApp( + workoutProvider: workoutProvider, + settingsProvider: settingsProvider, + historyManager: historyManager, + healthHistoryManager: healthHistoryManager, + child: Scaffold( + body: DraggableScrollableSheet( + initialChildSize: 1.0, + builder: (ctx, scrollController) => SessionDetailsSheet( + session: session, + provider: workoutProvider, + scrollController: scrollController, + onEdit: () => edited = true, + onDelete: () => deleted = true, + ), + ), + ), + )); + await tester.pumpAndSettle(); + + // Verify SessionDetailsSheet displays details + expect(find.textContaining('60 min'), findsOneWidget); + expect(find.text('Exercises'), findsOneWidget); + }); + }); +} diff --git a/workout-logger/test/userflow_routine_creation_test.dart b/workout-logger/test/userflow_routine_creation_test.dart new file mode 100644 index 0000000..b60a89f --- /dev/null +++ b/workout-logger/test/userflow_routine_creation_test.dart @@ -0,0 +1,123 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:repforge/models/models.dart'; +import 'package:repforge/screens/routines_screen.dart'; +import 'package:repforge/screens/widgets/routine_creator.dart'; +import 'package:repforge/services/managers/program_manager.dart'; +import 'package:repforge/services/settings_provider.dart'; +import 'package:repforge/services/workout_provider.dart'; +import 'test_utils/mock_storage_service.dart'; + +Widget _buildTestApp({ + required WorkoutProvider workoutProvider, + required SettingsProvider settingsProvider, + required Widget child, +}) { + return MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: workoutProvider), + ChangeNotifierProvider.value(value: settingsProvider), + ], + child: MaterialApp( + home: child, + ), + ); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late MockStorageService mockStorage; + late WorkoutProvider workoutProvider; + late SettingsProvider settingsProvider; + + setUp(() async { + mockStorage = MockStorageService(); + workoutProvider = WorkoutProvider( + mockStorage, + programManager: ProgramManager(mockStorage), + ); + settingsProvider = SettingsProvider(mockStorage); + + await workoutProvider.init(); + await settingsProvider.init(); + }); + + group('Userflow 3: Routine Creation & Management Flow', () { + testWidgets('RoutinesScreen renders title, empty state, and new routine button', (tester) async { + await tester.pumpWidget(_buildTestApp( + workoutProvider: workoutProvider, + settingsProvider: settingsProvider, + child: const RoutinesScreen(), + )); + await tester.pumpAndSettle(); + + expect(find.text('Routines'), findsWidgets); + }); + + testWidgets('CreateRoutineScreen renders input fields, selects exercise, and saves new routine', (tester) async { + final exercise = Exercise( + id: 'ex_bench', + name: 'Bench Press', + category: 'compound', + muscleActivations: [ + MuscleActivation(muscleGroupId: 'chest', activationPercentage: 100), + ], + ); + await mockStorage.saveCustomExercise(exercise); + await workoutProvider.init(); + + await tester.pumpWidget(_buildTestApp( + workoutProvider: workoutProvider, + settingsProvider: settingsProvider, + child: const CreateRoutineScreen(), + )); + await tester.pumpAndSettle(); + + expect(find.text('New Routine'), findsOneWidget); + expect(find.text('Save'), findsOneWidget); + + // Enter routine name into TextField + final textField = find.byType(TextField).first; + await tester.enterText(textField, 'Upper Body Hypertrophy'); + await tester.pump(); + + // Tap 'Add Exercises' button to open exercise picker modal + final addBtn = find.text('Add Exercises'); + expect(addBtn, findsOneWidget); + await tester.tap(addBtn); + await tester.pumpAndSettle(); + + // Select 'Bench Press' from picker modal + final benchPressFinder = find.text('Bench Press'); + expect(benchPressFinder, findsWidgets); + await tester.tap(benchPressFinder.first); + await tester.pump(); + + // Tap 'Add 1' button in picker header + await tester.tap(find.text('Add 1')); + await tester.pumpAndSettle(); + + // Tap Save + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + + // Verify routine saved in provider + expect(workoutProvider.routines.any((r) => r.name == 'Upper Body Hypertrophy'), isTrue); + }); + + testWidgets('RoutinesScreen renders saved routines list', (tester) async { + await workoutProvider.createRoutine('Legs & Core Routine', ['ex_squat']); + + await tester.pumpWidget(_buildTestApp( + workoutProvider: workoutProvider, + settingsProvider: settingsProvider, + child: const RoutinesScreen(), + )); + await tester.pumpAndSettle(); + + expect(find.text('Legs & Core Routine'), findsWidgets); + }); + }); +} diff --git a/workout-logger/test/userflow_settings_and_storage_test.dart b/workout-logger/test/userflow_settings_and_storage_test.dart new file mode 100644 index 0000000..385f57d --- /dev/null +++ b/workout-logger/test/userflow_settings_and_storage_test.dart @@ -0,0 +1,78 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:repforge/screens/settings_screen.dart'; +import 'package:repforge/services/api_service.dart'; +import 'package:repforge/services/managers/program_manager.dart'; +import 'package:repforge/services/settings_provider.dart'; +import 'package:repforge/services/workout_provider.dart'; +import 'test_utils/mock_storage_service.dart'; + +Widget _buildTestApp({ + required WorkoutProvider workoutProvider, + required SettingsProvider settingsProvider, + required ApiService apiService, + required Widget child, +}) { + return MultiProvider( + providers: [ + Provider.value(value: apiService), + ChangeNotifierProvider.value(value: workoutProvider), + ChangeNotifierProvider.value(value: settingsProvider), + ], + child: MaterialApp( + home: child, + ), + ); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late MockStorageService mockStorage; + late WorkoutProvider workoutProvider; + late SettingsProvider settingsProvider; + late ApiService apiService; + + setUp(() async { + mockStorage = MockStorageService(); + workoutProvider = WorkoutProvider( + mockStorage, + programManager: ProgramManager(mockStorage), + ); + settingsProvider = SettingsProvider(mockStorage); + apiService = ApiService(); + + await workoutProvider.init(); + await settingsProvider.init(); + }); + + group('Userflow 4: Settings & Storage Flow', () { + testWidgets('SettingsScreen renders title, section headers, and unit options', (tester) async { + await tester.pumpWidget(_buildTestApp( + workoutProvider: workoutProvider, + settingsProvider: settingsProvider, + apiService: apiService, + child: const SettingsScreen(), + )); + await tester.pumpAndSettle(); + + expect(find.text('Settings'), findsOneWidget); + expect(find.text('Preferences'), findsOneWidget); + }); + + testWidgets('Toggling weight unit in SettingsProvider persists to storage and updates display label', (tester) async { + expect(settingsProvider.weightUnit, equals(WeightUnit.kg)); + expect(settingsProvider.unitLabel, equals('kg')); + + await settingsProvider.setWeightUnit(WeightUnit.lbs); + expect(settingsProvider.weightUnit, equals(WeightUnit.lbs)); + expect(settingsProvider.unitLabel, equals('lbs')); + expect(mockStorage.settings['weightUnit'], equals('lbs')); + + await settingsProvider.setWeightIncrement(5.0); + expect(settingsProvider.weightIncrement, equals(5.0)); + expect(mockStorage.settings['weightIncrement'], equals('5.0')); + }); + }); +} diff --git a/workout-logger/test/userflow_workout_logging_test.dart b/workout-logger/test/userflow_workout_logging_test.dart new file mode 100644 index 0000000..d3c07ca --- /dev/null +++ b/workout-logger/test/userflow_workout_logging_test.dart @@ -0,0 +1,137 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:repforge/models/models.dart'; +import 'package:repforge/screens/workout_flow_screen.dart'; +import 'package:repforge/screens/workout_summary_screen.dart'; +import 'package:repforge/screens/widgets/rest_timer_view.dart'; +import 'package:repforge/services/managers/program_manager.dart'; +import 'package:repforge/services/settings_provider.dart'; +import 'package:repforge/services/workout_provider.dart'; +import 'test_utils/mock_storage_service.dart'; + +Widget _buildTestApp({ + required WorkoutProvider workoutProvider, + required SettingsProvider settingsProvider, + required Widget child, +}) { + return MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: workoutProvider), + ChangeNotifierProvider.value(value: settingsProvider), + ], + child: MaterialApp( + home: child, + ), + ); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late MockStorageService mockStorage; + late WorkoutProvider workoutProvider; + late SettingsProvider settingsProvider; + + setUp(() async { + mockStorage = MockStorageService(); + workoutProvider = WorkoutProvider( + mockStorage, + programManager: ProgramManager(mockStorage), + ); + settingsProvider = SettingsProvider(mockStorage); + + await workoutProvider.init(); + await settingsProvider.init(); + }); + + group('Userflow 1: Workout Logging & Rest Timer & Summary Screen Flow', () { + testWidgets('User completes sets, interacts with RestTimerView, and views WorkoutSummaryScreen', (tester) async { + // 1. Save custom exercise and start workout + final exercise = Exercise( + id: 'ex_bench', + name: 'Barbell Bench Press', + category: 'compound', + muscleActivations: [ + MuscleActivation(muscleGroupId: 'chest', activationPercentage: 100), + ], + ); + await mockStorage.saveCustomExercise(exercise); + await workoutProvider.init(); + + workoutProvider.startWorkout(exerciseIds: ['ex_bench']); + + // Render WorkoutFlowScreen + await tester.pumpWidget(_buildTestApp( + workoutProvider: workoutProvider, + settingsProvider: settingsProvider, + child: const WorkoutFlowScreen(), + )); + await tester.pumpAndSettle(); + + // Verify WorkoutFlowScreen renders exercise name + expect(find.text('Barbell Bench Press'), findsWidgets); + + // 2. Test RestTimerView overlay directly to ensure userflow interactive controls work + int adjustDelta = 0; + bool skipped = false; + + await tester.pumpWidget(_buildTestApp( + workoutProvider: workoutProvider, + settingsProvider: settingsProvider, + child: RestTimerView( + remainingSeconds: 60, + totalSeconds: 90, + onAdjust: (delta) => adjustDelta = delta, + onSkip: () => skipped = true, + nextExerciseName: 'Incline Dumbbell Press', + ), + )); + await tester.pumpAndSettle(); + + // Verify RestTimerView header and controls + expect(find.text('REST'), findsWidgets); + expect(find.text('Next up'), findsOneWidget); + expect(find.text('Incline Dumbbell Press'), findsOneWidget); + expect(find.text('SKIP REST'), findsOneWidget); + + // Tap +30s adjust button + await tester.tap(find.text('+30s')); + await tester.pump(); + expect(adjustDelta, equals(30)); + + // Tap SKIP REST button + await tester.tap(find.text('SKIP REST')); + await tester.pump(); + expect(skipped, isTrue); + + // 3. Complete workout and render WorkoutSummaryScreen + final summarySession = WorkoutSession( + id: 'completed_s1', + date: DateTime.now(), + duration: 45, + exercises: [ + ExerciseLog( + exerciseId: 'ex_bench', + sets: [ + WorkoutSet(weight: 100, reps: 10), + WorkoutSet(weight: 100, reps: 8), + ], + ), + ], + ); + + await tester.pumpWidget(_buildTestApp( + workoutProvider: workoutProvider, + settingsProvider: settingsProvider, + child: WorkoutSummaryScreen(session: summarySession), + )); + await tester.pumpAndSettle(); + + // Verify Summary Screen metrics: trophy, stat grid, volume, sets count + expect(find.text('Workout Complete!'), findsOneWidget); + expect(find.text('Done'), findsOneWidget); + expect(find.text('45m'), findsOneWidget); // Duration format + }); + }); +} From fefbd92d2d2e612eaaa328f9dd33fa82c5f6cf23 Mon Sep 17 00:00:00 2001 From: Devasy Patel <110348311+Devasy23@users.noreply.github.com> Date: Thu, 23 Jul 2026 17:07:54 +0530 Subject: [PATCH 12/14] updates acc to review comments --- .../lib/screens/workout_flow_screen.dart | 3 +- .../test/sleep_hr_builder_test.dart | 40 ++---------- workout-logger/test/sleep_hr_models_test.dart | 2 +- .../stub_health_connect_service.dart | 35 +++++++++++ ...flow_history_and_session_details_test.dart | 61 ++++--------------- .../userflow_settings_and_storage_test.dart | 21 ++++++- .../test/userflow_workout_logging_test.dart | 56 ++++++++--------- 7 files changed, 98 insertions(+), 120 deletions(-) create mode 100644 workout-logger/test/test_utils/stub_health_connect_service.dart diff --git a/workout-logger/lib/screens/workout_flow_screen.dart b/workout-logger/lib/screens/workout_flow_screen.dart index 24bbd90..3377710 100644 --- a/workout-logger/lib/screens/workout_flow_screen.dart +++ b/workout-logger/lib/screens/workout_flow_screen.dart @@ -684,8 +684,7 @@ class _WorkoutFlowScreenState extends State { await context.read().finishWorkout(); final newPRs = await prManager.checkAndUpdatePRs(session); if (!mounted) return; - nav.pop(); - nav.push(MaterialPageRoute( + nav.pushReplacement(MaterialPageRoute( builder: (_) => WorkoutSummaryScreen( session: session, newPRs: newPRs, diff --git a/workout-logger/test/sleep_hr_builder_test.dart b/workout-logger/test/sleep_hr_builder_test.dart index 9885fa9..2e8ba27 100644 --- a/workout-logger/test/sleep_hr_builder_test.dart +++ b/workout-logger/test/sleep_hr_builder_test.dart @@ -3,46 +3,14 @@ import 'package:repforge/models/models.dart'; import 'package:repforge/models/sleep_hr_models.dart'; import 'package:repforge/services/interfaces/health_connect_service_interface.dart'; import 'package:repforge/services/utils/sleep_hr_builder.dart'; - -class _StubHcService implements IHealthConnectService { - final List sleepPeriods; - final List hrSamples; - final List restingHrSamples; - - _StubHcService({ - this.sleepPeriods = const [], - this.hrSamples = const [], - this.restingHrSamples = const [], - }); - - @override - Future> readSleepSessions(DateTime start, DateTime end) async => sleepPeriods; - @override - Future> readHeartRateSamples(DateTime start, DateTime end) async => hrSamples; - @override - Future> readRestingHeartRate(DateTime start, DateTime end) async => restingHrSamples; - @override - Future> grantedReadTypes() async => {HealthReadType.heartRate, HealthReadType.sleep}; - @override - Future> readHrvRmssd(DateTime start, DateTime end) async => const []; - @override - Future isAvailable() async => true; - @override - Future requestPermissions() async => true; - @override - Future hasPermissions() async => true; - @override - Future requestReadPermissions() async => true; - @override - Future syncWorkoutSession(WorkoutSession session, {String? title}) async => true; -} +import 'test_utils/stub_health_connect_service.dart'; void main() { final granted = {HealthReadType.heartRate, HealthReadType.sleep}; group('Sleep & HR Builder Utils', () { test('buildHrDaySnapshot returns null when no HR samples or resting HR present', () async { - final stubHc = _StubHcService(); + final stubHc = StubHcService(); final snapshot = await buildHrDaySnapshot(stubHc, DateTime(2026, 7, 23), granted); expect(snapshot, isNull); @@ -63,7 +31,7 @@ void main() { value: 58.0, ); - final stubHc = _StubHcService( + final stubHc = StubHcService( hrSamples: [sample1, sample2], restingHrSamples: [resting], ); @@ -102,7 +70,7 @@ void main() { value: 58.0, ); - final stubHc = _StubHcService( + final stubHc = StubHcService( sleepPeriods: [sleepPeriod], hrSamples: [hrSample1, hrSample2, hrSample3], ); diff --git a/workout-logger/test/sleep_hr_models_test.dart b/workout-logger/test/sleep_hr_models_test.dart index 13a080b..13b8f87 100644 --- a/workout-logger/test/sleep_hr_models_test.dart +++ b/workout-logger/test/sleep_hr_models_test.dart @@ -21,7 +21,7 @@ void main() { }); test('SleepStageStats properties', () { - final stats = SleepStageStats( + const stats = SleepStageStats( stage: 'rem', minBpm: 55, p25Bpm: 60, diff --git a/workout-logger/test/test_utils/stub_health_connect_service.dart b/workout-logger/test/test_utils/stub_health_connect_service.dart new file mode 100644 index 0000000..36c87fb --- /dev/null +++ b/workout-logger/test/test_utils/stub_health_connect_service.dart @@ -0,0 +1,35 @@ +import 'package:repforge/models/models.dart'; +import 'package:repforge/services/interfaces/health_connect_service_interface.dart'; + +class StubHcService implements IHealthConnectService { + final List sleepPeriods; + final List hrSamples; + final List restingHrSamples; + + StubHcService({ + this.sleepPeriods = const [], + this.hrSamples = const [], + this.restingHrSamples = const [], + }); + + @override + Future> readSleepSessions(DateTime start, DateTime end) async => sleepPeriods; + @override + Future> readHeartRateSamples(DateTime start, DateTime end) async => hrSamples; + @override + Future> readRestingHeartRate(DateTime start, DateTime end) async => restingHrSamples; + @override + Future> grantedReadTypes() async => {HealthReadType.heartRate, HealthReadType.sleep}; + @override + Future> readHrvRmssd(DateTime start, DateTime end) async => const []; + @override + Future isAvailable() async => true; + @override + Future requestPermissions() async => true; + @override + Future hasPermissions() async => true; + @override + Future requestReadPermissions() async => true; + @override + Future syncWorkoutSession(WorkoutSession session, {String? title}) async => true; +} diff --git a/workout-logger/test/userflow_history_and_session_details_test.dart b/workout-logger/test/userflow_history_and_session_details_test.dart index 4b194a2..8294459 100644 --- a/workout-logger/test/userflow_history_and_session_details_test.dart +++ b/workout-logger/test/userflow_history_and_session_details_test.dart @@ -3,37 +3,13 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:provider/provider.dart'; import 'package:repforge/models/models.dart'; import 'package:repforge/screens/history_screen.dart'; -import 'package:repforge/screens/widgets/session_details_sheet.dart'; -import 'package:repforge/services/interfaces/health_connect_service_interface.dart'; import 'package:repforge/services/managers/health_history_manager.dart'; import 'package:repforge/services/managers/history_manager.dart'; import 'package:repforge/services/managers/program_manager.dart'; import 'package:repforge/services/settings_provider.dart'; import 'package:repforge/services/workout_provider.dart'; import 'test_utils/mock_storage_service.dart'; - -class _StubHcService implements IHealthConnectService { - @override - Future> readSleepSessions(DateTime start, DateTime end) async => const []; - @override - Future> readHeartRateSamples(DateTime start, DateTime end) async => const []; - @override - Future> readRestingHeartRate(DateTime start, DateTime end) async => const []; - @override - Future> grantedReadTypes() async => {}; - @override - Future> readHrvRmssd(DateTime start, DateTime end) async => const []; - @override - Future isAvailable() async => true; - @override - Future requestPermissions() async => true; - @override - Future hasPermissions() async => true; - @override - Future requestReadPermissions() async => true; - @override - Future syncWorkoutSession(WorkoutSession session, {String? title}) async => true; -} +import 'test_utils/stub_health_connect_service.dart'; Widget _buildTestApp({ required WorkoutProvider workoutProvider, @@ -67,7 +43,7 @@ void main() { setUp(() async { mockStorage = MockStorageService(); historyManager = HistoryManager(mockStorage); - healthHistoryManager = HealthHistoryManager(_StubHcService(), mockStorage); + healthHistoryManager = HealthHistoryManager(StubHcService(), mockStorage); workoutProvider = WorkoutProvider( mockStorage, programManager: ProgramManager(mockStorage), @@ -93,7 +69,11 @@ void main() { expect(find.text('History'), findsOneWidget); }); - testWidgets('HistoryScreen lists sessions and opens SessionDetailsSheet', (tester) async { + testWidgets('HistoryScreen lists sessions and opens SessionDetailsSheet on tap', (tester) async { + tester.view.physicalSize = const Size(800, 1800); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.resetPhysicalSize); + final session = WorkoutSession( id: 'hist_s1', date: DateTime.now(), @@ -110,6 +90,7 @@ void main() { ); await mockStorage.saveWorkoutSession(session); + await historyManager.loadSessions(); await workoutProvider.init(); // Reload sessions from storage await tester.pumpWidget(_buildTestApp( @@ -121,28 +102,10 @@ void main() { )); await tester.pumpAndSettle(); - // SessionDetailsSheet component test - bool edited = false; - bool deleted = false; - - await tester.pumpWidget(_buildTestApp( - workoutProvider: workoutProvider, - settingsProvider: settingsProvider, - historyManager: historyManager, - healthHistoryManager: healthHistoryManager, - child: Scaffold( - body: DraggableScrollableSheet( - initialChildSize: 1.0, - builder: (ctx, scrollController) => SessionDetailsSheet( - session: session, - provider: workoutProvider, - scrollController: scrollController, - onEdit: () => edited = true, - onDelete: () => deleted = true, - ), - ), - ), - )); + // Tap session item in HistoryScreen to open SessionDetailsSheet + final sessionCard = find.text('Quick Workout'); + expect(sessionCard, findsOneWidget); + await tester.tap(sessionCard); await tester.pumpAndSettle(); // Verify SessionDetailsSheet displays details diff --git a/workout-logger/test/userflow_settings_and_storage_test.dart b/workout-logger/test/userflow_settings_and_storage_test.dart index 385f57d..518de53 100644 --- a/workout-logger/test/userflow_settings_and_storage_test.dart +++ b/workout-logger/test/userflow_settings_and_storage_test.dart @@ -59,17 +59,34 @@ void main() { expect(find.text('Settings'), findsOneWidget); expect(find.text('Preferences'), findsOneWidget); + expect(find.text('kg'), findsOneWidget); + expect(find.text('lbs'), findsOneWidget); }); - testWidgets('Toggling weight unit in SettingsProvider persists to storage and updates display label', (tester) async { + testWidgets('Toggling weight unit in SettingsScreen persists to storage and updates display label', (tester) async { + await tester.pumpWidget(_buildTestApp( + workoutProvider: workoutProvider, + settingsProvider: settingsProvider, + apiService: apiService, + child: const SettingsScreen(), + )); + await tester.pumpAndSettle(); + expect(settingsProvider.weightUnit, equals(WeightUnit.kg)); expect(settingsProvider.unitLabel, equals('kg')); - await settingsProvider.setWeightUnit(WeightUnit.lbs); + // Tap 'lbs' unit button in SettingsScreen UI + final lbsButton = find.text('lbs'); + expect(lbsButton, findsOneWidget); + await tester.tap(lbsButton); + await tester.pumpAndSettle(); + + // Assert UI display label, provider state, and persistent storage expect(settingsProvider.weightUnit, equals(WeightUnit.lbs)); expect(settingsProvider.unitLabel, equals('lbs')); expect(mockStorage.settings['weightUnit'], equals('lbs')); + // Set increment and verify persistence await settingsProvider.setWeightIncrement(5.0); expect(settingsProvider.weightIncrement, equals(5.0)); expect(mockStorage.settings['weightIncrement'], equals('5.0')); diff --git a/workout-logger/test/userflow_workout_logging_test.dart b/workout-logger/test/userflow_workout_logging_test.dart index d3c07ca..4c67c59 100644 --- a/workout-logger/test/userflow_workout_logging_test.dart +++ b/workout-logger/test/userflow_workout_logging_test.dart @@ -4,7 +4,7 @@ import 'package:provider/provider.dart'; import 'package:repforge/models/models.dart'; import 'package:repforge/screens/workout_flow_screen.dart'; import 'package:repforge/screens/workout_summary_screen.dart'; -import 'package:repforge/screens/widgets/rest_timer_view.dart'; +import 'package:repforge/services/managers/pr_manager.dart'; import 'package:repforge/services/managers/program_manager.dart'; import 'package:repforge/services/settings_provider.dart'; import 'package:repforge/services/workout_provider.dart'; @@ -13,12 +13,14 @@ import 'test_utils/mock_storage_service.dart'; Widget _buildTestApp({ required WorkoutProvider workoutProvider, required SettingsProvider settingsProvider, + required PRManager prManager, required Widget child, }) { return MultiProvider( providers: [ ChangeNotifierProvider.value(value: workoutProvider), ChangeNotifierProvider.value(value: settingsProvider), + ChangeNotifierProvider.value(value: prManager), ], child: MaterialApp( home: child, @@ -32,9 +34,11 @@ void main() { late MockStorageService mockStorage; late WorkoutProvider workoutProvider; late SettingsProvider settingsProvider; + late PRManager prManager; setUp(() async { mockStorage = MockStorageService(); + prManager = PRManager(mockStorage); workoutProvider = WorkoutProvider( mockStorage, programManager: ProgramManager(mockStorage), @@ -43,11 +47,12 @@ void main() { await workoutProvider.init(); await settingsProvider.init(); + await prManager.load(); }); group('Userflow 1: Workout Logging & Rest Timer & Summary Screen Flow', () { - testWidgets('User completes sets, interacts with RestTimerView, and views WorkoutSummaryScreen', (tester) async { - // 1. Save custom exercise and start workout + testWidgets('User completes sets, interacts with RestTimerView, and views WorkoutSummaryScreen through production flow', (tester) async { + // 1. Save custom exercise and start active workout final exercise = Exercise( id: 'ex_bench', name: 'Barbell Bench Press', @@ -65,6 +70,7 @@ void main() { await tester.pumpWidget(_buildTestApp( workoutProvider: workoutProvider, settingsProvider: settingsProvider, + prManager: prManager, child: const WorkoutFlowScreen(), )); await tester.pumpAndSettle(); @@ -72,40 +78,28 @@ void main() { // Verify WorkoutFlowScreen renders exercise name expect(find.text('Barbell Bench Press'), findsWidgets); - // 2. Test RestTimerView overlay directly to ensure userflow interactive controls work - int adjustDelta = 0; - bool skipped = false; - - await tester.pumpWidget(_buildTestApp( - workoutProvider: workoutProvider, - settingsProvider: settingsProvider, - child: RestTimerView( - remainingSeconds: 60, - totalSeconds: 90, - onAdjust: (delta) => adjustDelta = delta, - onSkip: () => skipped = true, - nextExerciseName: 'Incline Dumbbell Press', - ), - )); + // 2. Drive production flow: Tap 'LOG SET' to trigger RestTimerView overlay in WorkoutFlowScreen + final logSetBtn = find.text('LOG SET'); + expect(logSetBtn, findsOneWidget); + await tester.tap(logSetBtn); await tester.pumpAndSettle(); - // Verify RestTimerView header and controls + // Verify RestTimerView overlay appears via WorkoutFlowScreen production state expect(find.text('REST'), findsWidgets); - expect(find.text('Next up'), findsOneWidget); - expect(find.text('Incline Dumbbell Press'), findsOneWidget); expect(find.text('SKIP REST'), findsOneWidget); - // Tap +30s adjust button - await tester.tap(find.text('+30s')); + // Tap '+30s' button during rest + final addTimeBtn = find.text('+30s'); + expect(addTimeBtn, findsOneWidget); + await tester.tap(addTimeBtn); await tester.pump(); - expect(adjustDelta, equals(30)); - // Tap SKIP REST button - await tester.tap(find.text('SKIP REST')); - await tester.pump(); - expect(skipped, isTrue); + // Tap 'SKIP REST' to return to active workout view + final skipBtn = find.text('SKIP REST'); + await tester.tap(skipBtn); + await tester.pumpAndSettle(); - // 3. Complete workout and render WorkoutSummaryScreen + // 3. Complete workout session and render WorkoutSummaryScreen final summarySession = WorkoutSession( id: 'completed_s1', date: DateTime.now(), @@ -124,14 +118,16 @@ void main() { await tester.pumpWidget(_buildTestApp( workoutProvider: workoutProvider, settingsProvider: settingsProvider, + prManager: prManager, child: WorkoutSummaryScreen(session: summarySession), )); await tester.pumpAndSettle(); // Verify Summary Screen metrics: trophy, stat grid, volume, sets count + expect(find.byType(WorkoutSummaryScreen), findsOneWidget); expect(find.text('Workout Complete!'), findsOneWidget); expect(find.text('Done'), findsOneWidget); - expect(find.text('45m'), findsOneWidget); // Duration format + expect(find.text('45m'), findsOneWidget); }); }); } From 538ef645595d815d3f0304147befe62b7184a994 Mon Sep 17 00:00:00 2001 From: Devasy Patel <110348311+Devasy23@users.noreply.github.com> Date: Thu, 23 Jul 2026 21:04:10 +0530 Subject: [PATCH 13/14] Adds gitignore and updates codecov yaml --- .codecov.yml | 22 ++++++++++++++++++++++ .github/workflows/test.yml | 1 + .gitignore | 6 ++++++ workout-logger/.gitignore | 6 ++++++ 4 files changed, 35 insertions(+) create mode 100644 .codecov.yml diff --git a/.codecov.yml b/.codecov.yml new file mode 100644 index 0000000..b49ab01 --- /dev/null +++ b/.codecov.yml @@ -0,0 +1,22 @@ +# Codecov Configuration for RepForge (Devasy/RepForge) +codecov: + require_ci_to_pass: yes + +coverage: + precision: 2 + round: down + range: "70...100" + + status: + project: + default: + target: auto + threshold: 1% + patch: + default: + target: auto + +ignore: + - "**/*.g.dart" + - "**/*.freezed.dart" + - "workout-logger/test/**/*" diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 15a27b4..36cdedf 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -61,4 +61,5 @@ jobs: with: files: workout-logger/coverage/lcov.info token: ${{ secrets.CODECOV_TOKEN }} + slug: Devasy/RepForge diff --git a/.gitignore b/.gitignore index 82e5c63..19d41dc 100644 --- a/.gitignore +++ b/.gitignore @@ -88,3 +88,9 @@ repforge_backup_*.json # Claude Code project memory & session files .claude/ + +# Hive test databases and temporary directories +*.hive +tmp_hive_*/ +**/tmp_hive_*/ + diff --git a/workout-logger/.gitignore b/workout-logger/.gitignore index 5f10f73..905f107 100644 --- a/workout-logger/.gitignore +++ b/workout-logger/.gitignore @@ -52,4 +52,10 @@ app.*.map.json .env .env.* +# Hive test databases and temporary directories +*.hive +tmp_hive_*/ +**/tmp_hive_*/ + + From f111df6d269c76e0989475838d46dcd8eb123d5c Mon Sep 17 00:00:00 2001 From: Devasy Patel <110348311+Devasy23@users.noreply.github.com> Date: Thu, 23 Jul 2026 21:12:55 +0530 Subject: [PATCH 14/14] updated comments according to review comments --- .../test/sleep_hr_builder_test.dart | 22 +++++++++++++++++-- .../stub_health_connect_service.dart | 10 ++++----- 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/workout-logger/test/sleep_hr_builder_test.dart b/workout-logger/test/sleep_hr_builder_test.dart index 2e8ba27..6d30012 100644 --- a/workout-logger/test/sleep_hr_builder_test.dart +++ b/workout-logger/test/sleep_hr_builder_test.dart @@ -6,11 +6,15 @@ import 'package:repforge/services/utils/sleep_hr_builder.dart'; import 'test_utils/stub_health_connect_service.dart'; void main() { - final granted = {HealthReadType.heartRate, HealthReadType.sleep}; + final granted = { + HealthReadType.heartRate, + HealthReadType.sleep, + HealthReadType.restingHeartRate, + }; group('Sleep & HR Builder Utils', () { test('buildHrDaySnapshot returns null when no HR samples or resting HR present', () async { - final stubHc = StubHcService(); + const stubHc = StubHcService(); final snapshot = await buildHrDaySnapshot(stubHc, DateTime(2026, 7, 23), granted); expect(snapshot, isNull); @@ -41,6 +45,7 @@ void main() { expect(snapshot, isNotNull); expect(snapshot!.minBpm, equals(70)); expect(snapshot.maxBpm, equals(120)); + expect(snapshot.restingBpm, equals(58)); expect(snapshot.buckets, isNotEmpty); }); @@ -80,6 +85,19 @@ void main() { expect(snapshot, isNotNull); expect(snapshot!.segments, isNotEmpty); expect(snapshot.stageStats, isNotEmpty); + + // Verify representative calculated values in snapshot.segments and snapshot.stageStats + final deepStats = snapshot.statsFor('deep'); + expect(deepStats, isNotNull); + expect(deepStats!.stage, equals('deep')); + expect(deepStats.minBpm, equals(55)); + expect(deepStats.maxBpm, equals(58)); + expect(deepStats.sampleCount, equals(3)); + + final firstSegment = snapshot.segments.first; + expect(firstSegment.stage, equals('deep')); + expect(firstSegment.minBpm, equals(55)); + expect(firstSegment.maxBpm, equals(58)); }); }); } diff --git a/workout-logger/test/test_utils/stub_health_connect_service.dart b/workout-logger/test/test_utils/stub_health_connect_service.dart index 36c87fb..c6196f6 100644 --- a/workout-logger/test/test_utils/stub_health_connect_service.dart +++ b/workout-logger/test/test_utils/stub_health_connect_service.dart @@ -6,20 +6,20 @@ class StubHcService implements IHealthConnectService { final List hrSamples; final List restingHrSamples; - StubHcService({ + const StubHcService({ this.sleepPeriods = const [], this.hrSamples = const [], this.restingHrSamples = const [], }); @override - Future> readSleepSessions(DateTime start, DateTime end) async => sleepPeriods; + Future> readSleepSessions(DateTime start, DateTime end) async => List.from(sleepPeriods); @override - Future> readHeartRateSamples(DateTime start, DateTime end) async => hrSamples; + Future> readHeartRateSamples(DateTime start, DateTime end) async => List.from(hrSamples); @override - Future> readRestingHeartRate(DateTime start, DateTime end) async => restingHrSamples; + Future> readRestingHeartRate(DateTime start, DateTime end) async => List.from(restingHrSamples); @override - Future> grantedReadTypes() async => {HealthReadType.heartRate, HealthReadType.sleep}; + Future> grantedReadTypes() async => {HealthReadType.heartRate, HealthReadType.sleep, HealthReadType.restingHeartRate}; @override Future> readHrvRmssd(DateTime start, DateTime end) async => const []; @override