Skip to main content

waft_material/
slider_theme.rs

1//! Flutter counterpart: material_ui's `slider_theme.dart`.
2//!
3//! The shapes a [`SliderThemeData`] carries are trait objects (`slider_parts.rs`,
4//! `slider_value_indicator_shape.rs`, `range_slider_parts.rs`); its `==` compares them with
5//! their `eq_shape`, which is identity unless a shape overrides it, as the built-in ones do.
6
7use std::fmt::{self, Debug};
8use std::rc::Rc;
9
10use waft_embedder::{Color, Size, lerp_double};
11use waft_foundation::{App, DiagnosticsProperty, DoubleProperty, EnumProperty};
12use waft_painting::{AnyColor, ColorProperty, EdgeInsetsGeometry, TextStyle};
13use waft_services::MouseCursorRef;
14use waft_widgets::{
15    BuildContext, InheritedTheme, InheritedWidget, IntoWidget, KeyRef, WidgetRef,
16    WidgetStateProperty, WidgetStatePropertyRef,
17};
18
19use crate::colors::Colors;
20use crate::range_slider_parts::{
21    RangeSliderThumbShapeRef, RangeSliderTickMarkShapeRef, RangeSliderTrackShapeRef,
22    RangeSliderValueIndicatorShapeRef, RangeThumbSelector, RoundRangeSliderThumbShape,
23    RoundRangeSliderTickMarkShape, RoundedRectRangeSliderTrackShape,
24};
25use crate::slider::SliderInteraction;
26use crate::slider_parts::{
27    RoundSliderThumbShape, RoundSliderTickMarkShape, RoundedRectSliderTrackShape,
28    SliderTickMarkShapeRef, SliderTrackShapeRef,
29};
30use crate::slider_value_indicator_shape::{
31    PaddleRangeSliderValueIndicatorShape, PaddleSliderValueIndicatorShape, RoundSliderOverlayShape,
32    SliderComponentShapeRef,
33};
34use crate::theme::Theme;
35
36/// Applies a slider theme to descendant `Slider` widgets.
37///
38/// A slider theme describes the colors and shape choices of the slider
39/// components.
40///
41/// Descendant widgets obtain the current theme's [`SliderThemeData`] object using
42/// [`SliderTheme::of`]. When a widget uses [`SliderTheme::of`], it is automatically
43/// rebuilt if the theme later changes.
44///
45/// The slider is as big as the largest of
46/// the `SliderComponentShape::get_preferred_size` of the thumb shape,
47/// the `SliderComponentShape::get_preferred_size` of the overlay shape,
48/// and the `SliderTickMarkShape::get_preferred_size` of the tick mark shape.
49///
50/// See also:
51///
52///  * [`SliderThemeData`], which describes the actual configuration of a slider
53///    theme.
54///  * `SliderComponentShape`, which can be used to create custom shapes for
55///    the `Slider`'s thumb, overlay, and value indicator and the
56///    `RangeSlider`'s overlay.
57///  * `SliderTrackShape`, which can be used to create custom shapes for the
58///    `Slider`'s track.
59///  * `SliderTickMarkShape`, which can be used to create custom shapes for the
60///    `Slider`'s tick marks.
61///  * `RangeSliderThumbShape`, which can be used to create custom shapes for
62///    the `RangeSlider`'s thumb.
63///  * `RangeSliderValueIndicatorShape`, which can be used to create custom
64///    shapes for the `RangeSlider`'s value indicator.
65///  * `RangeSliderTrackShape`, which can be used to create custom shapes for
66///    the `RangeSlider`'s track.
67///  * `RangeSliderTickMarkShape`, which can be used to create custom shapes for
68///    the `RangeSlider`'s tick marks.
69#[derive(Debug)]
70pub struct SliderTheme {
71    pub key: Option<KeyRef>,
72    /// Specifies the color and shape values for descendant slider widgets.
73    pub data: SliderThemeData,
74    pub child: WidgetRef,
75}
76
77impl SliderTheme {
78    /// Applies the given theme [`data`](Self::data) to `child`.
79    #[cfg_attr(debug_assertions, track_caller)]
80    pub fn new<K>(data: SliderThemeData, child: impl IntoWidget<K>) -> SliderTheme {
81        SliderTheme {
82            key: None,
83            data,
84            child: child.into_widget(),
85        }
86    }
87
88    /// Dart `SliderTheme(key:)`.
89    pub fn key(mut self, key: KeyRef) -> SliderTheme {
90        self.key = Some(key);
91        self
92    }
93
94    /// Returns the data from the closest [`SliderTheme`] instance that encloses
95    /// the given context.
96    ///
97    /// Defaults to the ambient `ThemeData::slider_theme` if there is no
98    /// [`SliderTheme`] in the given build context.
99    ///
100    /// ```text
101    /// SliderTheme::new(
102    ///     SliderTheme::of(app, context).copy_with().active_track_color(Color::new(0xff804040)),
103    ///     Slider::new(rocket_thrust, Some(on_changed)),
104    /// )
105    /// ```
106    ///
107    /// See also:
108    ///
109    ///  * [`SliderThemeData`], which describes the actual configuration of a slider
110    ///    theme.
111    pub fn of(app: &mut App, context: BuildContext) -> SliderThemeData {
112        match context.depend_on_inherited_widget_of_exact_type::<SliderTheme>(app) {
113            Some(inherited_theme) => inherited_theme.data.clone(),
114            None => Theme::of(app, context).slider_theme.clone(),
115        }
116    }
117}
118
119impl InheritedTheme for SliderTheme {
120    fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
121        SliderTheme::new(self.data.clone(), child).into_widget()
122    }
123}
124
125impl InheritedWidget for SliderTheme {
126    fn key(&self) -> Option<&KeyRef> {
127        self.key.as_ref()
128    }
129
130    fn child(&self) -> &WidgetRef {
131        &self.child
132    }
133
134    fn update_should_notify(&self, old_widget: &SliderTheme) -> bool {
135        self.data != old_widget.data
136    }
137
138    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
139        Some(self)
140    }
141}
142
143/// Describes the conditions under which the value indicator on a `Slider`
144/// will be shown. Used in `Slider::show_value_indicator` and
145/// [`SliderThemeData::show_value_indicator`].
146///
147/// See also:
148///
149///  * `Slider`, a Material Design slider widget.
150///  * [`SliderThemeData`], which describes the actual configuration of a slider
151///    theme.
152#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
153pub enum ShowValueIndicator {
154    /// The value indicator will only be shown while dragging for discrete sliders (sliders
155    /// where `Slider::divisions` is non-null).
156    OnlyForDiscrete,
157
158    /// The value indicator will only be shown while dragging for continuous sliders (sliders
159    /// where `Slider::divisions` is null).
160    OnlyForContinuous,
161
162    /// The value indicator is shown while dragging.
163    #[deprecated(note = "Use ShowValueIndicator::OnDrag. \
164                This feature was deprecated after v3.28.0-1.0.pre.")]
165    Always,
166
167    /// The value indicator is shown while dragging.
168    OnDrag,
169
170    /// The value indicator is always displayed as long as the slider has a
171    /// `Slider::on_changed` callback.
172    AlwaysVisible,
173
174    /// The value indicator will never be shown.
175    Never,
176}
177
178/// Identifier for a thumb.
179///
180/// There are 2 thumbs in a `RangeSlider`, [`start`](Thumb::Start) and [`end`](Thumb::End).
181///
182/// For `TextDirection::Ltr`, the [`start`](Thumb::Start) thumb is the left-most thumb and the
183/// [`end`](Thumb::End) thumb is the right-most thumb. For `TextDirection::Rtl` the
184/// [`start`](Thumb::Start) thumb is the right-most thumb, and the [`end`](Thumb::End) thumb is
185/// the left-most thumb.
186#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
187pub enum Thumb {
188    /// Left-most thumb for `TextDirection::Ltr`, otherwise, right-most thumb.
189    Start,
190
191    /// Right-most thumb for `TextDirection::Ltr`, otherwise, left-most thumb.
192    End,
193}
194
195/// Overrides the default values of visual properties for descendant
196/// `Slider` widgets.
197///
198/// Descendant widgets obtain the current [`SliderThemeData`] object with
199/// [`SliderTheme::of`]. Instances of [`SliderThemeData`] can
200/// be customized with [`SliderThemeData::copy_with`].
201///
202/// Typically a [`SliderThemeData`] is specified as part of the overall
203/// `Theme` with `ThemeData::slider_theme`.
204///
205/// This theme is for both the `Slider` and the `RangeSlider`. The properties
206/// that are only for the `Slider` are: [`tick_mark_shape`](Self::tick_mark_shape),
207/// [`thumb_shape`](Self::thumb_shape), [`track_shape`](Self::track_shape), and
208/// [`value_indicator_shape`](Self::value_indicator_shape). The properties that are only for
209/// the `RangeSlider` are [`range_tick_mark_shape`](Self::range_tick_mark_shape),
210/// [`range_thumb_shape`](Self::range_thumb_shape), [`range_track_shape`](Self::range_track_shape),
211/// [`range_value_indicator_shape`](Self::range_value_indicator_shape),
212/// [`overlapping_shape_stroke_color`](Self::overlapping_shape_stroke_color),
213/// [`min_thumb_separation`](Self::min_thumb_separation), and
214/// [`thumb_selector`](Self::thumb_selector).
215/// All other properties are used by both the `Slider` and the `RangeSlider`.
216///
217/// The parts of a slider are:
218///
219///  * The "thumb", which is a shape that slides horizontally when the user
220///    drags it.
221///  * The "track", which is the line that the slider thumb slides along.
222///  * The "tick marks", which are regularly spaced marks that are drawn when
223///    using discrete divisions.
224///  * The "value indicator", which appears when the user is dragging the thumb
225///    to indicate the value being selected.
226///  * The "overlay", which appears around the thumb, and is shown when the
227///    thumb is pressed, focused, or hovered. It is painted underneath the
228///    thumb, so it must extend beyond the bounds of the thumb itself to
229///    actually be visible.
230///  * The "active" side of the slider is the side between the thumb and the
231///    minimum value.
232///  * The "inactive" side of the slider is the side between the thumb and the
233///    maximum value.
234///  * The `Slider` is disabled when it is not accepting user input. See
235///    `Slider` for details on when this happens.
236///
237/// The thumb, track, tick marks, value indicator, and overlay can be customized
238/// by creating subclasses of `SliderTrackShape`,
239/// `SliderComponentShape`, and/or `SliderTickMarkShape`. See
240/// `RoundSliderThumbShape`, `RectangularSliderTrackShape`,
241/// `RoundSliderTickMarkShape`, `RectangularSliderValueIndicatorShape`, and
242/// `RoundSliderOverlayShape` for examples.
243///
244/// The track painting can be skipped by specifying 0 for [`track_height`](Self::track_height).
245/// The thumb painting can be skipped by specifying
246/// `SliderComponentShape::no_thumb` for [`thumb_shape`](Self::thumb_shape).
247/// The overlay painting can be skipped by specifying
248/// `SliderComponentShape::no_overlay` for [`overlay_shape`](Self::overlay_shape).
249/// The tick mark painting can be skipped by specifying
250/// `SliderTickMarkShape::no_tick_mark` for [`tick_mark_shape`](Self::tick_mark_shape).
251/// The value indicator painting can be skipped by specifying the
252/// appropriate [`ShowValueIndicator`] for [`show_value_indicator`](Self::show_value_indicator).
253///
254/// [`overlay_color`](Self::overlay_color) is an [`AnyColor`]: the slider resolves it by state
255/// when it is a `WidgetStateColor`, as Dart's `WidgetStateProperty.resolveAs` does.
256///
257/// See also:
258///
259///  * [`SliderTheme`] widget, which can override the slider theme of its
260///    children.
261///  * `Theme` widget, which performs a similar function to [`SliderTheme`],
262///    but for overall themes.
263///  * `ThemeData`, which has a default [`SliderThemeData`].
264#[derive(Clone, Default)]
265pub struct SliderThemeData {
266    /// The height of the `Slider` track.
267    pub track_height: Option<f64>,
268
269    /// The color of the `Slider` track between the `Slider::min` position and the
270    /// current thumb position.
271    pub active_track_color: Option<Color>,
272
273    /// The color of the `Slider` track between the current thumb position and the
274    /// `Slider::max` position.
275    pub inactive_track_color: Option<Color>,
276
277    /// The color of the `Slider` track between the current thumb position and the
278    /// `Slider::secondary_track_value` position.
279    pub secondary_active_track_color: Option<Color>,
280
281    /// The color of the `Slider` track between the `Slider::min` position and the
282    /// current thumb position when the `Slider` is disabled.
283    pub disabled_active_track_color: Option<Color>,
284
285    /// The color of the `Slider` track between the current thumb position and the
286    /// `Slider::secondary_track_value` position when the `Slider` is disabled.
287    pub disabled_secondary_active_track_color: Option<Color>,
288
289    /// The color of the `Slider` track between the current thumb position and the
290    /// `Slider::max` position when the `Slider` is disabled.
291    pub disabled_inactive_track_color: Option<Color>,
292
293    /// The color of the track's tick marks that are drawn between the `Slider::min`
294    /// position and the current thumb position.
295    pub active_tick_mark_color: Option<Color>,
296
297    /// The color of the track's tick marks that are drawn between the current
298    /// thumb position and the `Slider::max` position.
299    pub inactive_tick_mark_color: Option<Color>,
300
301    /// The color of the track's tick marks that are drawn between the `Slider::min`
302    /// position and the current thumb position when the `Slider` is disabled.
303    pub disabled_active_tick_mark_color: Option<Color>,
304
305    /// The color of the track's tick marks that are drawn between the current
306    /// thumb position and the `Slider::max` position when the `Slider` is
307    /// disabled.
308    pub disabled_inactive_tick_mark_color: Option<Color>,
309
310    /// The color given to the [`thumb_shape`](Self::thumb_shape) to draw itself with.
311    pub thumb_color: Option<Color>,
312
313    /// The color given to the perimeter of the top [`range_thumb_shape`](Self::range_thumb_shape)
314    /// when the thumbs are overlapping and the top
315    /// [`range_value_indicator_shape`](Self::range_value_indicator_shape) when the value
316    /// indicators are overlapping.
317    pub overlapping_shape_stroke_color: Option<Color>,
318
319    /// The color given to the [`thumb_shape`](Self::thumb_shape) to draw itself with when the
320    /// `Slider` is disabled.
321    pub disabled_thumb_color: Option<Color>,
322
323    /// The color of the overlay drawn around the slider thumb when it is
324    /// pressed, focused, or hovered.
325    ///
326    /// This is typically a semi-transparent color.
327    pub overlay_color: Option<AnyColor>,
328
329    /// The color given to the [`value_indicator_shape`](Self::value_indicator_shape) to draw
330    /// itself with.
331    pub value_indicator_color: Option<Color>,
332
333    /// The color given to the [`value_indicator_shape`](Self::value_indicator_shape) stroke.
334    pub value_indicator_stroke_color: Option<Color>,
335
336    /// The shape that will be used to draw the `Slider`'s overlay.
337    ///
338    /// Both the [`overlay_color`](Self::overlay_color) and a non default
339    /// [`overlay_shape`](Self::overlay_shape) may be specified. The default
340    /// [`overlay_shape`](Self::overlay_shape) refers to the [`overlay_color`](Self::overlay_color).
341    ///
342    /// The default value is `RoundSliderOverlayShape`.
343    pub overlay_shape: Option<SliderComponentShapeRef>,
344
345    /// The shape that will be used to draw the `Slider`'s tick marks.
346    ///
347    /// The `SliderTickMarkShape::get_preferred_size` is used to help determine the
348    /// location of each tick mark on the track. The slider's minimum size will
349    /// be at least this big.
350    ///
351    /// The default value is `RoundSliderTickMarkShape`.
352    ///
353    /// See also:
354    ///
355    ///  * `RoundRangeSliderTickMarkShape`, which is the default tick mark
356    ///    shape for the range slider.
357    pub tick_mark_shape: Option<SliderTickMarkShapeRef>,
358
359    /// The shape that will be used to draw the `Slider`'s thumb.
360    ///
361    /// The default value is `RoundSliderThumbShape`.
362    ///
363    /// See also:
364    ///
365    ///  * `RoundRangeSliderThumbShape`, which is the default thumb shape for
366    ///    the `RangeSlider`.
367    pub thumb_shape: Option<SliderComponentShapeRef>,
368
369    /// The shape that will be used to draw the `Slider`'s track.
370    ///
371    /// The `SliderTrackShape::get_preferred_rect` method is used to map
372    /// slider-relative gesture coordinates to the correct thumb position on the
373    /// track. It is also used to horizontally position tick marks, when the
374    /// slider is discrete.
375    ///
376    /// The default value is `RoundedRectSliderTrackShape`.
377    ///
378    /// See also:
379    ///
380    ///  * `RoundedRectRangeSliderTrackShape`, which is the default track
381    ///    shape for the `RangeSlider`.
382    pub track_shape: Option<SliderTrackShapeRef>,
383
384    /// The shape that will be used to draw the `Slider`'s value
385    /// indicator.
386    ///
387    /// The default value is `PaddleSliderValueIndicatorShape`.
388    ///
389    /// See also:
390    ///
391    ///  * `PaddleRangeSliderValueIndicatorShape`, which is the default value
392    ///    indicator shape for the `RangeSlider`.
393    pub value_indicator_shape: Option<SliderComponentShapeRef>,
394
395    /// The shape that will be used to draw the `RangeSlider`'s tick marks.
396    ///
397    /// The `RangeSliderTickMarkShape::get_preferred_size` is used to help determine
398    /// the location of each tick mark on the track. The slider's minimum size
399    /// will be at least this big.
400    ///
401    /// The default value is `RoundRangeSliderTickMarkShape`.
402    ///
403    /// See also:
404    ///
405    ///  * `RoundSliderTickMarkShape`, which is the default tick mark shape
406    ///    for the `Slider`.
407    pub range_tick_mark_shape: Option<RangeSliderTickMarkShapeRef>,
408
409    /// The shape that will be used for the `RangeSlider`'s thumbs.
410    ///
411    /// By default the same shape is used for both thumbs, but strokes the top
412    /// thumb when it overlaps the bottom thumb. The top thumb is always the last
413    /// selected thumb.
414    ///
415    /// The default value is `RoundRangeSliderThumbShape`.
416    ///
417    /// See also:
418    ///
419    ///  * `RoundSliderThumbShape`, which is the default thumb shape for the
420    ///    `Slider`.
421    pub range_thumb_shape: Option<RangeSliderThumbShapeRef>,
422
423    /// The shape that will be used to draw the `RangeSlider`'s track.
424    ///
425    /// The `SliderTrackShape::get_preferred_rect` method is used to map
426    /// slider-relative gesture coordinates to the correct thumb position on the
427    /// track. It is also used to horizontally position the tick marks, when the
428    /// slider is discrete.
429    ///
430    /// The default value is `RoundedRectRangeSliderTrackShape`.
431    ///
432    /// See also:
433    ///
434    ///  * `RoundedRectSliderTrackShape`, which is the default track
435    ///    shape for the `Slider`.
436    pub range_track_shape: Option<RangeSliderTrackShapeRef>,
437
438    /// The shape that will be used for the `RangeSlider`'s value indicators.
439    ///
440    /// The default shape uses the same value indicator for each thumb, but
441    /// strokes the top value indicator when it overlaps the bottom value
442    /// indicator. The top indicator corresponds to the top thumb, which is always
443    /// the most recently selected thumb.
444    ///
445    /// The default value is `PaddleRangeSliderValueIndicatorShape`.
446    ///
447    /// See also:
448    ///
449    ///  * `PaddleSliderValueIndicatorShape`, which is the default value
450    ///    indicator shape for the `Slider`.
451    pub range_value_indicator_shape: Option<RangeSliderValueIndicatorShapeRef>,
452
453    /// Whether the value indicator should be shown for different types of
454    /// sliders.
455    ///
456    /// By default, [`show_value_indicator`](Self::show_value_indicator) is set to
457    /// [`ShowValueIndicator::OnlyForDiscrete`]. The value indicator is only shown
458    /// when the thumb is being touched.
459    pub show_value_indicator: Option<ShowValueIndicator>,
460
461    /// The text style for the text on the value indicator.
462    pub value_indicator_text_style: Option<TextStyle>,
463
464    /// Limits the thumb's separation distance.
465    ///
466    /// Use this only if you want to control the visual appearance of the thumbs
467    /// in terms of a logical pixel value. This can be done when you want a
468    /// specific look for thumbs when they are close together. To limit with the
469    /// real values, rather than logical pixels, the values can be restricted by
470    /// the parent.
471    pub min_thumb_separation: Option<f64>,
472
473    /// Determines which thumb should be selected when the slider is interacted
474    /// with.
475    ///
476    /// If null, the default thumb selector finds the closest thumb, excluding
477    /// taps that are between the thumbs and not within any one touch target.
478    /// When the selection is within the touch target bounds of both thumbs, no
479    /// thumb is selected until the selection is moved.
480    ///
481    /// Override this for custom thumb selection.
482    pub thumb_selector: Option<RangeThumbSelector>,
483
484    /// The cursor for a mouse pointer when it enters or is hovering over the
485    /// widget.
486    ///
487    /// If specified, overrides the default value of `Slider::mouse_cursor`.
488    pub mouse_cursor: Option<WidgetStatePropertyRef<Option<MouseCursorRef>>>,
489
490    /// Allowed way for the user to interact with the `Slider`.
491    ///
492    /// If specified, overrides the default value of `Slider::allowed_interaction`.
493    pub allowed_interaction: Option<SliderInteraction>,
494
495    /// Determines the padding around the `Slider`.
496    ///
497    /// If specified, this padding overrides the default vertical padding of
498    /// the `Slider`, defaults to the height of the overlay shape, and the
499    /// horizontal padding, defaults to the width of the thumb shape or
500    /// overlay shape, whichever is larger.
501    pub padding: Option<EdgeInsetsGeometry>,
502
503    /// The size of the `HandleThumbShape` thumb.
504    ///
505    /// If [`thumb_shape`](Self::thumb_shape) is `HandleThumbShape`, this property is used to
506    /// set the size of the thumb. Otherwise, the default thumb size is 4 pixels for the
507    /// width and 44 pixels for the height.
508    pub thumb_size: Option<WidgetStatePropertyRef<Option<Size>>>,
509
510    /// The size of the gap between the active and inactive tracks of the
511    /// `GappedSliderTrackShape`.
512    ///
513    /// If [`track_shape`](Self::track_shape) is `GappedSliderTrackShape`, this property
514    /// is used to set the gap between the active and inactive tracks. Otherwise,
515    /// the default gap size is 6.0 pixels.
516    ///
517    /// The Slider defaults to `GappedSliderTrackShape` when the track shape is
518    /// not specified, and the [`track_gap`](Self::track_gap) can be used to adjust the gap
519    /// size.
520    ///
521    /// If `Slider::year2023` is true or `ThemeData::use_material3` is false, then
522    /// the Slider track shape defaults to `RoundedRectSliderTrackShape` and the
523    /// [`track_gap`](Self::track_gap) is ignored. In this case, set the track shape to
524    /// `GappedSliderTrackShape` to use the [`track_gap`](Self::track_gap).
525    ///
526    /// Defaults to 6.0 pixels of gap between the active and inactive tracks.
527    pub track_gap: Option<f64>,
528
529    /// Overrides the default value of `Slider::year2023` and `RangeSlider::year2023`.
530    ///
531    /// When true, the `Slider` and `RangeSlider` will use the 2023 Material Design 3
532    /// appearance. Defaults to true.
533    ///
534    /// If this is set to false, the `Slider` and `RangeSlider` will use the latest Material
535    /// Design 3 appearance, which was introduced in December 2023.
536    ///
537    /// If `ThemeData::use_material3` is false, then this property is ignored.
538    ///
539    /// Deprecated in Flutter after v3.27.0-0.2.pre: set this flag to false to opt into the
540    /// 2024 slider appearance. Its setter carries the deprecation.
541    pub year2023: Option<bool>,
542}
543
544crate::theme_data_getters::theme_data_getters! {
545    /// Dart's getters of `SliderThemeData`: the theme data answers with its fields, and a defaults
546    /// subclass (Dart's `_...Defaults...(context)`) computes the ones it overrides when they
547    /// are read.
548    pub trait SliderThemeDataGetters for SliderThemeData, fields: slider_theme_data {
549        track_height: Option<f64>,
550        active_track_color: Option<Color>,
551        inactive_track_color: Option<Color>,
552        secondary_active_track_color: Option<Color>,
553        disabled_active_track_color: Option<Color>,
554        disabled_secondary_active_track_color: Option<Color>,
555        disabled_inactive_track_color: Option<Color>,
556        active_tick_mark_color: Option<Color>,
557        inactive_tick_mark_color: Option<Color>,
558        disabled_active_tick_mark_color: Option<Color>,
559        disabled_inactive_tick_mark_color: Option<Color>,
560        thumb_color: Option<Color>,
561        overlapping_shape_stroke_color: Option<Color>,
562        disabled_thumb_color: Option<Color>,
563        overlay_color: Option<AnyColor>,
564        value_indicator_color: Option<Color>,
565        value_indicator_stroke_color: Option<Color>,
566        overlay_shape: Option<SliderComponentShapeRef>,
567        tick_mark_shape: Option<SliderTickMarkShapeRef>,
568        thumb_shape: Option<SliderComponentShapeRef>,
569        track_shape: Option<SliderTrackShapeRef>,
570        value_indicator_shape: Option<SliderComponentShapeRef>,
571        range_tick_mark_shape: Option<RangeSliderTickMarkShapeRef>,
572        range_thumb_shape: Option<RangeSliderThumbShapeRef>,
573        range_track_shape: Option<RangeSliderTrackShapeRef>,
574        range_value_indicator_shape: Option<RangeSliderValueIndicatorShapeRef>,
575        show_value_indicator: Option<ShowValueIndicator>,
576        value_indicator_text_style: Option<TextStyle>,
577        min_thumb_separation: Option<f64>,
578        thumb_selector: Option<RangeThumbSelector>,
579        mouse_cursor: Option<WidgetStatePropertyRef<Option<MouseCursorRef>>>,
580        allowed_interaction: Option<SliderInteraction>,
581        padding: Option<EdgeInsetsGeometry>,
582        thumb_size: Option<WidgetStatePropertyRef<Option<Size>>>,
583        track_gap: Option<f64>,
584        year2023: Option<bool>,
585    }
586}
587
588macro_rules! slider_theme_setters {
589    ($($field:ident: $ty:ty => $dart:literal),* $(,)?) => {
590        $(
591            #[doc = concat!("Dart `SliderThemeData(", $dart, ":)`.")]
592            pub fn $field(mut self, $field: $ty) -> SliderThemeData {
593                self.$field = Some($field);
594                self
595            }
596        )*
597    };
598}
599
600impl SliderThemeData {
601    /// Create a [`SliderThemeData`] given a set of exact values.
602    ///
603    /// This will rarely be used directly. It is used by [`lerp`](Self::lerp) to
604    /// create intermediate themes based on two themes.
605    ///
606    /// The simplest way to create a SliderThemeData is to use
607    /// [`copy_with`](Self::copy_with) on the one you get from [`SliderTheme::of`], or create an
608    /// entirely new one with [`SliderThemeData::from_primary_colors`].
609    pub fn new() -> SliderThemeData {
610        SliderThemeData::default()
611    }
612
613    /// Generates a SliderThemeData from three main colors.
614    ///
615    /// Usually these are the primary, dark and light colors from
616    /// a `ThemeData`.
617    ///
618    /// The opacities of these colors will be overridden with the Material Design
619    /// defaults when assigning them to the slider theme component colors.
620    ///
621    /// This is used to generate the default slider theme for a `ThemeData`.
622    pub fn from_primary_colors(
623        primary_color: Color,
624        primary_color_dark: Color,
625        primary_color_light: Color,
626        value_indicator_text_style: TextStyle,
627    ) -> SliderThemeData {
628        // These are Material Design defaults, and are used to derive
629        // component Colors (with opacity) from base colors.
630        const ACTIVE_TRACK_ALPHA: i32 = 0xff;
631        const INACTIVE_TRACK_ALPHA: i32 = 0x3d; // 24% opacity
632        const SECONDARY_ACTIVE_TRACK_ALPHA: i32 = 0x8a; // 54% opacity
633        const DISABLED_ACTIVE_TRACK_ALPHA: i32 = 0x52; // 32% opacity
634        const DISABLED_INACTIVE_TRACK_ALPHA: i32 = 0x1f; // 12% opacity
635        const DISABLED_SECONDARY_ACTIVE_TRACK_ALPHA: i32 = 0x1f; // 12% opacity
636        const ACTIVE_TICK_MARK_ALPHA: i32 = 0x8a; // 54% opacity
637        const INACTIVE_TICK_MARK_ALPHA: i32 = 0x8a; // 54% opacity
638        const DISABLED_ACTIVE_TICK_MARK_ALPHA: i32 = 0x1f; // 12% opacity
639        const DISABLED_INACTIVE_TICK_MARK_ALPHA: i32 = 0x1f; // 12% opacity
640        const THUMB_ALPHA: i32 = 0xff;
641        const DISABLED_THUMB_ALPHA: i32 = 0x52; // 32% opacity
642        const OVERLAY_ALPHA: i32 = 0x1f; // 12% opacity
643        const VALUE_INDICATOR_ALPHA: i32 = 0xff;
644
645        SliderThemeData::new()
646            .track_height(2.0)
647            .active_track_color(primary_color.with_alpha(ACTIVE_TRACK_ALPHA))
648            .inactive_track_color(primary_color.with_alpha(INACTIVE_TRACK_ALPHA))
649            .secondary_active_track_color(primary_color.with_alpha(SECONDARY_ACTIVE_TRACK_ALPHA))
650            .disabled_active_track_color(primary_color_dark.with_alpha(DISABLED_ACTIVE_TRACK_ALPHA))
651            .disabled_inactive_track_color(
652                primary_color_dark.with_alpha(DISABLED_INACTIVE_TRACK_ALPHA),
653            )
654            .disabled_secondary_active_track_color(
655                primary_color_dark.with_alpha(DISABLED_SECONDARY_ACTIVE_TRACK_ALPHA),
656            )
657            .active_tick_mark_color(primary_color_light.with_alpha(ACTIVE_TICK_MARK_ALPHA))
658            .inactive_tick_mark_color(primary_color.with_alpha(INACTIVE_TICK_MARK_ALPHA))
659            .disabled_active_tick_mark_color(
660                primary_color_light.with_alpha(DISABLED_ACTIVE_TICK_MARK_ALPHA),
661            )
662            .disabled_inactive_tick_mark_color(
663                primary_color_dark.with_alpha(DISABLED_INACTIVE_TICK_MARK_ALPHA),
664            )
665            .thumb_color(primary_color.with_alpha(THUMB_ALPHA))
666            .overlapping_shape_stroke_color(Colors::WHITE)
667            .disabled_thumb_color(primary_color_dark.with_alpha(DISABLED_THUMB_ALPHA))
668            .overlay_color(primary_color.with_alpha(OVERLAY_ALPHA))
669            .value_indicator_color(primary_color.with_alpha(VALUE_INDICATOR_ALPHA))
670            .value_indicator_stroke_color(primary_color.with_alpha(VALUE_INDICATOR_ALPHA))
671            .overlay_shape(Rc::new(RoundSliderOverlayShape::new()))
672            .tick_mark_shape(Rc::new(RoundSliderTickMarkShape::new()))
673            .thumb_shape(Rc::new(RoundSliderThumbShape::new()))
674            .track_shape(Rc::new(RoundedRectSliderTrackShape::new()))
675            .value_indicator_shape(Rc::new(PaddleSliderValueIndicatorShape::new()))
676            .range_tick_mark_shape(Rc::new(RoundRangeSliderTickMarkShape::new()))
677            .range_thumb_shape(Rc::new(RoundRangeSliderThumbShape::new()))
678            .range_track_shape(Rc::new(RoundedRectRangeSliderTrackShape::new()))
679            .range_value_indicator_shape(Rc::new(PaddleRangeSliderValueIndicatorShape::new()))
680            .value_indicator_text_style(value_indicator_text_style)
681            .show_value_indicator(ShowValueIndicator::OnlyForDiscrete)
682    }
683
684    slider_theme_setters!(
685        track_height: f64 => "trackHeight",
686        active_track_color: Color => "activeTrackColor",
687        inactive_track_color: Color => "inactiveTrackColor",
688        secondary_active_track_color: Color => "secondaryActiveTrackColor",
689        disabled_active_track_color: Color => "disabledActiveTrackColor",
690        disabled_inactive_track_color: Color => "disabledInactiveTrackColor",
691        disabled_secondary_active_track_color: Color => "disabledSecondaryActiveTrackColor",
692        active_tick_mark_color: Color => "activeTickMarkColor",
693        inactive_tick_mark_color: Color => "inactiveTickMarkColor",
694        disabled_active_tick_mark_color: Color => "disabledActiveTickMarkColor",
695        disabled_inactive_tick_mark_color: Color => "disabledInactiveTickMarkColor",
696        thumb_color: Color => "thumbColor",
697        overlapping_shape_stroke_color: Color => "overlappingShapeStrokeColor",
698        disabled_thumb_color: Color => "disabledThumbColor",
699    );
700
701    /// Dart `SliderThemeData(overlayColor:)`.
702    pub fn overlay_color(mut self, overlay_color: impl Into<AnyColor>) -> SliderThemeData {
703        self.overlay_color = Some(overlay_color.into());
704        self
705    }
706
707    slider_theme_setters!(
708        value_indicator_color: Color => "valueIndicatorColor",
709        value_indicator_stroke_color: Color => "valueIndicatorStrokeColor",
710        overlay_shape: SliderComponentShapeRef => "overlayShape",
711        tick_mark_shape: SliderTickMarkShapeRef => "tickMarkShape",
712        thumb_shape: SliderComponentShapeRef => "thumbShape",
713        track_shape: SliderTrackShapeRef => "trackShape",
714        value_indicator_shape: SliderComponentShapeRef => "valueIndicatorShape",
715        range_tick_mark_shape: RangeSliderTickMarkShapeRef => "rangeTickMarkShape",
716        range_thumb_shape: RangeSliderThumbShapeRef => "rangeThumbShape",
717        range_track_shape: RangeSliderTrackShapeRef => "rangeTrackShape",
718        range_value_indicator_shape: RangeSliderValueIndicatorShapeRef => "rangeValueIndicatorShape",
719        show_value_indicator: ShowValueIndicator => "showValueIndicator",
720        value_indicator_text_style: TextStyle => "valueIndicatorTextStyle",
721        min_thumb_separation: f64 => "minThumbSeparation",
722        thumb_selector: RangeThumbSelector => "thumbSelector",
723        mouse_cursor: WidgetStatePropertyRef<Option<MouseCursorRef>> => "mouseCursor",
724        allowed_interaction: SliderInteraction => "allowedInteraction",
725        thumb_size: WidgetStatePropertyRef<Option<Size>> => "thumbSize",
726        track_gap: f64 => "trackGap",
727    );
728
729    /// Dart `SliderThemeData(padding:)`.
730    pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> SliderThemeData {
731        self.padding = Some(padding.into());
732        self
733    }
734
735    /// Dart `SliderThemeData(year2023:)`.
736    #[deprecated(
737        note = "Set this flag to false to opt into the 2024 slider appearance. \
738                Defaults to true. In the future, this flag will default to false. Use \
739                SliderThemeData to customize individual properties. This feature was \
740                deprecated after v3.27.0-0.2.pre."
741    )]
742    pub fn year2023(mut self, year2023: bool) -> SliderThemeData {
743        self.year2023 = Some(year2023);
744        self
745    }
746
747    /// Creates a copy of this object but with the given fields replaced with the
748    /// new values.
749    ///
750    /// Dart's named arguments are the fluent setters on the copy
751    /// (`data.copy_with().track_height(4.0)`).
752    pub fn copy_with(&self) -> SliderThemeData {
753        self.clone()
754    }
755
756    /// Linearly interpolate between two slider themes.
757    ///
758    /// {@macro dart.ui.shadow.lerp}
759    pub fn lerp(a: &SliderThemeData, b: &SliderThemeData, t: f64) -> SliderThemeData {
760        if std::ptr::eq(a, b) {
761            return a.clone();
762        }
763        fn pick<T: Clone>(a: &Option<T>, b: &Option<T>, t: f64) -> Option<T> {
764            if t < 0.5 { a.clone() } else { b.clone() }
765        }
766        SliderThemeData {
767            track_height: lerp_double(a.track_height, b.track_height, t),
768            active_track_color: Color::lerp(a.active_track_color, b.active_track_color, t),
769            inactive_track_color: Color::lerp(a.inactive_track_color, b.inactive_track_color, t),
770            secondary_active_track_color: Color::lerp(
771                a.secondary_active_track_color,
772                b.secondary_active_track_color,
773                t,
774            ),
775            disabled_active_track_color: Color::lerp(
776                a.disabled_active_track_color,
777                b.disabled_active_track_color,
778                t,
779            ),
780            disabled_inactive_track_color: Color::lerp(
781                a.disabled_inactive_track_color,
782                b.disabled_inactive_track_color,
783                t,
784            ),
785            disabled_secondary_active_track_color: Color::lerp(
786                a.disabled_secondary_active_track_color,
787                b.disabled_secondary_active_track_color,
788                t,
789            ),
790            active_tick_mark_color: Color::lerp(
791                a.active_tick_mark_color,
792                b.active_tick_mark_color,
793                t,
794            ),
795            inactive_tick_mark_color: Color::lerp(
796                a.inactive_tick_mark_color,
797                b.inactive_tick_mark_color,
798                t,
799            ),
800            disabled_active_tick_mark_color: Color::lerp(
801                a.disabled_active_tick_mark_color,
802                b.disabled_active_tick_mark_color,
803                t,
804            ),
805            disabled_inactive_tick_mark_color: Color::lerp(
806                a.disabled_inactive_tick_mark_color,
807                b.disabled_inactive_tick_mark_color,
808                t,
809            ),
810            thumb_color: Color::lerp(a.thumb_color, b.thumb_color, t),
811            overlapping_shape_stroke_color: Color::lerp(
812                a.overlapping_shape_stroke_color,
813                b.overlapping_shape_stroke_color,
814                t,
815            ),
816            disabled_thumb_color: Color::lerp(a.disabled_thumb_color, b.disabled_thumb_color, t),
817            overlay_color: AnyColor::lerp(a.overlay_color.as_ref(), b.overlay_color.as_ref(), t)
818                .map(AnyColor::new),
819            value_indicator_color: Color::lerp(a.value_indicator_color, b.value_indicator_color, t),
820            value_indicator_stroke_color: Color::lerp(
821                a.value_indicator_stroke_color,
822                b.value_indicator_stroke_color,
823                t,
824            ),
825            overlay_shape: pick(&a.overlay_shape, &b.overlay_shape, t),
826            tick_mark_shape: pick(&a.tick_mark_shape, &b.tick_mark_shape, t),
827            thumb_shape: pick(&a.thumb_shape, &b.thumb_shape, t),
828            track_shape: pick(&a.track_shape, &b.track_shape, t),
829            value_indicator_shape: pick(&a.value_indicator_shape, &b.value_indicator_shape, t),
830            range_tick_mark_shape: pick(&a.range_tick_mark_shape, &b.range_tick_mark_shape, t),
831            range_thumb_shape: pick(&a.range_thumb_shape, &b.range_thumb_shape, t),
832            range_track_shape: pick(&a.range_track_shape, &b.range_track_shape, t),
833            range_value_indicator_shape: pick(
834                &a.range_value_indicator_shape,
835                &b.range_value_indicator_shape,
836                t,
837            ),
838            show_value_indicator: pick(&a.show_value_indicator, &b.show_value_indicator, t),
839            value_indicator_text_style: TextStyle::lerp(
840                a.value_indicator_text_style.as_ref(),
841                b.value_indicator_text_style.as_ref(),
842                t,
843            ),
844            min_thumb_separation: lerp_double(a.min_thumb_separation, b.min_thumb_separation, t),
845            thumb_selector: pick(&a.thumb_selector, &b.thumb_selector, t),
846            mouse_cursor: pick(&a.mouse_cursor, &b.mouse_cursor, t),
847            allowed_interaction: pick(&a.allowed_interaction, &b.allowed_interaction, t),
848            padding: EdgeInsetsGeometry::lerp(a.padding, b.padding, t),
849            thumb_size: <dyn WidgetStateProperty<Option<Size>>>::lerp_optional(
850                a.thumb_size.clone(),
851                b.thumb_size.clone(),
852                t,
853                Size::lerp,
854            ),
855            track_gap: lerp_double(a.track_gap, b.track_gap, t),
856            year2023: pick(&a.year2023, &b.year2023, t),
857        }
858    }
859}
860
861/// Dart's `==` on a `RangeThumbSelector`: a closure, equal only to itself.
862fn same_thumb_selector(a: &Option<RangeThumbSelector>, b: &Option<RangeThumbSelector>) -> bool {
863    match (a, b) {
864        (None, None) => true,
865        (Some(a), Some(b)) => Rc::ptr_eq(a, b),
866        _ => false,
867    }
868}
869
870impl PartialEq for SliderThemeData {
871    fn eq(&self, other: &SliderThemeData) -> bool {
872        if std::ptr::eq(self, other) {
873            return true;
874        }
875        other.track_height == self.track_height
876            && other.active_track_color == self.active_track_color
877            && other.inactive_track_color == self.inactive_track_color
878            && other.secondary_active_track_color == self.secondary_active_track_color
879            && other.disabled_active_track_color == self.disabled_active_track_color
880            && other.disabled_inactive_track_color == self.disabled_inactive_track_color
881            && other.disabled_secondary_active_track_color
882                == self.disabled_secondary_active_track_color
883            && other.active_tick_mark_color == self.active_tick_mark_color
884            && other.inactive_tick_mark_color == self.inactive_tick_mark_color
885            && other.disabled_active_tick_mark_color == self.disabled_active_tick_mark_color
886            && other.disabled_inactive_tick_mark_color == self.disabled_inactive_tick_mark_color
887            && other.thumb_color == self.thumb_color
888            && other.overlapping_shape_stroke_color == self.overlapping_shape_stroke_color
889            && other.disabled_thumb_color == self.disabled_thumb_color
890            && other.overlay_color == self.overlay_color
891            && other.value_indicator_color == self.value_indicator_color
892            && other.value_indicator_stroke_color == self.value_indicator_stroke_color
893            && other.overlay_shape == self.overlay_shape
894            && other.tick_mark_shape == self.tick_mark_shape
895            && other.thumb_shape == self.thumb_shape
896            && other.track_shape == self.track_shape
897            && other.value_indicator_shape == self.value_indicator_shape
898            && other.range_tick_mark_shape == self.range_tick_mark_shape
899            && other.range_thumb_shape == self.range_thumb_shape
900            && other.range_track_shape == self.range_track_shape
901            && other.range_value_indicator_shape == self.range_value_indicator_shape
902            && other.show_value_indicator == self.show_value_indicator
903            && other.value_indicator_text_style == self.value_indicator_text_style
904            && other.min_thumb_separation == self.min_thumb_separation
905            && same_thumb_selector(&other.thumb_selector, &self.thumb_selector)
906            && other.mouse_cursor == self.mouse_cursor
907            && other.allowed_interaction == self.allowed_interaction
908            && other.padding == self.padding
909            && other.thumb_size == self.thumb_size
910            && other.track_gap == self.track_gap
911            && other.year2023 == self.year2023
912    }
913}
914
915impl Debug for SliderThemeData {
916    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
917        let mut properties = f.debug_struct("SliderThemeData");
918        macro_rules! property {
919            ($($field:ident),* $(,)?) => {
920                $(
921                    if let Some(value) = &self.$field {
922                        properties.field(stringify!($field), value);
923                    }
924                )*
925            };
926        }
927        property!(
928            track_height,
929            active_track_color,
930            inactive_track_color,
931            secondary_active_track_color,
932            disabled_active_track_color,
933            disabled_inactive_track_color,
934            disabled_secondary_active_track_color,
935            active_tick_mark_color,
936            inactive_tick_mark_color,
937            disabled_active_tick_mark_color,
938            disabled_inactive_tick_mark_color,
939            thumb_color,
940            overlapping_shape_stroke_color,
941            disabled_thumb_color,
942            overlay_color,
943            value_indicator_color,
944            value_indicator_stroke_color,
945            overlay_shape,
946            tick_mark_shape,
947            thumb_shape,
948            track_shape,
949            value_indicator_shape,
950            range_tick_mark_shape,
951            range_thumb_shape,
952            range_track_shape,
953            range_value_indicator_shape,
954            show_value_indicator,
955            value_indicator_text_style,
956            min_thumb_separation,
957        );
958        if self.thumb_selector.is_some() {
959            properties.field("thumb_selector", &"RangeThumbSelector");
960        }
961        property!(
962            mouse_cursor,
963            allowed_interaction,
964            padding,
965            thumb_size,
966            track_gap,
967            year2023
968        );
969        properties.finish()
970    }
971}
972
973/// A callback that formats a numeric value from a `Slider` or `RangeSlider` widget.
974///
975/// See also:
976///
977///  * `Slider::semantic_formatter_callback`, which shows an example use case.
978///  * `RangeSlider::semantic_formatter_callback`, which shows an example use case.
979pub type SemanticFormatterCallback = Rc<dyn Fn(f64) -> String>;
980
981impl waft_foundation::Diagnosticable for SliderThemeData {
982    fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
983        let default_theme = SliderThemeData::new();
984        properties.add(
985            DoubleProperty::new("trackHeight", self.track_height)
986                .default_value(default_theme.track_height),
987        );
988        properties.add(
989            ColorProperty::new("activeTrackColor", self.active_track_color)
990                .default_value(default_theme.active_track_color),
991        );
992        properties.add(
993            ColorProperty::new("inactiveTrackColor", self.inactive_track_color)
994                .default_value(default_theme.inactive_track_color),
995        );
996        properties.add(
997            ColorProperty::new(
998                "secondaryActiveTrackColor",
999                self.secondary_active_track_color,
1000            )
1001            .default_value(default_theme.secondary_active_track_color),
1002        );
1003        properties.add(
1004            ColorProperty::new("disabledActiveTrackColor", self.disabled_active_track_color)
1005                .default_value(default_theme.disabled_active_track_color),
1006        );
1007        properties.add(
1008            ColorProperty::new(
1009                "disabledInactiveTrackColor",
1010                self.disabled_inactive_track_color,
1011            )
1012            .default_value(default_theme.disabled_inactive_track_color),
1013        );
1014        properties.add(
1015            ColorProperty::new(
1016                "disabledSecondaryActiveTrackColor",
1017                self.disabled_secondary_active_track_color,
1018            )
1019            .default_value(default_theme.disabled_secondary_active_track_color),
1020        );
1021        properties.add(
1022            ColorProperty::new("activeTickMarkColor", self.active_tick_mark_color)
1023                .default_value(default_theme.active_tick_mark_color),
1024        );
1025        properties.add(
1026            ColorProperty::new("inactiveTickMarkColor", self.inactive_tick_mark_color)
1027                .default_value(default_theme.inactive_tick_mark_color),
1028        );
1029        properties.add(
1030            ColorProperty::new(
1031                "disabledActiveTickMarkColor",
1032                self.disabled_active_tick_mark_color,
1033            )
1034            .default_value(default_theme.disabled_active_tick_mark_color),
1035        );
1036        properties.add(
1037            ColorProperty::new(
1038                "disabledInactiveTickMarkColor",
1039                self.disabled_inactive_tick_mark_color,
1040            )
1041            .default_value(default_theme.disabled_inactive_tick_mark_color),
1042        );
1043        properties.add(
1044            ColorProperty::new("thumbColor", self.thumb_color)
1045                .default_value(default_theme.thumb_color),
1046        );
1047        properties.add(
1048            ColorProperty::new(
1049                "overlappingShapeStrokeColor",
1050                self.overlapping_shape_stroke_color,
1051            )
1052            .default_value(default_theme.overlapping_shape_stroke_color),
1053        );
1054        properties.add(
1055            ColorProperty::new("disabledThumbColor", self.disabled_thumb_color)
1056                .default_value(default_theme.disabled_thumb_color),
1057        );
1058        properties.add(
1059            DiagnosticsProperty::<AnyColor>::new("overlayColor", self.overlay_color.clone())
1060                .default_value(default_theme.overlay_color.clone()),
1061        );
1062        properties.add(
1063            ColorProperty::new("valueIndicatorColor", self.value_indicator_color)
1064                .default_value(default_theme.value_indicator_color),
1065        );
1066        properties.add(
1067            ColorProperty::new(
1068                "valueIndicatorStrokeColor",
1069                self.value_indicator_stroke_color,
1070            )
1071            .default_value(default_theme.value_indicator_stroke_color),
1072        );
1073        properties.add(
1074            DiagnosticsProperty::<waft_foundation::InstanceOf<SliderComponentShapeRef>>::new(
1075                "overlayShape",
1076                self.overlay_shape.clone().map(waft_foundation::InstanceOf),
1077            )
1078            .default_value(
1079                default_theme
1080                    .overlay_shape
1081                    .clone()
1082                    .map(waft_foundation::InstanceOf),
1083            ),
1084        );
1085        properties.add(
1086            DiagnosticsProperty::<waft_foundation::InstanceOf<SliderTickMarkShapeRef>>::new(
1087                "tickMarkShape",
1088                self.tick_mark_shape
1089                    .clone()
1090                    .map(waft_foundation::InstanceOf),
1091            )
1092            .default_value(
1093                default_theme
1094                    .tick_mark_shape
1095                    .clone()
1096                    .map(waft_foundation::InstanceOf),
1097            ),
1098        );
1099        properties.add(
1100            DiagnosticsProperty::<waft_foundation::InstanceOf<SliderComponentShapeRef>>::new(
1101                "thumbShape",
1102                self.thumb_shape.clone().map(waft_foundation::InstanceOf),
1103            )
1104            .default_value(
1105                default_theme
1106                    .thumb_shape
1107                    .clone()
1108                    .map(waft_foundation::InstanceOf),
1109            ),
1110        );
1111        properties.add(
1112            DiagnosticsProperty::<waft_foundation::InstanceOf<SliderTrackShapeRef>>::new(
1113                "trackShape",
1114                self.track_shape.clone().map(waft_foundation::InstanceOf),
1115            )
1116            .default_value(
1117                default_theme
1118                    .track_shape
1119                    .clone()
1120                    .map(waft_foundation::InstanceOf),
1121            ),
1122        );
1123        properties.add(
1124            DiagnosticsProperty::<waft_foundation::InstanceOf<SliderComponentShapeRef>>::new(
1125                "valueIndicatorShape",
1126                self.value_indicator_shape
1127                    .clone()
1128                    .map(waft_foundation::InstanceOf),
1129            )
1130            .default_value(
1131                default_theme
1132                    .value_indicator_shape
1133                    .clone()
1134                    .map(waft_foundation::InstanceOf),
1135            ),
1136        );
1137        properties.add(
1138            DiagnosticsProperty::<waft_foundation::InstanceOf<RangeSliderTickMarkShapeRef>>::new(
1139                "rangeTickMarkShape",
1140                self.range_tick_mark_shape
1141                    .clone()
1142                    .map(waft_foundation::InstanceOf),
1143            )
1144            .default_value(
1145                default_theme
1146                    .range_tick_mark_shape
1147                    .clone()
1148                    .map(waft_foundation::InstanceOf),
1149            ),
1150        );
1151        properties.add(
1152            DiagnosticsProperty::<waft_foundation::InstanceOf<RangeSliderThumbShapeRef>>::new(
1153                "rangeThumbShape",
1154                self.range_thumb_shape
1155                    .clone()
1156                    .map(waft_foundation::InstanceOf),
1157            )
1158            .default_value(
1159                default_theme
1160                    .range_thumb_shape
1161                    .clone()
1162                    .map(waft_foundation::InstanceOf),
1163            ),
1164        );
1165        properties.add(
1166            DiagnosticsProperty::<waft_foundation::InstanceOf<RangeSliderTrackShapeRef>>::new(
1167                "rangeTrackShape",
1168                self.range_track_shape
1169                    .clone()
1170                    .map(waft_foundation::InstanceOf),
1171            )
1172            .default_value(
1173                default_theme
1174                    .range_track_shape
1175                    .clone()
1176                    .map(waft_foundation::InstanceOf),
1177            ),
1178        );
1179        properties.add(DiagnosticsProperty::<waft_foundation::InstanceOf<RangeSliderValueIndicatorShapeRef>>::new("rangeValueIndicatorShape", self.range_value_indicator_shape.clone().map(waft_foundation::InstanceOf)).default_value(default_theme.range_value_indicator_shape.clone().map(waft_foundation::InstanceOf)));
1180        properties.add(
1181            EnumProperty::<ShowValueIndicator>::new(
1182                "showValueIndicator",
1183                self.show_value_indicator,
1184            )
1185            .default_value(default_theme.show_value_indicator),
1186        );
1187        properties.add(
1188            DiagnosticsProperty::<TextStyle>::new(
1189                "valueIndicatorTextStyle",
1190                self.value_indicator_text_style.clone(),
1191            )
1192            .default_value(default_theme.value_indicator_text_style.clone()),
1193        );
1194        properties.add(
1195            DoubleProperty::new("minThumbSeparation", self.min_thumb_separation)
1196                .default_value(default_theme.min_thumb_separation),
1197        );
1198        properties.add(DiagnosticsProperty::<String>::new("thumbSelector", self.thumb_selector.as_ref().map(|_| "Closure: (TextDirection, RangeValues, double, Size, Size, double) => Thumb?".to_string())).default_value(None));
1199        properties.add(
1200            DiagnosticsProperty::<String>::new(
1201                "mouseCursor",
1202                self.mouse_cursor
1203                    .as_deref()
1204                    .map(|property| property.to_string()),
1205            )
1206            .default_value(
1207                default_theme
1208                    .mouse_cursor
1209                    .as_deref()
1210                    .map(|property| property.to_string()),
1211            ),
1212        );
1213        properties.add(
1214            EnumProperty::<SliderInteraction>::new("allowedInteraction", self.allowed_interaction)
1215                .default_value(default_theme.allowed_interaction),
1216        );
1217        properties.add(
1218            DiagnosticsProperty::<EdgeInsetsGeometry>::new("padding", self.padding)
1219                .default_value(default_theme.padding),
1220        );
1221        properties.add(
1222            DiagnosticsProperty::<String>::new(
1223                "thumbSize",
1224                self.thumb_size
1225                    .as_deref()
1226                    .map(|property| property.to_string()),
1227            )
1228            .default_value(
1229                default_theme
1230                    .thumb_size
1231                    .as_deref()
1232                    .map(|property| property.to_string()),
1233            ),
1234        );
1235        properties.add(
1236            DoubleProperty::new("trackGap", self.track_gap).default_value(default_theme.track_gap),
1237        );
1238        properties.add(
1239            DiagnosticsProperty::<bool>::new("year2023", self.year2023)
1240                .default_value(default_theme.year2023),
1241        );
1242    }
1243}
1244
1245impl std::fmt::Display for SliderThemeData {
1246    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1247        f.write_str(&waft_foundation::Diagnosticable::to_string(self))
1248    }
1249}
1250
1251#[cfg(test)]
1252mod tests {
1253    use std::cell::Cell;
1254    use std::time::Duration;
1255
1256    use waft_embedder::{Offset, RRect, Radius, TargetPlatform, TextDirection};
1257    use waft_foundation::ValueChanged;
1258    use waft_rendering::{RenderBox, RenderObject};
1259    use waft_services::SystemMouseCursors;
1260    use waft_widgets::{Center, SizedBox, StatefulBuilder, WidgetStatePropertyAll};
1261
1262    use waft_widgets::testing::{TestPointer, WidgetTester, test_widgets};
1263
1264    use super::*;
1265    use crate::material::Material;
1266    use crate::range_slider_parts::RangeSliderTrackShape;
1267    use crate::range_slider_parts::RectangularRangeSliderTrackShape;
1268    use crate::scaffold::Scaffold;
1269    use crate::slider::Slider;
1270    use crate::slider::tests::{
1271        active_cursor, default_theme, is_cursor, noop, overlay_render, paints_circle,
1272        render_paints, slider_rect, slider_render,
1273    };
1274    use crate::slider_parts::{RectangularSliderTrackShape, SliderTrackShape};
1275    use crate::test_support::{PaintInspection, is_same_color_as, material_app};
1276    use crate::theme_data::ThemeData;
1277    use waft_rendering::testing::{CanvasMethod, PaintCall, assert_paints, count_calls, paints};
1278
1279    // 'SliderThemeData copyWith, ==, hashCode basics'.
1280    #[test]
1281    fn slider_theme_data_copy_with_and_equality_basics() {
1282        assert_eq!(SliderThemeData::new(), SliderThemeData::new().copy_with());
1283    }
1284
1285    // 'SliderThemeData lerp special cases'.
1286    #[test]
1287    fn slider_theme_data_lerp_special_cases() {
1288        // A theme with a `thumb_size`: lerping it makes a new property, which compares by
1289        // identity, so only Dart's `identical` shortcut hands back an equal theme.
1290        let data = SliderThemeData::new().thumb_size(Rc::new(WidgetStatePropertyAll::new(Some(
1291            Size::new(20.0, 20.0),
1292        ))));
1293        let lerp = SliderThemeData::lerp(&data, &data, 0.5);
1294        assert!(Rc::ptr_eq(
1295            lerp.thumb_size.as_ref().expect("lerped"),
1296            data.thumb_size.as_ref().expect("given")
1297        ));
1298        assert_eq!(lerp, data);
1299    }
1300
1301    fn custom_colors() -> (Color, Color, Color, Color) {
1302        (
1303            Color::new(0xcafefeed),
1304            Color::new(0xdeadbeef),
1305            Color::new(0xdecaface),
1306            Color::new(0xfeedcafe),
1307        )
1308    }
1309
1310    /// Dart's `ThemeData.fallback().textTheme.bodyLarge!.copyWith(color: color)`.
1311    fn fallback_body_large(tester: &mut WidgetTester, color: Color) -> TextStyle {
1312        let fallback = ThemeData::fallback(&tester.cell.borrow(), None);
1313        fallback
1314            .text_theme
1315            .body_large
1316            .expect("the fallback theme has a body large style")
1317            .copy_with()
1318            .color(color)
1319    }
1320
1321    // 'SliderThemeData generates correct opacities for fromPrimaryColors'.
1322    #[test]
1323    fn from_primary_colors_generates_the_opacities() {
1324        test_widgets(|tester| {
1325            let (custom_color1, custom_color2, custom_color3, custom_color4) = custom_colors();
1326            let slider_theme = SliderThemeData::from_primary_colors(
1327                custom_color1,
1328                custom_color2,
1329                custom_color3,
1330                fallback_body_large(tester, custom_color4),
1331            );
1332
1333            assert_eq!(
1334                slider_theme.active_track_color,
1335                Some(custom_color1.with_alpha(0xff))
1336            );
1337            assert_eq!(
1338                slider_theme.inactive_track_color,
1339                Some(custom_color1.with_alpha(0x3d))
1340            );
1341            assert_eq!(
1342                slider_theme.secondary_active_track_color,
1343                Some(custom_color1.with_alpha(0x8a))
1344            );
1345            assert_eq!(
1346                slider_theme.disabled_active_track_color,
1347                Some(custom_color2.with_alpha(0x52))
1348            );
1349            assert_eq!(
1350                slider_theme.disabled_inactive_track_color,
1351                Some(custom_color2.with_alpha(0x1f))
1352            );
1353            assert_eq!(
1354                slider_theme.disabled_secondary_active_track_color,
1355                Some(custom_color2.with_alpha(0x1f))
1356            );
1357            assert_eq!(
1358                slider_theme.active_tick_mark_color,
1359                Some(custom_color3.with_alpha(0x8a))
1360            );
1361            assert_eq!(
1362                slider_theme.inactive_tick_mark_color,
1363                Some(custom_color1.with_alpha(0x8a))
1364            );
1365            assert_eq!(
1366                slider_theme.disabled_active_tick_mark_color,
1367                Some(custom_color3.with_alpha(0x1f))
1368            );
1369            assert_eq!(
1370                slider_theme.disabled_inactive_tick_mark_color,
1371                Some(custom_color2.with_alpha(0x1f))
1372            );
1373            assert_eq!(
1374                slider_theme.thumb_color,
1375                Some(custom_color1.with_alpha(0xff))
1376            );
1377            assert_eq!(
1378                slider_theme.disabled_thumb_color,
1379                Some(custom_color2.with_alpha(0x52))
1380            );
1381            assert_eq!(
1382                slider_theme.overlay_color,
1383                Some(AnyColor::new(custom_color1.with_alpha(0x1f)))
1384            );
1385            assert_eq!(
1386                slider_theme.value_indicator_color,
1387                Some(custom_color1.with_alpha(0xff))
1388            );
1389            assert_eq!(
1390                slider_theme.value_indicator_stroke_color,
1391                Some(custom_color1.with_alpha(0xff))
1392            );
1393            assert_eq!(
1394                slider_theme
1395                    .value_indicator_text_style
1396                    .and_then(|style| style.color)
1397                    .map(|color| color.color()),
1398                Some(custom_color4)
1399            );
1400        });
1401    }
1402
1403    // 'SliderThemeData generates correct shapes for fromPrimaryColors'.
1404    #[test]
1405    fn from_primary_colors_generates_the_shapes() {
1406        test_widgets(|tester| {
1407            use crate::range_slider_parts::{
1408                RoundRangeSliderThumbShape, RoundRangeSliderTickMarkShape,
1409                RoundedRectRangeSliderTrackShape,
1410            };
1411            use crate::slider_parts::{
1412                RoundSliderThumbShape, RoundSliderTickMarkShape, RoundedRectSliderTrackShape,
1413            };
1414            let (custom_color1, custom_color2, custom_color3, custom_color4) = custom_colors();
1415            let slider_theme = SliderThemeData::from_primary_colors(
1416                custom_color1,
1417                custom_color2,
1418                custom_color3,
1419                fallback_body_large(tester, custom_color4),
1420            );
1421
1422            fn is<T: PartialEq + 'static>(any: &dyn std::any::Any, expected: T) -> bool {
1423                any.downcast_ref::<T>() == Some(&expected)
1424            }
1425            assert!(is(
1426                slider_theme.overlay_shape.unwrap().as_any(),
1427                RoundSliderOverlayShape::new()
1428            ));
1429            assert!(is(
1430                slider_theme.tick_mark_shape.unwrap().as_any(),
1431                RoundSliderTickMarkShape::new()
1432            ));
1433            assert!(is(
1434                slider_theme.thumb_shape.unwrap().as_any(),
1435                RoundSliderThumbShape::new()
1436            ));
1437            assert!(is(
1438                slider_theme.track_shape.unwrap().as_any(),
1439                RoundedRectSliderTrackShape::new()
1440            ));
1441            assert!(is(
1442                slider_theme.value_indicator_shape.unwrap().as_any(),
1443                PaddleSliderValueIndicatorShape::new()
1444            ));
1445            assert!(is(
1446                slider_theme.range_tick_mark_shape.unwrap().as_any(),
1447                RoundRangeSliderTickMarkShape::new()
1448            ));
1449            assert!(is(
1450                slider_theme.range_thumb_shape.unwrap().as_any(),
1451                RoundRangeSliderThumbShape::new()
1452            ));
1453            assert!(is(
1454                slider_theme.range_track_shape.unwrap().as_any(),
1455                RoundedRectRangeSliderTrackShape::new()
1456            ));
1457            assert!(is(
1458                slider_theme.range_value_indicator_shape.unwrap().as_any(),
1459                PaddleRangeSliderValueIndicatorShape::new()
1460            ));
1461        });
1462    }
1463
1464    // 'SliderThemeData lerps correctly'.
1465    #[test]
1466    fn slider_theme_data_lerps() {
1467        test_widgets(|tester| {
1468            let slider_theme_black = SliderThemeData::from_primary_colors(
1469                Colors::BLACK,
1470                Colors::BLACK,
1471                Colors::BLACK,
1472                fallback_body_large(tester, Colors::BLACK),
1473            )
1474            .copy_with()
1475            .track_height(2.0);
1476            let slider_theme_white = SliderThemeData::from_primary_colors(
1477                Colors::WHITE,
1478                Colors::WHITE,
1479                Colors::WHITE,
1480                fallback_body_large(tester, Colors::WHITE),
1481            )
1482            .copy_with()
1483            .track_height(6.0);
1484            let lerp = SliderThemeData::lerp(&slider_theme_black, &slider_theme_white, 0.5);
1485            let middle_grey = Color::new(0xff7f7f7f);
1486            let same = |color: Option<Color>, alpha: i32| {
1487                is_same_color_as(color.expect("lerped"), middle_grey.with_alpha(alpha))
1488            };
1489
1490            assert_eq!(lerp.track_height, Some(4.0));
1491            assert!(same(lerp.active_track_color, 0xff));
1492            assert!(same(lerp.inactive_track_color, 0x3d));
1493            assert!(same(lerp.secondary_active_track_color, 0x8a));
1494            assert!(same(lerp.disabled_active_track_color, 0x52));
1495            assert!(same(lerp.disabled_inactive_track_color, 0x1f));
1496            assert!(same(lerp.disabled_secondary_active_track_color, 0x1f));
1497            assert!(same(lerp.active_tick_mark_color, 0x8a));
1498            assert!(same(lerp.inactive_tick_mark_color, 0x8a));
1499            assert!(same(lerp.disabled_active_tick_mark_color, 0x1f));
1500            assert!(same(lerp.disabled_inactive_tick_mark_color, 0x1f));
1501            assert!(same(lerp.thumb_color, 0xff));
1502            assert!(same(lerp.disabled_thumb_color, 0x52));
1503            assert!(same(lerp.overlay_color.map(|color| color.color()), 0x1f));
1504            assert!(same(lerp.value_indicator_color, 0xff));
1505            assert!(same(lerp.value_indicator_stroke_color, 0xff));
1506            assert!(same(
1507                lerp.value_indicator_text_style
1508                    .and_then(|style| style.color)
1509                    .map(|color| color.color()),
1510                0xff
1511            ));
1512        });
1513    }
1514
1515    // 'Track shape isRounded defaults'.
1516    #[test]
1517    fn track_shapes_report_whether_they_are_rounded() {
1518        use crate::range_slider_parts::RoundedRectRangeSliderTrackShape;
1519        use crate::slider_parts::RoundedRectSliderTrackShape;
1520        assert!(!SliderTrackShape::is_rounded(
1521            &RectangularSliderTrackShape::new()
1522        ));
1523        assert!(SliderTrackShape::is_rounded(
1524            &RoundedRectSliderTrackShape::new()
1525        ));
1526        assert!(!RangeSliderTrackShape::is_rounded(
1527            &RectangularRangeSliderTrackShape::new()
1528        ));
1529        assert!(RangeSliderTrackShape::is_rounded(
1530            &RoundedRectRangeSliderTrackShape::new()
1531        ));
1532    }
1533
1534    /// Dart's `_buildApp`: a slider at `value` under `slider_theme` in a scaffold's body.
1535    fn build_app(
1536        tester: &WidgetTester,
1537        slider_theme: SliderThemeData,
1538        value: f64,
1539        secondary_track_value: Option<f64>,
1540        enabled: bool,
1541    ) -> WidgetRef {
1542        let mut slider = Slider::new(value, enabled.then(noop).flatten()).label(format!("{value}"));
1543        if let Some(secondary_track_value) = secondary_track_value {
1544            slider = slider.secondary_track_value(secondary_track_value);
1545        }
1546        material_app(
1547            default_theme(tester),
1548            Scaffold::new()
1549                .body(Center::new().child(SliderTheme::new(slider_theme, slider)))
1550                .into_widget(),
1551        )
1552    }
1553
1554    // 'Slider parameters overrides theme properties'.
1555    #[test]
1556    fn slider_parameters_override_theme_properties() {
1557        test_widgets(|tester| {
1558            const ACTIVE_TRACK_COLOR: Color = Color::new(0xffff0001);
1559            const INACTIVE_TRACK_COLOR: Color = Color::new(0xffff0002);
1560            const SECONDARY_ACTIVE_TRACK_COLOR: Color = Color::new(0xffff0003);
1561            const THUMB_COLOR: Color = Color::new(0xffff0004);
1562
1563            let theme = ThemeData::builder()
1564                .platform(TargetPlatform::Android)
1565                .primary_swatch(Colors::BLUE)
1566                .slider_theme(
1567                    SliderThemeData::new()
1568                        .active_track_color(Color::new(0xff000001))
1569                        .inactive_tick_mark_color(Color::new(0xff000002))
1570                        .secondary_active_track_color(Color::new(0xff000003))
1571                        .thumb_color(Color::new(0xff000004)),
1572                )
1573                .build(&tester.cell.borrow());
1574            let value = 0.45;
1575            tester.pump_widget(material_app(
1576                theme,
1577                waft_widgets::Directionality::new(
1578                    TextDirection::Ltr,
1579                    Material::new().child(
1580                        Center::new().child(
1581                            Slider::new(value, noop())
1582                                .active_color(ACTIVE_TRACK_COLOR)
1583                                .inactive_color(INACTIVE_TRACK_COLOR)
1584                                .secondary_active_color(SECONDARY_ACTIVE_TRACK_COLOR)
1585                                .thumb_color(THUMB_COLOR)
1586                                .secondary_track_value(0.75)
1587                                .label(format!("{value}")),
1588                        ),
1589                    ),
1590                )
1591                .into_widget(),
1592            ));
1593
1594            // Test Slider parameters.
1595            assert!(render_paints(
1596                tester,
1597                slider_render(tester),
1598                &[
1599                    PaintCall::rrect(Some(INACTIVE_TRACK_COLOR)),
1600                    PaintCall::rrect(Some(ACTIVE_TRACK_COLOR)),
1601                    PaintCall::rrect(Some(SECONDARY_ACTIVE_TRACK_COLOR)),
1602                ],
1603            ));
1604            assert!(paints_circle(tester, slider_render(tester), THUMB_COLOR));
1605        });
1606    }
1607
1608    /// Dart's 'Slider uses ThemeData slider theme if present' and 'Slider overrides ThemeData
1609    /// theme if SliderTheme present', which pump the same app.
1610    fn uses_the_slider_theme_given(tester: &mut WidgetTester) {
1611        let theme = ThemeData::builder()
1612            .platform(TargetPlatform::Android)
1613            .primary_swatch(Colors::RED)
1614            .build(&tester.cell.borrow());
1615        let slider_theme = theme.slider_theme.clone();
1616        let purple = Colors::PURPLE.primary();
1617        let custom_theme = slider_theme
1618            .copy_with()
1619            .active_track_color(purple)
1620            .inactive_track_color(purple.with_alpha(0x3d))
1621            .secondary_active_track_color(purple.with_alpha(0x8a));
1622
1623        let app = build_app(tester, slider_theme, 0.5, Some(0.75), false);
1624        tester.pump_widget(app);
1625
1626        let rrect = |color: Option<Color>| PaintCall::rrect(color);
1627        assert!(render_paints(
1628            tester,
1629            slider_render(tester),
1630            &[
1631                rrect(custom_theme.disabled_active_track_color),
1632                rrect(custom_theme.disabled_inactive_track_color),
1633                rrect(custom_theme.disabled_secondary_active_track_color),
1634            ],
1635        ));
1636    }
1637
1638    // 'Slider uses ThemeData slider theme if present'.
1639    #[test]
1640    fn a_slider_uses_the_theme_data_slider_theme() {
1641        test_widgets(uses_the_slider_theme_given);
1642    }
1643
1644    // 'Slider overrides ThemeData theme if SliderTheme present'.
1645    #[test]
1646    fn a_slider_theme_overrides_the_theme_data_slider_theme() {
1647        test_widgets(uses_the_slider_theme_given);
1648    }
1649
1650    // 'The mouse cursor is themeable'.
1651    #[test]
1652    fn the_mouse_cursor_is_themeable() {
1653        test_widgets(|tester| {
1654            let theme = default_theme(tester);
1655            let cursor: MouseCursorRef = SystemMouseCursors::TEXT.into();
1656            let app = build_app(
1657                tester,
1658                theme
1659                    .slider_theme
1660                    .copy_with()
1661                    .mouse_cursor(Rc::new(WidgetStatePropertyAll::new(Some(cursor)))),
1662                0.0,
1663                None,
1664                true,
1665            );
1666            tester.pump_widget(app);
1667
1668            tester.pump_and_settle();
1669            let mut gesture = TestPointer::mouse(1, 0);
1670            tester.add_pointer(&mut gesture, Offset::ZERO);
1671            tester.move_to(&mut gesture, slider_rect(tester).center(), false);
1672            tester.pump_and_settle();
1673            assert!(is_cursor(&active_cursor(tester), SystemMouseCursors::TEXT));
1674        });
1675    }
1676
1677    // 'SliderTheme.allowedInteraction is themeable'.
1678    #[test]
1679    fn the_allowed_interaction_is_themeable() {
1680        test_widgets(|tester| {
1681            let value = Rc::new(Cell::new(0.0));
1682            let theme = default_theme(tester);
1683            let build = |theme_null: bool, slider_null: bool| {
1684                let value = Rc::clone(&value);
1685                let mut slider_theme = theme.slider_theme.copy_with();
1686                if !theme_null {
1687                    slider_theme = slider_theme.allowed_interaction(SliderInteraction::SlideOnly);
1688                }
1689                material_app(
1690                    theme.clone(),
1691                    Scaffold::new()
1692                        .body(Center::new().child(SliderTheme::new(
1693                            slider_theme,
1694                            StatefulBuilder::new(move |_app, _context, set_state| {
1695                                let on_changed_value = Rc::clone(&value);
1696                                let mut slider = Slider::new(
1697                                    value.get(),
1698                                    Some(Rc::new(move |app: &mut App, new_value: f64| {
1699                                        let value = Rc::clone(&on_changed_value);
1700                                        set_state(app, &mut |_app| value.set(new_value));
1701                                    })),
1702                                );
1703                                if !slider_null {
1704                                    slider = slider.allowed_interaction(SliderInteraction::TapOnly);
1705                                }
1706                                slider.into_widget()
1707                            }),
1708                        )))
1709                        .into_widget(),
1710                )
1711            };
1712            let mut gesture = TestPointer::touch(1);
1713            let tap = |tester: &mut WidgetTester, gesture: &mut TestPointer| {
1714                value.set(0.0);
1715                tester.down(gesture, slider_rect(tester).center());
1716                tester.pump();
1717                let tapped = value.get();
1718                tester.up(gesture);
1719                tapped
1720            };
1721            let slide = |tester: &mut WidgetTester, gesture: &mut TestPointer| {
1722                value.set(0.0);
1723                tester.down(gesture, slider_rect(tester).center());
1724                tester.pump();
1725                let at = gesture.position + Offset::new(50.0, 0.0);
1726                tester.move_to(gesture, at, true);
1727                let slid = value.get();
1728                tester.up(gesture);
1729                slid
1730            };
1731
1732            // when theme and parameter are specified, parameter is used [tapOnly].
1733            tester.pump_widget(build(false, false));
1734            // tap is allowed.
1735            assert_eq!(tap(tester, &mut gesture), 0.5); // changes
1736            // slide isn't allowed.
1737            assert_eq!(slide(tester, &mut gesture), 0.0); // no change
1738
1739            // when only parameter is specified, parameter is used [tapOnly].
1740            tester.pump_widget(build(true, false));
1741            // tap is allowed.
1742            assert_eq!(tap(tester, &mut gesture), 0.5); // changes
1743            // slide isn't allowed.
1744            assert_eq!(slide(tester, &mut gesture), 0.0); // no change
1745
1746            // when theme is specified but parameter is null, theme is used [slideOnly].
1747            tester.pump_widget(build(false, true));
1748            // tap isn't allowed.
1749            assert_eq!(tap(tester, &mut gesture), 0.0); // no change
1750            // slide isn't allowed.
1751            assert!(slide(tester, &mut gesture) > 0.0); // changes
1752
1753            // when both theme and parameter are null, default is used [tapAndSlide].
1754            tester.pump_widget(build(true, true));
1755            // tap is allowed.
1756            assert_eq!(tap(tester, &mut gesture), 0.5);
1757            // slide is allowed.
1758            assert!(slide(tester, &mut gesture) > 0.0); // changes
1759        });
1760    }
1761
1762    // 'Opt into 2024 Slider appearance with SliderThemeData.year2023'.
1763    #[test]
1764    #[expect(deprecated, reason = "Dart's case sets the deprecated `year2023`")]
1765    fn slider_theme_data_year2023_opts_into_the_2024_appearance() {
1766        test_widgets(|tester| {
1767            let theme = ThemeData::builder()
1768                .slider_theme(SliderThemeData::new().year2023(false))
1769                .build(&tester.cell.borrow());
1770            let color_scheme = theme.color_scheme.clone();
1771            let value = 0.45;
1772            tester.pump_widget(material_app(
1773                theme,
1774                Material::new()
1775                    .child(Center::new().child(Slider::new(value, noop())))
1776                    .into_widget(),
1777            ));
1778
1779            // Test default track shape.
1780            let outer = Radius::circular(8.0);
1781            let inner = Radius::circular(2.0);
1782            assert!(render_paints(
1783                tester,
1784                slider_render(tester),
1785                &[
1786                    // Active track.
1787                    PaintCall::rrect_at(
1788                        RRect::from_ltrb_and_corners(
1789                            24.0, 292.0, 356.4, 308.0, outer, inner, inner, outer,
1790                        ),
1791                        Some(color_scheme.primary()),
1792                    ),
1793                    // Inctive track.
1794                    PaintCall::rrect_at(
1795                        RRect::from_ltrb_and_corners(
1796                            368.4, 292.0, 776.0, 308.0, inner, outer, outer, inner,
1797                        ),
1798                        Some(color_scheme.secondary_container()),
1799                    ),
1800                ],
1801            ));
1802        });
1803    }
1804
1805    // 'Slider.year2023 overrides SliderThemeData.year2023'.
1806    #[test]
1807    #[expect(deprecated, reason = "Dart's case sets the deprecated `year2023`")]
1808    fn slider_year2023_overrides_the_theme_year2023() {
1809        test_widgets(|tester| {
1810            let theme = ThemeData::builder()
1811                .slider_theme(SliderThemeData::new().year2023(false))
1812                .build(&tester.cell.borrow());
1813            let color_scheme = theme.color_scheme.clone();
1814            let value = 0.45;
1815            let app_theme = default_theme(tester);
1816            tester.pump_widget(material_app(
1817                app_theme,
1818                Material::new()
1819                    .child(Center::new().child(crate::theme::Theme::new(
1820                        theme,
1821                        Slider::new(value, noop()).year2023(true),
1822                    )))
1823                    .into_widget(),
1824            ));
1825
1826            // Test default track shape.
1827            let active_track_corner_radius = Radius::circular(3.0);
1828            let inactive_track_corner_radius = Radius::circular(2.0);
1829            assert!(render_paints(
1830                tester,
1831                slider_render(tester),
1832                &[
1833                    // Active track.
1834                    PaintCall::rrect_at(
1835                        RRect::from_ltrbr(360.4, 298.0, 776.0, 302.0, inactive_track_corner_radius,),
1836                        Some(color_scheme.surface_container_highest()),
1837                    ),
1838                    // Inctive track.
1839                    PaintCall::rrect_at(
1840                        RRect::from_ltrbr(24.0, 297.0, 364.4, 303.0, active_track_corner_radius,),
1841                        Some(color_scheme.primary()),
1842                    ),
1843                ],
1844            ));
1845        });
1846    }
1847
1848    /// The colours Dart's 'Slider defaults' cases expect.
1849    struct DefaultColors {
1850        inactive_track: Color,
1851        active_track: Color,
1852        secondary_active_track: Color,
1853        disabled_active_track: Color,
1854        disabled_inactive_track: Color,
1855        disabled_secondary_active_track: Color,
1856        shadow: Color,
1857        thumb: Color,
1858        disabled_thumb: Color,
1859        active_tick_mark: Color,
1860        inactive_tick_mark: Color,
1861        disabled_active_tick_mark: Color,
1862        disabled_inactive_tick_mark: Color,
1863    }
1864
1865    /// The body Dart's 'Slider defaults' (Material 3 and Material 2) share: `build_app` makes
1866    /// the app for `divisions` and `enabled`.
1867    fn expect_slider_defaults(
1868        tester: &mut WidgetTester,
1869        colors: &DefaultColors,
1870        build_app: &dyn Fn(Option<i32>, bool) -> WidgetRef,
1871    ) {
1872        const TRACK_HEIGHT: f64 = 4.0;
1873        tester.pump_widget(build_app(None, true));
1874
1875        // Test default track height.
1876        let radius = Radius::circular(TRACK_HEIGHT / 2.0);
1877        let activated_radius = Radius::circular((TRACK_HEIGHT + 2.0) / 2.0);
1878        let render = slider_render(tester);
1879        assert!(render_paints(
1880            tester,
1881            render,
1882            &[
1883                // Inactive track.
1884                PaintCall::rrect_at(
1885                    RRect::from_ltrbr(360.4, 298.0, 776.0, 302.0, radius),
1886                    Some(colors.inactive_track),
1887                ),
1888                // Active track.
1889                PaintCall::rrect_at(
1890                    RRect::from_ltrbr(24.0, 297.0, 364.4, 303.0, activated_radius),
1891                    Some(colors.active_track),
1892                ),
1893            ],
1894        ));
1895
1896        // Test default colors for enabled slider.
1897        let tracks = |inactive: Color, active: Color, secondary: Color| {
1898            [
1899                PaintCall::rrect(Some(inactive)),
1900                PaintCall::rrect(Some(active)),
1901                PaintCall::rrect(Some(secondary)),
1902            ]
1903        };
1904        assert!(render_paints(
1905            tester,
1906            render,
1907            &tracks(
1908                colors.inactive_track,
1909                colors.active_track,
1910                colors.secondary_active_track
1911            )
1912        ));
1913        assert!(render_paints(
1914            tester,
1915            render,
1916            &[PaintCall::shadow(Some(colors.shadow))]
1917        ));
1918        assert!(render_paints(
1919            tester,
1920            render,
1921            &[PaintCall::circle(Some(colors.thumb))]
1922        ));
1923        assert!(!render_paints(
1924            tester,
1925            render,
1926            &[PaintCall::circle(Some(colors.disabled_thumb))]
1927        ));
1928        assert!(!render_paints(
1929            tester,
1930            render,
1931            &[PaintCall::rrect(Some(colors.disabled_active_track))]
1932        ));
1933        assert!(!render_paints(
1934            tester,
1935            render,
1936            &[PaintCall::rrect(Some(colors.disabled_inactive_track))]
1937        ));
1938        assert!(!render_paints(
1939            tester,
1940            render,
1941            &[PaintCall::rrect(Some(
1942                colors.disabled_secondary_active_track
1943            ))]
1944        ));
1945        assert!(!render_paints(
1946            tester,
1947            render,
1948            &[PaintCall::circle(Some(colors.active_tick_mark))]
1949        ));
1950        assert!(!render_paints(
1951            tester,
1952            render,
1953            &[PaintCall::circle(Some(colors.inactive_tick_mark))]
1954        ));
1955
1956        // Test defaults colors for discrete slider.
1957        tester.pump_widget(build_app(Some(3), true));
1958        let render = slider_render(tester);
1959        assert!(render_paints(
1960            tester,
1961            render,
1962            &tracks(
1963                colors.inactive_track,
1964                colors.active_track,
1965                colors.secondary_active_track
1966            )
1967        ));
1968        assert!(render_paints(
1969            tester,
1970            render,
1971            &[
1972                PaintCall::circle(Some(colors.active_tick_mark)),
1973                PaintCall::circle(Some(colors.active_tick_mark)),
1974                PaintCall::circle(Some(colors.inactive_tick_mark)),
1975                PaintCall::circle(Some(colors.inactive_tick_mark)),
1976                PaintCall::shadow(Some(Colors::BLACK)),
1977                PaintCall::circle(Some(colors.thumb)),
1978            ],
1979        ));
1980        assert!(!render_paints(
1981            tester,
1982            render,
1983            &[PaintCall::circle(Some(colors.disabled_thumb))]
1984        ));
1985        assert!(!render_paints(
1986            tester,
1987            render,
1988            &[PaintCall::rrect(Some(colors.disabled_active_track))]
1989        ));
1990        assert!(!render_paints(
1991            tester,
1992            render,
1993            &[PaintCall::rrect(Some(colors.disabled_inactive_track))]
1994        ));
1995        assert!(!render_paints(
1996            tester,
1997            render,
1998            &[PaintCall::rrect(Some(
1999                colors.disabled_secondary_active_track
2000            ))]
2001        ));
2002
2003        // Test defaults colors for disabled slider.
2004        tester.pump_widget(build_app(None, false));
2005        tester.pump_and_settle();
2006        let render = slider_render(tester);
2007        assert!(render_paints(
2008            tester,
2009            render,
2010            &tracks(
2011                colors.disabled_inactive_track,
2012                colors.disabled_active_track,
2013                colors.disabled_secondary_active_track
2014            )
2015        ));
2016        assert!(render_paints(
2017            tester,
2018            render,
2019            &[
2020                PaintCall::shadow(Some(colors.shadow)),
2021                PaintCall::circle(Some(colors.disabled_thumb))
2022            ]
2023        ));
2024        assert!(!render_paints(
2025            tester,
2026            render,
2027            &[PaintCall::circle(Some(colors.thumb))]
2028        ));
2029        assert!(!render_paints(
2030            tester,
2031            render,
2032            &[PaintCall::rrect(Some(colors.active_track))]
2033        ));
2034        assert!(!render_paints(
2035            tester,
2036            render,
2037            &[PaintCall::rrect(Some(colors.inactive_track))]
2038        ));
2039        assert!(!render_paints(
2040            tester,
2041            render,
2042            &[PaintCall::rrect(Some(colors.secondary_active_track))]
2043        ));
2044
2045        // Test defaults colors for disabled discrete slider.
2046        tester.pump_widget(build_app(Some(3), false));
2047        let render = slider_render(tester);
2048        assert!(render_paints(
2049            tester,
2050            render,
2051            &[
2052                PaintCall::circle(Some(colors.disabled_active_tick_mark)),
2053                PaintCall::circle(Some(colors.disabled_active_tick_mark)),
2054                PaintCall::circle(Some(colors.disabled_inactive_tick_mark)),
2055                PaintCall::circle(Some(colors.disabled_inactive_tick_mark)),
2056                PaintCall::shadow(Some(colors.shadow)),
2057                PaintCall::circle(Some(colors.disabled_thumb)),
2058            ],
2059        ));
2060        assert!(!render_paints(
2061            tester,
2062            render,
2063            &[PaintCall::circle(Some(colors.thumb))]
2064        ));
2065        assert!(!render_paints(
2066            tester,
2067            render,
2068            &[PaintCall::rrect(Some(colors.active_track))]
2069        ));
2070        assert!(!render_paints(
2071            tester,
2072            render,
2073            &[PaintCall::rrect(Some(colors.inactive_track))]
2074        ));
2075        assert!(!render_paints(
2076            tester,
2077            render,
2078            &[PaintCall::rrect(Some(colors.secondary_active_track))]
2079        ));
2080    }
2081
2082    /// Dart's `buildApp` of the 'Slider defaults' cases: a slider at 0.45 with a secondary
2083    /// track at 0.75 and a label.
2084    fn defaults_slider(divisions: Option<i32>, enabled: bool) -> Slider {
2085        let value = 0.45;
2086        let mut slider = Slider::new(value, enabled.then(noop).flatten())
2087            .secondary_track_value(0.75)
2088            .label(format!("{value}"));
2089        if let Some(divisions) = divisions {
2090            slider = slider.divisions(divisions);
2091        }
2092        slider
2093    }
2094
2095    // 'Slider defaults'.
2096    #[test]
2097    #[expect(deprecated, reason = "Dart's case calls the deprecated `withOpacity`")]
2098    fn slider_defaults() {
2099        test_widgets(|tester| {
2100            let theme = ThemeData::builder().build(&tester.cell.borrow());
2101            let color_scheme = theme.color_scheme.clone();
2102            let colors = DefaultColors {
2103                active_track: color_scheme.primary(),
2104                inactive_track: color_scheme.surface_container_highest(),
2105                secondary_active_track: color_scheme.primary().with_opacity(0.54),
2106                disabled_active_track: color_scheme.on_surface().with_opacity(0.38),
2107                disabled_inactive_track: color_scheme.on_surface().with_opacity(0.12),
2108                disabled_secondary_active_track: color_scheme.on_surface().with_opacity(0.12),
2109                shadow: color_scheme.shadow(),
2110                thumb: color_scheme.primary(),
2111                disabled_thumb: Color::alpha_blend(
2112                    color_scheme.on_surface().with_opacity(0.38),
2113                    color_scheme.surface(),
2114                ),
2115                active_tick_mark: color_scheme.on_primary().with_opacity(0.38),
2116                inactive_tick_mark: color_scheme.on_surface_variant().with_opacity(0.38),
2117                disabled_active_tick_mark: color_scheme.on_surface().with_opacity(0.38),
2118                disabled_inactive_tick_mark: color_scheme.on_surface().with_opacity(0.38),
2119            };
2120            let app_theme = default_theme(tester);
2121            let build_app = |divisions: Option<i32>, enabled: bool| {
2122                material_app(
2123                    app_theme.clone(),
2124                    waft_widgets::Directionality::new(
2125                        TextDirection::Ltr,
2126                        Material::new().child(Center::new().child(crate::theme::Theme::new(
2127                            theme.clone(),
2128                            defaults_slider(divisions, enabled),
2129                        ))),
2130                    )
2131                    .into_widget(),
2132                )
2133            };
2134            expect_slider_defaults(tester, &colors, &build_app);
2135        });
2136    }
2137
2138    // 'Material 2' 'Slider defaults'.
2139    #[test]
2140    #[expect(deprecated, reason = "Dart's case calls the deprecated `withOpacity`")]
2141    fn material2_slider_defaults() {
2142        test_widgets(|tester| {
2143            let theme = ThemeData::builder()
2144                .use_material3(false)
2145                .build(&tester.cell.borrow());
2146            let color_scheme = theme.color_scheme.clone();
2147            let colors = DefaultColors {
2148                active_track: color_scheme.primary(),
2149                inactive_track: color_scheme.primary().with_opacity(0.24),
2150                secondary_active_track: color_scheme.primary().with_opacity(0.54),
2151                disabled_active_track: color_scheme.on_surface().with_opacity(0.32),
2152                disabled_inactive_track: color_scheme.on_surface().with_opacity(0.12),
2153                disabled_secondary_active_track: color_scheme.on_surface().with_opacity(0.12),
2154                shadow: color_scheme.shadow(),
2155                thumb: color_scheme.primary(),
2156                disabled_thumb: Color::alpha_blend(
2157                    color_scheme.on_surface().with_opacity(0.38),
2158                    color_scheme.surface(),
2159                ),
2160                active_tick_mark: color_scheme.on_primary().with_opacity(0.54),
2161                inactive_tick_mark: color_scheme.primary().with_opacity(0.54),
2162                disabled_active_tick_mark: color_scheme.on_primary().with_opacity(0.12),
2163                disabled_inactive_tick_mark: color_scheme.on_surface().with_opacity(0.12),
2164            };
2165            let value_indicator_color = Color::alpha_blend(
2166                color_scheme.on_surface().with_opacity(0.60),
2167                color_scheme.surface().with_opacity(0.90),
2168            );
2169            let value = Rc::new(Cell::new(0.45));
2170            let build_app = |divisions: Option<i32>, enabled: bool| {
2171                let value = Rc::clone(&value);
2172                let mut slider = defaults_slider(divisions, enabled);
2173                if enabled {
2174                    slider.on_changed = Some(Rc::new(move |_app: &mut App, d: f64| value.set(d)));
2175                }
2176                material_app(
2177                    theme.clone(),
2178                    Material::new()
2179                        .child(Center::new().child(slider))
2180                        .into_widget(),
2181                )
2182            };
2183            expect_slider_defaults(tester, &colors, &build_app);
2184
2185            // Test the default color for value indicator.
2186            tester.pump_widget(build_app(Some(3), true));
2187            let center = slider_rect(tester).center();
2188            let mut gesture = TestPointer::touch(1);
2189            tester.down(&mut gesture, center);
2190            // Wait for value indicator animation to finish.
2191            tester.pump_and_settle();
2192            assert_eq!(value.get(), 2.0 / 3.0);
2193            let value_indicator_box = tester
2194                .first::<crate::slider::RenderValueIndicator>()
2195                .as_render_object(&tester.cell.borrow());
2196            assert!(render_paints(
2197                tester,
2198                value_indicator_box,
2199                &[
2200                    PaintCall::path(Some(value_indicator_color)),
2201                    PaintCall::Paragraph
2202                ],
2203            ));
2204            tester.up(&gesture);
2205            // Wait for value indicator animation to finish.
2206            tester.pump_and_settle();
2207        });
2208    }
2209
2210    // 'Slider uses the right theme colors for the right components'.
2211    #[test]
2212    #[expect(deprecated, reason = "Dart's case calls the deprecated `withOpacity`")]
2213    fn a_slider_uses_the_right_theme_colors_for_the_right_components() {
2214        test_widgets(|tester| {
2215            const CUSTOM_COLOR1: Color = Color::new(0xcafefeed);
2216            const CUSTOM_COLOR2: Color = Color::new(0xdeadbeef);
2217            const CUSTOM_COLOR3: Color = Color::new(0xdecaface);
2218            let theme = ThemeData::builder()
2219                .use_material3(false)
2220                .platform(TargetPlatform::Android)
2221                .primary_swatch(Colors::BLUE)
2222                .slider_theme(
2223                    SliderThemeData::new()
2224                        .disabled_thumb_color(Color::new(0xff000001))
2225                        .disabled_active_tick_mark_color(Color::new(0xff000002))
2226                        .disabled_active_track_color(Color::new(0xff000003))
2227                        .disabled_inactive_tick_mark_color(Color::new(0xff000004))
2228                        .disabled_inactive_track_color(Color::new(0xff000005))
2229                        .active_track_color(Color::new(0xff000006))
2230                        .active_tick_mark_color(Color::new(0xff000007))
2231                        .inactive_track_color(Color::new(0xff000008))
2232                        .inactive_tick_mark_color(Color::new(0xff000009))
2233                        .overlay_color(Color::new(0xff000010))
2234                        .thumb_color(Color::new(0xff000011))
2235                        .value_indicator_color(Color::new(0xff000012))
2236                        .disabled_secondary_active_track_color(Color::new(0xff000013))
2237                        .secondary_active_track_color(Color::new(0xff000014)),
2238                )
2239                .build(&tester.cell.borrow());
2240            let slider_theme = theme.slider_theme.clone();
2241            let value = Rc::new(Cell::new(0.45));
2242            #[derive(Default)]
2243            struct Args {
2244                active_color: Option<Color>,
2245                inactive_color: Option<Color>,
2246                secondary_active_color: Option<Color>,
2247                divisions: Option<i32>,
2248                disabled: bool,
2249            }
2250            let build_app = |args: Args| {
2251                let on_changed_value = Rc::clone(&value);
2252                let on_changed: Option<ValueChanged<f64>> = (!args.disabled).then(|| {
2253                    Rc::new(move |_app: &mut App, d: f64| on_changed_value.set(d))
2254                        as ValueChanged<f64>
2255                });
2256                let mut slider = Slider::new(value.get(), on_changed)
2257                    .secondary_track_value(0.75)
2258                    .label(format!("{}", value.get()));
2259                if let Some(divisions) = args.divisions {
2260                    slider = slider.divisions(divisions);
2261                }
2262                if let Some(active_color) = args.active_color {
2263                    slider = slider.active_color(active_color);
2264                }
2265                if let Some(inactive_color) = args.inactive_color {
2266                    slider = slider.inactive_color(inactive_color);
2267                }
2268                if let Some(secondary_active_color) = args.secondary_active_color {
2269                    slider = slider.secondary_active_color(secondary_active_color);
2270                }
2271                material_app(
2272                    theme.clone(),
2273                    waft_widgets::Directionality::new(
2274                        TextDirection::Ltr,
2275                        Material::new().child(
2276                            Center::new().child(crate::theme::Theme::new(theme.clone(), slider)),
2277                        ),
2278                    )
2279                    .into_widget(),
2280                )
2281            };
2282            let rrect = |color: Option<Color>| PaintCall::rrect(color);
2283            let circle = |color: Option<Color>| PaintCall::circle(color);
2284            let tracks =
2285                |inactive: Option<Color>, active: Option<Color>, secondary: Option<Color>| {
2286                    [rrect(inactive), rrect(active), rrect(secondary)]
2287                };
2288            let painted = |tester: &WidgetTester, calls: &[PaintCall]| {
2289                render_paints(tester, slider_render(tester), calls)
2290            };
2291            let not_painted = |tester: &WidgetTester, calls: &[PaintCall]| !painted(tester, calls);
2292            let no_disabled_tracks = |tester: &WidgetTester| {
2293                assert!(not_painted(
2294                    tester,
2295                    &[circle(slider_theme.disabled_thumb_color)]
2296                ));
2297                assert!(not_painted(
2298                    tester,
2299                    &[rrect(slider_theme.disabled_active_track_color)]
2300                ));
2301                assert!(not_painted(
2302                    tester,
2303                    &[rrect(slider_theme.disabled_inactive_track_color)]
2304                ));
2305                assert!(not_painted(
2306                    tester,
2307                    &[rrect(slider_theme.disabled_secondary_active_track_color)]
2308                ));
2309            };
2310
2311            tester.pump_widget(build_app(Args::default()));
2312
2313            // Check default theme for enabled widget.
2314            assert!(painted(
2315                tester,
2316                &tracks(
2317                    slider_theme.inactive_track_color,
2318                    slider_theme.active_track_color,
2319                    slider_theme.secondary_active_track_color
2320                )
2321            ));
2322            assert!(painted(
2323                tester,
2324                &[PaintCall::shadow(Some(Color::new(0xff000000)))]
2325            ));
2326            assert!(painted(tester, &[circle(slider_theme.thumb_color)]));
2327            no_disabled_tracks(tester);
2328            assert!(not_painted(
2329                tester,
2330                &[circle(slider_theme.active_tick_mark_color)]
2331            ));
2332            assert!(not_painted(
2333                tester,
2334                &[circle(slider_theme.inactive_tick_mark_color)]
2335            ));
2336
2337            // Test setting only the activeColor.
2338            tester.pump_widget(build_app(Args {
2339                active_color: Some(CUSTOM_COLOR1),
2340                ..Args::default()
2341            }));
2342            assert!(painted(
2343                tester,
2344                &tracks(
2345                    slider_theme.inactive_track_color,
2346                    Some(CUSTOM_COLOR1),
2347                    slider_theme.secondary_active_track_color
2348                )
2349            ));
2350            assert!(painted(tester, &[PaintCall::shadow(Some(Colors::BLACK))]));
2351            assert!(painted(tester, &[circle(Some(CUSTOM_COLOR1))]));
2352            assert!(not_painted(tester, &[circle(slider_theme.thumb_color)]));
2353            no_disabled_tracks(tester);
2354
2355            // Test setting only the inactiveColor.
2356            tester.pump_widget(build_app(Args {
2357                inactive_color: Some(CUSTOM_COLOR1),
2358                ..Args::default()
2359            }));
2360            assert!(painted(
2361                tester,
2362                &tracks(
2363                    Some(CUSTOM_COLOR1),
2364                    slider_theme.active_track_color,
2365                    slider_theme.secondary_active_track_color
2366                )
2367            ));
2368            assert!(painted(tester, &[PaintCall::shadow(Some(Colors::BLACK))]));
2369            assert!(painted(tester, &[circle(slider_theme.thumb_color)]));
2370            no_disabled_tracks(tester);
2371
2372            // Test setting only the secondaryActiveColor.
2373            tester.pump_widget(build_app(Args {
2374                secondary_active_color: Some(CUSTOM_COLOR1),
2375                ..Args::default()
2376            }));
2377            assert!(painted(
2378                tester,
2379                &tracks(
2380                    slider_theme.inactive_track_color,
2381                    slider_theme.active_track_color,
2382                    Some(CUSTOM_COLOR1)
2383                )
2384            ));
2385            assert!(painted(tester, &[PaintCall::shadow(Some(Colors::BLACK))]));
2386            assert!(painted(tester, &[circle(slider_theme.thumb_color)]));
2387            no_disabled_tracks(tester);
2388
2389            // Test setting both activeColor, inactiveColor, and secondaryActiveColor.
2390            tester.pump_widget(build_app(Args {
2391                active_color: Some(CUSTOM_COLOR1),
2392                inactive_color: Some(CUSTOM_COLOR2),
2393                secondary_active_color: Some(CUSTOM_COLOR3),
2394                ..Args::default()
2395            }));
2396            assert!(painted(
2397                tester,
2398                &tracks(
2399                    Some(CUSTOM_COLOR2),
2400                    Some(CUSTOM_COLOR1),
2401                    Some(CUSTOM_COLOR3)
2402                )
2403            ));
2404            assert!(painted(tester, &[PaintCall::shadow(Some(Colors::BLACK))]));
2405            assert!(painted(tester, &[circle(Some(CUSTOM_COLOR1))]));
2406            assert!(not_painted(tester, &[circle(slider_theme.thumb_color)]));
2407            no_disabled_tracks(tester);
2408
2409            // Test colors for discrete slider.
2410            tester.pump_widget(build_app(Args {
2411                divisions: Some(3),
2412                ..Args::default()
2413            }));
2414            assert!(painted(
2415                tester,
2416                &tracks(
2417                    slider_theme.inactive_track_color,
2418                    slider_theme.active_track_color,
2419                    slider_theme.secondary_active_track_color
2420                )
2421            ));
2422            assert!(painted(
2423                tester,
2424                &[
2425                    circle(slider_theme.active_tick_mark_color),
2426                    circle(slider_theme.active_tick_mark_color),
2427                    circle(slider_theme.inactive_tick_mark_color),
2428                    circle(slider_theme.inactive_tick_mark_color),
2429                    PaintCall::shadow(Some(Colors::BLACK)),
2430                    circle(slider_theme.thumb_color),
2431                ]
2432            ));
2433            no_disabled_tracks(tester);
2434
2435            // Test colors for discrete slider with inactiveColor and activeColor set.
2436            tester.pump_widget(build_app(Args {
2437                active_color: Some(CUSTOM_COLOR1),
2438                inactive_color: Some(CUSTOM_COLOR2),
2439                secondary_active_color: Some(CUSTOM_COLOR3),
2440                divisions: Some(3),
2441                ..Args::default()
2442            }));
2443            assert!(painted(
2444                tester,
2445                &tracks(
2446                    Some(CUSTOM_COLOR2),
2447                    Some(CUSTOM_COLOR1),
2448                    Some(CUSTOM_COLOR3)
2449                )
2450            ));
2451            assert!(painted(
2452                tester,
2453                &[
2454                    circle(Some(CUSTOM_COLOR2)),
2455                    circle(Some(CUSTOM_COLOR2)),
2456                    circle(Some(CUSTOM_COLOR1)),
2457                    circle(Some(CUSTOM_COLOR1)),
2458                    PaintCall::shadow(Some(Colors::BLACK)),
2459                    circle(Some(CUSTOM_COLOR1)),
2460                ]
2461            ));
2462            assert!(not_painted(tester, &[circle(slider_theme.thumb_color)]));
2463            no_disabled_tracks(tester);
2464            assert!(not_painted(
2465                tester,
2466                &[circle(slider_theme.active_tick_mark_color)]
2467            ));
2468            assert!(not_painted(
2469                tester,
2470                &[circle(slider_theme.inactive_tick_mark_color)]
2471            ));
2472
2473            // Test default theme for disabled widget.
2474            tester.pump_widget(build_app(Args {
2475                disabled: true,
2476                ..Args::default()
2477            }));
2478            tester.pump_and_settle();
2479            assert!(painted(
2480                tester,
2481                &tracks(
2482                    slider_theme.disabled_inactive_track_color,
2483                    slider_theme.disabled_active_track_color,
2484                    slider_theme.disabled_secondary_active_track_color
2485                )
2486            ));
2487            assert!(painted(
2488                tester,
2489                &[
2490                    PaintCall::shadow(Some(Colors::BLACK)),
2491                    circle(slider_theme.disabled_thumb_color)
2492                ]
2493            ));
2494            assert!(not_painted(tester, &[circle(slider_theme.thumb_color)]));
2495            // These 2 colors are too close to distinguish.
2496            assert!(not_painted(
2497                tester,
2498                &[rrect(slider_theme.inactive_track_color)]
2499            ));
2500            assert!(not_painted(
2501                tester,
2502                &[rrect(slider_theme.secondary_active_track_color)]
2503            ));
2504
2505            // Test default theme for disabled discrete widget.
2506            tester.pump_widget(build_app(Args {
2507                divisions: Some(3),
2508                disabled: true,
2509                ..Args::default()
2510            }));
2511            assert!(painted(
2512                tester,
2513                &[
2514                    circle(slider_theme.disabled_active_tick_mark_color),
2515                    circle(slider_theme.disabled_active_tick_mark_color),
2516                    circle(slider_theme.disabled_inactive_tick_mark_color),
2517                    circle(slider_theme.disabled_inactive_tick_mark_color),
2518                    PaintCall::shadow(Some(Colors::BLACK)),
2519                    circle(slider_theme.disabled_thumb_color),
2520                ]
2521            ));
2522            assert!(not_painted(tester, &[circle(slider_theme.thumb_color)]));
2523            // These 2 colors are too close to distinguish.
2524            assert!(not_painted(
2525                tester,
2526                &[rrect(slider_theme.inactive_track_color)]
2527            ));
2528            assert!(not_painted(
2529                tester,
2530                &[rrect(slider_theme.secondary_active_track_color)]
2531            ));
2532            assert!(not_painted(
2533                tester,
2534                &[circle(slider_theme.active_tick_mark_color)]
2535            ));
2536            assert!(not_painted(
2537                tester,
2538                &[circle(slider_theme.inactive_tick_mark_color)]
2539            ));
2540
2541            // Test setting the activeColor, inactiveColor and secondaryActiveColor for disabled
2542            // widget.
2543            tester.pump_widget(build_app(Args {
2544                active_color: Some(CUSTOM_COLOR1),
2545                inactive_color: Some(CUSTOM_COLOR2),
2546                secondary_active_color: Some(CUSTOM_COLOR3),
2547                disabled: true,
2548                ..Args::default()
2549            }));
2550            assert!(painted(
2551                tester,
2552                &tracks(
2553                    slider_theme.disabled_inactive_track_color,
2554                    slider_theme.disabled_active_track_color,
2555                    slider_theme.disabled_secondary_active_track_color
2556                )
2557            ));
2558            assert!(painted(
2559                tester,
2560                &[circle(slider_theme.disabled_thumb_color)]
2561            ));
2562            assert!(not_painted(tester, &[circle(slider_theme.thumb_color)]));
2563            // These colors are too close to distinguish.
2564            assert!(not_painted(
2565                tester,
2566                &[rrect(slider_theme.inactive_track_color)]
2567            ));
2568            assert!(not_painted(
2569                tester,
2570                &[rrect(slider_theme.secondary_active_track_color)]
2571            ));
2572
2573            // Test that the default value indicator has the right colors.
2574            tester.pump_widget(build_app(Args {
2575                divisions: Some(3),
2576                ..Args::default()
2577            }));
2578            let center = slider_rect(tester).center();
2579            let mut gesture = TestPointer::touch(1);
2580            tester.down(&mut gesture, center);
2581            // Wait for value indicator animation to finish.
2582            tester.pump_and_settle();
2583            assert_eq!(value.get(), 2.0 / 3.0);
2584            assert_paints(
2585                &tester.painted_ops_deep(overlay_render(tester)),
2586                &[
2587                    PaintCall::path(slider_theme.value_indicator_color),
2588                    PaintCall::Paragraph,
2589                ],
2590            );
2591            tester.up(&gesture);
2592            // Wait for value indicator animation to finish.
2593            tester.pump_and_settle();
2594
2595            // Testing the custom colors are used for the indicator.
2596            tester.pump_widget(build_app(Args {
2597                active_color: Some(CUSTOM_COLOR1),
2598                inactive_color: Some(CUSTOM_COLOR2),
2599                divisions: Some(3),
2600                ..Args::default()
2601            }));
2602            let center = slider_rect(tester).center();
2603            let mut gesture = TestPointer::touch(2);
2604            tester.down(&mut gesture, center);
2605            // Wait for value indicator animation to finish.
2606            tester.pump_and_settle();
2607            assert_eq!(value.get(), 2.0 / 3.0);
2608            assert_paints(
2609                &tester.painted_ops_deep(overlay_render(tester)),
2610                &[
2611                    rrect(Some(Color::new(0xfffafafa))),
2612                    rrect(Some(CUSTOM_COLOR2)), // Inactive track
2613                    rrect(Some(CUSTOM_COLOR1)), // Active track
2614                    circle(Some(CUSTOM_COLOR1.with_opacity(0.12))), // overlay
2615                    circle(Some(CUSTOM_COLOR2)), // 1st tick mark
2616                    circle(Some(CUSTOM_COLOR2)), // 2nd tick mark
2617                    circle(Some(CUSTOM_COLOR2)), // 3rd tick mark
2618                    circle(Some(CUSTOM_COLOR1)), // 4th tick mark
2619                    PaintCall::shadow(Some(Colors::BLACK)),
2620                    circle(Some(CUSTOM_COLOR1)), // thumb
2621                    PaintCall::path(slider_theme.value_indicator_color), // indicator
2622                ],
2623            );
2624            tester.up(&gesture);
2625        });
2626    }
2627
2628    // 'Slider can use theme overlay with material states'.
2629    #[test]
2630    fn a_slider_can_use_a_theme_overlay_with_material_states() {
2631        test_widgets(|tester| {
2632            let base_theme = ThemeData::builder()
2633                .platform(TargetPlatform::Android)
2634                .primary_swatch(Colors::BLUE)
2635                .build(&tester.cell.borrow());
2636            let brown = Colors::BROWN.get(&500).expect("a swatch shade");
2637            let slider_theme = base_theme.slider_theme.copy_with().overlay_color(
2638                waft_widgets::WidgetStateColor::resolve_with(move |states| {
2639                    if states.contains(&waft_widgets::WidgetState::Focused) {
2640                        return brown;
2641                    }
2642
2643                    Colors::TRANSPARENT
2644                }),
2645            );
2646            let focus_node = waft_widgets::FocusNode::new(&mut tester.cell.borrow_mut())
2647                .into_erased::<waft_widgets::AnyFocusNode>();
2648            tester.set_highlight_strategy(waft_widgets::FocusHighlightStrategy::AlwaysTraditional);
2649            let value = Rc::new(Cell::new(0.5));
2650            let theme = ThemeData::builder()
2651                .slider_theme(slider_theme)
2652                .build(&tester.cell.borrow());
2653            let build_app = |enabled: bool| {
2654                let value = Rc::clone(&value);
2655                material_app(
2656                    theme.clone(),
2657                    Material::new()
2658                        .child(Center::new().child(StatefulBuilder::new({
2659                            let focus_node = focus_node.clone();
2660                            move |_app, _context, set_state| {
2661                                let on_changed_value = Rc::clone(&value);
2662                                let on_changed: Option<ValueChanged<f64>> = enabled.then(|| {
2663                                    Rc::new(move |app: &mut App, new_value: f64| {
2664                                        let value = Rc::clone(&on_changed_value);
2665                                        set_state(app, &mut |_app| value.set(new_value));
2666                                    }) as ValueChanged<f64>
2667                                });
2668                                Slider::new(value.get(), on_changed)
2669                                    .autofocus(true)
2670                                    .focus_node(focus_node.clone())
2671                                    .into_widget()
2672                            }
2673                        })))
2674                        .into_widget(),
2675                )
2676            };
2677            tester.pump_widget(build_app(true));
2678
2679            // Check that the overlay shows when focused.
2680            tester.pump_and_settle();
2681            assert!(focus_node.has_primary_focus(&tester.cell.borrow()));
2682            assert!(paints_circle(tester, slider_render(tester), brown));
2683
2684            // Check that the overlay does not show when focused and disabled.
2685            tester.pump_widget(build_app(false));
2686            tester.pump_and_settle();
2687            assert!(!focus_node.has_primary_focus(&tester.cell.borrow()));
2688            assert!(!paints_circle(tester, slider_render(tester), brown));
2689            focus_node.dispose(&mut tester.cell.borrow_mut());
2690        });
2691    }
2692
2693    /// Dart's `RoundedRectSliderTrackShapeWithCustomAdditionalActiveTrackHeight`: a rounded
2694    /// rect track that paints with its own `additionalActiveTrackHeight`.
2695    #[derive(Debug)]
2696    struct RoundedRectSliderTrackShapeWithCustomAdditionalActiveTrackHeight {
2697        additional_active_track_height: f64,
2698    }
2699
2700    impl SliderTrackShape for RoundedRectSliderTrackShapeWithCustomAdditionalActiveTrackHeight {
2701        fn get_preferred_rect(
2702            &self,
2703            app: &App,
2704            parent_box: waft_rendering::AnyRenderBox,
2705            offset: Offset,
2706            slider_theme: &SliderThemeData,
2707            is_enabled: Option<bool>,
2708            is_discrete: Option<bool>,
2709        ) -> waft_embedder::Rect {
2710            SliderTrackShape::get_preferred_rect(
2711                &RoundedRectSliderTrackShape::new(),
2712                app,
2713                parent_box,
2714                offset,
2715                slider_theme,
2716                is_enabled,
2717                is_discrete,
2718            )
2719        }
2720
2721        fn paint(
2722            &self,
2723            app: &mut App,
2724            context: &mut waft_rendering::PaintingContext,
2725            offset: Offset,
2726            parent_box: waft_rendering::AnyRenderBox,
2727            slider_theme: &SliderThemeData,
2728            enable_animation: waft_animation::AnyAnimation<f64>,
2729            thumb_center: Offset,
2730            secondary_offset: Option<Offset>,
2731            _is_enabled: Option<bool>,
2732            _is_discrete: Option<bool>,
2733            text_direction: TextDirection,
2734        ) {
2735            RoundedRectSliderTrackShape::new().paint(
2736                app,
2737                context,
2738                offset,
2739                parent_box,
2740                slider_theme,
2741                enable_animation,
2742                text_direction,
2743                thumb_center,
2744                secondary_offset,
2745                false,
2746                false,
2747                self.additional_active_track_height,
2748            );
2749        }
2750
2751        fn is_rounded(&self) -> bool {
2752            true
2753        }
2754
2755        fn as_any(&self) -> &dyn std::any::Any {
2756            self
2757        }
2758    }
2759
2760    // 'activeTrackRadius is taken into account when painting the border of the active track'.
2761    #[test]
2762    fn the_active_track_radius_counts_when_painting_the_active_track_border() {
2763        test_widgets(|tester| {
2764            let slider_theme = default_theme(tester)
2765                .slider_theme
2766                .copy_with()
2767                .track_shape(Rc::new(
2768                    RoundedRectSliderTrackShapeWithCustomAdditionalActiveTrackHeight {
2769                        additional_active_track_height: 10.0,
2770                    },
2771                ));
2772            let app = build_app(tester, slider_theme, 0.5, None, true);
2773            tester.pump_widget(app);
2774            tester.pump_and_settle();
2775            let center = slider_rect(tester).center();
2776            let mut gesture = TestPointer::touch(1);
2777            tester.down(&mut gesture, center);
2778            assert!(render_paints(
2779                tester,
2780                slider_render(tester),
2781                &[
2782                    // Inactive track.
2783                    PaintCall::rrect_at(
2784                        RRect::from_ltrbr(398.0, 298.0, 776.0, 302.0, Radius::circular(2.0)),
2785                        None
2786                    ),
2787                    // Active track.
2788                    PaintCall::rrect_at(
2789                        RRect::from_ltrbr(24.0, 293.0, 402.0, 307.0, Radius::circular(7.0)),
2790                        None
2791                    ),
2792                ]
2793            ));
2794
2795            // Finish gesture to release resources.
2796            tester.up(&gesture);
2797            tester.pump_and_settle();
2798        });
2799    }
2800
2801    /// The body Dart's two 'Default value indicator color' cases share: a discrete slider at
2802    /// 0.5 labelled '1' in a `Row`, pressed; `overlay` is what the `Overlay` paints, from the
2803    /// `Material`'s background through the indicator.
2804    fn default_value_indicator_color(
2805        tester: &mut WidgetTester,
2806        theme: fn(&WidgetTester) -> ThemeData,
2807        overlay: &[PaintCall],
2808    ) {
2809        let theme = theme(tester);
2810        tester.pump_widget(material_app(
2811            theme,
2812            waft_widgets::Directionality::new(
2813                TextDirection::Ltr,
2814                waft_widgets::MediaQuery::new(
2815                    waft_widgets::MediaQueryData::default()
2816                        .text_scaler(waft_painting::TextScaler::NO_SCALING),
2817                    Material::new().child(waft_widgets::Row::new().children(vec![
2818                        waft_widgets::Expanded::new(
2819                            Slider::new(0.5, noop()).label("1").divisions(3),
2820                        )
2821                        .into_widget(),
2822                    ])),
2823                )
2824                .into_widget(),
2825            )
2826            .into_widget(),
2827        ));
2828
2829        let center = slider_rect(tester).center();
2830        let mut gesture = TestPointer::touch(1);
2831        tester.down(&mut gesture, center);
2832        // Wait for value indicator animation to finish.
2833        tester.pump_and_settle();
2834        assert_paints(&tester.painted_ops_deep(overlay_render(tester)), overlay);
2835
2836        // Finish gesture to release resources.
2837        tester.up(&gesture);
2838        tester.pump_and_settle();
2839    }
2840
2841    // 'Default value indicator color'.
2842    #[test]
2843    #[expect(deprecated, reason = "Dart's case reads the deprecated `value`")]
2844    fn the_default_value_indicator_color() {
2845        test_widgets(|tester| {
2846            let primary = ThemeData::builder()
2847                .platform(TargetPlatform::Android)
2848                .build(&tester.cell.borrow())
2849                .color_scheme
2850                .primary();
2851            default_value_indicator_color(
2852                tester,
2853                |tester| {
2854                    ThemeData::builder()
2855                        .platform(TargetPlatform::Android)
2856                        .build(&tester.cell.borrow())
2857                },
2858                &[
2859                    PaintCall::rrect(Some(Color::new(0xfffef7ff))),
2860                    PaintCall::rrect(Some(Color::new(0xffe6e0e9))),
2861                    PaintCall::rrect(Some(Color::new(0xff6750a4))),
2862                    PaintCall::path(Some(Color::new(primary.value()))),
2863                ],
2864            );
2865        });
2866    }
2867
2868    // 'Material 2' 'Default value indicator color'.
2869    #[test]
2870    fn material2_the_default_value_indicator_color() {
2871        test_widgets(|tester| {
2872            default_value_indicator_color(
2873                tester,
2874                |tester| {
2875                    ThemeData::builder()
2876                        .use_material3(false)
2877                        .platform(TargetPlatform::Android)
2878                        .build(&tester.cell.borrow())
2879                },
2880                &[
2881                    PaintCall::rrect(Some(Color::new(0xfffafafa))),
2882                    PaintCall::rrect(Some(Color::new(0x3d2196f3))),
2883                    PaintCall::rrect(Some(Color::new(0xff2196f3))),
2884                    // Test that the value indicator text is painted with the correct color.
2885                    PaintCall::path(Some(Color::new(0xf55f5f5f))),
2886                ],
2887            );
2888        });
2889    }
2890
2891    /// Dart's `_buildApp` with its `divisions`: a slider at `value` under `slider_theme` in a
2892    /// scaffold's body.
2893    fn build_discrete_app(
2894        tester: &WidgetTester,
2895        slider_theme: SliderThemeData,
2896        value: f64,
2897        divisions: i32,
2898    ) -> WidgetRef {
2899        let slider = Slider::new(value, noop())
2900            .label(format!("{value}"))
2901            .divisions(divisions);
2902        material_app(
2903            default_theme(tester),
2904            Scaffold::new()
2905                .body(Center::new().child(SliderTheme::new(slider_theme, slider)))
2906                .into_widget(),
2907        )
2908    }
2909
2910    /// How many ops of `of`'s kind `render` records: Dart's `paintsExactlyCountTimes`.
2911    /// The render object that paints the slider's value indicator in the overlay.
2912    fn value_indicator_box(tester: &WidgetTester) -> waft_rendering::AnyRenderObject {
2913        tester
2914            .first::<crate::slider::RenderValueIndicator>()
2915            .as_render_object(&tester.cell.borrow())
2916    }
2917
2918    /// The body of Dart's two 'skips all painting at zero scale' cases: a slider showing only
2919    /// its value indicator, which paints nothing on the press's first frame and one path the
2920    /// next.
2921    fn value_indicator_skips_painting_at_zero_scale(
2922        tester: &mut WidgetTester,
2923        configure: fn(SliderThemeData) -> SliderThemeData,
2924        check_material: bool,
2925    ) {
2926        use crate::slider_parts::SliderTickMarkShape;
2927        use crate::slider_value_indicator_shape::SliderComponentShape;
2928        // Pump a slider with just a value indicator.
2929        let slider_theme = configure(
2930            default_theme(tester)
2931                .slider_theme
2932                .copy_with()
2933                .track_height(0.0)
2934                .overlay_shape(<dyn SliderComponentShape>::no_overlay())
2935                .thumb_shape(<dyn SliderComponentShape>::no_thumb())
2936                .tick_mark_shape(<dyn SliderTickMarkShape>::no_tick_mark()),
2937        );
2938        let app = build_discrete_app(tester, slider_theme, 0.5, 4);
2939        tester.pump_widget(app);
2940
2941        // Tap the center of the track to kick off the animation of the value indicator.
2942        let center = slider_rect(tester).center();
2943        let mut gesture = TestPointer::touch(1);
2944        tester.down(&mut gesture, center);
2945
2946        // Nothing to paint at scale 0.
2947        tester.pump();
2948        if check_material {
2949            assert_eq!(
2950                count_calls(
2951                    &tester.painted_ops(slider_render(tester)),
2952                    CanvasMethod::DrawRect
2953                ),
2954                0
2955            );
2956            assert_eq!(
2957                count_calls(
2958                    &tester.painted_ops(slider_render(tester)),
2959                    CanvasMethod::DrawCircle
2960                ),
2961                0
2962            );
2963        }
2964        assert_eq!(
2965            count_calls(
2966                &tester.painted_ops(value_indicator_box(tester)),
2967                CanvasMethod::DrawPath
2968            ),
2969            0
2970        );
2971
2972        // Painting a path for the value indicator.
2973        tester.pump_by(Duration::from_millis(16));
2974        assert_eq!(
2975            count_calls(
2976                &tester.painted_ops(value_indicator_box(tester)),
2977                CanvasMethod::DrawPath
2978            ),
2979            1
2980        );
2981
2982        tester.up(&gesture);
2983    }
2984
2985    // 'PaddleSliderValueIndicatorShape skips all painting at zero scale'.
2986    #[test]
2987    #[expect(
2988        deprecated,
2989        reason = "Dart's case sets the deprecated `ShowValueIndicator.always`"
2990    )]
2991    fn the_paddle_value_indicator_skips_all_painting_at_zero_scale() {
2992        test_widgets(|tester| {
2993            value_indicator_skips_painting_at_zero_scale(
2994                tester,
2995                |theme| {
2996                    theme
2997                        .show_value_indicator(ShowValueIndicator::Always)
2998                        .value_indicator_shape(Rc::new(PaddleSliderValueIndicatorShape::new()))
2999                },
3000                true,
3001            );
3002        });
3003    }
3004
3005    // 'Default slider value indicator shape skips all painting at zero scale'.
3006    #[test]
3007    fn the_default_value_indicator_shape_skips_all_painting_at_zero_scale() {
3008        test_widgets(|tester| {
3009            value_indicator_skips_painting_at_zero_scale(
3010                tester,
3011                |theme| theme.show_value_indicator(ShowValueIndicator::OnDrag),
3012                false,
3013            );
3014        });
3015    }
3016
3017    /// Dart's `_buildApp(sliderTheme, value:)`, its rounded-rect track's painted rrects in
3018    /// order.
3019    fn rounded_rect_tracks(tester: &mut WidgetTester, value: f64, rrects: &[RRect]) -> bool {
3020        use crate::slider_parts::RoundedRectSliderTrackShape;
3021        let slider_theme =
3022            SliderThemeData::new().track_shape(Rc::new(RoundedRectSliderTrackShape::new()));
3023        let app = build_app(tester, slider_theme, value, None, true);
3024        tester.pump_widget(app);
3025        let calls: Vec<PaintCall> = rrects
3026            .iter()
3027            .map(|rrect| PaintCall::rrect_at(*rrect, None))
3028            .collect();
3029        render_paints(tester, slider_render(tester), &calls)
3030    }
3031
3032    // 'RoundedRectSliderTrackShape' 'Only draw active track if thumb center is higher than
3033    // trackRect.left and track radius'.
3034    #[test]
3035    fn a_rounded_rect_track_draws_its_active_track_only_past_the_left_radius() {
3036        test_widgets(|tester| {
3037            assert!(rounded_rect_tracks(
3038                tester,
3039                0.0,
3040                // Inactive track.
3041                &[RRect::from_ltrbr(
3042                    22.0,
3043                    298.0,
3044                    776.0,
3045                    302.0,
3046                    Radius::circular(2.0)
3047                )]
3048            ));
3049
3050            assert!(rounded_rect_tracks(
3051                tester,
3052                0.025,
3053                &[
3054                    // Inactive track.
3055                    RRect::from_ltrbr(40.8, 298.0, 776.0, 302.0, Radius::circular(2.0)),
3056                    // Active track.
3057                    RRect::from_ltrbr(24.0, 297.0, 44.8, 303.0, Radius::circular(3.0)),
3058                ]
3059            ));
3060        });
3061    }
3062
3063    // 'RoundedRectSliderTrackShape' 'Only draw inactive track if thumb center is lower than
3064    // trackRect.right and track radius'.
3065    #[test]
3066    fn a_rounded_rect_track_draws_its_inactive_track_only_before_the_right_radius() {
3067        test_widgets(|tester| {
3068            assert!(rounded_rect_tracks(
3069                tester,
3070                1.0,
3071                // Active track.
3072                &[RRect::from_ltrbr(
3073                    24.0,
3074                    297.0,
3075                    778.0,
3076                    303.0,
3077                    Radius::circular(3.0)
3078                )]
3079            ));
3080
3081            assert!(rounded_rect_tracks(
3082                tester,
3083                0.975,
3084                &[
3085                    // Inactive track.
3086                    RRect::from_ltrbr(755.2, 298.0, 776.0, 302.0, Radius::circular(2.0)),
3087                    // Active track.
3088                    RRect::from_ltrbr(24.0, 297.0, 759.2, 303.0, Radius::circular(3.0)),
3089                ]
3090            ));
3091        });
3092    }
3093
3094    // 'RoundedRectSliderTrackShape' 'Active track is painted on top of the inactive track in
3095    // RTL'.
3096    #[test]
3097    fn the_active_track_is_painted_on_top_of_the_inactive_track_in_rtl() {
3098        test_widgets(|tester| {
3099            use crate::slider_parts::RoundedRectSliderTrackShape;
3100            // Regression test for https://github.com/flutter/flutter/issues/194278
3101            let theme = default_theme(tester);
3102            tester.pump_widget(material_app(
3103                theme,
3104                waft_widgets::Directionality::new(
3105                    TextDirection::Rtl,
3106                    Material::new().child(
3107                        Center::new().child(SliderTheme::new(
3108                            SliderThemeData::new()
3109                                .track_shape(Rc::new(RoundedRectSliderTrackShape::new())),
3110                            Slider::new(0.5, noop()),
3111                        )),
3112                    ),
3113                )
3114                .into_widget(),
3115            ));
3116
3117            // Both track segments extend past the thumb center by half of the track
3118            // height, so the inactive track must be painted first for the rounded end
3119            // of the active track not to be covered by it.
3120            assert!(render_paints(
3121                tester,
3122                slider_render(tester),
3123                &[
3124                    // Inactive track.
3125                    PaintCall::rrect_at(
3126                        RRect::from_ltrbr(24.0, 298.0, 402.0, 302.0, Radius::circular(2.0)),
3127                        None
3128                    ),
3129                    // Active track.
3130                    PaintCall::rrect_at(
3131                        RRect::from_ltrbr(398.0, 297.0, 776.0, 303.0, Radius::circular(3.0)),
3132                        None
3133                    ),
3134                ]
3135            ));
3136        });
3137    }
3138
3139    // 'SliderThemeData.padding can override the default Slider padding'.
3140    #[test]
3141    fn slider_theme_data_padding_overrides_the_default_slider_padding() {
3142        test_widgets(|tester| {
3143            use waft_painting::{EdgeInsets, EdgeInsetsDirectional};
3144            let build_slider = |tester: &WidgetTester, padding: EdgeInsetsGeometry| {
3145                let theme = ThemeData::builder()
3146                    .slider_theme(SliderThemeData::new().padding(padding))
3147                    .build(&tester.cell.borrow());
3148                material_app(
3149                    theme,
3150                    Material::new()
3151                        .child(Center::new().child(
3152                            waft_widgets::IntrinsicHeight::new().child(Slider::new(0.5, noop())),
3153                        ))
3154                        .into_widget(),
3155                )
3156            };
3157            let slider_render_box_size = |tester: &WidgetTester| {
3158                tester
3159                    .first::<crate::slider::RenderSlider>()
3160                    .size(&tester.cell.borrow())
3161            };
3162            let tracks = |inactive: (f64, f64, f64, f64), active: (f64, f64, f64, f64)| {
3163                [
3164                    // Inactive track.
3165                    PaintCall::rrect_at(
3166                        RRect::from_ltrbr(
3167                            inactive.0,
3168                            inactive.1,
3169                            inactive.2,
3170                            inactive.3,
3171                            Radius::circular(2.0),
3172                        ),
3173                        None,
3174                    ),
3175                    // Active track.
3176                    PaintCall::rrect_at(
3177                        RRect::from_ltrbr(
3178                            active.0,
3179                            active.1,
3180                            active.2,
3181                            active.3,
3182                            Radius::circular(3.0),
3183                        ),
3184                        None,
3185                    ),
3186                ]
3187            };
3188
3189            // Test Slider height and tracks spacing with zero padding.
3190            let app = build_slider(tester, EdgeInsets::ZERO.into());
3191            tester.pump_widget(app);
3192            tester.pump_and_settle();
3193
3194            // The height equals to the default thumb height.
3195            assert_eq!(slider_render_box_size(tester), Size::new(800.0, 20.0));
3196            assert!(render_paints(
3197                tester,
3198                slider_render(tester),
3199                &tracks((398.0, 8.0, 800.0, 12.0), (0.0, 7.0, 402.0, 13.0))
3200            ));
3201
3202            // Test Slider height and tracks spacing with directional padding.
3203            const START_PADDING: f64 = 100.0;
3204            const END_PADDING: f64 = 20.0;
3205            let app = build_slider(
3206                tester,
3207                EdgeInsetsDirectional::only(START_PADDING, 0.0, END_PADDING, 0.0).into(),
3208            );
3209            tester.pump_widget(app);
3210            tester.pump_and_settle();
3211
3212            assert_eq!(
3213                slider_render_box_size(tester),
3214                Size::new(800.0 - START_PADDING - END_PADDING, 20.0)
3215            );
3216            assert!(render_paints(
3217                tester,
3218                slider_render(tester),
3219                &tracks((338.0, 8.0, 680.0, 12.0), (0.0, 7.0, 342.0, 13.0))
3220            ));
3221
3222            // Test Slider height and tracks spacing with top and bottom padding.
3223            const TOP_PADDING: f64 = 100.0;
3224            const BOTTOM_PADDING: f64 = 20.0;
3225            const TRACK_HEIGHT: f64 = 20.0;
3226            let app = build_slider(
3227                tester,
3228                EdgeInsetsDirectional::only(0.0, TOP_PADDING, 0.0, BOTTOM_PADDING).into(),
3229            );
3230            tester.pump_widget(app);
3231            tester.pump_and_settle();
3232
3233            assert_eq!(
3234                crate::slider::tests::slider_size(tester),
3235                Size::new(800.0, TOP_PADDING + TRACK_HEIGHT + BOTTOM_PADDING)
3236            );
3237            assert_eq!(slider_render_box_size(tester), Size::new(800.0, 20.0));
3238            assert!(render_paints(
3239                tester,
3240                slider_render(tester),
3241                &tracks((398.0, 8.0, 800.0, 12.0), (0.0, 7.0, 402.0, 13.0))
3242            ));
3243        });
3244    }
3245
3246    fn paints_circle_at(
3247        tester: &WidgetTester,
3248        render: waft_rendering::AnyRenderObject,
3249        x: f64,
3250        y: f64,
3251        color: Color,
3252    ) -> bool {
3253        paints(
3254            &tester.painted_ops(render),
3255            &[PaintCall::Circle {
3256                x: Some(x),
3257                y: Some(y),
3258                radius: None,
3259                color: Some(color),
3260                style: None,
3261            }],
3262        )
3263        .is_ok()
3264    }
3265
3266    // 'Slider with transparent track colors and custom track height can reach extreme ends'.
3267    #[test]
3268    fn a_slider_with_transparent_tall_tracks_reaches_its_extreme_ends() {
3269        test_widgets(|tester| {
3270            const SLIDER_PADDING: f64 = 24.0;
3271            let theme = ThemeData::builder()
3272                .slider_theme(
3273                    SliderThemeData::new()
3274                        .track_height(100.0)
3275                        .active_track_color(Colors::TRANSPARENT)
3276                        .inactive_track_color(Colors::TRANSPARENT),
3277                )
3278                .build(&tester.cell.borrow());
3279            let primary = theme.color_scheme.primary();
3280            let build_slider = |value: f64| {
3281                material_app(
3282                    theme.clone(),
3283                    Material::new()
3284                        .child(
3285                            SizedBox::new()
3286                                .width(300.0)
3287                                .child(Slider::new(value, noop())),
3288                        )
3289                        .into_widget(),
3290                )
3291            };
3292
3293            tester.pump_widget(build_slider(0.0));
3294            assert!(paints_circle_at(
3295                tester,
3296                slider_render(tester),
3297                SLIDER_PADDING,
3298                300.0,
3299                primary
3300            ));
3301
3302            tester.pump_widget(build_slider(1.0));
3303            assert!(paints_circle_at(
3304                tester,
3305                slider_render(tester),
3306                800.0 - SLIDER_PADDING,
3307                300.0,
3308                primary
3309            ));
3310        });
3311    }
3312    // Flutter's "Default SliderThemeData debugFillProperties".
3313    #[test]
3314    fn a_slider_theme_data_describes_nothing_by_default() {
3315        assert_eq!(
3316            waft_widgets::testing::describe_properties(|properties| {
3317                waft_foundation::Diagnosticable::debug_fill_properties(
3318                    &SliderThemeData::new(),
3319                    properties,
3320                )
3321            }),
3322            Vec::<String>::new()
3323        );
3324    }
3325}