diff --git a/app/lib/application/app_exit_dialog.dart b/app/lib/application/app_exit_dialog.dart new file mode 100644 index 00000000..07fffb98 --- /dev/null +++ b/app/lib/application/app_exit_dialog.dart @@ -0,0 +1,49 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +/// Asks before Back leaves the app from the top of a tab. True to leave. +Future confirmAppExit( + BuildContext context, { + required bool cupertino, +}) async { + const title = Text('Close Pipelines?'); + final leave = cupertino + ? await showCupertinoDialog( + context: context, + builder: (context) => CupertinoAlertDialog( + title: title, + actions: [ + CupertinoDialogAction( + key: const Key('app-exit-stay'), + isDefaultAction: true, + onPressed: () => Navigator.of(context).pop(false), + child: const Text('Stay'), + ), + CupertinoDialogAction( + key: const Key('app-exit-close'), + onPressed: () => Navigator.of(context).pop(true), + child: const Text('Close'), + ), + ], + ), + ) + : await showDialog( + context: context, + builder: (context) => AlertDialog( + title: title, + actions: [ + TextButton( + key: const Key('app-exit-stay'), + onPressed: () => Navigator.of(context).pop(false), + child: const Text('Stay'), + ), + FilledButton( + key: const Key('app-exit-close'), + onPressed: () => Navigator.of(context).pop(true), + child: const Text('Close'), + ), + ], + ), + ); + return leave ?? false; +} diff --git a/app/lib/application/app_router.dart b/app/lib/application/app_router.dart index b7f726c8..3dd305f1 100644 --- a/app/lib/application/app_router.dart +++ b/app/lib/application/app_router.dart @@ -1,7 +1,9 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'app_exit_dialog.dart'; import 'app_route.dart'; /// Parses the browser (or platform) location into the app's routes. @@ -144,7 +146,19 @@ class AppRouterDelegate extends RouterDelegate with ChangeNotifier { return Navigator( key: _navigatorKey, pages: [ - _page(_pageKey, builder(context, shellRoute)), + // While an item is open inside its tab (a wide screen keeps it + // there), Android's Back and back gesture step up a level instead of + // leaving the app: the shell tells the system it handles Back. + _page( + _pageKey, + PopScope( + canPop: !_canStepUp && !_asksBeforeExit, + onPopInvokedWithResult: (didPop, _) { + if (!didPop && !_stepUp()) _confirmExit(); + }, + child: builder(context, shellRoute), + ), + ), // Templates is a Settings sub-page: the shell stays mounted underneath, // so closing restores Settings exactly as it was left. if (templates) _page(_templatesPageKey, templatesBuilder!(context)), @@ -232,6 +246,38 @@ class AppRouterDelegate extends RouterDelegate with ChangeNotifier { closeTemplates(); return true; } + if (_stepUp()) return true; + return _confirmExit(); + } + + /// At the top of a tab Android's Back would leave the app; ask first. + /// Elsewhere (a browser) Back keeps its usual meaning. + bool get _asksBeforeExit => + !kIsWeb && defaultTargetPlatform == TargetPlatform.android; + + bool _confirming = false; + + bool _confirmExit() { + final context = _navigatorKey.currentContext; + if (!_asksBeforeExit || context == null) return false; + if (_confirming) return true; + _confirming = true; + confirmAppExit(context, cupertino: cupertino).then((leave) { + _confirming = false; + if (leave) SystemNavigator.pop(); + }); + return true; + } + + /// Whether the open route has a level above it in its own tab (a stage, + /// a run, a pipeline, a chat). + bool get _canStepUp => + _route.runId != null || + _route.chatSessionId != null || + (_route.kind == AppRouteKind.pipelines && _route.pipelineId != null); + + /// Goes up one level: a stage to its run or pipeline, an item to its list. + bool _stepUp() { final runId = _route.runId; if (runId != null && _route.stageKey != null) { goTo(AppRoute.run(runId)); diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index b79af92d..f3169c29 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -178,6 +178,9 @@ class _PipelinesAppState extends State routeInformationParser: const AppRouteParser(), routerDelegate: _delegate, routeInformationProvider: _provider, + // Android's Back button and back gesture go through the router, so + // they close a page or step up a level instead of leaving the app. + backButtonDispatcher: RootBackButtonDispatcher(), ); unawaited(_session.start()); } @@ -434,6 +437,18 @@ class _PipelinesAppState extends State onViewPipelineRuns: (id) => _delegate.goTo(AppRoute.runsForPipeline(id)), onOpenSchedules: _delegate.openSchedules, + // The open pipeline is part of the route, so Back steps out of it. + onSelectionChanged: (id) { + final current = _delegate.route; + if (current.kind != AppRouteKind.pipelines) return; + if (id == null) { + if (current.pipelineId != null) { + _delegate.goTo(AppRoute.pipelines); + } + } else if (current.pipelineId != id) { + _delegate.goTo(AppRoute.pipeline(id)); + } + }, initialPipelineId: pipelinesRoute.pipelineId, initialVersion: pipelinesRoute.version, initialStageKey: pipelinesRoute.stageKey, diff --git a/app/lib/application/pipelines_destination.dart b/app/lib/application/pipelines_destination.dart index 9cc0974c..2321984e 100644 --- a/app/lib/application/pipelines_destination.dart +++ b/app/lib/application/pipelines_destination.dart @@ -21,6 +21,7 @@ class PipelinesDestination extends StatelessWidget { this.onRunStarted, this.onViewPipelineRuns, this.onOpenSchedules, + this.onSelectionChanged, this.initialPipelineId, this.initialVersion = 0, this.initialStageKey, @@ -38,6 +39,7 @@ class PipelinesDestination extends StatelessWidget { final ValueChanged? onRunStarted; final ValueChanged? onViewPipelineRuns; final VoidCallback? onOpenSchedules; + final ValueChanged? onSelectionChanged; /// The pipeline and pinned version a deep link names. final int? initialPipelineId; @@ -84,6 +86,7 @@ class PipelinesDestination extends StatelessWidget { onRunStarted: onRunStarted, onViewPipelineRuns: onViewPipelineRuns, onOpenSchedules: onOpenSchedules, + onSelectionChanged: onSelectionChanged, initialPipelineId: initialPipelineId, initialVersion: initialVersion, initialStageKey: initialStageKey, diff --git a/app/lib/features/pipelines/screen.dart b/app/lib/features/pipelines/screen.dart index 0c5b8e1f..413f8b09 100644 --- a/app/lib/features/pipelines/screen.dart +++ b/app/lib/features/pipelines/screen.dart @@ -34,6 +34,7 @@ class PipelinesScreen extends StatefulWidget { this.syncToken = 0, this.onRunStarted, this.onViewPipelineRuns, + this.onSelectionChanged, this.onOpenSchedules, this.initialPipelineId, this.initialVersion = 0, @@ -57,6 +58,10 @@ class PipelinesScreen extends StatefulWidget { final ValueChanged? onRunStarted; final ValueChanged? onViewPipelineRuns; + /// Reports the open pipeline (null for the list) so the route, and with it + /// Back, follows what is shown. + final ValueChanged? onSelectionChanged; + /// Opens every schedule; shown in the bar while the list is visible. final VoidCallback? onOpenSchedules; @@ -105,6 +110,17 @@ class _PipelinesScreenState extends State { // The detail read owns its own failure state; the list read continues. _controller.openPipeline(id, version: widget.initialVersion); } + _reported = _controller.selectedId; + _controller.addListener(_reportSelection); + } + + int? _reported; + + void _reportSelection() { + final id = _controller.selectedId; + if (id == _reported) return; + _reported = id; + widget.onSelectionChanged?.call(id); } @override @@ -113,10 +129,15 @@ class _PipelinesScreenState extends State { if (oldWidget.gateway != widget.gateway || oldWidget.endpoint != widget.endpoint) { _controller.dispose(); - _controller = PipelinesController( - PipelinesRepository(widget.gateway), - pendingRunStore: SharedPreferencesPendingRunStore(widget.endpoint), - )..load(); + _controller = + PipelinesController( + PipelinesRepository(widget.gateway), + pendingRunStore: SharedPreferencesPendingRunStore( + widget.endpoint, + ), + ) + ..load() + ..addListener(_reportSelection); } else if (oldWidget.syncToken != widget.syncToken) { // The socket was replaced; re-read through the existing controller so the // selected pipeline and requested version survive the reconnect. @@ -129,7 +150,12 @@ class _PipelinesScreenState extends State { final id = widget.initialPipelineId; if (id == null) { _controller.clearSelection(); - } else if (!_isRoutePin(_controller.detail)) { + } else if (!(_controller.selectedId == id && + // The route caught up with a pipeline opened from the list. + ((oldWidget.initialPipelineId != id && + widget.initialVersion <= 0) || + _controller.selectedVersion == widget.initialVersion)) && + !_isRoutePin(_controller.detail)) { _controller.openPipeline(id, version: widget.initialVersion); } } diff --git a/app/test/application/pipelines_app_test.dart b/app/test/application/pipelines_app_test.dart index d9475fc4..93e6f288 100644 --- a/app/test/application/pipelines_app_test.dart +++ b/app/test/application/pipelines_app_test.dart @@ -1,5 +1,6 @@ import 'dart:convert'; +import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/application/app_route.dart'; @@ -169,6 +170,65 @@ void main() { expect(find.text('Deep-linked run'), findsWidgets); }); + testWidgets('Android Back on a wide screen steps out of a run, not the app', ( + tester, + ) async { + tester.view.physicalSize = const Size(1000, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final exits = []; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + if (call.method == 'SystemNavigator.pop') exits.add(call.method); + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + final provider = PlatformRouteInformationProvider( + initialRouteInformation: RouteInformation(uri: Uri.parse('/runs/1')), + ); + addTearDown(provider.dispose); + await pumpApp(tester, channel: channel, client: client, provider: provider); + await replyList( + tester, + channel, + runs: [ + {'id': 1, 'name': 'Deep-linked run', 'status': 'running'}, + ], + ); + await replyDetail(tester, channel, 1); + expect(provider.value.uri.path, '/runs/1'); + + // The system Back button or gesture. + await tester.binding.handlePopRoute(); + await tester.pump(); + expect(provider.value.uri.path, '/runs'); + expect(exits, isEmpty); + + // From the list, Back asks before leaving the app. + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + expect(find.text('Close Pipelines?'), findsOneWidget); + await tester.tap(find.byKey(const Key('app-exit-stay'))); + await tester.pumpAndSettle(); + expect(exits, isEmpty); + expect(provider.value.uri.path, '/runs'); + + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('app-exit-close'))); + await tester.pumpAndSettle(); + expect(exits, ['SystemNavigator.pop']); + }); + testWidgets('tabs and run selection update the route; browser Back pops it', ( tester, ) async {