import 'dart:async'; import 'dart:collection'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../../errors/app_failure.dart'; import '../../l10n/l10n.dart'; class ErrorNotification { const ErrorNotification({required this.content, this.details}); final Widget content; final String? details; String get copyText { String textOf(Widget widget) { if (widget is Text) { return widget.data ?? widget.textSpan?.toPlainText() ?? ''; } if (widget is SingleChildScrollView && widget.child != null) { return textOf(widget.child!); } if (widget is SingleChildRenderObjectWidget && widget.child != null) { return textOf(widget.child!); } return ''; } final message = textOf(content); return details == null || details!.isEmpty || details == message ? message : '$message\n\n$details'; } } /// One error queue above navigation and dialogs, independent of local scaffolds. class ErrorNotificationHost extends StatefulWidget { const ErrorNotificationHost({super.key, required this.child}); final Widget child; static ErrorNotificationHostState? maybeOf(BuildContext context) => context.findAncestorStateOfType(); static ErrorNotificationHostState of(BuildContext context) => maybeOf(context)!; @override State createState() => ErrorNotificationHostState(); } class ErrorNotificationHostState extends State { late final OverlayEntry _entry = OverlayEntry(builder: _buildContent); final _pending = Queue(); ErrorNotification? _current; Timer? _timer; bool _copied = false; bool _hovered = false; void show(ErrorNotification notification) { if (!mounted) return; _pending.add(notification); if (_current == null) _next(); } void showFailure(AppFailure failure, String message) => show( ErrorNotification( content: Text(message), details: [ 'code: ${failure.code.name}', if (failure.httpStatusCode != null) 'HTTP: ${failure.httpStatusCode}', if (failure.diagnostic != null) failure.diagnostic!, ].join('\n'), ), ); void _startTimer() { _timer?.cancel(); if (_current != null && !_hovered) { _timer = Timer(const Duration(seconds: 8), dismiss); } } void _next() { setState(() { _current = _pending.isEmpty ? null : _pending.removeFirst(); _copied = false; }); _startTimer(); } void dismiss() { _timer?.cancel(); _next(); } void clear() { _timer?.cancel(); _pending.clear(); setState(() => _current = null); } Future _copy() async { final current = _current; if (current == null) return; try { await Clipboard.setData(ClipboardData(text: current.copyText)); if (mounted && identical(current, _current)) { setState(() => _copied = true); _startTimer(); } } catch (_) { // Keep the error visible so the user can retry copying. _timer?.cancel(); } } @override void dispose() { _timer?.cancel(); super.dispose(); } @override Widget build(BuildContext context) { _entry.markNeedsBuild(); return Overlay(initialEntries: [_entry]); } Widget _buildContent(BuildContext context) => Stack( fit: StackFit.expand, children: [ widget.child, if (_current case final current?) Positioned( top: MediaQuery.paddingOf(context).top + 48, left: 12, right: 12, child: Align( alignment: Alignment.topCenter, child: MouseRegion( onEnter: (_) { _hovered = true; _timer?.cancel(); }, onExit: (_) { _hovered = false; _startTimer(); }, child: Material( key: const Key('global-error-notification'), elevation: 8, color: Theme.of(context).colorScheme.surfaceContainerHigh, borderRadius: BorderRadius.circular(12), clipBehavior: Clip.antiAlias, child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 520), child: Padding( padding: const EdgeInsets.fromLTRB(12, 8, 4, 8), child: Semantics( liveRegion: true, child: Row( children: [ Icon( Icons.error_outline, color: Theme.of(context).colorScheme.error, size: 20, ), const SizedBox(width: 8), Expanded( child: ConstrainedBox( constraints: const BoxConstraints(maxHeight: 180), child: SingleChildScrollView( child: current.content, ), ), ), IconButton( key: const Key('copy-error-button'), tooltip: MaterialLocalizations.of(context) .copyButtonLabel, onPressed: _copy, icon: Icon( _copied ? Icons.check : Icons.copy, size: 18, ), ), IconButton( key: const Key('close-error-button'), tooltip: MaterialLocalizations.of(context) .closeButtonTooltip, onPressed: dismiss, icon: const Icon(Icons.close, size: 18), ), ], ), ), ), ), ), ), ), ), ], ); } /// Publishes a changed structured failure after the current build completes. class ErrorFailureListener extends StatefulWidget { const ErrorFailureListener({super.key, required this.message}); final AppFailure? message; @override State createState() => _ErrorFailureListenerState(); } class _ErrorFailureListenerState extends State { @override void initState() { super.initState(); _schedule(); } @override void didUpdateWidget(covariant ErrorFailureListener oldWidget) { super.didUpdateWidget(oldWidget); if (widget.message != oldWidget.message) _schedule(); } void _schedule() { final message = widget.message; if (message == null) return; WidgetsBinding.instance.addPostFrameCallback((_) { if (!mounted) return; ErrorNotificationHost.maybeOf(context) ?.showFailure(message, context.l10n.failureMessage(message)); }); } @override Widget build(BuildContext context) => const SizedBox.shrink(); }