Skip to main content

waft_material/
slider.rs

1//! Flutter counterpart: material_ui's `slider.dart`, with its part
2//! `generated/slider_defaults_m3.g.dart` in `generated/slider_defaults_m3.rs`.
3//!
4//! [`Slider`] builds the private leaf render object Dart calls `_RenderSlider`, a `RenderBox`
5//! with `RelayoutWhenSystemFontsChangeMixin`, and paints its value indicator through an
6//! `OverlayPortal` whose child is `_RenderValueIndicator`. The shapes paint with the label
7//! painter the render object owns: it lends the painter out of its arena slot for each shape
8//! call. The semantics configuration, its increase, decrease and focus actions, the
9//! accessibility focus callback and the semantic formatter's use wait with accessibility.
10
11use std::any::{Any, TypeId};
12use std::collections::HashMap;
13use std::fmt::{self, Debug};
14use std::rc::Rc;
15use std::time::Duration;
16use waft_widgets::{
17    ActionRef, BuildContext, CallbackAction, CompositedTransformFollower,
18    CompositedTransformTarget, Directionality, FocusNode, FocusNodeLeaf, FocusNodeRef,
19    FocusableActionDetector, GlobalKey, Intent, IntentRef, IntoWidget, KeyRef,
20    LeafRenderObjectWidget, MediaQuery, NavigationMode, OverlayPortal, OverlayPortalController,
21    Padding, RenderObjectWidget, ShortcutActivatorRef, ShortcutMap, SingleActivator, SizedBox,
22    State, StateData, StatefulWidget, TickerProviderStateMixin, TickerProviderStateMixinData,
23    WidgetRef, WidgetState, WidgetStateColor, WidgetStateMouseCursor, WidgetStateProperty,
24    WidgetStatePropertyAll, WidgetStatePropertyRef, WidgetStates, debug_check_has_media_query,
25};
26
27use waft_animation::{
28    AlwaysStoppedAnimation, Animation, AnimationBehavior, AnimationController, AnyAnimation,
29    CurvedAnimation, Curves,
30};
31use waft_cupertino::{CupertinoColors, CupertinoSlider};
32use waft_embedder::{
33    Color, FontWeight, Offset, Rect, Size, TargetPlatform, TextDirection, clamp_double,
34};
35use waft_foundation::{
36    App, DiagnosticPropertiesBuilder, DoubleProperty, FlagProperty, Handle, IntProperty, Listener,
37    ObjectFlagProperty, OptionRetained, Ref, StringProperty, Timer, ValueChanged,
38};
39use waft_gestures::{
40    DeviceGestureSettings, DragEndDetails, DragGestureRecognizer, DragStartDetails,
41    DragUpdateDetails, GestureArenaTeam, HorizontalDragGestureRecognizer, PointerEvent,
42    RecognizerLeaf, TapDownDetails, TapGestureRecognizer, TapUpDetails,
43};
44use waft_painting::{
45    ColorProperty, EdgeInsetsGeometry, K_DEFAULT_FONT_SIZE, PaintingBinding, TextPainter,
46    TextScaler, TextSpan, TextStyle,
47};
48use waft_rendering::{
49    AnyRenderObject, BoxConstraints, BoxHitTestEntry, LayerLink, PaintingContext, PipelineOwner,
50    RelayoutWhenSystemFontsChangeData, RelayoutWhenSystemFontsChangeMixin, RenderBox,
51    RenderBoxData, RenderHandle, RenderObject, RenderObjectBase, RenderObjectData,
52};
53use waft_scheduler::{SchedulerBinding, Ticker, TickerCallback, TickerProviderObject};
54use waft_services::{LogicalKeyboardKey, MouseCursorRef};
55
56use crate::colors::Colors;
57use crate::constants::K_RADIAL_REACTION_DURATION;
58use crate::debug::debug_check_has_material;
59use crate::generated::slider_defaults_m3::SliderDefaultsM3;
60use crate::slider_parts::SliderTickMarkShapeRef;
61use crate::slider_parts::SliderTrackShapeRef;
62use crate::slider_parts::{
63    DropSliderValueIndicatorShape, RoundSliderThumbShape, RoundSliderTickMarkShape,
64    RoundedRectSliderTrackShape, RoundedRectSliderValueIndicatorShape,
65};
66use crate::slider_theme::{
67    SemanticFormatterCallback, ShowValueIndicator, SliderTheme, SliderThemeData,
68    SliderThemeDataGetters,
69};
70use crate::slider_value_indicator_shape::SliderComponentShapeRef;
71use crate::slider_value_indicator_shape::{
72    RectangularSliderValueIndicatorShape, RoundSliderOverlayShape,
73};
74use crate::theme::Theme;
75use crate::theme_data_getters::DefaultsContext;
76use waft_painting::AnyColor;
77
78/// [`Slider`] uses this callback to paint the value indicator on the overlay.
79///
80/// Since the value indicator is painted on the Overlay; this method paints the
81/// value indicator in a `RenderBox` that appears in the `Overlay`.
82pub type PaintValueIndicator = Rc<dyn Fn(&mut App, &mut PaintingContext, Offset)>;
83
84#[derive(Clone, Copy, Debug, PartialEq, Eq)]
85enum SliderType {
86    Material,
87    Adaptive,
88}
89
90/// Possible ways for a user to interact with a [`Slider`].
91#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
92pub enum SliderInteraction {
93    /// Allows the user to interact with a [`Slider`] by tapping or sliding anywhere
94    /// on the track.
95    ///
96    /// Essentially all possible interactions are allowed.
97    ///
98    /// This is different from [`SliderInteraction::SlideOnly`] as when you try
99    /// to slide anywhere other than the thumb, the thumb will move to the first
100    /// point of contact.
101    TapAndSlide,
102
103    /// Allows the user to interact with a [`Slider`] by only tapping anywhere on
104    /// the track.
105    ///
106    /// Sliding interaction is ignored.
107    TapOnly,
108
109    /// Allows the user to interact with a [`Slider`] only by sliding anywhere on
110    /// the track.
111    ///
112    /// Tapping interaction is ignored.
113    SlideOnly,
114
115    /// Allows the user to interact with a [`Slider`] only by sliding the thumb.
116    ///
117    /// Tapping and sliding interactions on the track are ignored.
118    SlideThumb,
119}
120
121/// A Material Design slider.
122///
123/// Used to select from a range of values.
124///
125/// A slider can be used to select from either a continuous or a discrete set of
126/// values. The default is to use a continuous range of values from [`min`](Self::min) to
127/// [`max`](Self::max). To use discrete values, use a non-null value for
128/// [`divisions`](Self::divisions), which indicates the number of discrete intervals. For
129/// example, if [`min`](Self::min) is 0.0 and [`max`](Self::max) is 50.0 and
130/// [`divisions`](Self::divisions) is 5, then the slider can take on the discrete values 0.0,
131/// 10.0, 20.0, 30.0, 40.0, and 50.0.
132///
133/// The terms for the parts of a slider are:
134///
135///  * The "thumb", which is a shape that slides horizontally when the user
136///    drags it.
137///  * The "track", which is the line that the slider thumb slides along.
138///  * The "value indicator", which is a shape that pops up when the user
139///    is dragging the thumb to indicate the value being selected.
140///  * The "active" side of the slider is the side between the thumb and the
141///    minimum value.
142///  * The "inactive" side of the slider is the side between the thumb and the
143///    maximum value.
144///
145/// The slider will be disabled if [`on_changed`](Self::on_changed) is null or if the range
146/// given by [`min`](Self::min)..[`max`](Self::max) is empty (i.e. if [`min`](Self::min) is
147/// equal to [`max`](Self::max)).
148///
149/// The slider widget itself does not maintain any state. Instead, when the state
150/// of the slider changes, the widget calls the [`on_changed`](Self::on_changed) callback.
151/// Most widgets that use a slider will listen for the [`on_changed`](Self::on_changed)
152/// callback and rebuild the slider with a new [`value`](Self::value) to update the visual
153/// appearance of the slider. To know when the value starts to change, or when it is done
154/// changing, set the optional callbacks [`on_change_start`](Self::on_change_start) and/or
155/// [`on_change_end`](Self::on_change_end).
156///
157/// By default, a slider will be as wide as possible, centered vertically. When
158/// given unbounded constraints, it will attempt to make the track 144 pixels
159/// wide (with margins on each side) and will shrink-wrap vertically.
160///
161/// Requires one of its ancestors to be a `Material` widget.
162///
163/// Requires one of its ancestors to be a `MediaQuery` widget. Typically, these
164/// are introduced by the `MaterialApp` or `WidgetsApp` widget at the top of
165/// your application widget tree.
166///
167/// To determine how it should be displayed (e.g. colors, thumb shape, etc.),
168/// a slider uses the [`SliderThemeData`] available from either a [`SliderTheme`]
169/// widget or the `ThemeData::slider_theme` a `Theme` widget above it in the
170/// widget tree. You can also override some of the colors with the
171/// [`active_color`](Self::active_color) and [`inactive_color`](Self::inactive_color)
172/// properties, although more fine-grained control of the look is achieved using a
173/// [`SliderThemeData`].
174///
175/// Dart's constructor asserts run when the slider is turned into a `WidgetRef`
176/// (`into_widget`), once every setter has run.
177///
178/// See also:
179///
180///  * [`SliderTheme`] and [`SliderThemeData`] for information about controlling
181///    the visual appearance of the slider.
182///  * `Radio`, for selecting among a set of explicit values.
183///  * `Checkbox` and `Switch`, for toggling a particular value on or off.
184///  * <https://material.io/design/components/sliders.html>
185///  * `MediaQuery`, from which the text scale factor is obtained.
186#[derive(Clone)]
187pub struct Slider {
188    pub key: Option<KeyRef>,
189
190    /// The currently selected value for this slider.
191    ///
192    /// The slider's thumb is drawn at a position that corresponds to this value.
193    pub value: f64,
194
195    /// The secondary track value for this slider.
196    ///
197    /// If not null, a secondary track using [`secondary_active_color`](Self::secondary_active_color)
198    /// color is drawn between the thumb and this value, over the inactive track.
199    ///
200    /// If less than [`value`](Self::value), then the secondary track is not shown.
201    ///
202    /// It can be ideal for media scenarios such as showing the buffering progress
203    /// while the [`value`](Self::value) shows the play progress.
204    pub secondary_track_value: Option<f64>,
205
206    /// Called during a drag when the user is selecting a new value for the slider
207    /// by dragging.
208    ///
209    /// The slider passes the new value to the callback but does not actually
210    /// change state until the parent widget rebuilds the slider with the new
211    /// value.
212    ///
213    /// If null, the slider will be displayed as disabled.
214    ///
215    /// The callback provided to on_changed should update the state of the parent
216    /// `StatefulWidget` using the `State::set_state` method, so that the parent
217    /// gets rebuilt.
218    ///
219    /// See also:
220    ///
221    ///  * [`on_change_start`](Self::on_change_start) for a callback that is called when the
222    ///    user starts changing the value.
223    ///  * [`on_change_end`](Self::on_change_end) for a callback that is called when the user
224    ///    stops changing the value.
225    pub on_changed: Option<ValueChanged<f64>>,
226
227    /// Called when the user starts selecting a new value for the slider.
228    ///
229    /// This callback shouldn't be used to update the slider [`value`](Self::value) (use
230    /// [`on_changed`](Self::on_changed) for that), but rather to be notified when the user has
231    /// started selecting a new value by starting a drag or with a tap.
232    ///
233    /// The value passed will be the last [`value`](Self::value) that the slider had before the
234    /// change began.
235    ///
236    /// See also:
237    ///
238    ///  * [`on_change_end`](Self::on_change_end) for a callback that is called when the value
239    ///    change is complete.
240    pub on_change_start: Option<ValueChanged<f64>>,
241
242    /// Called when the user is done selecting a new value for the slider.
243    ///
244    /// This callback shouldn't be used to update the slider [`value`](Self::value) (use
245    /// [`on_changed`](Self::on_changed) for that), but rather to know when the user has
246    /// completed selecting a new [`value`](Self::value) by ending a drag or a click.
247    ///
248    /// See also:
249    ///
250    ///  * [`on_change_start`](Self::on_change_start) for a callback that is called when a
251    ///    value change begins.
252    pub on_change_end: Option<ValueChanged<f64>>,
253
254    /// The minimum value the user can select.
255    ///
256    /// Defaults to 0.0. Must be less than or equal to [`max`](Self::max).
257    ///
258    /// If the [`max`](Self::max) is equal to the [`min`](Self::min), then the slider is
259    /// disabled.
260    pub min: f64,
261
262    /// The maximum value the user can select.
263    ///
264    /// Defaults to 1.0. Must be greater than or equal to [`min`](Self::min).
265    ///
266    /// If the [`max`](Self::max) is equal to the [`min`](Self::min), then the slider is
267    /// disabled.
268    pub max: f64,
269
270    /// The number of discrete divisions.
271    ///
272    /// Typically used with [`label`](Self::label) to show the current discrete value.
273    ///
274    /// If null, the slider is continuous.
275    pub divisions: Option<i32>,
276
277    /// A label to show inside the value indicator above the slider's thumb.
278    ///
279    /// By default, the label is shown while dragging a discrete slider, where
280    /// [`divisions`](Self::divisions) is non-null. It can also be shown for a continuous
281    /// slider, where [`divisions`](Self::divisions) is null, by setting
282    /// [`show_value_indicator`](Self::show_value_indicator) to
283    /// [`ShowValueIndicator::OnlyForContinuous`], [`ShowValueIndicator::OnDrag`], or
284    /// [`ShowValueIndicator::AlwaysVisible`].
285    ///
286    /// If [`show_value_indicator`](Self::show_value_indicator) is null, the ambient
287    /// `SliderThemeData::show_value_indicator` determines when the label is shown.
288    ///
289    /// The label is rendered using the active `ThemeData`'s `TextTheme::body_large`
290    /// text style, with the theme data's `ColorScheme::on_primary` color. The
291    /// label's text style can be overridden with
292    /// `SliderThemeData::value_indicator_text_style`.
293    ///
294    /// If null, then the value indicator will not be displayed.
295    ///
296    /// Ignored if this slider is created with [`Slider::adaptive`].
297    ///
298    /// See also:
299    ///
300    ///  * `SliderComponentShape` for how to create a custom value indicator
301    ///    shape.
302    pub label: Option<String>,
303
304    /// The color to use for the portion of the slider track that is active.
305    ///
306    /// The "active" side of the slider is the side between the thumb and the
307    /// minimum value.
308    ///
309    /// If null, `SliderThemeData::active_track_color` of the ambient
310    /// [`SliderTheme`] is used. If that is null, `ColorScheme::primary` of the
311    /// surrounding `ThemeData` is used.
312    ///
313    /// Using a [`SliderTheme`] gives much more fine-grained control over the
314    /// appearance of various components of the slider.
315    pub active_color: Option<Color>,
316
317    /// The color for the inactive portion of the slider track.
318    ///
319    /// The "inactive" side of the slider is the side between the thumb and the
320    /// maximum value.
321    ///
322    /// If null, `SliderThemeData::inactive_track_color` of the ambient [`SliderTheme`]
323    /// is used. If [`year2023`](Self::year2023) is false and `ThemeData::use_material3` is
324    /// true, then `ColorScheme::secondary_container` is used and if
325    /// `ThemeData::use_material3` is false, `ColorScheme::primary` with an opacity of 0.24 is
326    /// used. Otherwise, `ColorScheme::surface_container_highest` is used.
327    ///
328    /// Using a [`SliderTheme`] gives much more fine-grained control over the
329    /// appearance of various components of the slider.
330    ///
331    /// Ignored if this slider is created with [`Slider::adaptive`].
332    pub inactive_color: Option<Color>,
333
334    /// The color to use for the portion of the slider track between the thumb and
335    /// the [`secondary_track_value`](Self::secondary_track_value).
336    ///
337    /// Defaults to the `SliderThemeData::secondary_active_track_color` of the current
338    /// [`SliderTheme`].
339    ///
340    /// If that is also null, defaults to `ColorScheme::primary` with an
341    /// opacity of 0.54.
342    ///
343    /// Using a [`SliderTheme`] gives much more fine-grained control over the
344    /// appearance of various components of the slider.
345    ///
346    /// Ignored if this slider is created with [`Slider::adaptive`].
347    pub secondary_active_color: Option<Color>,
348
349    /// The color of the thumb.
350    ///
351    /// If this color is null, [`Slider`] will use [`active_color`](Self::active_color), If
352    /// [`active_color`](Self::active_color) is also null, [`Slider`] will use
353    /// `SliderThemeData::thumb_color`.
354    ///
355    /// If that is also null, defaults to `ColorScheme::primary`.
356    ///
357    /// * `CupertinoSlider` will have a white thumb
358    ///   (like the native default iOS slider).
359    pub thumb_color: Option<Color>,
360
361    /// The highlight color that's typically used to indicate that
362    /// the slider thumb is focused, hovered, or dragged.
363    ///
364    /// If this property is null, [`Slider`] will use [`active_color`](Self::active_color) with
365    /// an opacity of 0.12, If null, `SliderThemeData::overlay_color`
366    /// will be used.
367    ///
368    /// If that is also null, If `ThemeData::use_material3` is true,
369    /// Slider will use `ColorScheme::primary` with an opacity of 0.08 when
370    /// slider thumb is hovered and with an opacity of 0.1 when slider thumb
371    /// is focused or dragged, If `ThemeData::use_material3` is false, defaults
372    /// to `ColorScheme::primary` with an opacity of 0.12.
373    pub overlay_color: Option<WidgetStatePropertyRef<Option<Color>>>,
374
375    /// The cursor for a mouse pointer when it enters or is hovering over the
376    /// widget.
377    ///
378    /// If [`mouse_cursor`](Self::mouse_cursor) is a [`WidgetStateMouseCursor`],
379    /// `WidgetStateProperty::resolve` is used for the following [`WidgetState`]s:
380    ///
381    ///  * [`WidgetState::Dragged`].
382    ///  * [`WidgetState::Hovered`].
383    ///  * [`WidgetState::Focused`].
384    ///  * [`WidgetState::Disabled`].
385    ///
386    /// If null, then the value of `SliderThemeData::mouse_cursor` is used. If that
387    /// is also null, then [`WidgetStateMouseCursor::clickable`] is used.
388    pub mouse_cursor: Option<MouseCursorRef>,
389
390    /// The callback used to create a semantic value from a slider value.
391    ///
392    /// Defaults to formatting values as a percentage.
393    ///
394    /// This is used by accessibility frameworks like TalkBack on Android to
395    /// inform users what the currently selected value is with more context.
396    ///
397    /// Ignored if this slider is created with [`Slider::adaptive`]
398    pub semantic_formatter_callback: Option<SemanticFormatterCallback>,
399
400    /// An optional focus node to use as the focus node for this widget.
401    pub focus_node: Option<FocusNodeRef>,
402
403    /// True if this widget will be selected as the initial focus when no other
404    /// node in its scope is currently focused.
405    pub autofocus: bool,
406
407    /// Allowed way for the user to interact with the [`Slider`].
408    ///
409    /// For example, if this is set to [`SliderInteraction::TapOnly`], the user can
410    /// interact with the slider only by tapping anywhere on the track. Sliding
411    /// will have no effect.
412    ///
413    /// Defaults to [`SliderInteraction::TapAndSlide`].
414    pub allowed_interaction: Option<SliderInteraction>,
415
416    /// Determines the padding around the [`Slider`].
417    ///
418    /// If specified, this padding overrides the default vertical padding of
419    /// the [`Slider`], defaults to the height of the overlay shape, and the
420    /// horizontal padding, defaults to the width of the thumb shape or
421    /// overlay shape, whichever is larger.
422    pub padding: Option<EdgeInsetsGeometry>,
423
424    /// Determines the conditions under which the value indicator is shown.
425    ///
426    /// If [`show_value_indicator`](Self::show_value_indicator) is null then the
427    /// ambient `SliderThemeData::show_value_indicator` is used. If that is also
428    /// null, defaults to [`ShowValueIndicator::OnlyForDiscrete`].
429    pub show_value_indicator: Option<ShowValueIndicator>,
430
431    /// When true, the [`Slider`] will use the 2023 Material Design 3 appearance.
432    /// Defaults to true.
433    ///
434    /// If this is set to false, the [`Slider`] will use the latest Material Design 3
435    /// appearance, which was introduced in December 2023.
436    ///
437    /// If `ThemeData::use_material3` is false, then this property is ignored.
438    ///
439    /// Deprecated in Flutter after v3.27.0-0.1.pre; its setter carries the deprecation.
440    pub year2023: Option<bool>,
441
442    slider_type: SliderType,
443}
444
445impl Slider {
446    /// Creates a Material Design slider.
447    ///
448    /// The slider itself does not maintain any state. Instead, when the state of
449    /// the slider changes, the widget calls the [`on_changed`](Self::on_changed) callback.
450    /// Most widgets that use a slider will listen for the [`on_changed`](Self::on_changed)
451    /// callback and rebuild the slider with a new [`value`](Self::value) to update the visual
452    /// appearance of the slider.
453    ///
454    /// * [`value`](Self::value) determines currently selected value for this slider.
455    /// * [`on_changed`](Self::on_changed) is called while the user is selecting a new value
456    ///   for the slider.
457    /// * [`on_change_start`](Self::on_change_start) is called when the user starts to select a
458    ///   new value for the slider.
459    /// * [`on_change_end`](Self::on_change_end) is called when the user is done selecting a
460    ///   new value for the slider.
461    ///
462    /// You can override some of the colors with the [`active_color`](Self::active_color) and
463    /// [`inactive_color`](Self::inactive_color) properties, although more fine-grained control
464    /// of the appearance is achieved using a [`SliderThemeData`].
465    pub fn new(value: f64, on_changed: Option<ValueChanged<f64>>) -> Slider {
466        Slider::with_type(value, on_changed, SliderType::Material)
467    }
468
469    /// Creates an adaptive [`Slider`] based on the target platform, following
470    /// Material design's
471    /// [Cross-platform guidelines](https://material.io/design/platform-guidance/cross-platform-adaptation.html).
472    ///
473    /// Creates a `CupertinoSlider` if the target platform is iOS or macOS, creates a
474    /// Material Design slider otherwise.
475    ///
476    /// If a `CupertinoSlider` is created, the following parameters are ignored:
477    /// [`secondary_track_value`](Self::secondary_track_value), [`label`](Self::label),
478    /// [`inactive_color`](Self::inactive_color),
479    /// [`secondary_active_color`](Self::secondary_active_color),
480    /// [`semantic_formatter_callback`](Self::semantic_formatter_callback),
481    /// [`show_value_indicator`](Self::show_value_indicator).
482    ///
483    /// The target platform is based on the current `Theme`: `ThemeData::platform`.
484    ///
485    /// Dart's `Slider.adaptive` has no `padding` parameter: its `padding` is null, so a
486    /// [`padding`](Self::padding) set on it is ignored ([`effective_padding`](Self::effective_padding)).
487    pub fn adaptive(value: f64, on_changed: Option<ValueChanged<f64>>) -> Slider {
488        Slider::with_type(value, on_changed, SliderType::Adaptive)
489    }
490
491    fn with_type(
492        value: f64,
493        on_changed: Option<ValueChanged<f64>>,
494        slider_type: SliderType,
495    ) -> Slider {
496        Slider {
497            key: None,
498            value,
499            secondary_track_value: None,
500            on_changed,
501            on_change_start: None,
502            on_change_end: None,
503            min: 0.0,
504            max: 1.0,
505            divisions: None,
506            label: None,
507            active_color: None,
508            inactive_color: None,
509            secondary_active_color: None,
510            thumb_color: None,
511            overlay_color: None,
512            mouse_cursor: None,
513            semantic_formatter_callback: None,
514            focus_node: None,
515            autofocus: false,
516            allowed_interaction: None,
517            padding: None,
518            show_value_indicator: None,
519            year2023: None,
520            slider_type,
521        }
522    }
523
524    /// Dart `Slider(key:)`.
525    pub fn key(mut self, key: KeyRef) -> Slider {
526        self.key = Some(key);
527        self
528    }
529
530    /// Dart `Slider(secondaryTrackValue:)`.
531    pub fn secondary_track_value(mut self, secondary_track_value: f64) -> Slider {
532        self.secondary_track_value = Some(secondary_track_value);
533        self
534    }
535
536    /// Dart `Slider(onChangeStart:)`.
537    pub fn on_change_start(mut self, on_change_start: ValueChanged<f64>) -> Slider {
538        self.on_change_start = Some(on_change_start);
539        self
540    }
541
542    /// Dart `Slider(onChangeEnd:)`.
543    pub fn on_change_end(mut self, on_change_end: ValueChanged<f64>) -> Slider {
544        self.on_change_end = Some(on_change_end);
545        self
546    }
547
548    /// Dart `Slider(min:)`.
549    pub fn min(mut self, min: f64) -> Slider {
550        self.min = min;
551        self
552    }
553
554    /// Dart `Slider(max:)`.
555    pub fn max(mut self, max: f64) -> Slider {
556        self.max = max;
557        self
558    }
559
560    /// Dart `Slider(divisions:)`.
561    pub fn divisions(mut self, divisions: i32) -> Slider {
562        debug_assert!(divisions > 0);
563        self.divisions = Some(divisions);
564        self
565    }
566
567    /// Dart `Slider(label:)`.
568    pub fn label(mut self, label: impl Into<String>) -> Slider {
569        self.label = Some(label.into());
570        self
571    }
572
573    /// Dart `Slider(activeColor:)`.
574    pub fn active_color(mut self, active_color: Color) -> Slider {
575        self.active_color = Some(active_color);
576        self
577    }
578
579    /// Dart `Slider(inactiveColor:)`.
580    pub fn inactive_color(mut self, inactive_color: Color) -> Slider {
581        self.inactive_color = Some(inactive_color);
582        self
583    }
584
585    /// Dart `Slider(secondaryActiveColor:)`.
586    pub fn secondary_active_color(mut self, secondary_active_color: Color) -> Slider {
587        self.secondary_active_color = Some(secondary_active_color);
588        self
589    }
590
591    /// Dart `Slider(thumbColor:)`.
592    pub fn thumb_color(mut self, thumb_color: Color) -> Slider {
593        self.thumb_color = Some(thumb_color);
594        self
595    }
596
597    /// Dart `Slider(overlayColor:)`.
598    pub fn overlay_color(mut self, overlay_color: WidgetStatePropertyRef<Option<Color>>) -> Slider {
599        self.overlay_color = Some(overlay_color);
600        self
601    }
602
603    /// Dart `Slider(mouseCursor:)`.
604    pub fn mouse_cursor(mut self, mouse_cursor: MouseCursorRef) -> Slider {
605        self.mouse_cursor = Some(mouse_cursor);
606        self
607    }
608
609    /// Dart `Slider(semanticFormatterCallback:)`.
610    pub fn semantic_formatter_callback(
611        mut self,
612        semantic_formatter_callback: SemanticFormatterCallback,
613    ) -> Slider {
614        self.semantic_formatter_callback = Some(semantic_formatter_callback);
615        self
616    }
617
618    /// Dart `Slider(focusNode:)`.
619    pub fn focus_node(mut self, focus_node: FocusNodeRef) -> Slider {
620        self.focus_node = Some(focus_node);
621        self
622    }
623
624    /// Dart `Slider(autofocus:)`.
625    pub fn autofocus(mut self, autofocus: bool) -> Slider {
626        self.autofocus = autofocus;
627        self
628    }
629
630    /// Dart `Slider(allowedInteraction:)`.
631    pub fn allowed_interaction(mut self, allowed_interaction: SliderInteraction) -> Slider {
632        self.allowed_interaction = Some(allowed_interaction);
633        self
634    }
635
636    /// Dart `Slider(padding:)`.
637    pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> Slider {
638        self.padding = Some(padding.into());
639        self
640    }
641
642    /// Dart `Slider(showValueIndicator:)`.
643    pub fn show_value_indicator(mut self, show_value_indicator: ShowValueIndicator) -> Slider {
644        self.show_value_indicator = Some(show_value_indicator);
645        self
646    }
647
648    /// Dart `Slider(year2023:)`.
649    #[deprecated(
650        note = "Set this flag to false to opt into the 2024 slider appearance. \
651                Defaults to true. In the future, this flag will default to false. Use \
652                SliderThemeData to customize individual properties. This feature was \
653                deprecated after v3.27.0-0.1.pre."
654    )]
655    pub fn year2023(mut self, year2023: bool) -> Slider {
656        self.year2023 = Some(year2023);
657        self
658    }
659
660    /// Dart's `padding` field: what [`padding`](Self::padding) was given, and null for a
661    /// slider made with [`Slider::adaptive`], whose constructor sets it so.
662    pub fn effective_padding(&self) -> Option<EdgeInsetsGeometry> {
663        match self.slider_type {
664            SliderType::Material => self.padding,
665            SliderType::Adaptive => None,
666        }
667    }
668}
669
670impl Debug for Slider {
671    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
672        let mut properties = f.debug_struct("Slider");
673        properties
674            .field("value", &self.value)
675            .field("secondary_track_value", &self.secondary_track_value);
676        if self.on_changed.is_none() {
677            properties.field("on_changed", &"disabled");
678        }
679        properties
680            .field("on_change_start", &self.on_change_start.is_some())
681            .field("on_change_end", &self.on_change_end.is_some())
682            .field("min", &self.min)
683            .field("max", &self.max)
684            .field("divisions", &self.divisions)
685            .field("label", &self.label)
686            .field("active_color", &self.active_color)
687            .field("inactive_color", &self.inactive_color)
688            .field("secondary_active_color", &self.secondary_active_color)
689            .field(
690                "semantic_formatter_callback",
691                &self.semantic_formatter_callback.is_some(),
692            )
693            .field("focus_node", &self.focus_node.is_some());
694        if self.autofocus {
695            properties.field("autofocus", &"autofocus");
696        }
697        properties.finish()
698    }
699}
700
701impl StatefulWidget for Slider {
702    type State = SliderState;
703
704    fn key(&self) -> Option<&KeyRef> {
705        self.key.as_ref()
706    }
707
708    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
709        properties.add(DoubleProperty::new("value", self.value));
710        properties.add(DoubleProperty::new(
711            "secondaryTrackValue",
712            self.secondary_track_value,
713        ));
714        properties.add(
715            ObjectFlagProperty::<String>::new(
716                "onChanged",
717                self.on_changed.as_ref().map(|_| String::new()),
718            )
719            .if_null("disabled"),
720        );
721        properties.add(ObjectFlagProperty::<String>::has(
722            "onChangeStart",
723            self.on_change_start.as_ref().map(|_| String::new()),
724        ));
725        properties.add(ObjectFlagProperty::<String>::has(
726            "onChangeEnd",
727            self.on_change_end.as_ref().map(|_| String::new()),
728        ));
729        properties.add(DoubleProperty::new("min", self.min));
730        properties.add(DoubleProperty::new("max", self.max));
731        properties.add(IntProperty::<i32>::new("divisions", self.divisions));
732        properties.add(StringProperty::new("label", self.label.clone()));
733        properties.add(ColorProperty::new("activeColor", self.active_color));
734        properties.add(ColorProperty::new("inactiveColor", self.inactive_color));
735        properties.add(ColorProperty::new(
736            "secondaryActiveColor",
737            self.secondary_active_color,
738        ));
739        properties.add(ObjectFlagProperty::<String>::has(
740            "semanticFormatterCallback",
741            self.semantic_formatter_callback
742                .as_ref()
743                .map(|_| String::new()),
744        ));
745        properties.add(ObjectFlagProperty::<String>::has(
746            "focusNode",
747            self.focus_node.as_ref().map(|_| String::new()),
748        ));
749        properties.add(FlagProperty::new("autofocus", Some(self.autofocus)).if_true("autofocus"));
750    }
751
752    fn debug_check_constructor(&self) {
753        debug_assert!(self.min <= self.max);
754        debug_assert!(
755            self.value >= self.min && self.value <= self.max,
756            "Value {} is not between minimum {} and maximum {}",
757            self.value,
758            self.min,
759            self.max
760        );
761        debug_assert!(
762            self.secondary_track_value
763                .is_none_or(|secondary| secondary >= self.min && secondary <= self.max),
764            "SecondaryValue {:?} is not between {} and {}",
765            self.secondary_track_value,
766            self.min,
767            self.max
768        );
769    }
770
771    fn create_state(&self) -> SliderState {
772        SliderState {
773            state: StateData::new(),
774            ticker_provider: TickerProviderStateMixinData::new(),
775            overlay_controller: None,
776            value_indicator_controller: None,
777            enable_controller: None,
778            position_controller: None,
779            interaction_timer: None,
780            render_object_key: GlobalKey::new(),
781            action_map: HashMap::new(),
782            paint_value_indicator: None,
783            dragging: false,
784            current_changed_value: None,
785            focus_node: None,
786            value_indicator_overlay_portal_controller: None,
787            focused: false,
788            hovering: false,
789            layer_link: None,
790        }
791    }
792}
793
794/// Dart's `_SliderState`.
795///
796/// The fields Dart makes in its initializers (the overlay portal controller, which Dart
797/// shows there, and the layer link) are made in `init_state`, the first point with an
798/// `App`.
799pub struct SliderState {
800    state: StateData<Slider>,
801    ticker_provider: TickerProviderStateMixinData,
802    // Animation controller that is run when the overlay (a.k.a radial reaction)
803    // is shown in response to user interaction.
804    overlay_controller: Option<Ref<AnimationController>>,
805    // Animation controller that is run when the value indicator is being shown
806    // or hidden.
807    value_indicator_controller: Option<Ref<AnimationController>>,
808    // Animation controller that is run when enabling/disabling the slider.
809    enable_controller: Option<Ref<AnimationController>>,
810    // Animation controller that is run when transitioning between one value
811    // and the next on a discrete slider.
812    position_controller: Option<Ref<AnimationController>>,
813    interaction_timer: Option<Timer>,
814    render_object_key: GlobalKey,
815    // Action mapping for a focused slider.
816    action_map: HashMap<TypeId, ActionRef>,
817    // Value Indicator Animation that appears on the Overlay.
818    paint_value_indicator: Option<PaintValueIndicator>,
819    dragging: bool,
820    // For discrete sliders, _handleChanged might receive the same value
821    // multiple times. To avoid calling widget.onChanged repeatedly, the
822    // value from _handleChanged is temporarily saved here.
823    current_changed_value: Option<f64>,
824    focus_node: Option<Ref<FocusNode>>,
825    // Always keep the ValueIndicator visible on the Overlay; otherwise, it cannot be updated
826    // during the build phase.
827    value_indicator_overlay_portal_controller: Option<Ref<OverlayPortalController>>,
828    focused: bool,
829    hovering: bool,
830    layer_link: Option<Ref<LayerLink>>,
831}
832
833thread_local! {
834    // Keyboard mapping for a focused slider.
835    static TRADITIONAL_NAV_SHORTCUT_MAP: ShortcutMap = vec![
836        adjust_shortcut(LogicalKeyboardKey::ARROW_UP, SliderAdjustmentType::Up),
837        adjust_shortcut(LogicalKeyboardKey::ARROW_DOWN, SliderAdjustmentType::Down),
838        adjust_shortcut(LogicalKeyboardKey::ARROW_LEFT, SliderAdjustmentType::Left),
839        adjust_shortcut(LogicalKeyboardKey::ARROW_RIGHT, SliderAdjustmentType::Right),
840    ];
841
842    // Keyboard mapping for a focused slider when using directional navigation.
843    // The vertical inputs are not handled to allow navigating out of the slider.
844    static DIRECTIONAL_NAV_SHORTCUT_MAP: ShortcutMap = vec![
845        adjust_shortcut(LogicalKeyboardKey::ARROW_LEFT, SliderAdjustmentType::Left),
846        adjust_shortcut(LogicalKeyboardKey::ARROW_RIGHT, SliderAdjustmentType::Right),
847    ];
848}
849
850fn adjust_shortcut(
851    key: LogicalKeyboardKey,
852    adjustment_type: SliderAdjustmentType,
853) -> (ShortcutActivatorRef, IntentRef) {
854    (
855        Rc::new(SingleActivator::new(key)) as ShortcutActivatorRef,
856        Rc::new(AdjustSliderIntent::new(adjustment_type)) as IntentRef,
857    )
858}
859
860impl SliderState {
861    const ENABLE_ANIMATION_DURATION: Duration = Duration::from_millis(75);
862    const VALUE_INDICATOR_ANIMATION_DURATION: Duration = Duration::from_millis(100);
863
864    fn overlay_controller(self: Handle<Self>, app: &App) -> &Ref<AnimationController> {
865        app.get(self)
866            .overlay_controller
867            .as_ref()
868            .expect("init_state made the overlay controller")
869    }
870
871    fn value_indicator_controller(self: Handle<Self>, app: &App) -> &Ref<AnimationController> {
872        app.get(self)
873            .value_indicator_controller
874            .as_ref()
875            .expect("init_state made the value indicator controller")
876    }
877
878    fn enable_controller(self: Handle<Self>, app: &App) -> &Ref<AnimationController> {
879        app.get(self)
880            .enable_controller
881            .as_ref()
882            .expect("init_state made the enable controller")
883    }
884
885    fn position_controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
886        app.get(self)
887            .position_controller
888            .handle()
889            .expect("init_state made the position controller")
890    }
891
892    fn enabled(self: Handle<Self>, app: &App) -> bool {
893        self.widget(app).on_changed.is_some()
894    }
895
896    fn effective_focus_node(self: Handle<Self>, app: &App) -> FocusNodeRef {
897        self.widget(app)
898            .focus_node
899            .clone()
900            .or_else(|| app.get(self).focus_node.as_ref().map(Ref::erase))
901            .expect("init_state made a focus node when the widget has none")
902    }
903
904    fn handle_changed(self: Handle<Self>, app: &mut App, value: f64) {
905        debug_assert!(self.widget(app).on_changed.is_some());
906        let lerp_value = self.lerp(app, value);
907        if app.get(self).current_changed_value != Some(lerp_value) {
908            app.get_mut(self).current_changed_value = Some(lerp_value);
909            if lerp_value != self.widget(app).value {
910                let on_changed = self
911                    .widget(app)
912                    .on_changed
913                    .clone()
914                    .expect("an enabled slider");
915                on_changed(app, lerp_value);
916            }
917        }
918    }
919
920    fn handle_drag_start(self: Handle<Self>, app: &mut App, value: f64) {
921        self.set_state(app, |state| {
922            state.dragging = true;
923        });
924        if let Some(on_change_start) = self.widget(app).on_change_start.clone() {
925            let lerp_value = self.lerp(app, value);
926            on_change_start(app, lerp_value);
927        }
928    }
929
930    fn handle_drag_end(self: Handle<Self>, app: &mut App, value: f64) {
931        self.set_state(app, |state| {
932            state.dragging = false;
933        });
934        app.get_mut(self).current_changed_value = None;
935        if let Some(on_change_end) = self.widget(app).on_change_end.clone() {
936            let lerp_value = self.lerp(app, value);
937            on_change_end(app, lerp_value);
938        }
939    }
940
941    fn action_handler(self: Handle<Self>, app: &mut App, intent: &AdjustSliderIntent) {
942        let render_object_key = app.get(self).render_object_key.clone();
943        let context = render_object_key
944            .current_context(app)
945            .expect("the slider's render object widget is mounted");
946        let directionality = Directionality::of(app, context);
947        let should_increase = match intent.adjustment_type {
948            SliderAdjustmentType::Up => true,
949            SliderAdjustmentType::Down => false,
950            SliderAdjustmentType::Left => directionality == TextDirection::Rtl,
951            SliderAdjustmentType::Right => directionality == TextDirection::Ltr,
952        };
953
954        let slider = context
955            .find_render_object(app)
956            .and_then(|render_object| render_object.downcast::<RenderSlider>(app))
957            .expect("the slider's render object is a _RenderSlider");
958        if should_increase {
959            slider.increase_action(app)
960        } else {
961            slider.decrease_action(app)
962        }
963    }
964
965    fn handle_focus_highlight_changed(self: Handle<Self>, app: &mut App, focused: bool) {
966        if focused != app.get(self).focused {
967            self.set_state(app, |state| {
968                state.focused = focused;
969            });
970        }
971    }
972
973    fn handle_hover_changed(self: Handle<Self>, app: &mut App, hovering: bool) {
974        if hovering != app.get(self).hovering {
975            self.set_state(app, |state| {
976                state.hovering = hovering;
977            });
978        }
979    }
980
981    // Returns a number between min and max, proportional to value, which must
982    // be between 0.0 and 1.0.
983    fn lerp(self: Handle<Self>, app: &App, value: f64) -> f64 {
984        debug_assert!(value >= 0.0);
985        debug_assert!(value <= 1.0);
986        let widget = self.widget(app);
987        if let Some(divisions) = widget.divisions {
988            return widget.min
989                + (value * f64::from(divisions)).round() * (widget.max - widget.min)
990                    / f64::from(divisions);
991        }
992        value * (widget.max - widget.min) + widget.min
993    }
994
995    fn discretize(self: Handle<Self>, app: &App, value: f64) -> f64 {
996        debug_assert!(self.widget(app).divisions.is_some());
997        debug_assert!((0.0..=1.0).contains(&value));
998
999        let divisions = f64::from(self.widget(app).divisions.expect("a discrete slider"));
1000        (value * divisions).round() / divisions
1001    }
1002
1003    fn convert(self: Handle<Self>, app: &App, value: f64) -> f64 {
1004        let mut ret = self.unlerp(app, value);
1005        if self.widget(app).divisions.is_some() {
1006            ret = self.discretize(app, ret);
1007        }
1008        ret
1009    }
1010
1011    // Returns a number between 0.0 and 1.0, given a value between min and max.
1012    fn unlerp(self: Handle<Self>, app: &App, value: f64) -> f64 {
1013        let widget = self.widget(app);
1014        debug_assert!(value <= widget.max);
1015        debug_assert!(value >= widget.min);
1016        if widget.max > widget.min {
1017            (value - widget.min) / (widget.max - widget.min)
1018        } else {
1019            0.0
1020        }
1021    }
1022
1023    fn build_material_slider(
1024        self: Handle<Self>,
1025        app: &mut App,
1026        context: BuildContext,
1027    ) -> WidgetRef {
1028        let widget = self.widget(app).clone();
1029        let theme = Theme::of(app, context);
1030        let mut slider_theme = SliderTheme::of(app, context);
1031        let year2023 = widget.year2023.or(slider_theme.year2023).unwrap_or(true);
1032        let defaults: Box<dyn SliderThemeDataGetters> = if theme.use_material3 {
1033            if year2023 {
1034                Box::new(SliderDefaultsM3Year2023::new(context))
1035            } else {
1036                Box::new(SliderDefaultsM3::new(context))
1037            }
1038        } else {
1039            Box::new(SliderDefaultsM2::new(context))
1040        };
1041
1042        // If the widget has active or inactive colors specified, then we plug them
1043        // in to the slider theme as best we can. If the developer wants more
1044        // control than that, then they need to use a SliderTheme. The default
1045        // colors come from the ThemeData.colorScheme. These colors, along with
1046        // the default shapes and text styles are aligned to the Material
1047        // Guidelines.
1048
1049        const DEFAULT_SHOW_VALUE_INDICATOR: ShowValueIndicator =
1050            ShowValueIndicator::OnlyForDiscrete;
1051        const DEFAULT_ALLOWED_INTERACTION: SliderInteraction = SliderInteraction::TapAndSlide;
1052
1053        let enabled = self.enabled(app);
1054        let (hovering, focused, dragging) = {
1055            let state = app.get(self);
1056            (state.hovering, state.focused, state.dragging)
1057        };
1058        let mut states = WidgetStates::new();
1059        if !enabled {
1060            states.insert(WidgetState::Disabled);
1061        }
1062        if hovering {
1063            states.insert(WidgetState::Hovered);
1064        }
1065        if focused {
1066            states.insert(WidgetState::Focused);
1067        }
1068        if dragging {
1069            states.insert(WidgetState::Dragged);
1070        }
1071
1072        // The value indicator's color is not the same as the thumb and active track
1073        // (which can be defined by activeColor) if the
1074        // RectangularSliderValueIndicatorShape is used. In all other cases, the
1075        // value indicator is assumed to be the same as the active color.
1076        let value_indicator_shape = slider_theme
1077            .value_indicator_shape
1078            .clone()
1079            .or_else(|| defaults.value_indicator_shape(app))
1080            .expect("the defaults have a value indicator shape");
1081        let value_indicator_color = if value_indicator_shape
1082            .as_any()
1083            .is::<RectangularSliderValueIndicatorShape>()
1084        {
1085            #[expect(deprecated, reason = "Dart calls the deprecated `Color.withOpacity`")]
1086            let fallback = Color::alpha_blend(
1087                theme.color_scheme.on_surface().with_opacity(0.60),
1088                theme.color_scheme.surface().with_opacity(0.90),
1089            );
1090            slider_theme.value_indicator_color.unwrap_or(fallback)
1091        } else {
1092            widget
1093                .active_color
1094                .or(slider_theme.value_indicator_color)
1095                .or_else(|| defaults.value_indicator_color(app))
1096                .expect("the defaults have a value indicator color")
1097        };
1098
1099        #[expect(deprecated, reason = "Dart calls the deprecated `Color.withOpacity`")]
1100        let effective_overlay_color = widget
1101            .overlay_color
1102            .as_ref()
1103            .and_then(|overlay_color| overlay_color.resolve(&states))
1104            .or_else(|| {
1105                widget
1106                    .active_color
1107                    .map(|active_color| active_color.with_opacity(0.12))
1108            })
1109            .or_else(|| {
1110                <dyn WidgetStateProperty<Color>>::resolve_as(&slider_theme.overlay_color, &states)
1111                    .map(|color| color.color())
1112            })
1113            .or_else(|| {
1114                <dyn WidgetStateProperty<Color>>::resolve_as(&defaults.overlay_color(app), &states)
1115                    .map(|color| color.color())
1116            });
1117
1118        let mut value_indicator_text_style = slider_theme
1119            .value_indicator_text_style
1120            .clone()
1121            .or_else(|| defaults.value_indicator_text_style(app))
1122            .expect("the defaults have a value indicator text style");
1123        if MediaQuery::bold_text_of(app, context) {
1124            value_indicator_text_style = value_indicator_text_style
1125                .merge(Some(&TextStyle::new().font_weight(FontWeight::BOLD)));
1126        }
1127
1128        slider_theme = SliderThemeData {
1129            track_height: slider_theme
1130                .track_height
1131                .or_else(|| defaults.track_height(app)),
1132            active_track_color: widget
1133                .active_color
1134                .or(slider_theme.active_track_color)
1135                .or_else(|| defaults.active_track_color(app)),
1136            inactive_track_color: widget
1137                .inactive_color
1138                .or(slider_theme.inactive_track_color)
1139                .or_else(|| defaults.inactive_track_color(app)),
1140            secondary_active_track_color: widget
1141                .secondary_active_color
1142                .or(slider_theme.secondary_active_track_color)
1143                .or_else(|| defaults.secondary_active_track_color(app)),
1144            disabled_active_track_color: slider_theme
1145                .disabled_active_track_color
1146                .or_else(|| defaults.disabled_active_track_color(app)),
1147            disabled_inactive_track_color: slider_theme
1148                .disabled_inactive_track_color
1149                .or_else(|| defaults.disabled_inactive_track_color(app)),
1150            disabled_secondary_active_track_color: slider_theme
1151                .disabled_secondary_active_track_color
1152                .or_else(|| defaults.disabled_secondary_active_track_color(app)),
1153            active_tick_mark_color: widget
1154                .inactive_color
1155                .or(slider_theme.active_tick_mark_color)
1156                .or_else(|| defaults.active_tick_mark_color(app)),
1157            inactive_tick_mark_color: widget
1158                .active_color
1159                .or(slider_theme.inactive_tick_mark_color)
1160                .or_else(|| defaults.inactive_tick_mark_color(app)),
1161            disabled_active_tick_mark_color: slider_theme
1162                .disabled_active_tick_mark_color
1163                .or_else(|| defaults.disabled_active_tick_mark_color(app)),
1164            disabled_inactive_tick_mark_color: slider_theme
1165                .disabled_inactive_tick_mark_color
1166                .or_else(|| defaults.disabled_inactive_tick_mark_color(app)),
1167            thumb_color: widget
1168                .thumb_color
1169                .or(widget.active_color)
1170                .or(slider_theme.thumb_color)
1171                .or_else(|| defaults.thumb_color(app)),
1172            disabled_thumb_color: slider_theme
1173                .disabled_thumb_color
1174                .or_else(|| defaults.disabled_thumb_color(app)),
1175            overlay_color: effective_overlay_color
1176                .map(Into::into)
1177                .or_else(|| slider_theme.overlay_color.clone()),
1178            value_indicator_color: Some(value_indicator_color),
1179            track_shape: slider_theme
1180                .track_shape
1181                .clone()
1182                .or_else(|| defaults.track_shape(app)),
1183            tick_mark_shape: slider_theme
1184                .tick_mark_shape
1185                .clone()
1186                .or_else(|| defaults.tick_mark_shape(app)),
1187            thumb_shape: slider_theme
1188                .thumb_shape
1189                .clone()
1190                .or_else(|| defaults.thumb_shape(app)),
1191            overlay_shape: slider_theme
1192                .overlay_shape
1193                .clone()
1194                .or_else(|| defaults.overlay_shape(app)),
1195            value_indicator_shape: Some(value_indicator_shape),
1196            show_value_indicator: Some(
1197                widget
1198                    .show_value_indicator
1199                    .or(slider_theme.show_value_indicator)
1200                    .unwrap_or(DEFAULT_SHOW_VALUE_INDICATOR),
1201            ),
1202            value_indicator_text_style: Some(value_indicator_text_style),
1203            padding: widget.effective_padding().or(slider_theme.padding),
1204            thumb_size: slider_theme
1205                .thumb_size
1206                .clone()
1207                .or_else(|| defaults.thumb_size(app)),
1208            track_gap: slider_theme.track_gap.or_else(|| defaults.track_gap(app)),
1209            ..slider_theme
1210        };
1211        let effective_mouse_cursor: MouseCursorRef =
1212            <dyn WidgetStateProperty<MouseCursorRef>>::resolve_as(&widget.mouse_cursor, &states)
1213                .or_else(|| {
1214                    slider_theme
1215                        .mouse_cursor
1216                        .as_ref()
1217                        .and_then(|mouse_cursor| mouse_cursor.resolve(&states))
1218                })
1219                .unwrap_or_else(|| WidgetStateMouseCursor::clickable().resolve(&states));
1220        let effective_allowed_interaction = widget
1221            .allowed_interaction
1222            .or(slider_theme.allowed_interaction)
1223            .unwrap_or(DEFAULT_ALLOWED_INTERACTION);
1224
1225        // This size is used as the max bounds for the painting of the value
1226        // indicators It must be kept in sync with the function with the same name
1227        // in range_slider.dart.
1228        let screen_size = MediaQuery::size_of(app, context);
1229
1230        // Dart's `handleDidGainAccessibilityFocus` (Windows) is a semantics callback and
1231        // waits with accessibility.
1232
1233        let shortcut_map = match MediaQuery::navigation_mode_of(app, context) {
1234            NavigationMode::Directional => DIRECTIONAL_NAV_SHORTCUT_MAP.with(Clone::clone),
1235            NavigationMode::Traditional => TRADITIONAL_NAV_SHORTCUT_MAP.with(Clone::clone),
1236        };
1237
1238        let font_size = slider_theme
1239            .value_indicator_text_style
1240            .as_ref()
1241            .and_then(|style| style.font_size)
1242            .unwrap_or(K_DEFAULT_FONT_SIZE);
1243        let font_size_to_scale = if font_size == 0.0 {
1244            K_DEFAULT_FONT_SIZE
1245        } else {
1246            font_size
1247        };
1248        let text_scaler = if theme.use_material3 {
1249            // TODO(tahatesser): This is an eye-balled value.
1250            // This needs to be updated when accessibility
1251            // guidelines are available on the material specs page
1252            // https://m3.material.io/components/sliders/accessibility.
1253            MediaQuery::text_scaler_of(app, context).clamp(0.0, 1.3)
1254        } else {
1255            MediaQuery::text_scaler_of(app, context)
1256        };
1257        let effective_text_scale = text_scaler.scale(font_size_to_scale) / font_size_to_scale;
1258
1259        let on_changed: Option<ValueChanged<f64>> =
1260            (widget.on_changed.is_some() && widget.max > widget.min).then(|| {
1261                Rc::new(move |app: &mut App, value: f64| self.handle_changed(app, value))
1262                    as ValueChanged<f64>
1263            });
1264        let on_change_start: ValueChanged<f64> =
1265            Rc::new(move |app: &mut App, value: f64| self.handle_drag_start(app, value));
1266        let on_change_end: ValueChanged<f64> =
1267            Rc::new(move |app: &mut App, value: f64| self.handle_drag_end(app, value));
1268        let layer_link = app
1269            .get(self)
1270            .layer_link
1271            .clone()
1272            .expect("init_state made the layer link");
1273        let show_value_indicator = slider_theme
1274            .show_value_indicator
1275            .expect("the theme's show_value_indicator was filled in above");
1276        let render_object_widget = SliderRenderObjectWidget {
1277            key: Some(app.get(self).render_object_key.clone().into()),
1278            value: self.convert(app, widget.value),
1279            secondary_track_value: widget
1280                .secondary_track_value
1281                .map(|secondary_track_value| self.convert(app, secondary_track_value)),
1282            divisions: widget.divisions,
1283            label: widget.label.clone(),
1284            slider_theme: slider_theme.clone(),
1285            text_scale_factor: effective_text_scale,
1286            screen_size,
1287            on_changed,
1288            on_change_start,
1289            on_change_end,
1290            state: self,
1291            has_focus: focused,
1292            hovering,
1293            allowed_interaction: effective_allowed_interaction,
1294        };
1295        let mut result = CompositedTransformTarget::new(layer_link)
1296            .child(render_object_widget)
1297            .into_widget();
1298
1299        let padding = widget.effective_padding().or(slider_theme.padding);
1300        if let Some(padding) = padding {
1301            result = Padding::new(padding).child(result).into_widget();
1302        }
1303        let controller = app
1304            .get(self)
1305            .value_indicator_overlay_portal_controller
1306            .clone()
1307            .expect("init_state made the overlay portal controller");
1308        result = OverlayPortal::new(controller, move |app: &mut App, _context: BuildContext| {
1309            self.build_value_indicator(app, show_value_indicator)
1310        })
1311        .child(result)
1312        .into_widget();
1313
1314        let focus_node = self.effective_focus_node(app);
1315        FocusableActionDetector::new(result)
1316            .actions(app.get(self).action_map.clone())
1317            .shortcuts(shortcut_map)
1318            .focus_node(focus_node)
1319            .autofocus(widget.autofocus)
1320            .enabled(enabled)
1321            .on_show_focus_highlight(move |app, focused| {
1322                self.handle_focus_highlight_changed(app, focused)
1323            })
1324            .on_show_hover_highlight(move |app, hovering| self.handle_hover_changed(app, hovering))
1325            .mouse_cursor(effective_mouse_cursor)
1326            .include_focus_semantics(false)
1327            .into_widget()
1328    }
1329
1330    fn build_cupertino_slider(self: Handle<Self>, app: &mut App) -> WidgetRef {
1331        let widget = self.widget(app);
1332        // The render box of a slider has a fixed height but takes up the available
1333        // width. Wrapping the [CupertinoSlider] in this manner will help maintain
1334        // the same size.
1335        let mut slider = CupertinoSlider::new(widget.value, widget.on_changed.clone())
1336            .min(widget.min)
1337            .max(widget.max);
1338        if let Some(on_change_start) = widget.on_change_start.clone() {
1339            slider = slider.on_change_start(on_change_start);
1340        }
1341        if let Some(on_change_end) = widget.on_change_end.clone() {
1342            slider = slider.on_change_end(on_change_end);
1343        }
1344        if let Some(divisions) = widget.divisions {
1345            slider = slider.divisions(divisions);
1346        }
1347        if let Some(active_color) = widget.active_color {
1348            slider = slider.active_color(active_color);
1349        }
1350        slider = match widget.thumb_color {
1351            Some(thumb_color) => slider.thumb_color(thumb_color),
1352            None => slider.thumb_color(CupertinoColors::WHITE),
1353        };
1354        SizedBox::new()
1355            .width(f64::INFINITY)
1356            .child(slider)
1357            .into_widget()
1358    }
1359
1360    fn build_value_indicator(
1361        self: Handle<Self>,
1362        app: &mut App,
1363        show_value_indicator: ShowValueIndicator,
1364    ) -> WidgetRef {
1365        let layer_link = app
1366            .get(self)
1367            .layer_link
1368            .clone()
1369            .expect("init_state made the layer link");
1370        let value_indicator = || {
1371            CompositedTransformFollower::new(layer_link.clone())
1372                .child(ValueIndicatorRenderObjectWidget { state: self })
1373                .into_widget()
1374        };
1375        let divisions = self.widget(app).divisions;
1376        #[expect(deprecated, reason = "Dart's switch names the deprecated `always`")]
1377        match show_value_indicator {
1378            ShowValueIndicator::Never => SizedBox::shrink().into_widget(),
1379            ShowValueIndicator::OnlyForDiscrete => {
1380                if divisions.is_some() {
1381                    value_indicator()
1382                } else {
1383                    SizedBox::shrink().into_widget()
1384                }
1385            }
1386            ShowValueIndicator::OnlyForContinuous => {
1387                if divisions.is_none() {
1388                    value_indicator()
1389                } else {
1390                    SizedBox::shrink().into_widget()
1391                }
1392            }
1393            ShowValueIndicator::AlwaysVisible
1394            | ShowValueIndicator::Always
1395            | ShowValueIndicator::OnDrag => value_indicator(),
1396        }
1397    }
1398}
1399
1400impl TickerProviderStateMixin for SliderState {
1401    fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
1402        &app.get(self).ticker_provider
1403    }
1404
1405    fn ticker_provider_data_mut(
1406        self: Handle<Self>,
1407        app: &mut App,
1408    ) -> &mut TickerProviderStateMixinData {
1409        &mut app.get_mut(self).ticker_provider
1410    }
1411}
1412
1413/// Dart's `vsync: this`.
1414impl TickerProviderObject for SliderState {
1415    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
1416        TickerProviderStateMixin::create_ticker(self, app, on_tick)
1417    }
1418}
1419
1420impl State for SliderState {
1421    type Widget = Slider;
1422    waft_widgets::state_accessors!();
1423
1424    fn init_state(self: Handle<Self>, app: &mut App) {
1425        let portal_controller =
1426            OverlayPortalController::new(app, Some("Slider ValueIndicator".to_string()));
1427        portal_controller.show(app);
1428        app.get_mut(self).value_indicator_overlay_portal_controller = Some(portal_controller);
1429        let layer_link = LayerLink::new(app);
1430        app.get_mut(self).layer_link = Some(layer_link);
1431
1432        let controller = |app: &mut App, duration: Duration| {
1433            AnimationController::new(
1434                app,
1435                None,
1436                Some(duration),
1437                None,
1438                0.0,
1439                1.0,
1440                AnimationBehavior::Normal,
1441                self,
1442            )
1443        };
1444        let overlay_controller = controller(app, K_RADIAL_REACTION_DURATION);
1445        let value_indicator_controller = controller(app, Self::VALUE_INDICATOR_ANIMATION_DURATION);
1446        let enable_controller = controller(app, Self::ENABLE_ANIMATION_DURATION);
1447        let position_controller = controller(app, Duration::ZERO);
1448        let this = app.get_mut(self);
1449        this.overlay_controller = Some(overlay_controller);
1450        this.value_indicator_controller = Some(value_indicator_controller);
1451        this.enable_controller = Some(enable_controller.clone());
1452        this.position_controller = Some(position_controller.clone());
1453        let enabled = self.widget(app).on_changed.is_some();
1454        enable_controller.set_value(app, if enabled { 1.0 } else { 0.0 });
1455        let value = self.convert(app, self.widget(app).value);
1456        position_controller.set_value(app, value);
1457        let adjust = CallbackAction::<AdjustSliderIntent>::new(
1458            app,
1459            Rc::new(move |app: &mut App, intent: &AdjustSliderIntent| {
1460                self.action_handler(app, intent);
1461                None
1462            }),
1463        );
1464        app.get_mut(self)
1465            .action_map
1466            .insert(TypeId::of::<AdjustSliderIntent>(), adjust.into_erased());
1467        if self.widget(app).focus_node.is_none() {
1468            // Only create a new node if the widget doesn't have one.
1469            if app.get(self).focus_node.is_none() {
1470                let focus_node = FocusNode::new(app);
1471                app.get_mut(self).focus_node = Some(focus_node);
1472            }
1473        }
1474    }
1475
1476    fn activate(self: Handle<Self>, app: &mut App) {
1477        TickerProviderStateMixin::activate(self, app);
1478    }
1479
1480    fn dispose(self: Handle<Self>, app: &mut App) {
1481        if let Some(timer) = app.get_mut(self).interaction_timer.take() {
1482            timer.cancel(app);
1483        }
1484        let controllers = [
1485            self.overlay_controller(app).handle(),
1486            self.value_indicator_controller(app).handle(),
1487            self.enable_controller(app).handle(),
1488            self.position_controller(app),
1489        ];
1490        for controller in controllers {
1491            controller.dispose(app);
1492        }
1493        if let Some(focus_node) = app.get(self).focus_node.handle() {
1494            focus_node.dispose(app);
1495        }
1496        TickerProviderStateMixin::dispose(self, app);
1497    }
1498
1499    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1500        debug_assert!(debug_check_has_material(app, context));
1501        debug_assert!(debug_check_has_media_query(app, context));
1502
1503        match self.widget(app).slider_type {
1504            SliderType::Material => self.build_material_slider(app, context),
1505            SliderType::Adaptive => {
1506                let theme = Theme::of(app, context);
1507                match theme.platform {
1508                    TargetPlatform::Android
1509                    | TargetPlatform::Fuchsia
1510                    | TargetPlatform::Linux
1511                    | TargetPlatform::Windows => self.build_material_slider(app, context),
1512                    TargetPlatform::IOS | TargetPlatform::MacOS => self.build_cupertino_slider(app),
1513                }
1514            }
1515        }
1516    }
1517}
1518
1519/// Dart's `_SliderRenderObjectWidget`.
1520struct SliderRenderObjectWidget {
1521    key: Option<KeyRef>,
1522    value: f64,
1523    secondary_track_value: Option<f64>,
1524    divisions: Option<i32>,
1525    label: Option<String>,
1526    slider_theme: SliderThemeData,
1527    text_scale_factor: f64,
1528    screen_size: Size,
1529    on_changed: Option<ValueChanged<f64>>,
1530    on_change_start: ValueChanged<f64>,
1531    on_change_end: ValueChanged<f64>,
1532    state: Handle<SliderState>,
1533    has_focus: bool,
1534    hovering: bool,
1535    allowed_interaction: SliderInteraction,
1536}
1537
1538impl Debug for SliderRenderObjectWidget {
1539    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1540        f.debug_struct("_SliderRenderObjectWidget")
1541            .field("value", &self.value)
1542            .field("divisions", &self.divisions)
1543            .field("label", &self.label)
1544            .finish_non_exhaustive()
1545    }
1546}
1547
1548impl RenderObjectWidget for SliderRenderObjectWidget {
1549    type RenderObject = RenderSlider;
1550
1551    fn key(&self) -> Option<&KeyRef> {
1552        self.key.as_ref()
1553    }
1554
1555    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
1556        let text_direction = Directionality::of(app, context);
1557        let platform = Theme::of(app, context).platform;
1558        let gesture_settings = MediaQuery::gesture_settings_of(app, context);
1559        RenderSlider::new(
1560            app,
1561            self.value,
1562            self.secondary_track_value,
1563            self.divisions,
1564            self.label.clone(),
1565            self.slider_theme.clone(),
1566            self.text_scale_factor,
1567            self.screen_size,
1568            platform,
1569            self.on_changed.clone(),
1570            Some(self.on_change_start.clone()),
1571            Some(self.on_change_end.clone()),
1572            self.state,
1573            text_direction,
1574            self.has_focus,
1575            self.hovering,
1576            gesture_settings,
1577            self.allowed_interaction,
1578        )
1579        .as_object()
1580    }
1581
1582    fn update_render_object(
1583        &self,
1584        app: &mut App,
1585        context: BuildContext,
1586        render_object: RenderHandle<RenderSlider>,
1587    ) {
1588        let text_direction = Directionality::of(app, context);
1589        let platform = Theme::of(app, context).platform;
1590        let gesture_settings = MediaQuery::gesture_settings_of(app, context);
1591        // We should update the `divisions` ahead of `value`, because the `value`
1592        // setter dependent on the `divisions`.
1593        render_object.set_divisions(app, self.divisions);
1594        render_object.set_value(app, self.value);
1595        render_object.set_secondary_track_value(app, self.secondary_track_value);
1596        render_object.set_label(app, self.label.clone());
1597        render_object.set_slider_theme(app, self.slider_theme.clone());
1598        render_object.set_text_scale_factor(app, self.text_scale_factor);
1599        render_object.set_screen_size(app, self.screen_size);
1600        render_object.set_on_changed(app, self.on_changed.clone());
1601        render_object.get_mut(app).on_change_start = Some(self.on_change_start.clone());
1602        render_object.get_mut(app).on_change_end = Some(self.on_change_end.clone());
1603        render_object.set_text_direction(app, text_direction);
1604        render_object.set_platform(app, platform);
1605        render_object.set_has_focus(app, self.has_focus);
1606        render_object.set_hovering(app, self.hovering);
1607        render_object.set_gesture_settings(app, Some(gesture_settings));
1608        render_object.set_allowed_interaction(app, self.allowed_interaction);
1609        // Ticker provider cannot change since there's a 1:1 relationship between
1610        // the _SliderRenderObjectWidget object and the _SliderState object.
1611    }
1612}
1613
1614impl LeafRenderObjectWidget for SliderRenderObjectWidget {}
1615
1616/// Dart's `_RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin`.
1617pub(crate) struct RenderSlider {
1618    render_object: RenderObjectData,
1619    render_box: RenderBoxData,
1620    system_fonts: RelayoutWhenSystemFontsChangeData,
1621    value: f64,
1622    secondary_track_value: Option<f64>,
1623    divisions: Option<i32>,
1624    label: Option<String>,
1625    slider_theme: SliderThemeData,
1626    text_scale_factor: f64,
1627    screen_size: Size,
1628    platform: TargetPlatform,
1629    on_changed: Option<ValueChanged<f64>>,
1630    on_change_start: Option<ValueChanged<f64>>,
1631    on_change_end: Option<ValueChanged<f64>>,
1632    state: Handle<SliderState>,
1633    text_direction: TextDirection,
1634    has_focus: bool,
1635    hovering: bool,
1636    hovering_thumb: bool,
1637    allowed_interaction: SliderInteraction,
1638    overlay_animation: Ref<CurvedAnimation>,
1639    value_indicator_animation: Ref<CurvedAnimation>,
1640    enable_animation: Ref<CurvedAnimation>,
1641    label_painter: TextPainter,
1642    drag: Ref<HorizontalDragGestureRecognizer>,
1643    tap: Ref<TapGestureRecognizer>,
1644    active: bool,
1645    current_drag_value: f64,
1646    overlay_rect: Option<Rect>,
1647}
1648
1649impl RenderSlider {
1650    const POSITION_ANIMATION_DURATION: Duration = Duration::from_millis(75);
1651    const MINIMUM_INTERACTION_TIME: Duration = Duration::from_millis(500);
1652
1653    // This value is the touch target, 48, multiplied by 3.
1654    const MIN_PREFERRED_TRACK_WIDTH: f64 = 144.0;
1655
1656    // Buffer to account for the internal padding of standard Material value indicator shapes,
1657    // preventing them from bleeding off the screen edges.
1658    //
1659    // The value 64.0 is a heuristic that covers the minimum size of the shape
1660    // (padding + minimum label width) at a text scale factor of roughly 2.0.
1661    const K_VALUE_INDICATOR_HORIZONTAL_BUFFER: f64 = 64.0;
1662
1663    #[expect(
1664        clippy::too_many_arguments,
1665        reason = "Dart's constructor parameters, in its order"
1666    )]
1667    fn new(
1668        app: &mut App,
1669        value: f64,
1670        secondary_track_value: Option<f64>,
1671        divisions: Option<i32>,
1672        label: Option<String>,
1673        slider_theme: SliderThemeData,
1674        text_scale_factor: f64,
1675        screen_size: Size,
1676        platform: TargetPlatform,
1677        on_changed: Option<ValueChanged<f64>>,
1678        on_change_start: Option<ValueChanged<f64>>,
1679        on_change_end: Option<ValueChanged<f64>>,
1680        state: Handle<SliderState>,
1681        text_direction: TextDirection,
1682        has_focus: bool,
1683        hovering: bool,
1684        gesture_settings: DeviceGestureSettings,
1685        allowed_interaction: SliderInteraction,
1686    ) -> RenderHandle<RenderSlider> {
1687        debug_assert!((0.0..=1.0).contains(&value));
1688        debug_assert!(secondary_track_value.is_none_or(|value| (0.0..=1.0).contains(&value)));
1689        let drag = HorizontalDragGestureRecognizer::new(app);
1690        let tap = TapGestureRecognizer::new(app);
1691        let overlay_animation = CurvedAnimation::new(
1692            app,
1693            state.overlay_controller(app).erase(),
1694            Curves::fast_out_slow_in(),
1695            None,
1696        );
1697        let value_indicator_animation = CurvedAnimation::new(
1698            app,
1699            state.value_indicator_controller(app).erase(),
1700            Curves::fast_out_slow_in(),
1701            None,
1702        );
1703        let enable_animation = CurvedAnimation::new(
1704            app,
1705            state.enable_controller(app).erase(),
1706            Curves::ease_in_out(),
1707            None,
1708        );
1709        let this = RenderHandle::new_box(
1710            app,
1711            RenderSlider {
1712                render_object: RenderObjectData::new(),
1713                render_box: RenderBoxData::new(),
1714                system_fonts: RelayoutWhenSystemFontsChangeData::new(),
1715                value,
1716                secondary_track_value,
1717                divisions,
1718                label,
1719                slider_theme,
1720                text_scale_factor,
1721                screen_size,
1722                platform,
1723                on_changed,
1724                on_change_start,
1725                on_change_end,
1726                state,
1727                text_direction,
1728                has_focus,
1729                hovering,
1730                hovering_thumb: false,
1731                allowed_interaction,
1732                overlay_animation,
1733                value_indicator_animation,
1734                enable_animation,
1735                label_painter: TextPainter::new(),
1736                drag: drag.clone(),
1737                tap: tap.clone(),
1738                active: false,
1739                current_drag_value: 0.0,
1740                overlay_rect: None,
1741            },
1742        );
1743        this.update_label_painter(app);
1744        let team = GestureArenaTeam::new(app);
1745        drag.set_team(app, team.clone());
1746        drag.set_on_start(
1747            app,
1748            Some(Rc::new(move |app: &mut App, details: DragStartDetails| {
1749                this.handle_drag_start(app, details)
1750            })),
1751        );
1752        drag.set_on_update(
1753            app,
1754            Some(Rc::new(move |app: &mut App, details: DragUpdateDetails| {
1755                this.handle_drag_update(app, details)
1756            })),
1757        );
1758        drag.set_on_end(
1759            app,
1760            Some(Rc::new(move |app: &mut App, details: DragEndDetails| {
1761                this.handle_drag_end(app, details)
1762            })),
1763        );
1764        drag.set_on_cancel(
1765            app,
1766            Some(Listener::new(move |app: &mut App| {
1767                this.end_interaction(app)
1768            })),
1769        );
1770        drag.set_gesture_settings(app, Some(gesture_settings));
1771        tap.set_team(app, team);
1772        tap.set_on_tap_down(
1773            app,
1774            Some(Rc::new(move |app: &mut App, details: TapDownDetails| {
1775                this.handle_tap_down(app, details)
1776            })),
1777        );
1778        tap.set_on_tap_up(
1779            app,
1780            Some(Rc::new(move |app: &mut App, details: TapUpDetails| {
1781                this.handle_tap_up(app, details)
1782            })),
1783        );
1784        tap.set_gesture_settings(app, Some(gesture_settings));
1785        this
1786    }
1787
1788    // Compute the largest width and height needed to paint the slider shapes,
1789    // other than the track shape. It is assumed that these shapes are vertically
1790    // centered on the track.
1791    fn max_slider_part_width(self: RenderHandle<Self>, app: &App) -> f64 {
1792        self.slider_part_sizes(app)
1793            .iter()
1794            .map(|size| size.width())
1795            .fold(f64::NEG_INFINITY, f64::max)
1796    }
1797
1798    fn max_slider_part_height(self: RenderHandle<Self>, app: &App) -> f64 {
1799        self.slider_part_sizes(app)
1800            .iter()
1801            .map(|size| size.height())
1802            .fold(f64::NEG_INFINITY, f64::max)
1803    }
1804
1805    fn thumb_size_height(self: RenderHandle<Self>, app: &App) -> f64 {
1806        self.thumb_shape(app)
1807            .get_preferred_size(self.is_interactive(app), self.is_discrete(app))
1808            .height()
1809    }
1810
1811    fn overlay_height(self: RenderHandle<Self>, app: &App) -> f64 {
1812        self.overlay_shape(app)
1813            .get_preferred_size(self.is_interactive(app), self.is_discrete(app))
1814            .height()
1815    }
1816
1817    fn slider_part_sizes(self: RenderHandle<Self>, app: &App) -> [Size; 3] {
1818        let (is_interactive, is_discrete) = (self.is_interactive(app), self.is_discrete(app));
1819        let slider_theme = &self.get(app).slider_theme;
1820        [
1821            Size::new(
1822                self.overlay_shape(app)
1823                    .get_preferred_size(is_interactive, is_discrete)
1824                    .width(),
1825                if slider_theme.padding.is_some() {
1826                    self.thumb_size_height(app)
1827                } else {
1828                    self.overlay_height(app)
1829                },
1830            ),
1831            self.thumb_shape(app)
1832                .get_preferred_size(is_interactive, is_discrete),
1833            slider_theme
1834                .tick_mark_shape
1835                .as_ref()
1836                .expect("the slider fills in its tick mark shape")
1837                .get_preferred_size(slider_theme, is_interactive),
1838        ]
1839    }
1840
1841    fn min_preferred_track_height(self: RenderHandle<Self>, app: &App) -> f64 {
1842        self.get(app)
1843            .slider_theme
1844            .track_height
1845            .expect("the slider fills in its track height")
1846    }
1847
1848    fn thumb_shape(self: RenderHandle<Self>, app: &App) -> Rc<dyn crate::SliderComponentShape> {
1849        self.get(app)
1850            .slider_theme
1851            .thumb_shape
1852            .clone()
1853            .expect("the slider fills in its thumb shape")
1854    }
1855
1856    fn overlay_shape(self: RenderHandle<Self>, app: &App) -> Rc<dyn crate::SliderComponentShape> {
1857        self.get(app)
1858            .slider_theme
1859            .overlay_shape
1860            .clone()
1861            .expect("the slider fills in its overlay shape")
1862    }
1863
1864    fn track_shape(self: RenderHandle<Self>, app: &App) -> Rc<dyn crate::SliderTrackShape> {
1865        self.get(app)
1866            .slider_theme
1867            .track_shape
1868            .clone()
1869            .expect("the slider fills in its track shape")
1870    }
1871
1872    // This rect is used in gesture calculations, where the gesture coordinates
1873    // are relative to the sliders origin. Therefore, the offset is passed as
1874    // (0,0).
1875    fn track_rect(self: RenderHandle<Self>, app: &App) -> Rect {
1876        let slider_theme = &self.get(app).slider_theme;
1877        self.track_shape(app).get_preferred_rect(
1878            app,
1879            self.as_box(),
1880            Offset::ZERO,
1881            slider_theme,
1882            None,
1883            Some(false),
1884        )
1885    }
1886
1887    // Tick marks and the thumb are painted in an adjusted coordinate space that
1888    // reserves half a track height of padding on each end for discrete rounded
1889    // tracks, so gesture math needs to account for that same padding to stay
1890    // aligned with the visual tick positions.
1891    fn discrete_rounded_track_padding(self: RenderHandle<Self>, app: &App) -> f64 {
1892        if self.is_discrete(app) && self.track_shape(app).is_rounded() {
1893            self.track_rect(app).height()
1894        } else {
1895            0.0
1896        }
1897    }
1898
1899    fn is_interactive(self: RenderHandle<Self>, app: &App) -> bool {
1900        self.get(app).on_changed.is_some()
1901    }
1902
1903    fn is_discrete(self: RenderHandle<Self>, app: &App) -> bool {
1904        self.get(app)
1905            .divisions
1906            .is_some_and(|divisions| divisions > 0)
1907    }
1908
1909    fn value(self: RenderHandle<Self>, app: &App) -> f64 {
1910        self.get(app).value
1911    }
1912
1913    fn set_value(self: RenderHandle<Self>, app: &mut App, new_value: f64) {
1914        debug_assert!((0.0..=1.0).contains(&new_value));
1915        let converted_value = if self.is_discrete(app) {
1916            self.discretize(app, new_value)
1917        } else {
1918            new_value
1919        };
1920        if converted_value == self.get(app).value {
1921            return;
1922        }
1923        self.get_mut(app).value = converted_value;
1924        let position_controller = self.get(app).state.position_controller(app);
1925        if self.is_discrete(app) {
1926            // Reset the duration to match the distance that we're traveling, so that
1927            // whatever the distance, we still do it in _positionAnimationDuration,
1928            // and if we get re-targeted in the middle, it still takes that long to
1929            // get to the new location.
1930            let distance = (converted_value - position_controller.value(app)).abs();
1931            app.get_mut(position_controller).duration = Some(if distance != 0.0 {
1932                Self::POSITION_ANIMATION_DURATION.mul_f64(1.0 / distance)
1933            } else {
1934                Duration::ZERO
1935            });
1936            position_controller.animate_to(app, converted_value, None, Curves::ease_in_out());
1937        } else {
1938            position_controller.set_value(app, converted_value);
1939        }
1940        // `markNeedsSemanticsUpdate()` waits with accessibility.
1941    }
1942
1943    fn set_secondary_track_value(self: RenderHandle<Self>, app: &mut App, new_value: Option<f64>) {
1944        debug_assert!(new_value.is_none_or(|value| (0.0..=1.0).contains(&value)));
1945        if new_value == self.get(app).secondary_track_value {
1946            return;
1947        }
1948        self.get_mut(app).secondary_track_value = new_value;
1949        self.mark_needs_paint(app);
1950        // `markNeedsSemanticsUpdate()` waits with accessibility.
1951    }
1952
1953    #[cfg(test)]
1954    fn gesture_settings(self: RenderHandle<Self>, app: &App) -> Option<DeviceGestureSettings> {
1955        self.get(app).drag.gesture_settings(app)
1956    }
1957
1958    fn set_gesture_settings(
1959        self: RenderHandle<Self>,
1960        app: &mut App,
1961        gesture_settings: Option<DeviceGestureSettings>,
1962    ) {
1963        let (drag, tap) = (self.get(app).drag.handle(), self.get(app).tap.handle());
1964        drag.set_gesture_settings(app, gesture_settings);
1965        tap.set_gesture_settings(app, gesture_settings);
1966    }
1967
1968    /// Dart's setter marks the semantics dirty when the platform changes; that waits with
1969    /// accessibility, so it only stores the platform.
1970    fn set_platform(self: RenderHandle<Self>, app: &mut App, value: TargetPlatform) {
1971        if self.get(app).platform == value {
1972            return;
1973        }
1974        self.get_mut(app).platform = value;
1975    }
1976
1977    fn divisions(self: RenderHandle<Self>, app: &App) -> Option<i32> {
1978        self.get(app).divisions
1979    }
1980
1981    fn set_divisions(self: RenderHandle<Self>, app: &mut App, value: Option<i32>) {
1982        if value == self.get(app).divisions {
1983            return;
1984        }
1985        self.get_mut(app).divisions = value;
1986        self.mark_needs_paint(app);
1987    }
1988
1989    fn label(self: RenderHandle<Self>, app: &App) -> Option<&str> {
1990        self.get(app).label.as_deref()
1991    }
1992
1993    fn set_label(self: RenderHandle<Self>, app: &mut App, value: Option<String>) {
1994        if value == self.get(app).label {
1995            return;
1996        }
1997        self.get_mut(app).label = value;
1998        self.update_label_painter(app);
1999    }
2000
2001    fn slider_theme(self: RenderHandle<Self>, app: &App) -> &SliderThemeData {
2002        &self.get(app).slider_theme
2003    }
2004
2005    fn set_slider_theme(self: RenderHandle<Self>, app: &mut App, value: SliderThemeData) {
2006        if value == self.get(app).slider_theme {
2007            return;
2008        }
2009        self.get_mut(app).slider_theme = value;
2010        self.update_label_painter(app);
2011    }
2012
2013    fn text_scale_factor(self: RenderHandle<Self>, app: &App) -> f64 {
2014        self.get(app).text_scale_factor
2015    }
2016
2017    fn set_text_scale_factor(self: RenderHandle<Self>, app: &mut App, value: f64) {
2018        if value == self.get(app).text_scale_factor {
2019            return;
2020        }
2021        self.get_mut(app).text_scale_factor = value;
2022        self.update_label_painter(app);
2023    }
2024
2025    fn screen_size(self: RenderHandle<Self>, app: &App) -> Size {
2026        self.get(app).screen_size
2027    }
2028
2029    fn set_screen_size(self: RenderHandle<Self>, app: &mut App, value: Size) {
2030        if value == self.get(app).screen_size {
2031            return;
2032        }
2033        self.get_mut(app).screen_size = value;
2034        self.mark_needs_paint(app);
2035    }
2036
2037    fn on_changed(self: RenderHandle<Self>, app: &App) -> Option<ValueChanged<f64>> {
2038        self.get(app).on_changed.clone()
2039    }
2040
2041    /// Dart's setter returns early when the callback is the same object; a closure has no
2042    /// identity here, so it always stores the new one and acts only when interactivity flips,
2043    /// as Dart's does. Marking the semantics dirty waits with accessibility.
2044    fn set_on_changed(self: RenderHandle<Self>, app: &mut App, value: Option<ValueChanged<f64>>) {
2045        let was_interactive = self.is_interactive(app);
2046        self.get_mut(app).on_changed = value;
2047        if was_interactive != self.is_interactive(app) {
2048            let enable_controller = self.get(app).state.enable_controller(app).handle();
2049            if self.is_interactive(app) {
2050                enable_controller.forward(app, None);
2051            } else {
2052                enable_controller.reverse(app, None);
2053            }
2054            self.mark_needs_paint(app);
2055        }
2056    }
2057
2058    fn text_direction(self: RenderHandle<Self>, app: &App) -> TextDirection {
2059        self.get(app).text_direction
2060    }
2061
2062    fn set_text_direction(self: RenderHandle<Self>, app: &mut App, value: TextDirection) {
2063        if value == self.get(app).text_direction {
2064            return;
2065        }
2066        self.get_mut(app).text_direction = value;
2067        self.update_label_painter(app);
2068    }
2069
2070    /// True if this slider has the input focus.
2071    fn has_focus(self: RenderHandle<Self>, app: &App) -> bool {
2072        self.get(app).has_focus
2073    }
2074
2075    fn set_has_focus(self: RenderHandle<Self>, app: &mut App, value: bool) {
2076        if value == self.get(app).has_focus {
2077            return;
2078        }
2079        self.get_mut(app).has_focus = value;
2080        self.update_for_focus(app, value);
2081        // `markNeedsSemanticsUpdate()` waits with accessibility.
2082    }
2083
2084    /// True if this slider is being hovered over by a pointer.
2085    fn hovering(self: RenderHandle<Self>, app: &App) -> bool {
2086        self.get(app).hovering
2087    }
2088
2089    fn set_hovering(self: RenderHandle<Self>, app: &mut App, value: bool) {
2090        if value == self.get(app).hovering {
2091            return;
2092        }
2093        self.get_mut(app).hovering = value;
2094        self.update_for_hover(app, value);
2095    }
2096
2097    /// True if the slider is interactive and the slider thumb is being
2098    /// hovered over by a pointer.
2099    fn hovering_thumb(self: RenderHandle<Self>, app: &App) -> bool {
2100        self.get(app).hovering_thumb
2101    }
2102
2103    fn set_hovering_thumb(self: RenderHandle<Self>, app: &mut App, value: bool) {
2104        if value == self.get(app).hovering_thumb {
2105            return;
2106        }
2107        self.get_mut(app).hovering_thumb = value;
2108        let hovering = self.hovering(app);
2109        self.update_for_hover(app, hovering);
2110    }
2111
2112    fn allowed_interaction(self: RenderHandle<Self>, app: &App) -> SliderInteraction {
2113        self.get(app).allowed_interaction
2114    }
2115
2116    /// Dart's setter marks the semantics dirty; that waits with accessibility, so it only
2117    /// stores the value.
2118    fn set_allowed_interaction(self: RenderHandle<Self>, app: &mut App, value: SliderInteraction) {
2119        if value == self.get(app).allowed_interaction {
2120            return;
2121        }
2122        self.get_mut(app).allowed_interaction = value;
2123    }
2124
2125    fn update_for_focus(self: RenderHandle<Self>, app: &mut App, focused: bool) {
2126        let state = self.get(app).state;
2127        if focused {
2128            state.overlay_controller(app).forward(app, None);
2129            if self.should_show_value_indicator_when_dragged(app) {
2130                state.value_indicator_controller(app).forward(app, None);
2131            }
2132        } else {
2133            state.overlay_controller(app).reverse(app, None);
2134            if self.should_show_value_indicator_when_dragged(app) {
2135                state.value_indicator_controller(app).reverse(app, None);
2136            }
2137        }
2138    }
2139
2140    fn update_for_hover(self: RenderHandle<Self>, app: &mut App, hovered: bool) {
2141        let state = self.get(app).state;
2142        // Only show overlay when pointer is hovering the thumb.
2143        if hovered && self.hovering_thumb(app) {
2144            state.overlay_controller(app).forward(app, None);
2145        } else {
2146            // Only remove overlay when Slider is inactive and unfocused.
2147            if !self.get(app).active && !self.has_focus(app) {
2148                state.overlay_controller(app).reverse(app, None);
2149            }
2150        }
2151    }
2152
2153    fn should_always_show_value_indicator(self: RenderHandle<Self>, app: &App) -> bool {
2154        self.slider_theme(app).show_value_indicator == Some(ShowValueIndicator::AlwaysVisible)
2155    }
2156
2157    fn should_show_value_indicator_when_dragged(self: RenderHandle<Self>, app: &App) -> bool {
2158        #[expect(deprecated, reason = "Dart's switch names the deprecated `always`")]
2159        match self
2160            .slider_theme(app)
2161            .show_value_indicator
2162            .expect("the slider fills in its show_value_indicator")
2163        {
2164            ShowValueIndicator::OnlyForDiscrete => self.is_discrete(app),
2165            ShowValueIndicator::OnlyForContinuous => !self.is_discrete(app),
2166            ShowValueIndicator::Always | ShowValueIndicator::OnDrag => true,
2167            ShowValueIndicator::Never | ShowValueIndicator::AlwaysVisible => false,
2168        }
2169    }
2170
2171    fn adjustment_unit(self: RenderHandle<Self>, app: &App) -> f64 {
2172        match self.get(app).platform {
2173            // Matches iOS implementation of material slider.
2174            TargetPlatform::IOS | TargetPlatform::MacOS => 0.1,
2175            // Matches Android implementation of material slider.
2176            TargetPlatform::Android
2177            | TargetPlatform::Fuchsia
2178            | TargetPlatform::Linux
2179            | TargetPlatform::Windows => 0.05,
2180        }
2181    }
2182
2183    fn update_label_painter(self: RenderHandle<Self>, app: &mut App) {
2184        if let Some(label) = self.label(app).map(str::to_owned) {
2185            // Reserve space for the bubble's internal padding and screen margins.
2186            let screen_size = self.screen_size(app);
2187            let safe_max_width =
2188                (screen_size.width() - Self::K_VALUE_INDICATOR_HORIZONTAL_BUFFER).max(0.0);
2189            let mut text = TextSpan::new().text(label);
2190            if let Some(style) = self.slider_theme(app).value_indicator_text_style.clone() {
2191                text = text.style(style);
2192            }
2193            let text_direction = self.text_direction(app);
2194            let text_scale_factor = self.text_scale_factor(app);
2195            let fonts = PaintingBinding::instance(app).fonts(app);
2196            let (this, fonts) = app.get_disjoint_mut(self.handle(), fonts);
2197            let label_painter = &mut this.label_painter;
2198            label_painter.set_text(Some(Rc::new(text)));
2199            label_painter.set_text_direction(Some(text_direction));
2200            label_painter.set_text_scaler(TextScaler::linear(text_scale_factor));
2201            label_painter.set_max_lines(Some(1));
2202            // Standard Unicode ellipsis
2203            label_painter.set_ellipsis(Some("\u{2026}".to_string()));
2204            label_painter.layout(
2205                fonts,
2206                0.0,
2207                if screen_size.width().is_finite() && screen_size.width() > 0.0 {
2208                    safe_max_width
2209                } else {
2210                    f64::INFINITY
2211                },
2212            );
2213        } else {
2214            self.get_mut(app).label_painter.set_text(None);
2215        }
2216        // Changing the textDirection can result in the layout changing, because the
2217        // bidi algorithm might line up the glyphs differently which can result in
2218        // different ligatures, different shapes, etc. So we always markNeedsLayout.
2219        RenderBox::mark_needs_layout(self, app);
2220    }
2221
2222    /// Lends the label painter to a shape's `paint`, which Dart hands the painter object
2223    /// itself: it lives in this render object's arena slot, which the shape's `App` reaches.
2224    fn with_label_painter<R>(
2225        self: RenderHandle<Self>,
2226        app: &mut App,
2227        paint: impl FnOnce(&mut App, &mut TextPainter) -> R,
2228    ) -> R {
2229        let mut label_painter =
2230            std::mem::replace(&mut self.get_mut(app).label_painter, TextPainter::new());
2231        let result = paint(app, &mut label_painter);
2232        self.get_mut(app).label_painter = label_painter;
2233        result
2234    }
2235
2236    fn get_value_from_visual_position(
2237        self: RenderHandle<Self>,
2238        app: &App,
2239        visual_position: f64,
2240    ) -> f64 {
2241        match self.text_direction(app) {
2242            TextDirection::Rtl => 1.0 - visual_position,
2243            TextDirection::Ltr => visual_position,
2244        }
2245    }
2246
2247    fn get_value_from_global_position(
2248        self: RenderHandle<Self>,
2249        app: &App,
2250        global_position: Offset,
2251    ) -> f64 {
2252        let local_dx = self
2253            .as_box()
2254            .global_to_local(app, global_position, None)
2255            .dx();
2256        let padding = self.discrete_rounded_track_padding(app);
2257        let track_rect = self.track_rect(app);
2258        let adjusted_width = track_rect.width() - padding;
2259        // Invert the padded track-geometry formula (see _discreteRoundedTrackPadding)
2260        // so tap coordinates align with the visual tick positions. Without this, the
2261        // snap midpoints in tap space diverge from the visual midpoints between tick
2262        // marks, biasing lower-half taps toward the wrong (lower) division.
2263        let visual_position = if adjusted_width <= 0.0 {
2264            0.5
2265        } else {
2266            (local_dx - track_rect.left - padding / 2.0) / adjusted_width
2267        };
2268        self.get_value_from_visual_position(app, visual_position)
2269    }
2270
2271    fn discretize(self: RenderHandle<Self>, app: &App, value: f64) -> f64 {
2272        let mut result = clamp_double(value, 0.0, 1.0);
2273        if self.is_discrete(app) {
2274            let divisions = f64::from(self.divisions(app).expect("a discrete slider"));
2275            result = (result * divisions).round() / divisions;
2276        }
2277        result
2278    }
2279
2280    fn start_interaction(self: RenderHandle<Self>, app: &mut App, global_position: Offset) {
2281        let state = self.get(app).state;
2282        if !state.mounted(app) {
2283            return;
2284        }
2285        if !self.get(app).active && self.is_interactive(app) {
2286            match self.allowed_interaction(app) {
2287                SliderInteraction::TapAndSlide | SliderInteraction::TapOnly => {
2288                    let current_drag_value =
2289                        self.get_value_from_global_position(app, global_position);
2290                    let this = self.get_mut(app);
2291                    this.active = true;
2292                    this.current_drag_value = current_drag_value;
2293                }
2294                SliderInteraction::SlideThumb => {
2295                    if self.is_pointer_on_overlay(app, global_position) {
2296                        let value = self.value(app);
2297                        let this = self.get_mut(app);
2298                        this.active = true;
2299                        this.current_drag_value = value;
2300                    }
2301                }
2302                SliderInteraction::SlideOnly => {
2303                    let value = self.value(app);
2304                    let this = self.get_mut(app);
2305                    this.active = true;
2306                    this.current_drag_value = value;
2307                }
2308            }
2309
2310            if self.get(app).active {
2311                // We supply the *current* value as the start location, so that if we have
2312                // a tap, it consists of a call to onChangeStart with the previous value and
2313                // a call to onChangeEnd with the new value.
2314                if let Some(on_change_start) = self.get(app).on_change_start.clone() {
2315                    let value = self.discretize(app, self.value(app));
2316                    on_change_start(app, value);
2317                }
2318                let on_changed = self.on_changed(app).expect("an interactive slider");
2319                let value = self.discretize(app, self.get(app).current_drag_value);
2320                on_changed(app, value);
2321                state.overlay_controller(app).forward(app, None);
2322                if self.should_show_value_indicator_when_dragged(app) {
2323                    state.value_indicator_controller(app).forward(app, None);
2324                    if let Some(timer) = app.get_mut(state).interaction_timer.take() {
2325                        timer.cancel(app);
2326                    }
2327                    let time_dilation = SchedulerBinding::time_dilation(app);
2328                    // The timer keeps the render slider, as Dart's closure does: a slider
2329                    // replaced before it fires still reads `active`.
2330                    let this = self.handle().keep(app);
2331                    let timer = Timer::new(
2332                        app,
2333                        Self::MINIMUM_INTERACTION_TIME.mul_f64(time_dilation),
2334                        Listener::new(move |app: &mut App| {
2335                            app.get_mut(state).interaction_timer = None;
2336                            let value_indicator_controller =
2337                                state.value_indicator_controller(app).handle();
2338                            let active = app.get(&this).active;
2339                            if !active && value_indicator_controller.is_completed(app) {
2340                                value_indicator_controller.reverse(app, None);
2341                            }
2342                        }),
2343                    );
2344                    app.get_mut(state).interaction_timer = Some(timer);
2345                }
2346            }
2347        }
2348    }
2349
2350    fn end_interaction(self: RenderHandle<Self>, app: &mut App) {
2351        let state = self.get(app).state;
2352        if !state.mounted(app) {
2353            return;
2354        }
2355
2356        if self.get(app).active && state.mounted(app) {
2357            if let Some(on_change_end) = self.get(app).on_change_end.clone() {
2358                let value = self.discretize(app, self.get(app).current_drag_value);
2359                on_change_end(app, value);
2360            }
2361            let this = self.get_mut(app);
2362            this.active = false;
2363            this.current_drag_value = 0.0;
2364            state.overlay_controller(app).reverse(app, None);
2365            if self.should_show_value_indicator_when_dragged(app)
2366                && app.get(state).interaction_timer.is_none()
2367            {
2368                state.value_indicator_controller(app).reverse(app, None);
2369            }
2370        }
2371    }
2372
2373    fn handle_drag_start(self: RenderHandle<Self>, app: &mut App, details: DragStartDetails) {
2374        self.start_interaction(app, details.global_position);
2375    }
2376
2377    fn handle_drag_update(self: RenderHandle<Self>, app: &mut App, details: DragUpdateDetails) {
2378        if !self.get(app).state.mounted(app) {
2379            return;
2380        }
2381
2382        match self.allowed_interaction(app) {
2383            SliderInteraction::TapAndSlide
2384            | SliderInteraction::SlideOnly
2385            | SliderInteraction::SlideThumb => {
2386                if self.get(app).active && self.is_interactive(app) {
2387                    // Use the same coordinate width as _getValueFromGlobalPosition so
2388                    // that dragging immediately after a tap does not jump.
2389                    let effective_width =
2390                        self.track_rect(app).width() - self.discrete_rounded_track_padding(app);
2391                    if effective_width <= 0.0 {
2392                        return;
2393                    }
2394                    let value_delta = details
2395                        .primary_delta
2396                        .expect("a horizontal drag has a primary delta")
2397                        / effective_width;
2398                    let delta = match self.text_direction(app) {
2399                        TextDirection::Rtl => -value_delta,
2400                        TextDirection::Ltr => value_delta,
2401                    };
2402                    self.get_mut(app).current_drag_value += delta;
2403                    let on_changed = self.on_changed(app).expect("an interactive slider");
2404                    let value = self.discretize(app, self.get(app).current_drag_value);
2405                    on_changed(app, value);
2406                }
2407            }
2408            SliderInteraction::TapOnly => {
2409                // cannot slide (drag) as its tapOnly.
2410            }
2411        }
2412    }
2413
2414    fn handle_drag_end(self: RenderHandle<Self>, app: &mut App, _details: DragEndDetails) {
2415        self.end_interaction(app);
2416    }
2417
2418    fn handle_tap_down(self: RenderHandle<Self>, app: &mut App, details: TapDownDetails) {
2419        self.start_interaction(app, details.global_position);
2420    }
2421
2422    fn handle_tap_up(self: RenderHandle<Self>, app: &mut App, _details: TapUpDetails) {
2423        self.end_interaction(app);
2424    }
2425
2426    fn is_pointer_on_overlay(self: RenderHandle<Self>, app: &App, global_position: Offset) -> bool {
2427        self.get(app)
2428            .overlay_rect
2429            .expect("the slider has painted once")
2430            .contains(self.as_box().global_to_local(app, global_position, None))
2431    }
2432
2433    /// Calculates the local coordinate center of the [`Slider`] thumb given its
2434    /// physical placement on the track from 0.0 (left) to 1.0 (right).
2435    ///
2436    /// The `visual_position` is provided by the caller so semantics can use the
2437    /// raw logical value while paint can use the smoothly animated value.
2438    fn calc_thumb_center(
2439        self: RenderHandle<Self>,
2440        app: &App,
2441        track_rect: Rect,
2442        visual_position: f64,
2443    ) -> Offset {
2444        let padding = if self.track_shape(app).is_rounded() {
2445            track_rect.height()
2446        } else {
2447            0.0
2448        };
2449        let thumb_position = if self.is_discrete(app) {
2450            track_rect.left + visual_position * (track_rect.width() - padding) + padding / 2.0
2451        } else {
2452            track_rect.left + visual_position * track_rect.width()
2453        };
2454        // Apply padding to trackRect.left and trackRect.right if the track height is
2455        // greater than the thumb radius to ensure the thumb is drawn within the track.
2456        let thumb_preferred_size = self
2457            .thumb_shape(app)
2458            .get_preferred_size(self.is_interactive(app), self.is_discrete(app));
2459        let thumb_padding = if padding > thumb_preferred_size.width() / 2.0 {
2460            padding / 2.0
2461        } else {
2462            0.0
2463        };
2464        Offset::new(
2465            clamp_double(
2466                thumb_position,
2467                track_rect.left + thumb_padding,
2468                track_rect.right - thumb_padding,
2469            ),
2470            track_rect.center().dy(),
2471        )
2472    }
2473
2474    fn semantic_action_unit(self: RenderHandle<Self>, app: &App) -> f64 {
2475        match self.divisions(app) {
2476            Some(divisions) => 1.0 / f64::from(divisions),
2477            None => self.adjustment_unit(app),
2478        }
2479    }
2480
2481    /// Dart's `increaseAction`, which the arrow keys run; semantics' increase waits with
2482    /// accessibility.
2483    fn increase_action(self: RenderHandle<Self>, app: &mut App) {
2484        if self.is_interactive(app) {
2485            let on_change_start = self
2486                .get(app)
2487                .on_change_start
2488                .clone()
2489                .expect("the slider's own");
2490            let current_value = self.current_value(app);
2491            on_change_start(app, current_value);
2492            let increase = self.increase_value(app);
2493            let on_changed = self.on_changed(app).expect("an interactive slider");
2494            on_changed(app, increase);
2495            let on_change_end = self
2496                .get(app)
2497                .on_change_end
2498                .clone()
2499                .expect("the slider's own");
2500            on_change_end(app, increase);
2501        }
2502    }
2503
2504    /// Dart's `decreaseAction`, which the arrow keys run; semantics' decrease waits with
2505    /// accessibility.
2506    fn decrease_action(self: RenderHandle<Self>, app: &mut App) {
2507        if self.is_interactive(app) {
2508            let on_change_start = self
2509                .get(app)
2510                .on_change_start
2511                .clone()
2512                .expect("the slider's own");
2513            let current_value = self.current_value(app);
2514            on_change_start(app, current_value);
2515            let decrease = self.decrease_value(app);
2516            let on_changed = self.on_changed(app).expect("an interactive slider");
2517            on_changed(app, decrease);
2518            let on_change_end = self
2519                .get(app)
2520                .on_change_end
2521                .clone()
2522                .expect("the slider's own");
2523            on_change_end(app, decrease);
2524        }
2525    }
2526
2527    fn current_value(self: RenderHandle<Self>, app: &App) -> f64 {
2528        clamp_double(self.value(app), 0.0, 1.0)
2529    }
2530
2531    fn increase_value(self: RenderHandle<Self>, app: &App) -> f64 {
2532        clamp_double(self.value(app) + self.semantic_action_unit(app), 0.0, 1.0)
2533    }
2534
2535    fn decrease_value(self: RenderHandle<Self>, app: &App) -> f64 {
2536        clamp_double(self.value(app) - self.semantic_action_unit(app), 0.0, 1.0)
2537    }
2538}
2539
2540/// Dart's `addListener(markNeedsPaint)` on the slider's animations.
2541fn mark_slider_needs_paint(this: Handle<RenderSlider>, app: &mut App) {
2542    RenderHandle::from_handle(this).mark_needs_paint(app);
2543}
2544
2545impl RelayoutWhenSystemFontsChangeMixin for RenderSlider {
2546    fn relayout_when_system_fonts_change_data(
2547        self: RenderHandle<Self>,
2548        app: &App,
2549    ) -> &RelayoutWhenSystemFontsChangeData {
2550        &self.get(app).system_fonts
2551    }
2552
2553    fn relayout_when_system_fonts_change_data_mut(
2554        self: RenderHandle<Self>,
2555        app: &mut App,
2556    ) -> &mut RelayoutWhenSystemFontsChangeData {
2557        &mut self.get_mut(app).system_fonts
2558    }
2559
2560    fn system_fonts_did_change(self: RenderHandle<Self>, app: &mut App) {
2561        self.as_render_object(app).mark_needs_layout(app);
2562        self.get_mut(app).label_painter.mark_needs_layout();
2563        self.update_label_painter(app);
2564    }
2565}
2566
2567impl RenderObject for RenderSlider {
2568    waft_rendering::render_object_accessors!();
2569
2570    fn sized_by_parent(self: RenderHandle<Self>, _app: &App) -> bool {
2571        true
2572    }
2573
2574    /// `RenderBox.performLayout`: a box sized by its parent lays out nothing more.
2575    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
2576        debug_assert!(self.sized_by_parent(app));
2577    }
2578
2579    fn did_attach(self: RenderHandle<Self>, app: &mut App, _owner: Handle<PipelineOwner>) {
2580        RelayoutWhenSystemFontsChangeMixin::attach_system_fonts(self, app);
2581        let listener = Listener::handle_method(self.handle(), mark_slider_needs_paint);
2582        let this = self.get(app);
2583        let (overlay, value_indicator, enable) = (
2584            this.overlay_animation.clone(),
2585            this.value_indicator_animation.clone(),
2586            this.enable_animation.clone(),
2587        );
2588        let position_controller = this.state.position_controller(app);
2589        overlay.add_listener(app, listener.clone());
2590        value_indicator.add_listener(app, listener.clone());
2591        enable.add_listener(app, listener.clone());
2592        position_controller.add_listener(app, listener);
2593    }
2594
2595    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
2596        let listener = Listener::handle_method(self.handle(), mark_slider_needs_paint);
2597        let this = self.get(app);
2598        let (overlay, value_indicator, enable) = (
2599            this.overlay_animation.clone(),
2600            this.value_indicator_animation.clone(),
2601            this.enable_animation.clone(),
2602        );
2603        let position_controller = this.state.position_controller(app);
2604        overlay.remove_listener(app, &listener);
2605        value_indicator.remove_listener(app, &listener);
2606        enable.remove_listener(app, &listener);
2607        position_controller.remove_listener(app, &listener);
2608        RelayoutWhenSystemFontsChangeMixin::detach_system_fonts(self, app);
2609    }
2610
2611    fn dispose(self: RenderHandle<Self>, app: &mut App) {
2612        let (drag, tap) = (self.get(app).drag.handle(), self.get(app).tap.handle());
2613        RecognizerLeaf::dispose(drag, app);
2614        RecognizerLeaf::dispose(tap, app);
2615        self.get_mut(app).label_painter.dispose();
2616        let this = self.get(app);
2617        let (enable, value_indicator, overlay) = (
2618            this.enable_animation.handle(),
2619            this.value_indicator_animation.handle(),
2620            this.overlay_animation.handle(),
2621        );
2622        for animation in [enable, value_indicator, overlay] {
2623            animation.dispose(app);
2624        }
2625        RenderObjectBase::dispose(self, app);
2626    }
2627
2628    fn paint(
2629        self: RenderHandle<Self>,
2630        app: &mut App,
2631        context: &mut PaintingContext,
2632        offset: Offset,
2633    ) {
2634        let state = self.get(app).state;
2635        let controller_value = state.position_controller(app).value(app);
2636        let text_direction = self.text_direction(app);
2637
2638        // The visual position is the position of the thumb from 0 to 1 from left
2639        // to right. In left to right, this is the same as the value, but it is
2640        // reversed for right to left text.
2641        let secondary_track_value = self.get(app).secondary_track_value;
2642        let (visual_position, secondary_visual_position) =
2643            match (text_direction, secondary_track_value) {
2644                (TextDirection::Rtl, None) => (1.0 - controller_value, None),
2645                (TextDirection::Rtl, Some(secondary_track_value)) => {
2646                    (1.0 - controller_value, Some(1.0 - secondary_track_value))
2647                }
2648                (TextDirection::Ltr, secondary_track_value) => {
2649                    (controller_value, secondary_track_value)
2650                }
2651            };
2652
2653        let is_discrete = self.is_discrete(app);
2654        let is_interactive = self.is_interactive(app);
2655        let slider_theme = self.slider_theme(app).clone();
2656        let track_rect = self.track_shape(app).get_preferred_rect(
2657            app,
2658            self.as_box(),
2659            offset,
2660            &slider_theme,
2661            None,
2662            Some(is_discrete),
2663        );
2664
2665        let thumb_center = self.calc_thumb_center(app, track_rect, visual_position);
2666
2667        if is_interactive {
2668            let overlay_size = self
2669                .overlay_shape(app)
2670                .get_preferred_size(is_interactive, false);
2671            self.get_mut(app).overlay_rect =
2672                Some(Rect::from_circle(thumb_center, overlay_size.width() / 2.0));
2673        }
2674        let secondary_offset = secondary_visual_position.map(|secondary_visual_position| {
2675            Offset::new(
2676                track_rect.left + secondary_visual_position * track_rect.width(),
2677                track_rect.center().dy(),
2678            )
2679        });
2680
2681        // If [Slider.year2023] is false, the thumb uses handle thumb shape and gapped track shape.
2682        // The handle width and track gap are adjusted when the thumb is pressed.
2683        let no_states = WidgetStates::new();
2684        let mut thumb_width = slider_theme
2685            .thumb_size
2686            .as_ref()
2687            .and_then(|thumb_size| thumb_size.resolve(&no_states))
2688            .map(|size| size.width());
2689        let thumb_height = slider_theme
2690            .thumb_size
2691            .as_ref()
2692            .and_then(|thumb_size| thumb_size.resolve(&no_states))
2693            .map(|size| size.height());
2694        let mut track_gap = slider_theme.track_gap;
2695        let pressed_thumb_width = slider_theme
2696            .thumb_size
2697            .as_ref()
2698            .and_then(|thumb_size| thumb_size.resolve(&WidgetStates::from([WidgetState::Pressed])))
2699            .map(|size| size.width());
2700        if let (true, Some(width), Some(pressed_width), Some(gap)) = (
2701            self.get(app).active,
2702            thumb_width,
2703            pressed_thumb_width,
2704            track_gap,
2705        ) {
2706            let delta = width - pressed_width;
2707            if width > 0.0 {
2708                thumb_width = Some(pressed_width);
2709            }
2710            if gap > 0.0 {
2711                track_gap = Some(gap - delta / 2.0);
2712            }
2713        }
2714
2715        let enable_animation = self.get(app).enable_animation.as_animation();
2716        let overlay_animation = self.get(app).overlay_animation.as_animation();
2717        let value_indicator_animation = self.get(app).value_indicator_animation.as_animation();
2718        let mut track_theme = slider_theme.copy_with();
2719        if let Some(track_gap) = track_gap {
2720            track_theme.track_gap = Some(track_gap);
2721        }
2722        self.track_shape(app).paint(
2723            app,
2724            context,
2725            offset,
2726            self.as_box(),
2727            &track_theme,
2728            enable_animation,
2729            thumb_center,
2730            secondary_offset,
2731            Some(is_interactive),
2732            Some(is_discrete),
2733            text_direction,
2734        );
2735
2736        let value = self.value(app);
2737        let text_scale_factor = self.text_scale_factor(app);
2738        let screen_size = self.screen_size(app);
2739        let size_with_overflow = if screen_size.is_empty() {
2740            self.size(app)
2741        } else {
2742            screen_size
2743        };
2744        if !overlay_animation.is_dismissed(app) {
2745            let overlay_shape = self.overlay_shape(app);
2746            self.with_label_painter(app, |app, label_painter| {
2747                overlay_shape.paint(
2748                    app,
2749                    context,
2750                    thumb_center,
2751                    overlay_animation,
2752                    enable_animation,
2753                    is_discrete,
2754                    label_painter,
2755                    self.as_box(),
2756                    &slider_theme,
2757                    text_direction,
2758                    value,
2759                    text_scale_factor,
2760                    size_with_overflow,
2761                );
2762            });
2763        }
2764
2765        if is_discrete {
2766            let divisions = self.divisions(app).expect("a discrete slider");
2767            let tick_mark_shape = slider_theme
2768                .tick_mark_shape
2769                .clone()
2770                .expect("the slider fills in its tick mark shape");
2771            let tick_mark_width = tick_mark_shape
2772                .get_preferred_size(&slider_theme, is_interactive)
2773                .width();
2774            let discrete_track_padding = track_rect.height();
2775            let adjusted_track_width = track_rect.width() - discrete_track_padding;
2776            // If the tick marks would be too dense, don't bother painting them.
2777            if adjusted_track_width / f64::from(divisions) >= 3.0 * tick_mark_width {
2778                let dy = track_rect.center().dy();
2779                for i in 0..=divisions {
2780                    let value = f64::from(i) / f64::from(divisions);
2781                    // The ticks are mapped to be within the track, so the tick mark width
2782                    // must be subtracted from the track width.
2783                    let dx = track_rect.left
2784                        + value * adjusted_track_width
2785                        + discrete_track_padding / 2.0;
2786                    let tick_mark_offset = Offset::new(dx, dy);
2787                    tick_mark_shape.paint(
2788                        app,
2789                        context,
2790                        tick_mark_offset,
2791                        self.as_box(),
2792                        &slider_theme,
2793                        enable_animation,
2794                        thumb_center,
2795                        is_interactive,
2796                        text_direction,
2797                    );
2798                }
2799            }
2800        }
2801
2802        if is_interactive
2803            && self.label(app).is_some()
2804            && ((self.should_show_value_indicator_when_dragged(app)
2805                && !value_indicator_animation.is_dismissed(app))
2806                || self.should_always_show_value_indicator(app))
2807        {
2808            let paint_value_indicator: PaintValueIndicator = Rc::new(
2809                move |app: &mut App, context: &mut PaintingContext, offset: Offset| {
2810                    if self.as_render_object(app).attached(app)
2811                        && self.get(app).label_painter.text().is_some()
2812                    {
2813                        let Some(value_indicator_shape) =
2814                            self.slider_theme(app).value_indicator_shape.clone()
2815                        else {
2816                            return;
2817                        };
2818                        let always = self.should_always_show_value_indicator(app);
2819                        let (activation_animation, enable_animation) = if always {
2820                            (always_stopped_at_one(app), always_stopped_at_one(app))
2821                        } else {
2822                            let this = self.get(app);
2823                            (
2824                                this.value_indicator_animation.as_animation(),
2825                                this.enable_animation.as_animation(),
2826                            )
2827                        };
2828                        let slider_theme = self.slider_theme(app).clone();
2829                        let text_direction = self.text_direction(app);
2830                        let value = self.value(app);
2831                        let text_scale_factor = self.text_scale_factor(app);
2832                        let screen_size = self.screen_size(app);
2833                        let size_with_overflow = if screen_size.is_empty() {
2834                            self.size(app)
2835                        } else {
2836                            screen_size
2837                        };
2838                        let is_discrete = self.is_discrete(app);
2839                        self.with_label_painter(app, |app, label_painter| {
2840                            value_indicator_shape.paint(
2841                                app,
2842                                context,
2843                                offset + thumb_center,
2844                                activation_animation,
2845                                enable_animation,
2846                                is_discrete,
2847                                label_painter,
2848                                self.as_box(),
2849                                &slider_theme,
2850                                text_direction,
2851                                value,
2852                                text_scale_factor,
2853                                size_with_overflow,
2854                            );
2855                        });
2856                    }
2857                },
2858            );
2859            app.get_mut(state).paint_value_indicator = Some(paint_value_indicator);
2860        } else {
2861            app.get_mut(state).paint_value_indicator = None;
2862        }
2863
2864        let thumb_theme = match (thumb_width, thumb_height) {
2865            (Some(thumb_width), Some(thumb_height)) => {
2866                let mut thumb_theme = slider_theme.copy_with();
2867                thumb_theme.thumb_size = Some(Rc::new(WidgetStatePropertyAll::new(Some(
2868                    Size::new(thumb_width, thumb_height),
2869                ))));
2870                thumb_theme
2871            }
2872            _ => slider_theme.clone(),
2873        };
2874        let thumb_shape = self.thumb_shape(app);
2875        self.with_label_painter(app, |app, label_painter| {
2876            thumb_shape.paint(
2877                app,
2878                context,
2879                thumb_center,
2880                overlay_animation,
2881                enable_animation,
2882                is_discrete,
2883                label_painter,
2884                self.as_box(),
2885                &thumb_theme,
2886                text_direction,
2887                value,
2888                text_scale_factor,
2889                size_with_overflow,
2890            );
2891        });
2892    }
2893}
2894
2895impl RenderBox for RenderSlider {
2896    waft_rendering::render_box_accessors!();
2897
2898    fn hit_test_self(self: RenderHandle<Self>, _app: &App, _position: Offset) -> bool {
2899        true
2900    }
2901
2902    fn handle_event(
2903        self: RenderHandle<Self>,
2904        app: &mut App,
2905        event: &PointerEvent,
2906        _entry: &BoxHitTestEntry,
2907    ) {
2908        if !self.get(app).state.mounted(app) {
2909            return;
2910        }
2911        if let PointerEvent::Down(down) = event
2912            && self.is_interactive(app)
2913        {
2914            // We need to add the drag first so that it has priority.
2915            let (drag, tap) = (self.get(app).drag.handle(), self.get(app).tap.handle());
2916            drag.add_pointer(app, down.clone());
2917            tap.add_pointer(app, down.clone());
2918        }
2919        if self.is_interactive(app)
2920            && let Some(overlay_rect) = self.get(app).overlay_rect
2921        {
2922            self.set_hovering_thumb(app, overlay_rect.contains(event.local_position()));
2923        }
2924    }
2925
2926    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, _height: f64) -> f64 {
2927        Self::MIN_PREFERRED_TRACK_WIDTH + self.max_slider_part_width(app)
2928    }
2929
2930    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, _height: f64) -> f64 {
2931        Self::MIN_PREFERRED_TRACK_WIDTH + self.max_slider_part_width(app)
2932    }
2933
2934    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, _width: f64) -> f64 {
2935        self.min_preferred_track_height(app)
2936            .max(self.max_slider_part_height(app))
2937    }
2938
2939    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, _width: f64) -> f64 {
2940        self.min_preferred_track_height(app)
2941            .max(self.max_slider_part_height(app))
2942    }
2943
2944    fn compute_dry_layout(
2945        self: RenderHandle<Self>,
2946        app: &mut App,
2947        constraints: BoxConstraints,
2948    ) -> Size {
2949        Size::new(
2950            if constraints.has_bounded_width() {
2951                constraints.max_width
2952            } else {
2953                Self::MIN_PREFERRED_TRACK_WIDTH + self.max_slider_part_width(app)
2954            },
2955            if constraints.has_bounded_height() {
2956                constraints.max_height
2957            } else {
2958                self.min_preferred_track_height(app)
2959                    .max(self.max_slider_part_height(app))
2960            },
2961        )
2962    }
2963}
2964
2965/// Dart's `_AdjustSliderIntent`.
2966#[derive(Clone, Copy, Debug)]
2967struct AdjustSliderIntent {
2968    adjustment_type: SliderAdjustmentType,
2969}
2970
2971impl AdjustSliderIntent {
2972    const fn new(adjustment_type: SliderAdjustmentType) -> AdjustSliderIntent {
2973        AdjustSliderIntent { adjustment_type }
2974    }
2975}
2976
2977impl Intent for AdjustSliderIntent {
2978    fn as_any(&self) -> &dyn Any {
2979        self
2980    }
2981}
2982
2983#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2984enum SliderAdjustmentType {
2985    Right,
2986    Left,
2987    Up,
2988    Down,
2989}
2990
2991/// Dart's `_ValueIndicatorRenderObjectWidget`.
2992#[derive(Debug)]
2993struct ValueIndicatorRenderObjectWidget {
2994    state: Handle<SliderState>,
2995}
2996
2997impl RenderObjectWidget for ValueIndicatorRenderObjectWidget {
2998    type RenderObject = RenderValueIndicator;
2999
3000    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
3001        RenderValueIndicator::new(app, self.state).as_object()
3002    }
3003
3004    fn update_render_object(
3005        &self,
3006        app: &mut App,
3007        _context: BuildContext,
3008        render_object: RenderHandle<RenderValueIndicator>,
3009    ) {
3010        render_object.get_mut(app).state = self.state;
3011    }
3012}
3013
3014impl LeafRenderObjectWidget for ValueIndicatorRenderObjectWidget {}
3015
3016/// Dart's `_RenderValueIndicator extends RenderBox with RelayoutWhenSystemFontsChangeMixin`.
3017pub(crate) struct RenderValueIndicator {
3018    render_object: RenderObjectData,
3019    render_box: RenderBoxData,
3020    system_fonts: RelayoutWhenSystemFontsChangeData,
3021    value_indicator_animation: Ref<CurvedAnimation>,
3022    state: Handle<SliderState>,
3023}
3024
3025impl RenderValueIndicator {
3026    fn new(app: &mut App, state: Handle<SliderState>) -> RenderHandle<RenderValueIndicator> {
3027        let value_indicator_animation = CurvedAnimation::new(
3028            app,
3029            state.value_indicator_controller(app).erase(),
3030            Curves::fast_out_slow_in(),
3031            None,
3032        );
3033        RenderHandle::new_box(
3034            app,
3035            RenderValueIndicator {
3036                render_object: RenderObjectData::new(),
3037                render_box: RenderBoxData::new(),
3038                system_fonts: RelayoutWhenSystemFontsChangeData::new(),
3039                value_indicator_animation,
3040                state,
3041            },
3042        )
3043    }
3044}
3045
3046/// Dart's `addListener(markNeedsPaint)` on the value indicator's animations.
3047fn mark_value_indicator_needs_paint(this: Handle<RenderValueIndicator>, app: &mut App) {
3048    RenderHandle::from_handle(this).mark_needs_paint(app);
3049}
3050
3051impl RelayoutWhenSystemFontsChangeMixin for RenderValueIndicator {
3052    fn relayout_when_system_fonts_change_data(
3053        self: RenderHandle<Self>,
3054        app: &App,
3055    ) -> &RelayoutWhenSystemFontsChangeData {
3056        &self.get(app).system_fonts
3057    }
3058
3059    fn relayout_when_system_fonts_change_data_mut(
3060        self: RenderHandle<Self>,
3061        app: &mut App,
3062    ) -> &mut RelayoutWhenSystemFontsChangeData {
3063        &mut self.get_mut(app).system_fonts
3064    }
3065}
3066
3067impl RenderObject for RenderValueIndicator {
3068    waft_rendering::render_object_accessors!();
3069
3070    fn sized_by_parent(self: RenderHandle<Self>, _app: &App) -> bool {
3071        true
3072    }
3073
3074    /// `RenderBox.performLayout`: a box sized by its parent lays out nothing more.
3075    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
3076        debug_assert!(self.sized_by_parent(app));
3077    }
3078
3079    fn did_attach(self: RenderHandle<Self>, app: &mut App, _owner: Handle<PipelineOwner>) {
3080        RelayoutWhenSystemFontsChangeMixin::attach_system_fonts(self, app);
3081        let listener = Listener::handle_method(self.handle(), mark_value_indicator_needs_paint);
3082        let animation = self.get(app).value_indicator_animation.handle();
3083        let position_controller = self.get(app).state.position_controller(app);
3084        animation.add_listener(app, listener.clone());
3085        position_controller.add_listener(app, listener);
3086    }
3087
3088    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
3089        let listener = Listener::handle_method(self.handle(), mark_value_indicator_needs_paint);
3090        let animation = self.get(app).value_indicator_animation.handle();
3091        let position_controller = self.get(app).state.position_controller(app);
3092        animation.remove_listener(app, &listener);
3093        position_controller.remove_listener(app, &listener);
3094        RelayoutWhenSystemFontsChangeMixin::detach_system_fonts(self, app);
3095    }
3096
3097    fn paint(
3098        self: RenderHandle<Self>,
3099        app: &mut App,
3100        context: &mut PaintingContext,
3101        offset: Offset,
3102    ) {
3103        let state = self.get(app).state;
3104        if let Some(paint_value_indicator) = app.get(state).paint_value_indicator.clone() {
3105            paint_value_indicator(app, context, offset);
3106        }
3107    }
3108
3109    fn dispose(self: RenderHandle<Self>, app: &mut App) {
3110        let value_indicator_animation = self.get(app).value_indicator_animation.handle();
3111        value_indicator_animation.dispose(app);
3112        RenderObjectBase::dispose(self, app);
3113    }
3114}
3115
3116impl RenderBox for RenderValueIndicator {
3117    waft_rendering::render_box_accessors!();
3118
3119    fn compute_dry_layout(
3120        self: RenderHandle<Self>,
3121        _app: &mut App,
3122        constraints: BoxConstraints,
3123    ) -> Size {
3124        constraints.smallest()
3125    }
3126}
3127
3128/// Dart's `const AlwaysStoppedAnimation<double>(1)`, which Dart canonicalizes into one
3129/// object, kept per [`App`] and made on first use; the `App` keeps it for its life.
3130#[derive(Default)]
3131struct AlwaysStoppedAtOne {
3132    animation: Option<Ref<AlwaysStoppedAnimation<f64>>>,
3133}
3134
3135pub(crate) fn always_stopped_at_one(app: &mut App) -> AnyAnimation<f64> {
3136    let statics = app.singleton::<AlwaysStoppedAtOne>();
3137    if let Some(animation) = app.get(statics).animation.handle() {
3138        return animation.as_animation();
3139    }
3140    let animation = app.create(AlwaysStoppedAnimation::new(1.0));
3141    app.get_mut(statics).animation = Some(animation.clone());
3142    animation.as_animation()
3143}
3144
3145/// Dart's `_SliderDefaultsM2`.
3146struct SliderDefaultsM2 {
3147    /// Dart's `super(..)` arguments.
3148    slider_theme_data: SliderThemeData,
3149    context: DefaultsContext,
3150}
3151
3152impl SliderDefaultsM2 {
3153    fn new(context: BuildContext) -> SliderDefaultsM2 {
3154        SliderDefaultsM2 {
3155            slider_theme_data: SliderThemeData::new().track_height(4.0),
3156            context: DefaultsContext::new(context),
3157        }
3158    }
3159}
3160
3161#[allow(deprecated)]
3162impl SliderThemeDataGetters for SliderDefaultsM2 {
3163    fn slider_theme_data(&self) -> &SliderThemeData {
3164        &self.slider_theme_data
3165    }
3166
3167    fn active_track_color(&self, app: &mut App) -> Option<Color> {
3168        let theme = self.context.theme(app);
3169        let colors = &theme.color_scheme;
3170        Some(colors.primary())
3171    }
3172
3173    fn inactive_track_color(&self, app: &mut App) -> Option<Color> {
3174        let theme = self.context.theme(app);
3175        let colors = &theme.color_scheme;
3176        Some(colors.primary().with_opacity(0.24))
3177    }
3178
3179    fn secondary_active_track_color(&self, app: &mut App) -> Option<Color> {
3180        let theme = self.context.theme(app);
3181        let colors = &theme.color_scheme;
3182        Some(colors.primary().with_opacity(0.54))
3183    }
3184
3185    fn disabled_active_track_color(&self, app: &mut App) -> Option<Color> {
3186        let theme = self.context.theme(app);
3187        let colors = &theme.color_scheme;
3188        Some(colors.on_surface().with_opacity(0.32))
3189    }
3190
3191    fn disabled_inactive_track_color(&self, app: &mut App) -> Option<Color> {
3192        let theme = self.context.theme(app);
3193        let colors = &theme.color_scheme;
3194        Some(colors.on_surface().with_opacity(0.12))
3195    }
3196
3197    fn disabled_secondary_active_track_color(&self, app: &mut App) -> Option<Color> {
3198        let theme = self.context.theme(app);
3199        let colors = &theme.color_scheme;
3200        Some(colors.on_surface().with_opacity(0.12))
3201    }
3202
3203    fn active_tick_mark_color(&self, app: &mut App) -> Option<Color> {
3204        let theme = self.context.theme(app);
3205        let colors = &theme.color_scheme;
3206        Some(colors.on_primary().with_opacity(0.54))
3207    }
3208
3209    fn inactive_tick_mark_color(&self, app: &mut App) -> Option<Color> {
3210        let theme = self.context.theme(app);
3211        let colors = &theme.color_scheme;
3212        Some(colors.primary().with_opacity(0.54))
3213    }
3214
3215    fn disabled_active_tick_mark_color(&self, app: &mut App) -> Option<Color> {
3216        let theme = self.context.theme(app);
3217        let colors = &theme.color_scheme;
3218        Some(colors.on_primary().with_opacity(0.12))
3219    }
3220
3221    fn disabled_inactive_tick_mark_color(&self, app: &mut App) -> Option<Color> {
3222        let theme = self.context.theme(app);
3223        let colors = &theme.color_scheme;
3224        Some(colors.on_surface().with_opacity(0.12))
3225    }
3226
3227    fn thumb_color(&self, app: &mut App) -> Option<Color> {
3228        let theme = self.context.theme(app);
3229        let colors = &theme.color_scheme;
3230        Some(colors.primary())
3231    }
3232
3233    fn disabled_thumb_color(&self, app: &mut App) -> Option<Color> {
3234        let theme = self.context.theme(app);
3235        let colors = &theme.color_scheme;
3236        Some(Color::alpha_blend(
3237            colors.on_surface().with_opacity(0.38),
3238            colors.surface(),
3239        ))
3240    }
3241
3242    fn overlay_color(&self, app: &mut App) -> Option<AnyColor> {
3243        let theme = self.context.theme(app);
3244        let colors = &theme.color_scheme;
3245        Some(colors.primary().with_opacity(0.12).into())
3246    }
3247
3248    fn value_indicator_color(&self, app: &mut App) -> Option<Color> {
3249        let theme = self.context.theme(app);
3250        let colors = &theme.color_scheme;
3251        let slider_theme = SliderTheme::of(app, self.context.context());
3252        Some(
3253            if slider_theme
3254                .value_indicator_shape
3255                .as_ref()
3256                .is_some_and(|shape| shape.as_any().is::<RoundedRectSliderValueIndicatorShape>())
3257            {
3258                colors.inverse_surface()
3259            } else {
3260                colors.primary()
3261            },
3262        )
3263    }
3264
3265    fn value_indicator_shape(&self, _app: &mut App) -> Option<SliderComponentShapeRef> {
3266        Some(Rc::new(RectangularSliderValueIndicatorShape::new()))
3267    }
3268
3269    fn thumb_shape(&self, _app: &mut App) -> Option<SliderComponentShapeRef> {
3270        Some(Rc::new(RoundSliderThumbShape::new()))
3271    }
3272
3273    fn track_shape(&self, _app: &mut App) -> Option<SliderTrackShapeRef> {
3274        Some(Rc::new(RoundedRectSliderTrackShape::new()))
3275    }
3276
3277    fn overlay_shape(&self, _app: &mut App) -> Option<SliderComponentShapeRef> {
3278        Some(Rc::new(RoundSliderOverlayShape::new()))
3279    }
3280
3281    fn tick_mark_shape(&self, _app: &mut App) -> Option<SliderTickMarkShapeRef> {
3282        Some(Rc::new(RoundSliderTickMarkShape::new()))
3283    }
3284
3285    fn value_indicator_text_style(&self, app: &mut App) -> Option<TextStyle> {
3286        let theme = self.context.theme(app);
3287        let colors = &theme.color_scheme;
3288        Some(
3289            theme
3290                .text_theme
3291                .body_large
3292                .as_ref()
3293                .expect("the text theme has a body large style")
3294                .copy_with()
3295                .color(colors.on_primary()),
3296        )
3297    }
3298}
3299
3300/// Dart's `_SliderDefaultsM3Year2023`.
3301struct SliderDefaultsM3Year2023 {
3302    /// Dart's `super(..)` arguments.
3303    slider_theme_data: SliderThemeData,
3304    context: DefaultsContext,
3305}
3306
3307impl SliderDefaultsM3Year2023 {
3308    fn new(context: BuildContext) -> SliderDefaultsM3Year2023 {
3309        SliderDefaultsM3Year2023 {
3310            slider_theme_data: SliderThemeData::new().track_height(4.0),
3311            context: DefaultsContext::new(context),
3312        }
3313    }
3314}
3315
3316#[allow(deprecated)]
3317impl SliderThemeDataGetters for SliderDefaultsM3Year2023 {
3318    fn slider_theme_data(&self) -> &SliderThemeData {
3319        &self.slider_theme_data
3320    }
3321
3322    fn active_track_color(&self, app: &mut App) -> Option<Color> {
3323        let theme = self.context.theme(app);
3324        let colors = &theme.color_scheme;
3325        Some(colors.primary())
3326    }
3327
3328    fn inactive_track_color(&self, app: &mut App) -> Option<Color> {
3329        let theme = self.context.theme(app);
3330        let colors = &theme.color_scheme;
3331        Some(colors.surface_container_highest())
3332    }
3333
3334    fn secondary_active_track_color(&self, app: &mut App) -> Option<Color> {
3335        let theme = self.context.theme(app);
3336        let colors = &theme.color_scheme;
3337        Some(colors.primary().with_opacity(0.54))
3338    }
3339
3340    fn disabled_active_track_color(&self, app: &mut App) -> Option<Color> {
3341        let theme = self.context.theme(app);
3342        let colors = &theme.color_scheme;
3343        Some(colors.on_surface().with_opacity(0.38))
3344    }
3345
3346    fn disabled_inactive_track_color(&self, app: &mut App) -> Option<Color> {
3347        let theme = self.context.theme(app);
3348        let colors = &theme.color_scheme;
3349        Some(colors.on_surface().with_opacity(0.12))
3350    }
3351
3352    fn disabled_secondary_active_track_color(&self, app: &mut App) -> Option<Color> {
3353        let theme = self.context.theme(app);
3354        let colors = &theme.color_scheme;
3355        Some(colors.on_surface().with_opacity(0.12))
3356    }
3357
3358    fn active_tick_mark_color(&self, app: &mut App) -> Option<Color> {
3359        let theme = self.context.theme(app);
3360        let colors = &theme.color_scheme;
3361        Some(colors.on_primary().with_opacity(0.38))
3362    }
3363
3364    fn inactive_tick_mark_color(&self, app: &mut App) -> Option<Color> {
3365        let theme = self.context.theme(app);
3366        let colors = &theme.color_scheme;
3367        Some(colors.on_surface_variant().with_opacity(0.38))
3368    }
3369
3370    fn disabled_active_tick_mark_color(&self, app: &mut App) -> Option<Color> {
3371        let theme = self.context.theme(app);
3372        let colors = &theme.color_scheme;
3373        Some(colors.on_surface().with_opacity(0.38))
3374    }
3375
3376    fn disabled_inactive_tick_mark_color(&self, app: &mut App) -> Option<Color> {
3377        let theme = self.context.theme(app);
3378        let colors = &theme.color_scheme;
3379        Some(colors.on_surface().with_opacity(0.38))
3380    }
3381
3382    fn thumb_color(&self, app: &mut App) -> Option<Color> {
3383        let theme = self.context.theme(app);
3384        let colors = &theme.color_scheme;
3385        Some(colors.primary())
3386    }
3387
3388    fn disabled_thumb_color(&self, app: &mut App) -> Option<Color> {
3389        let theme = self.context.theme(app);
3390        let colors = &theme.color_scheme;
3391        Some(Color::alpha_blend(
3392            colors.on_surface().with_opacity(0.38),
3393            colors.surface(),
3394        ))
3395    }
3396
3397    fn overlay_color(&self, app: &mut App) -> Option<AnyColor> {
3398        let theme = self.context.theme(app);
3399        let colors = &theme.color_scheme;
3400        let primary = colors.primary();
3401        Some(
3402            WidgetStateColor::resolve_with(move |states: &WidgetStates| {
3403                if states.contains(&WidgetState::Dragged) {
3404                    return primary.with_opacity(0.1);
3405                }
3406                if states.contains(&WidgetState::Hovered) {
3407                    return primary.with_opacity(0.08);
3408                }
3409                if states.contains(&WidgetState::Focused) {
3410                    return primary.with_opacity(0.1);
3411                }
3412
3413                Colors::TRANSPARENT
3414            })
3415            .into_any(),
3416        )
3417    }
3418
3419    fn value_indicator_color(&self, app: &mut App) -> Option<Color> {
3420        let theme = self.context.theme(app);
3421        let colors = &theme.color_scheme;
3422        Some(colors.primary())
3423    }
3424
3425    fn value_indicator_shape(&self, _app: &mut App) -> Option<SliderComponentShapeRef> {
3426        Some(Rc::new(DropSliderValueIndicatorShape::new()))
3427    }
3428
3429    fn thumb_shape(&self, _app: &mut App) -> Option<SliderComponentShapeRef> {
3430        Some(Rc::new(RoundSliderThumbShape::new()))
3431    }
3432
3433    fn track_shape(&self, _app: &mut App) -> Option<SliderTrackShapeRef> {
3434        Some(Rc::new(RoundedRectSliderTrackShape::new()))
3435    }
3436
3437    fn overlay_shape(&self, _app: &mut App) -> Option<SliderComponentShapeRef> {
3438        Some(Rc::new(RoundSliderOverlayShape::new()))
3439    }
3440
3441    fn tick_mark_shape(&self, _app: &mut App) -> Option<SliderTickMarkShapeRef> {
3442        Some(Rc::new(RoundSliderTickMarkShape::new()))
3443    }
3444
3445    fn value_indicator_text_style(&self, app: &mut App) -> Option<TextStyle> {
3446        let theme = self.context.theme(app);
3447        let colors = &theme.color_scheme;
3448        Some(
3449            theme
3450                .text_theme
3451                .label_medium
3452                .as_ref()
3453                .expect("the text theme has a label medium style")
3454                .copy_with()
3455                .color(colors.on_primary()),
3456        )
3457    }
3458}
3459
3460#[cfg(test)]
3461pub(crate) mod tests {
3462    use std::cell::{Cell, RefCell};
3463
3464    use waft_embedder::valo::Op;
3465    use waft_widgets::{Center, StatefulBuilder};
3466
3467    use waft_widgets::testing::{
3468        TargetPlatformVariant, TestPointer, WidgetTester, expect, find, finds_nothing,
3469        finds_one_widget, test_widgets, test_widgets_variant,
3470    };
3471
3472    use super::*;
3473    use crate::material::Material;
3474    use crate::slider_parts::SliderTickMarkShape;
3475    use crate::slider_value_indicator_shape::SliderComponentShape;
3476    use crate::test_support::material_app;
3477
3478    pub(crate) use crate::test_support::PaintInspection;
3479    use crate::theme_data::ThemeData;
3480    use waft_rendering::testing::{
3481        CanvasMethod, PaintCall, assert_paints, colors_match, count_calls, paints,
3482    };
3483
3484    /// Dart's `LoggingThumbShape`: a thumb shape that also logs its repaint center.
3485    #[derive(Debug)]
3486    struct LoggingThumbShape {
3487        log: Rc<RefCell<Vec<Offset>>>,
3488    }
3489
3490    impl SliderComponentShape for LoggingThumbShape {
3491        fn get_preferred_size(&self, _is_enabled: bool, _is_discrete: bool) -> Size {
3492            Size::new(10.0, 10.0)
3493        }
3494
3495        fn paint(
3496            &self,
3497            _app: &mut App,
3498            context: &mut PaintingContext,
3499            thumb_center: Offset,
3500            _activation_animation: AnyAnimation<f64>,
3501            _enable_animation: AnyAnimation<f64>,
3502            _is_discrete: bool,
3503            _label_painter: &mut TextPainter,
3504            _parent_box: waft_rendering::AnyRenderBox,
3505            _slider_theme: &SliderThemeData,
3506            _text_direction: TextDirection,
3507            _value: f64,
3508            _text_scale_factor: f64,
3509            _size_with_overflow: Size,
3510        ) {
3511            use waft_painting::ClipContext;
3512            self.log.borrow_mut().push(thumb_center);
3513            context.canvas().draw_circle(
3514                thumb_center,
3515                5.0,
3516                &waft_embedder::Paint::from_color(Colors::RED.primary().into()),
3517            );
3518        }
3519
3520        fn as_any(&self) -> &dyn Any {
3521            self
3522        }
3523    }
3524
3525    /// Dart's `TallSliderTickMarkShape`.
3526    #[derive(Debug)]
3527    struct TallSliderTickMarkShape;
3528
3529    impl SliderTickMarkShape for TallSliderTickMarkShape {
3530        fn get_preferred_size(&self, _slider_theme: &SliderThemeData, _is_enabled: bool) -> Size {
3531            Size::new(10.0, 200.0)
3532        }
3533
3534        fn paint(
3535            &self,
3536            _app: &mut App,
3537            context: &mut PaintingContext,
3538            offset: Offset,
3539            _parent_box: waft_rendering::AnyRenderBox,
3540            _slider_theme: &SliderThemeData,
3541            _enable_animation: AnyAnimation<f64>,
3542            _thumb_center: Offset,
3543            _is_enabled: bool,
3544            _text_direction: TextDirection,
3545        ) {
3546            use waft_painting::ClipContext;
3547            context.canvas().draw_rect(
3548                Rect::from_ltwh(offset.dx(), offset.dy(), 10.0, 20.0),
3549                &waft_embedder::Paint::from_color(Colors::RED.primary().into()),
3550            );
3551        }
3552
3553        fn as_any(&self) -> &dyn Any {
3554            self
3555        }
3556    }
3557
3558    /// What a test's slider callbacks heard.
3559    #[derive(Default)]
3560    struct Heard {
3561        value: Cell<f64>,
3562        start_value: Cell<Option<f64>>,
3563        end_value: Cell<Option<f64>>,
3564        updates: Cell<usize>,
3565        start_updates: Cell<usize>,
3566        end_updates: Cell<usize>,
3567    }
3568
3569    impl Heard {
3570        fn starting_at(value: f64) -> Rc<Heard> {
3571            let heard = Rc::new(Heard::default());
3572            heard.value.set(value);
3573            heard
3574        }
3575    }
3576
3577    /// A slider configured by `configure`, its `value` and callbacks wired to `heard`.
3578    fn slider(
3579        heard: &Rc<Heard>,
3580        set_state: StateSetterRef,
3581        configure: impl Fn(Slider) -> Slider,
3582    ) -> Slider {
3583        let on_changed_heard = Rc::clone(heard);
3584        let start_heard = Rc::clone(heard);
3585        let end_heard = Rc::clone(heard);
3586        configure(
3587            Slider::new(
3588                heard.value.get(),
3589                Some(Rc::new(move |app: &mut App, new_value: f64| {
3590                    let heard = Rc::clone(&on_changed_heard);
3591                    set_state(app, &mut |_app| {
3592                        heard.updates.set(heard.updates.get() + 1);
3593                        heard.value.set(new_value);
3594                    });
3595                })),
3596            )
3597            .on_change_start(Rc::new(move |_app: &mut App, value: f64| {
3598                start_heard
3599                    .start_updates
3600                    .set(start_heard.start_updates.get() + 1);
3601                start_heard.start_value.set(Some(value));
3602            }))
3603            .on_change_end(Rc::new(move |_app: &mut App, value: f64| {
3604                end_heard.end_updates.set(end_heard.end_updates.get() + 1);
3605                end_heard.end_value.set(Some(value));
3606            })),
3607        )
3608    }
3609
3610    type StateSetterRef = waft_widgets::StateSetter;
3611
3612    /// Dart's `MaterialApp(home: Directionality(child: StatefulBuilder(... Material(child:
3613    /// Center(child: wrap(Slider(...)))))))`, the shape most cases pump.
3614    fn stateful_slider_app(
3615        tester: &WidgetTester,
3616        theme: ThemeData,
3617        text_direction: TextDirection,
3618        heard: &Rc<Heard>,
3619        build: impl Fn(&mut App, BuildContext, Slider) -> WidgetRef + 'static,
3620        configure: impl Fn(Slider) -> Slider + 'static,
3621    ) -> WidgetRef {
3622        let _ = tester;
3623        let heard = Rc::clone(heard);
3624        material_app(
3625            theme,
3626            Directionality::new(
3627                text_direction,
3628                StatefulBuilder::new(move |app, context, set_state| {
3629                    let slider = slider(&heard, set_state, &configure);
3630                    Material::new()
3631                        .child(Center::new().child(build(app, context, slider)))
3632                        .into_widget()
3633                }),
3634            )
3635            .into_widget(),
3636        )
3637    }
3638
3639    fn plain(_app: &mut App, _context: BuildContext, slider: Slider) -> WidgetRef {
3640        slider.into_widget()
3641    }
3642
3643    /// Dart's `ThemeData()`.
3644    pub(crate) fn default_theme(tester: &WidgetTester) -> ThemeData {
3645        ThemeData::builder().build(&tester.cell.borrow())
3646    }
3647
3648    pub(crate) fn slider_rect(tester: &WidgetTester) -> Rect {
3649        let slider = find::by_type::<Slider>().evaluate(tester)[0];
3650        let render = tester.render_box_of(slider);
3651        tester.get_rect(render)
3652    }
3653
3654    fn transient_callback_count(tester: &WidgetTester) -> usize {
3655        SchedulerBinding::transient_callback_count(&mut tester.cell.borrow_mut())
3656    }
3657
3658    // 'The initial value should respect the discrete value'.
3659    #[test]
3660    fn the_initial_value_should_respect_the_discrete_value() {
3661        test_widgets(|tester| {
3662            let heard = Heard::starting_at(0.20);
3663            let log = Rc::new(RefCell::new(Vec::new()));
3664            let thumb_log = Rc::clone(&log);
3665            let theme = default_theme(tester);
3666            tester.pump_widget(stateful_slider_app(
3667                tester,
3668                theme,
3669                TextDirection::Ltr,
3670                &heard,
3671                move |app, context, slider| {
3672                    let slider_theme =
3673                        SliderTheme::of(app, context)
3674                            .copy_with()
3675                            .thumb_shape(Rc::new(LoggingThumbShape {
3676                                log: Rc::clone(&thumb_log),
3677                            }));
3678                    SliderTheme::new(slider_theme, slider).into_widget()
3679                },
3680                |slider| slider.divisions(4),
3681            ));
3682
3683            assert_eq!(heard.value.get(), 0.20);
3684            assert_eq!(log.borrow().len(), 1);
3685            assert_eq!(log.borrow()[0], Offset::new(213.0, 300.0));
3686        });
3687    }
3688
3689    // 'Slider can move when tapped (LTR)'.
3690    #[test]
3691    fn a_slider_moves_when_tapped_ltr() {
3692        test_widgets(|tester| {
3693            let heard = Heard::starting_at(0.0);
3694            let theme = default_theme(tester);
3695            tester.pump_widget(stateful_slider_app(
3696                tester,
3697                theme,
3698                TextDirection::Ltr,
3699                &heard,
3700                plain,
3701                |slider| slider,
3702            ));
3703
3704            assert_eq!(heard.value.get(), 0.0);
3705            tester.tap_at(slider_rect(tester).center(), 1);
3706            assert_eq!(heard.value.get(), 0.5);
3707            assert_eq!(heard.start_value.get(), Some(0.0));
3708            assert_eq!(heard.end_value.get(), Some(0.5));
3709            heard.start_value.set(None);
3710            heard.end_value.set(None);
3711            tester.pump(); // No animation should start.
3712            assert_eq!(transient_callback_count(tester), 0);
3713
3714            let rect = slider_rect(tester);
3715            let target = rect.top_left() + (rect.bottom_right() - rect.top_left()) / 4.0;
3716            tester.tap_at(target, 2);
3717            assert!((heard.value.get() - 0.25).abs() <= 0.05);
3718            assert_eq!(heard.start_value.get(), Some(0.5));
3719            assert!((heard.end_value.get().unwrap() - 0.25).abs() <= 0.05);
3720            tester.pump(); // No animation should start.
3721            assert_eq!(transient_callback_count(tester), 0);
3722        });
3723    }
3724
3725    // 'Slider can move when tapped (RTL)'.
3726    #[test]
3727    fn a_slider_moves_when_tapped_rtl() {
3728        test_widgets(|tester| {
3729            let heard = Heard::starting_at(0.0);
3730            let theme = default_theme(tester);
3731            tester.pump_widget(stateful_slider_app(
3732                tester,
3733                theme,
3734                TextDirection::Rtl,
3735                &heard,
3736                plain,
3737                |slider| slider,
3738            ));
3739
3740            assert_eq!(heard.value.get(), 0.0);
3741            tester.tap_at(slider_rect(tester).center(), 1);
3742            assert_eq!(heard.value.get(), 0.5);
3743            tester.pump(); // No animation should start.
3744            assert_eq!(transient_callback_count(tester), 0);
3745
3746            let rect = slider_rect(tester);
3747            let target = rect.top_left() + (rect.bottom_right() - rect.top_left()) / 4.0;
3748            tester.tap_at(target, 2);
3749            assert!((heard.value.get() - 0.75).abs() <= 0.05);
3750            tester.pump(); // No animation should start.
3751            assert_eq!(transient_callback_count(tester), 0);
3752        });
3753    }
3754
3755    // "Slider doesn't send duplicate change events if tapped on the same value".
3756    #[test]
3757    fn a_slider_sends_no_duplicate_change_events_when_tapped_on_the_same_value() {
3758        test_widgets(|tester| {
3759            let heard = Heard::starting_at(0.0);
3760            let theme = default_theme(tester);
3761            tester.pump_widget(stateful_slider_app(
3762                tester,
3763                theme,
3764                TextDirection::Ltr,
3765                &heard,
3766                plain,
3767                |slider| slider,
3768            ));
3769
3770            assert_eq!(heard.value.get(), 0.0);
3771            tester.tap_at(slider_rect(tester).center(), 1);
3772            assert_eq!(heard.value.get(), 0.5);
3773            assert_eq!(heard.start_value.get(), Some(0.0));
3774            assert_eq!(heard.end_value.get(), Some(0.5));
3775            tester.pump();
3776            tester.tap_at(slider_rect(tester).center(), 2);
3777            assert_eq!(heard.value.get(), 0.5);
3778            tester.pump();
3779            assert_eq!(heard.updates.get(), 1);
3780            assert_eq!(heard.start_updates.get(), 2);
3781            assert_eq!(heard.end_updates.get(), 2);
3782        });
3783    }
3784
3785    // 'Value indicator shows for a bit after being tapped'.
3786    #[test]
3787    fn the_value_indicator_shows_for_a_bit_after_a_tap() {
3788        test_widgets(|tester| {
3789            let heard = Heard::starting_at(0.0);
3790            let theme = default_theme(tester);
3791            tester.pump_widget(stateful_slider_app(
3792                tester,
3793                theme,
3794                TextDirection::Ltr,
3795                &heard,
3796                plain,
3797                |slider| slider.divisions(4),
3798            ));
3799
3800            assert_eq!(heard.value.get(), 0.0);
3801            tester.tap_at(slider_rect(tester).center(), 1);
3802            assert_eq!(heard.value.get(), 0.5);
3803            tester.pump_by(Duration::from_millis(100));
3804            // Starts with the position animation and value indicator
3805            assert_eq!(transient_callback_count(tester), 2);
3806            tester.pump_by(Duration::from_millis(100));
3807            // Value indicator is longer than position.
3808            assert_eq!(transient_callback_count(tester), 1);
3809            tester.pump_by(Duration::from_millis(100));
3810            assert_eq!(transient_callback_count(tester), 0);
3811            tester.pump_by(Duration::from_millis(100));
3812            assert_eq!(transient_callback_count(tester), 0);
3813            tester.pump_by(Duration::from_millis(100));
3814            // Shown for long enough, value indicator is animated closed.
3815            assert_eq!(transient_callback_count(tester), 1);
3816            tester.pump_by(Duration::from_millis(101));
3817            assert_eq!(transient_callback_count(tester), 0);
3818        });
3819    }
3820
3821    /// The bounds of `path` when it is what `Canvas::draw_circle` records: one square contour
3822    /// of a move, four conic quarters and a close, which a zero radius records too. A rounded
3823    /// rect's contour has lines between its corners.
3824    pub(crate) fn circle_of(path: &waft_embedder::valo::Path) -> Option<Rect> {
3825        let bounds = path.bounds();
3826        // The conics' f32 points leave the two extents a rounding apart.
3827        let square = (bounds.width - bounds.height).abs() <= 1e-4 * bounds.width.max(1.0);
3828        (path.elements().count() == 6 && square).then(|| {
3829            Rect::from_ltwh(
3830                f64::from(bounds.x),
3831                f64::from(bounds.y),
3832                f64::from(bounds.width),
3833                f64::from(bounds.height),
3834            )
3835        })
3836    }
3837
3838    /// The circles `render` and its subtree draw: Dart's `drawCircle` calls.
3839    fn circles(tester: &WidgetTester, render: AnyRenderObject) -> Vec<Rect> {
3840        tester
3841            .painted_ops(render)
3842            .iter()
3843            .filter_map(|op| match op {
3844                Op::DrawPath { path, .. } => circle_of(path),
3845                _ => None,
3846            })
3847            .collect()
3848    }
3849
3850    pub(crate) fn slider_render(tester: &WidgetTester) -> AnyRenderObject {
3851        tester
3852            .first::<RenderSlider>()
3853            .as_render_object(&tester.cell.borrow())
3854    }
3855
3856    /// The value indicator box of Dart's cases: `tester.renderObject(find.byType(Overlay))`.
3857    /// Its route children are repaint boundaries, so a case reads it through `painted_ops_deep`.
3858    pub(crate) fn overlay_render(tester: &WidgetTester) -> AnyRenderObject {
3859        tester
3860            .render_box_of(find::by_type::<waft_widgets::Overlay>().evaluate(tester)[0])
3861            .as_object()
3862    }
3863
3864    // 'Tick marks are skipped when they are too dense'.
3865    #[test]
3866    fn tick_marks_are_skipped_when_too_dense() {
3867        test_widgets(|tester| {
3868            let theme = default_theme(tester);
3869            let build_slider = |divisions: i32| {
3870                material_app(
3871                    theme.clone(),
3872                    Directionality::new(
3873                        TextDirection::Ltr,
3874                        Material::new().child(
3875                            Center::new().child(
3876                                Slider::new(0.25, Some(Rc::new(|_app: &mut App, _value: f64| {})))
3877                                    .max(100.0)
3878                                    .divisions(divisions),
3879                            ),
3880                        ),
3881                    )
3882                    .into_widget(),
3883                )
3884            };
3885
3886            // Pump a slider with a reasonable amount of divisions to verify that the
3887            // tick marks are drawn when the number of tick marks is not too dense.
3888            tester.pump_widget(build_slider(4));
3889
3890            // 5 tick marks and a thumb.
3891            assert_eq!(circles(tester, slider_render(tester)).len(), 6);
3892
3893            // 200 divisions will produce a tick interval off less than 6,
3894            // which would be too dense to draw.
3895            tester.pump_widget(build_slider(200));
3896
3897            // No tick marks are drawn because they are too dense, but the thumb is
3898            // still drawn.
3899            assert_eq!(circles(tester, slider_render(tester)).len(), 1);
3900        });
3901    }
3902
3903    /// `tester.renderObject<RenderBox>(find.byType(Slider)).size`.
3904    pub(crate) fn slider_size(tester: &WidgetTester) -> Size {
3905        let slider = find::by_type::<Slider>().evaluate(tester)[0];
3906        let render = tester.render_box_of(slider);
3907        render.size(&tester.cell.borrow())
3908    }
3909
3910    // 'Slider sizing'.
3911    #[test]
3912    fn slider_sizing() {
3913        test_widgets(|tester| {
3914            let theme = default_theme(tester);
3915            let app = |theme: ThemeData, body: WidgetRef| {
3916                material_app(
3917                    theme,
3918                    Directionality::new(
3919                        TextDirection::Ltr,
3920                        Material::new().child(Center::new().child(body)),
3921                    )
3922                    .into_widget(),
3923                )
3924            };
3925            tester.pump_widget(app(theme.clone(), Slider::new(0.5, None).into_widget()));
3926            assert_eq!(slider_size(tester), Size::new(800.0, 600.0));
3927
3928            tester.pump_widget(app(
3929                theme.clone(),
3930                waft_widgets::IntrinsicWidth::new()
3931                    .child(Slider::new(0.5, None))
3932                    .into_widget(),
3933            ));
3934            assert_eq!(slider_size(tester), Size::new(144.0 + 2.0 * 24.0, 600.0));
3935
3936            tester.pump_widget(app(
3937                theme,
3938                waft_widgets::OverflowBox::new()
3939                    .max_width(f64::INFINITY)
3940                    .max_height(f64::INFINITY)
3941                    .child(Slider::new(0.5, None))
3942                    .into_widget(),
3943            ));
3944            assert_eq!(slider_size(tester), Size::new(144.0 + 2.0 * 24.0, 48.0));
3945        });
3946    }
3947
3948    /// Dart's `MaterialApp(home: Directionality(child: Material(child: body)))`.
3949    pub(crate) fn material_body<K>(
3950        theme: ThemeData,
3951        text_direction: TextDirection,
3952        body: impl IntoWidget<K>,
3953    ) -> WidgetRef {
3954        material_app(
3955            theme,
3956            Directionality::new(text_direction, Material::new().child(body)).into_widget(),
3957        )
3958    }
3959
3960    pub(crate) fn noop() -> Option<ValueChanged<f64>> {
3961        Some(Rc::new(|_app: &mut App, _value: f64| {}))
3962    }
3963
3964    fn logging(log: &Rc<RefCell<Vec<f64>>>) -> ValueChanged<f64> {
3965        let log = Rc::clone(log);
3966        Rc::new(move |_app: &mut App, value: f64| log.borrow_mut().push(value))
3967    }
3968
3969    // 'Slider take on discrete values'.
3970    #[test]
3971    fn a_slider_takes_on_discrete_values() {
3972        test_widgets(|tester| {
3973            let heard = Heard::starting_at(0.0);
3974            let theme = default_theme(tester);
3975            tester.pump_widget(stateful_slider_app(
3976                tester,
3977                theme,
3978                TextDirection::Ltr,
3979                &heard,
3980                |_app, _context, slider| {
3981                    SizedBox::new()
3982                        .width(144.0 + 2.0 * 16.0) // _kPreferredTotalWidth
3983                        .child(slider)
3984                        .into_widget()
3985                },
3986                |slider| slider.max(100.0).divisions(10),
3987            ));
3988
3989            assert_eq!(heard.value.get(), 0.0);
3990            tester.tap_at(slider_rect(tester).center(), 1);
3991            assert_eq!(heard.value.get(), 50.0);
3992            tester.drag_from(slider_rect(tester).center(), Offset::new(5.0, 0.0), 2);
3993            assert_eq!(heard.value.get(), 50.0);
3994            tester.drag_from(slider_rect(tester).center(), Offset::new(40.0, 0.0), 3);
3995            assert_eq!(heard.value.get(), 80.0);
3996
3997            tester.pump(); // Starts animation.
3998            assert!(transient_callback_count(tester) > 0);
3999            tester.pump_by(Duration::from_millis(200));
4000            tester.pump_by(Duration::from_millis(200));
4001            tester.pump_by(Duration::from_millis(200));
4002            tester.pump_by(Duration::from_millis(200));
4003            // Animation complete.
4004            assert_eq!(transient_callback_count(tester), 0);
4005        });
4006    }
4007
4008    // 'Discrete slider has no floating-point rounding errors'.
4009    #[test]
4010    fn a_discrete_slider_has_no_floating_point_rounding_errors() {
4011        test_widgets(|tester| {
4012            let values = Rc::new(RefCell::new(Vec::new()));
4013            let theme = default_theme(tester);
4014            tester.pump_widget(material_body(
4015                theme,
4016                TextDirection::Ltr,
4017                Center::new().child(
4018                    SizedBox::new().width(180.0).child(
4019                        Slider::new(0.0, Some(logging(&values)))
4020                            .max(35.0)
4021                            .divisions(35),
4022                    ),
4023                ),
4024            ));
4025
4026            let rect = slider_rect(tester);
4027            let active_track_width = rect.width() - 48.0;
4028            let start = rect.top_left() + Offset::new(24.0, rect.height() / 2.0);
4029            let mut gesture = TestPointer::touch(1);
4030            tester.down(&mut gesture, start);
4031            tester.move_to(
4032                &mut gesture,
4033                start + Offset::new(active_track_width * 29.0 / 35.0, 0.0),
4034                true,
4035            );
4036            tester.up(&gesture);
4037
4038            let values = values.borrow();
4039            assert!(!values.is_empty());
4040            assert_eq!(*values.last().unwrap(), 29.0);
4041            for value in values.iter() {
4042                assert_eq!(*value, value.round());
4043            }
4044        });
4045    }
4046
4047    // 'Slider can be given zero values'.
4048    #[test]
4049    fn a_slider_can_be_given_zero_values() {
4050        test_widgets(|tester| {
4051            let log = Rc::new(RefCell::new(Vec::new()));
4052            let theme = default_theme(tester);
4053            tester.pump_widget(material_body(
4054                theme.clone(),
4055                TextDirection::Ltr,
4056                Slider::new(0.0, Some(logging(&log))),
4057            ));
4058
4059            tester.tap_at(slider_rect(tester).center(), 1);
4060            assert_eq!(*log.borrow(), vec![0.5]);
4061            log.borrow_mut().clear();
4062
4063            tester.pump_widget(material_body(
4064                theme,
4065                TextDirection::Ltr,
4066                Slider::new(0.0, Some(logging(&log))).max(0.0),
4067            ));
4068
4069            tester.tap_at(slider_rect(tester).center(), 2);
4070            assert!(log.borrow().is_empty());
4071        });
4072    }
4073
4074    // 'Slider can tap in vertical scroller'.
4075    #[test]
4076    fn a_slider_can_be_tapped_in_a_vertical_scroller() {
4077        test_widgets(|tester| {
4078            let value = Rc::new(Cell::new(0.0));
4079            let on_changed_value = Rc::clone(&value);
4080            let theme = default_theme(tester);
4081            tester.pump_widget(material_body(
4082                theme,
4083                TextDirection::Ltr,
4084                waft_widgets::ListView::new().children([
4085                    Slider::new(
4086                        value.get(),
4087                        Some(Rc::new(move |_app: &mut App, new_value: f64| {
4088                            on_changed_value.set(new_value)
4089                        })),
4090                    )
4091                    .into_widget(),
4092                    SizedBox::new().height(2000.0).into_widget(),
4093                ]),
4094            ));
4095
4096            tester.tap_at(slider_rect(tester).center(), 1);
4097            assert_eq!(value.get(), 0.5);
4098        });
4099    }
4100
4101    /// Dart's 'Slider drags immediately' for `text_direction`: the value after a press at the
4102    /// centre and a move one pixel right.
4103    fn drags_immediately(tester: &mut WidgetTester, text_direction: TextDirection) -> f64 {
4104        let value = Rc::new(Cell::new(0.0));
4105        let on_changed_value = Rc::clone(&value);
4106        let theme = default_theme(tester);
4107        tester.pump_widget(material_body(
4108            theme,
4109            text_direction,
4110            Center::new().child(Slider::new(
4111                value.get(),
4112                Some(Rc::new(move |_app: &mut App, new_value: f64| {
4113                    on_changed_value.set(new_value)
4114                })),
4115            )),
4116        ));
4117
4118        let center = slider_rect(tester).center();
4119        let mut gesture = TestPointer::touch(1);
4120        tester.down(&mut gesture, center);
4121
4122        assert_eq!(value.get(), 0.5);
4123
4124        tester.move_to(&mut gesture, center + Offset::new(1.0, 0.0), true);
4125        let moved = value.get();
4126        tester.up(&gesture);
4127        moved
4128    }
4129
4130    // 'Slider drags immediately (LTR)'.
4131    #[test]
4132    fn a_slider_drags_immediately_ltr() {
4133        test_widgets(|tester| {
4134            assert!(drags_immediately(tester, TextDirection::Ltr) > 0.5);
4135        });
4136    }
4137
4138    // 'Slider drags immediately (RTL)'.
4139    #[test]
4140    fn a_slider_drags_immediately_rtl() {
4141        test_widgets(|tester| {
4142            assert!(drags_immediately(tester, TextDirection::Rtl) < 0.5);
4143        });
4144    }
4145
4146    // 'Slider onChangeStart and onChangeEnd fire once'.
4147    #[test]
4148    fn on_change_start_and_on_change_end_fire_once() {
4149        test_widgets(|tester| {
4150            // Regression test for https://github.com/flutter/flutter/issues/28115
4151            let heard = Heard::starting_at(0.0);
4152            let start_heard = Rc::clone(&heard);
4153            let end_heard = Rc::clone(&heard);
4154            let theme = default_theme(tester);
4155            tester.pump_widget(material_body(
4156                theme,
4157                TextDirection::Ltr,
4158                Center::new().child(
4159                    waft_widgets::GestureDetector::new()
4160                        .on_horizontal_drag_update(Rc::new(|_app: &mut App, _details| {}))
4161                        .child(
4162                            Slider::new(0.0, noop())
4163                                .on_change_start(Rc::new(move |_app: &mut App, _value: f64| {
4164                                    start_heard
4165                                        .start_updates
4166                                        .set(start_heard.start_updates.get() + 1)
4167                                }))
4168                                .on_change_end(Rc::new(move |_app: &mut App, _value: f64| {
4169                                    end_heard.end_updates.set(end_heard.end_updates.get() + 1)
4170                                })),
4171                        ),
4172                ),
4173            ));
4174
4175            tester.drag_from(slider_rect(tester).center(), Offset::new(20.0, 0.0), 1);
4176
4177            assert_eq!(heard.start_updates.get(), 1);
4178            assert_eq!(heard.end_updates.get(), 1);
4179        });
4180    }
4181
4182    pub(crate) fn paints_circle(
4183        tester: &WidgetTester,
4184        render: AnyRenderObject,
4185        color: Color,
4186    ) -> bool {
4187        paints(
4188            &tester.painted_ops(render),
4189            &[PaintCall::circle(Some(color))],
4190        )
4191        .is_ok()
4192    }
4193
4194    /// Dart's `MaterialApp(theme:, home: Material(child: Center(child: StatefulBuilder(...))))`
4195    /// whose builder makes a slider at `value` with `configure`, updating `value` when enabled.
4196    fn focusable_slider_app(
4197        theme: ThemeData,
4198        value: &Rc<Cell<f64>>,
4199        enabled: bool,
4200        configure: impl Fn(Slider) -> Slider + 'static,
4201    ) -> WidgetRef {
4202        let value = Rc::clone(value);
4203        material_app(
4204            theme,
4205            Material::new()
4206                .child(Center::new().child(StatefulBuilder::new(
4207                    move |_app, _context, set_state| {
4208                        let on_changed_value = Rc::clone(&value);
4209                        let on_changed: Option<ValueChanged<f64>> = enabled.then(|| {
4210                            Rc::new(move |app: &mut App, new_value: f64| {
4211                                let value = Rc::clone(&on_changed_value);
4212                                set_state(app, &mut |_app| value.set(new_value));
4213                            }) as ValueChanged<f64>
4214                        });
4215                        configure(Slider::new(value.get(), on_changed)).into_widget()
4216                    },
4217                )))
4218                .into_widget(),
4219        )
4220    }
4221
4222    fn new_focus_node(tester: &WidgetTester) -> FocusNodeRef {
4223        FocusNode::new(&mut tester.cell.borrow_mut()).into_erased()
4224    }
4225
4226    #[expect(deprecated, reason = "Dart's case calls the deprecated `withOpacity`")]
4227    fn primary_with_opacity(theme: &ThemeData, opacity: f64) -> Color {
4228        theme.color_scheme.primary().with_opacity(opacity)
4229    }
4230
4231    // 'Material3 - Slider is focusable and has correct focus color'.
4232    #[test]
4233    fn material3_a_slider_is_focusable_and_has_the_focus_color() {
4234        test_widgets(|tester| {
4235            let focus_node = new_focus_node(tester);
4236            tester.set_highlight_strategy(waft_widgets::FocusHighlightStrategy::AlwaysTraditional);
4237            let theme = default_theme(tester);
4238            let value = Rc::new(Cell::new(0.5));
4239            let build_app = |enabled: bool| {
4240                focusable_slider_app(theme.clone(), &value, enabled, {
4241                    let focus_node = focus_node.clone();
4242                    move |slider| slider.autofocus(true).focus_node(focus_node.clone())
4243                })
4244            };
4245            tester.pump_widget(build_app(true));
4246
4247            // Check that the overlay shows when focused.
4248            tester.pump_and_settle();
4249            assert!(focus_node.has_primary_focus(&tester.cell.borrow()));
4250            let focused_color = primary_with_opacity(&theme, 0.1);
4251            assert!(paints_circle(tester, slider_render(tester), focused_color));
4252
4253            // Check that the overlay does not show when unfocused and disabled.
4254            tester.pump_widget(build_app(false));
4255            tester.pump_and_settle();
4256            assert!(!focus_node.has_primary_focus(&tester.cell.borrow()));
4257            assert!(!paints_circle(tester, slider_render(tester), focused_color));
4258            focus_node.dispose(&mut tester.cell.borrow_mut());
4259        });
4260    }
4261
4262    // 'Slider has correct focus color from overlayColor property'.
4263    #[test]
4264    fn a_slider_takes_its_focus_color_from_overlay_color() {
4265        test_widgets(|tester| {
4266            let focus_node = new_focus_node(tester);
4267            tester.set_highlight_strategy(waft_widgets::FocusHighlightStrategy::AlwaysTraditional);
4268            let theme = default_theme(tester);
4269            let value = Rc::new(Cell::new(0.5));
4270            let purple = Colors::PURPLE.get(&500).expect("a swatch shade");
4271            let build_app = |enabled: bool| {
4272                focusable_slider_app(theme.clone(), &value, enabled, {
4273                    let focus_node = focus_node.clone();
4274                    move |slider| {
4275                        slider
4276                            .overlay_color(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
4277                                move |states: &WidgetStates| {
4278                                    if states.contains(&WidgetState::Focused) {
4279                                        return Some(purple);
4280                                    }
4281
4282                                    Some(Colors::TRANSPARENT)
4283                                },
4284                            ))
4285                            .autofocus(true)
4286                            .focus_node(focus_node.clone())
4287                    }
4288                })
4289            };
4290            tester.pump_widget(build_app(true));
4291
4292            // Check that the overlay shows when focused.
4293            tester.pump_and_settle();
4294            assert!(focus_node.has_primary_focus(&tester.cell.borrow()));
4295            assert!(paints_circle(tester, slider_render(tester), purple));
4296
4297            // Check that the overlay does not show when focused and disabled.
4298            tester.pump_widget(build_app(false));
4299            tester.pump_and_settle();
4300            assert!(!focus_node.has_primary_focus(&tester.cell.borrow()));
4301            assert!(!paints_circle(tester, slider_render(tester), purple));
4302            focus_node.dispose(&mut tester.cell.borrow_mut());
4303        });
4304    }
4305
4306    // 'Slider can be hovered and has correct hover color'.
4307    #[test]
4308    fn a_slider_can_be_hovered_and_has_the_hover_color() {
4309        test_widgets(|tester| {
4310            tester.set_highlight_strategy(waft_widgets::FocusHighlightStrategy::AlwaysTraditional);
4311            let theme = default_theme(tester);
4312            let value = Rc::new(Cell::new(0.5));
4313            let orange = Colors::ORANGE.get(&500).expect("a swatch shade");
4314            let build_app = |enabled: bool| {
4315                focusable_slider_app(theme.clone(), &value, enabled, |slider| slider)
4316            };
4317            tester.pump_widget(build_app(true));
4318
4319            // Slider does not have overlay when enabled and not hovered.
4320            tester.pump_and_settle();
4321            assert!(!paints_circle(tester, slider_render(tester), orange));
4322
4323            // Start hovering.
4324            let mut gesture = TestPointer::mouse(1, 0);
4325            tester.add_pointer(&mut gesture, Offset::ZERO);
4326            tester.move_to(&mut gesture, slider_rect(tester).center(), false);
4327
4328            // Slider has overlay when enabled and hovered.
4329            tester.pump_widget(build_app(true));
4330            tester.pump_and_settle();
4331            let hovered_color = primary_with_opacity(&theme, 0.08);
4332            assert!(paints_circle(tester, slider_render(tester), hovered_color));
4333
4334            // Slider still shows correct hovered color after pressing/dragging
4335            let mut pressed = TestPointer::mouse(1, waft_gestures::K_PRIMARY_BUTTON);
4336            pressed.position = gesture.position;
4337            tester.down(&mut pressed, slider_rect(tester).center());
4338            tester.pump();
4339            tester.up(&pressed);
4340            tester.pump_and_settle();
4341            gesture.position = pressed.position;
4342            tester.move_to(&mut gesture, Offset::new(0.0, 100.0), false);
4343            tester.pump_and_settle();
4344            tester.move_to(&mut gesture, slider_rect(tester).center(), false);
4345            tester.pump_and_settle();
4346            assert!(paints_circle(tester, slider_render(tester), hovered_color));
4347
4348            // Slider does not have an overlay when disabled and hovered.
4349            tester.pump_widget(build_app(false));
4350            tester.pump_and_settle();
4351            assert!(!paints_circle(tester, slider_render(tester), orange));
4352        });
4353    }
4354
4355    // 'Material3 - Slider is draggable and has correct dragged color'.
4356    #[test]
4357    fn material3_a_slider_is_draggable_and_has_the_dragged_color() {
4358        test_widgets(|tester| {
4359            tester.set_highlight_strategy(waft_widgets::FocusHighlightStrategy::AlwaysTraditional);
4360            let theme = default_theme(tester);
4361            let value = Rc::new(Cell::new(0.5));
4362            let focus_node = new_focus_node(tester);
4363            let build_app = |enabled: bool| {
4364                focusable_slider_app(theme.clone(), &value, enabled, {
4365                    let focus_node = focus_node.clone();
4366                    move |slider| slider.focus_node(focus_node.clone())
4367                })
4368            };
4369            tester.pump_widget(build_app(true));
4370
4371            // Slider does not have overlay when enabled and not dragged.
4372            tester.pump_and_settle();
4373            let dragged_color = primary_with_opacity(&theme, 0.1);
4374            assert!(!paints_circle(tester, slider_render(tester), dragged_color));
4375
4376            // Start dragging.
4377            let mut drag = TestPointer::touch(1);
4378            tester.down(&mut drag, slider_rect(tester).center());
4379            tester.pump_by(waft_gestures::K_PRESS_TIMEOUT);
4380
4381            // Less than configured touch slop, more than default touch slop
4382            let at = drag.position + Offset::new(19.0, 0.0);
4383            tester.move_to(&mut drag, at, true);
4384            tester.pump();
4385            // Valo records no draw that covers no pixel, and the overlay has just started
4386            // to grow from a zero radius, a circle Dart's `paints` matcher sees as a call; one
4387            // frame later it has a radius.
4388            tester.pump_by(Duration::from_millis(16));
4389
4390            // Slider has overlay when enabled and dragged.
4391            assert!(paints_circle(tester, slider_render(tester), dragged_color));
4392
4393            tester.up(&drag);
4394            tester.pump_and_settle();
4395
4396            // Slider without focus doesn't have overlay when enabled and dragged.
4397            assert!(!focus_node.has_focus(&tester.cell.borrow_mut()));
4398            assert!(!paints_circle(tester, slider_render(tester), dragged_color));
4399
4400            // Slider has overlay when enabled, dragged and focused.
4401            focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
4402            tester.pump_and_settle();
4403
4404            assert!(focus_node.has_focus(&tester.cell.borrow_mut()));
4405            assert!(paints_circle(tester, slider_render(tester), dragged_color));
4406            focus_node.dispose(&mut tester.cell.borrow_mut());
4407        });
4408    }
4409
4410    // 'OverlayColor property is correctly applied when activeColor is also provided'.
4411    #[test]
4412    fn overlay_color_applies_when_active_color_is_also_given() {
4413        test_widgets(|tester| {
4414            let focus_node = new_focus_node(tester);
4415            tester.set_highlight_strategy(waft_widgets::FocusHighlightStrategy::AlwaysTraditional);
4416            let theme = default_theme(tester);
4417            let value = Rc::new(Cell::new(0.5));
4418            const ACTIVE_COLOR: Color = Color::new(0xffff0000);
4419            const OVERLAY_COLOR: Color = Color::new(0xff0000ff);
4420            let build_app = |enabled: bool| {
4421                focusable_slider_app(theme.clone(), &value, enabled, {
4422                    let focus_node = focus_node.clone();
4423                    move |slider| {
4424                        slider
4425                            .active_color(ACTIVE_COLOR)
4426                            .overlay_color(Rc::new(WidgetStatePropertyAll::new(Some(
4427                                OVERLAY_COLOR,
4428                            ))))
4429                            .focus_node(focus_node.clone())
4430                    }
4431                })
4432            };
4433            tester.pump_widget(build_app(true));
4434            tester.pump_and_settle();
4435
4436            // Check that thumb color is using active color.
4437            assert!(paints_circle(tester, slider_render(tester), ACTIVE_COLOR));
4438
4439            focus_node.request_focus(&mut tester.cell.borrow_mut(), None);
4440            tester.pump_and_settle();
4441
4442            // Check that the overlay shows when focused.
4443            assert!(focus_node.has_primary_focus(&tester.cell.borrow()));
4444            assert!(paints_circle(tester, slider_render(tester), OVERLAY_COLOR));
4445
4446            // Check that the overlay does not show when focused and disabled.
4447            tester.pump_widget(build_app(false));
4448            tester.pump_and_settle();
4449            assert!(!focus_node.has_primary_focus(&tester.cell.borrow()));
4450            assert!(!paints_circle(tester, slider_render(tester), OVERLAY_COLOR));
4451            focus_node.dispose(&mut tester.cell.borrow_mut());
4452        });
4453    }
4454
4455    /// The values Dart's keyboard cases record: `startValue`, `currentValue`, `endValue`.
4456    struct KeyboardValues {
4457        start: Rc<Cell<f64>>,
4458        current: Rc<Cell<f64>>,
4459        end: Rc<Cell<f64>>,
4460    }
4461
4462    /// Dart's 'Slider can be incremented and decremented by keyboard shortcuts' app: an
4463    /// autofocused slider at 0.5 in `text_direction`.
4464    fn keyboard_slider(tester: &mut WidgetTester, text_direction: TextDirection) -> KeyboardValues {
4465        tester.set_highlight_strategy(waft_widgets::FocusHighlightStrategy::AlwaysTraditional);
4466        let values = KeyboardValues {
4467            start: Rc::new(Cell::new(0.0)),
4468            current: Rc::new(Cell::new(0.5)),
4469            end: Rc::new(Cell::new(0.0)),
4470        };
4471        let (start, current, end) = (
4472            Rc::clone(&values.start),
4473            Rc::clone(&values.current),
4474            Rc::clone(&values.end),
4475        );
4476        let theme = default_theme(tester);
4477        tester.pump_widget(material_app(
4478            theme,
4479            Material::new()
4480                .child(Center::new().child(StatefulBuilder::new(
4481                    move |_app, _context, set_state| {
4482                        let (start, current, end) =
4483                            (Rc::clone(&start), Rc::clone(&current), Rc::clone(&end));
4484                        let (start_set_state, end_set_state) =
4485                            (Rc::clone(&set_state), Rc::clone(&set_state));
4486                        let slider = Slider::new(
4487                            current.get(),
4488                            Some(Rc::new(move |app: &mut App, new_value: f64| {
4489                                let current = Rc::clone(&current);
4490                                set_state(app, &mut |_app| current.set(new_value));
4491                            })),
4492                        )
4493                        .on_change_start(Rc::new(move |app: &mut App, new_value: f64| {
4494                            let start = Rc::clone(&start);
4495                            start_set_state(app, &mut |_app| start.set(new_value));
4496                        }))
4497                        .on_change_end(Rc::new(move |app: &mut App, new_value: f64| {
4498                            let end = Rc::clone(&end);
4499                            end_set_state(app, &mut |_app| end.set(new_value));
4500                        }))
4501                        .autofocus(true);
4502                        Directionality::new(text_direction, slider).into_widget()
4503                    },
4504                )))
4505                .into_widget(),
4506        ));
4507        tester.pump_and_settle();
4508        values
4509    }
4510
4511    fn send_arrow(tester: &mut WidgetTester, logical: LogicalKeyboardKey) {
4512        use waft_services::PhysicalKeyboardKey;
4513        let physical = if logical == LogicalKeyboardKey::ARROW_RIGHT {
4514            PhysicalKeyboardKey::ARROW_RIGHT
4515        } else if logical == LogicalKeyboardKey::ARROW_LEFT {
4516            PhysicalKeyboardKey::ARROW_LEFT
4517        } else if logical == LogicalKeyboardKey::ARROW_UP {
4518            PhysicalKeyboardKey::ARROW_UP
4519        } else {
4520            PhysicalKeyboardKey::ARROW_DOWN
4521        };
4522        tester.send_key_event(physical, logical);
4523        tester.pump_and_settle();
4524    }
4525
4526    fn assert_keyboard_values(values: &KeyboardValues, start: f64, current: f64, end: f64) {
4527        assert_eq!(values.start.get(), start);
4528        assert_eq!(values.current.get(), current);
4529        assert_eq!(values.end.get(), end);
4530    }
4531
4532    /// The keyboard case for `platform`, whose arrows step by `step`: right, left, up and down
4533    /// in turn, right and left swapped by `text_direction`.
4534    fn keyboard_shortcuts_step(
4535        tester: &mut WidgetTester,
4536        text_direction: TextDirection,
4537        step: f64,
4538    ) {
4539        let values = keyboard_slider(tester, text_direction);
4540        let (up, down) = (0.5 + step, 0.5 - step);
4541        let right = match text_direction {
4542            TextDirection::Ltr => up,
4543            TextDirection::Rtl => down,
4544        };
4545
4546        send_arrow(tester, LogicalKeyboardKey::ARROW_RIGHT);
4547        assert_keyboard_values(&values, 0.5, right, right);
4548
4549        send_arrow(tester, LogicalKeyboardKey::ARROW_LEFT);
4550        assert_keyboard_values(&values, right, 0.5, 0.5);
4551
4552        send_arrow(tester, LogicalKeyboardKey::ARROW_UP);
4553        assert_keyboard_values(&values, 0.5, up, up);
4554
4555        send_arrow(tester, LogicalKeyboardKey::ARROW_DOWN);
4556        assert_keyboard_values(&values, up, 0.5, 0.5);
4557    }
4558
4559    // 'Slider can be incremented and decremented by keyboard shortcuts - LTR' (Android,
4560    // Fuchsia, Linux, Windows).
4561    #[test]
4562    fn the_keyboard_steps_a_slider_by_five_percent_ltr() {
4563        test_widgets(|_| {
4564            for platform in [
4565                TargetPlatform::Android,
4566                TargetPlatform::Fuchsia,
4567                TargetPlatform::Linux,
4568                TargetPlatform::Windows,
4569            ] {
4570                test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
4571                    keyboard_shortcuts_step(tester, TextDirection::Ltr, 0.05);
4572                });
4573            }
4574        });
4575    }
4576
4577    // 'Slider can be incremented and decremented by keyboard shortcuts - LTR' (iOS, macOS).
4578    #[test]
4579    fn the_keyboard_steps_a_slider_by_ten_percent_ltr_on_apple_platforms() {
4580        test_widgets(|_| {
4581            for platform in [TargetPlatform::IOS, TargetPlatform::MacOS] {
4582                test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
4583                    keyboard_shortcuts_step(tester, TextDirection::Ltr, 0.1);
4584                });
4585            }
4586        });
4587    }
4588
4589    // 'Slider can be incremented and decremented by keyboard shortcuts - RTL' (Android,
4590    // Fuchsia, Linux, Windows).
4591    #[test]
4592    fn the_keyboard_steps_a_slider_by_five_percent_rtl() {
4593        test_widgets(|_| {
4594            for platform in [
4595                TargetPlatform::Android,
4596                TargetPlatform::Fuchsia,
4597                TargetPlatform::Linux,
4598                TargetPlatform::Windows,
4599            ] {
4600                test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
4601                    keyboard_shortcuts_step(tester, TextDirection::Rtl, 0.05);
4602                });
4603            }
4604        });
4605    }
4606
4607    // 'Slider can be incremented and decremented by keyboard shortcuts - RTL' (iOS, macOS).
4608    #[test]
4609    fn the_keyboard_steps_a_slider_by_ten_percent_rtl_on_apple_platforms() {
4610        test_widgets(|_| {
4611            for platform in [TargetPlatform::IOS, TargetPlatform::MacOS] {
4612                test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
4613                    keyboard_shortcuts_step(tester, TextDirection::Rtl, 0.1);
4614                });
4615            }
4616        });
4617    }
4618
4619    /// Dart's `_FixedSizeCircle`: a value indicator that paints a 40 pixel circle and its label.
4620    #[derive(Debug)]
4621    struct FixedSizeCircle;
4622
4623    impl FixedSizeCircle {
4624        const CIRCLE_DIAMETER: f64 = 40.0;
4625    }
4626
4627    impl SliderComponentShape for FixedSizeCircle {
4628        fn get_preferred_size(&self, _is_enabled: bool, _is_discrete: bool) -> Size {
4629            Size::square(Self::CIRCLE_DIAMETER)
4630        }
4631
4632        fn paint(
4633            &self,
4634            app: &mut App,
4635            context: &mut PaintingContext,
4636            center: Offset,
4637            _activation_animation: AnyAnimation<f64>,
4638            _enable_animation: AnyAnimation<f64>,
4639            _is_discrete: bool,
4640            label_painter: &mut TextPainter,
4641            _parent_box: waft_rendering::AnyRenderBox,
4642            slider_theme: &SliderThemeData,
4643            _text_direction: TextDirection,
4644            _value: f64,
4645            _text_scale_factor: f64,
4646            _size_with_overflow: Size,
4647        ) {
4648            use waft_painting::ClipContext;
4649            let color = slider_theme
4650                .value_indicator_color
4651                .unwrap_or(Colors::PURPLE.primary());
4652            context.canvas().draw_circle(
4653                center,
4654                (Self::CIRCLE_DIAMETER / 2.0) as f32,
4655                &waft_embedder::Paint::from_color(color.into()),
4656            );
4657            let fonts = PaintingBinding::instance(app).fonts(app);
4658            label_painter.paint(app.get_mut(fonts), context.canvas(), center);
4659        }
4660
4661        fn as_any(&self) -> &dyn Any {
4662            self
4663        }
4664    }
4665
4666    /// Dart's `expectIndicatorVisible`: whether the value indicator box, the last render object
4667    /// in the tree, paints a circle in the theme's value indicator colour and a paragraph.
4668    fn indicator_visible(tester: &WidgetTester, theme: &SliderThemeData) -> bool {
4669        let Some(value_indicator_box) = tester.all::<RenderValueIndicator>().into_iter().last()
4670        else {
4671            return false;
4672        };
4673        let render = value_indicator_box.as_render_object(&tester.cell.borrow());
4674        let ops = tester.painted_ops(render);
4675        let color = theme
4676            .value_indicator_color
4677            .expect("the case's theme has one");
4678        let circle = ops.iter().position(|op| {
4679            matches!(op, Op::DrawPath { path, paint, .. }
4680                if circle_of(path).is_some() && colors_match(paint.color, color))
4681        });
4682        circle.is_some_and(|circle| {
4683            ops[circle..]
4684                .iter()
4685                .any(|op| matches!(op, Op::GlyphRun { .. }))
4686        })
4687    }
4688
4689    /// Dart's `expectValueIndicator` in 'Value indicator appears and disappears when it should'.
4690    fn expect_value_indicator(
4691        tester: &mut WidgetTester,
4692        visible_when_dragged: bool,
4693        visible_when_released: bool,
4694        theme: &SliderThemeData,
4695        divisions: Option<i32>,
4696        enabled: bool,
4697    ) {
4698        let base_theme = ThemeData::builder()
4699            .platform(TargetPlatform::Android)
4700            .primary_swatch(Colors::BLUE)
4701            .build(&tester.cell.borrow());
4702        let value = 0.45;
4703        let mut slider =
4704            Slider::new(value, enabled.then(|| noop()).flatten()).label(format!("{value}"));
4705        if let Some(divisions) = divisions {
4706            slider = slider.divisions(divisions);
4707        }
4708        let app = material_body(
4709            default_theme(tester),
4710            TextDirection::Ltr,
4711            Center::new().child(crate::theme::Theme::new(
4712                base_theme,
4713                SliderTheme::new(theme.clone(), slider),
4714            )),
4715        );
4716        tester.pump_widget(app);
4717        assert_eq!(indicator_visible(tester, theme), visible_when_released);
4718
4719        let center = slider_rect(tester).center();
4720        let mut gesture = TestPointer::touch(1);
4721        tester.down(&mut gesture, center);
4722        tester.pump_and_settle();
4723        assert_eq!(indicator_visible(tester, theme), visible_when_dragged);
4724
4725        tester.up(&gesture);
4726        tester.pump_and_settle();
4727        assert_eq!(indicator_visible(tester, theme), visible_when_released);
4728
4729        // Reset state to avoid state leak.
4730        tester.pump_widget(SizedBox::new().into_widget());
4731    }
4732
4733    /// Dart's `baseSliderTheme.copyWith(showValueIndicator:)` in that group.
4734    fn value_indicator_theme(
4735        tester: &WidgetTester,
4736        show_value_indicator: Option<ShowValueIndicator>,
4737    ) -> SliderThemeData {
4738        let base_theme = ThemeData::builder()
4739            .platform(TargetPlatform::Android)
4740            .primary_swatch(Colors::BLUE)
4741            .build(&tester.cell.borrow());
4742        let mut theme = base_theme
4743            .slider_theme
4744            .copy_with()
4745            .value_indicator_color(Colors::RED.primary())
4746            .value_indicator_shape(Rc::new(FixedSizeCircle));
4747        if let Some(show_value_indicator) = show_value_indicator {
4748            theme = theme.show_value_indicator(show_value_indicator);
4749        }
4750        theme
4751    }
4752
4753    /// The four `expectValueIndicator` calls of each case: discrete enabled, discrete
4754    /// disabled, continuous enabled and continuous disabled, with what they expect while
4755    /// dragged and once released.
4756    fn expect_value_indicators(
4757        tester: &mut WidgetTester,
4758        show_value_indicator: Option<ShowValueIndicator>,
4759        discrete: (bool, bool),
4760        continuous: (bool, bool),
4761    ) {
4762        let theme = value_indicator_theme(tester, show_value_indicator);
4763        expect_value_indicator(tester, discrete.0, discrete.1, &theme, Some(3), true);
4764        expect_value_indicator(tester, false, false, &theme, Some(3), false);
4765        expect_value_indicator(tester, continuous.0, continuous.1, &theme, None, true);
4766        expect_value_indicator(tester, false, false, &theme, None, false);
4767    }
4768
4769    // 'Value indicator appears and disappears when it should:' 'showValueIndicator set to
4770    // onlyForDiscrete'.
4771    #[test]
4772    fn the_value_indicator_shows_only_for_discrete() {
4773        test_widgets(|tester| {
4774            // The default value is onlyForDiscrete. No modification is needed.
4775            expect_value_indicators(tester, None, (true, false), (false, false));
4776        });
4777    }
4778
4779    // 'showValueIndicator set to onlyForContinuous'.
4780    #[test]
4781    fn the_value_indicator_shows_only_for_continuous() {
4782        test_widgets(|tester| {
4783            expect_value_indicators(
4784                tester,
4785                Some(ShowValueIndicator::OnlyForContinuous),
4786                (false, false),
4787                (true, false),
4788            );
4789        });
4790    }
4791
4792    // 'showValueIndicator set to onDrag'.
4793    #[test]
4794    fn the_value_indicator_shows_on_drag() {
4795        test_widgets(|tester| {
4796            expect_value_indicators(
4797                tester,
4798                Some(ShowValueIndicator::OnDrag),
4799                (true, false),
4800                (true, false),
4801            );
4802        });
4803    }
4804
4805    // 'showValueIndicator set to never'.
4806    #[test]
4807    fn the_value_indicator_never_shows() {
4808        test_widgets(|tester| {
4809            expect_value_indicators(
4810                tester,
4811                Some(ShowValueIndicator::Never),
4812                (false, false),
4813                (false, false),
4814            );
4815        });
4816    }
4817
4818    // 'showValueIndicator set to alwaysVisible'.
4819    #[test]
4820    fn the_value_indicator_is_always_visible() {
4821        test_widgets(|tester| {
4822            expect_value_indicators(
4823                tester,
4824                Some(ShowValueIndicator::AlwaysVisible),
4825                (true, true),
4826                (true, true),
4827            );
4828        });
4829    }
4830
4831    // 'Slider.adaptive'.
4832    #[test]
4833    fn slider_adaptive() {
4834        test_widgets(|tester| {
4835            let value = Rc::new(Cell::new(0.5));
4836            let build_frame = |tester: &WidgetTester, platform: TargetPlatform| {
4837                let theme = ThemeData::builder()
4838                    .platform(platform)
4839                    .build(&tester.cell.borrow());
4840                let value = Rc::clone(&value);
4841                material_app(
4842                    theme,
4843                    StatefulBuilder::new(move |_app, _context, set_state| {
4844                        let on_changed_value = Rc::clone(&value);
4845                        Material::new()
4846                            .child(Center::new().child(Slider::adaptive(
4847                                value.get(),
4848                                Some(Rc::new(move |app: &mut App, new_value: f64| {
4849                                    let value = Rc::clone(&on_changed_value);
4850                                    set_state(app, &mut |_app| value.set(new_value));
4851                                })),
4852                            )))
4853                            .into_widget()
4854                    })
4855                    .into_widget(),
4856                )
4857            };
4858
4859            for platform in [TargetPlatform::IOS, TargetPlatform::MacOS] {
4860                value.set(0.5);
4861                tester.pump_widget(build_frame(tester, platform));
4862                expect(tester, &find::by_type::<Slider>(), finds_one_widget());
4863                let cupertino = find::by_type::<CupertinoSlider>().evaluate(tester);
4864                assert_eq!(cupertino.len(), 1);
4865
4866                assert_eq!(value.get(), 0.5, "on {platform:?}");
4867                let center = tester.get_rect(cupertino[0]).center();
4868                let mut gesture = TestPointer::touch(1);
4869                tester.down(&mut gesture, center);
4870                // Drag to the right end of the track.
4871                tester.move_to(&mut gesture, center + Offset::new(600.0, 0.0), true);
4872                assert_eq!(value.get(), 1.0, "on {platform:?}");
4873                tester.up(&gesture);
4874            }
4875
4876            for platform in [
4877                TargetPlatform::Android,
4878                TargetPlatform::Fuchsia,
4879                TargetPlatform::Linux,
4880                TargetPlatform::Windows,
4881            ] {
4882                value.set(0.5);
4883                tester.pump_widget(build_frame(tester, platform));
4884                tester.pump_and_settle(); // Finish the theme change animation.
4885                expect(tester, &find::by_type::<Slider>(), finds_one_widget());
4886                expect(tester, &find::by_type::<CupertinoSlider>(), finds_nothing());
4887
4888                assert_eq!(value.get(), 0.5, "on {platform:?}");
4889                let center = slider_rect(tester).center();
4890                let mut gesture = TestPointer::touch(1);
4891                tester.down(&mut gesture, center);
4892                // Drag to the right end of the track.
4893                tester.move_to(&mut gesture, center + Offset::new(600.0, 0.0), true);
4894                assert_eq!(value.get(), 1.0, "on {platform:?}");
4895                tester.up(&gesture);
4896            }
4897        });
4898    }
4899
4900    // 'Slider respects height from theme'.
4901    #[test]
4902    fn a_slider_respects_the_height_of_its_theme() {
4903        test_widgets(|tester| {
4904            let heard = Heard::starting_at(0.0);
4905            let theme = default_theme(tester);
4906            tester.pump_widget(stateful_slider_app(
4907                tester,
4908                theme,
4909                TextDirection::Ltr,
4910                &heard,
4911                |app, context, slider| {
4912                    let slider_theme = SliderTheme::of(app, context)
4913                        .copy_with()
4914                        .tick_mark_shape(Rc::new(TallSliderTickMarkShape));
4915                    waft_widgets::IntrinsicHeight::new()
4916                        .child(SliderTheme::new(slider_theme, slider))
4917                        .into_widget()
4918                },
4919                |slider| slider.divisions(4),
4920            ));
4921
4922            assert_eq!(slider_size(tester).height(), 200.0);
4923        });
4924    }
4925
4926    pub(crate) fn active_cursor(tester: &WidgetTester) -> MouseCursorRef {
4927        tester.active_cursor(1)
4928    }
4929
4930    pub(crate) fn is_cursor(
4931        cursor: &MouseCursorRef,
4932        expected: waft_services::SystemMouseCursor,
4933    ) -> bool {
4934        let expected: MouseCursorRef = expected.into();
4935        **cursor == *expected
4936    }
4937
4938    // 'Slider changes mouse cursor when hovered'.
4939    #[test]
4940    fn a_slider_changes_the_mouse_cursor_when_hovered() {
4941        test_widgets(|tester| {
4942            use waft_services::SystemMouseCursors;
4943            let theme = default_theme(tester);
4944            let frame = |slider: Slider| {
4945                material_body(
4946                    theme.clone(),
4947                    TextDirection::Ltr,
4948                    Center::new().child(
4949                        waft_widgets::MouseRegion::new()
4950                            .cursor(SystemMouseCursors::FORBIDDEN.into())
4951                            .child(slider),
4952                    ),
4953                )
4954            };
4955            // Test Slider() constructor
4956            tester.pump_widget(frame(
4957                Slider::new(0.5, noop()).mouse_cursor(SystemMouseCursors::TEXT.into()),
4958            ));
4959
4960            let mut gesture = TestPointer::mouse(1, 0);
4961            tester.add_pointer(&mut gesture, slider_rect(tester).center());
4962
4963            tester.pump();
4964
4965            assert!(is_cursor(&active_cursor(tester), SystemMouseCursors::TEXT));
4966
4967            // Test Slider.adaptive() constructor
4968            tester.pump_widget(frame(
4969                Slider::adaptive(0.5, noop()).mouse_cursor(SystemMouseCursors::TEXT.into()),
4970            ));
4971
4972            assert!(is_cursor(&active_cursor(tester), SystemMouseCursors::TEXT));
4973
4974            // Test default cursor
4975            tester.pump_widget(frame(Slider::new(0.5, noop())));
4976
4977            assert!(is_cursor(&active_cursor(tester), SystemMouseCursors::CLICK));
4978        });
4979    }
4980
4981    // 'Slider WidgetStateMouseCursor resolves correctly'.
4982    #[test]
4983    fn a_slider_resolves_a_widget_state_mouse_cursor() {
4984        test_widgets(|tester| {
4985            use waft_services::{PhysicalKeyboardKey, SystemMouseCursors};
4986            let system_default_cursor = SystemMouseCursors::BASIC;
4987            let regular_cursor = SystemMouseCursors::CLICK;
4988            let disabled_cursor = SystemMouseCursors::FORBIDDEN;
4989            let focused_cursor = SystemMouseCursors::PRECISE;
4990            let hovered_cursor = SystemMouseCursors::GRAB;
4991            let dragged_cursor = SystemMouseCursors::MOVE;
4992
4993            let theme = default_theme(tester);
4994            let build_frame = |enabled: bool| {
4995                // Dart's `_StateDependentMouseCursor`.
4996                let cursor = WidgetStateMouseCursor::resolve_with(
4997                    move |states: &WidgetStates| {
4998                        let cursor = if states.contains(&WidgetState::Disabled) {
4999                            disabled_cursor
5000                        } else if states.contains(&WidgetState::Focused) {
5001                            focused_cursor
5002                        } else if states.contains(&WidgetState::Dragged) {
5003                            dragged_cursor
5004                        } else if states.contains(&WidgetState::Hovered) {
5005                            hovered_cursor
5006                        } else {
5007                            regular_cursor
5008                        };
5009                        cursor.into()
5010                    },
5011                    Some("_StateDependentMouseCursor"),
5012                );
5013                material_body(
5014                    theme.clone(),
5015                    TextDirection::Ltr,
5016                    waft_widgets::Column::new()
5017                        .main_axis_alignment(waft_rendering::MainAxisAlignment::Center)
5018                        .children([Center::new()
5019                            .child(
5020                                Slider::new(0.5, enabled.then(noop).flatten())
5021                                    .mouse_cursor(cursor.into()),
5022                            )
5023                            .into_widget()]),
5024                )
5025            };
5026
5027            let mut gesture = TestPointer::mouse(1, 0);
5028
5029            // Dart's tester starts with an empty view; this one has none until it pumps.
5030            tester.pump_widget(SizedBox::new().into_widget());
5031
5032            // System default.
5033            tester.add_pointer(&mut gesture, Offset::ZERO);
5034            tester.pump();
5035            assert!(is_cursor(&active_cursor(tester), system_default_cursor));
5036
5037            // Disabled.
5038            tester.pump_widget(build_frame(false));
5039            tester.move_to(&mut gesture, slider_rect(tester).center(), false);
5040            tester.pump();
5041            assert!(is_cursor(&active_cursor(tester), disabled_cursor));
5042
5043            // Regular.
5044            tester.pump_widget(build_frame(true));
5045            assert!(is_cursor(&active_cursor(tester), regular_cursor));
5046
5047            // Hovered.
5048            tester.pump();
5049            assert!(is_cursor(&active_cursor(tester), hovered_cursor));
5050
5051            // Dragged.
5052            let mut pressed = TestPointer::mouse(1, waft_gestures::K_PRIMARY_BUTTON);
5053            pressed.position = gesture.position;
5054            tester.down(&mut pressed, slider_rect(tester).center());
5055            let at = pressed.position + Offset::new(20.0, 0.0);
5056            tester.move_to(&mut pressed, at, true);
5057            tester.pump();
5058            assert!(is_cursor(&active_cursor(tester), dragged_cursor));
5059
5060            // Hovered.
5061            tester.up(&pressed);
5062            gesture.position = pressed.position;
5063            tester.pump();
5064            assert!(is_cursor(&active_cursor(tester), hovered_cursor));
5065
5066            // Focused.
5067            tester.send_key_event(PhysicalKeyboardKey::TAB, LogicalKeyboardKey::TAB);
5068            tester.pump();
5069            assert!(is_cursor(&active_cursor(tester), focused_cursor));
5070
5071            // System default.
5072            tester.move_to(&mut gesture, Offset::ZERO, false);
5073            tester.send_key_event(PhysicalKeyboardKey::TAB, LogicalKeyboardKey::TAB);
5074            tester.pump();
5075            assert!(is_cursor(&active_cursor(tester), system_default_cursor));
5076        });
5077    }
5078
5079    /// Dart's `MaterialApp(theme: ThemeData(platform: platform), home: Material(child: slider))`.
5080    fn platform_slider_app(
5081        tester: &WidgetTester,
5082        platform: TargetPlatform,
5083        slider: Slider,
5084    ) -> WidgetRef {
5085        let theme = ThemeData::builder()
5086            .platform(platform)
5087            .build(&tester.cell.borrow());
5088        material_app(theme, Material::new().child(slider).into_widget())
5089    }
5090
5091    // 'Slider paints thumbColor'.
5092    #[test]
5093    fn a_slider_paints_its_thumb_color() {
5094        test_widgets(|tester| {
5095            const COLOR: Color = Color::new(0xffffc107);
5096            let slider_adaptive = platform_slider_app(
5097                tester,
5098                TargetPlatform::IOS,
5099                Slider::new(0.0, noop()).thumb_color(COLOR),
5100            );
5101
5102            tester.pump_widget(slider_adaptive);
5103            tester.pump_and_settle();
5104
5105            assert!(paints_circle(tester, slider_render(tester), COLOR));
5106        });
5107    }
5108
5109    // 'Slider.adaptive paints thumbColor on Android'.
5110    #[test]
5111    fn slider_adaptive_paints_its_thumb_color_on_android() {
5112        test_widgets(|tester| {
5113            const COLOR: Color = Color::new(0xffffc107);
5114            let slider_adaptive = platform_slider_app(
5115                tester,
5116                TargetPlatform::Android,
5117                Slider::adaptive(0.0, noop()).thumb_color(COLOR),
5118            );
5119
5120            tester.pump_widget(slider_adaptive);
5121            tester.pump_and_settle();
5122
5123            assert!(paints_circle(tester, slider_render(tester), COLOR));
5124        });
5125    }
5126
5127    /// Dart's `paints..rrect()` five times then `..rrect(color: color)` on what the
5128    /// `CupertinoSlider` paints.
5129    fn assert_sixth_cupertino_rrect_color(tester: &WidgetTester, color: Color) {
5130        let cupertino = find::by_type::<CupertinoSlider>().evaluate(tester)[0];
5131        // The `Opacity` the Cupertino slider builds composites; what it paints is its child's.
5132        let opacity = tester.render_box_of(cupertino).as_object();
5133        let mut render = None;
5134        opacity.visit_children(&tester.cell.borrow(), &mut |child| render = Some(child));
5135        let render = render.expect("the opacity has the slider's render object");
5136        let mut pattern = vec![PaintCall::rrect(None); 5];
5137        pattern.push(PaintCall::rrect(Some(color)));
5138        assert_paints(&tester.painted_ops(render), &pattern);
5139    }
5140
5141    // 'If thumbColor is null, it defaults to CupertinoColors.white'.
5142    #[test]
5143    fn an_adaptive_thumb_color_defaults_to_cupertino_white() {
5144        test_widgets(|tester| {
5145            let slider_adaptive =
5146                platform_slider_app(tester, TargetPlatform::IOS, Slider::adaptive(0.0, noop()));
5147
5148            tester.pump_widget(slider_adaptive);
5149            tester.pump_and_settle();
5150
5151            assert_sixth_cupertino_rrect_color(tester, CupertinoColors::WHITE.color());
5152        });
5153    }
5154
5155    // 'Slider.adaptive passes thumbColor to CupertinoSlider'.
5156    #[test]
5157    fn slider_adaptive_passes_its_thumb_color_to_the_cupertino_slider() {
5158        test_widgets(|tester| {
5159            const COLOR: Color = Color::new(0xffffc107);
5160            let slider_adaptive = platform_slider_app(
5161                tester,
5162                TargetPlatform::IOS,
5163                Slider::adaptive(0.0, noop()).thumb_color(COLOR),
5164            );
5165
5166            tester.pump_widget(slider_adaptive);
5167            tester.pump_and_settle();
5168
5169            assert_sixth_cupertino_rrect_color(tester, COLOR);
5170        });
5171    }
5172
5173    // 'Drag gesture uses provided gesture settings'.
5174    #[test]
5175    fn the_drag_gesture_uses_the_gesture_settings_given() {
5176        test_widgets(|tester| {
5177            // Regression test for https://github.com/flutter/flutter/issues/103566
5178            let value = Rc::new(Cell::new(0.5));
5179            let drag_started = Rc::new(Cell::new(false));
5180            let slider_end = Rc::new(Cell::new(false));
5181            let theme = default_theme(tester);
5182            let build = |touch_slop: f64, with_end: bool| {
5183                let (value, drag_started, slider_end) = (
5184                    Rc::clone(&value),
5185                    Rc::clone(&drag_started),
5186                    Rc::clone(&slider_end),
5187                );
5188                material_body(
5189                    theme.clone(),
5190                    TextDirection::Ltr,
5191                    StatefulBuilder::new(move |app, context, set_state| {
5192                        let on_changed_value = Rc::clone(&value);
5193                        let started = Rc::clone(&drag_started);
5194                        let ended = Rc::clone(&slider_end);
5195                        let mut slider = Slider::new(
5196                            value.get(),
5197                            Some(Rc::new(move |app: &mut App, new_value: f64| {
5198                                let value = Rc::clone(&on_changed_value);
5199                                set_state(app, &mut |_app| value.set(new_value));
5200                            })),
5201                        );
5202                        if with_end {
5203                            slider = slider.on_change_end(Rc::new(
5204                                move |_app: &mut App, _end_value: f64| ended.set(true),
5205                            ));
5206                        }
5207                        let data = MediaQuery::of(app, context)
5208                            .copy_with()
5209                            .gesture_settings(DeviceGestureSettings::new(Some(touch_slop)));
5210                        Center::new()
5211                            .child(
5212                                waft_widgets::GestureDetector::new()
5213                                    .behavior(waft_rendering::HitTestBehavior::DeferToChild)
5214                                    .on_horizontal_drag_start(Rc::new(
5215                                        move |_app: &mut App, _details: DragStartDetails| {
5216                                            started.set(true)
5217                                        },
5218                                    )
5219                                        as waft_gestures::GestureDragStartCallback)
5220                                    .child(MediaQuery::new(data, slider).into_widget()),
5221                            )
5222                            .into_widget()
5223                    }),
5224                )
5225            };
5226            tester.pump_widget(build(20.0, false));
5227
5228            let mut drag = TestPointer::touch(1);
5229            tester.down(&mut drag, slider_rect(tester).center());
5230            tester.pump_by(waft_gestures::K_PRESS_TIMEOUT);
5231
5232            // Less than configured touch slop, more than default touch slop
5233            let at = drag.position + Offset::new(19.0, 0.0);
5234            tester.move_to(&mut drag, at, true);
5235            tester.pump();
5236
5237            assert_eq!(value.get(), 0.5);
5238            assert!(drag_started.get());
5239
5240            drag_started.set(false);
5241
5242            tester.up(&drag);
5243            tester.pump_and_settle();
5244
5245            let mut drag = TestPointer::touch(2);
5246            tester.down(&mut drag, slider_rect(tester).center());
5247            tester.pump_by(waft_gestures::K_PRESS_TIMEOUT);
5248
5249            tester.pump_widget(build(10.0, true));
5250
5251            // More than touch slop.
5252            let at = drag.position + Offset::new(12.0, 0.0);
5253            tester.move_to(&mut drag, at, true);
5254
5255            tester.up(&drag);
5256            tester.pump_and_settle();
5257
5258            assert!(slider_end.get());
5259            assert!(!drag_started.get());
5260            assert_eq!(
5261                tester
5262                    .first::<RenderSlider>()
5263                    .gesture_settings(&tester.cell.borrow()),
5264                Some(DeviceGestureSettings::new(Some(10.0)))
5265            );
5266        });
5267    }
5268
5269    /// Dart's `allowedInteraction` cases' app: a slider at `value` in the centre of a material,
5270    /// logging its callbacks, under `theme`.
5271    fn interaction_app(
5272        theme: ThemeData,
5273        value: &Rc<Cell<f64>>,
5274        logs: &Rc<RefCell<Vec<&'static str>>>,
5275        allowed_interaction: Option<SliderInteraction>,
5276    ) -> WidgetRef {
5277        let (value, logs) = (Rc::clone(value), Rc::clone(logs));
5278        material_app(
5279            theme,
5280            Material::new()
5281                .child(Center::new().child(StatefulBuilder::new(
5282                    move |_app, _context, set_state| {
5283                        let (start_logs, changed_logs, end_logs) =
5284                            (Rc::clone(&logs), Rc::clone(&logs), Rc::clone(&logs));
5285                        let on_changed_value = Rc::clone(&value);
5286                        let mut slider = Slider::new(
5287                            value.get(),
5288                            Some(Rc::new(move |app: &mut App, new_value: f64| {
5289                                changed_logs.borrow_mut().push("onChanged");
5290                                let value = Rc::clone(&on_changed_value);
5291                                set_state(app, &mut |_app| value.set(new_value));
5292                            })),
5293                        )
5294                        .on_change_start(Rc::new(move |_app: &mut App, _value: f64| {
5295                            start_logs.borrow_mut().push("onChangeStart")
5296                        }))
5297                        .on_change_end(Rc::new(
5298                            move |_app: &mut App, _value: f64| {
5299                                end_logs.borrow_mut().push("onChangeEnd")
5300                            },
5301                        ));
5302                        if let Some(allowed_interaction) = allowed_interaction {
5303                            slider = slider.allowed_interaction(allowed_interaction);
5304                        }
5305                        slider.into_widget()
5306                    },
5307                )))
5308                .into_widget(),
5309        )
5310    }
5311
5312    // 'Slider.allowedInteraction' 'SliderInteraction.tapOnly'.
5313    #[test]
5314    fn slider_interaction_tap_only() {
5315        test_widgets(|tester| {
5316            let value = Rc::new(Cell::new(1.0));
5317            // (slider's left padding (overlayRadius), windowHeight / 2)
5318            let start_of_the_slider_track = Offset::new(24.0, 300.0);
5319            let center_of_the_slide_track = Offset::new(400.0, 300.0);
5320            let logs = Rc::new(RefCell::new(Vec::new()));
5321
5322            // allow tap only
5323            let theme = default_theme(tester);
5324            tester.pump_widget(interaction_app(
5325                theme,
5326                &value,
5327                &logs,
5328                Some(SliderInteraction::TapOnly),
5329            ));
5330
5331            assert!(logs.borrow().is_empty());
5332
5333            // test tap
5334            let mut gesture = TestPointer::touch(1);
5335            tester.down(&mut gesture, center_of_the_slide_track);
5336            tester.pump();
5337            // changes from 1.0 -> 0.5
5338            assert_eq!(value.get(), 0.5);
5339            assert_eq!(*logs.borrow(), ["onChangeStart", "onChanged"]);
5340
5341            // test slide
5342            tester.move_to(&mut gesture, start_of_the_slider_track, true);
5343            tester.pump();
5344            // has no effect, remains 0.5
5345            assert_eq!(value.get(), 0.5);
5346            assert_eq!(*logs.borrow(), ["onChangeStart", "onChanged"]);
5347
5348            tester.up(&gesture);
5349            tester.pump();
5350            assert_eq!(
5351                *logs.borrow(),
5352                ["onChangeStart", "onChanged", "onChangeEnd"]
5353            );
5354        });
5355    }
5356
5357    // 'SliderInteraction.tapAndSlide (default)'.
5358    #[test]
5359    fn slider_interaction_tap_and_slide_is_the_default() {
5360        test_widgets(|tester| {
5361            let value = Rc::new(Cell::new(1.0));
5362            // (slider's left padding (overlayRadius), windowHeight / 2)
5363            let start_of_the_slider_track = Offset::new(24.0, 300.0);
5364            let center_of_the_slide_track = Offset::new(400.0, 300.0);
5365            let end_of_the_slider_track = Offset::new(800.0 - 24.0, 300.0);
5366            let logs = Rc::new(RefCell::new(Vec::new()));
5367
5368            let theme = default_theme(tester);
5369            tester.pump_widget(interaction_app(theme, &value, &logs, None));
5370
5371            assert!(logs.borrow().is_empty());
5372
5373            // Test tap.
5374            let mut gesture = TestPointer::touch(1);
5375            tester.down(&mut gesture, center_of_the_slide_track);
5376            tester.pump();
5377            // changes from 1.0 -> 0.5
5378            assert_eq!(value.get(), 0.5);
5379            assert_eq!(*logs.borrow(), ["onChangeStart", "onChanged"]);
5380
5381            // test slide
5382            tester.move_to(&mut gesture, start_of_the_slider_track, true);
5383            tester.pump();
5384            // changes from 0.5 -> 0.0
5385            assert_eq!(value.get(), 0.0);
5386            tester.move_to(&mut gesture, end_of_the_slider_track, true);
5387            tester.pump();
5388            // changes from 0.0 -> 1.0
5389            assert_eq!(value.get(), 1.0);
5390            assert_eq!(
5391                *logs.borrow(),
5392                ["onChangeStart", "onChanged", "onChanged", "onChanged"]
5393            );
5394
5395            tester.up(&gesture);
5396            tester.pump();
5397
5398            assert_eq!(
5399                *logs.borrow(),
5400                [
5401                    "onChangeStart",
5402                    "onChanged",
5403                    "onChanged",
5404                    "onChanged",
5405                    "onChangeEnd"
5406                ]
5407            );
5408        });
5409    }
5410
5411    fn paints_circle_at(
5412        tester: &WidgetTester,
5413        render: AnyRenderObject,
5414        color: Color,
5415        x: f64,
5416        radius: Option<f64>,
5417    ) -> bool {
5418        paints(
5419            &tester.painted_ops(render),
5420            &[PaintCall::Circle {
5421                x: Some(x),
5422                y: None,
5423                radius,
5424                color: Some(color),
5425                style: None,
5426            }],
5427        )
5428        .is_ok()
5429    }
5430
5431    // 'SliderInteraction.slideOnly'.
5432    #[test]
5433    fn slider_interaction_slide_only() {
5434        test_widgets(|tester| {
5435            const OVERLAY_RADIUS: f64 = 23.0;
5436            let overlay_color = Colors::RED.primary();
5437            let value = Rc::new(Cell::new(1.0));
5438            // (slider's left padding (overlayRadius), windowHeight / 2)
5439            let start_of_the_slider_track = Offset::new(OVERLAY_RADIUS, 300.0);
5440            let center_of_the_slider_track = Offset::new(400.0, 300.0);
5441            let end_of_the_slider_track = Offset::new(800.0 - OVERLAY_RADIUS, 300.0);
5442            let x_pos_thumb = |t: f64| {
5443                start_of_the_slider_track.dx()
5444                    + (end_of_the_slider_track.dx() - start_of_the_slider_track.dx()) * t
5445            };
5446            let logs = Rc::new(RefCell::new(Vec::new()));
5447
5448            let theme = ThemeData::builder()
5449                .slider_theme(
5450                    SliderThemeData::new()
5451                        .overlay_color(overlay_color)
5452                        .overlay_shape(Rc::new(
5453                            RoundSliderOverlayShape::new().overlay_radius(OVERLAY_RADIUS),
5454                        )),
5455                )
5456                .build(&tester.cell.borrow());
5457            tester.pump_widget(interaction_app(
5458                theme,
5459                &value,
5460                &logs,
5461                Some(SliderInteraction::SlideOnly),
5462            ));
5463
5464            assert!(logs.borrow().is_empty());
5465
5466            // Test tap.
5467            let mut gesture = TestPointer::touch(1);
5468            tester.down(&mut gesture, center_of_the_slider_track);
5469            // Start animation.
5470            tester.pump();
5471            // Go to mid-animation frame.
5472            tester.pump_by(K_RADIAL_REACTION_DURATION.mul_f64(0.5));
5473            assert!(paints_circle_at(
5474                tester,
5475                slider_render(tester),
5476                overlay_color,
5477                x_pos_thumb(value.get()),
5478                None
5479            ));
5480            // We have a non-linear asymmetric curve, so just verify the radius is not full.
5481            assert!(!paints_circle_at(
5482                tester,
5483                slider_render(tester),
5484                overlay_color,
5485                x_pos_thumb(value.get()),
5486                Some(OVERLAY_RADIUS)
5487            ));
5488
5489            // Finish animation.
5490            tester.pump_and_settle();
5491            // Overlay drawn.
5492            assert!(paints_circle_at(
5493                tester,
5494                slider_render(tester),
5495                overlay_color,
5496                x_pos_thumb(value.get()),
5497                Some(OVERLAY_RADIUS)
5498            ));
5499            // Has no other effect as tap is disabled, remains 1.0.
5500            assert_eq!(value.get(), 1.0);
5501            assert_eq!(*logs.borrow(), ["onChangeStart"]);
5502
5503            // Test slide.
5504            tester.move_to(&mut gesture, start_of_the_slider_track, true);
5505            tester.pump();
5506            // Changes from 1.0 -> 0.5.
5507            assert_eq!(value.get(), 0.5);
5508            // Overlay still there.
5509            assert!(paints_circle_at(
5510                tester,
5511                slider_render(tester),
5512                overlay_color,
5513                x_pos_thumb(value.get()),
5514                Some(OVERLAY_RADIUS)
5515            ));
5516            tester.move_to(&mut gesture, end_of_the_slider_track, true);
5517            tester.pump();
5518            // Changes from 0.0 -> 1.0.
5519            assert_eq!(value.get(), 1.0);
5520            assert_eq!(*logs.borrow(), ["onChangeStart", "onChanged", "onChanged"]);
5521            // Overlay still there.
5522            assert!(paints_circle_at(
5523                tester,
5524                slider_render(tester),
5525                overlay_color,
5526                x_pos_thumb(value.get()),
5527                Some(OVERLAY_RADIUS)
5528            ));
5529
5530            tester.up(&gesture);
5531
5532            // Start release animation.
5533            tester.pump();
5534            // Go to mid-animation frame.
5535            tester.pump_by(K_RADIAL_REACTION_DURATION.mul_f64(0.5));
5536            assert!(paints_circle_at(
5537                tester,
5538                slider_render(tester),
5539                overlay_color,
5540                x_pos_thumb(value.get()),
5541                None
5542            ));
5543            // Verify the radius is not full.
5544            assert!(!paints_circle_at(
5545                tester,
5546                slider_render(tester),
5547                overlay_color,
5548                x_pos_thumb(value.get()),
5549                Some(OVERLAY_RADIUS)
5550            ));
5551
5552            tester.pump_and_settle();
5553            // No overlay drawn.
5554            let color: waft_embedder::valo::Color = overlay_color.into();
5555            assert!(!tester.painted_ops(slider_render(tester)).iter().any(|op| matches!(op,
5556                Op::DrawPath { path, paint, .. } if paint.color == color
5557                    && circle_of(path).is_some_and(|circle| (circle.width() / 2.0 - OVERLAY_RADIUS).abs() < 1e-3))));
5558
5559            assert_eq!(
5560                *logs.borrow(),
5561                ["onChangeStart", "onChanged", "onChanged", "onChangeEnd"]
5562            );
5563        });
5564    }
5565
5566    // 'SliderInteraction.slideThumb'.
5567    #[test]
5568    fn slider_interaction_slide_thumb() {
5569        test_widgets(|tester| {
5570            let value = Rc::new(Cell::new(1.0));
5571            // (slider's left padding (overlayRadius), windowHeight / 2)
5572            let start_of_the_slider_track = Offset::new(24.0, 300.0);
5573            let center_of_the_slider_track = Offset::new(400.0, 300.0);
5574            let end_of_the_slider_track = Offset::new(800.0 - 24.0, 300.0);
5575            let logs = Rc::new(RefCell::new(Vec::new()));
5576
5577            let theme = default_theme(tester);
5578            tester.pump_widget(interaction_app(
5579                theme,
5580                &value,
5581                &logs,
5582                Some(SliderInteraction::SlideThumb),
5583            ));
5584
5585            assert!(logs.borrow().is_empty());
5586
5587            // test tap
5588            let mut gesture = TestPointer::touch(1);
5589            tester.down(&mut gesture, center_of_the_slider_track);
5590            tester.pump();
5591            // has no effect, remains 1.0
5592            assert_eq!(value.get(), 1.0);
5593            assert!(logs.borrow().is_empty());
5594
5595            // test slide
5596            tester.move_to(&mut gesture, start_of_the_slider_track, true);
5597            tester.pump();
5598            // has no effect, remains 1.0
5599            assert_eq!(value.get(), 1.0);
5600            assert!(logs.borrow().is_empty());
5601
5602            // test slide thumb
5603            tester.up(&gesture);
5604            tester.down(&mut gesture, end_of_the_slider_track); // where the thumb is
5605            tester.pump();
5606            // has no effect, remains 1.0
5607            assert_eq!(value.get(), 1.0);
5608            assert_eq!(*logs.borrow(), ["onChangeStart"]);
5609
5610            tester.move_to(&mut gesture, center_of_the_slider_track, true);
5611            tester.pump();
5612            // changes from 1.0 -> 0.5
5613            assert_eq!(value.get(), 0.5);
5614            assert_eq!(*logs.borrow(), ["onChangeStart", "onChanged"]);
5615
5616            // test tap inside overlay but not on thumb, then slide
5617            tester.up(&gesture);
5618            // default overlay radius is 12, so 10 is inside the overlay
5619            tester.down(
5620                &mut gesture,
5621                center_of_the_slider_track + Offset::new(-10.0, 0.0),
5622            );
5623            tester.pump();
5624            // changes from 1.0 -> 0.5
5625            assert_eq!(value.get(), 0.5);
5626            assert_eq!(
5627                *logs.borrow(),
5628                ["onChangeStart", "onChanged", "onChangeEnd", "onChangeStart"]
5629            );
5630
5631            tester.move_to(
5632                &mut gesture,
5633                end_of_the_slider_track + Offset::new(-10.0, 0.0),
5634                true,
5635            );
5636            tester.pump();
5637            // changes from 0.5 -> 1.0
5638            assert_eq!(value.get(), 1.0);
5639            assert_eq!(
5640                *logs.borrow(),
5641                [
5642                    "onChangeStart",
5643                    "onChanged",
5644                    "onChangeEnd",
5645                    "onChangeStart",
5646                    "onChanged"
5647                ]
5648            );
5649
5650            tester.up(&gesture);
5651            tester.pump();
5652
5653            assert_eq!(
5654                *logs.borrow(),
5655                [
5656                    "onChangeStart",
5657                    "onChanged",
5658                    "onChangeEnd",
5659                    "onChangeStart",
5660                    "onChanged",
5661                    "onChangeEnd"
5662                ]
5663            );
5664        });
5665    }
5666
5667    /// Dart's `LoggingRoundedRectSliderTrackShape`: a [`RoundedRectSliderTrackShape`] that logs
5668    /// the secondary offset it paints with.
5669    #[derive(Debug)]
5670    struct LoggingRoundedRectSliderTrackShape {
5671        secondary_offset_log: Rc<RefCell<Vec<Option<Offset>>>>,
5672    }
5673
5674    impl crate::slider_parts::SliderTrackShape for LoggingRoundedRectSliderTrackShape {
5675        fn get_preferred_rect(
5676            &self,
5677            app: &App,
5678            parent_box: waft_rendering::AnyRenderBox,
5679            offset: Offset,
5680            slider_theme: &SliderThemeData,
5681            is_enabled: Option<bool>,
5682            is_discrete: Option<bool>,
5683        ) -> Rect {
5684            crate::slider_parts::SliderTrackShape::get_preferred_rect(
5685                &RoundedRectSliderTrackShape::new(),
5686                app,
5687                parent_box,
5688                offset,
5689                slider_theme,
5690                Some(is_enabled.unwrap_or(true)),
5691                Some(is_discrete.unwrap_or(false)),
5692            )
5693        }
5694
5695        fn paint(
5696            &self,
5697            app: &mut App,
5698            context: &mut PaintingContext,
5699            offset: Offset,
5700            parent_box: waft_rendering::AnyRenderBox,
5701            slider_theme: &SliderThemeData,
5702            enable_animation: AnyAnimation<f64>,
5703            thumb_center: Offset,
5704            secondary_offset: Option<Offset>,
5705            is_enabled: Option<bool>,
5706            is_discrete: Option<bool>,
5707            text_direction: TextDirection,
5708        ) {
5709            self.secondary_offset_log
5710                .borrow_mut()
5711                .push(secondary_offset);
5712            crate::slider_parts::SliderTrackShape::paint(
5713                &RoundedRectSliderTrackShape::new(),
5714                app,
5715                context,
5716                offset,
5717                parent_box,
5718                slider_theme,
5719                enable_animation,
5720                thumb_center,
5721                secondary_offset,
5722                Some(is_enabled.unwrap_or(false)),
5723                Some(is_discrete.unwrap_or(false)),
5724                text_direction,
5725            );
5726        }
5727
5728        fn is_rounded(&self) -> bool {
5729            true
5730        }
5731
5732        fn as_any(&self) -> &dyn Any {
5733            self
5734        }
5735    }
5736
5737    // 'Can update renderObject when secondaryTrackValue is updated'.
5738    #[test]
5739    fn the_render_object_updates_with_the_secondary_track_value() {
5740        test_widgets(|tester| {
5741            let log = Rc::new(RefCell::new(Vec::new()));
5742            let logging_track_shape = Rc::new(LoggingRoundedRectSliderTrackShape {
5743                secondary_offset_log: Rc::clone(&log),
5744            });
5745            let theme = ThemeData::builder()
5746                .slider_theme(SliderThemeData::new().track_shape(logging_track_shape))
5747                .build(&tester.cell.borrow());
5748            let build_slider = |secondary_track_value: Option<f64>| {
5749                let mut slider = Slider::new(0.0, noop());
5750                if let Some(secondary_track_value) = secondary_track_value {
5751                    slider = slider.secondary_track_value(secondary_track_value);
5752                }
5753                material_app(
5754                    theme.clone(),
5755                    Material::new()
5756                        .child(Center::new().child(slider))
5757                        .into_widget(),
5758                )
5759            };
5760
5761            tester.pump_widget(build_slider(None));
5762            tester.pump_and_settle();
5763            assert_eq!(*log.borrow().last().unwrap(), None);
5764
5765            tester.pump_widget(build_slider(Some(0.2)));
5766            tester.pump_and_settle();
5767            assert_eq!(
5768                *log.borrow().last().unwrap(),
5769                Some(Offset::new(174.4, 300.0))
5770            );
5771
5772            tester.pump_widget(build_slider(Some(0.5)));
5773            tester.pump_and_settle();
5774            assert_eq!(
5775                *log.borrow().last().unwrap(),
5776                Some(Offset::new(400.0, 300.0))
5777            );
5778        });
5779    }
5780
5781    // 'Discrete Slider does not apply thumb padding in a non-rounded track shape'.
5782    #[test]
5783    fn a_discrete_slider_applies_no_thumb_padding_on_a_non_rounded_track() {
5784        test_widgets(|tester| {
5785            // Regression test for https://github.com/flutter/flutter/issues/161805
5786            // The default track left and right padding.
5787            let slider_padding = 24.0;
5788            let theme = ThemeData::builder()
5789                .slider_theme(
5790                    SliderThemeData::new()
5791                        // Thumb padding is applied based on the track height.
5792                        .track_height(100.0)
5793                        .track_shape(Rc::new(
5794                            crate::slider_parts::RectangularSliderTrackShape::new(),
5795                        )),
5796                )
5797                .build(&tester.cell.borrow());
5798            let build_slider = |value: f64| {
5799                material_app(
5800                    theme.clone(),
5801                    Material::new()
5802                        .child(
5803                            SizedBox::new()
5804                                .width(300.0)
5805                                .child(Slider::new(value, noop()).max(100.0).divisions(100)),
5806                        )
5807                        .into_widget(),
5808                )
5809            };
5810
5811            tester.pump_widget(build_slider(0.0));
5812
5813            let primary = theme.color_scheme.primary();
5814            let paints_thumb_at = |tester: &WidgetTester, x: f64| {
5815                let color: waft_embedder::valo::Color = primary.into();
5816                tester
5817                    .painted_ops(slider_render(tester))
5818                    .iter()
5819                    .any(|op| match op {
5820                        Op::DrawPath { path, paint, .. } if paint.color == color => circle_of(path)
5821                            .is_some_and(|circle| {
5822                                (circle.center().dx() - x).abs() < 1e-3
5823                                    && (circle.center().dy() - 300.0).abs() < 1e-3
5824                            }),
5825                        _ => false,
5826                    })
5827            };
5828            assert!(paints_thumb_at(tester, slider_padding));
5829
5830            tester.pump_widget(build_slider(100.0));
5831            tester.pump_and_settle();
5832
5833            assert!(paints_thumb_at(tester, 800.0 - slider_padding));
5834        });
5835    }
5836
5837    // 'Slider does not crash at zero area'.
5838    #[test]
5839    fn a_slider_does_not_crash_at_zero_area() {
5840        test_widgets(|tester| {
5841            let theme = default_theme(tester);
5842            tester.pump_widget(material_app(
5843                theme,
5844                crate::scaffold::Scaffold::new()
5845                    .body(Center::new().child(SizedBox::shrink().child(Slider::new(1.0, noop()))))
5846                    .into_widget(),
5847            ));
5848            assert_eq!(slider_size(tester), Size::ZERO);
5849        });
5850    }
5851
5852    /// Dart's `LoggingValueIndicatorShape`: a value indicator shape that logs the width of
5853    /// the label painter it is given.
5854    #[derive(Debug)]
5855    struct LoggingValueIndicatorShape {
5856        log_painter_widths: Rc<RefCell<Vec<f64>>>,
5857    }
5858
5859    impl SliderComponentShape for LoggingValueIndicatorShape {
5860        fn get_preferred_size(&self, _is_enabled: bool, _is_discrete: bool) -> Size {
5861            Size::new(10.0, 10.0)
5862        }
5863
5864        fn paint(
5865            &self,
5866            _app: &mut App,
5867            _context: &mut PaintingContext,
5868            _offset: Offset,
5869            _activation_animation: AnyAnimation<f64>,
5870            _enable_animation: AnyAnimation<f64>,
5871            _is_discrete: bool,
5872            label_painter: &mut TextPainter,
5873            _parent_box: waft_rendering::AnyRenderBox,
5874            _slider_theme: &SliderThemeData,
5875            _text_direction: TextDirection,
5876            _value: f64,
5877            _text_scale_factor: f64,
5878            _size_with_overflow: Size,
5879        ) {
5880            assert!(label_painter.text().is_some());
5881            self.log_painter_widths
5882                .borrow_mut()
5883                .push(label_painter.width());
5884        }
5885
5886        fn as_any(&self) -> &dyn Any {
5887            self
5888        }
5889    }
5890
5891    // 'Slider label respects horizontal buffer and avoids screen overflow'.
5892    #[test]
5893    fn the_label_keeps_the_horizontal_buffer_and_avoids_screen_overflow() {
5894        test_widgets(|tester| {
5895            let log_painters = Rc::new(RefCell::new(Vec::new()));
5896            let shape = Rc::new(LoggingValueIndicatorShape {
5897                log_painter_widths: Rc::clone(&log_painters),
5898            });
5899            let theme = default_theme(tester);
5900            #[expect(deprecated, reason = "Dart's case uses the deprecated `always`")]
5901            let show_value_indicator = ShowValueIndicator::Always;
5902            tester.pump_widget(material_app(
5903                theme,
5904                crate::scaffold::Scaffold::new()
5905                    .body(SliderTheme::new(
5906                        SliderThemeData::new()
5907                            .show_value_indicator(show_value_indicator)
5908                            .value_indicator_shape(shape),
5909                        Slider::new(0.5, noop()).divisions(10).label(
5910                            "A very long label string that exceeds standard screen widths to test clipping behavior",
5911                        ),
5912                    ))
5913                    .into_widget(),
5914            ));
5915
5916            let mut gesture = TestPointer::touch(1);
5917            tester.down(&mut gesture, slider_rect(tester).center());
5918            tester.pump_and_settle();
5919
5920            let screen_width = WidgetTester::SIZE.width();
5921
5922            assert!(!log_painters.borrow().is_empty());
5923            assert!(*log_painters.borrow().last().unwrap() <= screen_width - 64.0);
5924
5925            tester.up(&gesture);
5926        });
5927    }
5928
5929    /// Dart's `_PositionRecordingTickMarkShape`: records the center of each tick mark as it is
5930    /// painted.
5931    #[derive(Debug)]
5932    struct PositionRecordingTickMarkShape {
5933        positions: Rc<RefCell<Vec<Offset>>>,
5934    }
5935
5936    impl SliderTickMarkShape for PositionRecordingTickMarkShape {
5937        fn get_preferred_size(&self, _slider_theme: &SliderThemeData, _is_enabled: bool) -> Size {
5938            Size::ZERO
5939        }
5940
5941        fn paint(
5942            &self,
5943            _app: &mut App,
5944            _context: &mut PaintingContext,
5945            center: Offset,
5946            _parent_box: waft_rendering::AnyRenderBox,
5947            _slider_theme: &SliderThemeData,
5948            _enable_animation: AnyAnimation<f64>,
5949            _thumb_center: Offset,
5950            _is_enabled: bool,
5951            _text_direction: TextDirection,
5952        ) {
5953            self.positions.borrow_mut().push(center);
5954        }
5955
5956        fn as_any(&self) -> &dyn Any {
5957            self
5958        }
5959    }
5960
5961    /// Dart's `pumpDiscreteSlider`: pumps a slider whose tick mark centers are recorded, and
5962    /// returns the centers of the `divisions + 1` ticks painted on the first frame, ordered
5963    /// left to right. Dart's `ValueListenableBuilder` over the value is a `StatefulBuilder`
5964    /// whose `onChanged` sets it.
5965    fn pump_discrete_slider(
5966        tester: &mut WidgetTester,
5967        value: &Rc<Cell<f64>>,
5968        divisions: i32,
5969        text_direction: TextDirection,
5970        year2023: Option<bool>,
5971    ) -> Vec<Offset> {
5972        let tick_centers = Rc::new(RefCell::new(Vec::new()));
5973        let shape = Rc::new(PositionRecordingTickMarkShape {
5974            positions: Rc::clone(&tick_centers),
5975        });
5976        let theme = default_theme(tester);
5977        let value = Rc::clone(value);
5978        tester.pump_widget(material_app(
5979            theme,
5980            Directionality::new(
5981                text_direction,
5982                SliderTheme::new(
5983                    SliderThemeData::new().tick_mark_shape(shape),
5984                    Material::new().child(Center::new().child(StatefulBuilder::new(
5985                        move |_app, _context, set_state| {
5986                            let on_changed_value = Rc::clone(&value);
5987                            let mut slider = Slider::new(
5988                                value.get(),
5989                                Some(Rc::new(move |app: &mut App, new_value: f64| {
5990                                    let value = Rc::clone(&on_changed_value);
5991                                    set_state(app, &mut |_app| value.set(new_value));
5992                                })),
5993                            )
5994                            .max(f64::from(divisions))
5995                            .divisions(divisions);
5996                            if let Some(year2023) = year2023 {
5997                                #[expect(deprecated, reason = "Dart's case passes `year2023`")]
5998                                {
5999                                    slider = slider.year2023(year2023);
6000                                }
6001                            }
6002                            slider.into_widget()
6003                        },
6004                    ))),
6005                ),
6006            )
6007            .into_widget(),
6008        ));
6009        // Later repaints append to the list, so keep only the first frame's ticks.
6010        let first_frame: Vec<Offset> = tick_centers
6011            .borrow()
6012            .iter()
6013            .take(divisions as usize + 1)
6014            .copied()
6015            .collect();
6016        assert_eq!(first_frame.len(), divisions as usize + 1);
6017        first_frame
6018    }
6019
6020    /// Dart's 'Discrete Slider snaps at the visual midpoint between ticks ($name)'.
6021    fn snaps_at_the_visual_midpoint(
6022        tester: &mut WidgetTester,
6023        text_direction: TextDirection,
6024        year2023: Option<bool>,
6025    ) {
6026        const DIVISIONS: i32 = 10;
6027        let value = Rc::new(Cell::new(0.0));
6028        let tick_centers =
6029            pump_discrete_slider(tester, &value, DIVISIONS, text_direction, year2023);
6030        // Ticks are painted left to right in pixel space regardless of text
6031        // direction, so in RTL the tick at pixel index i has the value divisions - i.
6032        let value_of_tick = |pixel_index: i32| match text_direction {
6033            TextDirection::Ltr => f64::from(pixel_index),
6034            TextDirection::Rtl => f64::from(DIVISIONS - pixel_index),
6035        };
6036
6037        // A small offset keeps the taps well clear of the exact midpoint while
6038        // staying smaller than the smallest drift of the old formula.
6039        const MIDPOINT_OFFSET: f64 = 0.05;
6040        for i in 0..DIVISIONS {
6041            let index = i as usize;
6042            let midpoint_dx = (tick_centers[index].dx() + tick_centers[index + 1].dx()) / 2.0;
6043            let dy = tick_centers[index].dy();
6044
6045            tester.tap_at(Offset::new(midpoint_dx - MIDPOINT_OFFSET, dy), 1);
6046            tester.pump();
6047            assert_eq!(
6048                value.get(),
6049                value_of_tick(i),
6050                "Tapping just left of the midpoint between pixel ticks {i} and {}",
6051                i + 1
6052            );
6053
6054            tester.tap_at(Offset::new(midpoint_dx + MIDPOINT_OFFSET, dy), 1);
6055            tester.pump();
6056            assert_eq!(
6057                value.get(),
6058                value_of_tick(i + 1),
6059                "Tapping just right of the midpoint between pixel ticks {i} and {}",
6060                i + 1
6061            );
6062        }
6063    }
6064
6065    // 'Discrete Slider snaps at the visual midpoint between ticks (M3)'.
6066    #[test]
6067    fn a_discrete_slider_snaps_at_the_visual_midpoint_m3() {
6068        test_widgets(|tester| snaps_at_the_visual_midpoint(tester, TextDirection::Ltr, None));
6069    }
6070
6071    // 'Discrete Slider snaps at the visual midpoint between ticks (M3 RTL)'.
6072    #[test]
6073    fn a_discrete_slider_snaps_at_the_visual_midpoint_m3_rtl() {
6074        test_widgets(|tester| snaps_at_the_visual_midpoint(tester, TextDirection::Rtl, None));
6075    }
6076
6077    // 'Discrete Slider snaps at the visual midpoint between ticks (M3 with year2023 false
6078    // (gapped track))'.
6079    #[test]
6080    fn a_discrete_slider_snaps_at_the_visual_midpoint_on_the_gapped_track() {
6081        test_widgets(|tester| {
6082            snaps_at_the_visual_midpoint(tester, TextDirection::Ltr, Some(false))
6083        });
6084    }
6085
6086    // 'Discrete Slider snaps at the visual midpoint between ticks (M3 with year2023 false
6087    // (gapped track) RTL)'.
6088    #[test]
6089    fn a_discrete_slider_snaps_at_the_visual_midpoint_on_the_gapped_track_rtl() {
6090        test_widgets(|tester| {
6091            snaps_at_the_visual_midpoint(tester, TextDirection::Rtl, Some(false))
6092        });
6093    }
6094
6095    // 'Discrete Slider snaps to a tick when tapping its center'.
6096    #[test]
6097    fn a_discrete_slider_snaps_to_a_tick_tapped_at_its_center() {
6098        test_widgets(|tester| {
6099            const DIVISIONS: i32 = 10;
6100            let value = Rc::new(Cell::new(0.0));
6101            let tick_centers =
6102                pump_discrete_slider(tester, &value, DIVISIONS, TextDirection::Ltr, None);
6103
6104            for i in (0..=DIVISIONS).rev() {
6105                tester.tap_at(tick_centers[i as usize], 1);
6106                tester.pump();
6107                assert_eq!(value.get(), f64::from(i), "Tapping the center of tick {i}");
6108            }
6109        });
6110    }
6111
6112    // 'Discrete Slider drag after a tap uses the same track coordinates as the tap'.
6113    #[test]
6114    fn a_discrete_drag_after_a_tap_uses_the_tap_track_coordinates() {
6115        test_widgets(|tester| {
6116            // With many divisions, even a small mismatch between the width used to map
6117            // a position to a value and the width used to scale drag deltas adds up to
6118            // more than half a division over a full-track drag. The gapped track has the
6119            // largest padding, which makes the mismatch most visible.
6120            const DIVISIONS: i32 = 100;
6121            let value = Rc::new(Cell::new(0.0));
6122            let tick_centers =
6123                pump_discrete_slider(tester, &value, DIVISIONS, TextDirection::Ltr, Some(false));
6124
6125            let mut gesture = TestPointer::touch(1);
6126            tester.down(&mut gesture, tick_centers[0]);
6127            // Move past the touch slop first so the drag starts mid-gesture and the
6128            // rest of the movement is scaled by the drag delta normalizer.
6129            let at = gesture.position + Offset::new(waft_gestures::K_TOUCH_SLOP * 2.0, 0.0);
6130            tester.move_to(&mut gesture, at, true);
6131            tester.move_to(&mut gesture, *tick_centers.last().unwrap(), true);
6132            tester.pump();
6133            assert_eq!(value.get(), f64::from(DIVISIONS));
6134
6135            tester.move_to(&mut gesture, tick_centers[0], true);
6136            tester.pump();
6137            assert_eq!(value.get(), 0.0);
6138            tester.up(&gesture);
6139        });
6140    }
6141
6142    /// Dart's `expect(render, paints..calls)`.
6143    pub(crate) fn render_paints(
6144        tester: &WidgetTester,
6145        render: AnyRenderObject,
6146        calls: &[PaintCall],
6147    ) -> bool {
6148        paints(&tester.painted_ops(render), calls).is_ok()
6149    }
6150
6151    // 'Default Slider when year2023 is false'.
6152    #[test]
6153    #[expect(deprecated, reason = "Dart's case calls the deprecated `withOpacity`")]
6154    fn the_default_slider_when_year2023_is_false() {
6155        test_widgets(|tester| {
6156            let theme = default_theme(tester);
6157            let color_scheme = theme.color_scheme.clone();
6158            let active_track_color = color_scheme.primary();
6159            let inactive_track_color = color_scheme.secondary_container();
6160            let secondary_active_track_color = color_scheme.primary().with_opacity(0.54);
6161            let disabled_active_track_color = color_scheme.on_surface().with_opacity(0.38);
6162            let disabled_inactive_track_color = color_scheme.on_surface().with_opacity(0.12);
6163            let disabled_secondary_active_track_color =
6164                color_scheme.on_surface().with_opacity(0.38);
6165            let active_tick_mark_color = color_scheme.on_primary();
6166            let inactive_tick_mark_color = color_scheme.on_secondary_container();
6167            let disabled_active_tick_mark_color = color_scheme.on_inverse_surface();
6168            let disabled_inactive_tick_mark_color = color_scheme.on_surface();
6169            let thumb_color = color_scheme.primary();
6170            let disabled_thumb_color = color_scheme.on_surface().with_opacity(0.38);
6171            let value_indicator_color = color_scheme.inverse_surface();
6172            let value = 0.45;
6173            let app_theme = default_theme(tester);
6174            let build_app =
6175                |divisions: Option<i32>, enabled: bool, text_direction: TextDirection| {
6176                    let mut slider = Slider::new(value, enabled.then(noop).flatten())
6177                        .year2023(false)
6178                        .secondary_track_value(0.75)
6179                        .label(format!("{value}"));
6180                    if let Some(divisions) = divisions {
6181                        slider = slider.divisions(divisions);
6182                    }
6183                    material_body(
6184                        app_theme.clone(),
6185                        text_direction,
6186                        Center::new().child(crate::theme::Theme::new(theme.clone(), slider)),
6187                    )
6188                };
6189
6190            let app = build_app(None, true, TextDirection::Ltr);
6191            tester.pump_widget(app);
6192
6193            // Test default track shape.
6194            let outer = waft_embedder::Radius::circular(8.0);
6195            let inner = waft_embedder::Radius::circular(2.0);
6196            let rrect =
6197                |left, top, right, bottom, top_left, top_right, bottom_right, bottom_left| {
6198                    waft_embedder::RRect::from_ltrb_and_corners(
6199                        left,
6200                        top,
6201                        right,
6202                        bottom,
6203                        top_left,
6204                        top_right,
6205                        bottom_right,
6206                        bottom_left,
6207                    )
6208                };
6209            assert!(render_paints(
6210                tester,
6211                slider_render(tester),
6212                &[
6213                    // Active track.
6214                    PaintCall::rrect_at(
6215                        rrect(24.0, 292.0, 356.4, 308.0, outer, inner, inner, outer),
6216                        Some(active_track_color),
6217                    ),
6218                    // Inactive track.
6219                    PaintCall::rrect_at(
6220                        rrect(368.4, 292.0, 776.0, 308.0, inner, outer, outer, inner),
6221                        Some(inactive_track_color),
6222                    ),
6223                    // Secondary track.
6224                    PaintCall::rrect_at(
6225                        rrect(368.4, 292.0, 588.0, 308.0, inner, outer, outer, inner),
6226                        Some(secondary_active_track_color),
6227                    ),
6228                ],
6229            ));
6230
6231            // Test default track shape in RTL. It is the mirror image of the one in LTR,
6232            // and the secondary track stops a track gap before the thumb.
6233            // Regression test for https://github.com/flutter/flutter/issues/194279
6234            let app = build_app(None, true, TextDirection::Rtl);
6235            tester.pump_widget(app);
6236            assert!(render_paints(
6237                tester,
6238                slider_render(tester),
6239                &[
6240                    // Inactive track.
6241                    PaintCall::rrect_at(
6242                        rrect(24.0, 292.0, 431.6, 308.0, outer, inner, inner, outer),
6243                        Some(inactive_track_color),
6244                    ),
6245                    // Active track.
6246                    PaintCall::rrect_at(
6247                        rrect(443.6, 292.0, 776.0, 308.0, inner, outer, outer, inner),
6248                        Some(active_track_color),
6249                    ),
6250                    // Secondary track.
6251                    PaintCall::rrect_at(
6252                        rrect(212.0, 292.0, 431.6, 308.0, outer, inner, inner, outer),
6253                        Some(secondary_active_track_color),
6254                    ),
6255                ],
6256            ));
6257
6258            let app = build_app(None, true, TextDirection::Ltr);
6259            tester.pump_widget(app);
6260
6261            // Test default colors for enabled slider.
6262            let render = slider_render(tester);
6263            assert!(render_paints(
6264                tester,
6265                render,
6266                &[PaintCall::circle(None), PaintCall::rrect(Some(thumb_color))]
6267            ));
6268            assert!(!render_paints(
6269                tester,
6270                render,
6271                &[
6272                    PaintCall::circle(None),
6273                    PaintCall::circle(Some(disabled_thumb_color))
6274                ]
6275            ));
6276            assert!(!render_paints(
6277                tester,
6278                render,
6279                &[PaintCall::rrect(Some(disabled_active_track_color))]
6280            ));
6281            assert!(!render_paints(
6282                tester,
6283                render,
6284                &[PaintCall::rrect(Some(disabled_inactive_track_color))]
6285            ));
6286            assert!(!render_paints(
6287                tester,
6288                render,
6289                &[PaintCall::rrect(Some(
6290                    disabled_secondary_active_track_color
6291                ))]
6292            ));
6293
6294            // Test defaults colors for discrete slider.
6295            let app = build_app(Some(3), true, TextDirection::Ltr);
6296            tester.pump_widget(app);
6297            let render = slider_render(tester);
6298            assert!(render_paints(
6299                tester,
6300                render,
6301                &[
6302                    PaintCall::rrect(Some(active_track_color)),
6303                    PaintCall::rrect(Some(inactive_track_color)),
6304                    PaintCall::rrect(Some(secondary_active_track_color)),
6305                    PaintCall::circle(Some(active_tick_mark_color)),
6306                    PaintCall::circle(Some(active_tick_mark_color)),
6307                    PaintCall::circle(Some(inactive_tick_mark_color)),
6308                    PaintCall::circle(Some(inactive_tick_mark_color)),
6309                ],
6310            ));
6311            assert!(!render_paints(
6312                tester,
6313                render,
6314                &[PaintCall::circle(Some(disabled_thumb_color))]
6315            ));
6316            assert!(!render_paints(
6317                tester,
6318                render,
6319                &[PaintCall::rrect(Some(disabled_active_track_color))]
6320            ));
6321            assert!(!render_paints(
6322                tester,
6323                render,
6324                &[PaintCall::rrect(Some(disabled_inactive_track_color))]
6325            ));
6326            assert!(!render_paints(
6327                tester,
6328                render,
6329                &[PaintCall::rrect(Some(
6330                    disabled_secondary_active_track_color
6331                ))]
6332            ));
6333
6334            // Test defaults colors for disabled slider.
6335            let app = build_app(None, false, TextDirection::Ltr);
6336            tester.pump_widget(app);
6337            tester.pump_and_settle();
6338            let render = slider_render(tester);
6339            assert!(render_paints(
6340                tester,
6341                render,
6342                &[
6343                    PaintCall::rrect(Some(disabled_active_track_color)),
6344                    PaintCall::rrect(Some(disabled_inactive_track_color)),
6345                    PaintCall::rrect(Some(disabled_secondary_active_track_color)),
6346                ],
6347            ));
6348            assert!(render_paints(
6349                tester,
6350                render,
6351                &[
6352                    PaintCall::circle(None),
6353                    PaintCall::rrect(Some(disabled_thumb_color))
6354                ]
6355            ));
6356            assert!(!render_paints(
6357                tester,
6358                render,
6359                &[PaintCall::circle(None), PaintCall::rrect(Some(thumb_color))]
6360            ));
6361            assert!(!render_paints(
6362                tester,
6363                render,
6364                &[PaintCall::rrect(Some(active_track_color))]
6365            ));
6366            assert!(!render_paints(
6367                tester,
6368                render,
6369                &[PaintCall::rrect(Some(inactive_track_color))]
6370            ));
6371            assert!(!render_paints(
6372                tester,
6373                render,
6374                &[PaintCall::rrect(Some(secondary_active_track_color))]
6375            ));
6376
6377            // Test defaults colors for disabled discrete slider.
6378            let app = build_app(Some(3), false, TextDirection::Ltr);
6379            tester.pump_widget(app);
6380            let render = slider_render(tester);
6381            assert!(render_paints(
6382                tester,
6383                render,
6384                &[
6385                    PaintCall::rrect(Some(disabled_active_track_color)),
6386                    PaintCall::rrect(Some(disabled_inactive_track_color)),
6387                    PaintCall::rrect(Some(disabled_secondary_active_track_color)),
6388                    PaintCall::circle(Some(disabled_active_tick_mark_color)),
6389                    PaintCall::circle(Some(disabled_active_tick_mark_color)),
6390                    PaintCall::circle(Some(disabled_inactive_tick_mark_color)),
6391                    PaintCall::circle(Some(disabled_inactive_tick_mark_color)),
6392                    PaintCall::rrect(Some(disabled_thumb_color)),
6393                ],
6394            ));
6395            assert!(!render_paints(
6396                tester,
6397                render,
6398                &[PaintCall::circle(None), PaintCall::rrect(Some(thumb_color))]
6399            ));
6400            assert!(!render_paints(
6401                tester,
6402                render,
6403                &[PaintCall::rrect(Some(active_track_color))]
6404            ));
6405            assert!(!render_paints(
6406                tester,
6407                render,
6408                &[PaintCall::rrect(Some(inactive_track_color))]
6409            ));
6410            assert!(!render_paints(
6411                tester,
6412                render,
6413                &[PaintCall::rrect(Some(secondary_active_track_color))]
6414            ));
6415
6416            let app = build_app(Some(3), true, TextDirection::Ltr);
6417            tester.pump_widget(app);
6418            tester.pump_and_settle();
6419
6420            let center = slider_rect(tester).center();
6421            let mut gesture = TestPointer::touch(1);
6422            tester.down(&mut gesture, center);
6423            // Wait for value indicator animation to finish.
6424            tester.pump_and_settle();
6425
6426            let value_indicator_box = tester
6427                .first::<RenderValueIndicator>()
6428                .as_render_object(&tester.cell.borrow());
6429            let ops = tester.painted_ops(value_indicator_box);
6430            let scale = ops
6431                .iter()
6432                .position(|op| matches!(op, Op::Transform(_)))
6433                .expect("the value indicator scales");
6434            assert_paints(
6435                &ops[scale..],
6436                &[PaintCall::rrect(Some(value_indicator_color))],
6437            );
6438            tester.up(&gesture);
6439        });
6440    }
6441
6442    // 'Slider value indicator text when year2023 is false'.
6443    #[test]
6444    fn the_value_indicator_text_when_year2023_is_false() {
6445        test_widgets(|tester| {
6446            let value = 50.0_f64;
6447            let log = Rc::new(RefCell::new(Vec::new()));
6448            let shape = Rc::new(LoggingValueIndicatorLabel {
6449                log: Rc::clone(&log),
6450            });
6451            let theme = ThemeData::builder()
6452                .slider_theme(SliderThemeData::new().value_indicator_shape(shape))
6453                .build(&tester.cell.borrow());
6454            #[expect(deprecated, reason = "Dart's case passes `year2023`")]
6455            let slider = Slider::new(value, noop())
6456                .year2023(false)
6457                .max(100.0)
6458                .divisions(4)
6459                .label(format!("{}", value.round()));
6460            tester.pump_widget(material_app(
6461                theme.clone(),
6462                Material::new()
6463                    .child(Center::new().child(slider))
6464                    .into_widget(),
6465            ));
6466
6467            // Normal text
6468            let center = slider_rect(tester).center();
6469            let mut gesture = TestPointer::touch(1);
6470            tester.down(&mut gesture, center);
6471            tester.pump_and_settle();
6472
6473            let (text, style) = log.borrow().last().cloned().expect("the shape painted");
6474            assert_eq!(text, "50");
6475            assert_eq!(style.font_size, Some(14.0));
6476            assert_eq!(
6477                style.color.as_ref().map(|color| color.color()),
6478                Some(theme.color_scheme.on_inverse_surface())
6479            );
6480
6481            tester.up(&gesture);
6482            tester.pump_and_settle();
6483        });
6484    }
6485
6486    /// Dart's `LoggingValueIndicatorShape` logging the label span: its plain text and style.
6487    #[derive(Debug)]
6488    struct LoggingValueIndicatorLabel {
6489        log: Rc<RefCell<Vec<(String, TextStyle)>>>,
6490    }
6491
6492    impl SliderComponentShape for LoggingValueIndicatorLabel {
6493        fn get_preferred_size(&self, _is_enabled: bool, _is_discrete: bool) -> Size {
6494            Size::new(10.0, 10.0)
6495        }
6496
6497        fn paint(
6498            &self,
6499            _app: &mut App,
6500            _context: &mut PaintingContext,
6501            _offset: Offset,
6502            _activation_animation: AnyAnimation<f64>,
6503            _enable_animation: AnyAnimation<f64>,
6504            _is_discrete: bool,
6505            label_painter: &mut TextPainter,
6506            _parent_box: waft_rendering::AnyRenderBox,
6507            _slider_theme: &SliderThemeData,
6508            _text_direction: TextDirection,
6509            _value: f64,
6510            _text_scale_factor: f64,
6511            _size_with_overflow: Size,
6512        ) {
6513            let span = label_painter.text().cloned().expect("labelPainter.text!");
6514            let style = span.style().cloned().expect("the label's style");
6515            self.log
6516                .borrow_mut()
6517                .push((label_painter.plain_text().to_owned(), style));
6518        }
6519
6520        fn as_any(&self) -> &dyn Any {
6521            self
6522        }
6523    }
6524
6525    // "Slider doesn't start any animations after dispose".
6526    #[test]
6527    fn a_slider_starts_no_animation_after_dispose() {
6528        test_widgets(|tester| {
6529            let heard = Heard::starting_at(0.0);
6530            let theme = default_theme(tester);
6531            tester.pump_widget(stateful_slider_app(
6532                tester,
6533                theme,
6534                TextDirection::Ltr,
6535                &heard,
6536                plain,
6537                |slider| slider.divisions(4),
6538            ));
6539
6540            let mut gesture = TestPointer::touch(1);
6541            tester.down(&mut gesture, slider_rect(tester).center());
6542            tester.pump_and_settle();
6543            assert_eq!(heard.value.get(), 0.5);
6544            let at = gesture.position + Offset::new(-500.0, 0.0);
6545            tester.move_to(&mut gesture, at, true);
6546            tester.pump_and_settle();
6547            // Change the tree to dispose the original widget.
6548            tester.pump_widget(SizedBox::new().into_widget());
6549            assert_eq!(tester.pump_and_settle(), 1);
6550            tester.up(&gesture);
6551        });
6552    }
6553
6554    // 'Overlay appear only when hovered on the thumb on desktop' (macOS, Linux, Windows).
6555    #[test]
6556    fn the_overlay_appears_only_when_the_thumb_is_hovered_on_desktop() {
6557        test_widgets(|_| {
6558            for platform in [
6559                TargetPlatform::MacOS,
6560                TargetPlatform::Linux,
6561                TargetPlatform::Windows,
6562            ] {
6563                test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
6564                    let value = Rc::new(Cell::new(0.5));
6565                    const OVERLAY_COLOR: Color = Color::new(0xffff0000);
6566                    let theme = default_theme(tester);
6567                    let build_app = || {
6568                        focusable_slider_app(theme.clone(), &value, true, |slider| {
6569                            slider.overlay_color(Rc::new(WidgetStatePropertyAll::new(Some(
6570                                OVERLAY_COLOR,
6571                            ))))
6572                        })
6573                    };
6574                    tester.pump_widget(build_app());
6575
6576                    // Slider does not have overlay when enabled and not hovered.
6577                    tester.pump_and_settle();
6578                    assert!(!paints_circle(tester, slider_render(tester), OVERLAY_COLOR));
6579
6580                    // Hover on the slider but outside the thumb.
6581                    let mut gesture = TestPointer::mouse(1, 0);
6582                    tester.add_pointer(&mut gesture, Offset::ZERO);
6583                    tester.move_to(&mut gesture, slider_rect(tester).top_left(), false);
6584
6585                    tester.pump_widget(build_app());
6586                    tester.pump_and_settle();
6587                    assert!(!paints_circle(tester, slider_render(tester), OVERLAY_COLOR));
6588
6589                    // Hover on the thumb.
6590                    tester.move_to(&mut gesture, slider_rect(tester).center(), false);
6591                    tester.pump_and_settle();
6592                    assert!(
6593                        paints_circle(tester, slider_render(tester), OVERLAY_COLOR),
6594                        "on {platform:?}"
6595                    );
6596
6597                    // Hover on the slider but outside the thumb.
6598                    tester.move_to(&mut gesture, slider_rect(tester).bottom_right(), false);
6599                    tester.pump_and_settle();
6600                    assert!(!paints_circle(tester, slider_render(tester), OVERLAY_COLOR));
6601                });
6602            }
6603        });
6604    }
6605
6606    // 'showValueIndicator takes priority over theme'.
6607    #[test]
6608    fn show_value_indicator_takes_priority_over_the_theme() {
6609        test_widgets(|tester| {
6610            let theme = default_theme(tester);
6611            let red = Colors::RED.primary();
6612            let build_app =
6613                |theme_show_value_indicator: Option<ShowValueIndicator>,
6614                 slider_show_value_indicator: Option<ShowValueIndicator>| {
6615                    let mut slider_theme = SliderThemeData::new().value_indicator_color(red);
6616                    if let Some(show_value_indicator) = theme_show_value_indicator {
6617                        slider_theme = slider_theme.show_value_indicator(show_value_indicator);
6618                    }
6619                    let mut slider = Slider::new(0.5, noop()).label("0.5");
6620                    if let Some(show_value_indicator) = slider_show_value_indicator {
6621                        slider = slider.show_value_indicator(show_value_indicator);
6622                    }
6623                    material_app(
6624                        theme.clone(),
6625                        Material::new()
6626                            .child(Center::new().child(SliderTheme::new(slider_theme, slider)))
6627                            .into_widget(),
6628                    )
6629                };
6630            let check_value_indicator = |tester: &WidgetTester, is_visible: bool| {
6631                // _RenderValueIndicator is the last render object in the tree.
6632                let visible = tester
6633                    .all::<RenderValueIndicator>()
6634                    .into_iter()
6635                    .last()
6636                    .is_some_and(|value_indicator_box| {
6637                        let render = value_indicator_box.as_render_object(&tester.cell.borrow());
6638                        render_paints(
6639                            tester,
6640                            render,
6641                            &[PaintCall::path(Some(red)), PaintCall::Paragraph],
6642                        )
6643                    });
6644                assert_eq!(visible, is_visible);
6645            };
6646
6647            tester.pump_widget(build_app(Some(ShowValueIndicator::Never), None));
6648            check_value_indicator(tester, false);
6649
6650            tester.pump_widget(build_app(
6651                Some(ShowValueIndicator::Never),
6652                Some(ShowValueIndicator::AlwaysVisible),
6653            ));
6654            check_value_indicator(tester, true);
6655
6656            tester.pump_widget(build_app(
6657                Some(ShowValueIndicator::AlwaysVisible),
6658                Some(ShowValueIndicator::Never),
6659            ));
6660            check_value_indicator(tester, false);
6661        });
6662    }
6663
6664    // 'Event on Slider should perform no-op if already unmounted'.
6665    #[test]
6666    fn an_event_on_an_unmounted_slider_does_nothing() {
6667        test_widgets(|tester| {
6668            // Test covering crashing found in Google internal issue b/192329942.
6669            let value = Rc::new(Cell::new(0.0));
6670            let should_show_slider = Rc::new(Cell::new(true));
6671            let show_setter: Rc<RefCell<Option<waft_widgets::StateSetter>>> =
6672                Rc::new(RefCell::new(None));
6673            let theme = default_theme(tester);
6674            let (builder_value, builder_show, builder_setter) = (
6675                Rc::clone(&value),
6676                Rc::clone(&should_show_slider),
6677                Rc::clone(&show_setter),
6678            );
6679            tester.pump_widget(material_body(
6680                theme,
6681                TextDirection::Ltr,
6682                Center::new().child(StatefulBuilder::new(move |_app, _context, set_state| {
6683                    // Dart's `ValueListenableBuilder` over `shouldShowSliderListenable`.
6684                    *builder_setter.borrow_mut() = Some(Rc::clone(&set_state));
6685                    let on_changed_value = Rc::clone(&builder_value);
6686                    let child = if builder_show.get() {
6687                        Slider::new(
6688                            builder_value.get(),
6689                            Some(Rc::new(move |app: &mut App, new_value: f64| {
6690                                let value = Rc::clone(&on_changed_value);
6691                                set_state(app, &mut |_app| value.set(new_value));
6692                            })),
6693                        )
6694                        .into_widget()
6695                    } else {
6696                        SizedBox::expand().into_widget()
6697                    };
6698                    waft_widgets::GestureDetector::new()
6699                        .behavior(waft_rendering::HitTestBehavior::Translucent)
6700                        // Note: it is important that `onTap` is non-null so
6701                        // [GestureDetector] will register tap events.
6702                        .on_tap(Listener::new(|_app| {}))
6703                        .child(child)
6704                        .into_widget()
6705                })),
6706            ));
6707
6708            // Move Slider.
6709            let mut gesture = TestPointer::touch(1);
6710            tester.down(&mut gesture, slider_rect(tester).center());
6711            let at = gesture.position + Offset::new(1.0, 0.0);
6712            tester.move_to(&mut gesture, at, true);
6713            tester.pump_and_settle();
6714
6715            // Hide Slider. Slider will dispose and unmount.
6716            let set_state = show_setter.borrow().clone().expect("the builder ran");
6717            {
6718                let should_show_slider = Rc::clone(&should_show_slider);
6719                set_state(&mut tester.cell.borrow_mut(), &mut |_app| {
6720                    should_show_slider.set(false)
6721                });
6722            }
6723            tester.pump_and_settle();
6724
6725            // Move Slider after unmounted.
6726            let at = gesture.position + Offset::new(1.0, 0.0);
6727            tester.move_to(&mut gesture, at, true);
6728            tester.pump_and_settle();
6729        });
6730    }
6731
6732    // 'Slider.padding can override the default Slider padding'.
6733    #[test]
6734    fn slider_padding_overrides_the_default_padding() {
6735        test_widgets(|tester| {
6736            use waft_embedder::{RRect, Radius};
6737            use waft_painting::{EdgeInsets, EdgeInsetsDirectional};
6738            let theme = default_theme(tester);
6739            let build_slider = |padding: EdgeInsetsGeometry| {
6740                material_app(
6741                    theme.clone(),
6742                    Material::new()
6743                        .child(
6744                            Center::new().child(
6745                                waft_widgets::IntrinsicHeight::new()
6746                                    .child(Slider::new(0.5, noop()).padding(padding)),
6747                            ),
6748                        )
6749                        .into_widget(),
6750                )
6751            };
6752            let slider_render_box_size =
6753                |tester: &WidgetTester| tester.first::<RenderSlider>().size(&tester.cell.borrow());
6754            let tracks = |inactive: (f64, f64, f64, f64), active: (f64, f64, f64, f64)| {
6755                [
6756                    // Inactive track.
6757                    PaintCall::rrect_at(
6758                        RRect::from_ltrbr(
6759                            inactive.0,
6760                            inactive.1,
6761                            inactive.2,
6762                            inactive.3,
6763                            Radius::circular(2.0),
6764                        ),
6765                        None,
6766                    ),
6767                    // Active track.
6768                    PaintCall::rrect_at(
6769                        RRect::from_ltrbr(
6770                            active.0,
6771                            active.1,
6772                            active.2,
6773                            active.3,
6774                            Radius::circular(3.0),
6775                        ),
6776                        None,
6777                    ),
6778                ]
6779            };
6780
6781            // Test Slider height and tracks spacing with zero padding.
6782            tester.pump_widget(build_slider(EdgeInsets::ZERO.into()));
6783            tester.pump_and_settle();
6784
6785            // The height equals to the default thumb height.
6786            assert_eq!(slider_render_box_size(tester), Size::new(800.0, 20.0));
6787            assert!(render_paints(
6788                tester,
6789                slider_render(tester),
6790                &tracks((398.0, 8.0, 800.0, 12.0), (0.0, 7.0, 402.0, 13.0))
6791            ));
6792
6793            // Test Slider height and tracks spacing with directional padding.
6794            const START_PADDING: f64 = 100.0;
6795            const END_PADDING: f64 = 20.0;
6796            tester.pump_widget(build_slider(
6797                EdgeInsetsDirectional::only(START_PADDING, 0.0, END_PADDING, 0.0).into(),
6798            ));
6799            tester.pump_and_settle();
6800
6801            assert_eq!(
6802                slider_render_box_size(tester),
6803                Size::new(800.0 - START_PADDING - END_PADDING, 20.0)
6804            );
6805            assert!(render_paints(
6806                tester,
6807                slider_render(tester),
6808                &tracks((338.0, 8.0, 680.0, 12.0), (0.0, 7.0, 342.0, 13.0))
6809            ));
6810
6811            // Test Slider height and tracks spacing with top and bottom padding.
6812            const TOP_PADDING: f64 = 100.0;
6813            const BOTTOM_PADDING: f64 = 20.0;
6814            const TRACK_HEIGHT: f64 = 20.0;
6815            tester.pump_widget(build_slider(
6816                EdgeInsetsDirectional::only(0.0, TOP_PADDING, 0.0, BOTTOM_PADDING).into(),
6817            ));
6818            tester.pump_and_settle();
6819
6820            assert_eq!(
6821                slider_size(tester),
6822                Size::new(800.0, TOP_PADDING + TRACK_HEIGHT + BOTTOM_PADDING)
6823            );
6824            assert_eq!(slider_render_box_size(tester), Size::new(800.0, 20.0));
6825            assert!(render_paints(
6826                tester,
6827                slider_render(tester),
6828                &tracks((398.0, 8.0, 800.0, 12.0), (0.0, 7.0, 402.0, 13.0))
6829            ));
6830        });
6831    }
6832
6833    /// Dart's 'Discrete Slider repaints and animates when dragged' and 'Discrete Slider
6834    /// repaints when dragged', whose bodies are the same: the thumb's repaint centres while a
6835    /// discrete slider is pressed, then dragged to its start and animated there.
6836    fn discrete_slider_repaints_when_dragged(tester: &mut WidgetTester) {
6837        let heard = Heard::starting_at(0.0);
6838        let log = Rc::new(RefCell::new(Vec::new()));
6839        let thumb_log = Rc::clone(&log);
6840        let theme = default_theme(tester);
6841        tester.pump_widget(stateful_slider_app(
6842            tester,
6843            theme,
6844            TextDirection::Ltr,
6845            &heard,
6846            move |app, context, slider| {
6847                let slider_theme = SliderTheme::of(app, context)
6848                    .copy_with()
6849                    .thumb_shape(Rc::new(LoggingThumbShape {
6850                        log: Rc::clone(&thumb_log),
6851                    }));
6852                SliderTheme::new(slider_theme, slider).into_widget()
6853            },
6854            |slider| slider.divisions(4),
6855        ));
6856
6857        let expected_log = vec![
6858            Offset::new(26.0, 300.0),
6859            Offset::new(26.0, 300.0),
6860            Offset::new(400.0, 300.0),
6861        ];
6862        let mut gesture = TestPointer::touch(1);
6863        tester.down(&mut gesture, slider_rect(tester).center());
6864        tester.pump();
6865        tester.pump_by(Duration::from_millis(100));
6866        assert_eq!(heard.value.get(), 0.5);
6867        assert_eq!(log.borrow().len(), 3);
6868        assert_eq!(*log.borrow(), expected_log);
6869        let at = gesture.position + Offset::new(-500.0, 0.0);
6870        tester.move_to(&mut gesture, at, true);
6871        tester.pump();
6872        tester.pump_by(Duration::from_millis(10));
6873        assert_eq!(heard.value.get(), 0.0);
6874        assert_eq!(log.borrow().len(), 5);
6875        assert!((log.borrow().last().expect("logged").dx() - 386.6).abs() <= 0.1);
6876        // With no more gesture or value changes, the thumb position should still
6877        // be redrawn in the animated position.
6878        tester.pump();
6879        tester.pump_by(Duration::from_millis(10));
6880        assert_eq!(heard.value.get(), 0.0);
6881        assert_eq!(log.borrow().len(), 7);
6882        assert!((log.borrow().last().expect("logged").dx() - 344.8).abs() <= 0.1);
6883        // Final position.
6884        tester.pump_by(Duration::from_millis(80));
6885        assert_eq!(heard.value.get(), 0.0);
6886        assert_eq!(log.borrow().len(), 8);
6887        assert!((log.borrow().last().expect("logged").dx() - 26.0).abs() <= 0.1);
6888        tester.up(&gesture);
6889    }
6890
6891    // 'Discrete Slider repaints and animates when dragged'.
6892    #[test]
6893    fn a_discrete_slider_repaints_and_animates_when_dragged() {
6894        test_widgets(discrete_slider_repaints_when_dragged);
6895    }
6896
6897    // 'Discrete Slider repaints when dragged'.
6898    #[test]
6899    fn a_discrete_slider_repaints_when_dragged() {
6900        test_widgets(discrete_slider_repaints_when_dragged);
6901    }
6902
6903    // 'Slider has correct hovered color from overlayColor property'.
6904    #[test]
6905    fn a_slider_takes_its_hovered_color_from_overlay_color() {
6906        test_widgets(|tester| {
6907            tester.set_highlight_strategy(waft_widgets::FocusHighlightStrategy::AlwaysTraditional);
6908            let theme = default_theme(tester);
6909            let value = Rc::new(Cell::new(0.5));
6910            let cyan = Colors::CYAN.get(&500).expect("a swatch shade");
6911            let build_app = |enabled: bool| {
6912                focusable_slider_app(theme.clone(), &value, enabled, move |slider| {
6913                    slider.overlay_color(<dyn WidgetStateProperty<Option<Color>>>::resolve_with(
6914                        move |states: &WidgetStates| {
6915                            if states.contains(&WidgetState::Hovered) {
6916                                return Some(cyan);
6917                            }
6918
6919                            Some(Colors::TRANSPARENT)
6920                        },
6921                    ))
6922                })
6923            };
6924            tester.pump_widget(build_app(true));
6925
6926            // Slider does not have overlay when enabled and not hovered.
6927            tester.pump_and_settle();
6928            assert!(!paints_circle(tester, slider_render(tester), cyan));
6929
6930            // Start hovering.
6931            let mut gesture = TestPointer::mouse(1, 0);
6932            tester.add_pointer(&mut gesture, Offset::ZERO);
6933            tester.move_to(&mut gesture, slider_rect(tester).center(), false);
6934
6935            // Slider has overlay when enabled and hovered.
6936            tester.pump_widget(build_app(true));
6937            tester.pump_and_settle();
6938            assert!(paints_circle(tester, slider_render(tester), cyan));
6939
6940            // Slider does not have an overlay when disabled and hovered.
6941            tester.pump_widget(build_app(false));
6942            tester.pump_and_settle();
6943            assert!(!paints_circle(tester, slider_render(tester), cyan));
6944        });
6945    }
6946
6947    // 'Slider has correct dragged color from overlayColor property'.
6948    #[test]
6949    fn a_slider_takes_its_dragged_color_from_overlay_color() {
6950        test_widgets(|tester| {
6951            tester.set_highlight_strategy(waft_widgets::FocusHighlightStrategy::AlwaysTraditional);
6952            let theme = default_theme(tester);
6953            let value = Rc::new(Cell::new(0.5));
6954            let focus_node = new_focus_node(tester);
6955            let lime = Colors::LIME.get(&500).expect("a swatch shade");
6956            let build_app = |enabled: bool| {
6957                focusable_slider_app(theme.clone(), &value, enabled, {
6958                    let focus_node = focus_node.clone();
6959                    move |slider| {
6960                        slider.focus_node(focus_node.clone()).overlay_color(
6961                            <dyn WidgetStateProperty<Option<Color>>>::resolve_with(
6962                                move |states: &WidgetStates| {
6963                                    if states.contains(&WidgetState::Dragged) {
6964                                        return Some(lime);
6965                                    }
6966
6967                                    Some(Colors::TRANSPARENT)
6968                                },
6969                            ),
6970                        )
6971                    }
6972                })
6973            };
6974            tester.pump_widget(build_app(true));
6975
6976            // Slider does not have overlay when enabled and not dragged.
6977            tester.pump_and_settle();
6978            assert!(!paints_circle(tester, slider_render(tester), lime));
6979
6980            // Start dragging.
6981            let mut drag = TestPointer::touch(1);
6982            tester.down(&mut drag, slider_rect(tester).center());
6983            tester.pump_by(waft_gestures::K_PRESS_TIMEOUT);
6984
6985            // Less than configured touch slop, more than default touch slop
6986            let at = drag.position + Offset::new(19.0, 0.0);
6987            tester.move_to(&mut drag, at, true);
6988            tester.pump();
6989            // As in the dragged-colour case above: one frame later the overlay has a radius.
6990            tester.pump_by(Duration::from_millis(16));
6991
6992            // Slider has overlay when enabled and dragged.
6993            assert!(paints_circle(tester, slider_render(tester), lime));
6994
6995            tester.up(&drag);
6996            tester.pump_and_settle();
6997
6998            // Slider without focus doesn't have overlay when enabled and dragged.
6999            assert!(!focus_node.has_focus(&tester.cell.borrow_mut()));
7000            assert!(!paints_circle(tester, slider_render(tester), lime));
7001            focus_node.dispose(&mut tester.cell.borrow_mut());
7002        });
7003    }
7004
7005    // 'In directional nav, Slider can be navigated out of by using up and down arrows'.
7006    #[test]
7007    fn in_directional_navigation_up_and_down_arrows_leave_a_slider() {
7008        test_widgets(|tester| {
7009            use waft_widgets::{
7010                Column, DirectionalFocusIntent, MediaQueryData, Shortcuts, StateSetter,
7011                TraversalDirection,
7012            };
7013            let shortcuts: ShortcutMap = [
7014                (LogicalKeyboardKey::ARROW_LEFT, TraversalDirection::Left),
7015                (LogicalKeyboardKey::ARROW_RIGHT, TraversalDirection::Right),
7016                (LogicalKeyboardKey::ARROW_DOWN, TraversalDirection::Down),
7017                (LogicalKeyboardKey::ARROW_UP, TraversalDirection::Up),
7018            ]
7019            .into_iter()
7020            .map(|(key, direction)| {
7021                (
7022                    Rc::new(SingleActivator::new(key)) as ShortcutActivatorRef,
7023                    Rc::new(DirectionalFocusIntent::new(direction)) as IntentRef,
7024                )
7025            })
7026            .collect();
7027
7028            tester.set_highlight_strategy(waft_widgets::FocusHighlightStrategy::AlwaysTraditional);
7029            let top_slider_value = Rc::new(Cell::new(0.5));
7030            let bottom_slider_value = Rc::new(Cell::new(0.5));
7031            let theme = default_theme(tester);
7032            let (top, bottom) = (
7033                Rc::clone(&top_slider_value),
7034                Rc::clone(&bottom_slider_value),
7035            );
7036            let on_changed = |value: &Rc<Cell<f64>>, set_state: &StateSetter| {
7037                let (value, set_state) = (Rc::clone(value), Rc::clone(set_state));
7038                Some(Rc::new(move |app: &mut App, new_value: f64| {
7039                    let value = Rc::clone(&value);
7040                    set_state(app, &mut |_app| value.set(new_value));
7041                }) as ValueChanged<f64>)
7042            };
7043            tester.pump_widget(material_app(
7044                theme,
7045                Shortcuts::new(
7046                    shortcuts,
7047                    Material::new().child(Center::new().child(StatefulBuilder::new(
7048                        move |_app, _context, set_state| {
7049                            MediaQuery::new(
7050                                MediaQueryData::default()
7051                                    .navigation_mode(NavigationMode::Directional),
7052                                Column::new().children(vec![
7053                                    Slider::new(top.get(), on_changed(&top, &set_state))
7054                                        .autofocus(true)
7055                                        .into_widget(),
7056                                    Slider::new(bottom.get(), on_changed(&bottom, &set_state))
7057                                        .into_widget(),
7058                                ]),
7059                            )
7060                            .into_widget()
7061                        },
7062                    ))),
7063                )
7064                .into_widget(),
7065            ));
7066            tester.pump_and_settle();
7067
7068            let values = || (top_slider_value.get(), bottom_slider_value.get());
7069
7070            // The top slider is auto-focused and can be adjusted with left and right arrow keys.
7071            send_arrow(tester, LogicalKeyboardKey::ARROW_RIGHT);
7072            // focused top Slider increased after first arrowRight; unfocused bottom Slider
7073            // unaffected by first arrowRight
7074            assert_eq!(values(), (0.55, 0.5));
7075
7076            send_arrow(tester, LogicalKeyboardKey::ARROW_LEFT);
7077            // focused top Slider decreased after first arrowLeft; unfocused bottom Slider
7078            // unaffected by first arrowLeft
7079            assert_eq!(values(), (0.5, 0.5));
7080
7081            // Pressing the down-arrow key moves focus down to the bottom slider
7082            send_arrow(tester, LogicalKeyboardKey::ARROW_DOWN);
7083            // arrowDown unfocuses top Slider, does not alter its value; arrowDown focuses
7084            // bottom Slider, does not alter its value
7085            assert_eq!(values(), (0.5, 0.5));
7086
7087            // The bottom slider is now focused and can be adjusted with left and right arrow keys.
7088            send_arrow(tester, LogicalKeyboardKey::ARROW_RIGHT);
7089            // unfocused top Slider unaffected by second arrowRight; focused bottom Slider
7090            // increased by second arrowRight
7091            assert_eq!(values(), (0.5, 0.55));
7092
7093            send_arrow(tester, LogicalKeyboardKey::ARROW_LEFT);
7094            // unfocused top Slider unaffected by second arrowLeft; focused bottom Slider
7095            // decreased by second arrowLeft
7096            assert_eq!(values(), (0.5, 0.5));
7097
7098            // Pressing the up-arrow key moves focus back up to the top slider
7099            send_arrow(tester, LogicalKeyboardKey::ARROW_UP);
7100            // arrowUp focuses top Slider, does not alter its value; arrowUp unfocuses bottom
7101            // Slider, does not alter its value
7102            assert_eq!(values(), (0.5, 0.5));
7103
7104            // The top slider is now focused again and can be adjusted with left and right arrow
7105            // keys.
7106            send_arrow(tester, LogicalKeyboardKey::ARROW_RIGHT);
7107            // focused top Slider increased after third arrowRight; unfocused bottom Slider
7108            // unaffected by third arrowRight
7109            assert_eq!(values(), (0.55, 0.5));
7110
7111            send_arrow(tester, LogicalKeyboardKey::ARROW_LEFT);
7112            // focused top Slider decreased after third arrowLeft; unfocused bottom Slider
7113            // unaffected by third arrowLeft
7114            assert_eq!(values(), (0.5, 0.5));
7115        });
7116    }
7117
7118    /// The live handles a mounted slider owns: its state's controllers, value-indicator portal
7119    /// controller and layer link, and its two render objects' curved animations.
7120    fn slider_owned_handles(tester: &WidgetTester) -> Vec<waft_foundation::HandleId> {
7121        let (render, value_indicator) = (
7122            tester.first::<RenderSlider>(),
7123            tester.first::<RenderValueIndicator>(),
7124        );
7125        let app = tester.cell.borrow();
7126        let (render, value_indicator) = (render.get(&app), value_indicator.get(&app));
7127        let state = app.get(render.state);
7128        let mut handles: Vec<waft_foundation::HandleId> = vec![
7129            state
7130                .overlay_controller
7131                .as_ref()
7132                .expect("made in init_state")
7133                .handle()
7134                .into(),
7135            state
7136                .value_indicator_controller
7137                .as_ref()
7138                .expect("made in init_state")
7139                .handle()
7140                .into(),
7141            state
7142                .enable_controller
7143                .as_ref()
7144                .expect("made in init_state")
7145                .handle()
7146                .into(),
7147            state
7148                .position_controller
7149                .as_ref()
7150                .expect("made in init_state")
7151                .handle()
7152                .into(),
7153            state
7154                .value_indicator_overlay_portal_controller
7155                .as_ref()
7156                .expect("made in init_state")
7157                .handle()
7158                .into(),
7159            state
7160                .layer_link
7161                .as_ref()
7162                .expect("made in init_state")
7163                .handle()
7164                .into(),
7165        ];
7166        let animations: [waft_foundation::HandleId; 4] = [
7167            render.overlay_animation.handle().into(),
7168            render.value_indicator_animation.handle().into(),
7169            render.enable_animation.handle().into(),
7170            value_indicator.value_indicator_animation.handle().into(),
7171        ];
7172        handles.extend(animations);
7173        handles
7174    }
7175
7176    /// Not a Dart case: what Dart's collector frees once a slider is gone, its controllers,
7177    /// portal controller, layer link and curved animations, is freed here with the last
7178    /// reference to each.
7179    #[test]
7180    fn an_unmounted_slider_leaves_none_of_its_objects_alive() {
7181        test_widgets(|tester| {
7182            let heard = Heard::starting_at(0.0);
7183            let theme = default_theme(tester);
7184            tester.pump_widget(stateful_slider_app(
7185                tester,
7186                theme,
7187                TextDirection::Ltr,
7188                &heard,
7189                plain,
7190                |slider| slider.divisions(4).label("0"),
7191            ));
7192            let handles = slider_owned_handles(tester);
7193            {
7194                let app = tester.cell.borrow();
7195                assert!(handles.iter().all(|&handle| app.contains(handle)));
7196            }
7197
7198            tester.pump_widget(SizedBox::new().into_widget());
7199            tester.pump_and_settle();
7200            let app = tester.cell.borrow();
7201            for handle in handles {
7202                assert!(!app.contains(handle), "{handle:?} is still alive");
7203            }
7204        });
7205    }
7206
7207    /// Not a Dart case: the value indicator's timer reads the render slider, which a platform
7208    /// change replaces while the state lives on; the timer keeps the disposed render object
7209    /// readable until it fires, as Dart's closure keeps it alive.
7210    #[test]
7211    fn the_value_indicator_timer_outlives_a_render_slider_replaced_by_a_platform_change() {
7212        test_widgets(|tester| {
7213            let value = Rc::new(Cell::new(0.0));
7214            let build_frame = |tester: &WidgetTester, platform: TargetPlatform| {
7215                let theme = ThemeData::builder()
7216                    .platform(platform)
7217                    .build(&tester.cell.borrow());
7218                let value = Rc::clone(&value);
7219                material_app(
7220                    theme,
7221                    StatefulBuilder::new(move |_app, _context, set_state| {
7222                        let on_changed_value = Rc::clone(&value);
7223                        Material::new()
7224                            .child(
7225                                Center::new().child(
7226                                    Slider::adaptive(
7227                                        value.get(),
7228                                        Some(Rc::new(move |app: &mut App, new_value: f64| {
7229                                            let value = Rc::clone(&on_changed_value);
7230                                            set_state(app, &mut |_app| value.set(new_value));
7231                                        })),
7232                                    )
7233                                    .divisions(4)
7234                                    .label("label")
7235                                    .show_value_indicator(ShowValueIndicator::OnDrag),
7236                                ),
7237                            )
7238                            .into_widget()
7239                    })
7240                    .into_widget(),
7241                )
7242            };
7243            tester.pump_widget(build_frame(tester, TargetPlatform::Android));
7244            tester.pump_and_settle();
7245
7246            tester.tap_at(slider_rect(tester).center(), 1);
7247            assert_eq!(value.get(), 0.5);
7248            let render = tester.first::<RenderSlider>();
7249            let state = render.get(&tester.cell.borrow()).state;
7250            tester.pump_by(Duration::from_millis(100));
7251
7252            tester.pump_widget(build_frame(tester, TargetPlatform::IOS));
7253            // The theme's 200 ms change, ending before the timer's 500 ms.
7254            tester.pump_by(Duration::from_millis(300));
7255            expect(
7256                tester,
7257                &find::by_type::<CupertinoSlider>(),
7258                finds_one_widget(),
7259            );
7260            {
7261                let app = tester.cell.borrow();
7262                assert!(app.is_disposed(render.handle()));
7263                assert!(app.get(state).interaction_timer.is_some());
7264            }
7265
7266            // Past the 500 ms the timer waits.
7267            tester.pump_by(Duration::from_millis(500));
7268            assert!(tester.cell.borrow().get(state).interaction_timer.is_none());
7269            tester.pump_and_settle();
7270            assert!(!tester.cell.borrow().contains(render.handle()));
7271        });
7272    }
7273
7274    // 'Slider removes value indicator from overlay if Slider gets disposed without value
7275    // indicator animation completing.'
7276    #[test]
7277    fn a_slider_disposed_mid_indicator_removes_its_value_indicator_from_the_overlay() {
7278        test_widgets(|tester| {
7279            use waft_widgets::{Builder, Column, Navigator, Text, WidgetBuilder};
7280
7281            use crate::elevated_button::ElevatedButton;
7282            use crate::page::MaterialPageRoute;
7283            use crate::scaffold::Scaffold;
7284
7285            const FILL_COLOR: Color = Color::new(0xf55f5f5f);
7286            let value = Rc::new(Cell::new(0.0));
7287            let theme = ThemeData::builder()
7288                .use_material3(false)
7289                .build(&tester.cell.borrow());
7290            let builder_value = Rc::clone(&value);
7291            tester.pump_widget(material_app(
7292                theme,
7293                Scaffold::new()
7294                    .body(Builder::new(move |_app, context| {
7295                        // The builder is used to pass the context from the MaterialApp widget
7296                        // to the [Navigator]. This context is required in order for the
7297                        // Navigator to work.
7298                        let on_changed_value = Rc::clone(&builder_value);
7299                        Column::new()
7300                            .children(vec![
7301                                Slider::new(
7302                                    builder_value.get(),
7303                                    Some(Rc::new(move |_app: &mut App, new_value: f64| {
7304                                        on_changed_value.set(new_value);
7305                                    })),
7306                                )
7307                                .max(100.0)
7308                                .divisions(3)
7309                                .label(format!("{}", builder_value.get().round()))
7310                                .into_widget(),
7311                                ElevatedButton::new(
7312                                    Some(Listener::new(move |app| {
7313                                        let inner: WidgetBuilder =
7314                                            Rc::new(|_app: &mut App, context: BuildContext| {
7315                                                ElevatedButton::new(
7316                                                    Some(Listener::new(move |app| {
7317                                                        Navigator::pop(app, context, None);
7318                                                    })),
7319                                                    Some(Text::new("Inner page")),
7320                                                )
7321                                                .into_widget()
7322                                            });
7323                                        let route = MaterialPageRoute::new(app, inner);
7324                                        Navigator::push_replacement(
7325                                            app,
7326                                            context,
7327                                            route.erase(),
7328                                            None,
7329                                        );
7330                                    })),
7331                                    Some(Text::new("Next")),
7332                                )
7333                                .into_widget(),
7334                            ])
7335                            .into_widget()
7336                    }))
7337                    .into_widget(),
7338            ));
7339
7340            let overlay_ops =
7341                |tester: &WidgetTester| tester.painted_ops_deep(overlay_render(tester));
7342            let top_right = slider_rect(tester).top_right() + Offset::new(-24.0, 0.0);
7343            let mut gesture = TestPointer::touch(1);
7344            tester.down(&mut gesture, top_right);
7345            // Wait for value indicator animation to finish.
7346            tester.pump_and_settle();
7347
7348            expect(tester, &find::by_type::<Slider>(), finds_one_widget());
7349            let sequence = [
7350                // Represents the raised button with text, next: its shadow, Dart's
7351                // `path(color: Colors.black)` under `debugDisableShadows`.
7352                PaintCall::shadow(None),
7353                PaintCall::Paragraph,
7354                // Represents the Slider.
7355                PaintCall::path(Some(FILL_COLOR)),
7356                PaintCall::Paragraph,
7357            ];
7358            assert_paints(&overlay_ops(tester), &sequence);
7359            assert_eq!(
7360                count_calls(&overlay_ops(tester), CanvasMethod::DrawParagraph),
7361                2
7362            );
7363
7364            let next = find::text("Next").evaluate(tester)[0];
7365            let next = tester.get_rect(next).center();
7366            tester.tap_at(next, 2);
7367            tester.pump_and_settle();
7368
7369            expect(tester, &find::by_type::<Slider>(), finds_nothing());
7370            assert!(paints(&overlay_ops(tester), &sequence[2..]).is_err());
7371            // Represents the ElevatedButton with inner Text, inner page.
7372            assert_eq!(
7373                count_calls(&overlay_ops(tester), CanvasMethod::DrawParagraph),
7374                1
7375            );
7376            expect(tester, &find::text("Inner page"), finds_one_widget());
7377
7378            // Don't stop holding the value indicator.
7379            tester.up(&gesture);
7380            tester.pump_and_settle();
7381        });
7382    }
7383    /// `slider_test.dart`, "Slider implements debugFillProperties". The colors print as the
7384    /// `Color` the port stores, not as Dart's `MaterialColor` swatch wrapper.
7385    #[test]
7386    fn a_slider_describes_its_properties() {
7387        use waft_embedder::Color;
7388        use waft_foundation::DiagnosticPropertiesBuilder;
7389
7390        let active = Color::new(0xff2196f3);
7391        let inactive = Color::new(0xff9e9e9e);
7392        let secondary = Color::new(0xff607d8b);
7393        let slider = Slider::new(50.0, None)
7394            .secondary_track_value(75.0)
7395            .max(100.0)
7396            .divisions(10)
7397            .label("Set a value")
7398            .active_color(active)
7399            .inactive_color(inactive)
7400            .secondary_active_color(secondary);
7401        let cell = waft_foundation::AppCell::new();
7402        let app = cell.borrow();
7403        let description: Vec<String> = waft_widgets::testing::describe_properties(
7404            |properties: &mut DiagnosticPropertiesBuilder| {
7405                slider.debug_fill_properties(&app, properties)
7406            },
7407        );
7408        assert_eq!(
7409            description,
7410            [
7411                "value: 50.0".to_string(),
7412                "secondaryTrackValue: 75.0".to_string(),
7413                "disabled".to_string(),
7414                "min: 0.0".to_string(),
7415                "max: 100.0".to_string(),
7416                "divisions: 10".to_string(),
7417                "label: \"Set a value\"".to_string(),
7418                format!("activeColor: {active}"),
7419                format!("inactiveColor: {inactive}"),
7420                format!("secondaryActiveColor: {secondary}"),
7421            ]
7422        );
7423    }
7424}