Skip to content

Offline gym log for Android. No account, no ads, no internet.

Share routines, import them back and read Lyfta exports

InlitXef74685c08ab
diff --git a/lib/catalog/exercise_aliases.dart b/lib/catalog/exercise_aliases.dart
index 98933aa..12fd240 100644
--- a/lib/catalog/exercise_aliases.dart
+++ b/lib/catalog/exercise_aliases.dart
@@ -65,6 +65,7 @@ const Map<String, List<String>> kExerciseAliases = {
'Chin-up': ['Chin Up'],
'Close-Grip Lat Pulldown': ['Lat Pulldown - Close Grip (Cable)'],
'Crunch Floor': ['Crunch', 'Crunch (Bodyweight)'],
+ 'Dead Hang': ['Bar Hang', 'Hang'],
'Dumbbell Alternate Preacher Curl': ['Preacher Curl (Dumbbell)'],
'Dumbbell Arnold Press': ['Arnold Press (Dumbbell)'],
'Dumbbell Bench Press': ['Bench Press (Dumbbell)'],
@@ -94,6 +95,7 @@ const Map<String, List<String>> kExerciseAliases = {
],
'Elliptical Trainer': ['Elliptical Machine', 'Elliptical'],
'Face Pull': ['Face Pull (Cable)'],
+ 'Hiking': ['Hike'],
'Hip Abduction Machine': ['Hip Abduction (Machine)'],
'Hip Adduction Machine': ['Hip Adduction (Machine)'],
'Hip Thrust': ['Hip Thrust (Bodyweight)'],
@@ -118,7 +120,10 @@ const Map<String, List<String>> kExerciseAliases = {
'Machine Lateral Raise': ['Lateral Raise (Machine)'],
'Meadows Row': ['Meadows Row (Barbell)'],
'One-Arm Dumbbell Row': ['Single Arm Dumbbell Row', 'Dumbbell Row'],
+ 'Outdoor Cycling': ['Cycling', 'Biking', 'Bike Ride', 'Road Cycling'],
+ 'Outdoor Run': ['Running', 'Run', 'Jogging', 'Jog'],
'Pec Deck': ['Chest Fly (Machine)', 'Pec Deck (Machine)', 'Butterfly (Machine)'],
+ 'Plank': ['Front Plank', 'Forearm Plank'],
'Power Clean': ['Power Clean (Barbell)'],
'Pull-up': ['Pull Up'],
'Push-up': ['Push Up (Bodyweight)', 'Press Up'],
@@ -128,6 +133,7 @@ const Map<String, List<String>> kExerciseAliases = {
'Rowing Machine': ['Rowing (Machine)', 'Rowing'],
'Russian Twist': ['Russian Twist (Bodyweight)'],
'Seated Leg Curl': ['Leg Curl (Machine)', 'Seated Leg Curl (Machine)'],
+ 'Side Plank': ['Side Bridge'],
'Single Dumbbell Skullcrusher': ['Skullcrusher (Dumbbell)', 'Skull Crusher'],
'Single-Arm Cable Row': ['Seated Row Single Arm (Cable)'],
'Ski Erg': ['Ski Machine'],
@@ -137,13 +143,15 @@ const Map<String, List<String>> kExerciseAliases = {
'Smith Machine Bulgarian Split Squat': ['Bulgarian Split Squat (Smith Machine)'],
'Smith Seated Shoulder Press': ['Shoulder Press (Smith Machine)'],
'Stair Climber': ['Stair Machine', 'Stairmaster'],
- 'Stationary Bike': ['Cycling (Indoor)', 'Cycling'],
+ 'Stationary Bike': ['Cycling (Indoor)', 'Indoor Cycling'],
+ 'Swimming': ['Swim', 'Pool Swim'],
'Trap Bar Deadlift': ['Deadlift (Trap Bar)', 'Hex Bar Deadlift'],
- 'Treadmill Run': ['Running (Treadmill)', 'Running'],
- 'Treadmill Walk': ['Walking (Treadmill)', 'Walking'],
+ 'Treadmill Run': ['Running (Treadmill)', 'Treadmill'],
+ 'Treadmill Walk': ['Walking (Treadmill)'],
'Triceps Dip': ['Triceps Dip (Bodyweight)', 'Tricep Dip'],
'Upright Row': ['Upright Row (Barbell)', 'Upright Row (Cable)'],
- 'Weighted Front Plank': ['Plank', 'Front Plank'],
+ 'Walk': ['Walking', 'Outdoor Walk'],
+ 'Weighted Front Plank': ['Weighted Plank', 'Plank (Weighted)'],
'Weighted Hanging Leg-hip Raise': ['Hanging Leg Raise'],
'Weighted Pull-up': ['Pull Up (Weighted)'],
'Weighted Russian Twist': ['Russian Twist (Weighted)'],
diff --git a/lib/screens/ai_plan_screen.dart b/lib/screens/ai_plan_screen.dart
index 67becd2..c721e3f 100644
--- a/lib/screens/ai_plan_screen.dart
+++ b/lib/screens/ai_plan_screen.dart
@@ -1,18 +1,19 @@
-import 'dart:convert';
import 'dart:io';
-import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:phosphoricons_flutter/phosphoricons_flutter.dart';
import 'package:share_plus/share_plus.dart';
import '../l10n/l10n.dart';
+import '../services/plan_share.dart';
import '../state/fit_state.dart';
import '../theme/app_colors.dart';
import '../theme/app_theme.dart';
-import '../widgets/svg_icon.dart';
+import '../widgets/liquid_notch.dart';
import '../widgets/ui_kit.dart';
+import 'plan_import_sheet.dart';
class AiPlanScreen extends StatefulWidget {
const AiPlanScreen({super.key});
@@ -22,9 +23,18 @@ class AiPlanScreen extends StatefulWidget {
}
class _AiPlanScreenState extends State<AiPlanScreen> {
+ final TextEditingController _answer = TextEditingController();
List<String> _missed = const [];
int _added = 0;
+ int _routines = 0;
bool _unreadable = false;
+ bool _format = false;
+
+ @override
+ void dispose() {
+ _answer.dispose();
+ super.dispose();
+ }
@override
Widget build(BuildContext context) {
@@ -32,6 +42,7 @@ class _AiPlanScreenState extends State<AiPlanScreen> {
return SafeArea(
bottom: false,
child: SingleChildScrollView(
+ clipBehavior: Clip.none,
padding: const EdgeInsets.fromLTRB(20, 12, 20, 40),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
@@ -48,12 +59,12 @@ class _AiPlanScreenState extends State<AiPlanScreen> {
const SizedBox(width: 10),
Expanded(
child: Text(t.fullyOffline.toUpperCase(),
- style: AppTheme.f(12,
- weight: FontWeight.w700, color: gc.sage, letterSpacing: 1.4)),
+ style: AppTheme.f(12, weight: FontWeight.w700, color: gc.sage, letterSpacing: 1.4)),
),
]),
const SizedBox(height: 10),
- Text(t.aiIntro, style: AppTheme.f(13, weight: FontWeight.w500, color: gc.textSecondary, height: 1.5)),
+ Text(t.aiIntro,
+ style: AppTheme.f(13, weight: FontWeight.w500, color: gc.textSecondary, height: 1.5)),
const SizedBox(height: 18),
for (var i = 0; i < _steps.length; i++) ...[
if (i > 0) const SizedBox(height: 12),
@@ -63,11 +74,57 @@ class _AiPlanScreenState extends State<AiPlanScreen> {
),
),
const SizedBox(height: 20),
- PrimaryButton(label: t.exportCatalog, icon: Ic.layers, onTap: _export),
+ PrimaryButton(label: t.copyForAi, onTap: _copy),
const SizedBox(height: 10),
- GhostButton(
- label: t.importRoutine,
- icon: PhosphorIconsRegular.clipboardText,
+ GhostButton(label: t.shareAsFile, icon: PhosphorIconsRegular.shareNetwork, onTap: _export),
+ const SizedBox(height: 24),
+ TextField(
+ controller: _answer,
+ minLines: 8,
+ maxLines: 16,
+ keyboardType: TextInputType.multiline,
+ onChanged: (_) => setState(() {}),
+ style: AppTheme.f(12.5, weight: FontWeight.w500, color: gc.text, height: 1.35),
+ cursorColor: gc.accent,
+ decoration: InputDecoration(
+ hintText: t.aiPasteHint,
+ hintStyle: AppTheme.f(14, weight: FontWeight.w500, color: gc.textTertiary),
+ filled: true,
+ fillColor: gc.bgRaised,
+ contentPadding: const EdgeInsets.all(16),
+ border: OutlineInputBorder(borderRadius: BorderRadius.circular(20), borderSide: BorderSide.none),
+ ),
+ ),
+ const SizedBox(height: 10),
+ Row(children: [
+ _chip(gc, PhosphorIconsRegular.clipboardText, t.pasteAction, _paste),
+ const SizedBox(width: 8),
+ _chip(gc, PhosphorIconsRegular.fileArrowUp, t.chooseFile, _file),
+ const Spacer(),
+ GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: () => setState(() => _format = !_format),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 8),
+ child: Text(t.showFormat,
+ style: AppTheme.f(12.5, weight: FontWeight.w600, color: gc.accent)),
+ ),
+ ),
+ ]),
+ if (_format) ...[
+ const SizedBox(height: 8),
+ Container(
+ padding: const EdgeInsets.all(14),
+ decoration: BoxDecoration(color: gc.bgRaised, borderRadius: BorderRadius.circular(16)),
+ child: SelectableText(FitState.planTemplate,
+ style: TextStyle(fontFamily: 'monospace', fontSize: 11.5, color: gc.textSecondary, height: 1.4)),
+ ),
+ ],
+ const SizedBox(height: 14),
+ PrimaryButton(
+ label: t.importAction,
+ bg: _answer.text.trim().isEmpty ? gc.bgRaised2 : gc.ember,
+ fg: _answer.text.trim().isEmpty ? gc.textTertiary : gc.onEmber,
onTap: _import,
),
if (_unreadable || _added > 0 || _missed.isNotEmpty) ...[
@@ -80,7 +137,21 @@ class _AiPlanScreenState extends State<AiPlanScreen> {
);
}
- List<String> get _steps => [t.aiStep1, t.aiStep2, t.aiStep3, t.aiStep4];
+ List<String> get _steps => [t.aiStepCopy, t.aiStepAsk, t.aiStepPaste];
+
+ Widget _chip(GymColors gc, IconData icon, String label, VoidCallback onTap) => GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: onTap,
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 9),
+ decoration: BoxDecoration(color: gc.bgRaised, borderRadius: BorderRadius.circular(100)),
+ child: Row(mainAxisSize: MainAxisSize.min, children: [
+ Icon(icon, size: 15, color: gc.text),
+ const SizedBox(width: 7),
+ Text(label, style: AppTheme.f(12.5, weight: FontWeight.w600, color: gc.text)),
+ ]),
+ ),
+ );
Widget _step(GymColors gc, int n, String text) {
return Row(
@@ -94,7 +165,8 @@ class _AiPlanScreenState extends State<AiPlanScreen> {
child: Text('$n', style: AppTheme.f(12, weight: FontWeight.w700, color: gc.ember)),
),
const SizedBox(width: 12),
- Expanded(child: Text(text, style: AppTheme.f(13, weight: FontWeight.w500, color: gc.text, height: 1.45))),
+ Expanded(
+ child: Text(text, style: AppTheme.f(13, weight: FontWeight.w500, color: gc.text, height: 1.45))),
],
);
}
@@ -115,7 +187,7 @@ class _AiPlanScreenState extends State<AiPlanScreen> {
_unreadable
? t.planFailed
: good
- ? t.planImported(_added)
+ ? '${t.routinesAdded(_routines)} · ${t.exerciseCount(_added)}'
: t.planNothing,
style: AppTheme.f(13.5, weight: FontWeight.w600, color: good ? gc.sage : gc.text),
),
@@ -124,13 +196,29 @@ class _AiPlanScreenState extends State<AiPlanScreen> {
Text(t.aiMissing(_missed.length),
style: AppTheme.f(12, weight: FontWeight.w600, color: gc.textSecondary)),
const SizedBox(height: 4),
- Text(_missed.join(' · '), style: AppTheme.f(12, weight: FontWeight.w500, color: gc.textTertiary, height: 1.4)),
+ Text(_missed.join(' · '),
+ style: AppTheme.f(12, weight: FontWeight.w500, color: gc.textTertiary, height: 1.4)),
+ ],
+ if (good) ...[
+ const SizedBox(height: 10),
+ GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: fit.backFromAiPlan,
+ child: Text(t.routines, style: AppTheme.f(13, weight: FontWeight.w700, color: gc.accent)),
+ ),
],
],
),
);
}
+ Future<void> _copy() async {
+ await Clipboard.setData(ClipboardData(text: fit.planRequestText()));
+ if (!mounted) return;
+ showNotchToast(context, t.copiedDone,
+ subtitle: t.aiStepAsk, icon: PhosphorIconsFill.copy, accent: context.gc.sage);
+ }
+
Future<void> _export() async {
try {
final dir = await getTemporaryDirectory();
@@ -143,31 +231,38 @@ class _AiPlanScreenState extends State<AiPlanScreen> {
} catch (_) {}
}
- Future<void> _import() async {
- String? raw;
- try {
- final result = await FilePicker.platform.pickFiles(withData: true);
- if (result == null) return;
- final picked = result.files.single;
- final bytes =
- picked.bytes ?? (picked.path == null ? null : await File(picked.path!).readAsBytes());
- if (bytes != null) raw = utf8.decode(bytes, allowMalformed: true);
- } catch (_) {
- raw = null;
- }
- if (!mounted) return;
- if (raw == null) {
+ Future<void> _paste() async {
+ final data = await Clipboard.getData(Clipboard.kTextPlain);
+ final text = data?.text;
+ if (text == null || text.trim().isEmpty || !mounted) return;
+ setState(() => _answer.text = text);
+ }
+
+ Future<void> _file() async {
+ final text = await pickTextFile();
+ if (text == null || !mounted) return;
+ setState(() => _answer.text = text);
+ }
+
+ void _import() {
+ final raw = _answer.text;
+ if (raw.trim().isEmpty) return;
+ FocusScope.of(context).unfocus();
+ final plans = parsePlan(raw);
+ if (plans.isEmpty) {
setState(() {
_unreadable = true;
_added = 0;
+ _routines = 0;
_missed = const [];
});
return;
}
- final outcome = fit.importPlan(raw);
+ final outcome = fit.applyPlan(plans, schedule: fit.weeklyPlan.isEmpty);
setState(() {
- _unreadable = !outcome.readable;
+ _unreadable = false;
_added = outcome.added;
+ _routines = outcome.routines;
_missed = outcome.missed;
});
}
diff --git a/lib/screens/plan_import_sheet.dart b/lib/screens/plan_import_sheet.dart
new file mode 100644
index 0000000..2a7d320
--- /dev/null
+++ b/lib/screens/plan_import_sheet.dart
@@ -0,0 +1,299 @@
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:file_picker/file_picker.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:path_provider/path_provider.dart';
+import 'package:phosphoricons_flutter/phosphoricons_flutter.dart';
+import 'package:share_plus/share_plus.dart';
+
+import '../l10n/l10n.dart';
+import '../models/workout.dart';
+import '../services/plan_share.dart';
+import '../state/fit_state.dart';
+import '../theme/app_colors.dart';
+import '../theme/app_theme.dart';
+import '../widgets/glass.dart';
+import '../widgets/liquid_notch.dart';
+import '../widgets/ui_kit.dart';
+
+const _sample = '{ "name": "Push", "exercises": [ ... ] }';
+
+Future<void> sharePlan(List<Routine> routines, {String? title}) async {
+ if (routines.isEmpty) return;
+ final name = title ?? fit.routineTitle(routines.first);
+ try {
+ final dir = await getTemporaryDirectory();
+ final slug = name
+ .toLowerCase()
+ .replaceAll(RegExp(r'[^a-z0-9]+'), '-')
+ .replaceAll(RegExp(r'^-+|-+$'), '');
+ final file = File('${dir.path}/gymmane-${slug.isEmpty ? 'plan' : slug}.json');
+ await file.writeAsString(fit.exportPlanJson(routines));
+ await SharePlus.instance.share(ShareParams(
+ files: [XFile(file.path, mimeType: 'application/json')],
+ text: '${fit.planSummaryText(routines)}\n\n${t.shareMessage(name)}',
+ subject: name,
+ ));
+ } catch (_) {}
+}
+
+Future<String?> pickTextFile() async {
+ try {
+ final result = await FilePicker.platform.pickFiles(withData: true);
+ if (result == null) return null;
+ final picked = result.files.single;
+ final bytes = picked.bytes ?? (picked.path == null ? null : await File(picked.path!).readAsBytes());
+ return bytes == null ? null : utf8.decode(bytes, allowMalformed: true);
+ } catch (_) {
+ return null;
+ }
+}
+
+Future<void> showPlanImportSheet(BuildContext context, {String? text}) =>
+ showAppSheet<void>(
+ context: context,
+ isScrollControlled: true,
+ backgroundColor: Colors.transparent,
+ builder: (_) => _PlanImportSheet(initial: text),
+ );
+
+class _PlanImportSheet extends StatefulWidget {
+ const _PlanImportSheet({this.initial});
+
+ final String? initial;
+
+ @override
+ State<_PlanImportSheet> createState() => _PlanImportSheetState();
+}
+
+class _PlanImportSheetState extends State<_PlanImportSheet> {
+ late final TextEditingController _text = TextEditingController(text: widget.initial ?? '');
+ late bool _field = widget.initial == null;
+ List<PlanRoutine> _plans = const [];
+ bool _schedule = false;
+
+ @override
+ void initState() {
+ super.initState();
+ if (widget.initial != null) _parse();
+ }
+
+ @override
+ void dispose() {
+ _text.dispose();
+ super.dispose();
+ }
+
+ void _parse() {
+ final plans = _text.text.trim().isEmpty ? const <PlanRoutine>[] : parsePlan(_text.text);
+ setState(() {
+ _plans = plans;
+ _schedule = plans.any((p) => p.days.isNotEmpty) && fit.weeklyPlan.isEmpty;
+ });
+ }
+
+ Future<void> _paste() async {
+ final data = await Clipboard.getData(Clipboard.kTextPlain);
+ final text = data?.text;
+ if (text == null || text.trim().isEmpty) return;
+ _text.text = text;
+ _parse();
+ }
+
+ Future<void> _file() async {
+ final text = await pickTextFile();
+ if (text == null || !mounted) return;
+ _text.text = text;
+ setState(() => _field = false);
+ _parse();
+ }
+
+ void _apply() {
+ final result = fit.applyPlan(_plans, schedule: _schedule);
+ final gc = context.gc;
+ showNotchToast(
+ context,
+ result.routines > 0 ? t.routinesAdded(result.routines) : t.nothingToImport,
+ subtitle: result.routines > 0 ? t.exerciseCount(result.added) : null,
+ icon: result.routines > 0 ? PhosphorIconsFill.checkCircle : PhosphorIconsFill.warningCircle,
+ accent: result.routines > 0 ? gc.sage : gc.warn,
+ );
+ Navigator.of(context).pop();
+ }
+
+ String _days(List<int> days) => days.map(t.weekdayShort).join(', ');
+
+ @override
+ Widget build(BuildContext context) {
+ final gc = context.gc;
+ final preview = _plans.isEmpty ? null : fit.previewPlan(_plans);
+ final hasDays = _plans.any((p) => p.days.isNotEmpty);
+ return Container(
+ padding: sheetPad(context).add(EdgeInsets.only(bottom: MediaQuery.viewInsetsOf(context).bottom)),
+ constraints: BoxConstraints(maxHeight: MediaQuery.sizeOf(context).height * 0.9),
+ decoration: BoxDecoration(
+ color: gc.bgRaised,
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),
+ ),
+ child: SingleChildScrollView(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ const SheetHandle(),
+ const SizedBox(height: 18),
+ Text(titleCase(t.importRoutines), style: AppTheme.f(19, weight: FontWeight.w800, color: gc.text)),
+ const SizedBox(height: 6),
+ Text(t.importPasteHint,
+ style: AppTheme.f(12.5, weight: FontWeight.w500, color: gc.textSecondary, height: 1.4)),
+ const SizedBox(height: 14),
+ if (_field) ...[
+ TextField(
+ controller: _text,
+ minLines: 4,
+ maxLines: 8,
+ onChanged: (_) => _parse(),
+ style: AppTheme.f(12.5, weight: FontWeight.w500, color: gc.text, height: 1.35),
+ cursorColor: gc.accent,
+ decoration: InputDecoration(
+ hintText: _sample,
+ hintStyle: AppTheme.f(12.5, weight: FontWeight.w500, color: gc.textTertiary),
+ filled: true,
+ fillColor: gc.bgRaised2,
+ contentPadding: const EdgeInsets.all(14),
+ border: OutlineInputBorder(borderRadius: BorderRadius.circular(16), borderSide: BorderSide.none),
+ ),
+ ),
+ const SizedBox(height: 10),
+ Row(children: [
+ _action(gc, PhosphorIconsRegular.clipboardText, t.pasteAction, _paste),
+ const SizedBox(width: 8),
+ _action(gc, PhosphorIconsRegular.fileArrowUp, t.chooseFile, _file),
+ ]),
+ ],
+ if (preview != null && preview.routines > 0) ...[
+ const SizedBox(height: 18),
+ Text('${t.routineCount(preview.routines)} · ${t.exerciseCount(preview.added)}'.toUpperCase(),
+ style: AppTheme.f(10.5, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 1.3)),
+ const SizedBox(height: 10),
+ for (final p in _plans)
+ if (p.items.isNotEmpty) _planCard(gc, p),
+ if (preview.missed.isNotEmpty) ...[
+ const SizedBox(height: 4),
+ Text(t.aiMissing(preview.missed.length),
+ style: AppTheme.f(12, weight: FontWeight.w600, color: gc.warn)),
+ const SizedBox(height: 4),
+ Text(preview.missed.join(' · '),
+ style: AppTheme.f(12, weight: FontWeight.w500, color: gc.textTertiary, height: 1.4)),
+ ],
+ if (hasDays) ...[
+ const SizedBox(height: 12),
+ GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: () => setState(() => _schedule = !_schedule),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(vertical: 8),
+ child: Row(children: [
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(t.useTheirSchedule,
+ style: AppTheme.f(14, weight: FontWeight.w600, color: gc.text)),
+ const SizedBox(height: 2),
+ Text(t.useTheirScheduleHint,
+ style: AppTheme.f(11.5, weight: FontWeight.w500, color: gc.textSecondary)),
+ ],
+ ),
+ ),
+ const SizedBox(width: 12),
+ TinySwitch(on: _schedule),
+ ]),
+ ),
+ ),
+ ],
+ const SizedBox(height: 16),
+ PrimaryButton(label: t.addToMyRoutines, onTap: _apply),
+ ] else if (_text.text.trim().isNotEmpty) ...[
+ const SizedBox(height: 16),
+ Row(children: [
+ Icon(PhosphorIconsRegular.warningCircle, size: 16, color: gc.warn),
+ const SizedBox(width: 8),
+ Expanded(
+ child: Text(t.nothingToImport,
+ style: AppTheme.f(13, weight: FontWeight.w600, color: gc.textSecondary)),
+ ),
+ ]),
+ if (!_field) ...[
+ const SizedBox(height: 10),
+ Align(
+ alignment: Alignment.centerLeft,
+ child: Pill(
+ label: t.pasteAction,
+ bg: gc.bgRaised2,
+ fg: gc.accent,
+ onTap: () => setState(() => _field = true),
+ ),
+ ),
+ ],
+ ],
+ ],
+ ),
+ ),
+ );
+ }
+
+ Widget _action(GymColors gc, IconData icon, String label, VoidCallback onTap) => GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: onTap,
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 9),
+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(100)),
+ child: Row(mainAxisSize: MainAxisSize.min, children: [
+ Icon(icon, size: 15, color: gc.text),
+ const SizedBox(width: 7),
+ Text(label, style: AppTheme.f(12.5, weight: FontWeight.w600, color: gc.text)),
+ ]),
+ ),
+ );
+
+ Widget _planCard(GymColors gc, PlanRoutine p) {
+ final meta = [
+ if (p.group.isNotEmpty) p.group,
+ if (p.days.isNotEmpty) _days(p.days),
+ t.exerciseCount(p.items.length),
+ ].join(' · ');
+ return Container(
+ margin: const EdgeInsets.only(bottom: 8),
+ padding: const EdgeInsets.all(12),
+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(16)),
+ child: Row(children: [
+ Container(
+ width: 38,
+ height: 38,
+ decoration: BoxDecoration(color: gc.emberSoft, borderRadius: BorderRadius.circular(11)),
+ child: Icon(PhosphorIconsRegular.listChecks, size: 19, color: gc.ember),
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(p.name.isEmpty ? t.newRoutineName : p.name,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppTheme.f(14, weight: FontWeight.w600, color: gc.text)),
+ const SizedBox(height: 2),
+ Text(meta,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: AppTheme.f(11.5, weight: FontWeight.w500, color: gc.textSecondary)),
+ ],
+ ),
+ ),
+ ]),
+ );
+ }
+}
diff --git a/lib/screens/routines_screen.dart b/lib/screens/routines_screen.dart
index f2b1b7a..8c9eccd 100644
--- a/lib/screens/routines_screen.dart
+++ b/lib/screens/routines_screen.dart
@@ -7,8 +7,13 @@ import '../models/workout.dart';
import '../state/fit_state.dart';
import '../theme/app_colors.dart';
import '../theme/app_theme.dart';
+import '../widgets/dialogs.dart';
+import '../widgets/glass.dart';
+import '../widgets/liquid_notch.dart';
+import '../widgets/routine_folder.dart';
import '../widgets/svg_icon.dart';
import '../widgets/ui_kit.dart';
+import 'plan_import_sheet.dart';
class RoutinesScreen extends StatelessWidget {
const RoutinesScreen({super.key});
@@ -19,16 +24,43 @@ class RoutinesScreen extends StatelessWidget {
return SafeArea(
bottom: false,
child: SingleChildScrollView(
+ clipBehavior: Clip.none,
padding: const EdgeInsets.fromLTRB(20, 12, 20, 40),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- ScreenHeader(title: t.routines, onBack: fit.backFromRoutines, titleSize: 22),
+ ScreenHeader(
+ title: t.routines,
+ onBack: fit.backFromRoutines,
+ titleSize: 22,
+ actions: [
+ Semantics(
+ button: true,
+ label: t.importRoutines,
+ child: RoundAction(
+ onTap: () => showPlanImportSheet(context),
+ child: Icon(PhosphorIconsRegular.downloadSimple, size: 17, color: gc.text),
+ ),
+ ),
+ if (fit.routines.isNotEmpty) ...[
+ const SizedBox(width: 8),
+ Semantics(
+ button: true,
+ label: t.shareWeek,
+ child: RoundAction(
+ onTap: () => _shareMenu(context),
+ child: Icon(PhosphorIconsRegular.shareNetwork, size: 17, color: gc.text),
+ ),
+ ),
+ ],
+ ],
+ ),
const SizedBox(height: 22),
Text(t.weeklyPlan, style: AppTheme.f(12, weight: FontWeight.w600, color: gc.textSecondary, letterSpacing: 1.5)),
const SizedBox(height: 10),
SoftCard(
- radius: 18,
+ radius: 20,
+ borderColor: Colors.transparent,
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4),
child: Column(children: [for (int i = 0; i < 7; i++) _dayRow(context, gc, i)]),
),
@@ -44,10 +76,10 @@ class RoutinesScreen extends StatelessWidget {
else ...[
for (final group in fit.routineGroups) ...[
_groupHeader(gc, group, fit.routinesInGroup(group).length),
- for (final r in fit.routinesInGroup(group)) _routineCard(gc, r),
- const SizedBox(height: 8),
+ _folders(context, fit.routinesInGroup(group)),
+ const SizedBox(height: 10),
],
- for (final r in fit.routinesInGroup('')) _routineCard(gc, r),
+ _folders(context, fit.routinesInGroup('')),
],
const SizedBox(height: 16),
PrimaryButton(
@@ -61,6 +93,12 @@ class RoutinesScreen extends StatelessWidget {
onTap: () => _openTemplates(context),
),
const SizedBox(height: 10),
+ GhostButton(
+ label: t.importRoutines,
+ icon: PhosphorIconsRegular.downloadSimple,
+ onTap: () => showPlanImportSheet(context),
+ ),
+ const SizedBox(height: 10),
GhostButton(
label: t.aiRoutine,
icon: PhosphorIconsRegular.sparkle,
@@ -72,9 +110,10 @@ class RoutinesScreen extends StatelessWidget {
);
}
- void _openTemplates(BuildContext context) {
+ void _shareMenu(BuildContext context) {
final gc = context.gc;
- showModalBottomSheet<void>(
+ final planned = fit.routines.where((r) => fit.weeklyPlan.containsValue(r.id)).toList();
+ showAppSheet<void>(
context: context,
backgroundColor: Colors.transparent,
isScrollControlled: true,
@@ -92,14 +131,98 @@ class RoutinesScreen extends StatelessWidget {
children: [
const SheetHandle(),
const SizedBox(height: 18),
- Text(t.templates,
- textAlign: TextAlign.center,
- style: AppTheme.f(14, weight: FontWeight.w700, color: gc.text, letterSpacing: 0.4)),
- const SizedBox(height: 6),
- Text(t.templatesHint,
- textAlign: TextAlign.center,
- style: AppTheme.f(12, weight: FontWeight.w500, color: gc.textSecondary, height: 1.4)),
- const SizedBox(height: 18),
+ _shareOption(gc, PhosphorIconsRegular.calendarDots, t.shareWeek, t.shareWeekHint, () {
+ Navigator.pop(sheet);
+ sharePlan(planned.isEmpty ? fit.routines : [
+ ...planned,
+ ...fit.routines.where((r) => !planned.contains(r)),
+ ], title: t.weeklyPlan);
+ }),
+ const SizedBox(height: 14),
+ Text(t.shareRoutine.toUpperCase(),
+ style: AppTheme.f(10.5, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 1.3)),
+ const SizedBox(height: 8),
+ for (final r in [
+ for (final group in fit.routineGroups) ...fit.routinesInGroup(group),
+ ...fit.routinesInGroup(''),
+ ])
+ _shareOption(
+ gc,
+ PhosphorIconsRegular.listChecks,
+ fit.routineTitle(r),
+ [if (r.group.isNotEmpty) r.group, t.exerciseCount(r.exerciseIds.length)].join(' · '),
+ () {
+ Navigator.pop(sheet);
+ sharePlan([r]);
+ },
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _shareOption(GymColors gc, IconData icon, String title, String hint, VoidCallback onTap) {
+ return GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: onTap,
+ child: Container(
+ margin: const EdgeInsets.only(bottom: 8),
+ padding: const EdgeInsets.all(12),
+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(16)),
+ child: Row(children: [
+ Container(
+ width: 38,
+ height: 38,
+ decoration: BoxDecoration(color: gc.emberSoft, borderRadius: BorderRadius.circular(11)),
+ child: Icon(icon, size: 19, color: gc.ember),
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(title,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppTheme.f(14, weight: FontWeight.w600, color: gc.text)),
+ const SizedBox(height: 2),
+ Text(hint,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: AppTheme.f(11.5, weight: FontWeight.w500, color: gc.textSecondary)),
+ ],
+ ),
+ ),
+ Icon(PhosphorIconsRegular.shareNetwork, size: 16, color: gc.textSecondary),
+ ]),
+ ),
+ );
+ }
+
+ void _openTemplates(BuildContext context) {
+ final gc = context.gc;
+ showAppSheet<void>(
+ context: context,
+ backgroundColor: Colors.transparent,
+ isScrollControlled: true,
+ builder: (sheet) => Container(
+ padding: sheetPad(sheet),
+ constraints: BoxConstraints(maxHeight: MediaQuery.sizeOf(sheet).height * 0.85),
+ decoration: BoxDecoration(
+ color: gc.bgRaised,
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),
+ ),
+ child: SingleChildScrollView(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ const SheetHandle(),
+ const SizedBox(height: 16),
+ SheetTitle(t.templates, subtitle: t.templatesHint),
+ const SizedBox(height: 16),
for (final template in kProgramTemplates)
_templateCard(context, gc, sheet, template),
],
@@ -117,9 +240,8 @@ class RoutinesScreen extends StatelessWidget {
final made = fit.applyTemplate(template);
Navigator.pop(sheet);
if (made == 0 || !context.mounted) return;
- ScaffoldMessenger.of(context).showSnackBar(
- SnackBar(content: Text(t.templateAdded(made)), behavior: SnackBarBehavior.floating),
- );
+ showNotchToast(context, t.templateAdded(made),
+ subtitle: template.name, icon: PhosphorIconsFill.stack, accent: context.gc.sage);
},
child: Container(
margin: const EdgeInsets.only(bottom: 10),
@@ -211,111 +333,130 @@ class RoutinesScreen extends StatelessWidget {
);
}
- Widget _routineCard(GymColors gc, Routine r) {
- final n = r.exerciseIds.length;
- return GestureDetector(
- onTap: () => fit.openRoutine(r.id),
- behavior: HitTestBehavior.opaque,
- child: Container(
- margin: const EdgeInsets.only(bottom: 10),
- padding: const EdgeInsets.all(14),
- decoration: BoxDecoration(
- color: gc.bgRaised,
- borderRadius: BorderRadius.circular(18),
- ),
- child: Row(
- children: [
- Container(
- width: 44,
- height: 44,
- decoration: BoxDecoration(color: gc.emberSoft, borderRadius: BorderRadius.circular(12)),
- child: Icon(PhosphorIconsRegular.listChecks, size: 22, color: gc.ember),
- ),
- const SizedBox(width: 14),
+ Widget _folders(BuildContext context, List<Routine> list) {
+ return Column(children: [
+ for (var i = 0; i < list.length; i += 2)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 12),
+ child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Expanded(child: RoutineFolder(routine: list[i], onMenu: () => _routineMenu(context, list[i]))),
+ const SizedBox(width: 12),
Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(fit.routineTitle(r), style: AppTheme.f(15, weight: FontWeight.w600, color: gc.text)),
- const SizedBox(height: 2),
- Text(t.exerciseCount(n), style: AppTheme.f(12, weight: FontWeight.w500, color: gc.textSecondary)),
- ],
- ),
+ child: i + 1 < list.length
+ ? RoutineFolder(routine: list[i + 1], onMenu: () => _routineMenu(context, list[i + 1]))
+ : const SizedBox.shrink(),
),
- if (n > 0)
- GestureDetector(
- onTap: () => fit.startRoutine(r),
- child: Container(
- width: 40,
- height: 40,
- decoration: BoxDecoration(color: gc.ember, shape: BoxShape.circle),
- child: Icon(PhosphorIconsFill.play, size: 18, color: gc.onEmber),
- ),
- ),
- ],
+ ]),
),
- ),
- );
+ ]);
}
- void _pickRoutine(BuildContext context, int weekday) {
+ void _routineMenu(BuildContext context, Routine r) {
final gc = context.gc;
- showModalBottomSheet<void>(
+ showAppSheet<void>(
context: context,
- backgroundColor: gc.bgRaised,
- shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(24))),
- builder: (_) => SafeArea(
- child: Padding(
- padding: const EdgeInsets.fromLTRB(20, 18, 20, 20),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Text(t.setDay(t.weekday(weekday).toUpperCase()),
- style: AppTheme.f(14, weight: FontWeight.w700, color: gc.text, letterSpacing: 0.4)),
- const SizedBox(height: 14),
- _sheetItem(context, gc, t.restDayShort, fit.weeklyPlan[weekday] == null, () {
- fit.assignRoutineToDay(weekday, null);
- Navigator.pop(context);
+ backgroundColor: Colors.transparent,
+ builder: (sheet) => Container(
+ padding: sheetPad(sheet),
+ decoration: BoxDecoration(
+ color: gc.bgRaised,
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),
+ ),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ const SheetHandle(),
+ const SizedBox(height: 16),
+ SheetTitle(fit.routineTitle(r), subtitle: t.exerciseCount(r.exerciseIds.length)),
+ const SizedBox(height: 14),
+ OptionGroup([
+ OptionItem(t.editEntry, icon: PhosphorIconsRegular.pencilSimple, onTap: () {
+ Navigator.pop(sheet);
+ fit.openRoutine(r.id);
}),
- for (final r in [
- for (final group in fit.routineGroups) ...fit.routinesInGroup(group),
- ...fit.routinesInGroup(''),
- ])
- _sheetItem(
- context,
- gc,
- r.group.isEmpty ? fit.routineTitle(r) : '${r.group} · ${fit.routineTitle(r)}',
- fit.weeklyPlan[weekday] == r.id, () {
- fit.assignRoutineToDay(weekday, r.id);
- Navigator.pop(context);
+ if (r.exerciseIds.isNotEmpty)
+ OptionItem(titleCase(t.startWorkout), icon: PhosphorIconsRegular.play, onTap: () {
+ Navigator.pop(sheet);
+ fit.startRoutine(r);
}),
- ],
- ),
+ OptionItem(t.shareRoutine, icon: PhosphorIconsRegular.shareNetwork, onTap: () {
+ Navigator.pop(sheet);
+ sharePlan([r]);
+ }),
+ OptionItem(t.duplicateRoutine, icon: PhosphorIconsRegular.copy, onTap: () {
+ Navigator.pop(sheet);
+ fit.duplicateRoutine(r.id);
+ }),
+ OptionItem(t.delete, icon: PhosphorIconsRegular.trash, danger: true, onTap: () async {
+ Navigator.pop(sheet);
+ final ok = await askConfirm(
+ context,
+ title: t.deleteRoutine,
+ body: fit.routineTitle(r),
+ confirmLabel: t.delete,
+ danger: true,
+ );
+ if (ok) fit.deleteRoutine(r.id);
+ }),
+ ]),
+ ],
),
),
);
}
- Widget _sheetItem(BuildContext context, GymColors gc, String label, bool selected, VoidCallback onTap) {
- return GestureDetector(
- onTap: onTap,
- behavior: HitTestBehavior.opaque,
- child: Container(
- margin: const EdgeInsets.only(bottom: 8),
- padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
+ void _pickRoutine(BuildContext context, int weekday) {
+ final gc = context.gc;
+ final routines = [
+ for (final group in fit.routineGroups) ...fit.routinesInGroup(group),
+ ...fit.routinesInGroup(''),
+ ];
+ showAppSheet<void>(
+ context: context,
+ isScrollControlled: true,
+ backgroundColor: Colors.transparent,
+ builder: (sheet) => Container(
+ constraints: BoxConstraints(maxHeight: MediaQuery.sizeOf(sheet).height * 0.72),
+ padding: sheetPad(sheet),
decoration: BoxDecoration(
- color: selected ? gc.emberSoft : gc.bgRaised2,
- borderRadius: BorderRadius.circular(14),
- border: Border.all(color: selected ? gc.ember : Colors.transparent),
+ color: gc.bgRaised,
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(28)),
),
- child: Row(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- Expanded(
- child: Text(label,
- style: AppTheme.f(14, weight: FontWeight.w600, color: selected ? gc.ember : gc.text)),
+ const SheetHandle(),
+ const SizedBox(height: 16),
+ SheetTitle(titleCase(t.setDay(t.weekday(weekday).toUpperCase()))),
+ const SizedBox(height: 14),
+ Flexible(
+ child: OptionGroup(
+ scroll: true,
+ [
+ OptionItem(
+ t.restDayShort,
+ icon: PhosphorIconsRegular.moonStars,
+ selected: fit.weeklyPlan[weekday] == null,
+ onTap: () {
+ fit.assignRoutineToDay(weekday, null);
+ Navigator.pop(sheet);
+ },
+ ),
+ for (final r in routines)
+ OptionItem(
+ fit.routineTitle(r),
+ detail: r.group.isEmpty ? null : r.group,
+ selected: fit.weeklyPlan[weekday] == r.id,
+ onTap: () {
+ fit.assignRoutineToDay(weekday, r.id);
+ Navigator.pop(sheet);
+ },
+ ),
+ ],
+ ),
),
- if (selected) SvgPathIcon(Ic.checkBold, size: 16, color: gc.ember),
],
),
),
diff --git a/lib/screens/share_sheet.dart b/lib/screens/share_sheet.dart
index 00a431e..1882fed 100644
--- a/lib/screens/share_sheet.dart
+++ b/lib/screens/share_sheet.dart
@@ -4,17 +4,20 @@ import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:path_provider/path_provider.dart';
+import 'package:phosphoricons_flutter/phosphoricons_flutter.dart';
import 'package:share_plus/share_plus.dart';
import '../l10n/l10n.dart';
import '../state/fit_state.dart';
import '../theme/app_colors.dart';
import '../theme/app_theme.dart';
+import '../widgets/glass.dart';
+import '../widgets/liquid_notch.dart';
import '../widgets/share_cards.dart';
import '../widgets/ui_kit.dart';
Future<void> showShareSheet(BuildContext context, {ShareKind initial = ShareKind.streak}) =>
- showModalBottomSheet<void>(
+ showAppSheet<void>(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
@@ -65,7 +68,7 @@ class _ShareSheetState extends State<_ShareSheet> {
await SharePlus.instance.share(ShareParams(files: [XFile(file.path)], subject: 'GymMane'));
} catch (_) {
if (mounted) {
- ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(t.shareFailed)));
+ showNotchToast(context, t.shareFailed, icon: PhosphorIconsFill.warningCircle, accent: context.gc.warn);
}
} finally {
if (mounted) setState(() => _busy = false);
diff --git a/lib/services/exercise_match.dart b/lib/services/exercise_match.dart
index 07a9a1a..87a5289 100644
--- a/lib/services/exercise_match.dart
+++ b/lib/services/exercise_match.dart
@@ -83,6 +83,25 @@ bool _sameEquipment(Set<String> q, Set<String> c) {
return qe.intersection(ce).isNotEmpty;
}
+const _modifiers = {
+ 'one', 'single', 'arm', 'seated', 'sitted', 'standing', 'lying', 'alternate', 'alternating',
+ 'wide', 'close', 'narrow', 'grip', 'straight', 'bent', 'over', 'both', 'two', 'double', 'hand',
+};
+
+bool _fits(Set<String> qCore, Set<String> q, Set<String> c) {
+ if (qCore.isNotEmpty && c.containsAll(qCore)) return true;
+ final cMeaning = c.difference(_equipment);
+ return cMeaning.length >= 2 && cMeaning.difference(_modifiers).isNotEmpty && q.containsAll(cMeaning);
+}
+
+const _legs = {'quads', 'glutes', 'hamstrings', 'calves'};
+
+bool _sameMuscle(String? hint, Exercise e) =>
+ hint == null ||
+ e.primary == hint ||
+ e.secondary.contains(hint) ||
+ (_legs.contains(hint) && _legs.contains(e.primary));
+
int _score(Set<String> q, Set<String> c) {
final shared = q.intersection(c);
if (shared.difference(_equipment).isEmpty) return 0;
@@ -97,7 +116,7 @@ const _muscleHints = <List<String>, String>{
['oblique', 'twist', 'side bend', 'wood chop', 'russian']: 'obliques',
['crunch', 'sit up', 'plank', 'abdominal', 'leg raise', 'hollow', 'v up']: 'abdomen',
['shrug', 'trap ', 'trapezius', 'upright row']: 'trapezius',
- ['forearm', 'wrist', 'grip', 'farmer']: 'forearm',
+ ['forearm', 'wrist', 'farmer', 'gripper', 'hand grip']: 'forearm',
['triceps', 'pushdown', 'skullcrusher', 'kickback', 'dip']: 'triceps',
['biceps', 'curl', 'preacher', 'chin up']: 'biceps',
['lateral raise', 'shoulder', 'overhead press', 'military', 'arnold', 'face pull', 'delt', 'upright']:
@@ -120,6 +139,10 @@ Exercise? matchExercise(String name, Iterable<Exercise> pool) {
final key = searchKey(name);
if (key.isEmpty) return null;
+ for (final e in pool) {
+ if (_keyOf(e.name) == key) return e;
+ }
+
final alias = _aliasIndex[sortedKey(name)];
if (alias != null) {
final wanted = searchKey(alias);
@@ -136,6 +159,8 @@ Exercise? matchExercise(String name, Iterable<Exercise> pool) {
final q = key.split(' ').toSet();
final qMeaning = q.difference(_equipment);
if (qMeaning.isEmpty) return null;
+ final qCore = qMeaning.difference(_modifiers);
+ final hint = guessMuscle(name);
Exercise? exact;
var exactExtra = 1 << 30;
@@ -144,14 +169,14 @@ Exercise? matchExercise(String name, Iterable<Exercise> pool) {
for (final e in pool) {
final c = nameTokens(e.name).toSet();
- if (c.isEmpty || !_sameEquipment(q, c)) continue;
+ if (c.isEmpty || !_sameEquipment(q, c) || !_sameMuscle(hint, e)) continue;
if (c.containsAll(qMeaning)) {
final extra = c.difference(q).length;
if (extra < exactExtra) {
exact = e;
exactExtra = extra;
}
- } else {
+ } else if (_fits(qCore, q, c)) {
final s = _score(q, c);
if (s > looseScore) {
loose = e;
@@ -159,6 +184,5 @@ Exercise? matchExercise(String name, Iterable<Exercise> pool) {
}
}
}
- if (exact != null) return exact;
- return looseScore >= 5 ? loose : null;
+ return exact ?? (looseScore >= 3 ? loose : null);
}
diff --git a/lib/services/incoming_share.dart b/lib/services/incoming_share.dart
new file mode 100644
index 0000000..dda2dd3
--- /dev/null
+++ b/lib/services/incoming_share.dart
@@ -0,0 +1,23 @@
+import 'package:flutter/services.dart';
+
+class IncomingShare {
+ IncomingShare._();
+
+ static const _channel = MethodChannel('gymmane/incoming');
+
+ static void listen(void Function(String text) onText) {
+ _channel.setMethodCallHandler((call) async {
+ final text = call.arguments;
+ if (call.method == 'incoming' && text is String && text.trim().isNotEmpty) onText(text);
+ });
+ }
+
+ static Future<String?> take() async {
+ try {
+ final text = await _channel.invokeMethod<String>('take');
+ return text == null || text.trim().isEmpty ? null : text;
+ } catch (_) {
+ return null;
+ }
+ }
+}
diff --git a/lib/services/plan_share.dart b/lib/services/plan_share.dart
index 15fc432..c97452b 100644
--- a/lib/services/plan_share.dart
+++ b/lib/services/plan_share.dart
@@ -1,58 +1,151 @@
import 'dart:convert';
+class PlanSet {
+ const PlanSet({this.reps, this.weightKg, this.kind = 0, this.sec, this.km});
+ final int? reps;
+ final double? weightKg;
+ final int kind;
+ final int? sec;
+ final double? km;
+}
+
class PlanItem {
- const PlanItem(this.name, this.sets);
+ const PlanItem(
+ this.name,
+ this.sets, {
+ this.id,
+ this.reps,
+ this.weightKg,
+ this.restSec,
+ this.superset = false,
+ this.plan = const [],
+ this.muscle,
+ this.equipment,
+ this.level,
+ this.steps = const [],
+ this.mode = '',
+ });
final String name;
final int? sets;
+ final String? id;
+ final int? reps;
+ final double? weightKg;
+ final int? restSec;
+ final bool superset;
+ final List<PlanSet> plan;
+ final String? muscle;
+ final String? equipment;
+ final String? level;
+ final List<String> steps;
+ final String mode;
}
class PlanRoutine {
- const PlanRoutine(this.name, this.items);
+ const PlanRoutine(this.name, this.items, {this.group = '', this.days = const []});
final String name;
final List<PlanItem> items;
+ final String group;
+ final List<int> days;
}
-const _nameKeys = ['name', 'routine', 'title', 'nombre', 'rutina'];
-const _listKeys = ['exercises', 'items', 'ejercicios', 'movements', 'workout'];
+const _nameKeys = ['name', 'routine', 'title', 'nombre', 'rutina', 'workout', 'day', 'dia'];
+const _listKeys = ['exercises', 'items', 'ejercicios', 'movements', 'exercicios', 'esercizi', 'ubungen'];
+const _routineListKeys = ['routines', 'rutinas', 'plan', 'days', 'workouts', 'sessions', 'dias'];
+const _groupKeys = ['group', 'grupo', 'folder', 'program', 'programme', 'programa', 'split'];
+const _weekKeys = ['weeks', 'semanas', 'mesocycle', 'blocks'];
+const _dayKeys = ['days', 'dias', 'weekdays', 'schedule', 'on'];
const _setKeys = ['sets', 'series', 'setcount'];
-const _itemNameKeys = [..._nameKeys, 'exercise', 'ejercicio', 'movement', 'exercisename'];
+const _repKeys = ['reps', 'repetitions', 'repeticiones', 'rep', 'repeticoes', 'ripetizioni'];
+const _weightKeys = ['weight', 'weightkg', 'load', 'kg', 'peso', 'carga', 'lbs', 'lb'];
+const _restKeys = ['rest', 'restseconds', 'restsec', 'descanso', 'pause', 'riposo'];
+const _timeKeys = ['time', 'duration', 'seconds', 'sec', 'secs', 'tiempo', 'durationseconds'];
+const _distanceKeys = ['distance', 'km', 'distancekm', 'distancia'];
+const _itemNameKeys = ['name', 'exercise', 'ejercicio', 'movement', 'exercisename', 'title', 'nombre'];
+
+const _weekdayNames = {
+ 1: ['monday', 'mon', 'lunes', 'lun', 'segunda', 'lunedi', 'montag', 'mo'],
+ 2: ['tuesday', 'tue', 'tues', 'martes', 'mar', 'terca', 'martedi', 'dienstag', 'di'],
+ 3: ['wednesday', 'wed', 'miercoles', 'mie', 'quarta', 'mercoledi', 'mittwoch', 'mi'],
+ 4: ['thursday', 'thu', 'thur', 'thurs', 'jueves', 'jue', 'quinta', 'giovedi', 'donnerstag', 'do'],
+ 5: ['friday', 'fri', 'viernes', 'vie', 'sexta', 'venerdi', 'freitag', 'fr'],
+ 6: ['saturday', 'sat', 'sabado', 'sab', 'sabato', 'samstag', 'sa'],
+ 7: ['sunday', 'sun', 'domingo', 'dom', 'domenica', 'sonntag', 'so'],
+};
List<PlanRoutine> parsePlan(String raw) {
final data = _decode(raw);
- if (data == null) return const [];
+ if (data == null) return _parseCsv(raw);
+ final lb = data is Map<Object?, Object?> && _isLb(_value(data, ['unit', 'units', 'unidad']));
final out = <PlanRoutine>[];
- void addMap(Map<Object?, Object?> map) {
- final items = _items(_value(map, _listKeys));
+ void addRoutine(Map<Object?, Object?> map, String group) {
+ final items = _items(_value(map, _listKeys), lb);
if (items.isEmpty) return;
- out.add(PlanRoutine(_string(_value(map, _nameKeys)), items));
+ final own = _string(_value(map, _groupKeys));
+ out.add(PlanRoutine(
+ _string(_value(map, _nameKeys)),
+ items,
+ group: own.isNotEmpty ? own : group,
+ days: _days(_value(map, _dayKeys)),
+ ));
+ }
+
+ void addRoutines(List<Object?> list, String group) {
+ if (list.isNotEmpty && list.every((e) => e is String)) {
+ out.add(PlanRoutine('', _items(list, lb), group: group));
+ return;
+ }
+ for (final r in list) {
+ if (r is Map<Object?, Object?>) addRoutine(r, group);
+ }
}
if (data is Map<Object?, Object?>) {
- final nested = _value(data, ['routines', 'rutinas', 'plan', 'days']);
- if (nested is List) {
- for (final r in nested) {
- if (r is Map<Object?, Object?>) addMap(r);
+ final program = _string(_value(data, _groupKeys));
+ final weeks = _value(data, _weekKeys);
+ final nested = _routineList(data);
+ if (weeks is List) {
+ var n = 0;
+ for (final w in weeks) {
+ n++;
+ if (w is! Map<Object?, Object?>) continue;
+ final label = _string(_value(w, _nameKeys + ['week', 'semana']));
+ final week = label.isNotEmpty ? label : 'Week $n';
+ final group = program.isEmpty ? week : '$program · $week';
+ final inner = _routineList(w);
+ if (inner != null) addRoutines(inner, group);
}
+ } else if (nested != null) {
+ final name = _string(_value(data, _nameKeys));
+ addRoutines(nested, program.isNotEmpty ? program : (_listOfRoutines(nested) ? name : ''));
} else {
- addMap(data);
+ addRoutine(data, '');
}
} else if (data is List) {
- if (data.every((e) => e is String)) {
- out.add(PlanRoutine('', _items(data)));
- } else {
- for (final r in data) {
- if (r is Map<Object?, Object?>) addMap(r);
- }
- }
+ addRoutines(data, '');
}
return out;
}
+bool _listOfRoutines(List<Object?> list) =>
+ list.isNotEmpty && list.every((e) => e is Map<Object?, Object?> && _value(e, _listKeys) is List);
+
+List<Object?>? _routineList(Map<Object?, Object?> map) {
+ for (final entry in map.entries) {
+ final k = _norm(entry.key);
+ final v = entry.value;
+ if (!_routineListKeys.contains(k) || v is! List) continue;
+ if (v.isNotEmpty && v.every((e) => e is num || e is String) && _dayKeys.contains(k)) continue;
+ return v;
+ }
+ return null;
+}
+
Object? _decode(String raw) {
for (final text in _candidates(raw)) {
try {
- return jsonDecode(text);
+ final data = jsonDecode(text);
+ if (data is Map || data is List) return data;
} catch (_) {
continue;
}
@@ -73,17 +166,117 @@ List<String> _candidates(String raw) {
return out;
}
+String _norm(Object? key) => key.toString().toLowerCase().replaceAll(RegExp(r'[^a-z]'), '');
+
Object? _value(Map<Object?, Object?> map, List<String> keys) {
- for (final entry in map.entries) {
- final k = entry.key.toString().toLowerCase().replaceAll(RegExp(r'[^a-z]'), '');
- if (keys.contains(k)) return entry.value;
+ for (final key in keys) {
+ for (final entry in map.entries) {
+ if (_norm(entry.key) == key) return entry.value;
+ }
}
return null;
}
-String _string(Object? v) => v is String ? v.trim() : '';
+String _string(Object? v) => v is String ? v.trim() : (v is num ? '$v' : '');
+
+bool _isLb(Object? v) => v is String && RegExp(r'^\s*(lb|lbs|pounds?)\s*$', caseSensitive: false).hasMatch(v);
+
+int? _int(Object? v) {
+ if (v is num) return v.round();
+ if (v is String) {
+ final m = RegExp(r'\d+').firstMatch(v);
+ return m == null ? null : int.parse(m.group(0)!);
+ }
+ return null;
+}
+
+double? _double(Object? v) {
+ if (v is num) return v.toDouble();
+ if (v is String) {
+ final m = RegExp(r'\d+(?:[.,]\d+)?').firstMatch(v);
+ return m == null ? null : double.tryParse(m.group(0)!.replaceAll(',', '.'));
+ }
+ return null;
+}
+
+double? _weight(Object? v, bool lb) {
+ final n = _double(v);
+ if (n == null) return null;
+ final inLb = lb || (v is String && RegExp(r'lb', caseSensitive: false).hasMatch(v));
+ return inLb ? n / 2.20462 : n;
+}
+
+int? _seconds(Object? v) {
+ if (v is num) return v.round();
+ if (v is! String) return null;
+ final s = v.trim().toLowerCase();
+ final clock = RegExp(r'^(\d+):(\d{1,2})(?::(\d{1,2}))?$').firstMatch(s);
+ if (clock != null) {
+ final a = int.parse(clock.group(1)!), b = int.parse(clock.group(2)!);
+ final c = clock.group(3);
+ return c == null ? a * 60 + b : a * 3600 + b * 60 + int.parse(c);
+ }
+ final n = _double(s);
+ if (n == null) return null;
+ if (s.contains('h')) return (n * 3600).round();
+ if (s.contains('min') || RegExp(r'\d\s*m\b').hasMatch(s)) return (n * 60).round();
+ return n.round();
+}
+
+int _kind(Object? v) {
+ final s = _norm(v);
+ if (s.startsWith('warm') || s.startsWith('calent') || s == 'w') return 1;
+ if (s.startsWith('drop')) return 2;
+ if (s.startsWith('fail') || s.startsWith('fallo') || s == 'amrap') return 3;
+ if (s.startsWith('restpause') || s == 'rp') return 4;
+ return 0;
+}
+
+List<int> _days(Object? v) {
+ final list = v is List ? v : (v is String ? v.split(RegExp(r'[,/;\s]+')) : const []);
+ final out = <int>{};
+ for (final d in list) {
+ if (d is num && d >= 1 && d <= 7) out.add(d.toInt());
+ if (d is String) {
+ final k = d
+ .toLowerCase()
+ .replaceAll(RegExp(r'[áàâä]'), 'a')
+ .replaceAll(RegExp(r'[éèêë]'), 'e')
+ .replaceAll(RegExp(r'[íìîï]'), 'i')
+ .replaceAll(RegExp(r'[óòôö]'), 'o')
+ .replaceAll(RegExp(r'[úùûü]'), 'u')
+ .replaceAll('ç', 'c')
+ .replaceAll(RegExp(r'[^a-z0-9]'), '');
+ final n = int.tryParse(k);
+ if (n != null && n >= 1 && n <= 7) {
+ out.add(n);
+ continue;
+ }
+ for (final e in _weekdayNames.entries) {
+ if (e.value.contains(k) || (k.length > 3 && e.value.first.startsWith(k))) out.add(e.key);
+ }
+ }
+ }
+ return out.toList()..sort();
+}
+
+List<PlanSet> _planSets(Object? raw, bool lb) {
+ if (raw is! List) return const [];
+ final out = <PlanSet>[];
+ for (final s in raw) {
+ if (s is! Map<Object?, Object?>) continue;
+ out.add(PlanSet(
+ reps: _int(_value(s, _repKeys)),
+ weightKg: _weight(_value(s, _weightKeys), lb || _value(s, ['lbs', 'lb']) != null),
+ kind: _kind(_value(s, ['type', 'kind', 'tipo', 'settype'])),
+ sec: _seconds(_value(s, _timeKeys)),
+ km: _double(_value(s, _distanceKeys)),
+ ));
+ }
+ return out;
+}
-List<PlanItem> _items(Object? raw) {
+List<PlanItem> _items(Object? raw, bool lb) {
if (raw is! List) return const [];
final out = <PlanItem>[];
for (final entry in raw) {
@@ -91,12 +284,115 @@ List<PlanItem> _items(Object? raw) {
if (entry.trim().isNotEmpty) out.add(PlanItem(entry.trim(), null));
continue;
}
- if (entry is Map<Object?, Object?>) {
- final name = _string(_value(entry, _itemNameKeys));
- if (name.isEmpty) continue;
- final sets = _value(entry, _setKeys);
- out.add(PlanItem(name, sets is num ? sets.toInt() : int.tryParse('$sets')));
- }
+ if (entry is! Map<Object?, Object?>) continue;
+ final name = _string(_value(entry, _itemNameKeys));
+ final id = _string(_value(entry, ['id', 'exerciseid']));
+ if (name.isEmpty && id.isEmpty) continue;
+ final itemLb = lb || _isLb(_value(entry, ['unit', 'units'])) || _value(entry, ['lbs', 'lb']) != null;
+ final custom = _value(entry, ['custom', 'own', 'details']);
+ final info = custom is Map<Object?, Object?> ? custom : const <Object?, Object?>{};
+ final steps = _value(info, ['steps', 'howto', 'pasos', 'instructions']);
+ final superset = _value(entry, ['superset', 'supersetwithnext', 'linked', 'chain']);
+ out.add(PlanItem(
+ name.isEmpty ? id : name,
+ _int(_value(entry, _setKeys)),
+ id: id.isEmpty ? null : id,
+ reps: _int(_value(entry, _repKeys)),
+ weightKg: _weight(_value(entry, _weightKeys), itemLb),
+ restSec: _seconds(_value(entry, _restKeys)),
+ superset: superset == true || (superset is String && superset.toLowerCase() == 'true'),
+ plan: _planSets(_value(entry, ['plan', 'setplan', 'setsplan', 'detail']), itemLb),
+ muscle: _string(_value(info, ['muscle', 'primary', 'musculo'])),
+ equipment: _string(_value(info, ['equipment', 'material', 'gear'])),
+ level: _string(_value(info, ['level', 'difficulty', 'nivel'])),
+ steps: steps is List ? steps.whereType<String>().toList() : const [],
+ mode: _string(_value(info, ['track', 'mode', 'type'])),
+ ));
}
return out;
}
+
+List<List<String>> _rows(String raw) {
+ final lines = raw.split(RegExp(r'\r?\n')).map((l) => l.trim()).where((l) => l.isNotEmpty).toList();
+ if (lines.isEmpty) return const [];
+ final first = lines.first;
+ final sep = [';', '\t', ','].reduce((a, b) => first.split(a).length >= first.split(b).length ? a : b);
+ List<String> split(String line) {
+ final cells = <String>[];
+ final cell = StringBuffer();
+ var quoted = false;
+ for (var i = 0; i < line.length; i++) {
+ final c = line[i];
+ if (c == '"') {
+ quoted = !quoted;
+ } else if (c == sep && !quoted) {
+ cells.add(cell.toString().trim());
+ cell.clear();
+ } else {
+ cell.write(c);
+ }
+ }
+ cells.add(cell.toString().trim());
+ return cells;
+ }
+
+ return lines.map(split).where((r) => r.length >= 2).toList();
+}
+
+List<PlanRoutine> _parseCsv(String raw) {
+ final rows = _rows(raw);
+ if (rows.isEmpty) return const [];
+ final head = rows.first.map(_norm).toList();
+ int col(List<String> keys) => head.indexWhere(keys.contains);
+ var exercise = col(['exercise', 'ejercicio', 'exercisename', 'movement', 'name']);
+ var routine = col(['routine', 'rutina', 'workout', 'day', 'dia', 'session']);
+ var sets = col(_setKeys);
+ var reps = col(_repKeys);
+ var weight = col(_weightKeys);
+ final group = col(['week', 'semana', 'group', 'grupo', 'program']);
+ final rest = col(_restKeys);
+ final days = col(['weekday', 'weekdays', 'schedule']);
+ final lb = head.any((h) => h == 'lbs' || h == 'lb' || h == 'weightlbs');
+ var body = rows.skip(1).toList();
+ if (exercise < 0) {
+ final probe = rows.first;
+ if (probe.length < 3 || _int(probe[1]) != null || _int(probe[2]) == null) return const [];
+ body = rows;
+ routine = 0;
+ exercise = 1;
+ sets = 2;
+ reps = 3;
+ weight = 4;
+ }
+ String cell(List<String> r, int i) => i >= 0 && i < r.length ? r[i] : '';
+
+ final order = <String>[];
+ final grouped = <String, List<PlanItem>>{};
+ final groups = <String, String>{};
+ final schedule = <String, List<int>>{};
+ for (final r in body) {
+ final name = cell(r, exercise);
+ if (name.isEmpty || _int(name) != null) continue;
+ final g = cell(r, group);
+ final key = '$g|${cell(r, routine)}';
+ if (!grouped.containsKey(key)) {
+ order.add(key);
+ grouped[key] = [];
+ groups[key] = g;
+ schedule[key] = _days(cell(r, days));
+ }
+ grouped[key]!.add(PlanItem(
+ name,
+ _int(cell(r, sets)),
+ reps: _int(cell(r, reps)),
+ weightKg: _weight(cell(r, weight), lb),
+ restSec: _seconds(cell(r, rest)),
+ ));
+ }
+ return [
+ for (final key in order)
+ PlanRoutine(key.split('|').last, grouped[key]!, group: groups[key]!, days: schedule[key]!),
+ ];
+}
+
+String encodePlan(Map<String, Object?> plan) => const JsonEncoder.withIndent(' ').convert(plan);
diff --git a/lib/services/workout_import.dart b/lib/services/workout_import.dart
index 106d73a..384b214 100644
--- a/lib/services/workout_import.dart
+++ b/lib/services/workout_import.dart
@@ -9,6 +9,8 @@ const double _lbPerKg = 2.2046226218;
enum ImportFormat {
hevy,
strong,
+ lyfta,
+ fitbod,
fitnotes,
gymmane,
openGym,
@@ -27,9 +29,10 @@ extension ImportFormatX on ImportFormat {
}
class ParsedSet {
- ParsedSet(this.reps, this.weightKg);
+ ParsedSet(this.reps, this.weightKg, {this.rpe});
final int reps;
final double weightKg;
+ final double? rpe;
}
class ParsedWeight {
@@ -76,6 +79,7 @@ class _Fmt {
this.durationText,
this.durationSec,
this.setType,
+ this.warmupFlag,
});
final List<String> date;
@@ -90,6 +94,10 @@ class _Fmt {
final List<String>? durationText;
final List<String>? durationSec;
final List<String>? setType;
+ final List<String>? warmupFlag;
+ List<String> get rpe => const ['rpe'];
+ List<String> get rir => const ['rir'];
+ List<String> get effort => const ['rir/rpe', 'rpe/rir'];
}
const _formats = <ImportFormat, _Fmt>{
@@ -114,6 +122,25 @@ const _formats = <ImportFormat, _Fmt>{
durationText: ['duration'],
durationSec: ['duration (sec)', 'duration (seconds)'],
),
+ ImportFormat.lyfta: _Fmt(
+ date: ['date'],
+ group: ['title'],
+ exercise: ['exercise'],
+ reps: ['reps'],
+ weightKg: [],
+ weightLb: [],
+ weightPlain: ['weight'],
+ durationText: ['duration'],
+ setType: ['set type'],
+ ),
+ ImportFormat.fitbod: _Fmt(
+ date: ['date'],
+ exercise: ['exercise'],
+ reps: ['reps'],
+ weightKg: ['weight(kg)', 'weight (kg)'],
+ weightLb: ['weight(lbs)', 'weight(lb)', 'weight (lbs)'],
+ warmupFlag: ['iswarmup'],
+ ),
ImportFormat.fitnotes: _Fmt(
date: ['date'],
exercise: ['exercise'],
@@ -167,6 +194,15 @@ ImportFormat detectFormat(String csv) {
if (cols.isEmpty) return ImportFormat.unknown;
if (cols.contains('exercise_title') && cols.contains('start_time')) return ImportFormat.hevy;
if (cols.contains('exercise name') && cols.contains('set order')) return ImportFormat.strong;
+ if (cols.contains('exercise') &&
+ cols.contains('set type') &&
+ cols.contains('title') &&
+ (cols.contains('rir/rpe') || cols.any((c) => c.startsWith('recordlevel')))) {
+ return ImportFormat.lyfta;
+ }
+ if (cols.contains('exercise') && cols.contains('reps') && cols.contains('iswarmup')) {
+ return ImportFormat.fitbod;
+ }
if (cols.contains('weight_kg') && (cols.contains('est_1rm_kg') || cols.contains('volume_kg'))) {
return ImportFormat.gymmane;
}
@@ -301,7 +337,11 @@ ImportResult parseImport(String csv, {bool isLb = false}) {
for (final row in rows.skip(1)) {
final reps = int.tryParse(cell(row, fmt.reps)) ?? 0;
if (reps <= 0) continue;
- if (_norm(cell(row, fmt.setType)) == 'warmup') continue;
+ if (_norm(cell(row, fmt.setType)).startsWith('warmup') ||
+ _norm(cell(row, fmt.setType)).startsWith('warm_up') ||
+ _norm(cell(row, fmt.warmupFlag)) == 'true') {
+ continue;
+ }
final date = _parseDate(cell(row, fmt.date));
if (date == null) continue;
@@ -332,12 +372,24 @@ ImportResult parseImport(String csv, {bool isLb = false}) {
session.exercises.add(parsed);
return parsed;
});
- exercise.sets.add(ParsedSet(reps, kg));
+ exercise.sets.add(
+ ParsedSet(reps, kg, rpe: _effort(cell(row, fmt.rpe), cell(row, fmt.rir), cell(row, fmt.effort))));
}
return ImportResult(format, sessions.values.toList());
}
+double? _effort(String rpe, String rir, String either) {
+ double? read(String v) => double.tryParse(v.replaceAll(',', '.'));
+ final r = read(rpe);
+ if (r != null && r >= 1 && r <= 10) return r;
+ final left = read(rir);
+ if (left != null && left >= 0 && left <= 9) return 10 - left;
+ final mixed = read(either);
+ if (mixed == null || mixed < 0 || mixed > 10) return null;
+ return mixed >= 6 ? mixed : 10 - mixed;
+}
+
Map<String, dynamic>? _backupOf(String text) {
final head = text.trimLeft();
if (!head.startsWith('{')) return null;
@@ -458,6 +510,12 @@ String _delimiter(String csv) => (_firstLine(csv) ?? '').contains(';') ? ';' : '
int _parseDuration(String s) {
if (s.isEmpty) return 0;
+ final clock = RegExp(r'^(\d+):(\d{2})(?::(\d{2}))?$').firstMatch(s.trim());
+ if (clock != null) {
+ final a = int.parse(clock.group(1)!), b = int.parse(clock.group(2)!);
+ final c = clock.group(3);
+ return c == null ? a * 60 + b : a * 3600 + b * 60 + int.parse(c);
+ }
var seconds = 0;
final h = RegExp(r'(\d+)\s*h').firstMatch(s);
final m = RegExp(r'(\d+)\s*m').firstMatch(s);
diff --git a/lib/state/routines_state.dart b/lib/state/routines_state.dart
index d76243f..546952e 100644
--- a/lib/state/routines_state.dart
+++ b/lib/state/routines_state.dart
@@ -75,6 +75,14 @@ mixin RoutinesState on FitCore, LibraryState {
notifyListeners();
}
+ void setRoutineColor(String id, int color) {
+ final r = _routine(id);
+ if (r == null) return;
+ r.color = color;
+ _persist();
+ notifyListeners();
+ }
+
String duplicateRoutine(String id) {
final source = _routine(id);
if (source == null) return '';
@@ -82,7 +90,10 @@ mixin RoutinesState on FitCore, LibraryState {
final made = _routine(copy)!;
made.exerciseIds.addAll(source.exerciseIds);
made.sets.addAll(source.sets);
+ made.chained.addAll(source.chained);
+ made.plan.addAll({for (final e in source.plan.entries) e.key: [...e.value]});
made.group = source.group;
+ made.color = source.color;
_persist();
notifyListeners();
return copy;
@@ -101,6 +112,8 @@ mixin RoutinesState on FitCore, LibraryState {
if (r == null) return;
if (r.exerciseIds.remove(exId)) {
r.sets.remove(exId);
+ r.plan.remove(exId);
+ r.chained.remove(exId);
} else {
r.exerciseIds.add(exId);
}
@@ -108,7 +121,60 @@ mixin RoutinesState on FitCore, LibraryState {
notifyListeners();
}
- int routineSets(Routine r, String exId) => r.sets[exId] ?? kDefaultRoutineSets;
+ VoidCallback? removeRoutineExercise(String routineId, String exId) {
+ final r = _routine(routineId);
+ if (r == null) return null;
+ final at = r.exerciseIds.indexOf(exId);
+ if (at < 0) return null;
+ final sets = r.sets[exId];
+ final plan = r.plan[exId];
+ final chained = r.chained.contains(exId);
+ toggleRoutineExercise(routineId, exId);
+ return () {
+ final back = _routine(routineId);
+ if (back == null || back.exerciseIds.contains(exId)) return;
+ back.exerciseIds.insert(at.clamp(0, back.exerciseIds.length), exId);
+ if (sets != null) back.sets[exId] = sets;
+ if (plan != null) back.plan[exId] = plan;
+ if (chained) back.chained.add(exId);
+ _persist();
+ notifyListeners();
+ };
+ }
+
+ int routineSets(Routine r, String exId) {
+ final planned = r.plan[exId];
+ if (planned != null && planned.isNotEmpty) {
+ final working = planned.where((p) => p.kind != SetKind.warmup).length;
+ return working == 0 ? planned.length : working;
+ }
+ return r.sets[exId] ?? (modeOf(exId) == 'cardio' ? 1 : kDefaultRoutineSets);
+ }
+
+ List<PlannedSet> plannedSets(Routine r, String exId) => r.plan[exId] ?? const [];
+
+ void setRoutineSetCount(String routineId, String exId, int n) {
+ final r = _routine(routineId);
+ if (r == null || !r.exerciseIds.contains(exId)) return;
+ r.sets[exId] = n.clamp(1, 12);
+ _persist();
+ notifyListeners();
+ }
+
+ bool hasPlan(Routine r, String exId) => r.plan[exId]?.isNotEmpty ?? false;
+
+ void setPlannedSets(String routineId, String exId, List<PlannedSet> sets) {
+ final r = _routine(routineId);
+ if (r == null || !r.exerciseIds.contains(exId)) return;
+ if (sets.isEmpty) {
+ r.plan.remove(exId);
+ } else {
+ r.plan[exId] = List.unmodifiable(sets.take(20));
+ r.sets[exId] = sets.where((p) => p.kind != SetKind.warmup).length.clamp(1, 20);
+ }
+ _persist();
+ notifyListeners();
+ }
bool chainsToNext(Routine r, String exId) {
final i = r.exerciseIds.indexOf(exId);
@@ -126,6 +192,25 @@ mixin RoutinesState on FitCore, LibraryState {
void bumpRoutineSets(String routineId, String exId, int delta) {
final r = _routine(routineId);
if (r == null || !r.exerciseIds.contains(exId)) return;
+ final planned = r.plan[exId];
+ if (planned != null && planned.isNotEmpty) {
+ final next = [...planned];
+ if (delta > 0) {
+ for (var i = 0; i < delta && next.length < 20; i++) {
+ next.add(next
+ .lastWhere((s) => s.kind != SetKind.warmup, orElse: () => const PlannedSet())
+ .copyWith(kind: SetKind.normal));
+ }
+ } else {
+ for (var i = 0; i < -delta; i++) {
+ final last = next.lastIndexWhere((s) => s.kind != SetKind.warmup);
+ if (last < 0 || next.where((s) => s.kind != SetKind.warmup).length <= 1) break;
+ next.removeAt(last);
+ }
+ }
+ setPlannedSets(routineId, exId, next);
+ return;
+ }
r.sets[exId] = (routineSets(r, exId) + delta).clamp(1, 12);
_persist();
notifyListeners();
diff --git a/test/export_test.dart b/test/export_test.dart
index e3704d7..75d29ff 100644
--- a/test/export_test.dart
+++ b/test/export_test.dart
@@ -16,7 +16,8 @@ void main() {
]),
]);
final lines = csv.trim().split('\n');
- expect(lines.first, 'date,exercise,muscle,set,reps,weight_kg,volume_kg,est_1rm_kg');
+ expect(lines.first,
+ 'date,exercise,muscle,set,reps,weight_kg,volume_kg,est_1rm_kg,distance_km,duration_s,rpe');
expect(lines.length, 3);
expect(lines[1], startsWith('2026-07-14,Barbell Bench Press,chest,1,10,60,600,'));
expect(lines[2], contains(',2,8,70,560,'));
@@ -29,7 +30,7 @@ void main() {
final row = csv.trim().split('\n')[1];
expect(row, contains('"Chest Dip, Assisted"'));
- expect(row.replaceAll(RegExp('"[^"]*"'), 'X').split(',').length, 8);
+ expect(row.replaceAll(RegExp('"[^"]*"'), 'X').split(',').length, 11);
});
test('a name with quotes is escaped, not mangled', () {
@@ -47,6 +48,15 @@ void main() {
expect(csv, contains(',10,20,200,'));
});
+ test('cardio and timed sets carry their distance and time', () {
+ final csv = store.exportCsv([
+ _session(DateTime(2026, 9, 18), 'Outdoor Run', [LoggedSet(0, 0, sec: 1800, km: 5.25)]),
+ _session(DateTime(2026, 9, 18), 'Plank', [LoggedSet(0, 0, sec: 60)]),
+ ]);
+ expect(csv, contains(',0,0,0,0,5.25,1800'));
+ expect(csv, contains(',0,0,0,0,,60'));
+ });
+
test('rows come out oldest first regardless of input order', () {
final csv = store.exportCsv([
_session(DateTime(2026, 7, 16), 'B', [LoggedSet(1, 1)]),
@@ -59,6 +69,6 @@ void main() {
test('no sessions still yields a valid header-only file', () {
expect(store.exportCsv([]).trim(),
- 'date,exercise,muscle,set,reps,weight_kg,volume_kg,est_1rm_kg');
+ 'date,exercise,muscle,set,reps,weight_kg,volume_kg,est_1rm_kg,distance_km,duration_s,rpe');
});
}
diff --git a/test/import_test.dart b/test/import_test.dart
index c3dcd18..93462b5 100644
--- a/test/import_test.dart
+++ b/test/import_test.dart
@@ -257,4 +257,21 @@ void main() {
expect(logged.durationSec, 45 * 60);
});
});
+
+ group('Fitbod', () {
+ const csv = 'Date,Exercise,Reps,Weight(kg),Duration(s),Distance(m),Incline,Resistance,isWarmup,Note,multiplier\n'
+ '2024-03-04 18:02:11 +0000,Barbell Bench Press,10,40.0,0.0,0.0,0.0,0.0,true,,1.0\n'
+ '2024-03-04 18:02:11 +0000,Barbell Bench Press,8,60.0,0.0,0.0,0.0,0.0,false,,1.0\n'
+ '2024-03-04 18:02:11 +0000,Barbell Bench Press,8,62.5,0.0,0.0,0.0,0.0,false,,1.0\n'
+ '2024-03-06 18:10:00 +0000,Barbell Squat,5,100.0,0.0,0.0,0.0,0.0,false,,1.0\n';
+
+ test('detects the export and skips warm-ups', () {
+ expect(detectFormat(csv), ImportFormat.fitbod);
+ expect(needsUnitChoice(csv), isFalse);
+ final r = parseImport(csv);
+ expect(r.sessions.length, 2);
+ final bench = r.sessions.first.exercises.single;
+ expect(bench.sets.map((s) => s.weightKg), [60.0, 62.5]);
+ });
+ });
}