diff --git a/lib/bluetooth/devices/zwift/zwift_clickv2.dart b/lib/bluetooth/devices/zwift/zwift_clickv2.dart index 17994bb5..dedf9e42 100644 --- a/lib/bluetooth/devices/zwift/zwift_clickv2.dart +++ b/lib/bluetooth/devices/zwift/zwift_clickv2.dart @@ -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. diff --git a/lib/bluetooth/devices/zwift/zwift_clickv2_left_side.dart b/lib/bluetooth/devices/zwift/zwift_clickv2_left_side.dart index 607b9fc3..b4ef04fc 100644 --- a/lib/bluetooth/devices/zwift/zwift_clickv2_left_side.dart +++ b/lib/bluetooth/devices/zwift/zwift_clickv2_left_side.dart @@ -88,7 +88,7 @@ class ZwiftClickV2LeftSide extends ZwiftClickV2 { @override List showAdditionalInformation(BuildContext context) { return [ - UnlockToggle(device: this, children: unlockWarnings(context)), + UnlockToggle(children: unlockWarnings(context)), ]; } } diff --git a/lib/bluetooth/devices/zwift/zwift_clickv2_right_side.dart b/lib/bluetooth/devices/zwift/zwift_clickv2_right_side.dart index 0839ae6d..a9fa3b56 100644 --- a/lib/bluetooth/devices/zwift/zwift_clickv2_right_side.dart +++ b/lib/bluetooth/devices/zwift/zwift_clickv2_right_side.dart @@ -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().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 diff --git a/lib/i10n/intl_de.arb b/lib/i10n/intl_de.arb index 81f06e2a..a0344849 100644 --- a/lib/i10n/intl_de.arb +++ b/lib/i10n/intl_de.arb @@ -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" } diff --git a/lib/i10n/intl_en.arb b/lib/i10n/intl_en.arb index f1587d34..f4aa478e 100644 --- a/lib/i10n/intl_en.arb +++ b/lib/i10n/intl_en.arb @@ -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" } diff --git a/lib/i10n/intl_es.arb b/lib/i10n/intl_es.arb index 32d873a5..5de834e2 100644 --- a/lib/i10n/intl_es.arb +++ b/lib/i10n/intl_es.arb @@ -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" } diff --git a/lib/i10n/intl_fr.arb b/lib/i10n/intl_fr.arb index cb46662b..d58d344a 100644 --- a/lib/i10n/intl_fr.arb +++ b/lib/i10n/intl_fr.arb @@ -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" } diff --git a/lib/i10n/intl_it.arb b/lib/i10n/intl_it.arb index c8c735fd..33680d34 100644 --- a/lib/i10n/intl_it.arb +++ b/lib/i10n/intl_it.arb @@ -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" } diff --git a/lib/i10n/intl_pl.arb b/lib/i10n/intl_pl.arb index 195cb67c..f359fa74 100644 --- a/lib/i10n/intl_pl.arb +++ b/lib/i10n/intl_pl.arb @@ -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" } diff --git a/lib/pages/controller_settings.dart b/lib/pages/controller_settings.dart index 96f66dee..ddf917c8 100644 --- a/lib/pages/controller_settings.dart +++ b/lib/pages/controller_settings.dart @@ -317,35 +317,59 @@ class _ControllerSettingsPageState extends State { ); }, ), - 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, diff --git a/lib/pages/customize.dart b/lib/pages/customize.dart index 291f4bb7..9ab04682 100644 --- a/lib/pages/customize.dart +++ b/lib/pages/customize.dart @@ -123,7 +123,12 @@ class _CustomizeState extends State { 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 { ), 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 { ); } + /// 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 _getAllApps() { final baseApp = core.settings.getTrainerApp(); final customProfiles = core.settings.getCustomAppProfiles(); diff --git a/lib/pages/paywall.dart b/lib/pages/paywall.dart index f6bf04e8..3bd0bfe2 100644 --- a/lib/pages/paywall.dart +++ b/lib/pages/paywall.dart @@ -474,13 +474,19 @@ class _PaywallState extends State { 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 { 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), ], ); }, diff --git a/lib/utils/click_v2_onboarding.dart b/lib/utils/click_v2_onboarding.dart index d5f025b7..122cc16a 100644 --- a/lib/utils/click_v2_onboarding.dart +++ b/lib/utils/click_v2_onboarding.dart @@ -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 restoreLeftSides() async { const labels = {ZwiftClickV2LeftSide.label, ZwiftClickV2.label}; final ignored = core.settings.getIgnoredDevices().where((d) => labels.contains(d.name)).toList(); diff --git a/lib/utils/iap/iap_manager.dart b/lib/utils/iap/iap_manager.dart index c0a087c9..5b3b1e4b 100644 --- a/lib/utils/iap/iap_manager.dart +++ b/lib/utils/iap/iap_manager.dart @@ -468,14 +468,20 @@ class IAPManager { } } - Future ensureProForFeature(BuildContext context, {bool isAllowedForOldPurchases = false}) async { + /// [featureName] names the gated feature in the upgrade dialog — see + /// [showGoProDialog]. + Future 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; } diff --git a/lib/widgets/go_pro_dialog.dart b/lib/widgets/go_pro_dialog.dart index 71119a0b..a405ad7c 100644 --- a/lib/widgets/go_pro_dialog.dart +++ b/lib/widgets/go_pro_dialog.dart @@ -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 showGoProDialog(BuildContext context) async { +Future showGoProDialog(BuildContext context, {String? featureName}) async { final iapManager = IAPManager.instance; final result = await showDialog( @@ -19,7 +24,7 @@ Future 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), diff --git a/lib/widgets/keymap_explanation.dart b/lib/widgets/keymap_explanation.dart index cd7e2a32..48fb57e0 100644 --- a/lib/widgets/keymap_explanation.dart +++ b/lib/widgets/keymap_explanation.dart @@ -96,9 +96,11 @@ class _KeymapExplanationState extends State { @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)}', diff --git a/lib/widgets/new_unlock_method_toggle.dart b/lib/widgets/new_unlock_method_toggle.dart deleted file mode 100644 index 5666a68b..00000000 --- a/lib/widgets/new_unlock_method_toggle.dart +++ /dev/null @@ -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 createState() => _NewUnlockMethodToggleState(); -} - -class _NewUnlockMethodToggleState extends State { - late bool _enabled = core.settings.getUseNewUnlockMethod(); - - Future _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, - ], - ); - } -} diff --git a/lib/widgets/unlock_toggle.dart b/lib/widgets/unlock_toggle.dart index 8f66bbc1..fd129d4b 100644 --- a/lib/widgets/unlock_toggle.dart +++ b/lib/widgets/unlock_toggle.dart @@ -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 children; - const UnlockToggle({super.key, required this.device, required this.children}); + const UnlockToggle({super.key, required this.children}); @override State createState() => _UnlockToggleState(); @@ -47,81 +52,14 @@ class _UnlockToggleState extends State { 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( - 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, ], diff --git a/test/widgets/unlock_toggle_setup_again_test.dart b/test/widgets/unlock_toggle_setup_again_test.dart index 2aabb617..5f96556d 100644 --- a/test/widgets/unlock_toggle_setup_again_test.dart +++ b/test/widgets/unlock_toggle_setup_again_test.dart @@ -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), findsNothing); }); }