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/theme/theme.dart';
6 :
7 : part 'foss_slider_style.dart';
8 :
9 : // Fixed control geometry: the track bar, the thumb, and the touch target.
10 : // Mobile base values; none is token-able (nothing else references them).
11 : const double _trackHeight = 4;
12 : const double _thumbSize = 20;
13 : const double _trackInset = 2;
14 : const double _rangeMargin = 2;
15 : const double _ringWidth = 3;
16 : const double _dragScale = 1.2;
17 : const double _disabledOpacity = 0.64;
18 : const double _controlHeight = 48;
19 : const double _minTrackWidth = 176;
20 :
21 : // Focus ring alpha on the `ring` role: lighter in light mode, lifted in dark.
22 : const double _ringAlphaLight = 0.24;
23 : const double _ringAlphaDark = 0.48;
24 :
25 : // Keyboard step when continuous: a twentieth of the range per arrow press.
26 : const double _continuousStep = 0.05;
27 :
28 : // The thumb scale is the one animated transition; gated under reduced motion.
29 : const Duration _dragScaleDuration = Duration(milliseconds: 150);
30 :
31 : // A white knob in both themes (the one baked control color), with a faint 1px
32 : // dark rim along its top inner edge at rest.
33 : const Color _knobColor = Color(0xFFFFFFFF);
34 : const Color _thumbRim = Color(0x0A000000);
35 :
36 : /// {@category Inputs}
37 : /// {@template foss.slider.preview}
38 : /// <img src="https://fossui.org/components/slider/overview/light.png"
39 : /// alt="FossSlider, light theme" width="480"
40 : /// style="max-width:100%;height:auto" />
41 : /// <img src="https://fossui.org/components/slider/overview/dark.png"
42 : /// alt="FossSlider, dark theme" width="480"
43 : /// style="max-width:100%;height:auto" />
44 : ///
45 : /// See the [slider documentation ↗](https://fossui.org/docs/components/slider) or
46 : /// try it live in the
47 : /// [playground ↗](https://play.fossui.org/components/#/?path=components/slider/fossslider/playground).
48 : /// {@endtemplate}
49 : ///
50 : /// A horizontal slider: a track with a draggable thumb that picks a [double]
51 : /// from `[min, max]`.
52 : ///
53 : /// Continuous by default; pass [divisions] to snap to equal steps. A drag or a
54 : /// track tap maps the pointer to a value and reports it through [onChanged];
55 : /// [onChangeStart] and [onChangeEnd] bracket a drag. Passing `null` to
56 : /// [onChanged] or `false` to [enabled] disables the control. Arrow keys step
57 : /// the value, Home and End jump to [min] and [max]. Colors come from
58 : /// `context.fossTheme`; pass a [FossSliderStyle] to [style] for a one-off.
59 : ///
60 : /// {@macro foss.customize}
61 : ///
62 : /// ```dart
63 : /// FossSlider(
64 : /// value: _volume,
65 : /// onChanged: (v) => setState(() => _volume = v),
66 : /// semanticLabel: 'Volume',
67 : /// );
68 : /// ```
69 : class FossSlider extends StatefulWidget {
70 : /// {@macro foss.slider.preview}
71 : ///
72 : /// Creates a slider at [value], within `[min, max]`.
73 1 : const FossSlider({
74 : required this.value,
75 : required this.onChanged,
76 : this.min = 0,
77 : this.max = 100,
78 : this.divisions,
79 : this.onChangeStart,
80 : this.onChangeEnd,
81 : this.enabled = true,
82 : this.semanticLabel,
83 : this.style,
84 : super.key,
85 2 : }) : assert(min <= max, 'min must be <= max'),
86 : assert(
87 2 : divisions == null || divisions > 0,
88 : 'divisions must be positive',
89 : );
90 :
91 : /// The current value, within `[min, max]`. The caller holds and clamps it.
92 : final double value;
93 :
94 : /// Called with the new value as the thumb moves; `null` disables the control.
95 : final ValueChanged<double>? onChanged;
96 :
97 : /// Lower bound of the range. Defaults to 0.
98 : final double min;
99 :
100 : /// Upper bound of the range. Defaults to 100.
101 : final double max;
102 :
103 : /// Number of equal steps to snap to; `null` is continuous.
104 : final int? divisions;
105 :
106 : /// Called with the starting value when a drag begins.
107 : final ValueChanged<double>? onChangeStart;
108 :
109 : /// Called with the final value when a drag ends.
110 : final ValueChanged<double>? onChangeEnd;
111 :
112 : /// Whether the control accepts input. Disabled when false or [onChanged] is
113 : /// `null`.
114 : final bool enabled;
115 :
116 : /// Accessibility name for the control.
117 : final String? semanticLabel;
118 :
119 : /// Per-instance overrides layered on the theme-resolved style.
120 : final FossSliderStyle? style;
121 :
122 1 : @override
123 1 : State<FossSlider> createState() => _FossSliderState();
124 : }
125 :
126 : class _FossSliderState extends State<FossSlider> {
127 : final WidgetStatesController _states = WidgetStatesController();
128 : final GlobalKey _trackKey = GlobalKey();
129 :
130 : // True between a press and its release, so a press that becomes a drag does
131 : // not open a second value-change session.
132 : bool _inSession = false;
133 :
134 5 : bool get _enabled => widget.enabled && widget.onChanged != null;
135 :
136 1 : @override
137 : void initState() {
138 1 : super.initState();
139 3 : _states.update(WidgetState.disabled, !_enabled);
140 : }
141 :
142 1 : @override
143 : void didUpdateWidget(FossSlider oldWidget) {
144 1 : super.didUpdateWidget(oldWidget);
145 3 : _states.update(WidgetState.disabled, !_enabled);
146 : }
147 :
148 1 : @override
149 : void dispose() {
150 2 : _states.dispose();
151 1 : super.dispose();
152 : }
153 :
154 6 : double get _range => widget.max - widget.min;
155 :
156 1 : double get _fraction =>
157 10 : _range == 0 ? 0 : ((widget.value - widget.min) / _range).clamp(0.0, 1.0);
158 :
159 : // Clamps to the range, then snaps to the nearest division when stepped.
160 1 : double _snap(double value) {
161 5 : final clamped = value.clamp(widget.min, widget.max);
162 2 : final divisions = widget.divisions;
163 : if (divisions == null) return clamped;
164 2 : final step = _range / divisions;
165 9 : return widget.min + (((clamped - widget.min) / step).round() * step);
166 : }
167 :
168 1 : double get _keyboardStep {
169 2 : final divisions = widget.divisions;
170 2 : if (divisions != null) return _range / divisions;
171 2 : return _range * _continuousStep;
172 : }
173 :
174 : // Maps a global pointer position to a snapped value via the track's box, so
175 : // the math respects the laid-out width and the reading direction.
176 1 : double? _pointerToValue(Offset global) {
177 3 : final box = _trackKey.currentContext?.findRenderObject() as RenderBox?;
178 : if (box == null) return null;
179 2 : final width = box.size.width;
180 1 : final travel = width - _thumbSize;
181 1 : if (travel <= 0) return widget.value;
182 2 : final dx = box.globalToLocal(global).dx;
183 3 : final ltr = Directionality.of(context) == TextDirection.ltr;
184 3 : final fromStart = (ltr ? dx : width - dx) - _thumbSize / 2;
185 2 : final fraction = (fromStart / travel).clamp(0.0, 1.0);
186 6 : return _snap(widget.min + fraction * _range);
187 : }
188 :
189 1 : void _startSession(Offset global) {
190 1 : if (_pointerToValue(global) case final value?) {
191 1 : _inSession = true;
192 2 : _states.update(WidgetState.dragged, true);
193 3 : widget.onChangeStart?.call(value);
194 3 : widget.onChanged?.call(value);
195 : }
196 : }
197 :
198 1 : void _updateSession(Offset global) {
199 1 : if (_pointerToValue(global) case final value?) {
200 3 : widget.onChanged?.call(value);
201 : }
202 : }
203 :
204 1 : void _endSession() {
205 1 : if (!_inSession) return;
206 1 : _inSession = false;
207 2 : _states.update(WidgetState.dragged, false);
208 5 : widget.onChangeEnd?.call(widget.value);
209 : }
210 :
211 1 : void _emitKeyboard(double value) {
212 1 : final next = _snap(value);
213 6 : if (next != widget.value) widget.onChanged?.call(next);
214 : }
215 :
216 1 : Map<ShortcutActivator, Intent> _shortcuts(TextDirection direction) {
217 1 : final ltr = direction == TextDirection.ltr;
218 : const inc = _SliderIncrementIntent();
219 : const dec = _SliderDecrementIntent();
220 1 : return {
221 : const SingleActivator(LogicalKeyboardKey.arrowUp): inc,
222 : const SingleActivator(LogicalKeyboardKey.arrowDown): dec,
223 : const SingleActivator(LogicalKeyboardKey.arrowRight): ltr ? inc : dec,
224 : const SingleActivator(LogicalKeyboardKey.arrowLeft): ltr ? dec : inc,
225 : const SingleActivator(LogicalKeyboardKey.home): const _SliderMinIntent(),
226 : const SingleActivator(LogicalKeyboardKey.end): const _SliderMaxIntent(),
227 : };
228 : }
229 :
230 2 : Map<Type, Action<Intent>> get _actions => {
231 1 : _SliderIncrementIntent: CallbackAction<_SliderIncrementIntent>(
232 1 : onInvoke: (_) {
233 5 : _emitKeyboard(widget.value + _keyboardStep);
234 : return null;
235 : },
236 : ),
237 1 : _SliderDecrementIntent: CallbackAction<_SliderDecrementIntent>(
238 1 : onInvoke: (_) {
239 5 : _emitKeyboard(widget.value - _keyboardStep);
240 : return null;
241 : },
242 : ),
243 1 : _SliderMinIntent: CallbackAction<_SliderMinIntent>(
244 1 : onInvoke: (_) {
245 3 : _emitKeyboard(widget.min);
246 : return null;
247 : },
248 : ),
249 1 : _SliderMaxIntent: CallbackAction<_SliderMaxIntent>(
250 1 : onInvoke: (_) {
251 3 : _emitKeyboard(widget.max);
252 : return null;
253 : },
254 : ),
255 : };
256 :
257 1 : @override
258 : Widget build(BuildContext context) {
259 1 : final theme = context.fossTheme;
260 4 : final v = _apply(_resolve(theme), widget.style);
261 1 : final direction = Directionality.of(context);
262 : final reduceMotion =
263 2 : MediaQuery.maybeOf(context)?.disableAnimations ?? false;
264 :
265 1 : Widget control = LayoutBuilder(
266 1 : builder: (context, constraints) {
267 2 : final width = constraints.maxWidth.isFinite
268 2 : ? math.max(constraints.maxWidth, _minTrackWidth)
269 : : _minTrackWidth;
270 7 : final thumbStart = v.thumbSize / 2 + _fraction * (width - v.thumbSize);
271 1 : return SizedBox(
272 1 : key: _trackKey,
273 : height: _controlHeight,
274 : width: width,
275 1 : child: Stack(
276 : clipBehavior: Clip.none,
277 1 : children: [
278 1 : Positioned.fill(
279 1 : child: CustomPaint(
280 1 : painter: _TrackPainter(
281 1 : trackColor: v.trackColor,
282 1 : rangeColor: v.rangeColor,
283 1 : trackHeight: v.trackHeight,
284 2 : thumbRadius: v.thumbSize / 2,
285 1 : fraction: _fraction,
286 : textDirection: direction,
287 : ),
288 : ),
289 : ),
290 1 : PositionedDirectional(
291 3 : start: thumbStart - v.thumbSize / 2,
292 3 : top: (_controlHeight - v.thumbSize) / 2,
293 1 : child: _thumb(theme, v, reduceMotion: reduceMotion),
294 : ),
295 : ],
296 : ),
297 : );
298 : },
299 : );
300 :
301 1 : control = GestureDetector(
302 : behavior: HitTestBehavior.opaque,
303 4 : onTapDown: _enabled ? (d) => _startSession(d.globalPosition) : null,
304 3 : onTapUp: _enabled ? (_) => _endSession() : null,
305 2 : onTapCancel: _enabled ? _endSession : null,
306 1 : onHorizontalDragStart: _enabled
307 3 : ? (d) => _startSession(d.globalPosition)
308 : : null,
309 1 : onHorizontalDragUpdate: _enabled
310 3 : ? (d) => _updateSession(d.globalPosition)
311 : : null,
312 3 : onHorizontalDragEnd: _enabled ? (_) => _endSession() : null,
313 : child: control,
314 : );
315 :
316 1 : control = FocusableActionDetector(
317 1 : enabled: _enabled,
318 1 : mouseCursor: _enabled
319 : ? SystemMouseCursors.click
320 : : SystemMouseCursors.basic,
321 2 : shortcuts: _enabled ? _shortcuts(direction) : null,
322 2 : actions: _enabled ? _actions : null,
323 1 : onShowFocusHighlight: (value) =>
324 2 : _states.update(WidgetState.focused, value),
325 : child: control,
326 : );
327 :
328 1 : if (!_enabled) {
329 1 : control = Opacity(opacity: _disabledOpacity, child: control);
330 : }
331 :
332 1 : return Semantics(
333 : slider: true,
334 1 : enabled: _enabled,
335 2 : label: widget.semanticLabel,
336 3 : value: _format(widget.value),
337 6 : increasedValue: _format(_snap(widget.value + _keyboardStep)),
338 6 : decreasedValue: _format(_snap(widget.value - _keyboardStep)),
339 : // Drop the action at the bound it cannot move past, so a screen reader
340 : // never announces an unchanged value at the min or max.
341 6 : onIncrease: _enabled && widget.value < widget.max
342 6 : ? () => _emitKeyboard(widget.value + _keyboardStep)
343 : : null,
344 6 : onDecrease: _enabled && widget.value > widget.min
345 6 : ? () => _emitKeyboard(widget.value - _keyboardStep)
346 : : null,
347 : child: control,
348 : );
349 : }
350 :
351 1 : String _format(double value) {
352 5 : final clamped = value.clamp(widget.min, widget.max);
353 2 : return clamped == clamped.roundToDouble()
354 1 : ? clamped.toStringAsFixed(0)
355 1 : : clamped.toStringAsFixed(2);
356 : }
357 :
358 : // The thumb: a white knob that carries the resting shadow and rim, drops both
359 : // on focus or drag, paints the focus ring on keyboard focus, and scales up
360 : // while dragging.
361 1 : Widget _thumb(
362 : FossThemeData theme,
363 : _SliderVisuals v, {
364 : required bool reduceMotion,
365 : }) {
366 1 : final colors = theme.colors;
367 1 : final dark = colors.isDark;
368 1 : return ListenableBuilder(
369 1 : listenable: _states,
370 1 : builder: (_, _) {
371 3 : final focused = _states.value.contains(WidgetState.focused);
372 3 : final dragging = _states.value.contains(WidgetState.dragged);
373 : final atRest = !focused && !dragging;
374 :
375 1 : Widget thumb = SizedBox.square(
376 1 : dimension: v.thumbSize,
377 1 : child: DecoratedBox(
378 1 : decoration: ShapeDecoration(
379 1 : color: v.thumbColor,
380 3 : shape: CircleBorder(side: BorderSide(color: v.borderColor)),
381 1 : shadows: atRest ? v.shadow : const [],
382 : ),
383 : ),
384 : );
385 :
386 : if (atRest) {
387 1 : thumb = CustomPaint(
388 : foregroundPainter: const _RimPainter(color: _thumbRim),
389 : child: thumb,
390 : );
391 : }
392 : if (focused) {
393 1 : thumb = CustomPaint(
394 1 : foregroundPainter: _RingPainter(
395 2 : color: colors.ring.withValues(
396 : alpha: dark ? _ringAlphaDark : _ringAlphaLight,
397 : ),
398 : ),
399 : child: thumb,
400 : );
401 : }
402 :
403 1 : return TweenAnimationBuilder<double>(
404 1 : tween: Tween<double>(end: dragging ? _dragScale : 1),
405 : duration: reduceMotion ? Duration.zero : _dragScaleDuration,
406 : curve: Curves.ease,
407 1 : builder: (_, scale, child) =>
408 1 : Transform.scale(scale: scale, child: child),
409 : child: thumb,
410 : );
411 : },
412 : );
413 : }
414 : }
415 :
416 : class _SliderIncrementIntent extends Intent {
417 2 : const _SliderIncrementIntent();
418 : }
419 :
420 : class _SliderDecrementIntent extends Intent {
421 2 : const _SliderDecrementIntent();
422 : }
423 :
424 : class _SliderMinIntent extends Intent {
425 2 : const _SliderMinIntent();
426 : }
427 :
428 : class _SliderMaxIntent extends Intent {
429 2 : const _SliderMaxIntent();
430 : }
431 :
432 : /// Builds the default appearance from the theme tokens.
433 1 : _SliderVisuals _resolve(FossThemeData theme) {
434 1 : final c = theme.colors;
435 1 : return _SliderVisuals(
436 1 : trackColor: c.input,
437 1 : rangeColor: c.primary,
438 : thumbColor: _knobColor,
439 3 : borderColor: c.isDark ? c.background : c.input,
440 2 : shadow: theme.shadows.xs,
441 : trackHeight: _trackHeight,
442 : thumbSize: _thumbSize,
443 : );
444 : }
445 :
446 : /// Lays a per-instance [override] over the resolved [base], field by field.
447 1 : _SliderVisuals _apply(_SliderVisuals base, FossSliderStyle? override) {
448 : if (override == null) return base;
449 1 : return _SliderVisuals(
450 2 : trackColor: override.trackColor ?? base.trackColor,
451 1 : rangeColor: override.rangeColor ?? base.rangeColor,
452 2 : thumbColor: override.thumbColor ?? base.thumbColor,
453 2 : borderColor: override.borderColor ?? base.borderColor,
454 2 : shadow: override.shadow ?? base.shadow,
455 2 : trackHeight: override.trackHeight ?? base.trackHeight,
456 1 : thumbSize: override.thumbSize ?? base.thumbSize,
457 : );
458 : }
459 :
460 : /// The fully resolved, non-null appearance. A [FossSliderStyle] override is
461 : /// laid over it by [_apply], so the widget reads only non-null fields.
462 : @immutable
463 : class _SliderVisuals {
464 1 : const _SliderVisuals({
465 : required this.trackColor,
466 : required this.rangeColor,
467 : required this.thumbColor,
468 : required this.borderColor,
469 : required this.shadow,
470 : required this.trackHeight,
471 : required this.thumbSize,
472 : });
473 :
474 : final Color trackColor;
475 : final Color rangeColor;
476 : final Color thumbColor;
477 : final Color borderColor;
478 : final List<BoxShadow> shadow;
479 : final double trackHeight;
480 : final double thumbSize;
481 : }
482 :
483 : /// Paints the two stadium bars: the [trackColor] track inset at each end, and
484 : /// the [rangeColor] filled range from the start to the thumb center. In RTL the
485 : /// start is the right edge, so the fill grows leftward.
486 : class _TrackPainter extends CustomPainter {
487 1 : const _TrackPainter({
488 : required this.trackColor,
489 : required this.rangeColor,
490 : required this.trackHeight,
491 : required this.thumbRadius,
492 : required this.fraction,
493 : required this.textDirection,
494 : });
495 :
496 : final Color trackColor;
497 : final Color rangeColor;
498 : final double trackHeight;
499 : final double thumbRadius;
500 : final double fraction;
501 : final TextDirection textDirection;
502 :
503 1 : @override
504 : void paint(Canvas canvas, Size size) {
505 4 : final top = (size.height - trackHeight) / 2;
506 2 : final bottom = top + trackHeight;
507 3 : final radius = Radius.circular(trackHeight / 2);
508 :
509 1 : canvas.drawRRect(
510 1 : RRect.fromLTRBR(
511 : _trackInset,
512 : top,
513 2 : size.width - _trackInset,
514 : bottom,
515 : radius,
516 : ),
517 3 : Paint()..color = trackColor,
518 : );
519 :
520 2 : final ltr = textDirection == TextDirection.ltr;
521 8 : final fromStart = thumbRadius + fraction * (size.width - 2 * thumbRadius);
522 2 : final thumbX = ltr ? fromStart : size.width - fromStart;
523 2 : final startX = ltr ? _rangeMargin : size.width - _rangeMargin;
524 :
525 1 : canvas.drawRRect(
526 1 : RRect.fromLTRBR(
527 1 : math.min(startX, thumbX),
528 : top,
529 1 : math.max(startX, thumbX),
530 : bottom,
531 : radius,
532 : ),
533 3 : Paint()..color = rangeColor,
534 : );
535 : }
536 :
537 1 : @override
538 : bool shouldRepaint(_TrackPainter oldDelegate) =>
539 3 : oldDelegate.trackColor != trackColor ||
540 3 : oldDelegate.rangeColor != rangeColor ||
541 3 : oldDelegate.trackHeight != trackHeight ||
542 3 : oldDelegate.thumbRadius != thumbRadius ||
543 3 : oldDelegate.fraction != fraction ||
544 3 : oldDelegate.textDirection != textDirection;
545 : }
546 :
547 : /// Paints a 1px rim along the thumb's top inner edge, fading to nothing by the
548 : /// center: a faint dark line that reads against the white knob.
549 : class _RimPainter extends CustomPainter {
550 2 : const _RimPainter({required this.color});
551 :
552 : final Color color;
553 :
554 1 : @override
555 : void paint(Canvas canvas, Size size) {
556 2 : final rect = (Offset.zero & size).deflate(0.5);
557 1 : final paint = Paint()
558 2 : ..shader = LinearGradient(
559 : begin: Alignment.topCenter,
560 : end: Alignment.center,
561 4 : colors: [color, color.withValues(alpha: 0)],
562 1 : ).createShader(rect)
563 1 : ..style = PaintingStyle.stroke
564 1 : ..strokeWidth = 1;
565 4 : canvas.drawCircle(rect.center, rect.width / 2, paint);
566 : }
567 :
568 : // The thumb rim is a const painter, so the framework compares it by
569 : // identity and never calls this; kept to satisfy the interface.
570 : // coverage:ignore-start
571 : @override
572 : bool shouldRepaint(_RimPainter oldDelegate) => oldDelegate.color != color;
573 : // coverage:ignore-end
574 : }
575 :
576 : /// Paints the focus ring: a 3px circle concentric with the thumb, just outside
577 : /// its edge.
578 : class _RingPainter extends CustomPainter {
579 1 : const _RingPainter({required this.color});
580 :
581 : final Color color;
582 :
583 1 : @override
584 : void paint(Canvas canvas, Size size) {
585 1 : canvas.drawCircle(
586 1 : size.center(Offset.zero),
587 4 : size.width / 2 + _ringWidth / 2,
588 1 : Paint()
589 2 : ..color = color
590 1 : ..style = PaintingStyle.stroke
591 1 : ..strokeWidth = _ringWidth,
592 : );
593 : }
594 :
595 1 : @override
596 3 : bool shouldRepaint(_RingPainter oldDelegate) => oldDelegate.color != color;
597 : }
|