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

            Line data    Source code
       1              : import 'dart:math' as math;
       2              : 
       3              : import 'package:flutter/services.dart';
       4              : import 'package:flutter/widgets.dart';
       5              : import 'package:fossui/src/foundation/foss_since.dart';
       6              : import 'package:fossui/src/theme/theme.dart';
       7              : 
       8              : part 'foss_accordion_style.dart';
       9              : 
      10              : // Header geometry, mobile base. The chevron is painted in-package, so its size
      11              : // and opacity are widget constants rather than tokens.
      12              : const double _chevronSize = 16;
      13              : const double _chevronOpacity = 0.80;
      14              : const double _chevronStroke = 1.5;
      15              : 
      16              : // The chevron aligns to the first line of the title, nudged down to sit on the
      17              : // text baseline rather than the line box top.
      18              : const double _chevronNudge = 2;
      19              : 
      20              : const double _disabledOpacity = 0.64;
      21              : const double _ringWidth = 3;
      22              : const double _minTapTarget = 48;
      23              : 
      24              : /// One collapsible section of a [FossAccordion]: a [value] id, a [title]
      25              : /// header, and a [child] panel revealed when the section is open.
      26              : ///
      27              : /// This is data passed to [FossAccordion.children], not a widget. The accordion
      28              : /// owns the open set and renders the header, chevron, and animated panel.
      29              : ///
      30              : /// ```dart
      31              : /// const FossAccordionItem(
      32              : ///   value: 'shipping',
      33              : ///   title: Text('Shipping'),
      34              : ///   child: Text('Ships in two business days.'),
      35              : /// );
      36              : /// ```
      37              : @FossSince('0.1.1')
      38              : @immutable
      39              : class FossAccordionItem {
      40              :   /// Creates a section keyed by [value].
      41            1 :   const FossAccordionItem({
      42              :     required this.value,
      43              :     required this.title,
      44              :     required this.child,
      45              :     this.enabled = true,
      46              :   });
      47              : 
      48              :   /// The id of this section, unique within a [FossAccordion].
      49              :   final String value;
      50              : 
      51              :   /// The header content. Any widget; text inherits the title style.
      52              :   final Widget title;
      53              : 
      54              :   /// The panel content, revealed when the section is open. Any widget; text
      55              :   /// inherits the muted panel style.
      56              :   final Widget child;
      57              : 
      58              :   /// Whether the section accepts input. A disabled section dims and is skipped
      59              :   /// by the pointer and the keyboard.
      60              :   final bool enabled;
      61              : }
      62              : 
      63              : /// {@category Layout}
      64              : /// {@template foss.accordion.preview}
      65              : /// <img src="https://fossui.org/components/accordion/overview/light.png"
      66              : ///   alt="FossAccordion, light theme" width="480"
      67              : ///   style="max-width:100%;height:auto" />
      68              : /// <img src="https://fossui.org/components/accordion/overview/dark.png"
      69              : ///   alt="FossAccordion, dark theme" width="480"
      70              : ///   style="max-width:100%;height:auto" />
      71              : ///
      72              : /// See the [accordion documentation ↗](https://fossui.org/docs/components/accordion)
      73              : /// or try it live in the
      74              : /// [playground ↗](https://play.fossui.org/components/#/?path=components/accordion/fossaccordion/playground).
      75              : /// {@endtemplate}
      76              : ///
      77              : /// A stack of collapsible sections: each header toggles a panel of content open
      78              : /// or closed, with a rotating chevron and an animated height.
      79              : ///
      80              : /// [FossAccordion] owns the open set. Pass [value] with [onValueChanged] to
      81              : /// control it, or leave [value] null and seed [initialValue] to let the widget
      82              : /// hold its own set. In single mode (the default) opening a section closes the
      83              : /// others; set [multiple] to keep any number open. In single mode [collapsible]
      84              : /// lets the open section close on a second tap, so zero can be open.
      85              : ///
      86              : /// Colors, type, the chevron rotation, and the panel slide come from
      87              : /// `context.fossTheme`; pass a [FossAccordionStyle] to [style] for a one-off.
      88              : ///
      89              : /// {@macro foss.customize}
      90              : ///
      91              : /// ```dart
      92              : /// FossAccordion(
      93              : ///   initialValue: const {'a'},
      94              : ///   children: const [
      95              : ///     FossAccordionItem(
      96              : ///       value: 'a',
      97              : ///       title: Text('Is it accessible?'),
      98              : ///       child: Text('Yes. It follows the accessibility pattern.'),
      99              : ///     ),
     100              : ///     FossAccordionItem(
     101              : ///       value: 'b',
     102              : ///       title: Text('Is it styled?'),
     103              : ///       child: Text('Yes. It reads its colors and type from the theme.'),
     104              : ///     ),
     105              : ///   ],
     106              : /// );
     107              : /// ```
     108              : @FossSince('0.1.1')
     109              : class FossAccordion extends StatefulWidget {
     110              :   /// {@macro foss.accordion.preview}
     111              :   ///
     112              :   /// Creates an accordion over [children].
     113            1 :   const FossAccordion({
     114              :     required this.children,
     115              :     this.multiple = false,
     116              :     this.collapsible = true,
     117              :     this.initialValue,
     118              :     this.value,
     119              :     this.onValueChanged,
     120              :     this.style,
     121              :     super.key,
     122              :   }) : assert(
     123            1 :          value == null || initialValue == null,
     124              :          'Pass value (controlled) or initialValue (uncontrolled), not both.',
     125              :        );
     126              : 
     127              :   /// The ordered sections. Each [FossAccordionItem.value] must be unique.
     128              :   final List<FossAccordionItem> children;
     129              : 
     130              :   /// Whether more than one section may be open at once. Defaults to false
     131              :   /// (single): opening a section closes the others.
     132              :   final bool multiple;
     133              : 
     134              :   /// In single mode, whether the open section closes on a second tap (so zero
     135              :   /// sections can be open). Ignored when [multiple] is true. Defaults to true.
     136              :   final bool collapsible;
     137              : 
     138              :   /// The open set when uncontrolled ([value] is null). The widget owns the set
     139              :   /// after seeding.
     140              :   final Set<String>? initialValue;
     141              : 
     142              :   /// The open set when controlled. The parent owns the set and the widget
     143              :   /// renders it.
     144              :   final Set<String>? value;
     145              : 
     146              :   /// Called with the next open set whenever a section toggles. Fires in both
     147              :   /// controlled and uncontrolled modes.
     148              :   final ValueChanged<Set<String>>? onValueChanged;
     149              : 
     150              :   /// Per-instance overrides layered on the theme-resolved style.
     151              :   final FossAccordionStyle? style;
     152              : 
     153            1 :   @override
     154            1 :   State<FossAccordion> createState() => _FossAccordionState();
     155              : }
     156              : 
     157              : class _FossAccordionState extends State<FossAccordion> {
     158              :   final Map<String, FocusNode> _nodes = <String, FocusNode>{};
     159              :   late Set<String> _internal;
     160              :   String? _focused;
     161              : 
     162            4 :   Set<String> get _open => widget.value ?? _internal;
     163              : 
     164            1 :   @override
     165              :   void initState() {
     166            1 :     super.initState();
     167            2 :     assert(() {
     168            6 :       final ids = widget.children.map((c) => c.value).toList();
     169            4 :       return ids.length == ids.toSet().length;
     170            1 :     }(), 'FossAccordionItem values must be unique.');
     171            2 :     _internal = _seed();
     172              :   }
     173              : 
     174            1 :   @override
     175              :   void didUpdateWidget(FossAccordion oldWidget) {
     176            1 :     super.didUpdateWidget(oldWidget);
     177            6 :     final values = widget.children.map((c) => c.value).toSet();
     178            6 :     final stale = _nodes.keys.where((v) => !values.contains(v)).toList();
     179            2 :     for (final value in stale) {
     180            3 :       _nodes.remove(value)?.dispose();
     181              :     }
     182            4 :     if (_focused != null && !values.contains(_focused)) _focused = null;
     183              :     // Uncontrolled: drop open ids whose item was removed. Prune now so the
     184              :     // render is correct; defer the notify to after the frame, since firing
     185              :     // onValueChanged during a parent rebuild would setState mid-build.
     186            2 :     if (widget.value == null) {
     187            2 :       final pruned = _internal.intersection(values);
     188            4 :       if (pruned.length != _internal.length) {
     189            1 :         _internal = pruned;
     190            2 :         final notify = widget.onValueChanged;
     191              :         if (notify != null) {
     192            3 :           WidgetsBinding.instance.addPostFrameCallback((_) {
     193            2 :             if (mounted) notify(pruned);
     194              :           });
     195              :         }
     196              :       }
     197              :     }
     198              :   }
     199              : 
     200            1 :   @override
     201              :   void dispose() {
     202            3 :     for (final node in _nodes.values) {
     203            1 :       node.dispose();
     204              :     }
     205            1 :     super.dispose();
     206              :   }
     207              : 
     208              :   // Single mode holds at most one id: keep the first seed in children order and
     209              :   // drop the rest, so the invariant holds from the first frame.
     210            1 :   Set<String> _seed() {
     211            2 :     final initial = widget.initialValue;
     212              :     if (initial == null) return <String>{};
     213            3 :     if (widget.multiple) return <String>{...initial};
     214            3 :     for (final item in widget.children) {
     215            3 :       if (initial.contains(item.value)) return <String>{item.value};
     216              :     }
     217              :     return <String>{};
     218              :   }
     219              : 
     220            3 :   FocusNode _nodeFor(String value) => _nodes.putIfAbsent(value, FocusNode.new);
     221              : 
     222            1 :   void _toggle(String value) {
     223            1 :     final open = _open;
     224              :     final Set<String> next;
     225            2 :     if (widget.multiple) {
     226            1 :       next = <String>{...open};
     227            1 :       if (!next.add(value)) next.remove(value);
     228            1 :     } else if (open.contains(value)) {
     229            2 :       next = widget.collapsible ? <String>{} : open;
     230              :     } else {
     231            1 :       next = <String>{value};
     232              :     }
     233            4 :     if (next.length == open.length && next.containsAll(open)) return;
     234            3 :     widget.onValueChanged?.call(next);
     235            5 :     if (widget.value == null) setState(() => _internal = next);
     236              :   }
     237              : 
     238              :   // Walks from [from] by [step], skipping disabled sections, without wrapping.
     239            1 :   int? _adjacent(int from, int step) {
     240            7 :     for (var i = from + step; i >= 0 && i < widget.children.length; i += step) {
     241            4 :       if (widget.children[i].enabled) return i;
     242              :     }
     243              :     return null;
     244              :   }
     245              : 
     246            1 :   int? _edge({required bool last}) {
     247            5 :     final indices = List<int>.generate(widget.children.length, (i) => i);
     248            3 :     for (final i in last ? indices.reversed : indices) {
     249            4 :       if (widget.children[i].enabled) return i;
     250              :     }
     251              :     return null;
     252              :   }
     253              : 
     254            1 :   void _moveFocus(int? target) {
     255              :     if (target == null) return;
     256            6 :     _nodeFor(widget.children[target].value).requestFocus();
     257              :   }
     258              : 
     259            1 :   @override
     260              :   Widget build(BuildContext context) {
     261            1 :     final theme = context.fossTheme;
     262            3 :     final v = _resolve(theme, widget.style);
     263              :     final reduceMotion =
     264            2 :         MediaQuery.maybeOf(context)?.disableAnimations ?? false;
     265              : 
     266            1 :     return Column(
     267              :       mainAxisSize: MainAxisSize.min,
     268              :       crossAxisAlignment: CrossAxisAlignment.stretch,
     269            1 :       children: <Widget>[
     270            5 :         for (var i = 0; i < widget.children.length; i++)
     271            1 :           _buildItem(theme, v, reduceMotion, i),
     272              :       ],
     273              :     );
     274              :   }
     275              : 
     276            1 :   Widget _buildItem(
     277              :     FossThemeData theme,
     278              :     _AccordionVisuals v,
     279              :     bool reduceMotion,
     280              :     int index,
     281              :   ) {
     282            3 :     final item = widget.children[index];
     283            3 :     final open = _open.contains(item.value);
     284            5 :     final last = index == widget.children.length - 1;
     285            2 :     final duration = reduceMotion ? Duration.zero : theme.motion.overlay;
     286              : 
     287            1 :     Widget header = Padding(
     288            1 :       padding: v.headerPadding,
     289            1 :       child: Row(
     290              :         crossAxisAlignment: CrossAxisAlignment.start,
     291            1 :         spacing: v.headerGap,
     292            1 :         children: <Widget>[
     293            1 :           Expanded(
     294            1 :             child: DefaultTextStyle.merge(
     295            1 :               style: v.titleStyle,
     296            1 :               child: item.title,
     297              :             ),
     298              :           ),
     299            1 :           _Chevron(
     300              :             open: open,
     301            1 :             color: v.chevronColor,
     302              :             duration: duration,
     303              :           ),
     304              :         ],
     305              :       ),
     306              :     );
     307              : 
     308            1 :     header = ConstrainedBox(
     309              :       constraints: const BoxConstraints(minHeight: _minTapTarget),
     310              :       child: header,
     311              :     );
     312              : 
     313            4 :     if (_focused == item.value && item.enabled) {
     314            1 :       header = CustomPaint(
     315            1 :         foregroundPainter: _RingPainter(
     316            2 :           color: theme.colors.ring,
     317            2 :           radius: theme.radii.md,
     318              :         ),
     319              :         child: header,
     320              :       );
     321              :     }
     322              : 
     323            1 :     final trigger = MergeSemantics(
     324            1 :       child: Semantics(
     325              :         button: true,
     326              :         expanded: open,
     327            1 :         enabled: item.enabled,
     328            1 :         onTap: item.enabled ? () => _toggle(item.value) : null,
     329            1 :         child: FocusableActionDetector(
     330            1 :           enabled: item.enabled,
     331            2 :           focusNode: _nodeFor(item.value),
     332            1 :           mouseCursor: item.enabled
     333              :               ? SystemMouseCursors.click
     334              :               : SystemMouseCursors.basic,
     335              :           // Only clear when this item owns the highlight: on an arrow move the
     336              :           // next item's highlight-on can arrive before this one's off, and an
     337              :           // unguarded clear would drop the ring off the focused item.
     338            1 :           onShowFocusHighlight: (value) {
     339              :             if (value) {
     340            4 :               setState(() => _focused = item.value);
     341            3 :             } else if (_focused == item.value) {
     342            3 :               setState(() => _focused = null);
     343              :             }
     344              :           },
     345              :           shortcuts: const <ShortcutActivator, Intent>{
     346              :             SingleActivator(LogicalKeyboardKey.arrowDown): _MoveFocusIntent(1),
     347              :             SingleActivator(LogicalKeyboardKey.arrowUp): _MoveFocusIntent(-1),
     348              :             SingleActivator(LogicalKeyboardKey.home): _EdgeFocusIntent(
     349              :               last: false,
     350              :             ),
     351              :             SingleActivator(LogicalKeyboardKey.end): _EdgeFocusIntent(
     352              :               last: true,
     353              :             ),
     354              :           },
     355            1 :           actions: <Type, Action<Intent>>{
     356            1 :             ActivateIntent: CallbackAction<ActivateIntent>(
     357            1 :               onInvoke: (_) {
     358            2 :                 _toggle(item.value);
     359              :                 return null;
     360              :               },
     361              :             ),
     362            1 :             _MoveFocusIntent: CallbackAction<_MoveFocusIntent>(
     363            1 :               onInvoke: (intent) {
     364            3 :                 _moveFocus(_adjacent(index, intent.step));
     365              :                 return null;
     366              :               },
     367              :             ),
     368            1 :             _EdgeFocusIntent: CallbackAction<_EdgeFocusIntent>(
     369            1 :               onInvoke: (intent) {
     370            3 :                 _moveFocus(_edge(last: intent.last));
     371              :                 return null;
     372              :               },
     373              :             ),
     374              :           },
     375            1 :           child: GestureDetector(
     376              :             behavior: HitTestBehavior.opaque,
     377              :             excludeFromSemantics: true,
     378            4 :             onTap: item.enabled ? () => _toggle(item.value) : null,
     379              :             child: header,
     380              :           ),
     381              :         ),
     382              :       ),
     383              :     );
     384              : 
     385            1 :     final panel = _Panel(
     386              :       open: open,
     387              :       duration: duration,
     388            1 :       child: Padding(
     389            1 :         padding: v.panelPadding,
     390            3 :         child: DefaultTextStyle.merge(style: v.panelStyle, child: item.child),
     391              :       ),
     392              :     );
     393              : 
     394            1 :     Widget section = Column(
     395              :       mainAxisSize: MainAxisSize.min,
     396              :       crossAxisAlignment: CrossAxisAlignment.stretch,
     397            1 :       children: <Widget>[trigger, panel],
     398              :     );
     399              : 
     400              :     if (!last) {
     401            1 :       section = DecoratedBox(
     402            1 :         decoration: BoxDecoration(
     403            3 :           border: Border(bottom: BorderSide(color: v.dividerColor)),
     404              :         ),
     405              :         child: section,
     406              :       );
     407              :     }
     408            1 :     if (!item.enabled) {
     409            1 :       section = Opacity(opacity: _disabledOpacity, child: section);
     410              :     }
     411              :     return section;
     412              :   }
     413              : }
     414              : 
     415              : /// Moves keyboard focus to the section [step] away (skipping disabled ones).
     416              : class _MoveFocusIntent extends Intent {
     417            2 :   const _MoveFocusIntent(this.step);
     418              : 
     419              :   final int step;
     420              : }
     421              : 
     422              : /// Moves keyboard focus to the first ([last] false) or last section.
     423              : class _EdgeFocusIntent extends Intent {
     424            2 :   const _EdgeFocusIntent({required this.last});
     425              : 
     426              :   final bool last;
     427              : }
     428              : 
     429              : /// The chevron: a down-pointing glyph that rotates to point up when [open].
     430              : class _Chevron extends StatelessWidget {
     431            1 :   const _Chevron({
     432              :     required this.open,
     433              :     required this.color,
     434              :     required this.duration,
     435              :   });
     436              : 
     437              :   final bool open;
     438              :   final Color color;
     439              :   final Duration duration;
     440              : 
     441            1 :   @override
     442              :   Widget build(BuildContext context) {
     443            1 :     return TweenAnimationBuilder<double>(
     444            2 :       tween: Tween<double>(end: open ? 1 : 0),
     445            1 :       duration: duration,
     446              :       curve: Curves.easeInOut,
     447            2 :       builder: (context, t, child) => Transform.translate(
     448              :         offset: const Offset(0, _chevronNudge),
     449            2 :         child: Transform.rotate(angle: t * math.pi, child: child),
     450              :       ),
     451            1 :       child: CustomPaint(
     452              :         size: const Size.square(_chevronSize),
     453            2 :         painter: _ChevronPainter(color),
     454              :       ),
     455              :     );
     456              :   }
     457              : }
     458              : 
     459              : /// The collapsible panel: its height animates between 0 and the content's
     460              : /// natural height, clipped so content never spills during the transition.
     461              : class _Panel extends StatelessWidget {
     462            1 :   const _Panel({
     463              :     required this.open,
     464              :     required this.duration,
     465              :     required this.child,
     466              :   });
     467              : 
     468              :   final bool open;
     469              :   final Duration duration;
     470              :   final Widget child;
     471              : 
     472            1 :   @override
     473              :   Widget build(BuildContext context) {
     474            1 :     return TweenAnimationBuilder<double>(
     475            2 :       tween: Tween<double>(end: open ? 1 : 0),
     476            1 :       duration: duration,
     477              :       curve: Curves.easeInOut,
     478            2 :       builder: (context, t, child) => ClipRect(
     479            1 :         child: Align(
     480              :           alignment: Alignment.topCenter,
     481              :           heightFactor: t,
     482              :           child: child,
     483              :         ),
     484              :       ),
     485              :       // Closed content stays out of the semantics tree; only the open panel is
     486              :       // announced as the header's region.
     487            3 :       child: ExcludeSemantics(excluding: !open, child: child),
     488              :     );
     489              :   }
     490              : }
     491              : 
     492              : /// Paints a down-pointing chevron centered in its box.
     493              : class _ChevronPainter extends CustomPainter {
     494            1 :   const _ChevronPainter(this.color);
     495              : 
     496              :   final Color color;
     497              : 
     498            1 :   @override
     499              :   void paint(Canvas canvas, Size size) {
     500            1 :     final w = size.width;
     501            1 :     final h = size.height;
     502            1 :     final path = Path()
     503            3 :       ..moveTo(w * 0.25, h * 0.375)
     504            3 :       ..lineTo(w * 0.5, h * 0.625)
     505            3 :       ..lineTo(w * 0.75, h * 0.375);
     506            1 :     canvas.drawPath(
     507              :       path,
     508            1 :       Paint()
     509            2 :         ..color = color
     510            1 :         ..style = PaintingStyle.stroke
     511            1 :         ..strokeWidth = _chevronStroke
     512            1 :         ..strokeCap = StrokeCap.round
     513            1 :         ..strokeJoin = StrokeJoin.round,
     514              :     );
     515              :   }
     516              : 
     517            1 :   @override
     518            3 :   bool shouldRepaint(_ChevronPainter old) => old.color != color;
     519              : }
     520              : 
     521              : /// Paints the focus ring: a superellipse outset hugging the trigger at
     522              : /// [radius], so the ring reads smooth, not circular.
     523              : class _RingPainter extends CustomPainter {
     524            1 :   const _RingPainter({required this.color, required this.radius});
     525              : 
     526              :   final Color color;
     527              :   final double radius;
     528              : 
     529            1 :   @override
     530              :   void paint(Canvas canvas, Size size) {
     531            3 :     final rect = (Offset.zero & size).inflate(_ringWidth / 2);
     532            1 :     canvas.drawRSuperellipse(
     533            1 :       RSuperellipse.fromRectAndRadius(
     534              :         rect,
     535            4 :         Radius.circular(radius + _ringWidth / 2),
     536              :       ),
     537            1 :       Paint()
     538            2 :         ..color = color
     539            1 :         ..style = PaintingStyle.stroke
     540            1 :         ..strokeWidth = _ringWidth,
     541              :     );
     542              :   }
     543              : 
     544            1 :   @override
     545              :   bool shouldRepaint(_RingPainter old) =>
     546            6 :       old.color != color || old.radius != radius;
     547              : }
     548              : 
     549              : /// Builds the default appearance from the theme tokens, then lays a
     550              : /// per-instance [override] over it field by field.
     551            1 : _AccordionVisuals _resolve(FossThemeData theme, FossAccordionStyle? override) {
     552            1 :   final c = theme.colors;
     553            1 :   final t = theme.typography;
     554            2 :   final gap = theme.spacing(4);
     555            1 :   return _AccordionVisuals(
     556              :     titleStyle:
     557            5 :         override?.titleTextStyle ?? t.sm.medium.copyWith(color: c.foreground),
     558              :     panelStyle:
     559            4 :         override?.panelTextStyle ?? t.sm.copyWith(color: c.mutedForeground),
     560              :     chevronColor:
     561            1 :         override?.chevronColor ??
     562            2 :         c.foreground.withValues(alpha: _chevronOpacity),
     563            2 :     dividerColor: override?.dividerColor ?? c.border,
     564              :     headerPadding:
     565            2 :         override?.headerPadding ?? EdgeInsets.symmetric(vertical: gap),
     566            2 :     panelPadding: override?.panelPadding ?? EdgeInsets.only(bottom: gap),
     567              :     headerGap: gap,
     568              :   );
     569              : }
     570              : 
     571              : /// The fully resolved, non-null appearance. A [FossAccordionStyle] override is
     572              : /// laid over it by [_resolve], so the widget reads only non-null fields.
     573              : @immutable
     574              : class _AccordionVisuals {
     575            1 :   const _AccordionVisuals({
     576              :     required this.titleStyle,
     577              :     required this.panelStyle,
     578              :     required this.chevronColor,
     579              :     required this.dividerColor,
     580              :     required this.headerPadding,
     581              :     required this.panelPadding,
     582              :     required this.headerGap,
     583              :   });
     584              : 
     585              :   final TextStyle titleStyle;
     586              :   final TextStyle panelStyle;
     587              :   final Color chevronColor;
     588              :   final Color dividerColor;
     589              :   final EdgeInsetsGeometry headerPadding;
     590              :   final EdgeInsetsGeometry panelPadding;
     591              :   final double headerGap;
     592              : }
        

Generated by: LCOV version 2.0-1