mirror of
https://github.com/jonasbark/swiftcontrol.git
synced 2026-12-05 04:57:32 +01:00
feat: open Past Workouts in a sheet and surface duration / distance
Persists the WorkoutSummary alongside each saved workout as a sidecar JSON file (workout-…fit.json) so the past-workouts list can render duration, distance, avg power, and avg HR per row without parsing the FIT. Reading is best-effort — older workouts without a sidecar fall back to the previous filename-only layout. Splits WorkoutsListPage into a Scaffold-wrapped page (kept for backwards compatibility / desktop nav) and a chrome-free WorkoutsList widget that the MiniWorkoutCard now mounts inside openSheet at the bottom edge. WorkoutsList renders a small header and the "open folder" shortcut when its showHeader flag is set so it stays self-contained inside the sheet. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
import 'package:bike_control/bluetooth/devices/proxy/proxy_device.dart';
|
||||
import 'package:bike_control/gen/l10n.dart';
|
||||
import 'package:bike_control/pages/workout/workout_summary_dialog.dart';
|
||||
import 'package:bike_control/pages/workout/workouts_list_page.dart';
|
||||
import 'package:bike_control/pages/workout/workouts_list_page.dart' show WorkoutsList;
|
||||
import 'package:bike_control/services/workout/fit_writer.dart';
|
||||
import 'package:bike_control/services/workout/trainer_metrics.dart';
|
||||
import 'package:bike_control/services/workout/workout_recorder.dart';
|
||||
@@ -57,7 +57,11 @@ class _MiniWorkoutCardState extends State<MiniWorkoutCard> {
|
||||
return;
|
||||
}
|
||||
final bytes = FitFileWriter.encode(samples: result.samples, summary: result.summary);
|
||||
final file = await core.workoutRepository.save(startedAt: result.startedAt, fitBytes: bytes);
|
||||
final file = await core.workoutRepository.save(
|
||||
startedAt: result.startedAt,
|
||||
fitBytes: bytes,
|
||||
summary: result.summary,
|
||||
);
|
||||
if (!mounted) return;
|
||||
await showWorkoutSummaryDialog(context: context, summary: result.summary, fitFile: file);
|
||||
}
|
||||
@@ -101,7 +105,7 @@ class _MiniWorkoutCardState extends State<MiniWorkoutCard> {
|
||||
if (state == WorkoutState.idle) {
|
||||
return Row(
|
||||
spacing: 8,
|
||||
mainAxisAlignment: MainAxisAlignment.spaceAround,
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
_gridTile(
|
||||
context: context,
|
||||
@@ -114,8 +118,14 @@ class _MiniWorkoutCardState extends State<MiniWorkoutCard> {
|
||||
context: context,
|
||||
icon: LucideIcons.list,
|
||||
label: l10n.miniWorkoutPastWorkouts,
|
||||
onTap: () => Navigator.of(context).push(
|
||||
MaterialPageRoute(builder: (_) => const WorkoutsListPage()),
|
||||
onTap: () => openSheet(
|
||||
context: context,
|
||||
draggable: true,
|
||||
position: OverlayPosition.bottom,
|
||||
builder: (_) => const Padding(
|
||||
padding: EdgeInsets.fromLTRB(16, 12, 16, 24),
|
||||
child: WorkoutsList(showHeader: true),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
@@ -2,34 +2,19 @@ import 'dart:io';
|
||||
|
||||
import 'package:bike_control/gen/l10n.dart';
|
||||
import 'package:bike_control/services/workout/past_workout.dart';
|
||||
import 'package:bike_control/services/workout/workout_summary.dart';
|
||||
import 'package:bike_control/utils/core.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:share_plus/share_plus.dart';
|
||||
import 'package:shadcn_flutter/shadcn_flutter.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
class WorkoutsListPage extends StatefulWidget {
|
||||
/// Full-page wrapper around [WorkoutsList] for the Navigator stack. The same
|
||||
/// list is rendered inside a sheet via [WorkoutsList] without the Scaffold
|
||||
/// chrome — see `MiniWorkoutCard.openSheet(...)`.
|
||||
class WorkoutsListPage extends StatelessWidget {
|
||||
const WorkoutsListPage({super.key});
|
||||
|
||||
@override
|
||||
State<WorkoutsListPage> createState() => _WorkoutsListPageState();
|
||||
}
|
||||
|
||||
class _WorkoutsListPageState extends State<WorkoutsListPage> {
|
||||
late Future<List<PastWorkout>> _future;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_future = core.workoutRepository.list();
|
||||
}
|
||||
|
||||
void _refresh() {
|
||||
setState(() {
|
||||
_future = core.workoutRepository.list();
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context);
|
||||
@@ -57,33 +42,97 @@ class _WorkoutsListPageState extends State<WorkoutsListPage> {
|
||||
),
|
||||
const Divider(),
|
||||
],
|
||||
child: FutureBuilder<List<PastWorkout>>(
|
||||
future: _future,
|
||||
builder: (context, snapshot) {
|
||||
if (!snapshot.hasData) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
final items = snapshot.data!;
|
||||
if (items.isEmpty) {
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Text(l10n.miniWorkoutNoPastWorkouts),
|
||||
child: const WorkoutsList(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reusable list of past workouts. Renders just the list contents (no
|
||||
/// Scaffold) so it fits inside a sheet, drawer, or full-page Scaffold.
|
||||
class WorkoutsList extends StatefulWidget {
|
||||
/// When true, prepends a small header with the localized title and an
|
||||
/// "open folder" action — meant for sheet/drawer usage where there's no
|
||||
/// surrounding AppBar.
|
||||
final bool showHeader;
|
||||
const WorkoutsList({super.key, this.showHeader = false});
|
||||
|
||||
@override
|
||||
State<WorkoutsList> createState() => _WorkoutsListState();
|
||||
}
|
||||
|
||||
class _WorkoutsListState extends State<WorkoutsList> {
|
||||
late Future<List<PastWorkout>> _future;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_future = core.workoutRepository.list();
|
||||
}
|
||||
|
||||
void _refresh() {
|
||||
setState(() {
|
||||
_future = core.workoutRepository.list();
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context);
|
||||
return FutureBuilder<List<PastWorkout>>(
|
||||
future: _future,
|
||||
builder: (context, snapshot) {
|
||||
if (!snapshot.hasData) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
final items = snapshot.data!;
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (widget.showHeader)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(left: 4, right: 4, bottom: 8),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
l10n.miniWorkoutPastWorkouts,
|
||||
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
|
||||
),
|
||||
),
|
||||
if (!kIsWeb && (Platform.isMacOS || Platform.isWindows || Platform.isLinux))
|
||||
IconButton.ghost(
|
||||
icon: const Icon(LucideIcons.folder, size: 18),
|
||||
onPressed: () async {
|
||||
final dir = await core.workoutRepository.rootDirectory();
|
||||
await launchUrl(Uri.file(dir.path));
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
return ListView.separated(
|
||||
padding: const EdgeInsets.all(12),
|
||||
itemCount: items.length,
|
||||
separatorBuilder: (_, _) => const Divider(thickness: 0.5),
|
||||
itemBuilder: (context, i) => _row(items[i], l10n),
|
||||
);
|
||||
},
|
||||
),
|
||||
if (items.isEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Center(child: Text(l10n.miniWorkoutNoPastWorkouts)),
|
||||
)
|
||||
else
|
||||
ListView.separated(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
itemCount: items.length,
|
||||
separatorBuilder: (_, _) => const Divider(thickness: 0.5),
|
||||
itemBuilder: (context, i) => _row(items[i], l10n),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _row(PastWorkout w, AppLocalizations l10n) {
|
||||
final cs = Theme.of(context).colorScheme;
|
||||
final summary = w.summary;
|
||||
return Button.ghost(
|
||||
onPressed: () {}, // row tap reserved for future detail view
|
||||
child: Row(
|
||||
@@ -94,7 +143,14 @@ class _WorkoutsListPageState extends State<WorkoutsListPage> {
|
||||
spacing: 4,
|
||||
children: [
|
||||
Text(_fmtDate(w.startedAt), style: const TextStyle(fontWeight: FontWeight.w600)),
|
||||
Text(w.fileName, style: const TextStyle(fontSize: 11)),
|
||||
if (summary != null)
|
||||
Wrap(
|
||||
spacing: 12,
|
||||
runSpacing: 4,
|
||||
children: _summaryChips(summary, cs),
|
||||
)
|
||||
else
|
||||
Text(w.fileName, style: TextStyle(fontSize: 11, color: cs.mutedForeground)),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -111,6 +167,24 @@ class _WorkoutsListPageState extends State<WorkoutsListPage> {
|
||||
);
|
||||
}
|
||||
|
||||
List<Widget> _summaryChips(WorkoutSummary s, ColorScheme cs) {
|
||||
Widget chip(IconData icon, String label) => Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(icon, size: 11, color: cs.mutedForeground),
|
||||
const Gap(4),
|
||||
Text(label, style: TextStyle(fontSize: 11, color: cs.mutedForeground)),
|
||||
],
|
||||
);
|
||||
|
||||
return [
|
||||
chip(LucideIcons.clock, _fmtDuration(s.activeDuration)),
|
||||
if (s.distanceKm > 0) chip(LucideIcons.gauge, '${s.distanceKm.toStringAsFixed(1)} km'),
|
||||
if (s.avgPowerW > 0) chip(LucideIcons.zap, '${s.avgPowerW} W'),
|
||||
if (s.avgHeartRateBpm > 0) chip(LucideIcons.heart, '${s.avgHeartRateBpm} bpm'),
|
||||
];
|
||||
}
|
||||
|
||||
Future<void> _confirmDelete(PastWorkout w, AppLocalizations l10n) async {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
@@ -142,4 +216,12 @@ class _WorkoutsListPageState extends State<WorkoutsListPage> {
|
||||
String two(int v) => v.toString().padLeft(2, '0');
|
||||
return '${local.year}-${two(local.month)}-${two(local.day)} ${two(local.hour)}:${two(local.minute)}';
|
||||
}
|
||||
|
||||
static String _fmtDuration(Duration d) {
|
||||
String two(int v) => v.toString().padLeft(2, '0');
|
||||
final h = d.inHours;
|
||||
final m = d.inMinutes.remainder(60);
|
||||
final s = d.inSeconds.remainder(60);
|
||||
return h > 0 ? '$h:${two(m)}:${two(s)}' : '${two(m)}:${two(s)}';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,23 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'workout_summary.dart';
|
||||
|
||||
/// Listing-row view of a `.fit` file on disk. Fields are derived from the
|
||||
/// filename (startedAt) plus `stat()` (sizeBytes) — we don't parse FIT here
|
||||
/// to keep the list fast. Open-on-tap can do a full parse.
|
||||
/// to keep the list fast. [summary] is hydrated from a sidecar JSON written
|
||||
/// alongside the FIT at save time; older workouts without a sidecar leave
|
||||
/// it null.
|
||||
class PastWorkout {
|
||||
final File file;
|
||||
final DateTime startedAt;
|
||||
final int sizeBytes;
|
||||
final WorkoutSummary? summary;
|
||||
|
||||
const PastWorkout({
|
||||
required this.file,
|
||||
required this.startedAt,
|
||||
required this.sizeBytes,
|
||||
this.summary,
|
||||
});
|
||||
|
||||
String get fileName => file.path.split(Platform.pathSeparator).last;
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
import 'past_workout.dart';
|
||||
import 'workout_summary.dart';
|
||||
|
||||
class WorkoutRepository {
|
||||
final Directory? _rootOverride;
|
||||
@@ -22,11 +24,18 @@ class WorkoutRepository {
|
||||
return dir;
|
||||
}
|
||||
|
||||
Future<File> save({required DateTime startedAt, required List<int> fitBytes}) async {
|
||||
Future<File> save({
|
||||
required DateTime startedAt,
|
||||
required List<int> fitBytes,
|
||||
WorkoutSummary? summary,
|
||||
}) async {
|
||||
final dir = await rootDirectory();
|
||||
final name = _filenameFor(startedAt);
|
||||
final file = File('${dir.path}${Platform.pathSeparator}$name');
|
||||
await file.writeAsBytes(fitBytes, flush: true);
|
||||
if (summary != null) {
|
||||
await _sidecarFor(file).writeAsString(jsonEncode(summary.toJson()), flush: true);
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
@@ -40,7 +49,12 @@ class WorkoutRepository {
|
||||
final parsed = _parseFilename(e.path);
|
||||
if (parsed == null) continue;
|
||||
final stat = await e.stat();
|
||||
workouts.add(PastWorkout(file: e, startedAt: parsed, sizeBytes: stat.size));
|
||||
workouts.add(PastWorkout(
|
||||
file: e,
|
||||
startedAt: parsed,
|
||||
sizeBytes: stat.size,
|
||||
summary: await _readSidecar(e),
|
||||
));
|
||||
}
|
||||
workouts.sort((a, b) => b.startedAt.compareTo(a.startedAt));
|
||||
return workouts;
|
||||
@@ -48,6 +62,22 @@ class WorkoutRepository {
|
||||
|
||||
Future<void> delete(File file) async {
|
||||
if (await file.exists()) await file.delete();
|
||||
final sidecar = _sidecarFor(file);
|
||||
if (await sidecar.exists()) await sidecar.delete();
|
||||
}
|
||||
|
||||
File _sidecarFor(File fit) => File('${fit.path}.json');
|
||||
|
||||
Future<WorkoutSummary?> _readSidecar(File fit) async {
|
||||
final sidecar = _sidecarFor(fit);
|
||||
if (!await sidecar.exists()) return null;
|
||||
try {
|
||||
final raw = await sidecar.readAsString();
|
||||
final json = jsonDecode(raw) as Map<String, Object?>;
|
||||
return WorkoutSummary.fromJson(json);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
String _filenameFor(DateTime when) {
|
||||
|
||||
@@ -27,6 +27,32 @@ class WorkoutSummary {
|
||||
required this.sampleCount,
|
||||
});
|
||||
|
||||
Map<String, Object?> toJson() => {
|
||||
'startedAt': startedAt.toUtc().toIso8601String(),
|
||||
'activeDurationSeconds': activeDuration.inSeconds,
|
||||
'avgPowerW': avgPowerW,
|
||||
'maxPowerW': maxPowerW,
|
||||
'avgCadenceRpm': avgCadenceRpm,
|
||||
'avgSpeedKph': avgSpeedKph,
|
||||
'distanceKm': distanceKm,
|
||||
'avgHeartRateBpm': avgHeartRateBpm,
|
||||
'maxHeartRateBpm': maxHeartRateBpm,
|
||||
'sampleCount': sampleCount,
|
||||
};
|
||||
|
||||
factory WorkoutSummary.fromJson(Map<String, Object?> j) => WorkoutSummary(
|
||||
startedAt: DateTime.parse(j['startedAt'] as String),
|
||||
activeDuration: Duration(seconds: (j['activeDurationSeconds'] as num).toInt()),
|
||||
avgPowerW: (j['avgPowerW'] as num).toInt(),
|
||||
maxPowerW: (j['maxPowerW'] as num).toInt(),
|
||||
avgCadenceRpm: (j['avgCadenceRpm'] as num).toInt(),
|
||||
avgSpeedKph: (j['avgSpeedKph'] as num).toDouble(),
|
||||
distanceKm: (j['distanceKm'] as num).toDouble(),
|
||||
avgHeartRateBpm: (j['avgHeartRateBpm'] as num).toInt(),
|
||||
maxHeartRateBpm: (j['maxHeartRateBpm'] as num).toInt(),
|
||||
sampleCount: (j['sampleCount'] as num).toInt(),
|
||||
);
|
||||
|
||||
factory WorkoutSummary.fromSamples(
|
||||
List<WorkoutSample> samples, {
|
||||
required DateTime startedAt,
|
||||
|
||||
Reference in New Issue
Block a user