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

            Line data    Source code
       1              : import 'package:flutter/widgets.dart';
       2              : import 'package:fossui/src/foundation/foss_since.dart';
       3              : import 'package:fossui/src/theme/theme.dart';
       4              : 
       5              : part 'foss_toggle_style.dart';
       6              : 
       7              : const double _iconSize = 18;
       8              : const double _iconOpacity = 0.8;
       9              : const double _disabledOpacity = 0.64;
      10              : 
      11              : /// Fill opacity of the pressed (on) state: the input color at 64%.
      12              : const double _pressedFillOpacity = 0.64;
      13              : 
      14              : const double _ringWidth = 2;
      15              : const double _ringOffset = 1;
      16              : 
      17              : /// Minimum tap target, so a small toggle stays comfortably tappable without
      18              : /// growing its visual.
      19              : const double _minTapTarget = 44;
      20              : 
      21              : /// The visual treatment of a [FossToggle].
      22              : enum FossToggleVariant {
      23              :   /// Borderless: transparent at rest, filling on hover and when pressed.
      24              :   standard,
      25              : 
      26              :   /// Bordered surface that sits on the background and lifts with a shadow. The
      27              :   /// shadow flattens in the on-state, reading the toggle as pressed in.
      28              :   outline,
      29              : }
      30              : 
      31              : /// The size of a [FossToggle], sharing the FossButton-family metrics.
      32              : enum FossToggleSize {
      33              :   /// Compact: 32 logical pixels tall.
      34              :   sm,
      35              : 
      36              :   /// Default: 36 logical pixels tall.
      37              :   md,
      38              : 
      39              :   /// Prominent: 40 logical pixels tall.
      40              :   lg,
      41              : }
      42              : 
      43              : /// {@category Inputs}
      44              : /// {@template foss.toggle.preview}
      45              : /// <img src="https://fossui.org/components/toggle/overview/light.png"
      46              : ///   alt="FossToggle, light theme" width="480"
      47              : ///   style="max-width:100%;height:auto" />
      48              : /// <img src="https://fossui.org/components/toggle/overview/dark.png"
      49              : ///   alt="FossToggle, dark theme" width="480"
      50              : ///   style="max-width:100%;height:auto" />
      51              : ///
      52              : /// See the [toggle documentation ↗](https://fossui.org/docs/components/toggle) or
      53              : /// try it live in the
      54              : /// [playground ↗](https://play.fossui.org/components/#/?path=components/toggle/fosstoggle/playground).
      55              : /// {@endtemplate}
      56              : ///
      57              : /// A button that holds a two-state pressed look: tap it to turn it on, tap
      58              : /// again to release. It is the control behind a formatting button (bold,
      59              : /// italic) in a toolbar, sized and shaped like a FossButton but carrying a
      60              : /// binary on / off state.
      61              : ///
      62              : /// The toggle is controlled: it renders [pressed] and reports the flipped value
      63              : /// through [onPressedChanged] on a tap or Space / Enter. Passing `null` to
      64              : /// [onPressedChanged] disables it (dims the control and drops the pointer), so
      65              : /// there is no separate enabled flag.
      66              : ///
      67              : /// Renders a [child] label, a [leading] icon, or both; a null [child] makes a
      68              : /// square icon-only toggle, in which case name it for assistive tech with
      69              : /// [semanticLabel]. Colors, radius, type, and spacing come from
      70              : /// `context.fossTheme`; pass a [FossToggleStyle] to [style] for a one-off.
      71              : ///
      72              : /// {@macro foss.customize}
      73              : ///
      74              : /// See also FossButton for a momentary action, and FossToggleGroup for a
      75              : /// set of toggles bound to one selection.
      76              : ///
      77              : /// ```dart
      78              : /// FossToggle(
      79              : ///   pressed: isBold,
      80              : ///   leading: const Icon(boldIcon),
      81              : ///   semanticLabel: 'Bold',
      82              : ///   onPressedChanged: (on) => setState(() => isBold = on),
      83              : ///   child: const Text('Bold'),
      84              : /// );
      85              : /// ```
      86              : @FossSince('0.1.1')
      87              : class FossToggle extends StatefulWidget {
      88              :   /// {@macro foss.toggle.preview}
      89              :   ///
      90              :   /// Creates a toggle showing [pressed]. A null [onPressedChanged] disables it;
      91              :   /// a null [child] makes it a square icon-only toggle.
      92            2 :   const FossToggle({
      93              :     required this.pressed,
      94              :     this.onPressedChanged,
      95              :     this.variant = FossToggleVariant.standard,
      96              :     this.size = FossToggleSize.md,
      97              :     this.leading,
      98              :     this.child,
      99              :     this.semanticLabel,
     100              :     this.style,
     101              :     super.key,
     102              :   });
     103              : 
     104              :   /// The current state: `true` on (pressed), `false` off.
     105              :   final bool pressed;
     106              : 
     107              :   /// Called with the flipped value on a tap or Space / Enter. Null disables the
     108              :   /// toggle.
     109              :   final ValueChanged<bool>? onPressedChanged;
     110              : 
     111              :   /// The visual treatment. Defaults to [FossToggleVariant.standard].
     112              :   final FossToggleVariant variant;
     113              : 
     114              :   /// The size. Defaults to [FossToggleSize.md].
     115              :   final FossToggleSize size;
     116              : 
     117              :   /// Optional widget before the label, themed as an icon. When [child] is null
     118              :   /// it is the sole content of a square icon-only toggle.
     119              :   final Widget? leading;
     120              : 
     121              :   /// The label, typically a [Text]. Null makes a square icon-only toggle.
     122              :   final Widget? child;
     123              : 
     124              :   /// Accessibility name, required in spirit for an icon-only toggle where
     125              :   /// [child] is null.
     126              :   final String? semanticLabel;
     127              : 
     128              :   /// Per-instance overrides layered on the theme-resolved style.
     129              :   final FossToggleStyle? style;
     130              : 
     131              :   /// Whether the toggle is interactive: it has an [onPressedChanged].
     132            4 :   bool get enabled => onPressedChanged != null;
     133              : 
     134            2 :   @override
     135            2 :   State<FossToggle> createState() => _FossToggleState();
     136              : }
     137              : 
     138              : class _FossToggleState extends State<FossToggle> {
     139              :   final WidgetStatesController _states = WidgetStatesController();
     140              : 
     141            2 :   @override
     142              :   void initState() {
     143            2 :     super.initState();
     144            2 :     _sync();
     145              :   }
     146              : 
     147            2 :   @override
     148              :   void didUpdateWidget(FossToggle oldWidget) {
     149            2 :     super.didUpdateWidget(oldWidget);
     150            2 :     _sync();
     151              :   }
     152              : 
     153            2 :   void _sync() {
     154            2 :     _states
     155            6 :       ..update(WidgetState.selected, widget.pressed)
     156            6 :       ..update(WidgetState.disabled, !widget.enabled);
     157              :   }
     158              : 
     159            2 :   @override
     160              :   void dispose() {
     161            4 :     _states.dispose();
     162            2 :     super.dispose();
     163              :   }
     164              : 
     165           12 :   void _toggle() => widget.onPressedChanged?.call(!widget.pressed);
     166              : 
     167            2 :   @override
     168              :   Widget build(BuildContext context) {
     169            2 :     final theme = context.fossTheme;
     170           12 :     final visuals = _resolve(theme, widget.variant, widget.size).merge(
     171            4 :       widget.style,
     172              :     );
     173            4 :     final iconOnly = widget.child == null;
     174              : 
     175            2 :     return Semantics(
     176              :       button: true,
     177            4 :       toggled: widget.pressed,
     178            4 :       enabled: widget.enabled,
     179            4 :       label: widget.semanticLabel,
     180            2 :       child: FocusableActionDetector(
     181            4 :         enabled: widget.enabled,
     182            4 :         mouseCursor: widget.enabled
     183              :             ? SystemMouseCursors.click
     184              :             : SystemMouseCursors.basic,
     185            3 :         onShowHoverHighlight: (v) => _states.update(WidgetState.hovered, v),
     186            6 :         onShowFocusHighlight: (v) => _states.update(WidgetState.focused, v),
     187            2 :         actions: <Type, Action<Intent>>{
     188            2 :           ActivateIntent: CallbackAction<ActivateIntent>(
     189            1 :             onInvoke: (_) {
     190            1 :               _toggle();
     191              :               return null;
     192              :             },
     193              :           ),
     194              :         },
     195            2 :         child: GestureDetector(
     196            6 :           onTap: widget.enabled ? _toggle : null,
     197            2 :           child: ConstrainedBox(
     198              :             constraints: const BoxConstraints(
     199              :               minWidth: _minTapTarget,
     200              :               minHeight: _minTapTarget,
     201              :             ),
     202            2 :             child: Center(
     203              :               widthFactor: 1,
     204            2 :               child: ListenableBuilder(
     205            2 :                 listenable: _states,
     206            4 :                 builder: (context, _) => _paint(visuals, iconOnly),
     207              :               ),
     208              :             ),
     209              :           ),
     210              :         ),
     211              :       ),
     212              :     );
     213              :   }
     214              : 
     215            2 :   Widget _paint(_ToggleVisuals visuals, bool iconOnly) {
     216            4 :     final states = _states.value;
     217            4 :     final fg = visuals.foreground.resolve(states);
     218            4 :     final on = widget.pressed;
     219              : 
     220              :     // Icon-only toggles are square: floor the width to the height.
     221            1 :     final minWidth = iconOnly ? visuals.minHeight : 0.0;
     222            2 :     Widget surface = DecoratedBox(
     223            2 :       decoration: ShapeDecoration(
     224            4 :         color: visuals.background.resolve(states),
     225            2 :         shape: RoundedSuperellipseBorder(
     226            2 :           side: visuals.side,
     227            2 :           borderRadius: visuals.radius,
     228              :         ),
     229              :         // The lift drops when on or disabled, matching coss `shadow-none`.
     230            6 :         shadows: on || !widget.enabled ? const [] : visuals.shadow,
     231              :       ),
     232            2 :       child: Padding(
     233            2 :         padding: iconOnly ? EdgeInsets.zero : visuals.padding,
     234            2 :         child: ConstrainedBox(
     235            2 :           constraints: BoxConstraints(
     236              :             minWidth: minWidth,
     237            2 :             minHeight: visuals.minHeight,
     238              :           ),
     239            2 :           child: _content(visuals, iconOnly, fg),
     240              :         ),
     241              :       ),
     242              :     );
     243              : 
     244            4 :     if (!widget.enabled) {
     245            4 :       surface = Opacity(opacity: visuals.disabledOpacity, child: surface);
     246              :     }
     247              : 
     248            2 :     return CustomPaint(
     249            2 :       foregroundPainter: states.contains(WidgetState.focused)
     250            2 :           ? _FocusRingPainter(
     251            2 :               color: visuals.ring,
     252            2 :               offsetColor: visuals.ringOffset,
     253            2 :               radius: visuals.radius,
     254              :             )
     255              :           : null,
     256              :       child: surface,
     257              :     );
     258              :   }
     259              : 
     260              :   /// Builds the inner content: a single themed icon when icon-only, otherwise
     261              :   /// the leading / label row.
     262            2 :   Widget _content(_ToggleVisuals visuals, bool iconOnly, Color fg) {
     263            6 :     final iconColor = fg.withValues(alpha: fg.a * _iconOpacity);
     264            4 :     final icon = IconThemeData(size: visuals.iconSize, color: iconColor);
     265            4 :     final leading = widget.leading;
     266            4 :     final child = widget.child;
     267              : 
     268              :     if (iconOnly || child == null) {
     269            1 :       return IconTheme.merge(
     270              :         data: icon,
     271              :         child: leading ?? const SizedBox.shrink(),
     272              :       );
     273              :     }
     274              : 
     275            2 :     return Row(
     276              :       mainAxisSize: MainAxisSize.min,
     277            2 :       spacing: visuals.gap,
     278            2 :       children: [
     279            1 :         if (leading != null) IconTheme.merge(data: icon, child: leading),
     280            2 :         Flexible(
     281            2 :           child: DefaultTextStyle.merge(
     282            4 :             style: visuals.textStyle.copyWith(color: fg),
     283              :             maxLines: 1,
     284              :             softWrap: false,
     285              :             overflow: TextOverflow.ellipsis,
     286              :             child: child,
     287              :           ),
     288              :         ),
     289              :       ],
     290              :     );
     291              :   }
     292              : }
     293              : 
     294              : /// Scales [color] to [opacity] of its own alpha, keeping it translucent so the
     295              : /// pressed fill composites over whatever surface the toggle sits on.
     296            2 : Color _alpha(Color color, double opacity) =>
     297            6 :     color.withValues(alpha: color.a * opacity);
     298              : 
     299              : /// Composites [base] at [opacity] of its own alpha over a fixed [surface],
     300              : /// baking an opaque color used for the dark outline lift.
     301            1 : Color _overlay(Color base, double opacity, Color surface) =>
     302            4 :     Color.alphaBlend(base.withValues(alpha: base.a * opacity), surface);
     303              : 
     304              : /// Builds the default appearance for a (variant, size) from the theme tokens.
     305            2 : _ToggleVisuals _resolve(
     306              :   FossThemeData theme,
     307              :   FossToggleVariant variant,
     308              :   FossToggleSize size,
     309              : ) {
     310            2 :   final c = theme.colors;
     311              : 
     312              :   final Color rest;
     313              :   final Color hover;
     314              :   final Color pressedFill;
     315              :   final BorderSide side;
     316              :   final List<BoxShadow> shadow;
     317              :   switch (variant) {
     318            2 :     case FossToggleVariant.standard:
     319              :       rest = const Color(0x00000000);
     320            2 :       hover = c.accent;
     321            4 :       pressedFill = _alpha(c.input, _pressedFillOpacity);
     322              :       side = BorderSide.none;
     323              :       shadow = FossShadows.none;
     324            2 :     case FossToggleVariant.outline:
     325              :       // Dark mode lifts the surface with the input color; light rests on the
     326              :       // background and hovers to accent.
     327            2 :       if (c.isDark) {
     328            3 :         rest = _overlay(c.input, 0.32, c.background);
     329            3 :         hover = _overlay(c.input, 0.64, c.background);
     330            1 :         pressedFill = c.input;
     331              :       } else {
     332            2 :         rest = c.background;
     333            2 :         hover = c.accent;
     334            4 :         pressedFill = _alpha(c.input, _pressedFillOpacity);
     335              :       }
     336            4 :       side = BorderSide(color: c.input);
     337            4 :       shadow = theme.shadows.xs;
     338              :   }
     339              : 
     340              :   final (height, padX) = switch (size) {
     341            5 :     FossToggleSize.sm => (32.0, theme.spacing(1.5) - 1),
     342            8 :     FossToggleSize.md => (36.0, theme.spacing(2) - 1),
     343            4 :     FossToggleSize.lg => (40.0, theme.spacing(2.5) - 1),
     344              :   };
     345              : 
     346            2 :   return _ToggleVisuals(
     347            4 :     background: WidgetStateProperty.resolveWith((states) {
     348            2 :       if (states.contains(WidgetState.selected)) return pressedFill;
     349            2 :       if (states.contains(WidgetState.hovered)) return hover;
     350              :       return rest;
     351              :     }),
     352            2 :     foreground: WidgetStateProperty.resolveWith(
     353            4 :       (states) => states.contains(WidgetState.selected)
     354            2 :           ? c.accentForeground
     355            2 :           : c.foreground,
     356              :     ),
     357              :     side: side,
     358            8 :     radius: BorderRadius.all(Radius.circular(theme.radii.lg)),
     359            2 :     padding: EdgeInsets.symmetric(horizontal: padX),
     360              :     minHeight: height,
     361            6 :     textStyle: theme.typography.base.medium,
     362              :     shadow: shadow,
     363              :     iconSize: _iconSize,
     364            4 :     gap: theme.spacing(1.5),
     365              :     disabledOpacity: _disabledOpacity,
     366            2 :     ring: c.ring,
     367            2 :     ringOffset: c.background,
     368              :   );
     369              : }
     370              : 
     371              : /// The fully resolved, non-null appearance for one (variant, size). A public
     372              : /// [FossToggleStyle] override is laid over it by [merge], so the widget reads
     373              : /// only non-null fields and never needs the null-assertion operator.
     374              : @immutable
     375              : class _ToggleVisuals {
     376            2 :   const _ToggleVisuals({
     377              :     required this.background,
     378              :     required this.foreground,
     379              :     required this.side,
     380              :     required this.radius,
     381              :     required this.padding,
     382              :     required this.minHeight,
     383              :     required this.textStyle,
     384              :     required this.shadow,
     385              :     required this.iconSize,
     386              :     required this.gap,
     387              :     required this.disabledOpacity,
     388              :     required this.ring,
     389              :     required this.ringOffset,
     390              :   });
     391              : 
     392              :   final WidgetStateProperty<Color> background;
     393              :   final WidgetStateProperty<Color> foreground;
     394              :   final BorderSide side;
     395              :   final BorderRadius radius;
     396              :   final EdgeInsetsGeometry padding;
     397              :   final double minHeight;
     398              :   final TextStyle textStyle;
     399              :   final List<BoxShadow> shadow;
     400              :   final double iconSize;
     401              :   final double gap;
     402              :   final double disabledOpacity;
     403              :   final Color ring;
     404              :   final Color ringOffset;
     405              : 
     406              :   /// Lays a per-instance [override] over this resolved base, field by field.
     407            2 :   _ToggleVisuals merge(FossToggleStyle? override) {
     408              :     if (override == null) return this;
     409            2 :     final uniform = override.borderRadius;
     410            2 :     return _ToggleVisuals(
     411            4 :       background: override.backgroundColor ?? background,
     412            4 :       foreground: override.foregroundColor ?? foreground,
     413            3 :       side: override.side ?? side,
     414              :       radius:
     415            2 :           override.cornerRadius ??
     416              :           (uniform != null
     417            2 :               ? BorderRadius.all(Radius.circular(uniform))
     418            1 :               : radius),
     419            4 :       padding: override.padding ?? padding,
     420            3 :       minHeight: override.minHeight ?? minHeight,
     421            4 :       textStyle: override.textStyle ?? textStyle,
     422            3 :       shadow: override.shadow ?? shadow,
     423            4 :       iconSize: override.iconSize ?? iconSize,
     424            4 :       gap: override.gap ?? gap,
     425            4 :       disabledOpacity: override.disabledOpacity ?? disabledOpacity,
     426            2 :       ring: ring,
     427            2 :       ringOffset: ringOffset,
     428              :     );
     429              :   }
     430              : }
     431              : 
     432              : /// Paints the focus ring: a 2px superellipse outset just past the toggle edge,
     433              : /// with a 1px offset gap filled with [offsetColor] (the surface) so the ring
     434              : /// reads as detached, matching the corner shape rather than a circular arc.
     435              : class _FocusRingPainter extends CustomPainter {
     436            2 :   const _FocusRingPainter({
     437              :     required this.color,
     438              :     required this.offsetColor,
     439              :     required this.radius,
     440              :   });
     441              : 
     442              :   final Color color;
     443              :   final Color offsetColor;
     444              :   final BorderRadius radius;
     445              : 
     446              :   // A square corner stays square in the ring; a rounded one grows with the
     447              :   // outset, so a segmented item's ring follows its own joined corners.
     448            2 :   RSuperellipse _shape(Rect box, double inflate, double grow) {
     449            2 :     Radius corner(Radius c) =>
     450            8 :         c == Radius.zero ? Radius.zero : Radius.circular(c.x + grow);
     451            2 :     return RSuperellipse.fromRectAndCorners(
     452            2 :       box.inflate(inflate),
     453            6 :       topLeft: corner(radius.topLeft),
     454            6 :       topRight: corner(radius.topRight),
     455            6 :       bottomLeft: corner(radius.bottomLeft),
     456            6 :       bottomRight: corner(radius.bottomRight),
     457              :     );
     458              :   }
     459              : 
     460            2 :   @override
     461              :   void paint(Canvas canvas, Size size) {
     462            2 :     final box = Offset.zero & size;
     463              :     canvas
     464            2 :       ..drawRSuperellipse(
     465            6 :         _shape(box, _ringOffset / 2, _ringOffset / 2),
     466            2 :         Paint()
     467            4 :           ..color = offsetColor
     468            2 :           ..style = PaintingStyle.stroke
     469            2 :           ..strokeWidth = _ringOffset,
     470              :       )
     471            2 :       ..drawRSuperellipse(
     472           10 :         _shape(box, _ringOffset + _ringWidth / 2, _ringOffset + _ringWidth / 2),
     473            2 :         Paint()
     474            4 :           ..color = color
     475            2 :           ..style = PaintingStyle.stroke
     476            2 :           ..strokeWidth = _ringWidth,
     477              :       );
     478              :   }
     479              : 
     480            1 :   @override
     481              :   bool shouldRepaint(_FocusRingPainter old) =>
     482            3 :       old.color != color ||
     483            3 :       old.offsetColor != offsetColor ||
     484            3 :       old.radius != radius;
     485              : }
        

Generated by: LCOV version 2.0-1