feat(watch): Wear OS companion app - UX surfaces + bridge client (#91-E, #91-F)
This commit is contained in:
285
watch_app/lib/application/watch_session_view_model.dart
Normal file
285
watch_app/lib/application/watch_session_view_model.dart
Normal file
@ -0,0 +1,285 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:watch_bridge_contract/watch_bridge_contract.dart';
|
||||
|
||||
import '../infrastructure/watch_bridge/native_watch_bridge_client.dart';
|
||||
|
||||
final class WatchSessionUiState {
|
||||
const WatchSessionUiState({
|
||||
required this.projection,
|
||||
this.commandPending = false,
|
||||
this.waitingForPhone = false,
|
||||
this.connectionLost = false,
|
||||
this.staleProjection = false,
|
||||
this.lastAck,
|
||||
});
|
||||
|
||||
final WatchSessionProjection projection;
|
||||
final bool commandPending;
|
||||
final bool waitingForPhone;
|
||||
final bool connectionLost;
|
||||
final bool staleProjection;
|
||||
final WatchCommandAckEvent? lastAck;
|
||||
|
||||
bool get actionsEnabled => !commandPending && !connectionLost;
|
||||
|
||||
WatchSessionUiState copyWith({
|
||||
WatchSessionProjection? projection,
|
||||
bool? commandPending,
|
||||
bool? waitingForPhone,
|
||||
bool? connectionLost,
|
||||
bool? staleProjection,
|
||||
WatchCommandAckEvent? lastAck,
|
||||
}) {
|
||||
return WatchSessionUiState(
|
||||
projection: projection ?? this.projection,
|
||||
commandPending: commandPending ?? this.commandPending,
|
||||
waitingForPhone: waitingForPhone ?? this.waitingForPhone,
|
||||
connectionLost: connectionLost ?? this.connectionLost,
|
||||
staleProjection: staleProjection ?? this.staleProjection,
|
||||
lastAck: lastAck ?? this.lastAck,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
final class WatchSessionViewModel extends ValueNotifier<WatchSessionUiState> {
|
||||
WatchSessionViewModel({
|
||||
NativeWatchBridgeClient nativeClient =
|
||||
const MethodChannelNativeWatchBridgeClient(),
|
||||
Duration waitingThreshold = const Duration(milliseconds: 500),
|
||||
Duration commandTimeout = const Duration(seconds: 2),
|
||||
Duration staleProjectionThreshold = const Duration(seconds: 6),
|
||||
Duration connectionLostThreshold = const Duration(seconds: 10),
|
||||
}) : _nativeClient = nativeClient,
|
||||
_waitingThreshold = waitingThreshold,
|
||||
_commandTimeout = commandTimeout,
|
||||
_staleProjectionThreshold = staleProjectionThreshold,
|
||||
_connectionLostThreshold = connectionLostThreshold,
|
||||
super(WatchSessionUiState(projection: _initialProjection())) {
|
||||
_subscriptions.add(_nativeClient.projections.listen(_handleProjection));
|
||||
_subscriptions.add(_nativeClient.acks.listen(_handleAck));
|
||||
_subscriptions.add(
|
||||
_nativeClient.connectionEvents.listen(_handleConnectionEvent),
|
||||
);
|
||||
unawaited(_nativeClient.requestCapabilityRefresh());
|
||||
unawaited(_nativeClient.requestResync());
|
||||
_freshnessTimer = Timer.periodic(const Duration(seconds: 1), (_) {
|
||||
_syncFreshnessState();
|
||||
});
|
||||
}
|
||||
|
||||
final NativeWatchBridgeClient _nativeClient;
|
||||
final Duration _waitingThreshold;
|
||||
final Duration _commandTimeout;
|
||||
final Duration _staleProjectionThreshold;
|
||||
final Duration _connectionLostThreshold;
|
||||
final _subscriptions = <StreamSubscription<dynamic>>[];
|
||||
|
||||
Timer? _waitingTimer;
|
||||
Timer? _commandTimeoutTimer;
|
||||
Timer? _freshnessTimer;
|
||||
WatchCommandEnvelope? _pendingCommand;
|
||||
DateTime? _lastProjectionReceivedAt;
|
||||
var _commandCounter = 0;
|
||||
|
||||
Future<void> refresh() async {
|
||||
value = value.copyWith(connectionLost: false);
|
||||
try {
|
||||
await _nativeClient.requestCapabilityRefresh();
|
||||
await _nativeClient.requestResync();
|
||||
} on PlatformException {
|
||||
value = value.copyWith(connectionLost: true);
|
||||
unawaited(HapticFeedback.heavyImpact());
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> sendPrimaryAction() async {
|
||||
final action = value.projection.primaryAction;
|
||||
final command = switch (action) {
|
||||
WatchPrimaryAction.none => null,
|
||||
WatchPrimaryAction.startCurrentExercise =>
|
||||
WatchCommandType.startCurrentExercise,
|
||||
WatchPrimaryAction.pauseSession => WatchCommandType.pauseSession,
|
||||
WatchPrimaryAction.resumeSession => WatchCommandType.resumeSession,
|
||||
WatchPrimaryAction.startPreparedTimedStep =>
|
||||
WatchCommandType.startPreparedTimedStep,
|
||||
WatchPrimaryAction.skipCurrentRest => WatchCommandType.skipCurrentRest,
|
||||
};
|
||||
if (command == null) {
|
||||
await refresh();
|
||||
return;
|
||||
}
|
||||
await _sendCommand(command);
|
||||
}
|
||||
|
||||
Future<void> sendSecondaryAction(WatchSecondaryAction action) {
|
||||
final command = switch (action) {
|
||||
WatchSecondaryAction.skipCurrentStep => WatchCommandType.skipCurrentStep,
|
||||
WatchSecondaryAction.skipCurrentPassage =>
|
||||
WatchCommandType.skipCurrentPassage,
|
||||
WatchSecondaryAction.finishCurrentSet => WatchCommandType.finishCurrentSet,
|
||||
WatchSecondaryAction.skipCurrentSet => WatchCommandType.skipCurrentSet,
|
||||
WatchSecondaryAction.skipCurrentRest => WatchCommandType.skipCurrentRest,
|
||||
};
|
||||
return _sendCommand(command);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_waitingTimer?.cancel();
|
||||
_commandTimeoutTimer?.cancel();
|
||||
_freshnessTimer?.cancel();
|
||||
for (final subscription in _subscriptions) {
|
||||
unawaited(subscription.cancel());
|
||||
}
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _sendCommand(WatchCommandType type) async {
|
||||
if (!value.actionsEnabled || value.projection.deviceSessionId.isEmpty) {
|
||||
return;
|
||||
}
|
||||
final nowMs = DateTime.now().toUtc().millisecondsSinceEpoch;
|
||||
final command = WatchCommandEnvelope(
|
||||
commandId: 'watch-$nowMs-${_commandCounter++}',
|
||||
type: type,
|
||||
sessionId: value.projection.deviceSessionId,
|
||||
expectedRevision: value.projection.revision,
|
||||
sentAtEpochMs: nowMs,
|
||||
);
|
||||
_pendingCommand = command;
|
||||
value = value.copyWith(
|
||||
commandPending: true,
|
||||
waitingForPhone: false,
|
||||
connectionLost: false,
|
||||
);
|
||||
_waitingTimer?.cancel();
|
||||
_commandTimeoutTimer?.cancel();
|
||||
_waitingTimer = Timer(_waitingThreshold, () {
|
||||
value = value.copyWith(waitingForPhone: true);
|
||||
});
|
||||
_commandTimeoutTimer = Timer(_commandTimeout, () {
|
||||
_pendingCommand = null;
|
||||
value = value.copyWith(
|
||||
commandPending: false,
|
||||
waitingForPhone: false,
|
||||
connectionLost: true,
|
||||
);
|
||||
unawaited(HapticFeedback.heavyImpact());
|
||||
});
|
||||
try {
|
||||
await _nativeClient.sendCommand(command);
|
||||
} on PlatformException {
|
||||
_pendingCommand = null;
|
||||
_clearCommandTimers();
|
||||
value = value.copyWith(
|
||||
commandPending: false,
|
||||
waitingForPhone: false,
|
||||
connectionLost: true,
|
||||
);
|
||||
unawaited(HapticFeedback.heavyImpact());
|
||||
}
|
||||
}
|
||||
|
||||
void _handleProjection(WatchSessionProjection projection) {
|
||||
final previousProjection = value.projection;
|
||||
_lastProjectionReceivedAt = DateTime.now();
|
||||
_pendingCommand = null;
|
||||
_clearCommandTimers();
|
||||
value = WatchSessionUiState(
|
||||
projection: projection,
|
||||
lastAck: value.lastAck,
|
||||
);
|
||||
_triggerProjectionHaptic(previousProjection, projection);
|
||||
}
|
||||
|
||||
void _handleAck(WatchCommandAckEvent ack) {
|
||||
if (_pendingCommand?.commandId != ack.commandId) {
|
||||
value = value.copyWith(lastAck: ack);
|
||||
return;
|
||||
}
|
||||
_waitingTimer?.cancel();
|
||||
value = value.copyWith(
|
||||
waitingForPhone: false,
|
||||
connectionLost: false,
|
||||
lastAck: ack,
|
||||
);
|
||||
unawaited(HapticFeedback.lightImpact());
|
||||
if (_isRejected(ack.status)) {
|
||||
_pendingCommand = null;
|
||||
_clearCommandTimers();
|
||||
value = value.copyWith(commandPending: false);
|
||||
unawaited(_nativeClient.requestResync());
|
||||
}
|
||||
}
|
||||
|
||||
void _handleConnectionEvent(WatchBridgeConnectionEvent event) {
|
||||
value = value.copyWith(connectionLost: !event.isReachable);
|
||||
if (event.isReachable || event.requestsResync) {
|
||||
unawaited(_nativeClient.requestResync());
|
||||
}
|
||||
}
|
||||
|
||||
void _syncFreshnessState() {
|
||||
final receivedAt = _lastProjectionReceivedAt;
|
||||
if (receivedAt == null) {
|
||||
return;
|
||||
}
|
||||
final age = DateTime.now().difference(receivedAt);
|
||||
final stale = age >= _staleProjectionThreshold;
|
||||
final lost = age >= _connectionLostThreshold;
|
||||
if (stale != value.staleProjection || lost != value.connectionLost) {
|
||||
value = value.copyWith(staleProjection: stale, connectionLost: lost);
|
||||
}
|
||||
}
|
||||
|
||||
void _clearCommandTimers() {
|
||||
_waitingTimer?.cancel();
|
||||
_waitingTimer = null;
|
||||
_commandTimeoutTimer?.cancel();
|
||||
_commandTimeoutTimer = null;
|
||||
}
|
||||
|
||||
void _triggerProjectionHaptic(
|
||||
WatchSessionProjection previous,
|
||||
WatchSessionProjection current,
|
||||
) {
|
||||
final phaseChanged = previous.phase != current.phase;
|
||||
final enteredReadyTimer = current.phase == WatchSessionPhase.nextTimerReady &&
|
||||
previous.phase != WatchSessionPhase.nextTimerReady;
|
||||
final enteredRestEnd =
|
||||
previous.phase == WatchSessionPhase.restRunning &&
|
||||
current.phase != WatchSessionPhase.restRunning &&
|
||||
current.phase != WatchSessionPhase.restPaused;
|
||||
if (phaseChanged && (enteredReadyTimer || enteredRestEnd)) {
|
||||
unawaited(HapticFeedback.mediumImpact());
|
||||
unawaited(Future<void>.delayed(const Duration(milliseconds: 120), () {
|
||||
return HapticFeedback.mediumImpact();
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool _isRejected(WatchCommandAck ack) {
|
||||
return switch (ack) {
|
||||
WatchCommandAck.accepted || WatchCommandAck.acceptedNoOp => false,
|
||||
_ => true,
|
||||
};
|
||||
}
|
||||
|
||||
WatchSessionProjection _initialProjection() {
|
||||
return WatchSessionProjection(
|
||||
deviceSessionId: '',
|
||||
revision: 0,
|
||||
projectedAtEpochMs: DateTime.now().toUtc().millisecondsSinceEpoch,
|
||||
phase: WatchSessionPhase.noActiveSession,
|
||||
phoneReachable: false,
|
||||
seriesIndex: 0,
|
||||
seriesTotal: 0,
|
||||
exerciseName: '',
|
||||
primaryAction: WatchPrimaryAction.none,
|
||||
statusLabel: 'Téléphone indisponible',
|
||||
);
|
||||
}
|
||||
@ -0,0 +1,159 @@
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:watch_bridge_contract/watch_bridge_contract.dart';
|
||||
|
||||
final class WatchBridgeConnectionEvent {
|
||||
const WatchBridgeConnectionEvent({
|
||||
required this.isReachable,
|
||||
this.requestsResync = false,
|
||||
});
|
||||
|
||||
final bool isReachable;
|
||||
final bool requestsResync;
|
||||
}
|
||||
|
||||
final class WatchCommandAckEvent {
|
||||
const WatchCommandAckEvent({
|
||||
required this.commandId,
|
||||
required this.status,
|
||||
required this.sessionId,
|
||||
this.revisionAtAck,
|
||||
this.reasonCode,
|
||||
});
|
||||
|
||||
final String commandId;
|
||||
final WatchCommandAck status;
|
||||
final String sessionId;
|
||||
final int? revisionAtAck;
|
||||
final String? reasonCode;
|
||||
}
|
||||
|
||||
abstract interface class NativeWatchBridgeClient {
|
||||
Stream<WatchSessionProjection> get projections;
|
||||
|
||||
Stream<WatchCommandAckEvent> get acks;
|
||||
|
||||
Stream<WatchBridgeConnectionEvent> get connectionEvents;
|
||||
|
||||
Future<void> sendCommand(WatchCommandEnvelope command);
|
||||
|
||||
Future<void> requestResync();
|
||||
|
||||
Future<void> requestCapabilityRefresh();
|
||||
}
|
||||
|
||||
final class MethodChannelNativeWatchBridgeClient
|
||||
implements NativeWatchBridgeClient {
|
||||
const MethodChannelNativeWatchBridgeClient({
|
||||
MethodChannel methodChannel = const MethodChannel(_methodChannelName),
|
||||
EventChannel projectionChannel = const EventChannel(
|
||||
_projectionChannelName,
|
||||
),
|
||||
EventChannel ackChannel = const EventChannel(_ackChannelName),
|
||||
EventChannel connectionChannel = const EventChannel(
|
||||
_connectionChannelName,
|
||||
),
|
||||
}) : _methodChannel = methodChannel,
|
||||
_projectionChannel = projectionChannel,
|
||||
_ackChannel = ackChannel,
|
||||
_connectionChannel = connectionChannel;
|
||||
|
||||
static const _methodChannelName = 'gametime.watch_bridge/methods';
|
||||
static const _projectionChannelName = 'gametime.watch_bridge/projections';
|
||||
static const _ackChannelName = 'gametime.watch_bridge/acks';
|
||||
static const _connectionChannelName = 'gametime.watch_bridge/connection';
|
||||
|
||||
final MethodChannel _methodChannel;
|
||||
final EventChannel _projectionChannel;
|
||||
final EventChannel _ackChannel;
|
||||
final EventChannel _connectionChannel;
|
||||
|
||||
@override
|
||||
Stream<WatchSessionProjection> get projections {
|
||||
return _projectionChannel
|
||||
.receiveBroadcastStream()
|
||||
.where((event) => event is Map)
|
||||
.map((event) {
|
||||
return WatchSessionProjection.fromJson(_stringObjectMap(event));
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Stream<WatchCommandAckEvent> get acks {
|
||||
return _ackChannel
|
||||
.receiveBroadcastStream()
|
||||
.where((event) => event is Map)
|
||||
.map((event) {
|
||||
final json = _stringObjectMap(event);
|
||||
return WatchCommandAckEvent(
|
||||
commandId: _stringFromJson(json['commandId']),
|
||||
status: _enumFromJson(
|
||||
json['status'],
|
||||
WatchCommandAck.values,
|
||||
WatchCommandAck.rejectedPhoneBusy,
|
||||
),
|
||||
sessionId: _stringFromJson(json['sessionId']),
|
||||
revisionAtAck: _nullableIntFromJson(json['revisionAtAck']),
|
||||
reasonCode: _nullableStringFromJson(json['reasonCode']),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Stream<WatchBridgeConnectionEvent> get connectionEvents {
|
||||
return _connectionChannel
|
||||
.receiveBroadcastStream()
|
||||
.where((event) => event is Map)
|
||||
.map((event) {
|
||||
final json = _stringObjectMap(event);
|
||||
return WatchBridgeConnectionEvent(
|
||||
isReachable: json['isReachable'] == true,
|
||||
requestsResync: json['requestsResync'] == true,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> sendCommand(WatchCommandEnvelope command) {
|
||||
return _methodChannel.invokeMethod<void>('sendCommand', command.toJson());
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> requestCapabilityRefresh() {
|
||||
return _methodChannel.invokeMethod<void>('requestCapabilityRefresh');
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> requestResync() {
|
||||
return _methodChannel.invokeMethod<void>('requestResync');
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, Object?> _stringObjectMap(Object? value) {
|
||||
if (value is Map) {
|
||||
return value.map((key, value) => MapEntry(key.toString(), value));
|
||||
}
|
||||
return const {};
|
||||
}
|
||||
|
||||
String _stringFromJson(Object? value) {
|
||||
return value is String ? value : '';
|
||||
}
|
||||
|
||||
String? _nullableStringFromJson(Object? value) {
|
||||
return value is String ? value : null;
|
||||
}
|
||||
|
||||
int? _nullableIntFromJson(Object? value) {
|
||||
return value is int ? value : value is num ? value.toInt() : null;
|
||||
}
|
||||
|
||||
T _enumFromJson<T extends Enum>(Object? value, List<T> values, T fallback) {
|
||||
if (value is String) {
|
||||
for (final enumValue in values) {
|
||||
if (enumValue.name == value) {
|
||||
return enumValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
7
watch_app/lib/main.dart
Normal file
7
watch_app/lib/main.dart
Normal file
@ -0,0 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'presentation/watch_session_app.dart';
|
||||
|
||||
void main() {
|
||||
runApp(const WatchSessionApp());
|
||||
}
|
||||
38
watch_app/lib/presentation/watch_session_app.dart
Normal file
38
watch_app/lib/presentation/watch_session_app.dart
Normal file
@ -0,0 +1,38 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../application/watch_session_view_model.dart';
|
||||
import 'watch_session_screen.dart';
|
||||
import 'watch_theme.dart';
|
||||
|
||||
final class WatchSessionApp extends StatefulWidget {
|
||||
const WatchSessionApp({super.key});
|
||||
|
||||
@override
|
||||
State<WatchSessionApp> createState() => _WatchSessionAppState();
|
||||
}
|
||||
|
||||
final class _WatchSessionAppState extends State<WatchSessionApp> {
|
||||
late final WatchSessionViewModel _viewModel;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_viewModel = WatchSessionViewModel();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_viewModel.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp(
|
||||
debugShowCheckedModeBanner: false,
|
||||
title: 'GameTime',
|
||||
theme: watchTheme(),
|
||||
home: WatchSessionScreen(viewModel: _viewModel),
|
||||
);
|
||||
}
|
||||
}
|
||||
549
watch_app/lib/presentation/watch_session_screen.dart
Normal file
549
watch_app/lib/presentation/watch_session_screen.dart
Normal file
@ -0,0 +1,549 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:watch_bridge_contract/watch_bridge_contract.dart';
|
||||
|
||||
import '../application/watch_session_view_model.dart';
|
||||
|
||||
final class WatchSessionScreen extends StatefulWidget {
|
||||
const WatchSessionScreen({required this.viewModel, super.key});
|
||||
|
||||
final WatchSessionViewModel viewModel;
|
||||
|
||||
@override
|
||||
State<WatchSessionScreen> createState() => _WatchSessionScreenState();
|
||||
}
|
||||
|
||||
final class _WatchSessionScreenState extends State<WatchSessionScreen> {
|
||||
late final PageController _pageController;
|
||||
Timer? _ticker;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_pageController = PageController();
|
||||
_ticker = Timer.periodic(const Duration(seconds: 1), (_) {
|
||||
if (mounted) {
|
||||
setState(() {});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_ticker?.cancel();
|
||||
_pageController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ValueListenableBuilder<WatchSessionUiState>(
|
||||
valueListenable: widget.viewModel,
|
||||
builder: (context, state, _) {
|
||||
final projection = state.projection;
|
||||
if (projection.phase == WatchSessionPhase.noActiveSession) {
|
||||
return _RoundScaffold(
|
||||
child: _NoSessionView(
|
||||
projection: projection,
|
||||
pending: state.commandPending,
|
||||
onRefresh: widget.viewModel.refresh,
|
||||
),
|
||||
);
|
||||
}
|
||||
return PageView(
|
||||
controller: _pageController,
|
||||
children: [
|
||||
_RoundScaffold(
|
||||
child: _SessionMainView(
|
||||
state: state,
|
||||
onPrimary: widget.viewModel.sendPrimaryAction,
|
||||
onRetry: widget.viewModel.refresh,
|
||||
onActions: _showActions,
|
||||
),
|
||||
),
|
||||
_RoundScaffold(
|
||||
child: _ActionsView(
|
||||
state: state,
|
||||
onAction: _handleSecondaryAction,
|
||||
onSession: _showSession,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
void _showActions() {
|
||||
_pageController.animateToPage(
|
||||
1,
|
||||
duration: const Duration(milliseconds: 180),
|
||||
curve: Curves.easeOut,
|
||||
);
|
||||
}
|
||||
|
||||
void _showSession() {
|
||||
_pageController.animateToPage(
|
||||
0,
|
||||
duration: const Duration(milliseconds: 180),
|
||||
curve: Curves.easeOut,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _handleSecondaryAction(WatchSecondaryAction action) async {
|
||||
final confirmed = switch (action) {
|
||||
WatchSecondaryAction.skipCurrentPassage => await _confirm(
|
||||
title: 'Passer le passage ?',
|
||||
message: "L'étape en cours sera ignorée.",
|
||||
confirmLabel: 'Passer',
|
||||
),
|
||||
WatchSecondaryAction.skipCurrentSet => await _confirm(
|
||||
title: 'Passer la série ?',
|
||||
message: 'Le chrono en cours sera ignoré.',
|
||||
confirmLabel: 'Passer',
|
||||
),
|
||||
_ => true,
|
||||
};
|
||||
if (confirmed && mounted) {
|
||||
unawaited(widget.viewModel.sendSecondaryAction(action));
|
||||
_showSession();
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> _confirm({
|
||||
required String title,
|
||||
required String message,
|
||||
required String confirmLabel,
|
||||
}) async {
|
||||
final result = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) {
|
||||
return AlertDialog(
|
||||
title: Text(title),
|
||||
content: Text(message),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(false),
|
||||
child: const Text('Annuler'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.of(context).pop(true),
|
||||
child: Text(confirmLabel),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
return result ?? false;
|
||||
}
|
||||
}
|
||||
|
||||
final class _RoundScaffold extends StatelessWidget {
|
||||
const _RoundScaffold({required this.child});
|
||||
|
||||
final Widget child;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: SafeArea(
|
||||
minimum: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
|
||||
child: Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 210, maxHeight: 210),
|
||||
child: child,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
final class _NoSessionView extends StatelessWidget {
|
||||
const _NoSessionView({
|
||||
required this.projection,
|
||||
required this.pending,
|
||||
required this.onRefresh,
|
||||
});
|
||||
|
||||
final WatchSessionProjection projection;
|
||||
final bool pending;
|
||||
final VoidCallback onRefresh;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final phoneReachable = projection.phoneReachable;
|
||||
return Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Text(
|
||||
phoneReachable ? 'Aucune séance en cours' : 'Téléphone indisponible',
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.titleSmall,
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Text(
|
||||
phoneReachable
|
||||
? 'Lance une séance sur le téléphone.'
|
||||
: 'Rouvre GameTime sur le téléphone.',
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
FilledButton(
|
||||
onPressed: pending ? null : onRefresh,
|
||||
child: Text(pending ? 'Envoi...' : 'Actualiser'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
final class _SessionMainView extends StatelessWidget {
|
||||
const _SessionMainView({
|
||||
required this.state,
|
||||
required this.onPrimary,
|
||||
required this.onRetry,
|
||||
required this.onActions,
|
||||
});
|
||||
|
||||
final WatchSessionUiState state;
|
||||
final VoidCallback onPrimary;
|
||||
final VoidCallback onRetry;
|
||||
final VoidCallback onActions;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final projection = state.projection;
|
||||
final isRest = projection.phase == WatchSessionPhase.restRunning ||
|
||||
projection.phase == WatchSessionPhase.restPaused;
|
||||
if (state.connectionLost || !projection.phoneReachable) {
|
||||
return _ConnectionLostView(onRetry: onRetry);
|
||||
}
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: TextButton(
|
||||
onPressed: onActions,
|
||||
style: TextButton.styleFrom(
|
||||
visualDensity: VisualDensity.compact,
|
||||
minimumSize: const Size(56, 26),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
),
|
||||
child: const Text('Actions'),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: isRest
|
||||
? _RestContent(projection: projection)
|
||||
: _ActiveContent(projection: projection),
|
||||
),
|
||||
if (state.staleProjection)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 4),
|
||||
child: Text(
|
||||
'Dernier état reçu',
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: state.actionsEnabled ? onPrimary : null,
|
||||
child: Text(_primaryLabel(state)),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
final class _ActiveContent extends StatelessWidget {
|
||||
const _ActiveContent({required this.projection});
|
||||
|
||||
final WatchSessionProjection projection;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final timer = projection.dominantTimer;
|
||||
return Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Text(
|
||||
'SÉRIE ${projection.seriesIndex} / ${projection.seriesTotal}',
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.labelSmall,
|
||||
),
|
||||
const SizedBox(height: 3),
|
||||
Text(
|
||||
projection.exerciseName,
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.titleSmall,
|
||||
),
|
||||
if (_contextLine(projection) case final contextLine?)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: Text(
|
||||
contextLine,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
if (timer == null)
|
||||
Text(
|
||||
projection.statusLabel ?? '',
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodyMedium,
|
||||
)
|
||||
else ...[
|
||||
Text(
|
||||
_timerText(timer),
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.displayLarge,
|
||||
),
|
||||
Text(
|
||||
projection.statusLabel ?? timer.label,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
],
|
||||
if (projection.secondaryTimers.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 7),
|
||||
child: Text(
|
||||
projection.secondaryTimers.map(_compactTimerText).join(' · '),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
final class _RestContent extends StatelessWidget {
|
||||
const _RestContent({required this.projection});
|
||||
|
||||
final WatchSessionProjection projection;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final timer = projection.dominantTimer;
|
||||
return Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Text(
|
||||
'REPOS',
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.labelSmall,
|
||||
),
|
||||
const SizedBox(height: 3),
|
||||
Text(
|
||||
'Après série ${projection.seriesIndex} / ${projection.seriesTotal}',
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Text(
|
||||
timer == null ? '--:--' : _timerText(timer),
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.displayLarge,
|
||||
),
|
||||
Text(
|
||||
projection.statusLabel ?? timer?.label ?? '',
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
if (projection.nextExerciseName case final next?)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 9),
|
||||
child: Column(
|
||||
children: [
|
||||
Text(
|
||||
'Exercice suivant',
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
Text(
|
||||
next,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodyMedium,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
final class _ActionsView extends StatelessWidget {
|
||||
const _ActionsView({
|
||||
required this.state,
|
||||
required this.onAction,
|
||||
required this.onSession,
|
||||
});
|
||||
|
||||
final WatchSessionUiState state;
|
||||
final ValueChanged<WatchSecondaryAction> onAction;
|
||||
final VoidCallback onSession;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final actions = state.projection.secondaryActions;
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Actions',
|
||||
style: Theme.of(context).textTheme.titleSmall,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
onPressed: onSession,
|
||||
tooltip: 'Séance',
|
||||
visualDensity: VisualDensity.compact,
|
||||
icon: const Icon(Icons.chevron_left),
|
||||
),
|
||||
],
|
||||
),
|
||||
Expanded(
|
||||
child: actions.isEmpty || !state.projection.phoneReachable ||
|
||||
state.connectionLost
|
||||
? Center(
|
||||
child: Text(
|
||||
state.projection.phoneReachable && !state.connectionLost
|
||||
? 'Aucune action'
|
||||
: 'Connexion perdue',
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
)
|
||||
: ListView.separated(
|
||||
padding: const EdgeInsets.only(top: 4, bottom: 12),
|
||||
itemBuilder: (context, index) {
|
||||
final action = actions[index];
|
||||
return OutlinedButton(
|
||||
onPressed: state.actionsEnabled
|
||||
? () => onAction(action)
|
||||
: null,
|
||||
child: Text(_secondaryLabel(action)),
|
||||
);
|
||||
},
|
||||
separatorBuilder: (_, _) => const SizedBox(height: 8),
|
||||
itemCount: actions.length,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
final class _ConnectionLostView extends StatelessWidget {
|
||||
const _ConnectionLostView({required this.onRetry});
|
||||
|
||||
final VoidCallback onRetry;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
'Connexion perdue',
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.titleSmall,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Dernier état reçu il y a quelques secondes',
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
FilledButton(onPressed: onRetry, child: const Text('Réessayer')),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _primaryLabel(WatchSessionUiState state) {
|
||||
if (state.commandPending) {
|
||||
return state.waitingForPhone ? 'En attente du téléphone' : 'Envoi...';
|
||||
}
|
||||
return switch (state.projection.primaryAction) {
|
||||
WatchPrimaryAction.none => 'Actualiser',
|
||||
WatchPrimaryAction.startCurrentExercise => 'Démarrer l’exercice',
|
||||
WatchPrimaryAction.pauseSession => 'Pause',
|
||||
WatchPrimaryAction.resumeSession => 'Reprendre',
|
||||
WatchPrimaryAction.startPreparedTimedStep => 'Démarrer le chrono',
|
||||
WatchPrimaryAction.skipCurrentRest => 'Passer le repos',
|
||||
};
|
||||
}
|
||||
|
||||
String _secondaryLabel(WatchSecondaryAction action) {
|
||||
return switch (action) {
|
||||
WatchSecondaryAction.skipCurrentStep => 'Passer l’étape',
|
||||
WatchSecondaryAction.skipCurrentPassage => 'Passer le passage',
|
||||
WatchSecondaryAction.finishCurrentSet => 'Terminer la série',
|
||||
WatchSecondaryAction.skipCurrentSet => 'Passer la série',
|
||||
WatchSecondaryAction.skipCurrentRest => 'Passer le repos',
|
||||
};
|
||||
}
|
||||
|
||||
String? _contextLine(WatchSessionProjection projection) {
|
||||
final parts = [
|
||||
if (projection.passageIndex != null && projection.passageTotal != null)
|
||||
'Passage ${projection.passageIndex} / ${projection.passageTotal}',
|
||||
if (projection.stepIndex != null && projection.stepTotal != null)
|
||||
'Étape ${projection.stepIndex} / ${projection.stepTotal}',
|
||||
];
|
||||
if (parts.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
String _timerText(WatchTimerProjection timer) {
|
||||
final duration = _displayDuration(timer);
|
||||
final totalSeconds = duration.inSeconds;
|
||||
final minutes = (totalSeconds ~/ 60).toString().padLeft(2, '0');
|
||||
final seconds = (totalSeconds % 60).toString().padLeft(2, '0');
|
||||
return '$minutes:$seconds';
|
||||
}
|
||||
|
||||
String _compactTimerText(WatchTimerProjection timer) {
|
||||
return '${timer.label} ${_timerText(timer)}';
|
||||
}
|
||||
|
||||
Duration _displayDuration(WatchTimerProjection timer) {
|
||||
final elapsedMs = _interpolatedElapsedMs(timer);
|
||||
final displayMs = switch (timer.displayMode) {
|
||||
WatchTimerDisplayMode.elapsed => elapsedMs,
|
||||
WatchTimerDisplayMode.countdown => (timer.targetMs ?? 0) - elapsedMs,
|
||||
};
|
||||
return Duration(milliseconds: displayMs < 0 ? 0 : displayMs);
|
||||
}
|
||||
|
||||
int _interpolatedElapsedMs(WatchTimerProjection timer) {
|
||||
if (timer.runState != WatchTimerRunState.running ||
|
||||
timer.startedAtEpochMs == null) {
|
||||
return timer.accumulatedMs;
|
||||
}
|
||||
final nowMs = DateTime.now().millisecondsSinceEpoch;
|
||||
return timer.accumulatedMs + nowMs - timer.startedAtEpochMs!;
|
||||
}
|
||||
71
watch_app/lib/presentation/watch_theme.dart
Normal file
71
watch_app/lib/presentation/watch_theme.dart
Normal file
@ -0,0 +1,71 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
ThemeData watchTheme() {
|
||||
const background = Color(0xFF080A12);
|
||||
const surface = Color(0xFF141824);
|
||||
const text = Color(0xFFF5F1E8);
|
||||
const muted = Color(0xFFA7ADBA);
|
||||
const accent = Color(0xFFD72638);
|
||||
|
||||
final textTheme = Typography.whiteMountainView.copyWith(
|
||||
labelSmall: const TextStyle(
|
||||
fontSize: 10,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: muted,
|
||||
),
|
||||
bodySmall: const TextStyle(fontSize: 11, color: muted, height: 1.15),
|
||||
bodyMedium: const TextStyle(fontSize: 13, color: text, height: 1.15),
|
||||
titleSmall: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w800,
|
||||
color: text,
|
||||
height: 1.05,
|
||||
),
|
||||
displayLarge: const TextStyle(
|
||||
fontSize: 44,
|
||||
fontWeight: FontWeight.w900,
|
||||
color: text,
|
||||
height: 0.95,
|
||||
fontFeatures: [FontFeature.tabularFigures()],
|
||||
),
|
||||
);
|
||||
|
||||
return ThemeData(
|
||||
useMaterial3: true,
|
||||
brightness: Brightness.dark,
|
||||
scaffoldBackgroundColor: background,
|
||||
colorScheme: const ColorScheme.dark(
|
||||
primary: accent,
|
||||
onPrimary: Colors.white,
|
||||
secondary: Color(0xFFC9A24A),
|
||||
surface: surface,
|
||||
onSurface: text,
|
||||
onSurfaceVariant: muted,
|
||||
error: Color(0xFFFF4D5E),
|
||||
),
|
||||
textTheme: textTheme,
|
||||
filledButtonTheme: FilledButtonThemeData(
|
||||
style: FilledButton.styleFrom(
|
||||
minimumSize: const Size.fromHeight(38),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
|
||||
textStyle: textTheme.labelLarge?.copyWith(
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w800,
|
||||
),
|
||||
),
|
||||
),
|
||||
outlinedButtonTheme: OutlinedButtonThemeData(
|
||||
style: OutlinedButton.styleFrom(
|
||||
minimumSize: const Size.fromHeight(38),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
|
||||
side: const BorderSide(color: Color(0xFF303748)),
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
|
||||
textStyle: textTheme.labelLarge?.copyWith(
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w800,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user