import 'package:flutter/material.dart'; import 'action_refusal.dart'; import 'cancel_wording.dart'; /// Sends the confirmed cancellation. Returns null once the server has accepted /// it, or an [ActionRefusal] carrying the server's words verbatim; the prompt /// then stays open with dismissal available immediately. typedef CancelSubmit = Future Function(); /// Opens the native cancel confirmation for [runId]. /// /// Nothing is sent until the operator presses the confirm action, and the /// dismiss action (`Keep`) only closes the prompt. Future showCancelRunPrompt({ required BuildContext context, required num runId, required CancelSubmit onSubmit, }) { final prompt = _CancelPrompt(runId: runId, onSubmit: onSubmit); return showDialog( context: context, barrierDismissible: false, builder: (_) => prompt, ); } class _CancelPrompt extends StatefulWidget { const _CancelPrompt({required this.runId, required this.onSubmit}); final num runId; final CancelSubmit onSubmit; @override State<_CancelPrompt> createState() => _CancelPromptState(); } class _CancelPromptState extends State<_CancelPrompt> { bool _sending = false; bool _checking = false; bool _blocked = false; String? _error; void _keep() { if (!_sending) Navigator.of(context).pop(); } Future _confirm() async { if (_sending || _checking || _blocked) return; setState(() { _sending = true; _error = null; }); final refusal = await widget.onSubmit(); if (!mounted) return; if (refusal == null) { Navigator.of(context).pop(); return; } final check = refusal.stillPossible; setState(() { _sending = false; _error = refusal.message; _checking = check != null; }); if (check == null) return; bool? stillPossible; try { stillPossible = await check; } catch (_) { // The action reports re-read failures as null; never fabricate one here. } if (!mounted) return; setState(() { _checking = false; _blocked = stillPossible == false; }); } @override Widget build(BuildContext context) { return PopScope(canPop: !_sending, child: _material(context)); } bool get _confirmDisabled => _sending || _checking || _blocked; Widget _material(BuildContext context) { final theme = Theme.of(context); return AlertDialog( scrollable: true, title: Text(cancelDialogTitle(widget.runId)), content: _body(errorStyle: TextStyle(color: theme.colorScheme.error)), actions: [ TextButton( key: cancelKeepKey, onPressed: _sending ? null : _keep, child: const Text(cancelKeepLabel), ), FilledButton( key: cancelConfirmKey, onPressed: _confirmDisabled ? null : _confirm, child: const Text(cancelConfirmLabel), ), ], ); } Widget _body({required TextStyle errorStyle}) { return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ const Text(cancelDialogMessage), if (_error case final error?) Padding( padding: const EdgeInsets.only(top: 8), child: Text(error, key: cancelErrorKey, style: errorStyle), ), ], ); } }