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

            Line data    Source code
       1              : import 'package:flutter/semantics.dart' show SemanticsValidationResult;
       2              : import 'package:flutter/widgets.dart';
       3              : import 'package:fossui/src/components/checkbox/foss_checkbox.dart';
       4              : import 'package:fossui/src/components/switch/foss_switch.dart';
       5              : import 'package:fossui/src/theme/theme.dart';
       6              : 
       7              : part 'foss_radio_group.dart';
       8              : part 'foss_radio_style.dart';
       9              : 
      10              : const double _circleSize = 18;
      11              : const double _dotSize = 8;
      12              : const double _ringWidth = 2;
      13              : const double _ringOffset = 1;
      14              : const double _disabledOpacity = 0.64;
      15              : 
      16              : // Error border and ring alphas: the border deepens when the option is focused,
      17              : // the ring lifts in dark mode.
      18              : const double _errorBorderOpacity = 0.36;
      19              : const double _errorBorderFocusedOpacity = 0.64;
      20              : const double _errorRingOpacityLight = 0.48;
      21              : const double _errorRingOpacityDark = 0.24;
      22              : 
      23              : // Dark surfaces lift the unchecked fill by the input color at 32% of its alpha.
      24              : const double _darkFillOpacity = 0.32;
      25              : 
      26              : // Card variant: the checked card lifts its border to the primary role and tints
      27              : // its fill with the accent role.
      28              : const double _cardCheckedBorderOpacity = 0.48;
      29              : const double _cardCheckedFillOpacity = 0.5;
      30              : 
      31              : // Inner top-lit rim at rest: a faint dark line in light mode, a faint white
      32              : // highlight in dark mode.
      33              : const Color _rimLight = Color(0x0A000000);
      34              : const Color _rimDark = Color(0x0FFFFFFF);
      35              : 
      36              : /// {@category Inputs}
      37              : /// {@template foss.radio.preview}
      38              : /// <img src="https://fossui.org/components/radio/overview/light.png"
      39              : ///   alt="FossRadio, light theme" width="480"
      40              : ///   style="max-width:100%;height:auto" />
      41              : /// <img src="https://fossui.org/components/radio/overview/dark.png"
      42              : ///   alt="FossRadio, dark theme" width="480"
      43              : ///   style="max-width:100%;height:auto" />
      44              : ///
      45              : /// See the [radio documentation ↗](https://fossui.org/docs/components/radio) or
      46              : /// try it live in the
      47              : /// [playground ↗](https://play.fossui.org/components/#/?path=components/radio/fossradiogroup/playground).
      48              : /// {@endtemplate}
      49              : ///
      50              : /// A single option within a [FossRadioGroup].
      51              : ///
      52              : /// Renders a circular control with an optional [label] and [description]. Reads
      53              : /// its checked, enabled, and invalid state from the enclosing [FossRadioGroup]
      54              : /// and reports a tap by calling the group's callback with [value]. A bare
      55              : /// circle (no [label]) is valid. Setting `enabled: false` disables this option;
      56              : /// disabling the group disables every option.
      57              : ///
      58              : /// Must be placed under a [FossRadioGroup] of the same value type [T]. Colors,
      59              : /// type, and spacing come from `context.fossTheme`; pass a [FossRadioStyle] to
      60              : /// [style] for a one-off.
      61              : ///
      62              : /// {@macro foss.customize}
      63              : ///
      64              : /// See also [FossRadioGroup], which hosts the options, and [FossCheckbox] or
      65              : /// [FossSwitch] for related toggles.
      66              : ///
      67              : /// ```dart
      68              : /// FossRadio<String>(
      69              : ///   value: 'yearly',
      70              : ///   label: 'Yearly',
      71              : ///   description: 'Two months free',
      72              : /// );
      73              : /// ```
      74              : class FossRadio<T> extends StatefulWidget {
      75              :   /// {@macro foss.radio.preview}
      76              :   ///
      77              :   /// Creates a radio option. [value] identifies it within the group.
      78            1 :   const FossRadio({
      79              :     required this.value,
      80              :     this.label,
      81              :     this.description,
      82              :     this.enabled = true,
      83              :     this.style,
      84              :     super.key,
      85              :   });
      86              : 
      87              :   /// The value this option contributes to the group, compared by `==`.
      88              :   final T value;
      89              : 
      90              :   /// Optional title beside the circle.
      91              :   final String? label;
      92              : 
      93              :   /// Optional secondary line below the [label].
      94              :   final String? description;
      95              : 
      96              :   /// Whether this option accepts input. Disabled when false or when the group
      97              :   /// is disabled.
      98              :   final bool enabled;
      99              : 
     100              :   /// Per-instance overrides layered on the theme-resolved style.
     101              :   final FossRadioStyle? style;
     102              : 
     103            1 :   @override
     104            1 :   State<FossRadio<T>> createState() => _FossRadioState<T>();
     105              : }
     106              : 
     107              : class _FossRadioState<T> extends State<FossRadio<T>> {
     108              :   final FocusNode _focusNode = FocusNode();
     109              : 
     110            1 :   @override
     111              :   void dispose() {
     112            2 :     _focusNode.dispose();
     113            1 :     super.dispose();
     114              :   }
     115              : 
     116            1 :   @override
     117              :   Widget build(BuildContext context) {
     118            1 :     final theme = context.fossTheme;
     119            1 :     final group = _FossRadioGroupScope.of<T>(context);
     120              :     if (group == null) {
     121            1 :       throw FlutterError(
     122            1 :         'FossRadio<$T> must be placed inside a FossRadioGroup<$T>.',
     123              :       );
     124              :     }
     125              : 
     126            3 :     final enabled = widget.enabled && group.enabled;
     127            4 :     final v = _apply(_resolve(theme), widget.style);
     128              : 
     129              :     // The group's RadioGroup owns selection, roving focus, and the group
     130              :     // semantics; RawRadio registers this option, drives its gesture, focus, and
     131              :     // keyboard, and hands the paint back through [builder].
     132            1 :     Widget radio = RawRadio<T>(
     133            2 :       value: widget.value,
     134            1 :       focusNode: _focusNode,
     135              :       autofocus: false,
     136              :       toggleable: false,
     137              :       enabled: enabled,
     138            1 :       mouseCursor: WidgetStateProperty.resolveWith(
     139            1 :         (states) =>
     140              :             enabled ? SystemMouseCursors.click : SystemMouseCursors.basic,
     141              :       ),
     142            1 :       groupRegistry: RadioGroup.maybeOf<T>(context),
     143            2 :       builder: (context, state) => _option(
     144              :         theme,
     145              :         v,
     146            1 :         checked: state.value ?? false,
     147            2 :         focused: state.states.contains(WidgetState.focused),
     148              :         enabled: enabled,
     149            1 :         hasError: group.hasError,
     150            1 :         variant: group.variant,
     151              :       ),
     152              :     );
     153              : 
     154              :     // Mark the option invalid for assistive tech when the group is in error;
     155              :     // RawRadio already carries the radio role, checked, and mutex flags, which
     156              :     // MergeSemantics folds together with the label and description.
     157            1 :     if (group.hasError) {
     158            1 :       radio = Semantics(
     159              :         validationResult: SemanticsValidationResult.invalid,
     160              :         child: radio,
     161              :       );
     162              :     }
     163            1 :     return MergeSemantics(child: radio);
     164              :   }
     165              : 
     166            1 :   Widget _option(
     167              :     FossThemeData theme,
     168              :     _RadioVisuals v, {
     169              :     required bool checked,
     170              :     required bool focused,
     171              :     required bool enabled,
     172              :     required bool hasError,
     173              :     required FossRadioGroupVariant variant,
     174              :   }) {
     175            1 :     final card = variant == FossRadioGroupVariant.card;
     176            4 :     final hasText = widget.label != null || widget.description != null;
     177            1 :     Widget option = Row(
     178              :       crossAxisAlignment: CrossAxisAlignment.start,
     179              :       mainAxisSize: card ? MainAxisSize.max : MainAxisSize.min,
     180            1 :       spacing: v.gap,
     181            1 :       children: [
     182            1 :         _circleSlot(
     183              :           theme,
     184              :           v,
     185              :           checked: checked,
     186              :           focused: focused,
     187              :           hasError: hasError,
     188              :           enabled: enabled,
     189              :           hasText: hasText,
     190              :         ),
     191            2 :         if (hasText) Flexible(child: _texts(theme, v)),
     192              :       ],
     193              :     );
     194              : 
     195              :     if (card) {
     196            1 :       option = _card(theme, child: option, checked: checked);
     197              :     }
     198              :     if (!enabled) {
     199            1 :       option = Opacity(opacity: _disabledOpacity, child: option);
     200              :     }
     201              : 
     202              :     // The plain option hugs its circle and label so a stacked group reads
     203              :     // tight, matching the reference. The card supplies its own padded surface.
     204              :     return option;
     205              :   }
     206              : 
     207              :   // The circle, aligned to the first text line when a label or description is
     208              :   // present so it centers on the title rather than the whole text block.
     209            1 :   Widget _circleSlot(
     210              :     FossThemeData theme,
     211              :     _RadioVisuals v, {
     212              :     required bool checked,
     213              :     required bool focused,
     214              :     required bool hasError,
     215              :     required bool enabled,
     216              :     required bool hasText,
     217              :   }) {
     218            1 :     final circle = _circle(
     219              :       theme,
     220              :       v,
     221              :       checked: checked,
     222              :       focused: focused,
     223              :       hasError: hasError,
     224              :       enabled: enabled,
     225              :     );
     226              :     if (!hasText) return circle;
     227              :     // Center on the first text line: the title when present, else the
     228              :     // description, so a description-only option still aligns.
     229            4 :     final firstLine = widget.label != null ? v.labelStyle : v.descriptionStyle;
     230            3 :     final line = (firstLine.fontSize ?? 16) * (firstLine.height ?? 1);
     231            1 :     return SizedBox(
     232              :       height: line,
     233            1 :       child: Center(widthFactor: 1, child: circle),
     234              :     );
     235              :   }
     236              : 
     237            1 :   Widget _circle(
     238              :     FossThemeData theme,
     239              :     _RadioVisuals v, {
     240              :     required bool checked,
     241              :     required bool focused,
     242              :     required bool hasError,
     243              :     required bool enabled,
     244              :   }) {
     245            1 :     final colors = theme.colors;
     246            1 :     final dark = colors.isDark;
     247              :     final showBorder = !checked;
     248              : 
     249              :     // Border stays the resting input color except when invalid, where it
     250              :     // deepens and the focus ring switches to the destructive role.
     251            1 :     var borderColor = v.borderColor;
     252            1 :     var ringColor = focused ? colors.ring : null;
     253              :     if (hasError) {
     254              :       if (showBorder) {
     255            2 :         borderColor = colors.destructive.withValues(
     256              :           alpha: focused ? _errorBorderFocusedOpacity : _errorBorderOpacity,
     257              :         );
     258              :       }
     259              :       if (focused) {
     260            2 :         ringColor = colors.destructive.withValues(
     261              :           alpha: dark ? _errorRingOpacityDark : _errorRingOpacityLight,
     262              :         );
     263              :       }
     264              :     }
     265              : 
     266              :     // The resting shadow and inner rim drop when checked, invalid, or disabled.
     267              :     final atRest = !checked && !hasError && enabled;
     268              : 
     269            1 :     Widget circle = SizedBox.square(
     270            1 :       dimension: v.circleSize,
     271            1 :       child: DecoratedBox(
     272            1 :         decoration: ShapeDecoration(
     273            2 :           color: checked ? v.checkedColor : v.uncheckedFill,
     274            1 :           shape: CircleBorder(
     275            1 :             side: showBorder ? BorderSide(color: borderColor) : BorderSide.none,
     276              :           ),
     277            1 :           shadows: atRest ? v.shadow : const [],
     278              :         ),
     279              :         child: checked
     280            1 :             ? Center(
     281            1 :                 child: SizedBox.square(
     282            1 :                   dimension: v.dotSize,
     283            1 :                   child: DecoratedBox(
     284            1 :                     decoration: ShapeDecoration(
     285            1 :                       color: v.dotColor,
     286              :                       shape: const CircleBorder(),
     287              :                     ),
     288              :                   ),
     289              :                 ),
     290              :               )
     291              :             : null,
     292              :       ),
     293              :     );
     294              : 
     295              :     if (atRest) {
     296            1 :       circle = CustomPaint(
     297            1 :         foregroundPainter: _RimPainter(
     298              :           color: dark ? _rimDark : _rimLight,
     299              :           topLit: dark,
     300              :         ),
     301              :         child: circle,
     302              :       );
     303              :     }
     304              : 
     305              :     if (ringColor != null) {
     306            1 :       circle = CustomPaint(
     307            1 :         foregroundPainter: _RingPainter(
     308              :           color: ringColor,
     309            1 :           offsetColor: colors.background,
     310              :         ),
     311              :         child: circle,
     312              :       );
     313              :     }
     314              : 
     315              :     return circle;
     316              :   }
     317              : 
     318            1 :   Widget _texts(FossThemeData theme, _RadioVisuals v) {
     319            1 :     final colors = theme.colors;
     320            1 :     return Column(
     321              :       crossAxisAlignment: CrossAxisAlignment.start,
     322              :       mainAxisSize: MainAxisSize.min,
     323            2 :       spacing: theme.spacing(1.5),
     324            1 :       children: [
     325            2 :         if (widget.label case final label?)
     326            4 :           Text(label, style: v.labelStyle.copyWith(color: colors.foreground)),
     327            2 :         if (widget.description case final description?)
     328            1 :           Text(
     329              :             description,
     330            3 :             style: v.descriptionStyle.copyWith(color: colors.mutedForeground),
     331              :           ),
     332              :       ],
     333              :     );
     334              :   }
     335              : 
     336              :   // Wraps an option in the card surface: a bordered, padded box that lifts its
     337              :   // border and fill when checked. A min content height keeps the card past the
     338              :   // tap-target floor even for a single-line option.
     339            1 :   Widget _card(
     340              :     FossThemeData theme, {
     341              :     required Widget child,
     342              :     required bool checked,
     343              :   }) {
     344            1 :     final colors = theme.colors;
     345            1 :     return DecoratedBox(
     346            1 :       decoration: ShapeDecoration(
     347              :         // accent at 50% of its own alpha: the accent role
     348              :         // is already a faint translucent tint, so this is a barely-there wash,
     349              :         // not a half-opaque fill.
     350              :         color: checked
     351            2 :             ? colors.accent.withValues(
     352            3 :                 alpha: colors.accent.a * _cardCheckedFillOpacity,
     353              :               )
     354              :             : null,
     355            1 :         shape: RoundedSuperellipseBorder(
     356            1 :           side: BorderSide(
     357              :             color: checked
     358            2 :                 ? colors.primary.withValues(alpha: _cardCheckedBorderOpacity)
     359            1 :                 : colors.border,
     360              :           ),
     361            3 :           borderRadius: BorderRadius.circular(theme.radii.lg),
     362              :         ),
     363              :       ),
     364            1 :       child: Padding(
     365            3 :         padding: EdgeInsets.all(theme.spacing(3)),
     366            1 :         child: ConstrainedBox(
     367            3 :           constraints: BoxConstraints(minHeight: theme.spacing(6)),
     368              :           child: child,
     369              :         ),
     370              :       ),
     371              :     );
     372              :   }
     373              : }
     374              : 
     375              : /// Builds the default appearance from the theme tokens. The checked and
     376              : /// unchecked fills are both resolved here; the widget picks between them.
     377            1 : _RadioVisuals _resolve(FossThemeData theme) {
     378            1 :   final c = theme.colors;
     379              : 
     380              :   // Dark adds a faint lift to the unchecked circle: the input color at 32% of
     381              :   // its alpha, composited to opaque. Light is the bare surface.
     382            1 :   final uncheckedFill = c.isDark
     383            1 :       ? Color.alphaBlend(
     384            5 :           c.input.withValues(alpha: c.input.a * _darkFillOpacity),
     385            1 :           c.background,
     386              :         )
     387            1 :       : c.background;
     388              : 
     389            1 :   return _RadioVisuals(
     390              :     uncheckedFill: uncheckedFill,
     391            1 :     checkedColor: c.primary,
     392            1 :     dotColor: c.primaryForeground,
     393            1 :     borderColor: c.input,
     394            2 :     shadow: theme.shadows.xs,
     395              :     circleSize: _circleSize,
     396              :     dotSize: _dotSize,
     397            2 :     gap: theme.spacing(2),
     398            3 :     labelStyle: theme.typography.base.medium,
     399            2 :     descriptionStyle: theme.typography.xs,
     400              :   );
     401              : }
     402              : 
     403              : /// Lays a per-instance [override] over the resolved [base], field by field.
     404            1 : _RadioVisuals _apply(_RadioVisuals base, FossRadioStyle? override) {
     405              :   if (override == null) return base;
     406            1 :   return _RadioVisuals(
     407            1 :     uncheckedFill: override.backgroundColor ?? base.uncheckedFill,
     408            1 :     checkedColor: override.checkedColor ?? base.checkedColor,
     409            1 :     dotColor: override.dotColor ?? base.dotColor,
     410            1 :     borderColor: override.borderColor ?? base.borderColor,
     411            1 :     shadow: override.shadow ?? base.shadow,
     412            1 :     circleSize: override.circleSize ?? base.circleSize,
     413            1 :     dotSize: override.dotSize ?? base.dotSize,
     414            1 :     gap: override.gap ?? base.gap,
     415            1 :     labelStyle: override.labelStyle ?? base.labelStyle,
     416            1 :     descriptionStyle: override.descriptionStyle ?? base.descriptionStyle,
     417              :   );
     418              : }
     419              : 
     420              : /// The fully resolved, non-null appearance. A [FossRadioStyle] override is laid
     421              : /// over it by [_apply], so the widget reads only non-null fields and never
     422              : /// needs the null-assertion operator.
     423              : @immutable
     424              : class _RadioVisuals {
     425            1 :   const _RadioVisuals({
     426              :     required this.uncheckedFill,
     427              :     required this.checkedColor,
     428              :     required this.dotColor,
     429              :     required this.borderColor,
     430              :     required this.shadow,
     431              :     required this.circleSize,
     432              :     required this.dotSize,
     433              :     required this.gap,
     434              :     required this.labelStyle,
     435              :     required this.descriptionStyle,
     436              :   });
     437              : 
     438              :   final Color uncheckedFill;
     439              :   final Color checkedColor;
     440              :   final Color dotColor;
     441              :   final Color borderColor;
     442              :   final List<BoxShadow> shadow;
     443              :   final double circleSize;
     444              :   final double dotSize;
     445              :   final double gap;
     446              :   final TextStyle labelStyle;
     447              :   final TextStyle descriptionStyle;
     448              : }
     449              : 
     450              : /// Paints a 1px rim inside the circle: brightest along one edge, fading to
     451              : /// nothing by the center. [topLit] lights the top edge; otherwise the bottom.
     452              : class _RimPainter extends CustomPainter {
     453            1 :   const _RimPainter({required this.color, required this.topLit});
     454              : 
     455              :   final Color color;
     456              :   final bool topLit;
     457              : 
     458            1 :   @override
     459              :   void paint(Canvas canvas, Size size) {
     460            2 :     final rect = (Offset.zero & size).deflate(0.5);
     461            1 :     final shader = LinearGradient(
     462            1 :       begin: topLit ? Alignment.topCenter : Alignment.bottomCenter,
     463              :       end: Alignment.center,
     464            4 :       colors: [color, color.withValues(alpha: 0)],
     465            1 :     ).createShader(rect);
     466            1 :     final paint = Paint()
     467            1 :       ..shader = shader
     468            1 :       ..style = PaintingStyle.stroke
     469            1 :       ..strokeWidth = 1;
     470            4 :     canvas.drawCircle(rect.center, rect.width / 2, paint);
     471              :   }
     472              : 
     473            1 :   @override
     474              :   bool shouldRepaint(_RimPainter oldDelegate) =>
     475            3 :       oldDelegate.color != color || oldDelegate.topLit != topLit;
     476              : }
     477              : 
     478              : /// Paints the focus ring: a circle outset just past the control edge, with a
     479              : /// 1px gap (the offset) matching the resting design. The gap is filled with
     480              : /// [offsetColor] (the surface) so the ring reads as detached even over a tinted
     481              : /// card.
     482              : class _RingPainter extends CustomPainter {
     483            1 :   const _RingPainter({required this.color, required this.offsetColor});
     484              : 
     485              :   final Color color;
     486              :   final Color offsetColor;
     487              : 
     488            1 :   @override
     489              :   void paint(Canvas canvas, Size size) {
     490            1 :     final center = size.center(Offset.zero);
     491            2 :     final edge = size.width / 2;
     492              :     canvas
     493            1 :       ..drawCircle(
     494              :         center,
     495            2 :         edge + _ringOffset / 2,
     496            1 :         Paint()
     497            2 :           ..color = offsetColor
     498            1 :           ..style = PaintingStyle.stroke
     499            1 :           ..strokeWidth = _ringOffset,
     500              :       )
     501            1 :       ..drawCircle(
     502              :         center,
     503            3 :         edge + _ringOffset + _ringWidth / 2,
     504            1 :         Paint()
     505            2 :           ..color = color
     506            1 :           ..style = PaintingStyle.stroke
     507            1 :           ..strokeWidth = _ringWidth,
     508              :       );
     509              :   }
     510              : 
     511            1 :   @override
     512              :   bool shouldRepaint(_RingPainter oldDelegate) =>
     513            6 :       oldDelegate.color != color || oldDelegate.offsetColor != offsetColor;
     514              : }
        

Generated by: LCOV version 2.0-1