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

            Line data    Source code
       1              : part of 'foss_combobox.dart';
       2              : 
       3              : /// The shared input, anchored popup, filtering, roving highlight, and dismiss
       4              : /// handling behind [FossAutocomplete] and [FossCombobox]. The two faces differ
       5              : /// only in the config they pass: whether rows carry a check indicator, the
       6              : /// selection predicate, and what a pick reports.
       7              : class _FossComboboxField<T> extends StatefulWidget {
       8            3 :   const _FossComboboxField({
       9              :     required this.options,
      10              :     required this.size,
      11              :     required this.enabled,
      12              :     required this.showIndicator,
      13              :     required this.showTrigger,
      14              :     required this.showClear,
      15              :     required this.emptyText,
      16              :     required this.filter,
      17              :     required this.isSelected,
      18              :     required this.onPick,
      19              :     this.controller,
      20              :     this.focusNode,
      21              :     this.label,
      22              :     this.hintText,
      23              :     this.errorText,
      24              :     this.startAddon,
      25              :     this.initialText,
      26              :     this.resetOnBlur = false,
      27              :     this.onTextChanged,
      28              :     this.onClear,
      29              :     this.style,
      30              :     super.key,
      31              :   });
      32              : 
      33              :   final List<FossComboboxItem<T>> options;
      34              :   final FossTextFieldSize size;
      35              :   final bool enabled;
      36              :   final bool showIndicator;
      37              :   final bool showTrigger;
      38              :   final bool showClear;
      39              :   final String emptyText;
      40              :   final bool Function(String label, String query) filter;
      41              :   final bool Function(T value) isSelected;
      42              :   final void Function(FossComboboxItem<T> item) onPick;
      43              :   final TextEditingController? controller;
      44              :   final FocusNode? focusNode;
      45              :   final String? label;
      46              :   final String? hintText;
      47              :   final String? errorText;
      48              :   final Widget? startAddon;
      49              :   final String? initialText;
      50              : 
      51              :   /// When true, blurring without a pick restores the field text to the
      52              :   /// selected option's label. Single-select uses this; freeform autocomplete
      53              :   /// does not.
      54              :   final bool resetOnBlur;
      55              :   final ValueChanged<String>? onTextChanged;
      56              :   final VoidCallback? onClear;
      57              :   final FossComboboxStyle? style;
      58              : 
      59            3 :   @override
      60            3 :   State<_FossComboboxField<T>> createState() => _FossComboboxFieldState<T>();
      61              : }
      62              : 
      63              : class _FossComboboxFieldState<T> extends State<_FossComboboxField<T>>
      64              :     with
      65              :         SingleTickerProviderStateMixin,
      66              :         _ComboboxPopup<T, _FossComboboxField<T>> {
      67              :   late TextEditingController _controller;
      68              :   late FocusNode _focusNode;
      69              :   TextEditingController? _ownedController;
      70              :   FocusNode? _ownedFocusNode;
      71              : 
      72            3 :   @override
      73              :   void initState() {
      74            3 :     super.initState();
      75            3 :     _controller =
      76            6 :         widget.controller ??
      77           12 :         (_ownedController = TextEditingController(text: widget.initialText));
      78           15 :     _focusNode = widget.focusNode ?? (_ownedFocusNode = FocusNode());
      79            9 :     _focusNode.addListener(_onFocusChanged);
      80            9 :     _controller.addListener(_onTextChanged);
      81              :   }
      82              : 
      83            2 :   @override
      84              :   void didUpdateWidget(_FossComboboxField<T> oldWidget) {
      85            2 :     super.didUpdateWidget(oldWidget);
      86            8 :     if (widget.controller != oldWidget.controller) {
      87            1 :       _swapController(oldWidget);
      88              :     } else {
      89            2 :       _syncSelectedText(oldWidget);
      90              :     }
      91            9 :     if (widget.focusNode != oldWidget.focusNode) _swapFocusNode(oldWidget);
      92              :   }
      93              : 
      94            1 :   void _swapController(_FossComboboxField<T> oldWidget) {
      95            3 :     (oldWidget.controller ?? _ownedController)?.removeListener(_onTextChanged);
      96            1 :     _ownedController?.dispose();
      97            2 :     final provided = widget.controller;
      98              :     if (provided != null) {
      99            1 :       _ownedController = null;
     100            1 :       _controller = provided;
     101              :     } else {
     102            3 :       _controller = _ownedController = TextEditingController(
     103            2 :         text: oldWidget.controller?.text ?? widget.initialText,
     104              :       );
     105              :     }
     106            3 :     _controller.addListener(_onTextChanged);
     107              :   }
     108              : 
     109              :   // Reflect an externally driven selection: when the resolved label changes and
     110              :   // we own the controller, sync the field text. Skipped when it already
     111              :   // matches, so a local pick never reclobbers what it just wrote.
     112            2 :   void _syncSelectedText(_FossComboboxField<T> oldWidget) {
     113            4 :     if (widget.controller != null) return;
     114            8 :     if (widget.initialText == oldWidget.initialText) return;
     115           10 :     if (widget.initialText == _controller.text) return;
     116            4 :     final text = widget.initialText ?? '';
     117            2 :     _controller
     118            4 :       ..removeListener(_onTextChanged)
     119            2 :       ..text = text
     120            6 :       ..selection = TextSelection.collapsed(offset: text.length)
     121            4 :       ..addListener(_onTextChanged);
     122              :   }
     123              : 
     124            1 :   void _swapFocusNode(_FossComboboxField<T> oldWidget) {
     125            3 :     (oldWidget.focusNode ?? _ownedFocusNode)?.removeListener(_onFocusChanged);
     126            1 :     _ownedFocusNode?.dispose();
     127            2 :     final provided = widget.focusNode;
     128              :     if (provided != null) {
     129            1 :       _ownedFocusNode = null;
     130            1 :       _focusNode = provided;
     131              :     } else {
     132            3 :       _focusNode = _ownedFocusNode = FocusNode();
     133              :     }
     134            3 :     _focusNode.addListener(_onFocusChanged);
     135              :   }
     136              : 
     137            3 :   @override
     138              :   void dispose() {
     139            9 :     _focusNode.removeListener(_onFocusChanged);
     140            9 :     _controller.removeListener(_onTextChanged);
     141            6 :     _ownedController?.dispose();
     142            6 :     _ownedFocusNode?.dispose();
     143            3 :     super.dispose();
     144              :   }
     145              : 
     146            2 :   @override
     147            4 :   bool get popupEnabled => widget.enabled;
     148              : 
     149              :   // Maps the combobox overrides onto the embedded field so the input box honors
     150              :   // the fill, border, radius, text, and shadow, not just the popup.
     151            3 :   FossTextFieldStyle? get _fieldStyle {
     152            6 :     final s = widget.style;
     153              :     if (s == null) return null;
     154            2 :     return FossTextFieldStyle(
     155            2 :       backgroundColor: s.backgroundColor,
     156            2 :       borderColor: s.borderColor,
     157            2 :       borderRadius: s.borderRadius,
     158            2 :       textStyle: s.textStyle,
     159            2 :       shadow: s.shadow,
     160              :     );
     161              :   }
     162              : 
     163              :   // The label of the committed selection, or null when nothing is selected.
     164              :   // Autocomplete never selects, so this stays null there.
     165            2 :   String? get _selectedLabel {
     166            6 :     for (final o in widget.options) {
     167            9 :       if (widget.isSelected(o.value)) return o.label;
     168              :     }
     169              :     return null;
     170              :   }
     171              : 
     172            2 :   @override
     173              :   List<FossComboboxItem<T>> get filteredOptions {
     174            4 :     final query = _controller.text;
     175              :     // A pick writes the selected label into the field, so on reopen the query
     176              :     // equals the selection; treat that as no query rather than self-filtering
     177              :     // to the one chosen row.
     178           10 :     if (query.isEmpty || query == _selectedLabel) return widget.options;
     179            2 :     return [
     180            4 :       for (final o in widget.options)
     181            9 :         if (widget.filter(o.label, query)) o,
     182              :     ];
     183              :   }
     184              : 
     185            2 :   @override
     186              :   int initialHighlight() {
     187            2 :     final options = filteredOptions;
     188            2 :     final selected = options.indexWhere(
     189           12 :       (o) => o.enabled && widget.isSelected(o.value),
     190              :     );
     191            4 :     if (selected != -1) return selected;
     192            2 :     return _firstEnabled(options);
     193              :   }
     194              : 
     195            1 :   @override
     196            1 :   void onActivate(FossComboboxItem<T> item) => _pick(item);
     197              : 
     198            2 :   void _onFocusChanged() {
     199            4 :     if (_focusNode.hasFocus) {
     200            2 :       _openPopup();
     201              :     } else {
     202            2 :       _closePopup();
     203            2 :       _restoreSelectedText();
     204              :     }
     205              :   }
     206              : 
     207              :   // On blur without a pick, a single-select field snaps its text back to the
     208              :   // committed selection (or empty), so stray typing never lingers as the value.
     209            2 :   void _restoreSelectedText() {
     210            4 :     if (!widget.resetOnBlur) return;
     211           16 :     final selected = widget.options.where((o) => widget.isSelected(o.value));
     212            4 :     final text = selected.isEmpty ? '' : selected.first.label;
     213            6 :     if (_controller.text == text) return;
     214            2 :     _controller
     215            4 :       ..removeListener(_onTextChanged)
     216            2 :       ..text = text
     217            6 :       ..selection = TextSelection.collapsed(offset: text.length)
     218            4 :       ..addListener(_onTextChanged);
     219              :   }
     220              : 
     221            2 :   void _onTextChanged() {
     222            7 :     widget.onTextChanged?.call(_controller.text);
     223            2 :     _resetHighlight();
     224              :   }
     225              : 
     226            1 :   void _pick(FossComboboxItem<T> item) {
     227            1 :     if (!item.enabled) return;
     228            1 :     _controller
     229            2 :       ..removeListener(_onTextChanged)
     230            2 :       ..text = item.label
     231            4 :       ..selection = TextSelection.collapsed(offset: item.label.length)
     232            2 :       ..addListener(_onTextChanged);
     233            3 :     widget.onPick(item);
     234            1 :     _closePopup();
     235              :   }
     236              : 
     237            1 :   void _clear() {
     238            2 :     _controller.clear();
     239            3 :     widget.onClear?.call();
     240              :   }
     241              : 
     242            1 :   void _toggle() {
     243            1 :     if (_open) {
     244            1 :       _closePopup();
     245              :     } else {
     246            2 :       _focusNode.requestFocus();
     247            1 :       _openPopup();
     248              :     }
     249              :   }
     250              : 
     251            3 :   @override
     252              :   Widget build(BuildContext context) {
     253           21 :     final v = _apply(_resolve(context.fossTheme, widget.size), widget.style);
     254              : 
     255            3 :     final field = TextFieldTapRegion(
     256            3 :       child: Focus(
     257              :         canRequestFocus: false,
     258              :         skipTraversal: true,
     259            2 :         onKeyEvent: (node, event) => _handlePopupKey(event),
     260            3 :         child: Semantics(
     261            3 :           expanded: _open,
     262            3 :           child: KeyedSubtree(
     263            3 :             key: _anchorKey,
     264            3 :             child: FossTextField(
     265            3 :               controller: _controller,
     266            3 :               focusNode: _focusNode,
     267            6 :               size: widget.size,
     268            6 :               label: widget.label,
     269            6 :               hintText: widget.hintText,
     270            6 :               errorText: widget.errorText,
     271            6 :               enabled: widget.enabled,
     272            6 :               leading: widget.startAddon,
     273            3 :               trailing: _trailing(v),
     274            3 :               style: _fieldStyle,
     275            2 :               onSubmitted: (_) => _activateHighlighted(),
     276              :             ),
     277              :           ),
     278              :         ),
     279              :       ),
     280              :     );
     281              : 
     282            3 :     return OverlayPortal(
     283            3 :       controller: _portal,
     284            3 :       overlayChildBuilder: _buildOverlay,
     285              :       child: field,
     286              :     );
     287              :   }
     288              : 
     289            3 :   Widget? _trailing(_ComboboxVisuals v) {
     290            6 :     final color = v.foreground.withValues(
     291            9 :       alpha: v.foreground.a * _affixOpacity,
     292              :     );
     293            3 :     return ListenableBuilder(
     294            3 :       listenable: _controller,
     295            3 :       builder: (context, _) {
     296              :         final showClear =
     297           16 :             widget.showClear && _controller.text.isNotEmpty && widget.enabled;
     298            3 :         final children = <Widget>[
     299              :           if (showClear)
     300            2 :             _IconButton(
     301            2 :               size: v.iconSize,
     302            2 :               onTap: _clear,
     303            2 :               painter: CloseGlyph(color),
     304              :               label: 'Clear',
     305              :             ),
     306            6 :           if (widget.showTrigger && !showClear)
     307            3 :             _IconButton(
     308            3 :               size: v.iconSize,
     309            9 :               onTap: widget.enabled ? _toggle : null,
     310            3 :               painter: ChevronUpDownGlyph(color),
     311              :               label: 'Show options',
     312              :             ),
     313              :         ];
     314            3 :         if (children.isEmpty) return const SizedBox.shrink();
     315            3 :         return Row(mainAxisSize: MainAxisSize.min, children: children);
     316              :       },
     317              :     );
     318              :   }
     319              : 
     320            2 :   @override
     321              :   Widget buildPopupSurface(BuildContext context) {
     322            2 :     final theme = context.fossTheme;
     323           12 :     final v = _apply(_resolve(theme, widget.size), widget.style);
     324            2 :     final options = filteredOptions;
     325              :     final Widget body;
     326            2 :     if (options.isEmpty) {
     327            2 :       body = Padding(
     328            6 :         padding: EdgeInsets.all(theme.spacing(2)),
     329            2 :         child: Text(
     330            4 :           widget.emptyText,
     331              :           textAlign: TextAlign.center,
     332            6 :           style: v.textStyle.copyWith(color: v.mutedForeground),
     333              :         ),
     334              :       );
     335              :     } else {
     336            2 :       body = ListView(
     337              :         shrinkWrap: true,
     338            6 :         padding: EdgeInsets.all(theme.spacing(1)),
     339            2 :         children: [
     340            6 :           for (var i = 0; i < options.length; i++)
     341            2 :             _ComboRow<T>(
     342            2 :               item: options[i],
     343              :               theme: theme,
     344              :               visuals: v,
     345            4 :               showIndicator: widget.showIndicator,
     346           10 :               selected: widget.isSelected(options[i].value),
     347            4 :               highlighted: i == _highlight,
     348            2 :               onEnter: () => _highlightRow(i),
     349            3 :               onTap: () => _pick(options[i]),
     350              :             ),
     351              :         ],
     352              :       );
     353              :     }
     354              : 
     355            2 :     return _popupChrome(v, body);
     356              :   }
     357              : }
     358              : 
     359              : /// A single popup row: an optional check indicator, an optional icon, and the
     360              : /// label. Autocomplete rows omit the indicator column.
     361              : class _ComboRow<T> extends StatelessWidget {
     362            2 :   const _ComboRow({
     363              :     required this.item,
     364              :     required this.theme,
     365              :     required this.visuals,
     366              :     required this.showIndicator,
     367              :     required this.selected,
     368              :     required this.highlighted,
     369              :     required this.onEnter,
     370              :     required this.onTap,
     371              :   });
     372              : 
     373              :   final FossComboboxItem<T> item;
     374              :   final FossThemeData theme;
     375              :   final _ComboboxVisuals visuals;
     376              :   final bool showIndicator;
     377              :   final bool selected;
     378              :   final bool highlighted;
     379              :   final VoidCallback onEnter;
     380              :   final VoidCallback onTap;
     381              : 
     382            2 :   @override
     383              :   Widget build(BuildContext context) {
     384            4 :     final enabled = item.enabled;
     385            6 :     final fill = highlighted ? visuals.highlightColor : null;
     386            2 :     final textColor = highlighted
     387            4 :         ? visuals.highlightForeground
     388            4 :         : visuals.foreground;
     389              : 
     390            2 :     Widget row = Padding(
     391              :       // Combobox rows carry a wider end inset to balance the indicator
     392              :       // column; the flat autocomplete row is symmetric.
     393            2 :       padding: EdgeInsetsDirectional.only(
     394            6 :         start: theme.spacing(2),
     395           11 :         end: showIndicator ? theme.spacing(4) : theme.spacing(2),
     396            6 :         top: theme.spacing(1),
     397            6 :         bottom: theme.spacing(1),
     398              :       ),
     399            2 :       child: Row(
     400            2 :         children: [
     401            4 :           if (showIndicator) ...[
     402            2 :             SizedBox(
     403              :               width: _indicatorColumn,
     404              :               height: _indicatorColumn,
     405            4 :               child: selected ? FossGlyphIcon(CheckGlyph(textColor)) : null,
     406              :             ),
     407            8 :             SizedBox(width: theme.spacing(2)),
     408              :           ],
     409            5 :           if (item.icon case final icon?) ...[
     410            1 :             IconTheme.merge(
     411            3 :               data: IconThemeData(color: textColor, size: visuals.iconSize),
     412              :               child: icon,
     413              :             ),
     414            4 :             SizedBox(width: theme.spacing(2)),
     415              :           ],
     416            2 :           Expanded(
     417            2 :             child: Text(
     418            4 :               item.label,
     419              :               maxLines: 1,
     420              :               overflow: TextOverflow.ellipsis,
     421            6 :               style: visuals.textStyle.copyWith(color: textColor),
     422              :             ),
     423              :           ),
     424              :         ],
     425              :       ),
     426              :     );
     427              : 
     428            2 :     row = ConstrainedBox(
     429              :       constraints: const BoxConstraints(minHeight: _rowMinHeight),
     430            2 :       child: DecoratedBox(
     431            2 :         decoration: ShapeDecoration(
     432              :           color: fill,
     433            2 :           shape: RoundedSuperellipseBorder(
     434            6 :             borderRadius: BorderRadius.circular(visuals.rowRadius),
     435              :           ),
     436              :         ),
     437            2 :         child: Align(heightFactor: 1, child: row),
     438              :       ),
     439              :     );
     440              : 
     441            1 :     if (!enabled) row = Opacity(opacity: _disabledOpacity, child: row);
     442              : 
     443            2 :     return MergeSemantics(
     444            2 :       child: Semantics(
     445              :         button: true,
     446            2 :         selected: selected,
     447              :         enabled: enabled,
     448            2 :         child: MouseRegion(
     449              :           cursor: enabled ? SystemMouseCursors.click : SystemMouseCursors.basic,
     450            3 :           onEnter: enabled ? (_) => onEnter() : null,
     451            2 :           child: GestureDetector(
     452              :             behavior: HitTestBehavior.opaque,
     453            2 :             onTap: enabled ? onTap : null,
     454              :             child: row,
     455              :           ),
     456              :         ),
     457              :       ),
     458              :     );
     459              :   }
     460              : }
     461              : 
     462              : /// A small square icon button for the trailing trigger and clear affordances,
     463              : /// carrying a [label] so assistive tech announces it as a button.
     464              : class _IconButton extends StatelessWidget {
     465            3 :   const _IconButton({
     466              :     required this.size,
     467              :     required this.painter,
     468              :     required this.onTap,
     469              :     required this.label,
     470              :   });
     471              : 
     472              :   final double size;
     473              :   final CustomPainter painter;
     474              :   final VoidCallback? onTap;
     475              :   final String label;
     476              : 
     477            3 :   @override
     478              :   Widget build(BuildContext context) {
     479              :     // The glyph keeps its small visual footprint while an OverflowBox grows the
     480              :     // hit region to the minimum touch target without inflating the field.
     481              :     // HitTestBehavior.opaque makes the whole region tappable.
     482            3 :     return Semantics(
     483              :       button: true,
     484            3 :       label: label,
     485            3 :       enabled: onTap != null,
     486            3 :       child: SizedBox.square(
     487            3 :         dimension: size,
     488            3 :         child: OverflowBox(
     489              :           maxWidth: _minHitTarget,
     490              :           maxHeight: _minHitTarget,
     491            3 :           child: GestureDetector(
     492              :             behavior: HitTestBehavior.opaque,
     493            3 :             onTap: onTap,
     494            3 :             child: MouseRegion(
     495            3 :               cursor: onTap == null
     496              :                   ? SystemMouseCursors.basic
     497              :                   : SystemMouseCursors.click,
     498            3 :               child: Center(
     499            3 :                 child: CustomPaint(
     500            6 :                   size: Size.square(size),
     501            3 :                   painter: painter,
     502              :                 ),
     503              :               ),
     504              :             ),
     505              :           ),
     506              :         ),
     507              :       ),
     508              :     );
     509              :   }
     510              : }
     511              : 
     512              : /// Positions the popup below the anchor, flipping above when there is no room,
     513              : /// and clamping its height to the viewport and the popup maximum.
     514              : class _PopupLayout extends SingleChildLayoutDelegate {
     515            2 :   const _PopupLayout({required this.anchor, required this.bottomInset});
     516              : 
     517              :   final Rect anchor;
     518              : 
     519              :   /// Height taken by the on-screen keyboard at the bottom of the overlay.
     520              :   final double bottomInset;
     521              : 
     522            2 :   @override
     523              :   BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
     524            6 :     final viewportBottom = constraints.maxHeight - bottomInset;
     525            8 :     final below = viewportBottom - anchor.bottom - _popupOffset;
     526            6 :     final above = anchor.top - _popupOffset;
     527            6 :     final room = (math.max(below, above) - _popupMargin).clamp(
     528              :       0.0,
     529            2 :       constraints.maxHeight,
     530              :     );
     531              :     // Match the anchor width, capped to the viewport minus a margin on each
     532              :     // side, so the popup keeps symmetric insets and never runs off the edge.
     533            2 :     final width = math.min(
     534            4 :       anchor.width,
     535            6 :       constraints.maxWidth - _popupMargin * 2,
     536              :     );
     537            2 :     return BoxConstraints(
     538              :       minWidth: width,
     539              :       maxWidth: width,
     540            2 :       maxHeight: math.min(room, _popupMaxHeight),
     541              :     );
     542              :   }
     543              : 
     544            2 :   @override
     545              :   Offset getPositionForChild(Size size, Size childSize) {
     546           14 :     final below = (size.height - bottomInset) - anchor.bottom - _popupOffset;
     547            4 :     final placeBelow = childSize.height <= below;
     548              :     final dy = placeBelow
     549            6 :         ? anchor.bottom + _popupOffset
     550            5 :         : anchor.top - _popupOffset - childSize.height;
     551            4 :     final dx = anchor.left
     552            2 :         .clamp(
     553              :           _popupMargin,
     554           10 :           math.max(_popupMargin, size.width - _popupMargin - childSize.width),
     555              :         )
     556            2 :         .toDouble();
     557            2 :     return Offset(dx, dy);
     558              :   }
     559              : 
     560            2 :   @override
     561              :   bool shouldRelayout(_PopupLayout oldDelegate) =>
     562           12 :       oldDelegate.anchor != anchor || oldDelegate.bottomInset != bottomInset;
     563              : }
        

Generated by: LCOV version 2.0-1