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

            Line data    Source code
       1              : import 'package:flutter/services.dart'
       2              :     show
       3              :         AutofillHints,
       4              :         FilteringTextInputFormatter,
       5              :         LengthLimitingTextInputFormatter,
       6              :         TextInputAction,
       7              :         TextInputFormatter,
       8              :         TextInputType;
       9              : import 'package:flutter/widgets.dart';
      10              : import 'package:fossui/src/foundation/foss_field_box.dart';
      11              : import 'package:fossui/src/foundation/foss_since.dart';
      12              : import 'package:fossui/src/theme/theme.dart';
      13              : 
      14              : part 'foss_otp_field_style.dart';
      15              : 
      16              : // Dark surfaces lift the fill by the input color at 32% of its alpha, matching
      17              : // the shared field box.
      18              : const double _darkFillOpacity = 0.32;
      19              : 
      20              : /// The size of a [FossOtpField].
      21              : enum FossOtpFieldSize {
      22              :   /// Default: 36 x 36 slots with 16pt text.
      23              :   md,
      24              : 
      25              :   /// Prominent: 40 x 40 slots with 18pt text.
      26              :   lg,
      27              : }
      28              : 
      29              : /// The character set a [FossOtpField] slot accepts. A rejected character is
      30              : /// dropped, never shown.
      31              : enum FossOtpValidation {
      32              :   /// Digits only (`0`-`9`). The default, and the numeric keyboard.
      33              :   numeric,
      34              : 
      35              :   /// Latin letters only (`a`-`z`, `A`-`Z`).
      36              :   alphabetic,
      37              : 
      38              :   /// Latin letters and digits.
      39              :   alphanumeric,
      40              : 
      41              :   /// No filtering; every character is accepted.
      42              :   none,
      43              : }
      44              : 
      45              : /// {@category Inputs}
      46              : /// {@template foss.otp-field.preview}
      47              : /// <img src="https://fossui.org/components/otp-field/overview/light.png"
      48              : ///   alt="FossOtpField, light theme" width="360"
      49              : ///   style="max-width:100%;height:auto" />
      50              : /// <img src="https://fossui.org/components/otp-field/overview/dark.png"
      51              : ///   alt="FossOtpField, dark theme" width="360"
      52              : ///   style="max-width:100%;height:auto" />
      53              : ///
      54              : /// See the [otp field documentation ↗](https://fossui.org/docs/components/otp-field) or
      55              : /// try it live in the
      56              : /// [playground ↗](https://play.fossui.org/components/#/?path=components/otp_field/fossotpfield/playground).
      57              : /// {@endtemplate}
      58              : ///
      59              : /// A segmented one-time-code field: a row of single-character slots over one
      60              : /// hidden input.
      61              : ///
      62              : /// Typing places a character in the active slot and advances the caret;
      63              : /// backspace clears and retreats; arrow keys move the caret; a paste (or the
      64              : /// platform one-time-code autofill) fills the whole row at once, dropping any
      65              : /// character [validation] rejects. Colors, radius, and type come from
      66              : /// `context.fossTheme`, so a global retheme restyles every field. For a
      67              : /// one-off, pass a [FossOtpFieldStyle] to [style].
      68              : ///
      69              : /// The code is a plain [String] of up to [length] characters. Use it controlled
      70              : /// with [value] and [onChanged], or uncontrolled; [onCompleted] fires each time
      71              : /// the row fills. Set [obscure] to mask each character with a dot, and [groups]
      72              : /// (summing to [length]) to split the row with a separator, for example
      73              : /// `groups: [3, 3]`. Passing `enabled: false` disables the whole field.
      74              : ///
      75              : /// {@macro foss.customize}
      76              : ///
      77              : /// ```dart
      78              : /// FossOtpField(
      79              : ///   length: 6,
      80              : ///   groups: const [3, 3],
      81              : ///   onCompleted: (code) => verify(code),
      82              : /// );
      83              : /// ```
      84              : @FossSince('0.1.1')
      85              : class FossOtpField extends StatefulWidget {
      86              :   /// {@macro foss.otp-field.preview}
      87              :   ///
      88              :   /// Creates a one-time-code field. Only [length] is required.
      89            1 :   const FossOtpField({
      90              :     required this.length,
      91              :     this.value,
      92              :     this.onChanged,
      93              :     this.onCompleted,
      94              :     this.size = FossOtpFieldSize.md,
      95              :     this.validation = FossOtpValidation.numeric,
      96              :     this.groups,
      97              :     this.obscure = false,
      98              :     this.autofocus = false,
      99              :     this.error = false,
     100              :     this.enabled = true,
     101              :     this.semanticsLabel,
     102              :     this.style,
     103              :     super.key,
     104            2 :   }) : assert(length > 0, 'length must be at least 1');
     105              : 
     106              :   /// The number of slots, and the maximum code length.
     107              :   final int length;
     108              : 
     109              :   /// The current code, for controlled use. Pair with [onChanged]. When null the
     110              :   /// field keeps its own value.
     111              :   final String? value;
     112              : 
     113              :   /// Called with the whole code on every edit.
     114              :   final ValueChanged<String>? onChanged;
     115              : 
     116              :   /// Called with the code each time the row fills to [length]. Fires on every
     117              :   /// transition into the full state, so deleting a digit and retyping it fires
     118              :   /// again.
     119              :   final ValueChanged<String>? onCompleted;
     120              : 
     121              :   /// The size. Defaults to [FossOtpFieldSize.md].
     122              :   final FossOtpFieldSize size;
     123              : 
     124              :   /// The accepted character set. Defaults to [FossOtpValidation.numeric].
     125              :   final FossOtpValidation validation;
     126              : 
     127              :   /// Optional group sizes that split the row with a separator pill, for example
     128              :   /// `[3, 3]`. Ignored unless the sizes sum to [length].
     129              :   final List<int>? groups;
     130              : 
     131              :   /// Whether to mask each character with a dot, for privacy. Defaults to false.
     132              :   final bool obscure;
     133              : 
     134              :   /// Whether to focus the field on first build. Defaults to false.
     135              :   final bool autofocus;
     136              : 
     137              :   /// Whether to show the invalid state. Defaults to false.
     138              :   final bool error;
     139              : 
     140              :   /// Whether the field accepts input. When false it dims and stops responding.
     141              :   final bool enabled;
     142              : 
     143              :   /// The accessible name for the field. Defaults to a generic code label.
     144              :   final String? semanticsLabel;
     145              : 
     146              :   /// Per-instance overrides layered on the theme-resolved style.
     147              :   final FossOtpFieldStyle? style;
     148              : 
     149            1 :   @override
     150            1 :   State<FossOtpField> createState() => _FossOtpFieldState();
     151              : }
     152              : 
     153              : class _FossOtpFieldState extends State<FossOtpField>
     154              :     with SingleTickerProviderStateMixin {
     155              :   late final TextEditingController _controller;
     156              :   late final FocusNode _focusNode;
     157              :   late final AnimationController _blink;
     158              : 
     159              :   // The last text seen, so [onChanged] fires only on a real value change, not
     160              :   // on a caret move, and a controlled write does not echo back.
     161              :   String _lastText = '';
     162              :   bool _wasComplete = false;
     163              : 
     164              :   // A programmatic controller write skips the input formatters, so a controlled
     165              :   // value is clamped to [length] here to keep it inside the slot row.
     166            1 :   String _clamped(String? value) {
     167              :     final text = value ?? '';
     168            4 :     return text.length > widget.length
     169            3 :         ? text.substring(0, widget.length)
     170              :         : text;
     171              :   }
     172              : 
     173            1 :   @override
     174              :   void initState() {
     175            1 :     super.initState();
     176            4 :     _lastText = _clamped(widget.value);
     177            6 :     _wasComplete = _lastText.length == widget.length;
     178            3 :     _controller = TextEditingController(text: _lastText);
     179            2 :     _focusNode = FocusNode();
     180            3 :     _controller.addListener(_onChanged);
     181            3 :     _focusNode.addListener(_onFocusChanged);
     182              :     // Duration is set from the theme in build, where the inherited lookup is
     183              :     // safe; a resting default keeps the controller valid until then.
     184            2 :     _blink = AnimationController(
     185              :       vsync: this,
     186              :       duration: const Duration(seconds: 1),
     187              :     );
     188              :   }
     189              : 
     190            1 :   @override
     191              :   void didUpdateWidget(FossOtpField oldWidget) {
     192            1 :     super.didUpdateWidget(oldWidget);
     193            2 :     if (widget.value case final incoming?) {
     194            1 :       final v = _clamped(incoming);
     195            3 :       if (v != _controller.text) {
     196              :         // Suppress the echo: mark this write seen before it fires the listener.
     197              :         // Resync completeness too, so a later user edit still fires onCompleted
     198              :         // exactly once against the true prior state.
     199            1 :         _lastText = v;
     200            5 :         _wasComplete = v.length == widget.length;
     201            3 :         _controller.value = TextEditingValue(
     202              :           text: v,
     203            2 :           selection: TextSelection.collapsed(offset: v.length),
     204              :         );
     205              :       }
     206              :     }
     207            5 :     if (oldWidget.enabled && !widget.enabled && _focusNode.hasFocus) {
     208            2 :       _focusNode.unfocus();
     209              :     }
     210              :   }
     211              : 
     212            1 :   @override
     213              :   void dispose() {
     214            1 :     _controller
     215            2 :       ..removeListener(_onChanged)
     216            1 :       ..dispose();
     217            1 :     _focusNode
     218            2 :       ..removeListener(_onFocusChanged)
     219            1 :       ..dispose();
     220            2 :     _blink.dispose();
     221            1 :     super.dispose();
     222              :   }
     223              : 
     224            3 :   void _onFocusChanged() => setState(() {});
     225              : 
     226            1 :   void _onChanged() {
     227            2 :     final text = _controller.text;
     228            2 :     if (text != _lastText) {
     229            1 :       _lastText = text;
     230            3 :       widget.onChanged?.call(text);
     231            4 :       final complete = text.length == widget.length;
     232            4 :       if (complete && !_wasComplete) widget.onCompleted?.call(text);
     233            1 :       _wasComplete = complete;
     234              :     }
     235              :     // Rebuild for a caret move too, so the active slot tracks the selection.
     236            2 :     setState(() {});
     237              :   }
     238              : 
     239            1 :   void _handleTap() {
     240            2 :     if (!widget.enabled) return;
     241            2 :     _focusNode.requestFocus();
     242              :     // Drop the caret past the entered digits: the row fills left to right, so
     243              :     // end-of-text is the next empty slot regardless of where the tap landed.
     244            3 :     _controller.selection = TextSelection.collapsed(
     245            3 :       offset: _controller.text.length,
     246              :     );
     247              :   }
     248              : 
     249            1 :   List<TextInputFormatter> get _formatters {
     250            2 :     final allow = switch (widget.validation) {
     251            2 :       FossOtpValidation.numeric => RegExp('[0-9]'),
     252            1 :       FossOtpValidation.alphabetic => RegExp('[A-Za-z]'),
     253            2 :       FossOtpValidation.alphanumeric => RegExp('[A-Za-z0-9]'),
     254            1 :       FossOtpValidation.none => null,
     255              :     };
     256            1 :     return [
     257            3 :       LengthLimitingTextInputFormatter(widget.length),
     258            1 :       if (allow != null) FilteringTextInputFormatter.allow(allow),
     259              :     ];
     260              :   }
     261              : 
     262              :   // The slot the caret sits in, or null when unfocused or the selection spans a
     263              :   // range. A collapsed selection at offset i means the next character lands in
     264              :   // slot i; a caret past the last slot (a full row) clamps to it, so a focused
     265              :   // field always shows exactly one active slot.
     266            1 :   int? _activeIndex() {
     267            4 :     if (!_focusNode.hasFocus || !widget.enabled) return null;
     268            2 :     final selection = _controller.selection;
     269            1 :     if (!selection.isCollapsed) return null;
     270            1 :     final offset = selection.baseOffset;
     271            1 :     if (offset < 0) return null;
     272            4 :     return offset.clamp(0, widget.length - 1);
     273              :   }
     274              : 
     275              :   // The boundary slot indices a separator follows, when [groups] sums to
     276              :   // [length]; empty otherwise (a bad grouping is a silent no-op).
     277            1 :   Set<int> _separatorAfter() {
     278            2 :     final groups = widget.groups;
     279              :     if (groups == null) return const {};
     280              :     var sum = 0;
     281            2 :     for (final g in groups) {
     282            1 :       sum += g;
     283              :     }
     284            3 :     if (sum != widget.length) return const {};
     285              :     final boundaries = <int>{};
     286              :     var running = 0;
     287            4 :     for (var i = 0; i < groups.length - 1; i++) {
     288            2 :       running += groups[i];
     289            2 :       boundaries.add(running - 1);
     290              :     }
     291              :     return boundaries;
     292              :   }
     293              : 
     294            1 :   @override
     295              :   Widget build(BuildContext context) {
     296            1 :     final theme = context.fossTheme;
     297            6 :     final v = _apply(_resolve(theme, widget.size), widget.style);
     298            1 :     final colors = theme.colors;
     299              : 
     300            4 :     _blink.duration = theme.motion.caretBlink;
     301            1 :     final reduceMotion = MediaQuery.maybeDisableAnimationsOf(context) ?? false;
     302              : 
     303            2 :     final baseFont = v.textStyle.fontSize ?? 16;
     304            1 :     final scaler = MediaQuery.textScalerOf(context);
     305            2 :     final scale = scaler.scale(baseFont) / baseFont;
     306              : 
     307            2 :     final text = _controller.text;
     308            1 :     final active = _activeIndex();
     309            1 :     final separators = _separatorAfter();
     310              : 
     311              :     // The caret blinks only while a slot is active; an idle field schedules no
     312              :     // frames, and reduced motion holds the caret steady.
     313              :     if (active != null && !reduceMotion) {
     314            4 :       if (!_blink.isAnimating) _blink.repeat(reverse: true);
     315              :     } else {
     316            4 :       if (_blink.isAnimating) _blink.stop();
     317            2 :       _blink.value = 1;
     318              :     }
     319              : 
     320            1 :     final row = <Widget>[];
     321            4 :     for (var i = 0; i < widget.length; i++) {
     322            1 :       row.add(
     323            1 :         _OtpSlot(
     324            3 :           character: i < text.length ? text[i] : null,
     325            1 :           active: i == active,
     326            2 :           error: widget.error,
     327            2 :           enabled: widget.enabled,
     328            2 :           obscure: widget.obscure,
     329              :           scale: scale,
     330            1 :           blink: _blink,
     331              :           visuals: v,
     332              :           colors: colors,
     333              :         ),
     334              :       );
     335            1 :       if (separators.contains(i)) {
     336            2 :         row.add(_OtpSeparator(visuals: v, scale: scale));
     337              :       }
     338              :     }
     339              : 
     340            1 :     final editable = EditableText(
     341            1 :       controller: _controller,
     342            1 :       focusNode: _focusNode,
     343            2 :       readOnly: !widget.enabled,
     344              :       rendererIgnoresPointer: true,
     345              :       showCursor: false,
     346              :       cursorWidth: 0,
     347            2 :       style: v.textStyle.copyWith(color: const Color(0x00000000)),
     348              :       cursorColor: const Color(0x00000000),
     349              :       backgroundCursorColor: const Color(0x00000000),
     350              :       selectionColor: const Color(0x00000000),
     351            3 :       keyboardType: widget.validation == FossOtpValidation.numeric
     352              :           ? TextInputType.number
     353              :           : TextInputType.text,
     354              :       textInputAction: TextInputAction.done,
     355            1 :       inputFormatters: _formatters,
     356            2 :       autofocus: widget.autofocus,
     357              :       autofillHints: const [AutofillHints.oneTimeCode],
     358              :       textAlign: TextAlign.center,
     359            2 :       enableInteractiveSelection: widget.enabled,
     360              :     );
     361              : 
     362            1 :     return MergeSemantics(
     363            1 :       child: Semantics(
     364            2 :         label: widget.semanticsLabel ?? 'Verification code',
     365              :         textField: true,
     366            2 :         enabled: widget.enabled,
     367              :         // Read back progress: masked as dots when obscured, else the digits.
     368            2 :         value: widget.obscure
     369            4 :             ? '•' * _controller.text.length
     370            2 :             : _controller.text,
     371              :         // A tap outside releases focus and dismisses the keyboard, as touch
     372              :         // users expect.
     373            1 :         child: TapRegion(
     374            1 :           onTapOutside: (_) {
     375            4 :             if (_focusNode.hasFocus) _focusNode.unfocus();
     376              :           },
     377            1 :           child: GestureDetector(
     378              :             behavior: HitTestBehavior.opaque,
     379            1 :             onTap: _handleTap,
     380            1 :             child: Stack(
     381            1 :               children: [
     382            1 :                 Positioned.fill(child: editable),
     383            1 :                 ExcludeSemantics(
     384            1 :                   child: Row(
     385              :                     mainAxisSize: MainAxisSize.min,
     386            2 :                     spacing: v.gap * scale,
     387              :                     children: row,
     388              :                   ),
     389              :                 ),
     390              :               ],
     391              :             ),
     392              :           ),
     393              :         ),
     394              :       ),
     395              :     );
     396              :   }
     397              : }
     398              : 
     399              : /// A single OTP slot: the shared field box chrome around a centered character,
     400              : /// masked dot, or blinking caret.
     401              : class _OtpSlot extends StatelessWidget {
     402            1 :   const _OtpSlot({
     403              :     required this.character,
     404              :     required this.active,
     405              :     required this.error,
     406              :     required this.enabled,
     407              :     required this.obscure,
     408              :     required this.scale,
     409              :     required this.blink,
     410              :     required this.visuals,
     411              :     required this.colors,
     412              :   });
     413              : 
     414              :   final String? character;
     415              :   final bool active;
     416              :   final bool error;
     417              :   final bool enabled;
     418              :   final bool obscure;
     419              :   final double scale;
     420              :   final Animation<double> blink;
     421              :   final _OtpVisuals visuals;
     422              :   final FossColors colors;
     423              : 
     424            1 :   @override
     425              :   Widget build(BuildContext context) {
     426            4 :     final size = visuals.slotSize * scale;
     427            5 :     final font = (visuals.textStyle.fontSize ?? 16) * scale;
     428              : 
     429              :     final Widget content;
     430            1 :     final char = character;
     431              :     if (char != null) {
     432            1 :       content = obscure
     433            1 :           ? _dot(font)
     434            1 :           : Text(
     435              :               char,
     436              :               textAlign: TextAlign.center,
     437              :               textHeightBehavior: const TextHeightBehavior(
     438              :                 leadingDistribution: TextLeadingDistribution.even,
     439              :               ),
     440            5 :               style: visuals.textStyle.copyWith(color: visuals.textColor),
     441              :             );
     442            1 :     } else if (active) {
     443            1 :       content = _caret(font);
     444              :     } else {
     445              :       content = const SizedBox.shrink();
     446              :     }
     447              : 
     448            1 :     return FossFieldBox(
     449            1 :       enabled: enabled,
     450            1 :       hasError: error,
     451            1 :       focused: active,
     452            2 :       background: visuals.background,
     453            2 :       borderColor: visuals.borderColor,
     454            2 :       ringColor: colors.ring,
     455            2 :       destructiveColor: colors.destructive,
     456            2 :       borderRadius: visuals.borderRadius,
     457              :       minHeight: size,
     458            2 :       shadow: visuals.shadow,
     459            2 :       isDark: colors.isDark,
     460            1 :       child: SizedBox(
     461              :         width: size,
     462              :         height: size,
     463            1 :         child: Center(child: content),
     464              :       ),
     465              :     );
     466              :   }
     467              : 
     468            2 :   Widget _dot(double font) => SizedBox(
     469            1 :     width: font * 0.5,
     470            1 :     height: font * 0.5,
     471            1 :     child: DecoratedBox(
     472            1 :       decoration: BoxDecoration(
     473            2 :         color: visuals.textColor,
     474              :         shape: BoxShape.circle,
     475              :       ),
     476              :     ),
     477              :   );
     478              : 
     479            2 :   Widget _caret(double font) => FadeTransition(
     480            1 :     opacity: blink,
     481            1 :     child: SizedBox(
     482            2 :       width: 2 * scale,
     483              :       height: font,
     484            1 :       child: DecoratedBox(
     485            1 :         decoration: BoxDecoration(
     486            2 :           color: visuals.textColor,
     487            1 :           borderRadius: BorderRadius.circular(FossRadii.full),
     488              :         ),
     489              :       ),
     490              :     ),
     491              :   );
     492              : }
     493              : 
     494              : /// The pill divider between two groups: a full-radius bar in the border color.
     495              : class _OtpSeparator extends StatelessWidget {
     496            1 :   const _OtpSeparator({required this.visuals, required this.scale});
     497              : 
     498              :   final _OtpVisuals visuals;
     499              :   final double scale;
     500              : 
     501            1 :   @override
     502            1 :   Widget build(BuildContext context) => SizedBox(
     503            5 :     width: visuals.separatorSize.width * scale,
     504            5 :     height: visuals.separatorSize.height * scale,
     505            1 :     child: DecoratedBox(
     506            1 :       decoration: BoxDecoration(
     507            2 :         color: visuals.separatorColor,
     508            1 :         borderRadius: BorderRadius.circular(FossRadii.full),
     509              :       ),
     510              :     ),
     511              :   );
     512              : }
     513              : 
     514              : /// Builds the default slot appearance for a [size] from the theme tokens.
     515            1 : _OtpVisuals _resolve(FossThemeData theme, FossOtpFieldSize size) {
     516            1 :   final c = theme.colors;
     517              :   final (slotSize, textStyle) = switch (size) {
     518            3 :     FossOtpFieldSize.md => (36.0, theme.typography.base),
     519            3 :     FossOtpFieldSize.lg => (40.0, theme.typography.lg),
     520              :   };
     521              : 
     522              :   // Dark adds a faint lift over the surface: the input color at 32% of its
     523              :   // alpha, composited to opaque. Light is the bare surface.
     524            1 :   final fill = c.isDark
     525            1 :       ? Color.alphaBlend(
     526            5 :           c.input.withValues(alpha: c.input.a * _darkFillOpacity),
     527            1 :           c.background,
     528              :         )
     529            1 :       : c.background;
     530              : 
     531            1 :   return _OtpVisuals(
     532              :     background: fill,
     533            1 :     borderColor: c.input,
     534            1 :     textColor: c.foreground,
     535            2 :     borderRadius: theme.radii.lg,
     536              :     slotSize: slotSize,
     537              :     textStyle: textStyle,
     538            2 :     gap: theme.spacing(2),
     539            2 :     shadow: theme.shadows.xs,
     540            1 :     separatorColor: c.input,
     541              :     separatorSize: const Size(12, 2),
     542              :   );
     543              : }
     544              : 
     545              : /// Lays a per-instance [override] over the resolved [base], field by field.
     546            1 : _OtpVisuals _apply(_OtpVisuals base, FossOtpFieldStyle? override) {
     547              :   if (override == null) return base;
     548            1 :   return _OtpVisuals(
     549            2 :     background: override.backgroundColor ?? base.background,
     550            2 :     borderColor: override.borderColor ?? base.borderColor,
     551            1 :     textColor: base.textColor,
     552            2 :     borderRadius: override.borderRadius ?? base.borderRadius,
     553            1 :     slotSize: override.slotSize ?? base.slotSize,
     554            2 :     textStyle: override.textStyle ?? base.textStyle,
     555            2 :     gap: override.gap ?? base.gap,
     556            2 :     shadow: override.shadow ?? base.shadow,
     557            2 :     separatorColor: override.separatorColor ?? base.separatorColor,
     558            2 :     separatorSize: override.separatorSize ?? base.separatorSize,
     559              :   );
     560              : }
        

Generated by: LCOV version 2.0-1