Line data Source code
1 : import 'package:flutter/widgets.dart';
2 : import 'package:fossui/src/components/checkbox/foss_checkbox.dart';
3 : import 'package:fossui/src/components/radio/foss_radio.dart';
4 : import 'package:fossui/src/theme/theme.dart';
5 :
6 : part 'foss_switch_style.dart';
7 :
8 : // Fixed control geometry, mobile base. The track is a pill, the thumb a circle
9 : // inset by the same gap on every side; the thumb travel falls out of the two
10 : // (inner width minus the thumb), so it is never a separate literal.
11 : const double _thumbSize = 20;
12 : const double _trackWidth = 38;
13 : const double _trackHeight = 22;
14 :
15 : const double _disabledOpacity = 0.64;
16 : const double _ringWidth = 2;
17 : const double _ringOffset = 1;
18 : const double _minTapTarget = 48;
19 :
20 : // Pressed thumb squish: a small stretch along the travel axis from the leading
21 : // edge, springing back on release.
22 : const double _pressScaleX = 1.1;
23 :
24 : // The thumb slides faster than the track crossfades; both are below the token
25 : // set, so the slide and the squish are local widget constants. The crossfade
26 : // reuses the overlay duration token.
27 : const Duration _slideDuration = Duration(milliseconds: 150);
28 : const Duration _squishDuration = Duration(milliseconds: 100);
29 :
30 : /// {@category Inputs}
31 : /// {@template foss.switch.preview}
32 : /// <img src="https://fossui.org/components/switch/overview/light.png"
33 : /// alt="FossSwitch, light theme" width="480"
34 : /// style="max-width:100%;height:auto" />
35 : /// <img src="https://fossui.org/components/switch/overview/dark.png"
36 : /// alt="FossSwitch, dark theme" width="480"
37 : /// style="max-width:100%;height:auto" />
38 : ///
39 : /// See the [switch documentation ↗](https://fossui.org/docs/components/switch) or
40 : /// try it live in the
41 : /// [playground ↗](https://play.fossui.org/components/#/?path=components/switch/fossswitch/playground).
42 : /// {@endtemplate}
43 : ///
44 : /// An instant on / off toggle: a pill track with a sliding thumb that commits a
45 : /// boolean the moment it is flipped.
46 : ///
47 : /// The switch is controlled: it renders [value] and reports the toggled value
48 : /// through [onChanged] on a tap, a drag, or Space / Enter. Passing `null` to
49 : /// [onChanged] disables it (dims the control and drops the pointer), so there
50 : /// is no separate enabled flag. It carries no visible label; lay out the row
51 : /// around it and name it for assistive tech with [semanticLabel].
52 : ///
53 : /// Colors, the track crossfade, and the thumb come from `context.fossTheme`;
54 : /// pass a [FossSwitchStyle] to [style] for a one-off.
55 : ///
56 : /// {@macro foss.customize}
57 : ///
58 : /// See also [FossCheckbox] for a labelled toggle and [FossRadio] for a single
59 : /// choice from a set.
60 : ///
61 : /// ```dart
62 : /// FossSwitch(
63 : /// value: wifiOn,
64 : /// semanticLabel: 'Wi-Fi',
65 : /// onChanged: (on) => setState(() => wifiOn = on),
66 : /// );
67 : /// ```
68 : class FossSwitch extends StatefulWidget {
69 : /// {@macro foss.switch.preview}
70 : ///
71 : /// Creates a switch showing [value].
72 2 : const FossSwitch({
73 : required this.value,
74 : this.onChanged,
75 : this.semanticLabel,
76 : this.style,
77 : super.key,
78 : });
79 :
80 : /// The current state: `true` on, `false` off.
81 : final bool value;
82 :
83 : /// Called with the toggled value on a tap, drag, or Space / Enter. Null
84 : /// disables the switch.
85 : final ValueChanged<bool>? onChanged;
86 :
87 : /// Accessibility name for the toggle.
88 : final String? semanticLabel;
89 :
90 : /// Per-instance overrides layered on the theme-resolved style.
91 : final FossSwitchStyle? style;
92 :
93 2 : @override
94 2 : State<FossSwitch> createState() => _FossSwitchState();
95 : }
96 :
97 : class _FossSwitchState extends State<FossSwitch> {
98 : final WidgetStatesController _states = WidgetStatesController();
99 :
100 6 : bool get _enabled => widget.onChanged != null;
101 :
102 2 : @override
103 : void dispose() {
104 4 : _states.dispose();
105 2 : super.dispose();
106 : }
107 :
108 12 : void _toggle() => widget.onChanged?.call(!widget.value);
109 :
110 6 : void _press(bool pressed) => _states.update(WidgetState.pressed, pressed);
111 :
112 : // A flick toggles toward its direction; a still release falls back to a plain
113 : // toggle. The pointer axis is mapped through the reading direction so a drag
114 : // to the visual end always means "on".
115 1 : void _dragEnd(DragEndDetails details, TextDirection direction) {
116 1 : _press(false);
117 1 : final velocity = details.primaryVelocity ?? 0;
118 1 : if (velocity == 0) {
119 1 : _toggle();
120 : return;
121 : }
122 3 : final toEnd = direction == TextDirection.ltr ? velocity > 0 : velocity < 0;
123 6 : if (toEnd != widget.value) widget.onChanged?.call(toEnd);
124 : }
125 :
126 2 : @override
127 : Widget build(BuildContext context) {
128 2 : final theme = context.fossTheme;
129 6 : final v = _resolve(theme, widget.style);
130 2 : final direction = Directionality.of(context);
131 : final reduceMotion =
132 4 : MediaQuery.maybeOf(context)?.disableAnimations ?? false;
133 4 : final on = widget.value;
134 :
135 : // Off rests at the leading edge, on at the trailing edge; the squish grows
136 : // from whichever edge the thumb sits against. Both mirror under RTL.
137 : final align = on
138 : ? AlignmentDirectional.centerEnd
139 : : AlignmentDirectional.centerStart;
140 8 : final pad = (v.trackHeight - v.thumbSize) / 2;
141 :
142 2 : Widget visual = ListenableBuilder(
143 2 : listenable: _states,
144 2 : builder: (context, child) {
145 6 : final focused = _states.value.contains(WidgetState.focused);
146 6 : final pressed = _states.value.contains(WidgetState.pressed);
147 :
148 : final squish = pressed && !reduceMotion ? _pressScaleX : 1.0;
149 2 : final thumb = TweenAnimationBuilder<double>(
150 2 : tween: Tween<double>(end: squish),
151 : duration: reduceMotion ? Duration.zero : _squishDuration,
152 : curve: Curves.ease,
153 4 : builder: (_, scale, thumbChild) => Transform(
154 2 : alignment: align.resolve(direction),
155 2 : transform: Matrix4.diagonal3Values(scale, 1, 1),
156 : child: thumbChild,
157 : ),
158 2 : child: SizedBox.square(
159 2 : dimension: v.thumbSize,
160 2 : child: DecoratedBox(
161 2 : decoration: ShapeDecoration(
162 2 : color: v.thumbColor,
163 : shape: const CircleBorder(),
164 2 : shadows: v.shadow,
165 : ),
166 : ),
167 : ),
168 : );
169 :
170 2 : Widget track = TweenAnimationBuilder<double>(
171 2 : tween: Tween<double>(end: on ? 1 : 0),
172 4 : duration: reduceMotion ? Duration.zero : theme.motion.overlay,
173 : curve: Curves.ease,
174 4 : builder: (_, t, trackChild) => DecoratedBox(
175 2 : decoration: ShapeDecoration(
176 6 : color: Color.lerp(v.inactiveTrackColor, v.activeTrackColor, t),
177 : shape: const StadiumBorder(),
178 : ),
179 : child: trackChild,
180 : ),
181 2 : child: Padding(
182 2 : padding: EdgeInsets.all(pad),
183 2 : child: AnimatedAlign(
184 : alignment: align,
185 : duration: reduceMotion ? Duration.zero : _slideDuration,
186 : curve: Curves.ease,
187 : child: thumb,
188 : ),
189 : ),
190 : );
191 :
192 : if (focused) {
193 1 : track = CustomPaint(
194 1 : foregroundPainter: _RingPainter(
195 2 : color: theme.colors.ring,
196 2 : offsetColor: theme.colors.background,
197 : ),
198 : child: track,
199 : );
200 : }
201 : return track;
202 : },
203 : );
204 :
205 2 : visual = SizedBox(
206 2 : width: v.trackWidth,
207 2 : height: v.trackHeight,
208 : child: visual,
209 : );
210 :
211 2 : if (!_enabled) {
212 1 : visual = Opacity(opacity: _disabledOpacity, child: visual);
213 : }
214 :
215 : // The visible track is small; the gesture and focus target is floored to
216 : // the minimum tap size around it without enlarging the pill.
217 2 : final control = FocusableActionDetector(
218 2 : enabled: _enabled,
219 2 : mouseCursor: _enabled
220 : ? SystemMouseCursors.click
221 : : SystemMouseCursors.basic,
222 1 : onShowFocusHighlight: (value) =>
223 2 : _states.update(WidgetState.focused, value),
224 2 : actions: <Type, Action<Intent>>{
225 2 : ActivateIntent: CallbackAction<ActivateIntent>(
226 1 : onInvoke: (_) {
227 1 : _toggle();
228 : return null;
229 : },
230 : ),
231 : },
232 2 : child: GestureDetector(
233 : behavior: HitTestBehavior.opaque,
234 : // The toggle role, state, and tap live on the outer Semantics node; the
235 : // drag handlers would otherwise leak scroll actions into the tree.
236 : excludeFromSemantics: true,
237 4 : onTap: _enabled ? _toggle : null,
238 6 : onTapDown: _enabled ? (_) => _press(true) : null,
239 6 : onTapUp: _enabled ? (_) => _press(false) : null,
240 2 : onTapCancel: _enabled ? () => _press(false) : null,
241 4 : onHorizontalDragStart: _enabled ? (_) => _press(true) : null,
242 4 : onHorizontalDragEnd: _enabled ? (d) => _dragEnd(d, direction) : null,
243 6 : onHorizontalDragCancel: _enabled ? () => _press(false) : null,
244 2 : child: ConstrainedBox(
245 : constraints: const BoxConstraints(
246 : minWidth: _minTapTarget,
247 : minHeight: _minTapTarget,
248 : ),
249 2 : child: Center(child: visual),
250 : ),
251 : ),
252 : );
253 :
254 : // One merged node carries the toggle role, its state, and the focus action
255 : // from the detector, so assistive tech announces the switch once.
256 2 : return MergeSemantics(
257 2 : child: Semantics(
258 : toggled: on,
259 2 : enabled: _enabled,
260 4 : label: widget.semanticLabel,
261 4 : onTap: _enabled ? _toggle : null,
262 : child: control,
263 : ),
264 : );
265 : }
266 : }
267 :
268 : // The thumb wears the small shadow softened to a 5% tint, a faint lift rather
269 : // than a drop shadow.
270 4 : List<BoxShadow> _thumbShadow(List<BoxShadow> base) => <BoxShadow>[
271 2 : for (final shadow in base)
272 6 : shadow.copyWith(color: shadow.color.withValues(alpha: 0.05)),
273 : ];
274 :
275 : /// Builds the default appearance from the theme tokens, then lays a
276 : /// per-instance [override] over it field by field.
277 2 : _SwitchVisuals _resolve(FossThemeData theme, FossSwitchStyle? override) {
278 2 : final c = theme.colors;
279 2 : return _SwitchVisuals(
280 3 : activeTrackColor: override?.activeTrackColor ?? c.primary,
281 3 : inactiveTrackColor: override?.inactiveTrackColor ?? c.input,
282 3 : thumbColor: override?.thumbColor ?? c.background,
283 7 : shadow: override?.shadow ?? _thumbShadow(theme.shadows.sm),
284 1 : trackWidth: override?.trackWidth ?? _trackWidth,
285 1 : trackHeight: override?.trackHeight ?? _trackHeight,
286 1 : thumbSize: override?.thumbSize ?? _thumbSize,
287 : );
288 : }
289 :
290 : /// The fully resolved, non-null appearance. A [FossSwitchStyle] override is
291 : /// laid over it by [_resolve], so the widget reads only non-null fields.
292 : @immutable
293 : class _SwitchVisuals {
294 2 : const _SwitchVisuals({
295 : required this.activeTrackColor,
296 : required this.inactiveTrackColor,
297 : required this.thumbColor,
298 : required this.shadow,
299 : required this.trackWidth,
300 : required this.trackHeight,
301 : required this.thumbSize,
302 : });
303 :
304 : final Color activeTrackColor;
305 : final Color inactiveTrackColor;
306 : final Color thumbColor;
307 : final List<BoxShadow> shadow;
308 : final double trackWidth;
309 : final double trackHeight;
310 : final double thumbSize;
311 : }
312 :
313 : /// Paints the focus ring: a stadium outset just past the track, with a 1px gap
314 : /// (the offset) filled with [offsetColor] (the surface) so the ring reads as
315 : /// detached from the track.
316 : class _RingPainter extends CustomPainter {
317 1 : const _RingPainter({required this.color, required this.offsetColor});
318 :
319 : final Color color;
320 : final Color offsetColor;
321 :
322 1 : @override
323 : void paint(Canvas canvas, Size size) {
324 1 : final box = Offset.zero & size;
325 1 : RRect pill(double inflate) {
326 1 : final rect = box.inflate(inflate);
327 1 : return RRect.fromRectAndRadius(
328 : rect,
329 3 : Radius.circular(rect.shortestSide / 2),
330 : );
331 : }
332 :
333 : canvas
334 1 : ..drawRRect(
335 2 : pill(_ringOffset / 2),
336 1 : Paint()
337 2 : ..color = offsetColor
338 1 : ..style = PaintingStyle.stroke
339 1 : ..strokeWidth = _ringOffset,
340 : )
341 1 : ..drawRRect(
342 3 : pill(_ringOffset + _ringWidth / 2),
343 1 : Paint()
344 2 : ..color = color
345 1 : ..style = PaintingStyle.stroke
346 1 : ..strokeWidth = _ringWidth,
347 : );
348 : }
349 :
350 1 : @override
351 : bool shouldRepaint(_RingPainter old) =>
352 6 : old.color != color || old.offsetColor != offsetColor;
353 : }
|