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

            Line data    Source code
       1              : import 'package:flutter/semantics.dart' show SemanticsRole;
       2              : import 'package:flutter/widgets.dart';
       3              : import 'package:fossui/src/components/toggle/foss_toggle.dart';
       4              : import 'package:fossui/src/foundation/foss_since.dart';
       5              : import 'package:fossui/src/theme/theme.dart';
       6              : 
       7              : part 'foss_toggle_group_style.dart';
       8              : 
       9              : /// Cell height of a joined outline bar, matching the toggle tap target so the
      10              : /// segments sit flush against the shared frame.
      11              : const double _cellHeight = 44;
      12              : 
      13              : /// One entry in a [FossToggleGroup]: a [value] id, an optional [leading] icon
      14              : /// and [child] label, and its own [enabled] flag. Its pressed state is derived
      15              : /// from the group selection, not stored here, so it is a plain configuration
      16              : /// object rather than a widget.
      17              : ///
      18              : /// A null [child] with a [leading] icon makes a square icon-only entry; name it
      19              : /// for assistive tech with [semanticLabel].
      20              : ///
      21              : /// ```dart
      22              : /// FossToggleGroupItem(
      23              : ///   value: 'bold',
      24              : ///   leading: const Icon(boldIcon),
      25              : ///   semanticLabel: 'Bold',
      26              : /// );
      27              : /// ```
      28              : @immutable
      29              : class FossToggleGroupItem {
      30              :   /// Creates a group entry. [value] identifies it within the group and must be
      31              :   /// unique among the group's items.
      32            1 :   const FossToggleGroupItem({
      33              :     required this.value,
      34              :     this.leading,
      35              :     this.child,
      36              :     this.semanticLabel,
      37              :     this.enabled = true,
      38              :   });
      39              : 
      40              :   /// The id this entry contributes to the group selection, compared by `==`.
      41              :   final String value;
      42              : 
      43              :   /// Optional widget before the label, themed as an icon. When [child] is null
      44              :   /// it is the sole content of a square icon-only entry.
      45              :   final Widget? leading;
      46              : 
      47              :   /// The label, typically a [Text]. Null makes a square icon-only entry.
      48              :   final Widget? child;
      49              : 
      50              :   /// Accessibility name, required in spirit for an icon-only entry.
      51              :   final String? semanticLabel;
      52              : 
      53              :   /// Whether this entry accepts input. Disabled when false or when the group is
      54              :   /// disabled.
      55              :   final bool enabled;
      56              : }
      57              : 
      58              : /// {@category Inputs}
      59              : /// {@template foss.toggleGroup.preview}
      60              : /// <img src="https://fossui.org/components/toggle-group/overview/light.png"
      61              : ///   alt="FossToggleGroup, light theme" width="480"
      62              : ///   style="max-width:100%;height:auto" />
      63              : /// <img src="https://fossui.org/components/toggle-group/overview/dark.png"
      64              : ///   alt="FossToggleGroup, dark theme" width="480"
      65              : ///   style="max-width:100%;height:auto" />
      66              : ///
      67              : /// See the
      68              : /// [toggle group documentation ↗](https://fossui.org/docs/components/toggle-group)
      69              : /// or try it live in the
      70              : /// [playground ↗](https://play.fossui.org/components/#/?path=components/toggle_group/fosstogglegroup/playground).
      71              : /// {@endtemplate}
      72              : ///
      73              : /// Binds a row or column of toggles to one shared selection. Each
      74              : /// [FossToggleGroupItem]'s pressed state is its membership in the group value,
      75              : /// and [variant] and [size] propagate to every item, so the toggles line up and
      76              : /// restyle together.
      77              : ///
      78              : /// Use [FossToggleGroup.single] for a one-of-many choice (a `String` value that
      79              : /// swaps, and clears to null when the active item is tapped again) or
      80              : /// [FossToggleGroup.multiple] for independent toggles (a `Set<String>`). In the
      81              : /// [FossToggleVariant.outline] variant the items join into one segmented bar
      82              : /// with a shared border and rounded outer ends; in
      83              : /// [FossToggleVariant.standard] they sit as separate buttons with a small gap.
      84              : ///
      85              : /// A null `onChanged` or `enabled: false` disables the whole group; an item
      86              : /// own `enabled: false` disables just that one. Colors, radius, and spacing
      87              : /// come from `context.fossTheme`; pass a [FossToggleGroupStyle] to [style] for
      88              : /// a one-off.
      89              : ///
      90              : /// {@macro foss.customize}
      91              : ///
      92              : /// See also [FossToggle] for a single two-state button.
      93              : ///
      94              : /// ```dart
      95              : /// FossToggleGroup.single(
      96              : ///   value: alignment,
      97              : ///   variant: FossToggleVariant.outline,
      98              : ///   onChanged: (v) => setState(() => alignment = v),
      99              : ///   children: const [
     100              : ///     FossToggleGroupItem(value: 'left', child: Text('Left')),
     101              : ///     FossToggleGroupItem(value: 'center', child: Text('Center')),
     102              : ///     FossToggleGroupItem(value: 'right', child: Text('Right')),
     103              : ///   ],
     104              : /// );
     105              : /// ```
     106              : @FossSince('0.1.1')
     107              : class FossToggleGroup extends StatelessWidget {
     108              :   /// {@macro foss.toggleGroup.preview}
     109              :   ///
     110              :   /// Creates a single-selection group. One item is on at a time; selecting
     111              :   /// another swaps it, and tapping the active item again clears it to null.
     112            1 :   const FossToggleGroup.single({
     113              :     required this.children,
     114              :     required String? value,
     115              :     required ValueChanged<String?> onChanged,
     116              :     this.variant = FossToggleVariant.standard,
     117              :     this.size = FossToggleSize.md,
     118              :     this.orientation = Axis.horizontal,
     119              :     this.enabled = true,
     120              :     this.style,
     121              :     super.key,
     122              :   }) : _single = true,
     123              :        _value = value,
     124              :        _onSingleChanged = onChanged,
     125              :        _values = const {},
     126              :        _onMultipleChanged = null;
     127              : 
     128              :   /// {@macro foss.toggleGroup.preview}
     129              :   ///
     130              :   /// Creates a multi-selection group. Items toggle independently in and out of
     131              :   /// the [value] set.
     132            1 :   const FossToggleGroup.multiple({
     133              :     required this.children,
     134              :     required Set<String> value,
     135              :     required ValueChanged<Set<String>> onChanged,
     136              :     this.variant = FossToggleVariant.standard,
     137              :     this.size = FossToggleSize.md,
     138              :     this.orientation = Axis.horizontal,
     139              :     this.enabled = true,
     140              :     this.style,
     141              :     super.key,
     142              :   }) : _single = false,
     143              :        _values = value,
     144              :        _onMultipleChanged = onChanged,
     145              :        _value = null,
     146              :        _onSingleChanged = null;
     147              : 
     148              :   /// The entries laid out and bound to the selection.
     149              :   final List<FossToggleGroupItem> children;
     150              : 
     151              :   /// The visual treatment, propagated to every item. Defaults to
     152              :   /// [FossToggleVariant.standard].
     153              :   final FossToggleVariant variant;
     154              : 
     155              :   /// The size, propagated to every item. Defaults to [FossToggleSize.md].
     156              :   final FossToggleSize size;
     157              : 
     158              :   /// The layout axis. Defaults to [Axis.horizontal].
     159              :   final Axis orientation;
     160              : 
     161              :   /// Whether the group accepts input. When false every item is disabled.
     162              :   final bool enabled;
     163              : 
     164              :   /// Per-instance overrides layered on the theme-resolved style.
     165              :   final FossToggleGroupStyle? style;
     166              : 
     167              :   final bool _single;
     168              :   final String? _value;
     169              :   final ValueChanged<String?>? _onSingleChanged;
     170              :   final Set<String> _values;
     171              :   final ValueChanged<Set<String>>? _onMultipleChanged;
     172              : 
     173            1 :   bool _isOn(FossToggleGroupItem item) =>
     174            7 :       _single ? _value == item.value : _values.contains(item.value);
     175              : 
     176            1 :   void _onToggle(FossToggleGroupItem item, {required bool on}) {
     177            1 :     if (_single) {
     178              :       // Tapping the active item clears the selection to null.
     179            3 :       _onSingleChanged?.call(on ? null : item.value);
     180              :       return;
     181              :     }
     182            2 :     final next = Set<String>.of(_values);
     183              :     if (on) {
     184            2 :       next.remove(item.value);
     185              :     } else {
     186            2 :       next.add(item.value);
     187              :     }
     188            2 :     _onMultipleChanged?.call(next);
     189              :   }
     190              : 
     191            1 :   @override
     192              :   Widget build(BuildContext context) {
     193              :     assert(
     194            9 :       children.map((c) => c.value).toSet().length == children.length,
     195              :       'FossToggleGroup item values must be unique; a duplicate makes two cells '
     196              :       'share selection state.',
     197              :     );
     198            1 :     final theme = context.fossTheme;
     199            2 :     final resolved = _GroupVisuals.resolve(theme, style);
     200            2 :     final outline = variant == FossToggleVariant.outline;
     201            1 :     final direction = Directionality.of(context);
     202            3 :     final radius = Radius.circular(theme.radii.lg);
     203            3 :     final last = children.length - 1;
     204              : 
     205            1 :     final items = <Widget>[
     206            4 :       for (var i = 0; i < children.length; i++)
     207            1 :         _item(
     208            2 :           children[i],
     209              :           outline: outline,
     210            1 :           corners: _cornerRadius(
     211              :             radius: radius,
     212            1 :             isFirst: i == 0,
     213            1 :             isLast: i == last,
     214            1 :             orientation: orientation,
     215              :             direction: direction,
     216              :           ),
     217              :         ),
     218              :     ];
     219              : 
     220              :     Widget bar;
     221              :     if (outline) {
     222              :       // Join the cells into one bar with 1px seams; the shared frame rounds the
     223              :       // outer ends over the flush segments.
     224            1 :       final seamed = <Widget>[
     225            4 :         for (var i = 0; i < items.length; i++) ...[
     226            4 :           if (i > 0) _Seam(orientation: orientation, color: resolved.border),
     227            1 :           items[i],
     228              :         ],
     229              :       ];
     230            1 :       final joined = Flex(
     231            1 :         direction: orientation,
     232              :         mainAxisSize: MainAxisSize.min,
     233              :         crossAxisAlignment: CrossAxisAlignment.stretch,
     234              :         children: seamed,
     235              :       );
     236            1 :       bar = CustomPaint(
     237            1 :         foregroundPainter: _FramePainter(
     238            1 :           color: resolved.border,
     239            2 :           radius: theme.radii.lg,
     240              :         ),
     241              :         // Bound the cross axis so the seams and cells can stretch to a shared
     242              :         // extent even when the group sits in an unbounded slot (a scroll view).
     243            2 :         child: orientation == Axis.horizontal
     244            1 :             ? IntrinsicHeight(child: joined)
     245            1 :             : IntrinsicWidth(child: joined),
     246              :       );
     247              :     } else {
     248            1 :       bar = Flex(
     249            1 :         direction: orientation,
     250              :         mainAxisSize: MainAxisSize.min,
     251            1 :         spacing: resolved.gap,
     252              :         children: items,
     253              :       );
     254              :     }
     255              : 
     256            1 :     return Semantics(
     257              :       container: true,
     258              :       // A single-select group is a radio group; multiple-select has no matching
     259              :       // role, so it stays a bare container.
     260            1 :       role: _single ? SemanticsRole.radioGroup : SemanticsRole.none,
     261            1 :       child: FocusTraversalGroup(
     262            1 :         policy: WidgetOrderTraversalPolicy(),
     263              :         child: bar,
     264              :       ),
     265              :     );
     266              :   }
     267              : 
     268            1 :   Widget _item(
     269              :     FossToggleGroupItem item, {
     270              :     required bool outline,
     271              :     required BorderRadius corners,
     272              :   }) {
     273            1 :     final on = _isOn(item);
     274            2 :     final itemEnabled = enabled && item.enabled;
     275            1 :     return FossToggle(
     276              :       pressed: on,
     277            2 :       onPressedChanged: itemEnabled ? (_) => _onToggle(item, on: on) : null,
     278            1 :       variant: variant,
     279            1 :       size: size,
     280            1 :       leading: item.leading,
     281            1 :       semanticLabel: item.semanticLabel,
     282              :       style: outline
     283            1 :           ? FossToggleStyle(
     284              :               side: BorderSide.none,
     285              :               shadow: const [],
     286              :               cornerRadius: corners,
     287              :               minHeight: _cellHeight,
     288              :             )
     289              :           : null,
     290            1 :       child: item.child,
     291              :     );
     292              :   }
     293              : }
     294              : 
     295              : /// Resolves the joined-bar corners for an item at a position. A horizontal
     296              : /// group rounds along the reading axis and mirrors under RTL; a vertical group
     297              : /// rounds top to bottom. The first item rounds its leading corners, the last
     298              : /// its trailing corners, and the middle items stay square.
     299            1 : BorderRadius _cornerRadius({
     300              :   required Radius radius,
     301              :   required bool isFirst,
     302              :   required bool isLast,
     303              :   required Axis orientation,
     304              :   required TextDirection direction,
     305              : }) {
     306            1 :   if (isFirst && isLast) return BorderRadius.all(radius);
     307              :   var topLeft = Radius.zero;
     308              :   var topRight = Radius.zero;
     309              :   var bottomLeft = Radius.zero;
     310              :   var bottomRight = Radius.zero;
     311              : 
     312            1 :   if (orientation == Axis.vertical) {
     313              :     if (isFirst) {
     314              :       topLeft = radius;
     315              :       topRight = radius;
     316              :     }
     317              :     if (isLast) {
     318              :       bottomLeft = radius;
     319              :       bottomRight = radius;
     320              :     }
     321              :   } else {
     322            1 :     final ltr = direction == TextDirection.ltr;
     323              :     if (isFirst) {
     324              :       if (ltr) {
     325              :         topLeft = bottomLeft = radius;
     326              :       } else {
     327              :         topRight = bottomRight = radius;
     328              :       }
     329              :     }
     330              :     if (isLast) {
     331              :       if (ltr) {
     332              :         topRight = bottomRight = radius;
     333              :       } else {
     334              :         topLeft = bottomLeft = radius;
     335              :       }
     336              :     }
     337              :   }
     338              : 
     339            1 :   return BorderRadius.only(
     340              :     topLeft: topLeft,
     341              :     topRight: topRight,
     342              :     bottomLeft: bottomLeft,
     343              :     bottomRight: bottomRight,
     344              :   );
     345              : }
     346              : 
     347              : /// A 1px divider between two joined outline cells, stretched to fill the bar's
     348              : /// cross axis by the enclosing [Flex].
     349              : class _Seam extends StatelessWidget {
     350            1 :   const _Seam({required this.orientation, required this.color});
     351              : 
     352              :   final Axis orientation;
     353              :   final Color color;
     354              : 
     355            1 :   @override
     356              :   Widget build(BuildContext context) {
     357            2 :     final horizontal = orientation == Axis.horizontal;
     358            1 :     return SizedBox(
     359              :       width: horizontal ? 1 : null,
     360              :       height: horizontal ? null : 1,
     361            2 :       child: ColoredBox(color: color),
     362              :     );
     363              :   }
     364              : }
     365              : 
     366              : /// The resolved group appearance: the item gap and the connected-bar border.
     367              : @immutable
     368              : class _GroupVisuals {
     369            1 :   const _GroupVisuals({required this.gap, required this.border});
     370              : 
     371            1 :   factory _GroupVisuals.resolve(FossThemeData theme, FossToggleGroupStyle? s) =>
     372            1 :       _GroupVisuals(
     373            2 :         gap: s?.gap ?? theme.spacing(0.5),
     374            2 :         border: s?.connectedBorderColor ?? theme.colors.input,
     375              :       );
     376              : 
     377              :   final double gap;
     378              :   final Color border;
     379              : }
     380              : 
     381              : /// Paints the shared 1px frame around a joined outline bar as a superellipse,
     382              : /// rounding the outer ends over the flush segments.
     383              : class _FramePainter extends CustomPainter {
     384            1 :   const _FramePainter({required this.color, required this.radius});
     385              : 
     386              :   final Color color;
     387              :   final double radius;
     388              : 
     389            1 :   @override
     390              :   void paint(Canvas canvas, Size size) {
     391            2 :     final rect = (Offset.zero & size).deflate(0.5);
     392            1 :     canvas.drawRSuperellipse(
     393            3 :       RSuperellipse.fromRectAndRadius(rect, Radius.circular(radius)),
     394            1 :       Paint()
     395            2 :         ..color = color
     396            1 :         ..style = PaintingStyle.stroke
     397            1 :         ..strokeWidth = 1,
     398              :     );
     399              :   }
     400              : 
     401            1 :   @override
     402              :   bool shouldRepaint(_FramePainter old) =>
     403            6 :       old.color != color || old.radius != radius;
     404              : }
        

Generated by: LCOV version 2.0-1