diff --git a/lib/data/backup_extras.dart b/lib/data/backup_extras.dart index bff49bae2..fc3b0ccb6 100644 --- a/lib/data/backup_extras.dart +++ b/lib/data/backup_extras.dart @@ -197,6 +197,7 @@ const Map kPrefTypes = { 'workout.ghost_buzz': 'bool', 'workout.interval_buzz': 'bool', 'workout.interval_last': 'string', + 'workout.routines': 'string', 'workout.show_map': 'bool', }; diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 45b397116..08ca29331 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -2087,6 +2087,9 @@ "activitySetupSessionRunningBody": "Es kann immer nur eine Trainingseinheit gleichzeitig aufgezeichnet werden.", "activitySetupOpenRunningSession": "Laufendes Training öffnen", "activitySetupStart": "Start", + "activityRoutineSave": "Als Routine speichern", + "activityRoutineSaved": "Als Routine gespeichert", + "activityRoutineStart": "Diese Routine starten", "activityPickerTitle": "Aktivität wählen", "activityPickerSearchLabel": "Aktivitäten durchsuchen", "activityPickerSearchHint": "{count} Aktivitäten durchsuchen", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 79e2f5305..8eb96edd7 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -10102,6 +10102,18 @@ "@activitySetupStart": { "description": "Button label to start a new activity session" }, + "activityRoutineSave": "Save as routine", + "@activityRoutineSave": { + "description": "Button to save a finished strength workout as a reusable routine" + }, + "activityRoutineSaved": "Saved as a routine", + "@activityRoutineSaved": { + "description": "Shown after a workout was saved as a routine" + }, + "activityRoutineStart": "Start this routine", + "@activityRoutineStart": { + "description": "Row on the strength setup screen that starts a saved routine" + }, "activityPickerTitle": "Choose activity", "@activityPickerTitle": { "description": "Nav bar title on the activity picker screen" diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 46fbd8b55..5f35b8e9f 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -2024,6 +2024,9 @@ "activitySetupSessionRunningBody": "Solo puede haber una sesión activa a la vez.", "activitySetupOpenRunningSession": "Abrir la sesión en curso", "activitySetupStart": "Empezar", + "activityRoutineSave": "Guardar como rutina", + "activityRoutineSaved": "Guardada como rutina", + "activityRoutineStart": "Empezar esta rutina", "activityPickerTitle": "Elegir actividad", "activityPickerSearchLabel": "Buscar actividades", "activityPickerSearchHint": "Buscar entre {count} actividades", diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 7a5e7bc45..6890c56bf 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -2010,6 +2010,9 @@ "activitySetupSessionRunningBody": "Une seule séance peut être active à la fois.", "activitySetupOpenRunningSession": "Ouvrir la séance en cours", "activitySetupStart": "Démarrer", + "activityRoutineSave": "Enregistrer comme routine", + "activityRoutineSaved": "Enregistrée comme routine", + "activityRoutineStart": "Démarrer cette routine", "activityPickerTitle": "Choisir une activité", "activityPickerSearchLabel": "Rechercher des activités", "activityPickerSearchHint": "Rechercher parmi {count} activités", diff --git a/lib/l10n/app_hi.arb b/lib/l10n/app_hi.arb index 798ec22df..0a54d2011 100644 --- a/lib/l10n/app_hi.arb +++ b/lib/l10n/app_hi.arb @@ -2010,6 +2010,9 @@ "activitySetupSessionRunningBody": "एक समय में केवल एक सेशन चल सकता है।", "activitySetupOpenRunningSession": "चल रहा सेशन खोलें", "activitySetupStart": "शुरू करें", + "activityRoutineSave": "रूटीन के रूप में सहेजें", + "activityRoutineSaved": "रूटीन के रूप में सहेजा गया", + "activityRoutineStart": "यह रूटीन शुरू करें", "activityPickerTitle": "गतिविधि चुनें", "activityPickerSearchLabel": "गतिविधियाँ खोजें", "activityPickerSearchHint": "{count} गतिविधियों में खोजें", diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 0ed257491..f617e78c1 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -4666,6 +4666,9 @@ "activitySetupSessionRunningBody": "Одновременно может идти только одна.", "activitySetupOpenRunningSession": "Открыть текущую тренировку", "activitySetupStart": "Начать", + "activityRoutineSave": "Сохранить как программу", + "activityRoutineSaved": "Сохранено как программа", + "activityRoutineStart": "Начать эту программу", "activityPickerTitle": "Выбрать активность", "activityPickerSearchLabel": "Поиск активностей", "activityPickerSearchHint": "Поиск среди {count} активностей", diff --git a/lib/l10n/app_th.arb b/lib/l10n/app_th.arb index 20e86ffc0..57d524267 100644 --- a/lib/l10n/app_th.arb +++ b/lib/l10n/app_th.arb @@ -9765,6 +9765,9 @@ "description": "Status card action button to jump to the already-running session" }, "activitySetupStart": "เริ่ม", + "activityRoutineSave": "บันทึกเป็นรูทีน", + "activityRoutineSaved": "บันทึกเป็นรูทีนแล้ว", + "activityRoutineStart": "เริ่มรูทีนนี้", "@activitySetupStart": { "description": "Button label to start a new activity session" }, diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index acf920567..af6b6109f 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -2010,6 +2010,9 @@ "activitySetupSessionRunningBody": "同一时间只能进行一项训练。", "activitySetupOpenRunningSession": "打开正在进行的训练", "activitySetupStart": "开始", + "activityRoutineSave": "保存为训练计划", + "activityRoutineSaved": "已保存为训练计划", + "activityRoutineStart": "开始此训练计划", "activityPickerTitle": "选择活动", "activityPickerSearchLabel": "搜索活动", "activityPickerSearchHint": "在 {count} 项活动中搜索", diff --git a/lib/state/prefs.dart b/lib/state/prefs.dart index e36f61921..981bd7404 100644 --- a/lib/state/prefs.dart +++ b/lib/state/prefs.dart @@ -148,6 +148,9 @@ class Prefs { /// next session opens where the last one left off. static const String intervalLast = 'workout.interval_last'; + /// Saved strength routines, a JSON list of exercise-key lists. + static const String routines = 'workout.routines'; + /// How a non-WHOOP wearable's numbers are drawn: one number per metric /// (default) or ours beside the device's own. A UX choice, not a fact. static const String wearableSideBySide = 'ui.wearable_side_by_side'; diff --git a/lib/ui2/activity/routines.dart b/lib/ui2/activity/routines.dart new file mode 100644 index 000000000..2df5ec346 --- /dev/null +++ b/lib/ui2/activity/routines.dart @@ -0,0 +1,36 @@ +import 'dart:convert'; + +/// Saved strength routines: just the exercise keys in order. Weights and reps +/// are not stored, the live screen already opens each exercise at what was +/// lifted last time. Kept in Prefs as a JSON list, newest first. +const kMaxRoutines = 10; + +List> decodeRoutines(String raw) { + try { + final v = jsonDecode(raw); + if (v is! List) return const []; + return [ + for (final r in v) + if (r is List && r.isNotEmpty && r.every((k) => k is String && k.isNotEmpty)) + List.from(r), + ]; + } catch (_) { + return const []; + } +} + +String encodeRoutines(List> routines) => jsonEncode(routines); + +bool hasRoutine(List> routines, List keys) => + routines.any((r) => r.join('\u0000') == keys.join('\u0000')); + +/// [keys] at the front, any identical routine dropped, capped at +/// [kMaxRoutines]. An empty list is not a routine. +List> withRoutine(List> routines, List keys) { + if (keys.isEmpty) return routines; + return [ + keys, + for (final r in routines) + if (r.join('\u0000') != keys.join('\u0000')) r, + ].take(kMaxRoutines).toList(); +} diff --git a/lib/ui2/activity/setup.dart b/lib/ui2/activity/setup.dart index 80a4f0e2a..729cb4f5b 100644 --- a/lib/ui2/activity/setup.dart +++ b/lib/ui2/activity/setup.dart @@ -24,6 +24,7 @@ import '../theme.dart'; import 'catalogue.dart'; import 'ghost.dart'; import 'live.dart'; +import 'routines.dart'; import 'summary.dart' show Arch, archOf; /// The window the calorie estimate is quoted over — the same one @@ -116,10 +117,14 @@ class _ActivitySetupState extends State { bool _starting = false; bool _refused = false; + late final _routines = archOf(widget.a) == Arch.strength + ? decodeRoutines(Prefs.getString(Prefs.routines, '')) + : const >[]; + /// Open the session in the app FIRST, then the screen. The screen used to /// be pushed on its own, so a "live" workout ran its own clock while the /// app recorded nothing and `sessions` gained no row. - Future _start() async { + Future _start([List? routine]) async { if (_starting) return; setState(() => _starting = true); final start = widget.host.onStart; @@ -145,6 +150,7 @@ class _ActivitySetupState extends State { restSec: interval ? _restSec : null, rounds: interval ? _rounds : null); if (_ghost != null) LiveDraft.current?.put('ghost_id', _ghost!.id); + if (routine != null) LiveDraft.current?.put('exercise_plan', routine); } await Navigator.of(context).pushReplacement(MaterialPageRoute( // Passed straight through too, not just via the draft above: a caller @@ -296,6 +302,33 @@ class _ActivitySetupState extends State { l), ]), ), + if (_routines.isNotEmpty) ...[ + const SizedBox(height: S.x4), + Surface( + pad: const EdgeInsets.symmetric(horizontal: S.x4), + child: Column(children: [ + for (var i = 0; i < _routines.length; i++) ...[ + Pressable( + onTap: _starting ? null : () => _start(_routines[i]), + child: _row( + p, + LucideIcons.dumbbell, + [ + for (final k in _routines[i]) + exerciseByKey(k)?.labelFor( + Localizations.localeOf(c) + .languageCode) ?? + k + ].join(', '), + l?.activityRoutineStart ?? 'Start this routine', + null), + ), + if (i < _routines.length - 1) + Divider(color: p.line, height: 1), + ], + ]), + ), + ], if (a.track == Track.interval) ...[ const SizedBox(height: S.x4), Surface( diff --git a/lib/ui2/activity/summary.dart b/lib/ui2/activity/summary.dart index b60f2494e..948640993 100644 --- a/lib/ui2/activity/summary.dart +++ b/lib/ui2/activity/summary.dart @@ -29,6 +29,7 @@ import 'package:lucide_icons_flutter/lucide_icons.dart'; import 'package:provider/provider.dart'; import '../../data/db.dart'; +import 'routines.dart'; import 'dart:convert' show utf8; import 'dart:typed_data' show Uint8List; @@ -2461,6 +2462,40 @@ class _ActivitySummaryState extends State { ]), ), ), + if (!r.strength.isEmpty) + Padding( + padding: const EdgeInsets.only(top: S.x4), + child: Builder(builder: (_) { + final keys = r.strength.exercises; + final saved = hasRoutine( + decodeRoutines(Prefs.getString(Prefs.routines, '')), keys); + return Surface( + child: Pressable( + onTap: saved + ? null + : () => setState(() => Prefs.setString( + Prefs.routines, + encodeRoutines(withRoutine( + decodeRoutines( + Prefs.getString(Prefs.routines, '')), + keys)))), + child: Row(children: [ + Icon(saved ? LucideIcons.check : LucideIcons.bookmarkPlus, + size: 17, color: p.ink2), + const SizedBox(width: S.x3), + Expanded( + child: Text( + saved + ? (l?.activityRoutineSaved ?? + 'Saved as a routine') + : (l?.activityRoutineSave ?? + 'Save as routine'), + style: F.body.copyWith(color: p.ink))), + ]), + ), + ); + }), + ), if (r.strength.hasUnloadedSets) Padding( padding: const EdgeInsets.only(top: S.x4), diff --git a/test/backup/settings_audit_guard_test.dart b/test/backup/settings_audit_guard_test.dart index e86115960..35bb5ba6b 100644 --- a/test/backup/settings_audit_guard_test.dart +++ b/test/backup/settings_audit_guard_test.dart @@ -26,7 +26,7 @@ const _mustTravel = { 'ai_morning_enabled', 'ai_morning_min', 'ai_evening_enabled', 'ai_evening_min', 'ai_journal_enabled', 'ai_journal_min', 'workout.zone_alert_enabled', 'workout.zone_alert_target_zone', 'workout.ghost_buzz', 'workout.rpe_skips', - 'workout.interval_buzz', 'workout.interval_last', 'workout.show_map', + 'workout.interval_buzz', 'workout.interval_last', 'workout.routines', 'workout.show_map', 'notif_health', 'notif_recovery', 'notif_reminders', 'notif_device', 'notif_quiet_enabled', 'notif_quiet_start', 'notif_quiet_end', 'notif_critical_override', 'notif_water', 'notif_water_interval', diff --git a/test/strength_routines_test.dart b/test/strength_routines_test.dart new file mode 100644 index 000000000..c8cd3ad69 --- /dev/null +++ b/test/strength_routines_test.dart @@ -0,0 +1,27 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:openstrap_edge/ui2/activity/routines.dart'; + +void main() { + test('round trip, newest first, dedupe, cap', () { + var r = >[]; + r = withRoutine(r, ['bench', 'row']); + r = withRoutine(r, ['squat']); + r = withRoutine(r, ['bench', 'row']); + expect(r, [['bench', 'row'], ['squat']]); + expect(hasRoutine(r, ['squat']), isTrue); + expect(hasRoutine(r, ['row', 'bench']), isFalse); + expect(decodeRoutines(encodeRoutines(r)), r); + for (var i = 0; i < 15; i++) { + r = withRoutine(r, ['k$i']); + } + expect(r.length, kMaxRoutines); + expect(r.first, ['k14']); + }); + + test('empty and junk', () { + expect(withRoutine([], []), isEmpty); + for (final s in ['', 'x', '{}', '[[]]', '[[1]]', '[["a"],[""]]']) { + expect(decodeRoutines(s).length, s == '[["a"],[""]]' ? 1 : 0, reason: s); + } + }); +}