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

            Line data    Source code
       1              : import 'package:flutter/services.dart' show TextInputAction, TextInputType;
       2              : import 'package:flutter/widgets.dart';
       3              : import 'package:fossui/src/components/combobox/foss_combobox.dart';
       4              : import 'package:fossui/src/foundation/foss_field_box.dart';
       5              : import 'package:fossui/src/theme/theme.dart';
       6              : 
       7              : part 'foss_text_field_style.dart';
       8              : part 'foss_text_field_view.dart';
       9              : part 'foss_text_field_visuals.dart';
      10              : 
      11              : const double _disabledOpacity = 0.64;
      12              : 
      13              : /// The size of a [FossTextField].
      14              : enum FossTextFieldSize {
      15              :   /// Compact: 30 logical pixels tall.
      16              :   sm,
      17              : 
      18              :   /// Default: 34 logical pixels tall.
      19              :   md,
      20              : 
      21              :   /// Prominent: 38 logical pixels tall.
      22              :   lg,
      23              : }
      24              : 
      25              : /// {@category Inputs}
      26              : /// {@template foss.text-field.preview}
      27              : /// <img src="https://fossui.org/components/text-field/overview/light.png"
      28              : ///   alt="FossTextField, light theme" width="480"
      29              : ///   style="max-width:100%;height:auto" />
      30              : /// <img src="https://fossui.org/components/text-field/overview/dark.png"
      31              : ///   alt="FossTextField, dark theme" width="480"
      32              : ///   style="max-width:100%;height:auto" />
      33              : ///
      34              : /// See the [text field documentation ↗](https://fossui.org/docs/components/text-field) or
      35              : /// try it live in the
      36              : /// [playground ↗](https://play.fossui.org/components/#/?path=components/text_field/fosstextfield/playground).
      37              : /// {@endtemplate}
      38              : ///
      39              : /// A text field in the fossui style.
      40              : ///
      41              : /// Pairs an editable box with an optional [label] above and a [helperText] or
      42              : /// [errorText] caption below. Colors, radius, type, and spacing come from
      43              : /// `context.fossTheme`, so a global retheme restyles every field. For a
      44              : /// one-off, pass a [FossTextFieldStyle] to [style].
      45              : ///
      46              : /// Single line by default. Set [maxLines] to anything other than 1 (or null to
      47              : /// grow without bound) for a multiline textarea: it grows with content,
      48              : /// top-aligns its text, and takes no [leading] / [trailing] icons.
      49              : ///
      50              : /// A non-null [errorText] puts the field in its invalid state and replaces the
      51              : /// helper caption. Passing `enabled: false` disables it. [leading] and
      52              : /// [trailing] take any widget (icon-agnostic) and are themed to match the text.
      53              : ///
      54              : /// The [controller] and [focusNode] are optional; when omitted, the field
      55              : /// creates and disposes its own.
      56              : ///
      57              : /// Text can be selected and edited, but the field shows no copy and paste
      58              : /// selection toolbar: it builds on the widgets layer and takes no platform
      59              : /// selection controls.
      60              : ///
      61              : /// {@macro foss.customize}
      62              : ///
      63              : /// See also [FossAutocomplete] for a field with a filtered dropdown.
      64              : ///
      65              : /// ```dart
      66              : /// FossTextField(
      67              : ///   label: 'Email',
      68              : ///   hintText: 'you@example.com',
      69              : ///   helperText: 'We never share it.',
      70              : ///   keyboardType: TextInputType.emailAddress,
      71              : ///   leading: const Icon(mailIcon),
      72              : ///   onChanged: (value) => setState(() => email = value),
      73              : /// );
      74              : /// ```
      75              : class FossTextField extends StatefulWidget {
      76              :   /// {@macro foss.text-field.preview}
      77              :   ///
      78              :   /// Creates a text field. All fields are optional; the most common pairing is
      79              :   /// a [label] with an [onChanged] callback or a [controller].
      80            4 :   const FossTextField({
      81              :     this.controller,
      82              :     this.focusNode,
      83              :     this.size = FossTextFieldSize.md,
      84              :     this.label,
      85              :     this.hintText,
      86              :     this.helperText,
      87              :     this.errorText,
      88              :     this.enabled = true,
      89              :     this.leading,
      90              :     this.trailing,
      91              :     this.obscureText = false,
      92              :     this.keyboardType,
      93              :     this.textInputAction,
      94              :     this.minLines,
      95              :     this.maxLines = 1,
      96              :     this.onChanged,
      97              :     this.onSubmitted,
      98              :     this.style,
      99              :     super.key,
     100              :   }) : assert(
     101            8 :          maxLines == 1 || (leading == null && trailing == null),
     102              :          'leading and trailing are single-line only; a multiline field has no '
     103              :          'icon rail',
     104              :        );
     105              : 
     106              :   /// Holds the editable text. Created and disposed internally when null.
     107              :   ///
     108              :   /// Swapping a provided controller for null carries the text over, but not the
     109              :   /// selection or the listeners on the old controller.
     110              :   final TextEditingController? controller;
     111              : 
     112              :   /// Manages keyboard focus. Created and disposed internally when null.
     113              :   final FocusNode? focusNode;
     114              : 
     115              :   /// The size. Defaults to [FossTextFieldSize.md].
     116              :   final FossTextFieldSize size;
     117              : 
     118              :   /// Optional label rendered above the box.
     119              :   final String? label;
     120              : 
     121              :   /// Placeholder shown while the field is empty.
     122              :   final String? hintText;
     123              : 
     124              :   /// Helper caption below the box. Hidden when [errorText] is set.
     125              :   final String? helperText;
     126              : 
     127              :   /// Error caption below the box. A non-null value marks the field invalid and
     128              :   /// replaces [helperText].
     129              :   final String? errorText;
     130              : 
     131              :   /// Whether the field accepts input. When false it dims and stops responding.
     132              :   final bool enabled;
     133              : 
     134              :   /// Optional widget before the editable content, themed as an icon.
     135              :   final Widget? leading;
     136              : 
     137              :   /// Optional widget after the editable content, themed as an icon.
     138              :   final Widget? trailing;
     139              : 
     140              :   /// Whether to hide the text, for passwords. Defaults to false.
     141              :   final bool obscureText;
     142              : 
     143              :   /// The keyboard layout to request.
     144              :   final TextInputType? keyboardType;
     145              : 
     146              :   /// The action button on the keyboard (next, done, search, ...).
     147              :   final TextInputAction? textInputAction;
     148              : 
     149              :   /// Starting line count for a multiline field. Ignored when [maxLines] is 1.
     150              :   final int? minLines;
     151              : 
     152              :   /// Maximum visible lines. The default 1 is a single-line input; any other
     153              :   /// value (including null, which grows without bound) makes the field a
     154              :   /// multiline textarea: it grows with content, top-aligns its text, and drops
     155              :   /// the [leading] / [trailing] slots.
     156              :   final int? maxLines;
     157              : 
     158              :   /// Called whenever the text changes.
     159              :   final ValueChanged<String>? onChanged;
     160              : 
     161              :   /// Called when the user submits from the keyboard action button.
     162              :   final ValueChanged<String>? onSubmitted;
     163              : 
     164              :   /// Per-instance overrides layered on the theme-resolved style.
     165              :   final FossTextFieldStyle? style;
     166              : 
     167            4 :   @override
     168            4 :   State<FossTextField> createState() => _FossTextFieldState();
     169              : }
     170              : 
     171              : class _FossTextFieldState extends State<FossTextField>
     172              :     implements TextSelectionGestureDetectorBuilderDelegate {
     173              :   final GlobalKey<EditableTextState> _editableKey =
     174              :       GlobalKey<EditableTextState>();
     175              : 
     176            4 :   late final TextSelectionGestureDetectorBuilder _gestureBuilder =
     177            4 :       TextSelectionGestureDetectorBuilder(delegate: this);
     178              : 
     179              :   // The active controller and focus node, always resolved to a non-null value:
     180              :   // the supplied one when given, otherwise an internally created one. The
     181              :   // `_owned` references hold only what this state created, so dispose touches
     182              :   // exactly those and never a caller's instance.
     183              :   late TextEditingController _controller;
     184              :   late FocusNode _focusNode;
     185              :   TextEditingController? _ownedController;
     186              :   FocusNode? _ownedFocusNode;
     187              : 
     188            3 :   @override
     189            3 :   GlobalKey<EditableTextState> get editableTextKey => _editableKey;
     190              : 
     191            4 :   @override
     192              :   bool get forcePressEnabled => false;
     193              : 
     194            2 :   @override
     195            4 :   bool get selectionEnabled => widget.enabled;
     196              : 
     197            4 :   @override
     198              :   void initState() {
     199            4 :     super.initState();
     200            8 :     final controller = widget.controller;
     201            6 :     _controller = controller ?? (_ownedController = TextEditingController());
     202            8 :     final focusNode = widget.focusNode;
     203            6 :     _focusNode = focusNode ?? (_ownedFocusNode = FocusNode());
     204           12 :     _focusNode.addListener(_onFocusChanged);
     205              :   }
     206              : 
     207            4 :   @override
     208              :   void didUpdateWidget(FossTextField oldWidget) {
     209            4 :     super.didUpdateWidget(oldWidget);
     210           16 :     if (oldWidget.controller != widget.controller) {
     211            3 :       _ownedController?.dispose();
     212            4 :       final controller = widget.controller;
     213              :       if (controller != null) {
     214            2 :         _ownedController = null;
     215            2 :         _controller = controller;
     216              :       } else {
     217            3 :         _controller = _ownedController = TextEditingController(
     218            2 :           text: oldWidget.controller?.text,
     219              :         );
     220              :       }
     221              :     }
     222           16 :     if (oldWidget.focusNode != widget.focusNode) {
     223            6 :       _focusNode.removeListener(_onFocusChanged);
     224            3 :       _ownedFocusNode?.dispose();
     225            4 :       final focusNode = widget.focusNode;
     226              :       if (focusNode != null) {
     227            2 :         _ownedFocusNode = null;
     228            2 :         _focusNode = focusNode;
     229              :       } else {
     230            3 :         _focusNode = _ownedFocusNode = FocusNode();
     231              :       }
     232            6 :       _focusNode.addListener(_onFocusChanged);
     233              :     }
     234              :     // A field disabled mid-edit must not keep focus, or traversal sits on a
     235              :     // dead field and the keyboard stays up.
     236           14 :     if (oldWidget.enabled && !widget.enabled && _focusNode.hasFocus) {
     237            2 :       _focusNode.unfocus();
     238              :     }
     239              :   }
     240              : 
     241            9 :   void _onFocusChanged() => setState(() {});
     242              : 
     243            4 :   @override
     244              :   void dispose() {
     245           12 :     _focusNode.removeListener(_onFocusChanged);
     246            5 :     _ownedController?.dispose();
     247            5 :     _ownedFocusNode?.dispose();
     248            4 :     super.dispose();
     249              :   }
     250              : 
     251            4 :   @override
     252              :   Widget build(BuildContext context) {
     253            4 :     final theme = context.fossTheme;
     254           24 :     final v = _apply(_resolve(theme, widget.size), widget.style);
     255              : 
     256            8 :     final hasError = widget.errorText != null;
     257           14 :     final focused = _focusNode.hasFocus && widget.enabled;
     258              : 
     259            4 :     final box = _buildBox(theme, v, hasError: hasError, focused: focused);
     260              : 
     261           16 :     final caption = widget.errorText ?? widget.helperText;
     262              :     final captionColor = hasError
     263            2 :         ? theme.colors.destructiveForeground
     264            4 :         : v.helperColor;
     265              : 
     266            4 :     return Column(
     267              :       mainAxisSize: MainAxisSize.min,
     268              :       crossAxisAlignment: CrossAxisAlignment.start,
     269            8 :       spacing: theme.spacing(2),
     270            4 :       children: [
     271              :         // The editable carries the field's accessible name, so the visible
     272              :         // label is excluded from semantics to avoid announcing it twice.
     273            8 :         if (widget.label case final label?)
     274            1 :           ExcludeSemantics(
     275            1 :             child: Opacity(
     276            2 :               opacity: widget.enabled ? 1 : _disabledOpacity,
     277            1 :               child: Text(
     278              :                 label,
     279            3 :                 style: v.labelStyle.copyWith(color: v.labelColor),
     280              :               ),
     281              :             ),
     282              :           ),
     283            4 :         box,
     284              :         if (caption case final text?)
     285            1 :           Semantics(
     286              :             liveRegion: hasError,
     287            1 :             child: Text(
     288              :               text,
     289            2 :               style: v.helperStyle.copyWith(color: captionColor),
     290              :             ),
     291              :           ),
     292              :       ],
     293              :     );
     294              :   }
     295              : 
     296            4 :   Widget _buildBox(
     297              :     FossThemeData theme,
     298              :     _FieldVisuals v, {
     299              :     required bool hasError,
     300              :     required bool focused,
     301              :   }) {
     302            4 :     final colors = theme.colors;
     303              : 
     304              :     // A multiline field grows with its text: top-align the content, add
     305              :     // vertical padding, size the min height to the starting line count, and
     306              :     // drop the single-line icon rail.
     307           12 :     final multiline = widget.maxLines != 1;
     308              :     // Vertical inset trims 1px against the border, matching the horizontal
     309              :     // inset.
     310              :     final padding = multiline
     311            6 :         ? v.padding.add(EdgeInsets.symmetric(vertical: theme.spacing(1.5) - 1))
     312            4 :         : v.padding;
     313              : 
     314            4 :     final box = FossFieldBox(
     315            8 :       enabled: widget.enabled,
     316              :       hasError: hasError,
     317              :       focused: focused,
     318            4 :       background: v.background,
     319            4 :       borderColor: v.borderColor,
     320            4 :       ringColor: colors.ring,
     321            4 :       destructiveColor: colors.destructive,
     322            4 :       borderRadius: v.borderRadius,
     323            5 :       minHeight: multiline ? _multilineMinHeight(theme, v) : v.minHeight,
     324            4 :       shadow: v.shadow,
     325            4 :       isDark: colors.isDark,
     326            4 :       child: Padding(
     327              :         padding: padding,
     328            4 :         child: Row(
     329            4 :           spacing: v.gap,
     330              :           crossAxisAlignment: multiline
     331              :               ? CrossAxisAlignment.start
     332              :               : CrossAxisAlignment.center,
     333            4 :           children: [
     334            8 :             if (widget.leading case final leading? when !multiline)
     335            2 :               IconTheme.merge(data: v.iconTheme, child: leading),
     336            4 :             Expanded(
     337            4 :               child: _FieldEditable(
     338            4 :                 editableKey: _editableKey,
     339            4 :                 controller: _controller,
     340            4 :                 focusNode: _focusNode,
     341              :                 colors: colors,
     342              :                 visuals: v,
     343            8 :                 enabled: widget.enabled,
     344            8 :                 obscureText: widget.obscureText,
     345            8 :                 keyboardType: widget.keyboardType,
     346            8 :                 textInputAction: widget.textInputAction,
     347            8 :                 minLines: widget.minLines,
     348            8 :                 maxLines: widget.maxLines,
     349            8 :                 label: widget.label,
     350            8 :                 hintText: widget.hintText,
     351            8 :                 onChanged: widget.onChanged,
     352            8 :                 onSubmitted: widget.onSubmitted,
     353              :               ),
     354              :             ),
     355            8 :             if (widget.trailing case final trailing? when !multiline)
     356            8 :               IconTheme.merge(data: v.iconTheme, child: trailing),
     357              :           ],
     358              :         ),
     359              :       ),
     360              :     );
     361              : 
     362            8 :     if (!widget.enabled) return box;
     363              : 
     364              :     // The selection gesture detector requests focus on tap and positions the
     365              :     // caret; translucent so taps anywhere in the box reach it. A tap outside
     366              :     // releases focus and dismisses the keyboard, as touch users expect.
     367            4 :     return TapRegion(
     368            1 :       onTapOutside: (_) {
     369            4 :         if (_focusNode.hasFocus) _focusNode.unfocus();
     370              :       },
     371            8 :       child: _gestureBuilder.buildGestureDetector(
     372              :         behavior: HitTestBehavior.translucent,
     373              :         child: box,
     374              :       ),
     375              :     );
     376              :   }
     377              : 
     378              :   // Minimum box height for a multiline field: the starting line count times the
     379              :   // resolved line height, plus the vertical padding. Defaults to 3 lines when
     380              :   // [minLines] is unset, matching the reference textarea's resting size.
     381            1 :   double _multilineMinHeight(FossThemeData theme, _FieldVisuals v) {
     382            2 :     final lines = widget.minLines ?? 3;
     383            1 :     final style = v.textStyle;
     384              :     // Scale the line by the ambient text scaler so the resting textarea keeps
     385              :     // its [lines]-line height as the user's font size grows.
     386            2 :     final scaler = MediaQuery.textScalerOf(context);
     387              :     final lineHeight =
     388            4 :         (style.height ?? 1.5) * scaler.scale(style.fontSize ?? 16);
     389            6 :     return lines * lineHeight + (theme.spacing(1.5) - 1) * 2;
     390              :   }
     391              : }
        

Generated by: LCOV version 2.0-1