Line data Source code
1 : import 'package:flutter/widgets.dart';
2 : import 'package:fossui/src/foundation/foss_since.dart';
3 : import 'package:fossui/src/icons/foss_glyph.dart';
4 : import 'package:fossui/src/theme/theme.dart';
5 :
6 : part 'foss_chip_style.dart';
7 :
8 : const double _affixOpacity = 0.8;
9 : const double _disabledOpacity = 0.64;
10 :
11 : /// Fill opacity of the soft hover step: the input color at 64%, composited so
12 : /// it lands darker than the 4% rest fill in both themes.
13 : const double _hoverFillOpacity = 0.64;
14 :
15 : /// Fill opacity of a selected chip under the pointer.
16 : const double _selectedHoverOpacity = 0.9;
17 :
18 : const double _removeGlyphSize = 16;
19 :
20 : const double _ringWidth = 2;
21 : const double _ringOffset = 1;
22 :
23 : /// Minimum tap target, so a compact chip stays comfortably tappable.
24 : const double _minTapTarget = 48;
25 :
26 : /// The visual treatment of a [FossChip].
27 : enum FossChipVariant {
28 : /// Tinted fill, no border. The default.
29 : soft,
30 :
31 : /// Bordered surface that sits flat on the background.
32 : outline,
33 : }
34 :
35 : /// The size of a [FossChip].
36 : enum FossChipSize {
37 : /// Compact: 24 logical pixels tall, sized to sit inside a field.
38 : sm,
39 :
40 : /// Default: 32 logical pixels tall, matching a small button.
41 : md,
42 : }
43 :
44 : /// {@category Inputs}
45 : /// {@template foss.chip.preview}
46 : /// <img src="https://fossui.org/components/chip/overview/light.png"
47 : /// alt="FossChip, light theme" width="480"
48 : /// style="max-width:100%;height:auto" />
49 : /// <img src="https://fossui.org/components/chip/overview/dark.png"
50 : /// alt="FossChip, dark theme" width="480"
51 : /// style="max-width:100%;height:auto" />
52 : ///
53 : /// See the [chip documentation ↗](https://fossui.org/docs/components/chip) or
54 : /// try it live in the
55 : /// [playground ↗](https://play.fossui.org/components/#/?path=components/chip/fosschip/playground).
56 : /// {@endtemplate}
57 : ///
58 : /// A compact pill carrying a value the user can pick or drop: a filter in a
59 : /// bar, a tag on a record, an entry in a multi-select field.
60 : ///
61 : /// The callbacks decide what it is. With neither it is a static tag. With
62 : /// [onRemove] it grows a close affordance at the end. With [onSelected] the
63 : /// body toggles [selected], and the chip fills with the primary color when on.
64 : /// Both together give a filter chip that can also be dropped. Set [enabled] to
65 : /// false to dim it and block both.
66 : ///
67 : /// Selection is controlled: the chip renders [selected] and reports the flipped
68 : /// value through [onSelected] on a tap or Space / Enter. Colors, radius, type,
69 : /// and spacing come from `context.fossTheme`; pass a [FossChipStyle] to [style]
70 : /// for a one-off.
71 : ///
72 : /// {@macro foss.customize}
73 : ///
74 : /// See also FossBadge for a static status pill, and FossToggle for a
75 : /// button-shaped two-state control.
76 : ///
77 : /// ```dart
78 : /// FossChip(
79 : /// label: const Text('Design'),
80 : /// selected: isOn,
81 : /// onSelected: (on) => setState(() => isOn = on),
82 : /// onRemove: () => setState(() => tags.remove('Design')),
83 : /// );
84 : /// ```
85 : @FossSince('0.1.2')
86 : class FossChip extends StatefulWidget {
87 : /// {@macro foss.chip.preview}
88 : ///
89 : /// Creates a chip showing [label]. Passing [onSelected] makes the body
90 : /// selectable; passing [onRemove] adds the close affordance.
91 5 : const FossChip({
92 : required this.label,
93 : this.variant = FossChipVariant.soft,
94 : this.size = FossChipSize.md,
95 : this.leading,
96 : this.selected = false,
97 : this.onSelected,
98 : this.onRemove,
99 : this.removeLabel = 'Remove',
100 : this.enabled = true,
101 : this.semanticLabel,
102 : this.style,
103 : super.key,
104 : });
105 :
106 : /// The pill content, typically a [Text]. Color, weight, and type step are
107 : /// applied through `DefaultTextStyle`.
108 : final Widget label;
109 :
110 : /// The visual treatment. Defaults to [FossChipVariant.soft].
111 : final FossChipVariant variant;
112 :
113 : /// The size. Defaults to [FossChipSize.md].
114 : final FossChipSize size;
115 :
116 : /// Optional widget before the label, themed as an icon.
117 : final Widget? leading;
118 :
119 : /// Whether the chip reads as chosen. Only meaningful with [onSelected].
120 : final bool selected;
121 :
122 : /// Called with the flipped value when the body is tapped or activated. Null
123 : /// leaves the body inert.
124 : final ValueChanged<bool>? onSelected;
125 :
126 : /// Called when the close affordance is activated. Null hides it.
127 : final VoidCallback? onRemove;
128 :
129 : /// Accessibility name for the close affordance.
130 : final String removeLabel;
131 :
132 : /// Whether the chip responds to input. False dims it and blocks the body and
133 : /// the close affordance alike.
134 : final bool enabled;
135 :
136 : /// Accessibility name for the chip, when [label] does not carry the whole
137 : /// meaning. It replaces the label in the semantics tree rather than adding
138 : /// to it, so assistive technology announces one name.
139 : final String? semanticLabel;
140 :
141 : /// Per-instance overrides layered on the theme-resolved style.
142 : final FossChipStyle? style;
143 :
144 : /// Whether the body toggles selection: it is enabled and has an
145 : /// [onSelected].
146 14 : bool get selectable => enabled && onSelected != null;
147 :
148 5 : @override
149 5 : State<FossChip> createState() => _FossChipState();
150 : }
151 :
152 : class _FossChipState extends State<FossChip> {
153 : final WidgetStatesController _states = WidgetStatesController();
154 :
155 5 : @override
156 : void initState() {
157 5 : super.initState();
158 5 : _sync();
159 : }
160 :
161 3 : @override
162 : void didUpdateWidget(FossChip oldWidget) {
163 3 : super.didUpdateWidget(oldWidget);
164 3 : _sync();
165 : }
166 :
167 5 : void _sync() {
168 5 : _states
169 15 : ..update(WidgetState.selected, widget.selected)
170 15 : ..update(WidgetState.disabled, !widget.enabled);
171 : }
172 :
173 5 : @override
174 : void dispose() {
175 10 : _states.dispose();
176 5 : super.dispose();
177 : }
178 :
179 6 : void _toggle() => widget.onSelected?.call(!widget.selected);
180 :
181 5 : @override
182 : Widget build(BuildContext context) {
183 5 : final theme = context.fossTheme;
184 5 : final visuals = _resolve(
185 : theme,
186 10 : widget.variant,
187 10 : widget.size,
188 15 : ).merge(widget.style);
189 :
190 5 : Widget chip = ListenableBuilder(
191 5 : listenable: _states,
192 10 : builder: (context, _) => _paint(visuals),
193 : );
194 :
195 10 : if (widget.selectable) {
196 2 : chip = FocusableActionDetector(
197 : mouseCursor: SystemMouseCursors.click,
198 3 : onShowHoverHighlight: (v) => _states.update(WidgetState.hovered, v),
199 3 : onShowFocusHighlight: (v) => _states.update(WidgetState.focused, v),
200 2 : actions: <Type, Action<Intent>>{
201 2 : ActivateIntent: CallbackAction<ActivateIntent>(
202 1 : onInvoke: (_) {
203 1 : _toggle();
204 : return null;
205 : },
206 : ),
207 : },
208 2 : child: GestureDetector(
209 2 : onTap: _toggle,
210 : // A selectable body is a tap target in its own right, so it floors at
211 : // the minimum. An inert body keeps its exact box, which is what lets
212 : // a field lay chips out without extra row height.
213 2 : child: ConstrainedBox(
214 : constraints: const BoxConstraints(minHeight: _minTapTarget),
215 2 : child: Center(widthFactor: 1, heightFactor: 1, child: chip),
216 : ),
217 : ),
218 : );
219 : }
220 :
221 5 : return Semantics(
222 : container: true,
223 10 : button: widget.selectable,
224 14 : toggled: widget.onSelected == null ? null : widget.selected,
225 10 : enabled: widget.enabled,
226 10 : label: widget.semanticLabel,
227 : child: chip,
228 : );
229 : }
230 :
231 5 : Widget _paint(_ChipVisuals visuals) {
232 10 : final states = _states.value;
233 10 : final foreground = visuals.foreground.resolve(states);
234 10 : final remove = widget.onRemove;
235 :
236 5 : Widget surface = DecoratedBox(
237 5 : decoration: ShapeDecoration(
238 10 : color: visuals.background.resolve(states),
239 5 : shape: RoundedSuperellipseBorder(
240 10 : side: visuals.side.resolve(states),
241 5 : borderRadius: visuals.radius,
242 : ),
243 : ),
244 5 : child: ConstrainedBox(
245 10 : constraints: BoxConstraints(minHeight: visuals.minHeight),
246 5 : child: Row(
247 : mainAxisSize: MainAxisSize.min,
248 5 : children: [
249 5 : Flexible(
250 5 : child: Padding(
251 5 : padding: EdgeInsetsDirectional.only(
252 5 : start: visuals.padStart,
253 : // With a close affordance the button's own padding closes the
254 : // end, and doubling up would push the glyph off the edge.
255 2 : end: remove == null ? visuals.padEnd : 0,
256 : ),
257 5 : child: _content(visuals, foreground),
258 : ),
259 : ),
260 : if (remove != null)
261 4 : _RemoveButton(
262 : color: foreground,
263 4 : padding: visuals.removePadding,
264 4 : radius: visuals.removeRadius,
265 4 : ring: visuals.ring,
266 4 : ringOffset: visuals.ringOffset,
267 8 : label: widget.removeLabel,
268 8 : enabled: widget.enabled,
269 : onRemove: remove,
270 : ),
271 : ],
272 : ),
273 : ),
274 : );
275 :
276 10 : if (!widget.enabled) {
277 4 : surface = Opacity(opacity: visuals.disabledOpacity, child: surface);
278 : }
279 :
280 5 : return CustomPaint(
281 5 : foregroundPainter: states.contains(WidgetState.focused)
282 1 : ? _FocusRingPainter(
283 1 : color: visuals.ring,
284 1 : offsetColor: visuals.ringOffset,
285 1 : radius: visuals.radius,
286 : )
287 : : null,
288 : child: surface,
289 : );
290 : }
291 :
292 : /// Builds the leading icon and label row.
293 5 : Widget _content(_ChipVisuals visuals, Color foreground) {
294 10 : final leading = widget.leading;
295 5 : var label = DefaultTextStyle.merge(
296 10 : style: visuals.textStyle.copyWith(color: foreground),
297 : maxLines: 1,
298 : softWrap: false,
299 : overflow: TextOverflow.ellipsis,
300 10 : child: widget.label,
301 : );
302 :
303 : // A semanticLabel names the whole chip, so the visible text drops out of
304 : // the tree rather than being announced after it.
305 10 : if (widget.semanticLabel != null) {
306 1 : label = ExcludeSemantics(child: label);
307 : }
308 :
309 : if (leading == null) return label;
310 :
311 1 : return Row(
312 : mainAxisSize: MainAxisSize.min,
313 1 : spacing: visuals.gap,
314 1 : children: [
315 1 : ExcludeSemantics(
316 1 : child: IconTheme.merge(
317 1 : data: IconThemeData(
318 1 : size: visuals.iconSize,
319 3 : color: foreground.withValues(alpha: foreground.a * _affixOpacity),
320 : ),
321 : child: leading,
322 : ),
323 : ),
324 1 : Flexible(child: label),
325 : ],
326 : );
327 : }
328 : }
329 :
330 : /// The close affordance: its own focus stop, its own hover, and a hit region
331 : /// grown past the small glyph without disturbing the chip's layout.
332 : class _RemoveButton extends StatefulWidget {
333 4 : const _RemoveButton({
334 : required this.color,
335 : required this.padding,
336 : required this.radius,
337 : required this.ring,
338 : required this.ringOffset,
339 : required this.label,
340 : required this.enabled,
341 : required this.onRemove,
342 : });
343 :
344 : final Color color;
345 : final EdgeInsetsGeometry padding;
346 : final BorderRadius radius;
347 : final Color ring;
348 : final Color ringOffset;
349 : final String label;
350 : final bool enabled;
351 : final VoidCallback onRemove;
352 :
353 4 : @override
354 4 : State<_RemoveButton> createState() => _RemoveButtonState();
355 : }
356 :
357 : class _RemoveButtonState extends State<_RemoveButton> {
358 : bool _hovered = false;
359 : bool _focused = false;
360 :
361 4 : @override
362 : Widget build(BuildContext context) {
363 8 : final lit = _hovered || _focused;
364 12 : final color = widget.color.withValues(
365 16 : alpha: widget.color.a * (lit ? 1.0 : _affixOpacity),
366 : );
367 :
368 4 : return Semantics(
369 : button: true,
370 8 : enabled: widget.enabled,
371 8 : label: widget.label,
372 4 : child: FocusableActionDetector(
373 8 : enabled: widget.enabled,
374 8 : mouseCursor: widget.enabled
375 : ? SystemMouseCursors.click
376 : : SystemMouseCursors.basic,
377 4 : onShowHoverHighlight: (v) => setState(() => _hovered = v),
378 4 : onShowFocusHighlight: (v) => setState(() => _focused = v),
379 4 : actions: <Type, Action<Intent>>{
380 4 : ActivateIntent: CallbackAction<ActivateIntent>(
381 1 : onInvoke: (_) {
382 3 : widget.onRemove();
383 : return null;
384 : },
385 : ),
386 : },
387 4 : child: GestureDetector(
388 : behavior: HitTestBehavior.opaque,
389 14 : onTap: widget.enabled ? widget.onRemove : null,
390 4 : child: Padding(
391 8 : padding: widget.padding,
392 4 : child: CustomPaint(
393 4 : foregroundPainter: _focused
394 1 : ? _FocusRingPainter(
395 2 : color: widget.ring,
396 2 : offsetColor: widget.ringOffset,
397 2 : radius: widget.radius,
398 : )
399 : : null,
400 : // Compact glyph footprint, hit region grown to the minimum touch
401 : // target so the small mark is comfortably tappable. The overflow
402 : // keeps that growth out of the chip's layout.
403 4 : child: SizedBox.square(
404 : dimension: _removeGlyphSize,
405 4 : child: OverflowBox(
406 : maxWidth: _minTapTarget,
407 : maxHeight: _minTapTarget,
408 4 : child: Center(
409 4 : child: CustomPaint(
410 : size: const Size.square(_removeGlyphSize),
411 4 : painter: CloseGlyph(color),
412 : ),
413 : ),
414 : ),
415 : ),
416 : ),
417 : ),
418 : ),
419 : ),
420 : );
421 : }
422 : }
423 :
424 : /// Scales [color] to [opacity] of its own alpha, keeping it translucent so the
425 : /// fill composites over whatever surface the chip sits on.
426 1 : Color _alpha(Color color, double opacity) =>
427 3 : color.withValues(alpha: color.a * opacity);
428 :
429 : /// Composites [base] at [opacity] of its own alpha over a fixed [surface],
430 : /// baking an opaque color for the soft hover step.
431 5 : Color _overlay(Color base, double opacity, Color surface) =>
432 20 : Color.alphaBlend(base.withValues(alpha: base.a * opacity), surface);
433 :
434 : /// Builds the default appearance for a (variant, size) from the theme tokens.
435 5 : _ChipVisuals _resolve(
436 : FossThemeData theme,
437 : FossChipVariant variant,
438 : FossChipSize size,
439 : ) {
440 5 : final c = theme.colors;
441 :
442 : final Color rest;
443 : final Color hover;
444 : final Color restForeground;
445 : final BorderSide side;
446 : switch (variant) {
447 5 : case FossChipVariant.soft:
448 5 : rest = c.accent;
449 15 : hover = _overlay(c.input, _hoverFillOpacity, c.background);
450 5 : restForeground = c.accentForeground;
451 : side = BorderSide.none;
452 1 : case FossChipVariant.outline:
453 1 : rest = c.background;
454 1 : hover = c.accent;
455 1 : restForeground = c.foreground;
456 2 : side = BorderSide(color: c.input);
457 : }
458 :
459 : // Selection collapses both variants to the same solid pill, so a chosen chip
460 : // reads the same wherever it sits.
461 : final selectedSide = switch (variant) {
462 5 : FossChipVariant.soft => BorderSide.none,
463 3 : FossChipVariant.outline => BorderSide(color: c.primary),
464 : };
465 :
466 : final (minHeight, padX, removePadX, removePadY, iconSize) = switch (size) {
467 5 : FossChipSize.sm => (
468 : 24.0,
469 8 : theme.spacing(2),
470 8 : theme.spacing(1.5),
471 8 : theme.spacing(1),
472 : 14.0,
473 : ),
474 2 : FossChipSize.md => (
475 : 32.0,
476 4 : theme.spacing(2.5),
477 4 : theme.spacing(2),
478 4 : theme.spacing(2),
479 : 16.0,
480 : ),
481 : };
482 :
483 5 : return _ChipVisuals(
484 10 : background: WidgetStateProperty.resolveWith((states) {
485 5 : if (states.contains(WidgetState.selected)) {
486 2 : return states.contains(WidgetState.hovered)
487 2 : ? _alpha(c.primary, _selectedHoverOpacity)
488 2 : : c.primary;
489 : }
490 5 : if (states.contains(WidgetState.hovered)) return hover;
491 : return rest;
492 : }),
493 5 : foreground: WidgetStateProperty.resolveWith(
494 10 : (states) => states.contains(WidgetState.selected)
495 2 : ? c.primaryForeground
496 : : restForeground,
497 : ),
498 5 : side: WidgetStateProperty.resolveWith(
499 10 : (states) => states.contains(WidgetState.selected) ? selectedSide : side,
500 : ),
501 20 : radius: BorderRadius.all(Radius.circular(theme.radii.md)),
502 20 : removeRadius: BorderRadius.all(Radius.circular(theme.radii.sm)),
503 : padStart: padX,
504 : padEnd: padX,
505 5 : removePadding: EdgeInsets.symmetric(
506 : horizontal: removePadX,
507 : vertical: removePadY,
508 : ),
509 : minHeight: minHeight,
510 15 : textStyle: theme.typography.sm.medium,
511 : iconSize: iconSize,
512 10 : gap: theme.spacing(1),
513 : disabledOpacity: _disabledOpacity,
514 5 : ring: c.ring,
515 5 : ringOffset: c.background,
516 : );
517 : }
518 :
519 : /// The fully resolved, non-null appearance for one (variant, size). A public
520 : /// [FossChipStyle] override is laid over it by [merge], so the widget reads
521 : /// only non-null fields and never needs the null-assertion operator.
522 : @immutable
523 : class _ChipVisuals {
524 5 : const _ChipVisuals({
525 : required this.background,
526 : required this.foreground,
527 : required this.side,
528 : required this.radius,
529 : required this.removeRadius,
530 : required this.padStart,
531 : required this.padEnd,
532 : required this.removePadding,
533 : required this.minHeight,
534 : required this.textStyle,
535 : required this.iconSize,
536 : required this.gap,
537 : required this.disabledOpacity,
538 : required this.ring,
539 : required this.ringOffset,
540 : });
541 :
542 : final WidgetStateProperty<Color> background;
543 : final WidgetStateProperty<Color> foreground;
544 : final WidgetStateProperty<BorderSide> side;
545 : final BorderRadius radius;
546 : final BorderRadius removeRadius;
547 : final double padStart;
548 : final double padEnd;
549 : final EdgeInsetsGeometry removePadding;
550 : final double minHeight;
551 : final TextStyle textStyle;
552 : final double iconSize;
553 : final double gap;
554 : final double disabledOpacity;
555 : final Color ring;
556 : final Color ringOffset;
557 :
558 : /// Lays a per-instance [override] over this resolved base, field by field.
559 5 : _ChipVisuals merge(FossChipStyle? override) {
560 : if (override == null) return this;
561 2 : final uniform = override.borderRadius;
562 : final corners = uniform == null
563 1 : ? radius
564 4 : : BorderRadius.all(Radius.circular(uniform));
565 2 : return _ChipVisuals(
566 4 : background: override.backgroundColor ?? background,
567 4 : foreground: override.foregroundColor ?? foreground,
568 2 : side: switch (override.side) {
569 1 : final s? => WidgetStatePropertyAll(s),
570 2 : null => side,
571 : },
572 : radius: corners,
573 2 : removeRadius: removeRadius,
574 4 : padStart: override.padding ?? padStart,
575 4 : padEnd: override.padding ?? padEnd,
576 2 : removePadding: removePadding,
577 4 : minHeight: override.minHeight ?? minHeight,
578 4 : textStyle: override.textStyle ?? textStyle,
579 4 : iconSize: override.iconSize ?? iconSize,
580 4 : gap: override.gap ?? gap,
581 4 : disabledOpacity: override.disabledOpacity ?? disabledOpacity,
582 2 : ring: ring,
583 2 : ringOffset: ringOffset,
584 : );
585 : }
586 : }
587 :
588 : /// Paints the focus ring: a 2px superellipse outset just past the edge, with a
589 : /// 1px offset gap filled with [offsetColor] (the surface) so the ring reads as
590 : /// detached, matching the corner shape rather than a circular arc.
591 : class _FocusRingPainter extends CustomPainter {
592 1 : const _FocusRingPainter({
593 : required this.color,
594 : required this.offsetColor,
595 : required this.radius,
596 : });
597 :
598 : final Color color;
599 : final Color offsetColor;
600 : final BorderRadius radius;
601 :
602 1 : RSuperellipse _shape(Rect box, double inflate, double grow) {
603 1 : Radius corner(Radius c) =>
604 4 : c == Radius.zero ? Radius.zero : Radius.circular(c.x + grow);
605 1 : return RSuperellipse.fromRectAndCorners(
606 1 : box.inflate(inflate),
607 3 : topLeft: corner(radius.topLeft),
608 3 : topRight: corner(radius.topRight),
609 3 : bottomLeft: corner(radius.bottomLeft),
610 3 : bottomRight: corner(radius.bottomRight),
611 : );
612 : }
613 :
614 1 : @override
615 : void paint(Canvas canvas, Size size) {
616 1 : final box = Offset.zero & size;
617 : canvas
618 1 : ..drawRSuperellipse(
619 3 : _shape(box, _ringOffset / 2, _ringOffset / 2),
620 1 : Paint()
621 2 : ..color = offsetColor
622 1 : ..style = PaintingStyle.stroke
623 1 : ..strokeWidth = _ringOffset,
624 : )
625 1 : ..drawRSuperellipse(
626 5 : _shape(box, _ringOffset + _ringWidth / 2, _ringOffset + _ringWidth / 2),
627 1 : Paint()
628 2 : ..color = color
629 1 : ..style = PaintingStyle.stroke
630 1 : ..strokeWidth = _ringWidth,
631 : );
632 : }
633 :
634 1 : @override
635 : bool shouldRepaint(_FocusRingPainter old) =>
636 3 : old.color != color ||
637 3 : old.offsetColor != offsetColor ||
638 3 : old.radius != radius;
639 : }
|