Line data Source code
1 : import 'package:flutter/foundation.dart' show setEquals;
2 : import 'package:flutter/semantics.dart' show SemanticsValidationResult;
3 : import 'package:flutter/widgets.dart';
4 : import 'package:fossui/src/components/radio/foss_radio.dart';
5 : import 'package:fossui/src/components/switch/foss_switch.dart';
6 : import 'package:fossui/src/icons/foss_glyph.dart';
7 : import 'package:fossui/src/theme/theme.dart';
8 :
9 : part 'foss_checkbox_group.dart';
10 : part 'foss_checkbox_style.dart';
11 :
12 : const double _boxSize = 18;
13 : const double _glyphSize = 14;
14 : const double _boxRadius = 4;
15 : const double _ringWidth = 2;
16 : const double _ringOffset = 1;
17 : const double _disabledOpacity = 0.64;
18 : const double _minTapTarget = 48;
19 :
20 : // Error border and ring alphas: the border deepens when the box is focused, the
21 : // ring lifts in dark mode.
22 : const double _errorBorderOpacity = 0.36;
23 : const double _errorBorderFocusedOpacity = 0.64;
24 : const double _errorRingOpacityLight = 0.48;
25 : const double _errorRingOpacityDark = 0.24;
26 :
27 : // Dark surfaces lift the resting fill by the input color at 32% of its alpha.
28 : const double _darkFillOpacity = 0.32;
29 :
30 : // Card variant: the checked or hovered card lifts its fill with the accent
31 : // role, the checked card lifts its border to the primary role.
32 : const double _cardCheckedBorderOpacity = 0.48;
33 : const double _cardFillOpacity = 0.5;
34 :
35 : // Inner top-lit rim at rest: a faint dark line in light mode, a faint white
36 : // highlight in dark mode.
37 : const Color _rimLight = Color(0x0A000000);
38 : const Color _rimDark = Color(0x0FFFFFFF);
39 :
40 : /// {@category Inputs}
41 : /// {@template foss.checkbox.preview}
42 : /// <img src="https://fossui.org/components/checkbox/overview/light.png"
43 : /// alt="FossCheckbox, light theme" width="480"
44 : /// style="max-width:100%;height:auto" />
45 : /// <img src="https://fossui.org/components/checkbox/overview/dark.png"
46 : /// alt="FossCheckbox, dark theme" width="480"
47 : /// style="max-width:100%;height:auto" />
48 : ///
49 : /// See the [checkbox documentation ↗](https://fossui.org/docs/components/checkbox) or
50 : /// try it live in the
51 : /// [playground ↗](https://play.fossui.org/components/#/?path=components/checkbox/fosscheckbox/playground).
52 : /// {@endtemplate}
53 : ///
54 : /// A checkbox: an independent on / off toggle that can also show an
55 : /// indeterminate state.
56 : ///
57 : /// [value] is tristate: `true` checked, `false` unchecked, `null` indeterminate
58 : /// (the minus glyph). A tap reports the new definite state through [onChanged]:
59 : /// unchecked and indeterminate go to `true`, checked goes to `false`. The
60 : /// checkbox never produces `null` itself; set [value] to `null` to drive the
61 : /// indeterminate state. `onChanged: null` (or `enabled: false`) disables it.
62 : ///
63 : /// Renders a square box with an optional [label] and [description]. A non-null
64 : /// [errorText] marks it invalid and shows a caption below. Colors, type, and
65 : /// spacing come from `context.fossTheme`; pass a [FossCheckboxStyle] to [style]
66 : /// for a one-off.
67 : ///
68 : /// For a multi-select set of options, see [FossCheckboxGroup].
69 : ///
70 : /// {@macro foss.customize}
71 : ///
72 : /// See also [FossCheckboxGroup] for a multi-select set, and [FossRadio] or
73 : /// [FossSwitch] for related toggles.
74 : ///
75 : /// ```dart
76 : /// FossCheckbox(
77 : /// value: accepted,
78 : /// label: 'Accept terms and conditions',
79 : /// onChanged: (checked) => setState(() => accepted = checked),
80 : /// );
81 : /// ```
82 : class FossCheckbox extends StatelessWidget {
83 : /// {@macro foss.checkbox.preview}
84 : ///
85 : /// Creates a checkbox. [value] is `true`, `false`, or `null` (indeterminate).
86 1 : const FossCheckbox({
87 : this.value = false,
88 : this.onChanged,
89 : this.label,
90 : this.description,
91 : this.errorText,
92 : this.enabled = true,
93 : this.style,
94 : super.key,
95 : });
96 :
97 : /// The checked state: `true`, `false`, or `null` for indeterminate.
98 : final bool? value;
99 :
100 : /// Called with the new definite state on a tap. Null disables the checkbox.
101 : final ValueChanged<bool>? onChanged;
102 :
103 : /// Optional title beside the box.
104 : final String? label;
105 :
106 : /// Optional secondary line below the [label].
107 : final String? description;
108 :
109 : /// Error caption below the control. A non-null value marks it invalid.
110 : final String? errorText;
111 :
112 : /// Whether the checkbox accepts input. Disabled when false or when
113 : /// [onChanged] is null.
114 : final bool enabled;
115 :
116 : /// Per-instance overrides layered on the theme-resolved style.
117 : final FossCheckboxStyle? style;
118 :
119 2 : @override
120 : Widget build(BuildContext context) {
121 2 : final theme = context.fossTheme;
122 2 : final onChanged = this.onChanged;
123 2 : final active = enabled && onChanged != null;
124 2 : final checked = value ?? false;
125 2 : final indeterminate = value == null;
126 :
127 2 : final control = _FossCheckboxControl(
128 : checked: checked,
129 : indeterminate: indeterminate,
130 : enabled: active,
131 2 : hasError: errorText != null,
132 : card: false,
133 : standalone: true,
134 2 : label: label,
135 2 : description: description,
136 2 : style: style,
137 4 : onToggle: active ? () => onChanged(value != true) : null,
138 : );
139 :
140 2 : if (errorText case final text?) {
141 1 : return Column(
142 : crossAxisAlignment: CrossAxisAlignment.start,
143 : mainAxisSize: MainAxisSize.min,
144 2 : spacing: theme.spacing(2),
145 1 : children: [
146 : control,
147 1 : Semantics(
148 : liveRegion: true,
149 1 : child: Text(
150 : text,
151 3 : style: theme.typography.xs.copyWith(
152 2 : color: theme.colors.destructiveForeground,
153 : ),
154 : ),
155 : ),
156 : ],
157 : );
158 : }
159 : return control;
160 : }
161 : }
162 :
163 : /// The shared box, texts, gesture, focus, and semantics for one checkbox.
164 : /// [FossCheckbox] and [FossCheckboxItem] both delegate their rendering here so
165 : /// the control looks identical standalone or inside a group.
166 : class _FossCheckboxControl extends StatefulWidget {
167 2 : const _FossCheckboxControl({
168 : required this.checked,
169 : required this.indeterminate,
170 : required this.enabled,
171 : required this.hasError,
172 : required this.card,
173 : required this.standalone,
174 : required this.label,
175 : required this.description,
176 : required this.style,
177 : required this.onToggle,
178 : });
179 :
180 : final bool checked;
181 : final bool indeterminate;
182 : final bool enabled;
183 : final bool hasError;
184 : final bool card;
185 :
186 : /// A standalone [FossCheckbox] floors its plain box to a full tap target; a
187 : /// grouped item stays compact so a stacked group reads tight.
188 : final bool standalone;
189 :
190 : final String? label;
191 : final String? description;
192 : final FossCheckboxStyle? style;
193 : final VoidCallback? onToggle;
194 :
195 2 : @override
196 2 : State<_FossCheckboxControl> createState() => _FossCheckboxControlState();
197 : }
198 :
199 : class _FossCheckboxControlState extends State<_FossCheckboxControl> {
200 : final WidgetStatesController _states = WidgetStatesController();
201 :
202 2 : @override
203 : void dispose() {
204 4 : _states.dispose();
205 2 : super.dispose();
206 : }
207 :
208 2 : @override
209 : Widget build(BuildContext context) {
210 2 : final theme = context.fossTheme;
211 6 : final v = _resolve(theme, widget.style);
212 8 : final hasText = widget.label != null || widget.description != null;
213 :
214 2 : Widget option = Row(
215 : crossAxisAlignment: CrossAxisAlignment.start,
216 4 : mainAxisSize: widget.card ? MainAxisSize.max : MainAxisSize.min,
217 2 : spacing: v.gap,
218 2 : children: [
219 2 : _boxSlot(theme, v, hasText: hasText),
220 2 : if (hasText) Flexible(child: _texts(theme, v)),
221 : ],
222 : );
223 :
224 4 : if (widget.card) {
225 1 : option = _cardSurface(theme, child: option);
226 : }
227 4 : if (!widget.enabled) {
228 2 : option = Opacity(opacity: _disabledOpacity, child: option);
229 : }
230 :
231 : // One merged node carries the checkbox role plus the label and description
232 : // so assistive tech announces the option once, not twice; an errored box
233 : // reports invalid.
234 2 : return MergeSemantics(
235 2 : child: Semantics(
236 4 : checked: widget.checked,
237 4 : mixed: widget.indeterminate ? true : null,
238 4 : enabled: widget.enabled,
239 4 : validationResult: widget.hasError
240 : ? SemanticsValidationResult.invalid
241 : : SemanticsValidationResult.none,
242 2 : child: FocusableActionDetector(
243 4 : enabled: widget.enabled,
244 4 : mouseCursor: widget.enabled
245 : ? SystemMouseCursors.click
246 : : SystemMouseCursors.basic,
247 1 : onShowFocusHighlight: (value) =>
248 2 : _states.update(WidgetState.focused, value),
249 : // Only the card surface reacts to hover; the bare box does not, so
250 : // skip the hover state (and its rebuild) outside the card variant.
251 4 : onShowHoverHighlight: widget.card
252 3 : ? (value) => _states.update(WidgetState.hovered, value)
253 : : null,
254 2 : actions: <Type, Action<Intent>>{
255 2 : ActivateIntent: CallbackAction<ActivateIntent>(
256 1 : onInvoke: (_) {
257 3 : widget.onToggle?.call();
258 : return null;
259 : },
260 : ),
261 : },
262 2 : child: GestureDetector(
263 : behavior: HitTestBehavior.opaque,
264 4 : onTap: widget.onToggle,
265 2 : child: _hitArea(option),
266 : ),
267 : ),
268 : ),
269 : );
270 : }
271 :
272 : // The card supplies its own padded surface. A standalone checkbox floors its
273 : // box to a full tap target on both axes (the [Align] keeps the box tight); a
274 : // grouped item hugs its content so a stacked group reads tight, matching the
275 : // reference.
276 2 : Widget _hitArea(Widget option) {
277 8 : if (widget.card || !widget.standalone) return option;
278 2 : return ConstrainedBox(
279 : constraints: const BoxConstraints(
280 : minHeight: _minTapTarget,
281 : minWidth: _minTapTarget,
282 : ),
283 2 : child: Align(
284 : alignment: AlignmentDirectional.centerStart,
285 : heightFactor: 1,
286 : widthFactor: 1,
287 : child: option,
288 : ),
289 : );
290 : }
291 :
292 : // The box, aligned to the first text line when a label or description is
293 : // present so it centers on the title rather than the whole text block.
294 2 : Widget _boxSlot(
295 : FossThemeData theme,
296 : _CheckboxVisuals v, {
297 : required bool hasText,
298 : }) {
299 2 : final box = ListenableBuilder(
300 2 : listenable: _states,
301 4 : builder: (_, _) => _box(theme, v),
302 : );
303 : if (!hasText) return box;
304 3 : final firstLine = widget.label != null ? v.labelStyle : v.descriptionStyle;
305 3 : final line = (firstLine.fontSize ?? 16) * (firstLine.height ?? 1);
306 1 : return SizedBox(
307 : height: line,
308 1 : child: Center(widthFactor: 1, child: box),
309 : );
310 : }
311 :
312 2 : Widget _box(FossThemeData theme, _CheckboxVisuals v) {
313 2 : final colors = theme.colors;
314 2 : final dark = colors.isDark;
315 6 : final focused = _states.value.contains(WidgetState.focused);
316 4 : final checked = widget.checked;
317 : final showBorder = !checked;
318 :
319 : // Border stays the resting input color except when invalid, where it
320 : // deepens and the focus ring switches to the destructive role.
321 2 : var borderColor = v.borderColor;
322 1 : var ringColor = focused ? colors.ring : null;
323 4 : if (widget.hasError) {
324 : if (showBorder) {
325 2 : borderColor = colors.destructive.withValues(
326 : alpha: focused ? _errorBorderFocusedOpacity : _errorBorderOpacity,
327 : );
328 : }
329 : if (focused) {
330 2 : ringColor = colors.destructive.withValues(
331 : alpha: dark ? _errorRingOpacityDark : _errorRingOpacityLight,
332 : );
333 : }
334 : }
335 :
336 : // The resting shadow and inner rim sit on the unchecked and indeterminate
337 : // box; they drop when checked, invalid, or disabled.
338 8 : final atRest = !checked && !widget.hasError && widget.enabled;
339 :
340 2 : Widget box = SizedBox.square(
341 2 : dimension: v.boxSize,
342 2 : child: DecoratedBox(
343 2 : decoration: ShapeDecoration(
344 4 : color: checked ? v.checkedColor : v.uncheckedFill,
345 2 : shape: RoundedSuperellipseBorder(
346 2 : side: showBorder ? BorderSide(color: borderColor) : BorderSide.none,
347 2 : borderRadius: BorderRadius.circular(_boxRadius),
348 : ),
349 1 : shadows: atRest ? v.shadow : const [],
350 : ),
351 2 : child: _glyph(v),
352 : ),
353 : );
354 :
355 : if (atRest) {
356 1 : box = CustomPaint(
357 1 : foregroundPainter: _RimPainter(
358 : color: dark ? _rimDark : _rimLight,
359 : topLit: dark,
360 : ),
361 : child: box,
362 : );
363 : }
364 :
365 : if (ringColor != null) {
366 1 : box = CustomPaint(
367 1 : foregroundPainter: _RingPainter(
368 : color: ringColor,
369 1 : offsetColor: colors.background,
370 : ),
371 : child: box,
372 : );
373 : }
374 :
375 : return box;
376 : }
377 :
378 : // The centered glyph: a checkmark when checked, a minus when indeterminate,
379 : // nothing when unchecked. Painted in-package, so no icon dependency.
380 2 : Widget? _glyph(_CheckboxVisuals v) {
381 8 : if (!widget.checked && !widget.indeterminate) return null;
382 2 : return Center(
383 2 : child: FossGlyphIcon(
384 12 : widget.checked ? CheckGlyph(v.checkColor) : MinusGlyph(v.minusColor),
385 2 : size: v.glyphSize,
386 : ),
387 : );
388 : }
389 :
390 1 : Widget _texts(FossThemeData theme, _CheckboxVisuals v) {
391 1 : final colors = theme.colors;
392 1 : return Column(
393 : crossAxisAlignment: CrossAxisAlignment.start,
394 : mainAxisSize: MainAxisSize.min,
395 2 : spacing: theme.spacing(1.5),
396 1 : children: [
397 2 : if (widget.label case final label?)
398 4 : Text(label, style: v.labelStyle.copyWith(color: colors.foreground)),
399 2 : if (widget.description case final description?)
400 1 : Text(
401 : description,
402 3 : style: v.descriptionStyle.copyWith(color: colors.mutedForeground),
403 : ),
404 : ],
405 : );
406 : }
407 :
408 : // Wraps an option in the card surface: a bordered, padded box that lifts its
409 : // border when checked and tints its fill when checked or hovered. A min
410 : // content height keeps the card past the tap-target floor.
411 1 : Widget _cardSurface(FossThemeData theme, {required Widget child}) {
412 1 : final colors = theme.colors;
413 1 : return ListenableBuilder(
414 1 : listenable: _states,
415 1 : builder: (_, _) {
416 3 : final hovered = _states.value.contains(WidgetState.hovered);
417 2 : final tinted = widget.checked || hovered;
418 1 : return DecoratedBox(
419 1 : decoration: ShapeDecoration(
420 : // accent at 50% of its own alpha: the accent
421 : // role is already a faint translucent tint, so this is a
422 : // barely-there wash, not a half-opaque fill.
423 : color: tinted
424 2 : ? colors.accent.withValues(
425 3 : alpha: colors.accent.a * _cardFillOpacity,
426 : )
427 : : null,
428 1 : shape: RoundedSuperellipseBorder(
429 1 : side: BorderSide(
430 2 : color: widget.checked
431 2 : ? colors.primary.withValues(
432 : alpha: _cardCheckedBorderOpacity,
433 : )
434 1 : : colors.border,
435 : ),
436 3 : borderRadius: BorderRadius.circular(theme.radii.lg),
437 : ),
438 : ),
439 1 : child: Padding(
440 3 : padding: EdgeInsets.all(theme.spacing(3)),
441 1 : child: ConstrainedBox(
442 3 : constraints: BoxConstraints(minHeight: theme.spacing(6)),
443 : child: child,
444 : ),
445 : ),
446 : );
447 : },
448 : );
449 : }
450 : }
451 :
452 : /// Builds the default appearance from the theme tokens, then lays a
453 : /// per-instance [override] over it field by field.
454 2 : _CheckboxVisuals _resolve(FossThemeData theme, FossCheckboxStyle? override) {
455 2 : final c = theme.colors;
456 :
457 : // Dark adds a faint lift to the resting box: the input color at 32% of its
458 : // alpha, composited to opaque. Light is the bare surface.
459 2 : final uncheckedFill = c.isDark
460 1 : ? Color.alphaBlend(
461 5 : c.input.withValues(alpha: c.input.a * _darkFillOpacity),
462 1 : c.background,
463 : )
464 2 : : c.background;
465 :
466 2 : return _CheckboxVisuals(
467 1 : uncheckedFill: override?.backgroundColor ?? uncheckedFill,
468 3 : checkedColor: override?.checkedColor ?? c.primary,
469 3 : checkColor: override?.checkColor ?? c.primaryForeground,
470 2 : minusColor: c.foreground,
471 3 : borderColor: override?.borderColor ?? c.input,
472 5 : shadow: override?.shadow ?? theme.shadows.xs,
473 1 : boxSize: override?.boxSize ?? _boxSize,
474 1 : glyphSize: override?.glyphSize ?? _glyphSize,
475 5 : gap: override?.gap ?? theme.spacing(2),
476 7 : labelStyle: override?.labelStyle ?? theme.typography.base.medium,
477 5 : descriptionStyle: override?.descriptionStyle ?? theme.typography.xs,
478 : );
479 : }
480 :
481 : /// The fully resolved, non-null appearance. The widget reads only non-null
482 : /// fields and never needs the null-assertion operator.
483 : @immutable
484 : class _CheckboxVisuals {
485 2 : const _CheckboxVisuals({
486 : required this.uncheckedFill,
487 : required this.checkedColor,
488 : required this.checkColor,
489 : required this.minusColor,
490 : required this.borderColor,
491 : required this.shadow,
492 : required this.boxSize,
493 : required this.glyphSize,
494 : required this.gap,
495 : required this.labelStyle,
496 : required this.descriptionStyle,
497 : });
498 :
499 : final Color uncheckedFill;
500 : final Color checkedColor;
501 : final Color checkColor;
502 : final Color minusColor;
503 : final Color borderColor;
504 : final List<BoxShadow> shadow;
505 : final double boxSize;
506 : final double glyphSize;
507 : final double gap;
508 : final TextStyle labelStyle;
509 : final TextStyle descriptionStyle;
510 : }
511 :
512 : /// Builds the superellipse outline of a box [rect] with corner [radius].
513 2 : Path _boxPath(Rect rect, double radius) => RoundedSuperellipseBorder(
514 1 : borderRadius: BorderRadius.circular(radius),
515 1 : ).getOuterPath(rect);
516 :
517 : /// Paints a 1px rim inside the box: brightest along one edge, fading to nothing
518 : /// by the center. [topLit] lights the top edge; otherwise the bottom.
519 : class _RimPainter extends CustomPainter {
520 1 : const _RimPainter({required this.color, required this.topLit});
521 :
522 : final Color color;
523 : final bool topLit;
524 :
525 1 : @override
526 : void paint(Canvas canvas, Size size) {
527 2 : final rect = (Offset.zero & size).deflate(0.5);
528 1 : final shader = LinearGradient(
529 1 : begin: topLit ? Alignment.topCenter : Alignment.bottomCenter,
530 : end: Alignment.center,
531 4 : colors: [color, color.withValues(alpha: 0)],
532 1 : ).createShader(rect);
533 1 : final paint = Paint()
534 1 : ..shader = shader
535 1 : ..style = PaintingStyle.stroke
536 1 : ..strokeWidth = 1;
537 2 : canvas.drawPath(_boxPath(rect, _boxRadius), paint);
538 : }
539 :
540 1 : @override
541 : bool shouldRepaint(_RimPainter old) =>
542 6 : old.color != color || old.topLit != topLit;
543 : }
544 :
545 : /// Paints the focus ring: a superellipse outset just past the box edge, with a
546 : /// 1px gap (the offset). The gap is filled with [offsetColor] (the surface) so
547 : /// the ring reads as detached even over a tinted card.
548 : class _RingPainter extends CustomPainter {
549 1 : const _RingPainter({required this.color, required this.offsetColor});
550 :
551 : final Color color;
552 : final Color offsetColor;
553 :
554 1 : @override
555 : void paint(Canvas canvas, Size size) {
556 1 : final box = Offset.zero & size;
557 : canvas
558 1 : ..drawPath(
559 5 : _boxPath(box.inflate(_ringOffset / 2), _boxRadius + _ringOffset / 2),
560 1 : Paint()
561 2 : ..color = offsetColor
562 1 : ..style = PaintingStyle.stroke
563 1 : ..strokeWidth = _ringOffset,
564 : )
565 1 : ..drawPath(
566 1 : _boxPath(
567 3 : box.inflate(_ringOffset + _ringWidth / 2),
568 3 : _boxRadius + _ringOffset + _ringWidth / 2,
569 : ),
570 1 : Paint()
571 2 : ..color = color
572 1 : ..style = PaintingStyle.stroke
573 1 : ..strokeWidth = _ringWidth,
574 : );
575 : }
576 :
577 1 : @override
578 : bool shouldRepaint(_RingPainter old) =>
579 3 : old.color != color || old.offsetColor != offsetColor;
580 : }
|