Line data Source code
1 : import 'package:flutter/widgets.dart';
2 : import 'package:fossui/src/components/spinner/foss_spinner.dart';
3 : import 'package:fossui/src/theme/theme.dart';
4 :
5 : part 'foss_button_controller.dart';
6 : part 'foss_button_painters.dart';
7 : part 'foss_button_style.dart';
8 :
9 : const double _iconSize = 18;
10 : const double _iconOpacity = 0.8;
11 : const double _disabledOpacity = 0.64;
12 : const double _minTapTarget = 48;
13 :
14 : /// Inner top-rim highlight on filled variants: 16% white at rest, 8% black when
15 : /// pressed.
16 : const Color _rimLight = Color(0x29FFFFFF);
17 : const Color _rimPressed = Color(0x14000000);
18 :
19 : /// The visual treatment of a [FossButton].
20 : enum FossButtonVariant {
21 : /// Solid, high-emphasis primary action.
22 : primary,
23 :
24 : /// Subtle filled secondary action.
25 : secondary,
26 :
27 : /// Bordered, low-emphasis action on the surface.
28 : outline,
29 :
30 : /// Borderless, minimal action.
31 : ghost,
32 :
33 : /// Solid action for destructive operations.
34 : destructive,
35 :
36 : /// Borderless text action that underlines on interaction.
37 : link,
38 : }
39 :
40 : /// The size of a [FossButton].
41 : enum FossButtonSize {
42 : /// Compact: 32 logical pixels tall.
43 : sm,
44 :
45 : /// Default: 36 logical pixels tall.
46 : md,
47 :
48 : /// Prominent: 40 logical pixels tall.
49 : lg,
50 : }
51 :
52 : /// {@category Inputs}
53 : /// {@template foss.button.preview}
54 : /// <img src="https://fossui.org/components/button/variants/light.png"
55 : /// alt="FossButton variants, light theme" width="480"
56 : /// style="max-width:100%;height:auto" />
57 : /// <img src="https://fossui.org/components/button/variants/dark.png"
58 : /// alt="FossButton variants, dark theme" width="480"
59 : /// style="max-width:100%;height:auto" />
60 : ///
61 : /// See the [button documentation ↗](https://fossui.org/docs/components/button) or
62 : /// try it live in the
63 : /// [playground ↗](https://play.fossui.org/components/#/?path=components/button/fossbutton/playground).
64 : /// {@endtemplate}
65 : ///
66 : /// A pressable button in the fossui style.
67 : ///
68 : /// Pick a look with [variant] and a size with [size]; both read their colors,
69 : /// radius, type, and spacing from `context.fossTheme`, so a global retheme
70 : /// restyles every button. For a one-off, pass a [FossButtonStyle] to [style].
71 : /// Passing a null [onPressed] disables the button.
72 : ///
73 : /// [leading] and [trailing] take any widget (icon-agnostic); their color and
74 : /// size are themed to match the label.
75 : ///
76 : /// Loading and disabled can be set two ways. Declaratively: pass [loading] or a
77 : /// null [onPressed]. Imperatively: pass a [FossButtonController] and drive it,
78 : /// which toggles either state without rebuilding the button.
79 : ///
80 : /// It does not guard against repeated taps: if [onPressed] runs an async
81 : /// action, gate re-entrancy yourself or drive a [FossButtonController].
82 : ///
83 : /// {@macro foss.customize}
84 : ///
85 : /// Every size keeps a 48 logical-pixel minimum tap target, larger than its
86 : /// visual height. [FossButton.icon] has no visible label, so it requires a
87 : /// [semanticLabel].
88 : ///
89 : /// See also [FossButtonStyle] for one-off overrides and [FossButtonController]
90 : /// to drive loading and disabled imperatively.
91 : ///
92 : /// ```dart
93 : /// FossButton(
94 : /// onPressed: () => save(),
95 : /// loading: isSaving,
96 : /// leading: const Icon(checkIcon),
97 : /// child: const Text('Save'),
98 : /// );
99 : /// ```
100 : ///
101 : /// The [loading] flag swaps the label for a spinner. To keep a message beside
102 : /// the spinner, compose it instead: put a [FossSpinner] in [leading] and pass a
103 : /// null [onPressed] to disable.
104 : ///
105 : /// ```dart
106 : /// FossButton(
107 : /// onPressed: null,
108 : /// leading: const FossSpinner(size: 18),
109 : /// child: const Text('Loading...'),
110 : /// );
111 : /// ```
112 : class FossButton extends StatefulWidget {
113 : /// {@macro foss.button.preview}
114 : ///
115 : /// Creates a button. [child] is the label; a null [onPressed] disables it,
116 : /// and [loading] shows a spinner in place of the content.
117 6 : const FossButton({
118 : required this.child,
119 : this.onPressed,
120 : this.controller,
121 : this.variant = FossButtonVariant.primary,
122 : this.size = FossButtonSize.md,
123 : this.leading,
124 : this.trailing,
125 : this.style,
126 : this.semanticLabel,
127 : this.loading = false,
128 : this.loadingIndicator,
129 : super.key,
130 : }) : _iconOnly = false;
131 :
132 : /// {@macro foss.button.preview}
133 : ///
134 : /// Creates a square, icon-only button sized to its [size]. [icon] is the sole
135 : /// content and [semanticLabel] names the action for assistive tech, since
136 : /// there is no visible label.
137 : ///
138 : /// ```dart
139 : /// FossButton.icon(
140 : /// onPressed: share,
141 : /// semanticLabel: 'Share',
142 : /// icon: const Icon(shareIcon),
143 : /// );
144 : /// ```
145 3 : const FossButton.icon({
146 : required Widget icon,
147 : required this.semanticLabel,
148 : this.onPressed,
149 : this.controller,
150 : this.variant = FossButtonVariant.primary,
151 : this.size = FossButtonSize.md,
152 : this.style,
153 : this.loading = false,
154 : this.loadingIndicator,
155 : super.key,
156 : }) : child = icon,
157 : leading = null,
158 : trailing = null,
159 : _iconOnly = true;
160 :
161 : /// The label, typically a [Text].
162 : final Widget child;
163 :
164 : /// Called when the button is tapped or activated. Null disables the button.
165 : final VoidCallback? onPressed;
166 :
167 : /// Optional controller to drive loading and disabled imperatively, without
168 : /// rebuilding the button. You own it and must dispose it.
169 : final FossButtonController? controller;
170 :
171 : /// The visual treatment. Defaults to [FossButtonVariant.primary].
172 : final FossButtonVariant variant;
173 :
174 : /// The size. Defaults to [FossButtonSize.md].
175 : final FossButtonSize size;
176 :
177 : /// Optional widget before the label, themed as an icon.
178 : final Widget? leading;
179 :
180 : /// Optional widget after the label, themed as an icon.
181 : final Widget? trailing;
182 :
183 : /// Per-instance overrides layered on the theme-resolved style.
184 : final FossButtonStyle? style;
185 :
186 : /// Accessibility label, for when [child] is not descriptive on its own.
187 : final String? semanticLabel;
188 :
189 : /// Whether the button shows a spinner and is non-interactive.
190 : final bool loading;
191 :
192 : /// Replaces the built-in spinner shown while [loading].
193 : final Widget? loadingIndicator;
194 :
195 : final bool _iconOnly;
196 :
197 : /// Whether the button shows its loading spinner: the [loading] flag is set,
198 : /// or the [controller] is in [FossButtonStatus.loading].
199 26 : bool get isLoading => loading || (controller?.isLoading ?? false);
200 :
201 : /// Whether the button is interactive. It must have an [onPressed], not be
202 : /// loading, and, if a [controller] is set, be in [FossButtonStatus.idle].
203 8 : bool get enabled {
204 16 : if (onPressed == null || isLoading) return false;
205 18 : return controller?.status != FossButtonStatus.disabled;
206 : }
207 :
208 8 : @override
209 8 : State<FossButton> createState() => _FossButtonState();
210 : }
211 :
212 : class _FossButtonState extends State<FossButton> {
213 : final WidgetStatesController _states = WidgetStatesController();
214 :
215 8 : @override
216 : void initState() {
217 8 : super.initState();
218 20 : widget.controller?.addListener(_onControllerChanged);
219 8 : _syncDisabled();
220 : }
221 :
222 2 : @override
223 : void didUpdateWidget(FossButton oldWidget) {
224 2 : super.didUpdateWidget(oldWidget);
225 8 : if (oldWidget.controller != widget.controller) {
226 3 : oldWidget.controller?.removeListener(_onControllerChanged);
227 4 : widget.controller?.addListener(_onControllerChanged);
228 : }
229 2 : _syncDisabled();
230 : }
231 :
232 6 : void _onControllerChanged() => setState(_syncDisabled);
233 :
234 8 : void _syncDisabled() {
235 16 : final disabled = !widget.enabled;
236 16 : _states.update(WidgetState.disabled, disabled);
237 : // Disabling mid-press leaves the gesture without an up event; clear the
238 : // pressed bit so the button does not stay stuck in its pressed look.
239 8 : if (disabled) _states.update(WidgetState.pressed, false);
240 : }
241 :
242 8 : @override
243 : void dispose() {
244 20 : widget.controller?.removeListener(_onControllerChanged);
245 16 : _states.dispose();
246 8 : super.dispose();
247 : }
248 :
249 8 : @override
250 : Widget build(BuildContext context) {
251 8 : final theme = context.fossTheme;
252 8 : final visuals = _apply(
253 56 : _resolve(theme, widget.variant, widget.size, iconOnly: widget._iconOnly),
254 16 : widget.style,
255 : );
256 16 : final ring = theme.colors.ring;
257 :
258 8 : return Semantics(
259 : button: true,
260 16 : enabled: widget.enabled,
261 16 : label: widget.semanticLabel,
262 8 : child: FocusableActionDetector(
263 16 : enabled: widget.enabled,
264 16 : mouseCursor: widget.enabled
265 : ? SystemMouseCursors.click
266 : : SystemMouseCursors.basic,
267 3 : onShowHoverHighlight: (v) => _states.update(WidgetState.hovered, v),
268 9 : onShowFocusHighlight: (v) => _states.update(WidgetState.focused, v),
269 8 : actions: <Type, Action<Intent>>{
270 8 : ActivateIntent: CallbackAction<ActivateIntent>(
271 3 : onInvoke: (_) {
272 9 : widget.onPressed?.call();
273 : return null;
274 : },
275 : ),
276 : },
277 8 : child: GestureDetector(
278 16 : onTapDown: widget.enabled
279 15 : ? (_) => _states.update(WidgetState.pressed, true)
280 : : null,
281 16 : onTapUp: widget.enabled
282 15 : ? (_) => _states.update(WidgetState.pressed, false)
283 : : null,
284 16 : onTapCancel: widget.enabled
285 3 : ? () => _states.update(WidgetState.pressed, false)
286 : : null,
287 32 : onTap: widget.enabled ? widget.onPressed : null,
288 8 : child: ConstrainedBox(
289 : constraints: const BoxConstraints(
290 : minWidth: _minTapTarget,
291 : minHeight: _minTapTarget,
292 : ),
293 8 : child: Center(
294 : widthFactor: 1,
295 8 : child: ListenableBuilder(
296 8 : listenable: _states,
297 16 : builder: (context, _) => _paint(visuals, ring),
298 : ),
299 : ),
300 : ),
301 : ),
302 : ),
303 : );
304 : }
305 :
306 8 : Widget _paint(_ButtonVisuals visuals, Color ring) {
307 16 : final states = _states.value;
308 16 : final fg = visuals.foreground.resolve(states);
309 8 : final pressed = states.contains(WidgetState.pressed);
310 :
311 8 : var child = _content(visuals, states, fg);
312 16 : if (widget.isLoading) {
313 : // Overlay a spinner; keep the content at zero opacity so width holds.
314 2 : child = Stack(
315 : alignment: Alignment.center,
316 2 : children: [
317 2 : Opacity(opacity: 0, child: child),
318 4 : widget.loadingIndicator ??
319 4 : FossSpinner(size: visuals.iconSize, color: fg),
320 : ],
321 : );
322 : }
323 :
324 : // Icon-only buttons are square: floor the width to the height.
325 19 : final minWidth = widget._iconOnly ? visuals.minHeight : 0.0;
326 8 : Widget surface = DecoratedBox(
327 8 : decoration: ShapeDecoration(
328 16 : color: visuals.background.resolve(states),
329 8 : shape: RoundedSuperellipseBorder(
330 8 : side: visuals.side,
331 16 : borderRadius: BorderRadius.circular(visuals.borderRadius),
332 : ),
333 24 : shadows: pressed || !widget.enabled ? const [] : visuals.shadow,
334 : ),
335 8 : child: Padding(
336 8 : padding: visuals.padding,
337 8 : child: ConstrainedBox(
338 8 : constraints: BoxConstraints(
339 : minWidth: minWidth,
340 8 : minHeight: visuals.minHeight,
341 : ),
342 : child: child,
343 : ),
344 : ),
345 : );
346 :
347 : // Filled variants carry a 1px top-lit inner rim; pressed swaps it to a
348 : // faint dark line. Skipped when disabled, matching the resting elevation.
349 40 : if (widget.variant.isFilled && widget.enabled) {
350 8 : surface = CustomPaint(
351 8 : foregroundPainter: _TopHighlightPainter(
352 : color: pressed ? _rimPressed : _rimLight,
353 8 : radius: visuals.borderRadius,
354 : ),
355 : child: surface,
356 : );
357 : }
358 :
359 16 : if (!widget.enabled) {
360 8 : surface = Opacity(opacity: visuals.disabledOpacity, child: surface);
361 : }
362 :
363 8 : return CustomPaint(
364 8 : foregroundPainter: states.contains(WidgetState.focused)
365 6 : ? _FocusRingPainter(color: ring, radius: visuals.borderRadius)
366 : : null,
367 : child: surface,
368 : );
369 : }
370 :
371 : /// Builds the inner content: a single themed icon when icon-only, otherwise
372 : /// the leading / label / trailing row.
373 8 : Widget _content(_ButtonVisuals visuals, Set<WidgetState> states, Color fg) {
374 24 : final iconColor = fg.withValues(alpha: fg.a * _iconOpacity);
375 16 : final icon = IconThemeData(size: visuals.iconSize, color: iconColor);
376 :
377 16 : if (widget._iconOnly) {
378 9 : return IconTheme.merge(data: icon, child: widget.child);
379 : }
380 :
381 : final interacting =
382 6 : states.contains(WidgetState.pressed) ||
383 6 : states.contains(WidgetState.hovered);
384 18 : final underline = widget.variant == FossButtonVariant.link && interacting;
385 12 : final leading = widget.leading;
386 12 : final trailing = widget.trailing;
387 :
388 6 : return Row(
389 : mainAxisSize: MainAxisSize.min,
390 6 : spacing: visuals.gap,
391 6 : children: [
392 1 : if (leading != null) IconTheme.merge(data: icon, child: leading),
393 6 : Flexible(
394 6 : child: DefaultTextStyle.merge(
395 : // Set the style outright (decoration too) so it renders the same
396 : // under any app, not only where an ancestor clears it.
397 12 : style: visuals.textStyle.copyWith(
398 : color: fg,
399 : decoration: underline
400 : ? TextDecoration.underline
401 : : TextDecoration.none,
402 : ),
403 : maxLines: 1,
404 : softWrap: false,
405 : overflow: TextOverflow.ellipsis,
406 12 : child: widget.child,
407 : ),
408 : ),
409 1 : if (trailing != null) IconTheme.merge(data: icon, child: trailing),
410 : ],
411 : );
412 : }
413 : }
414 :
415 : /// Solid-fill variants: they tint the drop shadow with their own color and
416 : /// carry the top-lit inner rim. The single source for "is this filled".
417 : extension on FossButtonVariant {
418 8 : bool get isFilled =>
419 8 : this == FossButtonVariant.primary ||
420 4 : this == FossButtonVariant.destructive;
421 : }
422 :
423 : /// Scales [color] to [opacity] of its own alpha, keeping it translucent so it
424 : /// composites over whatever surface the button sits on at paint time. A fill
425 : /// that stays translucent blends on the popover of a dialog or the fill of a
426 : /// card, not just the app background.
427 8 : Color _alpha(Color color, double opacity) =>
428 24 : color.withValues(alpha: color.a * opacity);
429 :
430 : /// Composites [base] at [opacity] of its own alpha over a fixed [surface],
431 : /// baking an opaque color at resolve time. Used only where the fill is already
432 : /// opaque against a known surface.
433 3 : Color _overlay(Color base, double opacity, Color surface) =>
434 12 : Color.alphaBlend(base.withValues(alpha: base.a * opacity), surface);
435 :
436 : /// Recolors the [base] shadow layers to [color] at [alpha], keeping geometry.
437 : /// Filled variants tint their drop shadow with their own fill, not flat black.
438 16 : List<BoxShadow> _tint(List<BoxShadow> base, Color color, double alpha) => [
439 8 : for (final s in base)
440 8 : BoxShadow(
441 8 : color: color.withValues(alpha: alpha),
442 8 : offset: s.offset,
443 8 : blurRadius: s.blurRadius,
444 8 : spreadRadius: s.spreadRadius,
445 8 : blurStyle: s.blurStyle,
446 : ),
447 : ];
448 :
449 : /// Builds the default appearance for a (variant, size) from the theme tokens.
450 8 : _ButtonVisuals _resolve(
451 : FossThemeData theme,
452 : FossButtonVariant variant,
453 : FossButtonSize size, {
454 : required bool iconOnly,
455 : }) {
456 8 : final c = theme.colors;
457 :
458 : final Color base;
459 : final Color hover;
460 : final Color pressed;
461 : final Color fg;
462 : final BorderSide side;
463 : switch (variant) {
464 8 : case FossButtonVariant.primary:
465 8 : base = c.primary;
466 16 : hover = _alpha(c.primary, 0.9);
467 : pressed = hover;
468 8 : fg = c.primaryForeground;
469 16 : side = BorderSide(color: c.primary);
470 4 : case FossButtonVariant.secondary:
471 2 : base = c.secondary;
472 4 : hover = _alpha(c.secondary, 0.9);
473 4 : pressed = _alpha(c.secondary, 0.8);
474 2 : fg = c.secondaryForeground;
475 : side = BorderSide.none;
476 4 : case FossButtonVariant.outline:
477 : // Dark mode fills with the input color (32% at rest, 64% interacting)
478 : // rather than the flat popover, so the surface reads lifted like a field.
479 3 : if (c.isDark) {
480 6 : base = _overlay(c.input, 0.32, c.background);
481 6 : hover = _overlay(c.input, 0.64, c.background);
482 : } else {
483 3 : base = c.popover;
484 9 : hover = _overlay(c.accent, 0.5, c.popover);
485 : }
486 : pressed = hover;
487 3 : fg = c.foreground;
488 6 : side = BorderSide(color: c.input);
489 4 : case FossButtonVariant.ghost:
490 : base = const Color(0x00000000);
491 4 : hover = c.accent;
492 : pressed = hover;
493 4 : fg = c.foreground;
494 : side = BorderSide.none;
495 1 : case FossButtonVariant.destructive:
496 1 : base = c.destructive;
497 2 : hover = _alpha(c.destructive, 0.9);
498 : pressed = hover;
499 1 : fg = c.destructiveForegroundOn;
500 2 : side = BorderSide(color: c.destructive);
501 1 : case FossButtonVariant.link:
502 : base = const Color(0x00000000);
503 : hover = base;
504 : pressed = base;
505 1 : fg = c.foreground;
506 : side = BorderSide.none;
507 : }
508 :
509 : // Filled variants tint the lift with their own fill; outline keeps the
510 : // neutral lift; the rest cast none.
511 : final shadow = switch (variant) {
512 32 : _ when variant.isFilled => _tint(theme.shadows.xs, base, 0.24),
513 10 : FossButtonVariant.outline => theme.shadows.xs,
514 : _ => FossShadows.none,
515 : };
516 :
517 : final (height, gap, horizontalPadding) = switch (size) {
518 20 : FossButtonSize.sm => (32.0, theme.spacing(1.5), theme.spacing(2.5)),
519 35 : FossButtonSize.md => (36.0, theme.spacing(2), theme.spacing(3)),
520 5 : FossButtonSize.lg => (40.0, theme.spacing(2), theme.spacing(3.5)),
521 : };
522 :
523 8 : return _ButtonVisuals(
524 16 : background: WidgetStateProperty.resolveWith((states) {
525 8 : if (states.contains(WidgetState.pressed)) return pressed;
526 8 : if (states.contains(WidgetState.hovered)) return hover;
527 : return base;
528 : }),
529 8 : foreground: WidgetStatePropertyAll(fg),
530 : side: side,
531 16 : borderRadius: theme.radii.lg,
532 : // Icon-only buttons drop side padding; squareness is enforced at paint.
533 : padding: iconOnly
534 : ? EdgeInsets.zero
535 6 : : EdgeInsets.symmetric(horizontal: horizontalPadding),
536 : minHeight: height,
537 24 : textStyle: theme.typography.base.medium,
538 : shadow: shadow,
539 : iconSize: _iconSize,
540 : gap: gap,
541 : disabledOpacity: _disabledOpacity,
542 : );
543 : }
544 :
545 : /// The fully resolved, non-null appearance for one (variant, size). A public
546 : /// [FossButtonStyle] override is laid over it by [_apply], so the widget reads
547 : /// only non-null fields and never needs the null-assertion operator.
548 : @immutable
549 : class _ButtonVisuals {
550 8 : const _ButtonVisuals({
551 : required this.background,
552 : required this.foreground,
553 : required this.side,
554 : required this.borderRadius,
555 : required this.padding,
556 : required this.minHeight,
557 : required this.textStyle,
558 : required this.shadow,
559 : required this.iconSize,
560 : required this.gap,
561 : required this.disabledOpacity,
562 : });
563 :
564 : final WidgetStateProperty<Color> background;
565 : final WidgetStateProperty<Color> foreground;
566 : final BorderSide side;
567 : final double borderRadius;
568 : final EdgeInsetsGeometry padding;
569 : final double minHeight;
570 : final TextStyle textStyle;
571 : final List<BoxShadow> shadow;
572 : final double iconSize;
573 : final double gap;
574 : final double disabledOpacity;
575 : }
576 :
577 : /// Lays a per-instance [override] over the resolved [base], field by field.
578 8 : _ButtonVisuals _apply(_ButtonVisuals base, FossButtonStyle? override) {
579 : if (override == null) return base;
580 1 : return _ButtonVisuals(
581 2 : background: override.backgroundColor ?? base.background,
582 2 : foreground: override.foregroundColor ?? base.foreground,
583 2 : side: override.side ?? base.side,
584 2 : borderRadius: override.borderRadius ?? base.borderRadius,
585 2 : padding: override.padding ?? base.padding,
586 2 : minHeight: override.minHeight ?? base.minHeight,
587 2 : textStyle: override.textStyle ?? base.textStyle,
588 2 : shadow: override.shadow ?? base.shadow,
589 2 : iconSize: override.iconSize ?? base.iconSize,
590 2 : gap: override.gap ?? base.gap,
591 2 : disabledOpacity: override.disabledOpacity ?? base.disabledOpacity,
592 : );
593 : }
|