LCOV - code coverage report
Current view: top level - components/toast - foss_toaster.dart Coverage Total Hit
Test: fossui coverage Lines: 100.0 % 189 189
Test Date: 2026-11-29 09:15:47 Functions: - 0 0

            Line data    Source code
       1              : import 'dart:async' show unawaited;
       2              : 
       3              : import 'package:flutter/semantics.dart' show Assertiveness, SemanticsService;
       4              : import 'package:flutter/widgets.dart';
       5              : import 'package:fossui/src/components/spinner/foss_spinner.dart';
       6              : import 'package:fossui/src/components/toast/foss_toast.dart';
       7              : import 'package:fossui/src/components/toast/foss_toast_controller.dart';
       8              : import 'package:fossui/src/icons/foss_glyph.dart';
       9              : import 'package:fossui/src/theme/colors/foss_colors.dart';
      10              : import 'package:fossui/src/theme/foss_theme.dart';
      11              : import 'package:fossui/src/theme/typography/foss_typography.dart';
      12              : 
      13              : /// Maximum width of a toast surface in logical pixels.
      14              : const double _maxWidth = 360;
      15              : 
      16              : /// The leading glyph extent. Centered in a box as tall as the first text line
      17              : /// so it lands on that line rather than the top of the row.
      18              : const double _iconSize = 16;
      19              : 
      20              : /// The slide curve for a toast entering or leaving.
      21              : const Cubic _slideCurve = Cubic(0.22, 1, 0.36, 1);
      22              : 
      23              : /// How much each rear card in the pile shrinks per step behind the front.
      24              : const double _rearScaleStep = 0.1;
      25              : 
      26              : /// Depth tint blended over the popover fill per rear card index, so the cards
      27              : /// behind read as set back. Light darkens gently; dark leans harder to stay
      28              : /// legible against the near-black surface.
      29              : const double _rearDarkenLight = 0.01;
      30              : const double _rearDarkenDark = 0.06;
      31              : 
      32              : /// Shares a [FossToastController] with the subtree. Read it with
      33              : /// [FossToastScope.of]; provided by a [FossToaster].
      34              : class FossToastScope extends InheritedNotifier<FossToastController> {
      35              :   /// Creates the scope around [child], backed by [controller].
      36            2 :   const FossToastScope({
      37              :     required FossToastController controller,
      38              :     required super.child,
      39              :     super.key,
      40            2 :   }) : super(notifier: controller);
      41              : 
      42              :   /// The nearest controller above [context]. Throws when no [FossToaster] is an
      43              :   /// ancestor.
      44            2 :   static FossToastController of(BuildContext context) {
      45            2 :     final scope = context.dependOnInheritedWidgetOfExactType<FossToastScope>();
      46            2 :     if (scope?.notifier case final controller?) return controller;
      47            1 :     throw FlutterError(
      48              :       'showFossToast requires a FossToaster ancestor in the widget tree.',
      49              :     );
      50              :   }
      51              : }
      52              : 
      53              : /// {@category Overlays}
      54              : /// Hosts transient toasts over its [child]. Mount it once near the app root,
      55              : /// above everything that needs to raise a toast.
      56              : ///
      57              : /// ```dart
      58              : /// FossToaster(child: MyApp());
      59              : /// ```
      60              : class FossToaster extends StatefulWidget {
      61              :   /// Creates a toaster around [child].
      62            2 :   const FossToaster({required this.child, super.key});
      63              : 
      64              :   /// The app subtree below the toasts.
      65              :   final Widget child;
      66              : 
      67            2 :   @override
      68            2 :   State<FossToaster> createState() => _FossToasterState();
      69              : }
      70              : 
      71              : class _FossToasterState extends State<FossToaster> {
      72              :   final FossToastController _controller = FossToastController();
      73              : 
      74            2 :   @override
      75              :   void dispose() {
      76            4 :     _controller.dispose();
      77            2 :     super.dispose();
      78              :   }
      79              : 
      80            2 :   @override
      81              :   Widget build(BuildContext context) {
      82            2 :     return FossToastScope(
      83            2 :       controller: _controller,
      84            2 :       child: Stack(
      85              :         textDirection: TextDirection.ltr,
      86            2 :         children: [
      87            4 :           widget.child,
      88            2 :           Positioned(
      89              :             left: 0,
      90              :             right: 0,
      91              :             bottom: 0,
      92            4 :             child: _ToastViewport(controller: _controller),
      93              :           ),
      94              :         ],
      95              :       ),
      96              :     );
      97              :   }
      98              : }
      99              : 
     100              : /// A handle to a raised toast, returned by [showFossToast]. Holds the toast's
     101              : /// id and its toaster so the caller can [dismiss] it early or [update] its
     102              : /// message without threading a [BuildContext] back in.
     103              : ///
     104              : /// ```dart
     105              : /// final toast = showFossToast(context, const FossToast(
     106              : ///   variant: FossToastVariant.loading,
     107              : ///   title: Text('Saving'),
     108              : /// ));
     109              : /// await save();
     110              : /// toast.update(const FossToast(
     111              : ///   variant: FossToastVariant.success,
     112              : ///   title: Text('Saved'),
     113              : /// ));
     114              : /// ```
     115              : class FossToastHandle {
     116            2 :   const FossToastHandle._(this._controller, this._id);
     117              : 
     118              :   final FossToastController _controller;
     119              :   final int _id;
     120              : 
     121              :   /// Removes the toast now. A no-op once it has already left the screen.
     122            4 :   void dismiss() => _controller.dismiss(_id);
     123              : 
     124              :   /// Replaces the toast's message in place and restarts its timer, the
     125              :   /// loading-to-status flip. A no-op once the toast is gone.
     126            4 :   void update(FossToast toast) => _controller.update(_id, toast);
     127              : }
     128              : 
     129              : /// Raises [toast] on the nearest [FossToaster] and returns a [FossToastHandle]
     130              : /// to dismiss or update it.
     131            2 : FossToastHandle showFossToast(BuildContext context, FossToast toast) {
     132            2 :   final controller = FossToastScope.of(context);
     133            4 :   return FossToastHandle._(controller, controller.show(toast));
     134              : }
     135              : 
     136              : class _ToastViewport extends StatefulWidget {
     137            2 :   const _ToastViewport({required this.controller});
     138              : 
     139              :   final FossToastController controller;
     140              : 
     141            2 :   @override
     142            2 :   State<_ToastViewport> createState() => _ToastViewportState();
     143              : }
     144              : 
     145              : class _ToastViewportState extends State<_ToastViewport> {
     146              :   // A stable key per toast id, so a card keeps its element (and its running
     147              :   // animations) as it moves forward through the pile, even as it changes from a
     148              :   // filled rear into the sizing front. Without this the promotion would remount
     149              :   // and replay the entrance, which reads as a flicker.
     150              :   final Map<int, GlobalKey> _keys = <int, GlobalKey>{};
     151              : 
     152            6 :   GlobalKey _keyFor(int id) => _keys.putIfAbsent(id, GlobalKey.new);
     153              : 
     154            2 :   @override
     155              :   Widget build(BuildContext context) {
     156            4 :     final sp = context.fossTheme.spacing;
     157            4 :     final controller = widget.controller;
     158            2 :     return ListenableBuilder(
     159              :       listenable: controller,
     160            2 :       builder: (context, _) {
     161            2 :         final entries = controller.entries;
     162           14 :         _keys.removeWhere((id, _) => entries.every((e) => e.id != id));
     163            4 :         final visible = entries.length > FossToastController.maxVisible
     164            3 :             ? entries.sublist(entries.length - FossToastController.maxVisible)
     165              :             : entries;
     166            2 :         if (visible.isEmpty) return const SizedBox.shrink();
     167            2 :         final front = visible.last;
     168              : 
     169            4 :         Widget cardFor(FossToastEntry entry, int depth) => _PileToast(
     170            4 :           key: _keyFor(entry.id),
     171            2 :           toast: entry.toast,
     172              :           depth: depth,
     173            2 :           peek: sp(3),
     174            3 :           onDismiss: () => controller.dismiss(entry.id),
     175            2 :           onPressChange: (pressed) =>
     176            4 :               controller.setPressed(entry.id, pressed: pressed),
     177              :         );
     178              : 
     179            2 :         return SafeArea(
     180            2 :           child: Padding(
     181            4 :             padding: EdgeInsets.all(sp(4)),
     182            2 :             child: Stack(
     183              :               alignment: Alignment.bottomCenter,
     184              :               clipBehavior: Clip.none,
     185            2 :               children: [
     186              :                 // The cards behind fill the front's box so they share its size;
     187              :                 // the newest is the non-positioned front that sizes the stack
     188              :                 // and paints on top.
     189            7 :                 for (var p = 0; p < visible.length - 1; p++)
     190            1 :                   Positioned.fill(
     191            5 :                     child: cardFor(visible[p], visible.length - 1 - p),
     192              :                   ),
     193            2 :                 cardFor(front, 0),
     194              :               ],
     195              :             ),
     196              :           ),
     197              :         );
     198              :       },
     199              :     );
     200              :   }
     201              : }
     202              : 
     203              : /// One card in the toast pile, placed by [depth] (0 is the front): scaling down
     204              : /// and lifting by [peek] per step, so the cards behind peek out by a uniform
     205              : /// sliver. Only the front shows its content and takes input; the same element
     206              : /// carries a toast from the back to the front, so a promotion animates rather
     207              : /// than remounting.
     208              : class _PileToast extends StatefulWidget {
     209            2 :   const _PileToast({
     210              :     required this.toast,
     211              :     required this.depth,
     212              :     required this.peek,
     213              :     required this.onDismiss,
     214              :     required this.onPressChange,
     215              :     super.key,
     216              :   });
     217              : 
     218              :   final FossToast toast;
     219              :   final int depth;
     220              :   final double peek;
     221              :   final VoidCallback onDismiss;
     222              :   final ValueChanged<bool> onPressChange;
     223              : 
     224            2 :   @override
     225            2 :   State<_PileToast> createState() => _PileToastState();
     226              : }
     227              : 
     228              : class _PileToastState extends State<_PileToast> {
     229              :   bool _shown = false;
     230              :   bool _dismissed = false;
     231              : 
     232            8 :   bool get _isFront => widget.depth == 0;
     233              : 
     234              :   // The front nests two Dismissibles; a diagonal fling can cross both
     235              :   // thresholds, so collapse the pair to a single dismiss.
     236            1 :   void _dismiss() {
     237            1 :     if (_dismissed) return;
     238            1 :     _dismissed = true;
     239            3 :     widget.onDismiss();
     240              :   }
     241              : 
     242            2 :   @override
     243              :   void initState() {
     244            2 :     super.initState();
     245              :     // A toast is always enqueued as the front, so its first frame runs the
     246              :     // entrance slide. A toast promoted from behind kept its element, so it
     247              :     // never reaches here again; its move forward rides the pile transform.
     248            6 :     WidgetsBinding.instance.addPostFrameCallback((_) {
     249            2 :       if (!mounted) return;
     250            6 :       setState(() => _shown = true);
     251              :       // Error toasts interrupt assertively; other types ride the surface's
     252              :       // polite live region. Only a plain-text message can be announced.
     253            8 :       if (widget.toast.variant == FossToastVariant.error) {
     254            3 :         final message = _announcement(widget.toast);
     255              :         if (message != null) {
     256            1 :           unawaited(
     257            1 :             SemanticsService.sendAnnouncement(
     258            2 :               View.of(context),
     259              :               message,
     260            2 :               Directionality.of(context),
     261              :               assertiveness: Assertiveness.assertive,
     262              :             ),
     263              :           );
     264              :         }
     265              :       }
     266              :     });
     267              :   }
     268              : 
     269            2 :   @override
     270              :   Widget build(BuildContext context) {
     271            2 :     final theme = context.fossTheme;
     272              :     final reduceMotion =
     273            4 :         MediaQuery.maybeOf(context)?.disableAnimations ?? false;
     274            4 :     final duration = reduceMotion ? Duration.zero : theme.motion.toast;
     275            2 :     final shown = reduceMotion || _shown;
     276            4 :     final depth = widget.depth;
     277              : 
     278              :     // The front carries the message and sizes the stack; the cards behind are
     279              :     // blank surfaces filling that box, so the pile shows one toast over a set
     280              :     // back stack and a promotion reveals the message without a second surface.
     281            2 :     Widget card = _isFront
     282            6 :         ? _ToastSurface(toast: widget.toast)
     283            1 :         : _RearSurface(depth: depth);
     284              : 
     285              :     // A press holds the toast open; the countdown resumes on release. The raw
     286              :     // pointer listener fires on down regardless of the gesture arena.
     287            2 :     card = Listener(
     288              :       behavior: HitTestBehavior.opaque,
     289            8 :       onPointerDown: (_) => widget.onPressChange(true),
     290            4 :       onPointerUp: (_) => widget.onPressChange(false),
     291            4 :       onPointerCancel: (_) => widget.onPressChange(false),
     292              :       child: card,
     293              :     );
     294              : 
     295              :     // Entrance: a newly enqueued front slides up and fades in.
     296            2 :     card = AnimatedSlide(
     297              :       offset: shown ? Offset.zero : const Offset(0, 0.5),
     298              :       duration: duration,
     299              :       curve: _slideCurve,
     300            2 :       child: AnimatedOpacity(
     301              :         opacity: shown ? 1 : 0,
     302              :         duration: duration,
     303              :         child: card,
     304              :       ),
     305              :     );
     306              : 
     307              :     // Pile placement, animated so a change of depth glides between positions.
     308            2 :     card = AnimatedScale(
     309            4 :       scale: 1 - _rearScaleStep * depth,
     310              :       alignment: Alignment.topCenter,
     311              :       duration: duration,
     312              :       curve: _slideCurve,
     313              :       child: card,
     314              :     );
     315            2 :     card = AnimatedContainer(
     316              :       duration: duration,
     317              :       curve: _slideCurve,
     318           10 :       transform: Matrix4.translationValues(0, -widget.peek * depth, 0),
     319              :       child: card,
     320              :     );
     321              : 
     322              :     // Only the front takes input and is read out; the rest peek behind it.
     323            4 :     card = IgnorePointer(ignoring: !_isFront, child: card);
     324            4 :     card = ExcludeSemantics(excluding: !_isFront, child: card);
     325              : 
     326              :     // A single Dismissible tracks one axis, so a horizontal one nests over a
     327              :     // downward one to let the front be flung left, right, or down. The
     328              :     // directions relax to none behind the front, keeping the tree shape stable
     329              :     // across a promotion so no element is torn down.
     330            2 :     return Dismissible(
     331              :       key: const ValueKey<String>('foss-toast-h'),
     332            2 :       direction: _isFront ? DismissDirection.horizontal : DismissDirection.none,
     333              :       resizeDuration: null,
     334            2 :       onDismissed: (_) => _dismiss(),
     335            2 :       child: Dismissible(
     336              :         key: const ValueKey<String>('foss-toast-v'),
     337            2 :         direction: _isFront ? DismissDirection.down : DismissDirection.none,
     338              :         resizeDuration: null,
     339            2 :         onDismissed: (_) => _dismiss(),
     340              :         child: card,
     341              :       ),
     342              :     );
     343              :   }
     344              : }
     345              : 
     346              : /// A blank surface for a toast behind the front. It fills the front's box, and
     347              : /// its [_PileToast] scales and lifts it by [depth] to peek out; the fill
     348              : /// darkens by depth so the pile reads as one message over a set-back stack.
     349              : class _RearSurface extends StatelessWidget {
     350            1 :   const _RearSurface({required this.depth});
     351              : 
     352              :   final int depth;
     353              : 
     354            1 :   @override
     355              :   Widget build(BuildContext context) {
     356            1 :     final theme = context.fossTheme;
     357            1 :     final colors = theme.colors;
     358            1 :     return DecoratedBox(
     359            1 :       decoration: _toastDecoration(
     360              :         theme,
     361            1 :         fill: Color.alphaBlend(
     362            2 :           colors.foreground.withValues(
     363            3 :             alpha: (colors.isDark ? _rearDarkenDark : _rearDarkenLight) * depth,
     364              :           ),
     365            1 :           colors.popover,
     366              :         ),
     367            1 :         border: colors.border,
     368            2 :         radius: theme.radii.lg,
     369              :       ),
     370              :     );
     371              :   }
     372              : }
     373              : 
     374              : /// The front toast surface: the superelliptical card, its leading glyph, and
     375              : /// its title, description, and action.
     376              : class _ToastSurface extends StatelessWidget {
     377            2 :   const _ToastSurface({required this.toast});
     378              : 
     379              :   final FossToast toast;
     380              : 
     381            2 :   @override
     382              :   Widget build(BuildContext context) {
     383            2 :     final theme = context.fossTheme;
     384            2 :     final colors = theme.colors;
     385            2 :     final sp = theme.spacing;
     386            4 :     final s = toast.style;
     387              : 
     388            6 :     final titleStyle = theme.typography.sm.medium
     389            2 :         .copyWith(
     390            2 :           color: colors.popoverForeground,
     391              :           decoration: TextDecoration.none,
     392              :         )
     393            3 :         .merge(s?.titleStyle);
     394            4 :     final descriptionStyle = theme.typography.sm
     395            2 :         .copyWith(
     396            2 :           color: colors.mutedForeground,
     397              :           decoration: TextDecoration.none,
     398              :         )
     399            3 :         .merge(s?.descriptionStyle);
     400              : 
     401           10 :     final leading = toast.icon ?? _leadingFor(toast.variant, colors);
     402              :     // The leading box matches the first text line's height so the glyph centers
     403              :     // on the line instead of top-aligning to the row.
     404            4 :     final firstLineStyle = toast.title != null ? titleStyle : descriptionStyle;
     405              :     final leadingBox =
     406            6 :         (firstLineStyle.fontSize ?? 14) * (firstLineStyle.height ?? 1);
     407              : 
     408            2 :     return Semantics(
     409              :       // Non-error toasts announce politely through the live region; an error is
     410              :       // announced assertively from initState, so it stays off the live region
     411              :       // to avoid a double read.
     412            6 :       liveRegion: toast.variant != FossToastVariant.error,
     413              :       container: true,
     414            2 :       child: DefaultTextStyle(
     415            6 :         style: theme.typography.sm.copyWith(
     416            2 :           color: colors.popoverForeground,
     417              :           decoration: TextDecoration.none,
     418              :         ),
     419            2 :         child: ConstrainedBox(
     420              :           constraints: const BoxConstraints(maxWidth: _maxWidth),
     421            2 :           child: DecoratedBox(
     422            2 :             decoration: _toastDecoration(
     423              :               theme,
     424            3 :               fill: s?.backgroundColor ?? colors.popover,
     425            3 :               border: s?.borderColor ?? colors.border,
     426            5 :               radius: s?.borderRadius ?? theme.radii.lg,
     427              :             ),
     428            2 :             child: Padding(
     429            2 :               padding: EdgeInsets.symmetric(
     430            2 :                 horizontal: sp(3.5),
     431            2 :                 vertical: sp(3),
     432              :               ),
     433            2 :               child: Row(
     434              :                 crossAxisAlignment: CrossAxisAlignment.start,
     435            2 :                 spacing: sp(2),
     436            2 :                 children: [
     437              :                   if (leading != null)
     438            2 :                     SizedBox(
     439              :                       width: _iconSize,
     440              :                       height: leadingBox,
     441            2 :                       child: Center(child: leading),
     442              :                     ),
     443            2 :                   Expanded(
     444            2 :                     child: Column(
     445              :                       crossAxisAlignment: CrossAxisAlignment.start,
     446              :                       mainAxisSize: MainAxisSize.min,
     447            2 :                       spacing: sp(0.5),
     448            2 :                       children: [
     449            4 :                         if (toast.title case final title?)
     450            2 :                           DefaultTextStyle.merge(
     451              :                             style: titleStyle,
     452              :                             child: title,
     453              :                           ),
     454            4 :                         if (toast.description case final description?)
     455            1 :                           DefaultTextStyle.merge(
     456              :                             style: descriptionStyle,
     457              :                             child: description,
     458              :                           ),
     459              :                       ],
     460              :                     ),
     461              :                   ),
     462            4 :                   ?toast.action,
     463              :                 ],
     464              :               ),
     465              :             ),
     466              :           ),
     467              :         ),
     468              :       ),
     469              :     );
     470              :   }
     471              : }
     472              : 
     473              : /// The shared toast surface decoration: a superelliptical border over [fill]
     474              : /// with the large shadow. Used by the front toast and each rear pile card so
     475              : /// their shapes stay in lockstep.
     476            2 : ShapeDecoration _toastDecoration(
     477              :   FossThemeData theme, {
     478              :   required Color fill,
     479              :   required Color border,
     480              :   required double radius,
     481              : }) {
     482            2 :   return ShapeDecoration(
     483              :     color: fill,
     484            2 :     shape: RoundedSuperellipseBorder(
     485            2 :       side: BorderSide(color: border),
     486            2 :       borderRadius: BorderRadius.circular(radius),
     487              :     ),
     488            4 :     shadows: theme.shadows.lg,
     489              :   );
     490              : }
     491              : 
     492              : /// The plain-text message of [toast] for an assertive announcement: the title
     493              : /// then the description, taken from simple [Text] widgets. Null when neither is
     494              : /// plain text, since a rich widget carries no string to announce.
     495            1 : String? _announcement(FossToast toast) {
     496            3 :   String? textOf(Widget? widget) => widget is Text ? widget.data : null;
     497            1 :   final parts = <String>[
     498            2 :     ?textOf(toast.title),
     499            2 :     ?textOf(toast.description),
     500              :   ];
     501            2 :   return parts.isEmpty ? null : parts.join('. ');
     502              : }
     503              : 
     504              : /// The default leading slot for [type], or null for [FossToastVariant.neutral].
     505            2 : Widget? _leadingFor(FossToastVariant type, FossColors colors) {
     506              :   switch (type) {
     507            2 :     case FossToastVariant.neutral:
     508              :       return null;
     509            2 :     case FossToastVariant.loading:
     510            2 :       return FossSpinner(size: _iconSize, color: colors.mutedForeground);
     511            2 :     case FossToastVariant.info:
     512            2 :       return FossGlyphIcon(
     513            4 :         InfoGlyph(colors.info),
     514              :         size: _iconSize,
     515              :         semanticLabel: 'info',
     516              :       );
     517            1 :     case FossToastVariant.success:
     518            1 :       return FossGlyphIcon(
     519            2 :         SuccessGlyph(colors.success),
     520              :         size: _iconSize,
     521              :         semanticLabel: 'success',
     522              :       );
     523            1 :     case FossToastVariant.warning:
     524            1 :       return FossGlyphIcon(
     525            2 :         WarningGlyph(colors.warning),
     526              :         size: _iconSize,
     527              :         semanticLabel: 'warning',
     528              :       );
     529            1 :     case FossToastVariant.error:
     530            1 :       return FossGlyphIcon(
     531            2 :         ErrorGlyph(colors.destructive),
     532              :         size: _iconSize,
     533              :         semanticLabel: 'error',
     534              :       );
     535              :   }
     536              : }
        

Generated by: LCOV version 2.0-1