LCOV - code coverage report
Current view: top level - components/number_field - foss_number_field.dart Coverage Total Hit
Test: fossui coverage Lines: 100.0 % 242 242
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/components/text_field/foss_text_field.dart'
       6              :     show FossTextField, FossTextFieldSize, fieldMetrics;
       7              : import 'package:fossui/src/foundation/foss_field_box.dart';
       8              : import 'package:fossui/src/foundation/foss_since.dart';
       9              : import 'package:fossui/src/theme/theme.dart';
      10              : 
      11              : part 'foss_number_field_style.dart';
      12              : 
      13              : const double _iconSize = 18;
      14              : const double _disabledOpacity = 0.64;
      15              : 
      16              : // The painted glyph and placeholder sit quieter than the value: the glyph at
      17              : // 80% of the foreground alpha, the placeholder at 72% of the muted alpha.
      18              : const double _glyphOpacity = 0.8;
      19              : const double _placeholderOpacity = 0.72;
      20              : 
      21              : // The text selection highlight is the ring color at a low alpha.
      22              : const double _selectionOpacity = 0.24;
      23              : 
      24              : /// {@category Inputs}
      25              : /// {@template foss.number_field.preview}
      26              : /// <img src="https://fossui.org/components/number_field/overview/light.png"
      27              : ///   alt="FossNumberField, light theme" width="480"
      28              : ///   style="max-width:100%;height:auto" />
      29              : /// <img src="https://fossui.org/components/number_field/overview/dark.png"
      30              : ///   alt="FossNumberField, dark theme" width="480"
      31              : ///   style="max-width:100%;height:auto" />
      32              : ///
      33              : /// See the [number field documentation ↗](https://fossui.org/docs/components/number-field)
      34              : /// or try it live in the
      35              : /// [playground ↗](https://play.fossui.org/components/#/?path=components/number_field/fossnumberfield/playground).
      36              : /// {@endtemplate}
      37              : ///
      38              : /// A numeric input flanked by a decrement and an increment button.
      39              : ///
      40              : /// Type a number, or step it with the buttons and the keyboard. The value is a
      41              : /// [num] held in `[min, max]`, moved by [step] (and [largeStep] on the page
      42              : /// keys). A stepper press moves the value one [step]; it does not auto-repeat
      43              : /// on a held press. Sizing, radius, fill, border, and state colors come from
      44              : /// the same tokens as [FossTextField] through `context.fossTheme`, so the two
      45              : /// controls line up pixel for pixel; a global retheme restyles both. For a
      46              : /// one-off, pass a [FossNumberFieldStyle] to [style].
      47              : ///
      48              : /// Drive it controlled with [value] plus [onChanged], or uncontrolled with
      49              : /// [initialValue]. [onChanged] fires with the parsed value, or null when the
      50              : /// field is cleared or the text does not parse. A typed value out of range
      51              : /// snaps in on commit; the steppers stop at the bounds.
      52              : ///
      53              : /// Display and typed entry route through [format] and [parse]; the defaults are
      54              : /// a plain decimal string and a permissive number parse, with no locale
      55              : /// dependency. Pass your own to render currency or a locale.
      56              : ///
      57              : /// {@macro foss.customize}
      58              : ///
      59              : /// ```dart
      60              : /// FossNumberField(
      61              : ///   value: quantity,
      62              : ///   min: 0,
      63              : ///   max: 10,
      64              : ///   onChanged: (v) => setState(() => quantity = v),
      65              : /// );
      66              : /// ```
      67              : @FossSince('0.1.1')
      68              : class FossNumberField extends StatefulWidget {
      69              :   /// {@macro foss.number_field.preview}
      70              :   ///
      71              :   /// Creates a number field. All fields are optional; drive it with [value] +
      72              :   /// [onChanged] or seed it with [initialValue].
      73            1 :   const FossNumberField({
      74              :     this.value,
      75              :     this.onChanged,
      76              :     this.initialValue,
      77              :     this.min,
      78              :     this.max,
      79              :     this.step = 1,
      80              :     this.largeStep,
      81              :     this.size = FossTextFieldSize.md,
      82              :     this.format,
      83              :     this.parse,
      84              :     this.placeholder,
      85              :     this.error = false,
      86              :     this.enabled = true,
      87              :     this.semanticsLabel,
      88              :     this.style,
      89              :     super.key,
      90              :   });
      91              : 
      92              :   /// The controlled current value. Pair with [onChanged] and omit
      93              :   /// [initialValue]. Null shows an empty field.
      94              :   final num? value;
      95              : 
      96              :   /// Called with the new value whenever it changes, or null when the field is
      97              :   /// cleared or the text does not parse.
      98              :   final ValueChanged<num?>? onChanged;
      99              : 
     100              :   /// The uncontrolled seed value. Omit when [value] is set.
     101              :   final num? initialValue;
     102              : 
     103              :   /// Inclusive lower bound. Null leaves the value unbounded below.
     104              :   final num? min;
     105              : 
     106              :   /// Inclusive upper bound. Null leaves the value unbounded above.
     107              :   final num? max;
     108              : 
     109              :   /// The increment for the buttons and the arrow keys. Defaults to 1.
     110              :   final num step;
     111              : 
     112              :   /// The increment for the page keys. Defaults to ten times [step].
     113              :   final num? largeStep;
     114              : 
     115              :   /// The size. Shares [FossTextFieldSize] with [FossTextField]. Defaults to
     116              :   /// [FossTextFieldSize.md].
     117              :   final FossTextFieldSize size;
     118              : 
     119              :   /// Renders the value for display. Defaults to a plain decimal string.
     120              :   final String Function(num value)? format;
     121              : 
     122              :   /// Reads typed entry into a value. Returns null when the text is not a
     123              :   /// number. Defaults to a permissive number parse.
     124              :   final num? Function(String text)? parse;
     125              : 
     126              :   /// Placeholder shown while the field is empty.
     127              :   final String? placeholder;
     128              : 
     129              :   /// Whether the control shows its invalid state. Recolors the border and ring.
     130              :   final bool error;
     131              : 
     132              :   /// Whether the control accepts input. When false it dims and both steppers
     133              :   /// stop responding.
     134              :   final bool enabled;
     135              : 
     136              :   /// Accessibility name for the control.
     137              :   final String? semanticsLabel;
     138              : 
     139              :   /// Per-instance overrides layered on the theme-resolved style.
     140              :   final FossNumberFieldStyle? style;
     141              : 
     142            1 :   @override
     143            1 :   State<FossNumberField> createState() => _FossNumberFieldState();
     144              : }
     145              : 
     146              : class _FossNumberFieldState extends State<FossNumberField>
     147              :     implements TextSelectionGestureDetectorBuilderDelegate {
     148              :   final GlobalKey<EditableTextState> _editableKey =
     149              :       GlobalKey<EditableTextState>();
     150              : 
     151            1 :   late final TextSelectionGestureDetectorBuilder _gestureBuilder =
     152            1 :       TextSelectionGestureDetectorBuilder(delegate: this);
     153              : 
     154              :   late final TextEditingController _controller;
     155              :   late final FocusNode _focusNode;
     156              : 
     157              :   // The source of truth for the value. Seeded from [value] or [initialValue],
     158              :   // synced from [value] on a controlled update, and updated on edit or step.
     159              :   num? _value;
     160              : 
     161            1 :   @override
     162            1 :   GlobalKey<EditableTextState> get editableTextKey => _editableKey;
     163              : 
     164            1 :   @override
     165              :   bool get forcePressEnabled => false;
     166              : 
     167            1 :   @override
     168            2 :   bool get selectionEnabled => widget.enabled;
     169              : 
     170            6 :   num get _largeStep => widget.largeStep ?? widget.step * 10;
     171              : 
     172            1 :   @override
     173              :   void initState() {
     174            1 :     super.initState();
     175            6 :     _value = _clamp(widget.value ?? widget.initialValue);
     176            4 :     _controller = TextEditingController(text: _displayText(_value));
     177            3 :     _focusNode = FocusNode(onKeyEvent: _handleKey)
     178            2 :       ..addListener(_onFocusChanged);
     179              :   }
     180              : 
     181            1 :   @override
     182              :   void didUpdateWidget(FossNumberField oldWidget) {
     183            1 :     super.didUpdateWidget(oldWidget);
     184              :     // A controlled update from the parent is authoritative: clamp it in and
     185              :     // reformat the field, unless the user is mid-edit and would fight the text.
     186            4 :     if (widget.value != oldWidget.value) {
     187            3 :       final clamped = _clamp(widget.value);
     188            1 :       _value = clamped;
     189            3 :       if (!_focusNode.hasFocus) _syncText();
     190              :       // The parent handed us a value outside the bounds. Report the clamped
     191              :       // value back so a controlled parent converges instead of holding a value
     192              :       // the field can never show. Deferred to avoid notifying mid-build; the
     193              :       // correction clamps to itself, so it settles in one extra frame.
     194            3 :       if (clamped != widget.value) {
     195            3 :         WidgetsBinding.instance.addPostFrameCallback((_) {
     196            4 :           if (mounted) widget.onChanged?.call(clamped);
     197              :         });
     198              :       }
     199              :     }
     200            5 :     if (oldWidget.enabled && !widget.enabled && _focusNode.hasFocus) {
     201            2 :       _focusNode.unfocus();
     202              :     }
     203              :   }
     204              : 
     205            1 :   @override
     206              :   void dispose() {
     207            1 :     _focusNode
     208            2 :       ..removeListener(_onFocusChanged)
     209            1 :       ..dispose();
     210            2 :     _controller.dispose();
     211            1 :     super.dispose();
     212              :   }
     213              : 
     214            4 :   String _format(num value) => (widget.format ?? _defaultFormat)(value);
     215              : 
     216            4 :   num? _parse(String text) => (widget.parse ?? _defaultParse)(text);
     217              : 
     218            2 :   String _displayText(num? value) => value == null ? '' : _format(value);
     219              : 
     220            1 :   num? _clamp(num? value) {
     221              :     if (value == null) return null;
     222              :     var result = value;
     223            2 :     final min = widget.min;
     224            2 :     final max = widget.max;
     225            1 :     if (min != null && result < min) result = min;
     226            1 :     if (max != null && result > max) result = max;
     227              :     return result;
     228              :   }
     229              : 
     230              :   // Writes the formatted value into the controller with the caret at the end,
     231              :   // used after a step, a commit, or a controlled update, never while typing.
     232            1 :   void _syncText() {
     233            2 :     final text = _displayText(_value);
     234            3 :     _controller.value = TextEditingValue(
     235              :       text: text,
     236            2 :       selection: TextSelection.collapsed(offset: text.length),
     237              :     );
     238              :   }
     239              : 
     240            1 :   void _emit(num? next, {required bool syncText}) {
     241            2 :     final changed = next != _value;
     242            3 :     setState(() => _value = next);
     243            1 :     if (syncText) _syncText();
     244            3 :     if (changed) widget.onChanged?.call(next);
     245              :   }
     246              : 
     247              :   // Steps from the current value, or from the lower bound (or zero) when empty,
     248              :   // and clamps into range.
     249            1 :   void _step(num delta) {
     250            2 :     if (!widget.enabled) return;
     251            3 :     final base = _value ?? widget.min ?? 0;
     252            3 :     _emit(_clamp(_addStep(base, delta)), syncText: true);
     253              :   }
     254              : 
     255            3 :   void _onTextChanged(String text) => _emit(_parse(text), syncText: false);
     256              : 
     257            1 :   void _onFocusChanged() {
     258            2 :     setState(() {});
     259              :     // Committing on blur snaps a typed out-of-range value into the bounds and
     260              :     // normalizes the text to the formatted value.
     261            5 :     if (!_focusNode.hasFocus) _emit(_clamp(_value), syncText: true);
     262              :   }
     263              : 
     264            1 :   KeyEventResult _handleKey(FocusNode node, KeyEvent event) {
     265            3 :     if (!widget.enabled || event is KeyUpEvent) return KeyEventResult.ignored;
     266            1 :     return switch (event.logicalKey) {
     267            4 :       LogicalKeyboardKey.arrowUp => _stepped(widget.step),
     268            5 :       LogicalKeyboardKey.arrowDown => _stepped(-widget.step),
     269            3 :       LogicalKeyboardKey.pageUp => _stepped(_largeStep),
     270            4 :       LogicalKeyboardKey.pageDown => _stepped(-_largeStep),
     271              :       _ => KeyEventResult.ignored,
     272              :     };
     273              :   }
     274              : 
     275            1 :   KeyEventResult _stepped(num delta) {
     276            1 :     _step(delta);
     277              :     return KeyEventResult.handled;
     278              :   }
     279              : 
     280            1 :   @override
     281              :   Widget build(BuildContext context) {
     282            1 :     final theme = context.fossTheme;
     283            6 :     final v = _apply(_resolve(theme, widget.size), widget.style);
     284            1 :     final colors = theme.colors;
     285              : 
     286            1 :     final value = _value;
     287            2 :     final min = widget.min;
     288            2 :     final max = widget.max;
     289              :     final canDecrement =
     290            3 :         widget.enabled && !(min != null && value != null && value <= min);
     291              :     final canIncrement =
     292            3 :         widget.enabled && !(max != null && value != null && value >= max);
     293              : 
     294            1 :     final box = FossFieldBox(
     295            2 :       enabled: widget.enabled,
     296            2 :       hasError: widget.error,
     297            4 :       focused: _focusNode.hasFocus && widget.enabled,
     298            1 :       background: v.background,
     299            1 :       borderColor: v.borderColor,
     300            1 :       ringColor: colors.ring,
     301            1 :       destructiveColor: colors.destructive,
     302            1 :       borderRadius: v.borderRadius,
     303            1 :       minHeight: v.minHeight,
     304            1 :       shadow: v.shadow,
     305            1 :       isDark: colors.isDark,
     306              :       // Clip the content to the box's inner superellipse (inset past the 1px
     307              :       // border) so a stepper's hover fill nests inside the corner instead of
     308              :       // squaring off over the border.
     309            1 :       child: ClipPath(
     310            2 :         clipper: _FieldClip(v.borderRadius),
     311              :         // Resolve the row's height (the box min height) before stretching, so
     312              :         // the stretch has a bound even when the field sits in an unbounded box.
     313            1 :         child: IntrinsicHeight(
     314            1 :           child: Row(
     315              :             // Stretch the steppers to the full field height so each button, its
     316              :             // hover fill, and its tap target fill the box rather than a short
     317              :             // glyph-height band centered in it.
     318              :             crossAxisAlignment: CrossAxisAlignment.stretch,
     319            1 :             children: [
     320            1 :               _Stepper(
     321              :                 plus: false,
     322              :                 interactive: canDecrement,
     323            2 :                 dim: widget.enabled && !canDecrement,
     324              :                 visuals: v,
     325              :                 semanticsLabel: 'Decrement',
     326            5 :                 onStep: () => _step(-widget.step),
     327              :               ),
     328            1 :               Expanded(
     329            1 :                 child: _buildEditable(colors, v, canDecrement, canIncrement),
     330              :               ),
     331            1 :               _Stepper(
     332              :                 plus: true,
     333              :                 interactive: canIncrement,
     334            2 :                 dim: widget.enabled && !canIncrement,
     335              :                 visuals: v,
     336              :                 semanticsLabel: 'Increment',
     337            4 :                 onStep: () => _step(widget.step),
     338              :               ),
     339              :             ],
     340              :           ),
     341              :         ),
     342              :       ),
     343              :     );
     344              : 
     345            2 :     if (!widget.enabled) return box;
     346              : 
     347            1 :     return TapRegion(
     348            1 :       onTapOutside: (_) {
     349            4 :         if (_focusNode.hasFocus) _focusNode.unfocus();
     350              :       },
     351            2 :       child: _gestureBuilder.buildGestureDetector(
     352              :         behavior: HitTestBehavior.translucent,
     353              :         child: box,
     354              :       ),
     355              :     );
     356              :   }
     357              : 
     358            1 :   Widget _buildEditable(
     359              :     FossColors colors,
     360              :     _NumberFieldVisuals v,
     361              :     bool canDecrement,
     362              :     bool canIncrement,
     363              :   ) {
     364            2 :     final textStyle = v.textStyle.copyWith(
     365            1 :       color: v.textColor,
     366              :       fontFeatures: const [FontFeature.tabularFigures()],
     367              :     );
     368              : 
     369            1 :     final editable = EditableText(
     370            1 :       key: _editableKey,
     371            1 :       controller: _controller,
     372            1 :       focusNode: _focusNode,
     373            2 :       readOnly: !widget.enabled,
     374              :       rendererIgnoresPointer: true,
     375              :       textAlign: TextAlign.center,
     376              :       style: textStyle,
     377              :       // Even leading centers the value vertically against the base type's line
     378              :       // height, matching the placeholder so the first keystroke does not jump.
     379              :       textHeightBehavior: const TextHeightBehavior(
     380              :         leadingDistribution: TextLeadingDistribution.even,
     381              :       ),
     382            1 :       cursorColor: colors.foreground,
     383            1 :       backgroundCursorColor: colors.mutedForeground,
     384            2 :       selectionColor: colors.ring.withValues(alpha: _selectionOpacity),
     385              :       cursorOpacityAnimates: true,
     386              :       keyboardType: const TextInputType.numberWithOptions(
     387              :         signed: true,
     388              :         decimal: true,
     389              :       ),
     390            1 :       keyboardAppearance: colors.isDark ? Brightness.dark : Brightness.light,
     391              :       inputFormatters: const [_NumericFormatter()],
     392            1 :       onChanged: _onTextChanged,
     393            2 :       enableInteractiveSelection: widget.enabled,
     394              :     );
     395              : 
     396            2 :     final placeholder = widget.placeholder;
     397              :     // The adjustable value and its stepped previews must agree on emptiness:
     398              :     // when the field is empty the previews stay empty too.
     399            2 :     final valueText = _displayText(_value);
     400            3 :     final base = _value ?? widget.min ?? 0;
     401            1 :     final increased = valueText.isEmpty
     402              :         ? ''
     403            5 :         : _displayText(_clamp(_addStep(base, widget.step)));
     404            1 :     final decreased = valueText.isEmpty
     405              :         ? ''
     406            6 :         : _displayText(_clamp(_addStep(base, -widget.step)));
     407              : 
     408            1 :     return Semantics(
     409            2 :       label: widget.semanticsLabel,
     410              :       value: valueText,
     411              :       increasedValue: increased,
     412              :       decreasedValue: decreased,
     413              :       textField: true,
     414            2 :       enabled: widget.enabled,
     415            4 :       onIncrease: canIncrement ? () => _step(widget.step) : null,
     416            5 :       onDecrease: canDecrement ? () => _step(-widget.step) : null,
     417            1 :       child: Stack(
     418              :         alignment: Alignment.center,
     419            1 :         children: [
     420              :           if (placeholder != null)
     421            1 :             Positioned.fill(
     422            1 :               child: ValueListenableBuilder<TextEditingValue>(
     423            1 :                 valueListenable: _controller,
     424            3 :                 builder: (context, value, _) => value.text.isEmpty
     425            1 :                     ? IgnorePointer(
     426            1 :                         child: ExcludeSemantics(
     427            1 :                           child: Text(
     428              :                             placeholder,
     429              :                             textAlign: TextAlign.center,
     430              :                             maxLines: 1,
     431              :                             overflow: TextOverflow.ellipsis,
     432              :                             textHeightBehavior: const TextHeightBehavior(
     433              :                               leadingDistribution: TextLeadingDistribution.even,
     434              :                             ),
     435            3 :                             style: v.textStyle.copyWith(color: v.hintColor),
     436              :                           ),
     437              :                         ),
     438              :                       )
     439              :                     : const SizedBox.shrink(),
     440              :               ),
     441              :             ),
     442            1 :           editable,
     443              :         ],
     444              :       ),
     445              :     );
     446              :   }
     447              : }
     448              : 
     449              : /// The default display: a plain decimal string with no trailing zeros.
     450            1 : String _defaultFormat(num value) {
     451            2 :   if (value is int) return value.toString();
     452            1 :   final d = value.toDouble();
     453            4 :   return d == d.truncateToDouble() ? d.toStringAsFixed(0) : d.toString();
     454              : }
     455              : 
     456              : // Adds a step without accumulating IEEE-754 drift: quantizes the sum to the
     457              : // decimal precision of its operands, so 0.1 + 0.1 + 0.1 lands on 0.3, not
     458              : // 0.30000000000000004. Integer arithmetic passes through exactly.
     459            1 : num _addStep(num base, num delta) {
     460            3 :   if (base is int && delta is int) return base + delta;
     461            3 :   final places = math.max(_decimals(base), _decimals(delta));
     462            2 :   final factor = math.pow(10, places).toDouble();
     463            4 :   return ((base + delta) * factor).roundToDouble() / factor;
     464              : }
     465              : 
     466            1 : int _decimals(num value) {
     467            1 :   if (value is int) return 0;
     468            1 :   final text = value.toString();
     469            1 :   final dot = text.indexOf('.');
     470            4 :   return dot < 0 ? 0 : text.length - dot - 1;
     471              : }
     472              : 
     473              : /// The default parse: a permissive number read, null when the text is not a
     474              : /// number.
     475            3 : num? _defaultParse(String text) => num.tryParse(text.trim());
     476              : 
     477              : /// Rejects any edit that would leave the text a non-numeric shape, allowing a
     478              : /// partial entry (empty, a lone sign, a trailing separator) while typing.
     479              : class _NumericFormatter extends TextInputFormatter {
     480            2 :   const _NumericFormatter();
     481              : 
     482            3 :   static final _pattern = RegExp(r'^[+-]?\d*\.?\d*$');
     483              : 
     484            1 :   @override
     485              :   TextEditingValue formatEditUpdate(
     486              :     TextEditingValue oldValue,
     487              :     TextEditingValue newValue,
     488            3 :   ) => _pattern.hasMatch(newValue.text) ? newValue : oldValue;
     489              : }
     490              : 
     491              : /// One end of the control: a shrink-0 button with a painted plus or minus
     492              : /// glyph. Fills with the hover color on pointer hover; dims its glyph when it
     493              : /// is at a bound. Shares the input's focus stop, so it carries no focus ring.
     494              : class _Stepper extends StatefulWidget {
     495            1 :   const _Stepper({
     496              :     required this.plus,
     497              :     required this.interactive,
     498              :     required this.dim,
     499              :     required this.visuals,
     500              :     required this.semanticsLabel,
     501              :     required this.onStep,
     502              :   });
     503              : 
     504              :   final bool plus;
     505              :   final bool interactive;
     506              :   final bool dim;
     507              :   final _NumberFieldVisuals visuals;
     508              :   final String semanticsLabel;
     509              :   final VoidCallback onStep;
     510              : 
     511            1 :   @override
     512            1 :   State<_Stepper> createState() => _StepperState();
     513              : }
     514              : 
     515              : class _StepperState extends State<_Stepper> {
     516              :   bool _hovered = false;
     517              : 
     518            1 :   @override
     519              :   Widget build(BuildContext context) {
     520            2 :     final v = widget.visuals;
     521            2 :     final glyphColor = widget.dim
     522            5 :         ? v.glyphColor.withValues(alpha: v.glyphColor.a * _disabledOpacity)
     523            1 :         : v.glyphColor;
     524              : 
     525              :     // The full-height fill; the field clips its outer corner to the box radius,
     526              :     // and its inner edge stays square against the value.
     527            3 :     final fill = _hovered && widget.interactive
     528            2 :         ? ColoredBox(color: v.stepperHoverColor)
     529              :         : const SizedBox.shrink();
     530              : 
     531            1 :     final glyph = Padding(
     532            2 :       padding: EdgeInsets.symmetric(horizontal: v.stepperPadX),
     533            1 :       child: SizedBox.square(
     534            1 :         dimension: v.iconSize,
     535            1 :         child: CustomPaint(
     536            3 :           painter: _GlyphPainter(color: glyphColor, plus: widget.plus),
     537              :         ),
     538              :       ),
     539              :     );
     540              : 
     541            1 :     return Semantics(
     542              :       button: true,
     543            2 :       enabled: widget.interactive,
     544            2 :       label: widget.semanticsLabel,
     545            1 :       child: MouseRegion(
     546            2 :         cursor: widget.interactive
     547              :             ? SystemMouseCursors.click
     548              :             : SystemMouseCursors.basic,
     549            4 :         onEnter: (_) => setState(() => _hovered = true),
     550            4 :         onExit: (_) => setState(() => _hovered = false),
     551            1 :         child: GestureDetector(
     552              :           behavior: HitTestBehavior.opaque,
     553            4 :           onTap: widget.interactive ? widget.onStep : null,
     554            1 :           child: Stack(
     555              :             alignment: Alignment.center,
     556            1 :             children: [
     557            1 :               Positioned.fill(child: fill),
     558              :               glyph,
     559              :             ],
     560              :           ),
     561              :         ),
     562              :       ),
     563              :     );
     564              :   }
     565              : }
     566              : 
     567              : /// Paints a centered minus, or a plus when [plus], as 1.5px rounded strokes.
     568              : class _GlyphPainter extends CustomPainter {
     569            1 :   const _GlyphPainter({required this.color, required this.plus});
     570              : 
     571              :   final Color color;
     572              :   final bool plus;
     573              : 
     574            1 :   @override
     575              :   void paint(Canvas canvas, Size size) {
     576            1 :     final center = size.center(Offset.zero);
     577            3 :     final arm = size.width / 2 * 0.55;
     578            1 :     final paint = Paint()
     579            2 :       ..color = color
     580            1 :       ..strokeWidth = 1.5
     581            1 :       ..strokeCap = StrokeCap.round;
     582            1 :     canvas.drawLine(
     583            2 :       center - Offset(arm, 0),
     584            2 :       center + Offset(arm, 0),
     585              :       paint,
     586              :     );
     587            1 :     if (plus) {
     588            1 :       canvas.drawLine(
     589            2 :         center - Offset(0, arm),
     590            2 :         center + Offset(0, arm),
     591              :         paint,
     592              :       );
     593              :     }
     594              :   }
     595              : 
     596            1 :   @override
     597              :   bool shouldRepaint(_GlyphPainter oldDelegate) =>
     598            6 :       oldDelegate.color != color || oldDelegate.plus != plus;
     599              : }
     600              : 
     601              : /// Clips the field content to the superellipse just inside the 1px border, so
     602              : /// a stepper's full-height fill nests within the corner instead of overhanging.
     603              : class _FieldClip extends CustomClipper<Path> {
     604            1 :   const _FieldClip(this.radius);
     605              : 
     606              :   final double radius;
     607              : 
     608            1 :   @override
     609            1 :   Path getClip(Size size) => RoundedSuperellipseBorder(
     610            4 :     borderRadius: BorderRadius.circular(math.max(0, radius - 1)),
     611            3 :   ).getOuterPath((Offset.zero & size).deflate(1));
     612              : 
     613            1 :   @override
     614            3 :   bool shouldReclip(_FieldClip oldClipper) => oldClipper.radius != radius;
     615              : }
     616              : 
     617              : /// Builds the default appearance for a [size] from the theme tokens, reusing
     618              : /// the text field's shared field metrics so the two controls resolve one box.
     619            1 : _NumberFieldVisuals _resolve(FossThemeData theme, FossTextFieldSize size) {
     620            1 :   final c = theme.colors;
     621            1 :   final m = fieldMetrics(theme, size);
     622            1 :   return _NumberFieldVisuals(
     623              :     background: m.fill,
     624            1 :     borderColor: c.input,
     625            1 :     textColor: c.foreground,
     626            2 :     hintColor: c.mutedForeground.withValues(alpha: _placeholderOpacity),
     627            5 :     glyphColor: c.foreground.withValues(alpha: c.foreground.a * _glyphOpacity),
     628            1 :     stepperHoverColor: c.accent,
     629              :     borderRadius: m.radius,
     630            1 :     stepperPadX: m.padX - 1,
     631              :     minHeight: m.minHeight,
     632            2 :     textStyle: theme.typography.base,
     633              :     iconSize: _iconSize,
     634            2 :     shadow: theme.shadows.xs,
     635              :   );
     636              : }
     637              : 
     638              : /// Lays a per-instance [override] over the resolved [base], field by field.
     639            1 : _NumberFieldVisuals _apply(
     640              :   _NumberFieldVisuals base,
     641              :   FossNumberFieldStyle? override,
     642              : ) {
     643              :   if (override == null) return base;
     644            1 :   return _NumberFieldVisuals(
     645            2 :     background: override.backgroundColor ?? base.background,
     646            2 :     borderColor: override.borderColor ?? base.borderColor,
     647            1 :     textColor: base.textColor,
     648            1 :     hintColor: base.hintColor,
     649            1 :     glyphColor: base.glyphColor,
     650            2 :     stepperHoverColor: override.stepperHoverColor ?? base.stepperHoverColor,
     651            1 :     borderRadius: override.borderRadius ?? base.borderRadius,
     652            1 :     stepperPadX: base.stepperPadX,
     653            2 :     minHeight: override.minHeight ?? base.minHeight,
     654            2 :     textStyle: override.textStyle ?? base.textStyle,
     655            2 :     iconSize: override.iconSize ?? base.iconSize,
     656            2 :     shadow: override.shadow ?? base.shadow,
     657              :   );
     658              : }
     659              : 
     660              : /// The fully resolved, non-null appearance for one size. A
     661              : /// [FossNumberFieldStyle] override is laid over it by [_apply], so the widget
     662              : /// reads only non-null fields and never needs the null-assertion operator.
     663              : @immutable
     664              : class _NumberFieldVisuals {
     665            1 :   const _NumberFieldVisuals({
     666              :     required this.background,
     667              :     required this.borderColor,
     668              :     required this.textColor,
     669              :     required this.hintColor,
     670              :     required this.glyphColor,
     671              :     required this.stepperHoverColor,
     672              :     required this.borderRadius,
     673              :     required this.stepperPadX,
     674              :     required this.minHeight,
     675              :     required this.textStyle,
     676              :     required this.iconSize,
     677              :     required this.shadow,
     678              :   });
     679              : 
     680              :   final Color background;
     681              :   final Color borderColor;
     682              :   final Color textColor;
     683              :   final Color hintColor;
     684              :   final Color glyphColor;
     685              :   final Color stepperHoverColor;
     686              :   final double borderRadius;
     687              :   final double stepperPadX;
     688              :   final double minHeight;
     689              :   final TextStyle textStyle;
     690              :   final double iconSize;
     691              :   final List<BoxShadow> shadow;
     692              : }
        

Generated by: LCOV version 2.0-1