Files
cutdex/lib/shared/widgets/error_notification_host.dart
lingjhf abc1868550
Gitea CI / Check code and tests (push) Successful in 6m37s
Gitea CI / Build Windows x64 app (push) Successful in 3m18s
Gitea CI / Build Android APK (push) Successful in 3m47s
Gitea CI / Audit and package Windows x64 (push) Successful in 1m7s
Gitea CI / Assemble and validate CI artifacts (push) Successful in 50s
Gitea CI / Gitea CI passed (push) Successful in 2s
Gitea Release / Prepare draft Release (push) Successful in 9s
Gitea Release / Upload Android to draft Release (push) Successful in 16s
Gitea Release / Upload Windows to draft Release (push) Successful in 22s
Gitea Release / Verify and publish Release (push) Successful in 14s
feat(workspace): 桌面工作区、主题与交互更新,发布 0.1.2
2026-10-08 18:17:12 +00:00

288 lines
8.7 KiB
Dart

import 'dart:async';
import 'dart:collection';
import 'package:cutdex_ui/icons.dart';
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})
: isError = true,
actionLabel = null,
onAction = null;
const ErrorNotification.message({
required this.content,
this.actionLabel,
this.onAction,
}) : assert((actionLabel == null) == (onAction == null)),
details = null,
isError = false;
final Widget content;
final String? details;
final bool isError;
final String? actionLabel;
final VoidCallback? onAction;
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 notification queue above navigation and dialogs, independent of scaffolds.
class ErrorNotificationHost extends StatefulWidget {
const ErrorNotificationHost({super.key, required this.child});
final Widget child;
static ErrorNotificationHostState? maybeOf(BuildContext context) =>
context.findAncestorStateOfType<ErrorNotificationHostState>();
static ErrorNotificationHostState of(BuildContext context) =>
maybeOf(context)!;
@override
State<ErrorNotificationHost> createState() => ErrorNotificationHostState();
}
class ErrorNotificationHostState extends State<ErrorNotificationHost> {
late final OverlayEntry _entry = OverlayEntry(builder: _buildContent);
final _pending = Queue<ErrorNotification>();
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 showMessage({
required Widget content,
String? actionLabel,
VoidCallback? onAction,
}) => show(
ErrorNotification.message(
content: content,
actionLabel: actionLabel,
onAction: onAction,
),
);
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(Duration(seconds: _current!.isError ? 8 : 4), dismiss);
}
}
void _next() {
setState(() {
_current = _pending.isEmpty ? null : _pending.removeFirst();
_copied = false;
_hovered = false;
});
_startTimer();
}
void dismiss() {
_timer?.cancel();
_next();
}
void clear() {
_timer?.cancel();
_pending.clear();
setState(() => _current = null);
}
Future<void> _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: Key(
current.isError
? 'global-error-notification'
: 'global-message-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(
current.isError ? AppIcons.error : AppIcons.success,
color: current.isError
? Theme.of(context).colorScheme.error
: Theme.of(context).colorScheme.primary,
size: 20,
),
const SizedBox(width: 8),
Expanded(
child: ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 180),
child: SingleChildScrollView(
child: current.content,
),
),
),
if (current.actionLabel case final label?)
TextButton(
onPressed: () {
dismiss();
current.onAction!();
},
child: Text(label),
),
if (current.isError)
IconButton(
key: const Key('copy-error-button'),
tooltip: MaterialLocalizations.of(context)
.copyButtonLabel,
onPressed: _copy,
icon: Icon(
_copied ? AppIcons.check : AppIcons.copy,
size: 18,
),
),
IconButton(
key: Key(
current.isError
? 'close-error-button'
: 'close-message-button',
),
tooltip: MaterialLocalizations.of(context)
.closeButtonTooltip,
onPressed: dismiss,
icon: const Icon(AppIcons.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<ErrorFailureListener> createState() => _ErrorFailureListenerState();
}
class _ErrorFailureListenerState extends State<ErrorFailureListener> {
@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();
}