fix: UI feedback round — remembered devices, Click V2 unlock, paywall, Pro dialog

- Remembered controllers offer a single "Forget" instead of two disconnect
  variants: there is no link to drop on a device that isn't here.
- Click V2: drop the unlock-mode dropdown and the new-unlock-method toggle.
  The explainer stays the one place the mode is chosen — it also does the
  follow-on work (un-ignoring the left puck, the right-side-only remap,
  cancelling the reset timer) that the bare dropdown never did. "Set up
  again" now sits on the right puck's card too.
- Paywall: the Base column reads "Basis"/"Base" rather than "VOLL"/"FULL",
  and the one-time Base card moves above the Pro plans so top-to-bottom
  matches the comparison table's left-to-right.
- A remembered controller's own settings page shows its button mapping
  again. The gate counted live controllers only and KeymapExplanation
  looked its filterDevice up in the live list, so the page fell through to
  a warning about connection methods, which had nothing to do with it.
- showGoProDialog takes a feature name for its title, so the keymap sync
  cloud icon says what it does instead of only "Pro Feature".

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jonas Bark
2026-08-13 07:50:34 +02:00
parent 279357da5e
commit 74bb2737ba
19 changed files with 187 additions and 335 deletions

View File

@@ -9,7 +9,6 @@ import 'package:bike_control/utils/i18n_extension.dart';
import 'package:bike_control/utils/interpreter.dart';
import 'package:bike_control/utils/keymap/buttons.dart';
import 'package:bike_control/widgets/controller/controller_layout.dart';
import 'package:bike_control/widgets/new_unlock_method_toggle.dart';
import 'package:bike_control/widgets/ui/warning.dart';
import 'package:bike_control/widgets/unlock_confirm.dart';
import 'package:dartx/dartx.dart';
@@ -223,23 +222,6 @@ class ZwiftClickV2 extends ZwiftRide {
return unlockWarnings(context);
}
/// The new-unlock-method toggle lives in the detail page's "Preferences"
/// section (via [buildPreferences]) rather than [showAdditionalInformation],
/// so it shows only when the controller entry is opened, not on the compact
/// overview card.
@override
Widget? buildPreferences(BuildContext context) {
final superPreferences = super.buildPreferences(context);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
spacing: 12,
children: [
if (superPreferences != null) superPreferences,
const NewUnlockMethodToggle(),
],
);
}
/// The unlock-status warning(s) for this Click. Split out from
/// [showAdditionalInformation] so [ZwiftClickV2LeftSide] can wrap exactly
/// these in its unlock-mode toggle.

View File

@@ -88,7 +88,7 @@ class ZwiftClickV2LeftSide extends ZwiftClickV2 {
@override
List<Widget> showAdditionalInformation(BuildContext context) {
return [
UnlockToggle(device: this, children: unlockWarnings(context)),
UnlockToggle(children: unlockWarnings(context)),
];
}
}

View File

@@ -10,8 +10,8 @@ import 'package:bike_control/utils/keymap/buttons.dart';
import 'package:bike_control/utils/keymap/keymap.dart';
import 'package:bike_control/utils/keymap/manager.dart';
import 'package:bike_control/widgets/controller/controller_layout.dart';
import 'package:bike_control/widgets/new_unlock_method_toggle.dart';
import 'package:bike_control/widgets/ui/toast.dart';
import 'package:bike_control/widgets/unlock_toggle.dart';
import 'package:flutter/foundation.dart';
import 'package:prop/prop.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart';
@@ -105,32 +105,22 @@ class ZwiftClickV2RightSide extends ZwiftRide {
// side back rather than forgetting it, so it stays in the device list.
// Offering to drop a puck that is already out would just be confusing.
final hasLiveLeftSide = core.connection.devices.whereType<ZwiftClickV2LeftSide>().any((d) => d.isConnected);
if (!hasLiveLeftSide) return [];
return [
Text(context.i18n.unlock_useRightSideOnlyDescription).xSmall.normal,
SizedBox(
width: double.infinity,
child: Button.outline(
onPressed: () => _useRightSideOnly(context),
child: Text(context.i18n.unlock_useRightSideOnly),
// The unlock mode is one setting covering both pucks, so the way back
// into the explainer belongs on either card — a rider looking at the
// right side shouldn't have to find the left one to change it.
const UnlockToggle(children: []),
if (hasLiveLeftSide) ...[
Text(context.i18n.unlock_useRightSideOnlyDescription).xSmall.normal,
SizedBox(
width: double.infinity,
child: Button.outline(
onPressed: () => _useRightSideOnly(context),
child: Text(context.i18n.unlock_useRightSideOnly),
),
),
),
];
}
/// Detail page only: the new-unlock-method toggle lives under "Preferences"
/// so it doesn't show on the compact overview card.
@override
Widget? buildPreferences(BuildContext context) {
final superPreferences = super.buildPreferences(context);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
spacing: 12,
children: [
if (superPreferences != null) superPreferences,
const NewUnlockMethodToggle(),
],
);
];
}
/// Switches to a "right side only" setup: the left controller (which needs

View File

@@ -350,7 +350,7 @@
},
"firmware": "Firmware",
"forceCloseToUpdate": "Schließen die App, um die neue Version zu verwenden.",
"full": "VOLL",
"full": "Basis",
"fullVersion": "Basis Version",
"fullVersionDescription": "Die Basisversion beinhaltet: \n– Unbegrenzte Befehle pro Tag \n– Zugriff auf zukünftigen Updates \n– Kein Abonnement! Nur eine einmalige Gebühr :)",
"getSupport": "Unterstützung erhalten",
@@ -1666,5 +1666,6 @@
"chainUndo": "Rückgängig",
"chainUpgrade": "Upgrade",
"chainMoreOptions": "Weitere Optionen",
"chainCloseAndQuit": "Verbindungen schließen & App beenden"
"chainCloseAndQuit": "Verbindungen schließen & App beenden",
"forget": "Vergessen"
}

View File

@@ -351,7 +351,7 @@
},
"firmware": "Firmware",
"forceCloseToUpdate": "Force-close the app to use the new version",
"full": "FULL",
"full": "Base",
"fullVersion": "Base",
"fullVersionDescription": "The base version includes:\n- Unlimited commands per day\n- Access to all future updates\n- No subscription! A one-time fee only :)",
"getSupport": "Get Support",
@@ -1860,5 +1860,6 @@
}
},
"chainStatusBridged": "Bridged",
"chainCloseAndQuit": "Close connections & quit app"
"chainCloseAndQuit": "Close connections & quit app",
"forget": "Forget"
}

View File

@@ -350,7 +350,7 @@
},
"firmware": "Firmware",
"forceCloseToUpdate": "Fuerza el cierre de la app para usar la nueva versión",
"full": "LLENO",
"full": "Base",
"fullVersion": "Base",
"fullVersionDescription": "La versión básica incluye: \n- Comandos ilimitados por día \n- Acceso a todas las actualizaciones futuras \n- ¡Sin suscripción! Un solo pago :)",
"getSupport": "Obtener ayuda",
@@ -1666,5 +1666,6 @@
"chainUndo": "Deshacer",
"chainUpgrade": "Mejorar",
"chainMoreOptions": "Más opciones",
"chainCloseAndQuit": "Cerrar conexiones y salir de la app"
"chainCloseAndQuit": "Cerrar conexiones y salir de la app",
"forget": "Olvidar"
}

View File

@@ -350,7 +350,7 @@
},
"firmware": "Firmware",
"forceCloseToUpdate": "Fermez de force l'application pour utiliser la nouvelle version.",
"full": "COMPLET",
"full": "Base",
"fullVersion": "Base",
"fullVersionDescription": "La version de base comprend : \n- Commandes illimitées par jour \n- Accès à toutes les mises à jour futures \n- Aucun abonnement ! Un paiement unique :)",
"getSupport": "Obtenir de l'aide",
@@ -1666,5 +1666,6 @@
"chainUndo": "Annuler",
"chainUpgrade": "Passer à la version supérieure",
"chainMoreOptions": "Plus d’options",
"chainCloseAndQuit": "Fermer les connexions et quitter l’application"
"chainCloseAndQuit": "Fermer les connexions et quitter l’application",
"forget": "Oublier"
}

View File

@@ -350,7 +350,7 @@
},
"firmware": "Firmware",
"forceCloseToUpdate": "Forza la chiusura dell'app per utilizzare la nuova versione",
"full": "PIENO",
"full": "Base",
"fullVersion": "Base",
"fullVersionDescription": "La versione base include: \n- Comandi illimitati al giorno \n- Accesso a tutti i futuri aggiornamenti \n- Nessun abbonamento! Un solo pagamento una tantum :)",
"getSupport": "Ottieni supporto",
@@ -1666,5 +1666,6 @@
"chainUndo": "Annulla",
"chainUpgrade": "Passa alla versione completa",
"chainMoreOptions": "Altre opzioni",
"chainCloseAndQuit": "Chiudi le connessioni ed esci dall’app"
"chainCloseAndQuit": "Chiudi le connessioni ed esci dall’app",
"forget": "Dimentica"
}

View File

@@ -350,7 +350,7 @@
},
"firmware": "Firmware",
"forceCloseToUpdate": "Wymuś zamknięcie aplikacji, aby móc korzystać z nowej wersji",
"full": "PEŁNY",
"full": "Podstawa",
"fullVersion": "Opierać",
"fullVersionDescription": "Wersja podstawowa zawiera: \n- Nielimitowane polecenia dziennie \n- Dostęp do wszystkich przyszłych aktualizacji \n- Brak subskrypcji! Opłata jednorazowa :)",
"getSupport": "Uzyskaj wsparcie",
@@ -1666,5 +1666,6 @@
"chainUndo": "Cofnij",
"chainUpgrade": "Uaktualnij",
"chainMoreOptions": "Więcej opcji",
"chainCloseAndQuit": "Zamknij połączenia i wyjdź z aplikacji"
"chainCloseAndQuit": "Zamknij połączenia i wyjdź z aplikacji",
"forget": "Zapomnij"
}

View File

@@ -317,35 +317,59 @@ class _ControllerSettingsPageState extends State<ControllerSettingsPage> {
);
},
),
LoadingWidget(
futureCallback: () async {
await core.connection.disconnect(device, forget: true, persistForget: false);
if (mounted) Navigator.of(context).pop();
},
renderChild: (isLoading, tap) => _buildActionButton(
icon: LucideIcons.bluetoothOff,
label: AppLocalizations.of(context).disconnectAndForgetForThisSession,
isLoading: isLoading,
onTap: tap,
if (_isRemembered(device))
// A remembered controller is a picture of a device, not a device:
// there is no link to drop, so both disconnect variants collapse
// into the one thing that can actually be done to it.
LoadingWidget(
futureCallback: () async {
await core.connection.forgetRemembered(device.uniqueId);
if (mounted) Navigator.of(context).pop();
},
renderChild: (isLoading, tap) => _buildActionButton(
icon: LucideIcons.trash2,
label: AppLocalizations.of(context).forget,
isLoading: isLoading,
isDestructive: true,
onTap: tap,
),
)
else ...[
LoadingWidget(
futureCallback: () async {
await core.connection.disconnect(device, forget: true, persistForget: false);
if (mounted) Navigator.of(context).pop();
},
renderChild: (isLoading, tap) => _buildActionButton(
icon: LucideIcons.bluetoothOff,
label: AppLocalizations.of(context).disconnectAndForgetForThisSession,
isLoading: isLoading,
onTap: tap,
),
),
),
LoadingWidget(
futureCallback: () async {
await core.connection.disconnect(device, forget: true, persistForget: true);
if (mounted) Navigator.of(context).pop();
},
renderChild: (isLoading, tap) => _buildActionButton(
icon: LucideIcons.trash2,
label: AppLocalizations.of(context).disconnectAndForget,
isLoading: isLoading,
isDestructive: true,
onTap: tap,
LoadingWidget(
futureCallback: () async {
await core.connection.disconnect(device, forget: true, persistForget: true);
if (mounted) Navigator.of(context).pop();
},
renderChild: (isLoading, tap) => _buildActionButton(
icon: LucideIcons.trash2,
label: AppLocalizations.of(context).disconnectAndForget,
isLoading: isLoading,
isDestructive: true,
onTap: tap,
),
),
),
],
],
);
}
/// True for a controller that only exists as a remembered stand-in — no live
/// device has taken it over, so nothing is connected to disconnect from.
bool _isRemembered(BaseDevice device) =>
core.connection.offlineControllers.any((d) => d.uniqueId == device.uniqueId);
Widget _buildActionButton({
required IconData icon,
required String label,

View File

@@ -123,7 +123,12 @@ class _CustomizeState extends State<CustomizePage> {
onPressed: IAPManager.instance.isProEnabled
? null
: () {
IAPManager.instance.ensureProForFeature(context);
// The cloud icon carries no label of its own, so the
// dialog is where the rider finds out what it does.
IAPManager.instance.ensureProForFeature(
context,
featureName: context.i18n.synchronizeAcrossDevices,
);
},
),
),
@@ -138,8 +143,7 @@ class _CustomizeState extends State<CustomizePage> {
),
if (!screenshotMode) Gap(12),
if (core.actionHandler.supportedApp != null &&
(core.connection.controllerDevices.isNotEmpty || (core.connection.proxyDevices.any((e) => e.isConnected))))
if (core.actionHandler.supportedApp != null && _hasSomethingToMap)
KeymapExplanation(
key: Key(core.actionHandler.supportedApp!.keymap.runtimeType.toString()),
keymap: core.actionHandler.supportedApp!.keymap,
@@ -178,6 +182,20 @@ class _CustomizeState extends State<CustomizePage> {
);
}
/// Whether there are any buttons worth showing a mapping table for.
///
/// [CustomizePage.filterDevice] is the strongest answer there is: the page is
/// embedded in that device's own settings, so the rider is looking straight
/// at the thing whose buttons they came to map. It counts even when the
/// device is only a remembered stand-in — a controller that is switched off
/// is still one whose mapping can be edited, and falling through to "no
/// connection method selected" both hid that and named a reason that had
/// nothing to do with it.
bool get _hasSomethingToMap =>
widget.filterDevice != null ||
core.connection.controllerDevices.isNotEmpty ||
core.connection.proxyDevices.any((e) => e.isConnected);
List<SupportedApp> _getAllApps() {
final baseApp = core.settings.getTrainerApp();
final customProfiles = core.settings.getCustomAppProfiles();

View File

@@ -474,13 +474,19 @@ class _PaywallState extends State<Paywall> {
SizedBox(
width: fullColumnWidth,
child: Center(
child: Text(
AppLocalizations.of(context).full,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 14,
letterSpacing: 0.8,
color: Color(0xFF55565C),
// "Base" is short in most languages but not all — shrink rather
// than wrap or clip inside a fixed-width column.
child: FittedBox(
fit: BoxFit.scaleDown,
child: Text(
AppLocalizations.of(context).full,
maxLines: 1,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 14,
letterSpacing: 0.8,
color: Color(0xFF55565C),
),
),
),
),
@@ -582,37 +588,45 @@ class _PaywallState extends State<Paywall> {
return Column(
spacing: 12,
children: [
// Base leads, mirroring the comparison table above it: its column
// is the left one, so reading top-to-bottom here matches reading
// left-to-right there.
if (!_iapManager.isPurchased.value) _buildFullVersionCard(context),
// Yearly and monthly always sit side by side — they're a
// comparison. IntrinsicHeight bounds the row to its tallest card
// so stretch can equalise them: inside the sheet's scroll view
// the cross axis is unbounded, and stretching against that hands
// the cards an infinite height ("RenderBox was not laid out").
IntrinsicHeight(
child: Row(
spacing: 12,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: _buildPlanCard(
plan: _PaywallPlan.yearly,
title: AppLocalizations.of(context).paywall_yearly,
price: _pricing.yearlyPrice,
billed: _pricing.yearlyBilled,
badge: _pricing.discountBadge,
Padding(
// The yearly card's discount badge hangs 10px above the row and
// would otherwise sit on top of the Base card now above it.
padding: const EdgeInsets.only(top: 8),
child: IntrinsicHeight(
child: Row(
spacing: 12,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: _buildPlanCard(
plan: _PaywallPlan.yearly,
title: AppLocalizations.of(context).paywall_yearly,
price: _pricing.yearlyPrice,
billed: _pricing.yearlyBilled,
badge: _pricing.discountBadge,
),
),
),
Expanded(
child: _buildPlanCard(
plan: _PaywallPlan.monthly,
title: AppLocalizations.of(context).paywall_monthly,
price: _pricing.monthlyPrice,
billed: _pricing.monthlyBilled,
Expanded(
child: _buildPlanCard(
plan: _PaywallPlan.monthly,
title: AppLocalizations.of(context).paywall_monthly,
price: _pricing.monthlyPrice,
billed: _pricing.monthlyBilled,
),
),
],
),
],
),
),
if (!_iapManager.isPurchased.value) _buildFullVersionCard(context),
],
);
},

View File

@@ -89,7 +89,7 @@ abstract final class ClickV2Onboarding {
for (final device in pendingDevices) {
// forget: false is what drops the cached scan result, so the active
// scan rediscovers the controller and rebuilds it with the class the
// new setting selects. This mirrors NewUnlockMethodToggle exactly.
// new setting selects.
// persistForget: false keeps it out of the ignored-devices list.
await core.connection.disconnect(device, forget: false, persistForget: false);
}
@@ -146,10 +146,10 @@ abstract final class ClickV2Onboarding {
/// which is exactly [ZwiftClickV2LeftSide.label], since that is what
/// `Connection.disconnect` wrote there.
///
/// Public because right-side-only is not the only way out of it: switching
/// off the split representation entirely (NewUnlockMethodToggle) rebuilds the
/// LEFT puck as the legacy unified controller, so leaving it ignored would
/// leave the rider with no Click at all.
/// Public because right-side-only is not the only way out of it: anything
/// that switches off the split representation rebuilds the LEFT puck as the
/// legacy unified controller, so leaving it ignored would leave the rider
/// with no Click at all.
static Future<void> restoreLeftSides() async {
const labels = {ZwiftClickV2LeftSide.label, ZwiftClickV2.label};
final ignored = core.settings.getIgnoredDevices().where((d) => labels.contains(d.name)).toList();

View File

@@ -468,14 +468,20 @@ class IAPManager {
}
}
Future<bool> ensureProForFeature(BuildContext context, {bool isAllowedForOldPurchases = false}) async {
/// [featureName] names the gated feature in the upgrade dialog — see
/// [showGoProDialog].
Future<bool> ensureProForFeature(
BuildContext context, {
bool isAllowedForOldPurchases = false,
String? featureName,
}) async {
if (isProEnabledForCurrentDevice || (isAllowedForOldPurchases && hasPurchasedBefore50RVC)) {
return true;
} else if (isProEnabled) {
buildToast(title: AppLocalizations.of(context).currentDeviceIsNotRegistered);
return isProEnabledForCurrentDevice;
} else {
await showGoProDialog(context);
await showGoProDialog(context, featureName: featureName);
}
return IAPManager.instance.hasActiveSubscription;
}

View File

@@ -6,8 +6,13 @@ import 'package:bike_control/widgets/ui/small_progress_indicator.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart';
/// Shows a dialog prompting the user to upgrade to Pro.
///
/// [featureName] names the thing the rider just reached for. Pass it wherever
/// the entry point is an icon or a toggle: "Pro Feature" alone tells them the
/// price of something they never found out the name of.
///
/// Returns true if the user initiated a purchase, false otherwise.
Future<bool> showGoProDialog(BuildContext context) async {
Future<bool> showGoProDialog(BuildContext context, {String? featureName}) async {
final iapManager = IAPManager.instance;
final result = await showDialog<bool>(
@@ -19,7 +24,7 @@ Future<bool> showGoProDialog(BuildContext context) async {
children: [
Icon(Icons.workspace_premium, color: Colors.orange),
const SizedBox(width: 8),
Text('Pro Feature'),
Expanded(child: Text(featureName ?? 'Pro Feature')),
],
),
content: Text(AppLocalizations.of(c).thisFeatureIsOnlyAvailableWithPro),

View File

@@ -96,9 +96,11 @@ class _KeymapExplanationState extends State<KeymapExplanation> {
@override
Widget build(BuildContext context) {
final devices = widget.filterDevice != null
? core.connection.controllerDevices.where((d) => d == widget.filterDevice).toList()
: core.connection.controllerDevices;
// Filtered to one device, that device IS the answer — no need to find it in
// the live list, which a remembered controller (switched off, still fully
// editable) is deliberately not part of. Looking it up there left its own
// settings page with no mapping table at all.
final devices = widget.filterDevice != null ? [widget.filterDevice!] : core.connection.controllerDevices;
final keyButtonMap = devices.associateWith((device) {
return device.availableButtons.distinct().sortedBy(
(button) => button.color != null ? '0${(button.icon?.codePoint ?? 0)}' : '1${(button.icon?.codePoint ?? 0)}',

View File

@@ -1,95 +0,0 @@
import 'package:bike_control/bluetooth/devices/zwift/zwift_clickv2.dart';
import 'package:bike_control/bluetooth/devices/zwift/zwift_clickv2_right_side.dart';
import 'package:bike_control/utils/click_v2_onboarding.dart';
import 'package:bike_control/utils/core.dart';
import 'package:bike_control/utils/i18n_extension.dart';
import 'package:bike_control/widgets/ui/toast.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart';
/// Toggle that switches between the new split left/right Click V2 controllers
/// (with the unlock handling the right side avoids entirely) and the legacy
/// single [ZwiftClickV2]. Shown in the settings of all three Click V2 device
/// variants. Defaults on.
///
/// Flipping it re-creates the connected Click(s): a plain disconnect drops them
/// from the scan cache so the active scan rediscovers and reconnects them with
/// the representation the new setting now selects.
class NewUnlockMethodToggle extends StatefulWidget {
const NewUnlockMethodToggle({super.key});
@override
State<NewUnlockMethodToggle> createState() => _NewUnlockMethodToggleState();
}
class _NewUnlockMethodToggleState extends State<NewUnlockMethodToggle> {
late bool _enabled = core.settings.getUseNewUnlockMethod();
Future<void> _onChanged(bool value) async {
// Read localised text up front: disconnecting below removes this card from
// the tree, so `context` may be unmounted by the time we show the toast.
final reconnectingMessage = context.i18n.unlock_newMethodReconnecting;
setState(() => _enabled = value);
await core.settings.setUseNewUnlockMethod(value);
if (!value) {
// Right-side-only cannot survive this switch. In the legacy
// representation the LEFT puck is what becomes the unified
// [ZwiftClickV2] and the right puck builds nothing at all (see
// BluetoothDevice.fromScanResult) — so leaving the left side on the
// ignored list here leaves the rider with no Click whatsoever, and the
// chain falls back to its empty "Controller" placeholder.
await core.settings.setClickV2RightSideOnly(false);
await ClickV2Onboarding.restoreLeftSides();
} else if (!core.settings.getUnlockWithZwift()) {
// Switching the split representation ON is the rider asking for the
// handling whose whole point is the right puck needing no unlock — so
// land them on it, rather than on the left puck's restart loop, which is
// what the legacy mode they just left already was. A rider who
// deliberately chose unlock-with-Zwift keeps both sides; this only
// covers the default.
//
// Before the disconnect below, while the left puck is still a live
// device: that is what puts it on the ignored list, and it is the same
// physical device whether it currently exists as the unified controller
// or as a split left side.
await ClickV2Onboarding.chooseRightSideOnly();
}
final clicks = core.connection.bluetoothDevices
.where((d) => d is ZwiftClickV2 || d is ZwiftClickV2RightSide)
.toList();
for (final device in clicks) {
await core.connection.disconnect(device, forget: false, persistForget: false);
}
// A full restart, not just the disconnects above. The scanner dedupes
// against its cached adverts, and in the legacy representation the right
// puck's advert was cached while resolving to no device at all
// (fromScanResult returns null for it) — so without clearing that cache the
// right side is never rebuilt, and the rider ends up with the one puck this
// switch was meant to move them off.
await core.connection.stop();
await core.connection.performScanning();
if (clicks.isNotEmpty) {
buildToast(title: reconnectingMessage);
}
}
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
spacing: 4,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(child: Text(context.i18n.unlock_newMethod).small.semiBold),
Switch(value: _enabled, onChanged: _onChanged),
],
),
Text(context.i18n.unlock_newMethodDescription).xSmall.muted,
],
);
}
}

View File

@@ -1,16 +1,21 @@
import 'package:bike_control/bluetooth/devices/zwift/zwift_clickv2_left_side.dart';
import 'package:bike_control/bluetooth/messages/notification.dart';
import 'package:bike_control/pages/click_v2_onboarding.dart';
import 'package:bike_control/utils/core.dart';
import 'package:bike_control/utils/i18n_extension.dart';
import 'package:prop/devices/click_logic.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart';
import 'package:url_launcher/url_launcher_string.dart';
/// The unlock-mode header shown on both Zwift Click V2 pucks: what the mode is
/// called, where to read about it, and the way back into the explainer that
/// sets it.
///
/// Deliberately not a mode picker. The explainer is the one place the choice is
/// made — it is what applies the follow-on work each mode needs (un-ignoring
/// the left puck, remapping for right-side-only, cancelling the reset timer),
/// none of which a bare dropdown did.
class UnlockToggle extends StatefulWidget {
final ZwiftClickV2LeftSide device;
/// Shown only in unlock-with-Zwift mode — the warnings that mode implies.
final List<Widget> children;
const UnlockToggle({super.key, required this.device, required this.children});
const UnlockToggle({super.key, required this.children});
@override
State<UnlockToggle> createState() => _UnlockToggleState();
@@ -47,81 +52,14 @@ class _UnlockToggleState extends State<UnlockToggle> {
onPressed: () async {
await context.push(const ClickV2OnboardingPage());
if (!mounted) return;
// The page may have applied a different choice than what's
// currently shown here (ClickV2Onboarding writes the setting
// directly, not through this widget's onChanged) — refresh so
// the Select and the gated warning children reflect it.
// The page writes the setting directly, so re-read it: the
// gated warning children below have to follow the new choice.
setState(() => _unlockWithZwift = core.settings.getUnlockWithZwift());
},
child: Text(context.i18n.clickV2Onboarding_setUpAgain).xSmall,
),
],
),
Select<bool>(
value: _unlockWithZwift,
popup: SelectPopup(
items: SelectItemList(
children: [
SelectItemButton(
value: false,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(context.i18n.unlock_modeRestart).bold,
Text(context.i18n.unlock_modeRestartDescription).xSmall.muted,
],
),
),
SelectItemButton(
value: true,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(context.i18n.unlock_modeZwift).bold,
Text(context.i18n.unlock_modeZwiftDescription).xSmall.muted,
],
),
),
],
),
).call,
itemBuilder: (context, value) => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(value ? context.i18n.unlock_modeZwift : context.i18n.unlock_modeRestart),
Text(
value ? context.i18n.unlock_modeZwiftDescription : context.i18n.unlock_modeRestartDescription,
).xSmall.normal.muted,
],
),
onChanged: (unlockWithZwift) async {
if (unlockWithZwift == null) return;
setState(() {
_unlockWithZwift = unlockWithZwift;
});
await core.settings.setUnlockWithZwift(unlockWithZwift);
if (unlockWithZwift) {
ClickLogic.resetTimer();
} else {
// `services` is populated by BluetoothDevice.connect() after
// discovery completes, but `isConnected` flips true earlier --
// from the raw BLE connection-state listener -- so there's a
// narrow window where this fires with services still null.
// The rider's choice still needs to be recorded either way;
// only the handshake itself is skipped when we can't send it.
final services = widget.device.services;
if (services != null) {
ClickLogic.setupHandshake(services, widget.device.device.deviceId, isRight: false);
} else {
core.connection.signalNotification(
LogNotification(
'UnlockToggle: skipped setupHandshake for ${widget.device.device.deviceId} -- services not ready yet',
),
);
}
}
},
),
if (_unlockWithZwift) ...widget.children,
],

View File

@@ -1,42 +1,20 @@
import 'package:bike_control/bluetooth/devices/bluetooth_device.dart';
import 'package:bike_control/bluetooth/devices/zwift/constants.dart';
import 'package:bike_control/bluetooth/devices/zwift/zwift_clickv2_left_side.dart';
import 'package:bike_control/gen/l10n.dart';
import 'package:bike_control/pages/click_v2_onboarding.dart';
import 'package:bike_control/utils/actions/base_actions.dart';
import 'package:bike_control/utils/core.dart';
import 'package:bike_control/widgets/unlock_toggle.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shadcn_flutter/shadcn_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:universal_ble/universal_ble.dart';
import 'dart:typed_data';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late ZwiftClickV2LeftSide device;
setUp(() async {
SharedPreferences.setMockInitialValues({});
core.actionHandler = StubActions();
core.settings.prefs = await SharedPreferences.getInstance();
await AppLocalizations.load(const Locale('en'));
device = BluetoothDevice.fromScanResult(
BleDevice(
deviceId: 'click-left',
name: 'Zwift Click',
manufacturerDataList: [
ManufacturerData(
ZwiftConstants.ZWIFT_MANUFACTURER_ID,
Uint8List.fromList([ZwiftConstants.CLICK_V2_LEFT_SIDE]),
),
],
services: [ZwiftConstants.ZWIFT_CUSTOM_SERVICE_UUID.toLowerCase()],
),
) as ZwiftClickV2LeftSide;
});
testWidgets('offers a way back into the onboarding explainer', (tester) async {
@@ -50,7 +28,7 @@ void main() {
ShadcnApp(
localizationsDelegates: const [AppLocalizations.delegate],
supportedLocales: const [Locale('en')],
home: Scaffold(child: UnlockToggle(device: device, children: const [])),
home: Scaffold(child: const UnlockToggle(children: [])),
),
);
await tester.pumpAndSettle();
@@ -63,35 +41,19 @@ void main() {
expect(find.byType(ClickV2OnboardingPage), findsOneWidget);
});
testWidgets('flipping unlock mode on a never-connected device does not throw', (tester) async {
// A device fresh off a scan result -- never connected -- has services ==
// null; BluetoothDevice.connect() is what populates it. This is the
// narrow race the guard in UnlockToggle exists for: isConnected can flip
// true before that assignment lands.
expect(device.services, isNull);
// Start on "Unlock using Zwift" so switching to "Restart" below exercises
// the ClickLogic.setupHandshake branch (the else arm), not resetTimer.
await core.settings.setUnlockWithZwift(true);
// The explainer is the only place the unlock mode is chosen — a dropdown
// beside it could set the setting without doing the work each mode needs.
testWidgets('offers no unlock-mode picker of its own', (tester) async {
tester.platformDispatcher.accessibilityFeaturesTestValue = const FakeAccessibilityFeatures(disableAnimations: true);
await tester.pumpWidget(
ShadcnApp(
localizationsDelegates: const [AppLocalizations.delegate],
supportedLocales: const [Locale('en')],
home: Scaffold(child: UnlockToggle(device: device, children: const [])),
home: Scaffold(child: const UnlockToggle(children: [])),
),
);
await tester.pumpAndSettle();
// Open the dropdown via its current (Zwift) value, then pick "Restart".
await tester.tap(find.text('Unlock using Zwift'));
await tester.pumpAndSettle();
await tester.tap(find.text('Restart device every minute'));
await tester.pumpAndSettle();
// Before the guard, this would have thrown on `services!` with services
// still null. No exception reaching here is the assertion.
expect(tester.takeException(), isNull);
expect(find.byType(Select<bool>), findsNothing);
});
}