Skip to main content

waft_material/
range_slider.rs

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