Skip to main content

waft_material/
tooltip.rs

1//! Flutter counterpart: material_ui's `tooltip.dart`.
2
3use std::fmt;
4use std::rc::Rc;
5use std::time::Duration;
6
7use waft_embedder::SignedDuration;
8use waft_embedder::{Brightness, Radius, TargetPlatform, TextAlign};
9use waft_foundation::{
10    App, DiagnosticPropertiesBuilder, DiagnosticsProperty, DoubleProperty, FlagProperty, Handle,
11    Ref, StringProperty,
12};
13use waft_painting::{
14    BorderRadius, BoxDecoration, DecorationRef, EdgeInsets, EdgeInsetsGeometry, InlineSpanRef,
15    TextSpan, TextStyle, position_dependent_box,
16};
17use waft_rendering::BoxConstraints;
18use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
19use waft_services::{MouseCursor, MouseCursorRef};
20use waft_widgets::{
21    BuildContext, Center, ConstrainedBox, Container, DefaultTextStyle, FadeTransition, GlobalKey,
22    IntoWidget, KeyRef, MouseRegion, RawTooltip, RawTooltipState, SingleTickerProviderStateMixin,
23    SingleTickerProviderStateMixinData, SizedBox, State, StateData, StatefulWidget,
24    StatelessWidget, Text, TooltipPositionContext, TooltipPositionDelegate, TooltipTriggerMode,
25    TooltipTriggeredCallback, WidgetRef,
26};
27
28use crate::colors::Colors;
29use crate::theme::Theme;
30use crate::tooltip_theme::{TooltipTheme, TooltipThemeData};
31use crate::tooltip_visibility::TooltipVisibility;
32
33/// A Material Design tooltip.
34///
35/// Tooltips provide text labels which help explain the function of a button or
36/// other user interface action. Wrap the button in a [`Tooltip`] widget and provide
37/// a message which will be shown when the widget is long pressed.
38///
39/// Many widgets, such as `IconButton`, `FloatingActionButton`, and
40/// `PopupMenuButton` have a `tooltip` property that, when non-null, causes the
41/// widget to include a [`Tooltip`] in its build.
42///
43/// Tooltips improve the accessibility of visual widgets by proving a textual
44/// representation of the widget, which, for example, can be vocalized by a
45/// screen reader.
46///
47/// This tooltip will default to showing above its child instead of below when its ambient
48/// [`TooltipThemeData::prefer_below`] is false. Setting that piece of theme data is
49/// recommended to avoid having a finger or cursor hide the tooltip. For other ways to set
50/// that piece of theme data see:
51///
52/// * `Theme::data`, `ThemeData::tooltip_theme`
53/// * [`TooltipTheme::data`]
54///
55/// or it can be set directly on each tooltip with [`Tooltip::prefer_below`].
56///
57/// A tooltip can be shown manually with [`TooltipTriggerMode::Manual`] by calling the
58/// [`TooltipState::ensure_tooltip_visible`] function.
59///
60/// See also:
61///
62///  * <https://material.io/design/components/tooltips.html>
63///  * [`TooltipTheme`] or `ThemeData::tooltip_theme`
64///  * [`TooltipVisibility`]
65pub struct Tooltip {
66    pub key: Option<KeyRef>,
67
68    /// The text to display in the tooltip.
69    ///
70    /// Only one of [`message`](Self::message) and [`rich_message`](Self::rich_message) may be
71    /// non-null.
72    pub message: Option<String>,
73
74    /// The rich text to display in the tooltip.
75    ///
76    /// Only one of [`message`](Self::message) and [`rich_message`](Self::rich_message) may be
77    /// non-null.
78    pub rich_message: Option<InlineSpanRef>,
79
80    /// The minimum height of the [`Tooltip`]'s message.
81    #[deprecated(
82        note = "Use Tooltip.constraints instead. This feature was deprecated after v3.30.0-0.1.pre."
83    )]
84    pub height: Option<f64>,
85
86    /// Constrains the size of the [`Tooltip`]'s message.
87    ///
88    /// If null, then the [`TooltipThemeData::constraints`] of the ambient
89    /// `ThemeData::tooltip_theme` will be used. If that is also null, then a default value
90    /// will be picked based on the current platform. For desktop platforms, the default value
91    /// is `BoxConstraints(minHeight: 24.0)`, while for mobile platforms the default value is
92    /// `BoxConstraints(minHeight: 32.0)`.
93    pub constraints: Option<BoxConstraints>,
94
95    /// The amount of space by which to inset the [`Tooltip`]'s message.
96    ///
97    /// On mobile, defaults to 16.0 logical pixels horizontally and 4.0 vertically.
98    /// On desktop, defaults to 8.0 logical pixels horizontally and 4.0 vertically.
99    pub padding: Option<EdgeInsetsGeometry>,
100
101    /// The empty space that surrounds the tooltip.
102    ///
103    /// Defines the tooltip's outer `Container::margin`. By default, a
104    /// long tooltip will span the width of its window. If long enough,
105    /// a tooltip might also span the window's height. This property allows
106    /// one to define how much space the tooltip must be inset from the edges
107    /// of their display window.
108    ///
109    /// If this property is null, then [`TooltipThemeData::margin`] is used.
110    /// If [`TooltipThemeData::margin`] is also null, the default margin is
111    /// 0.0 logical pixels on all sides.
112    ///
113    /// See also:
114    ///
115    ///  * [`constraints`](Self::constraints), which allow setting an explicit size for the
116    ///    tooltip.
117    pub margin: Option<EdgeInsetsGeometry>,
118
119    /// The vertical gap between the widget and the displayed tooltip.
120    ///
121    /// When [`prefer_below`](Self::prefer_below) is set to true and tooltips have sufficient
122    /// space to display themselves, this property defines how much vertical space
123    /// tooltips will position themselves under their corresponding widgets.
124    /// Otherwise, tooltips will position themselves above their corresponding
125    /// widgets with the given offset.
126    pub vertical_offset: Option<f64>,
127
128    /// Whether the tooltip defaults to being displayed below the widget.
129    ///
130    /// If there is insufficient space to display the tooltip in
131    /// the preferred direction, the tooltip will be displayed in the opposite
132    /// direction.
133    ///
134    /// If this property is null, then [`TooltipThemeData::prefer_below`] is used.
135    /// If that is also null, the default value is true.
136    ///
137    /// Applying [`TooltipThemeData::prefer_below`]: `false` for the entire app
138    /// is recommended to avoid having a finger or cursor hide a tooltip.
139    pub prefer_below: Option<bool>,
140
141    /// Whether the tooltip's [`message`](Self::message) or
142    /// [`rich_message`](Self::rich_message) should be excluded from the semantics tree.
143    ///
144    /// Defaults to false. A tooltip will add a `Semantics` label that is set to
145    /// [`Tooltip::message`] if non-null, or the plain text value of
146    /// [`Tooltip::rich_message`] otherwise. Set this property to true if the app is
147    /// going to provide its own custom semantics label.
148    pub exclude_from_semantics: Option<bool>,
149
150    /// The widget below this widget in the tree.
151    pub child: Option<WidgetRef>,
152
153    /// Specifies the tooltip's shape and background color.
154    ///
155    /// The tooltip shape defaults to a rounded rectangle with a border radius of
156    /// 4.0. Tooltips will also default to an opacity of 90% and with the color
157    /// `Colors::GREY[700]` if `ThemeData::brightness` is [`Brightness::Light`], and
158    /// `Colors::WHITE` if it is [`Brightness::Dark`].
159    pub decoration: Option<DecorationRef>,
160
161    /// The style to use for the message of the tooltip.
162    ///
163    /// If null, the message's [`TextStyle`] will be determined based on
164    /// `ThemeData`. If `ThemeData::brightness` is set to [`Brightness::Dark`],
165    /// `TextTheme::body_medium` of `ThemeData::text_theme` will be used with
166    /// `Colors::WHITE`. Otherwise, if `ThemeData::brightness` is set to
167    /// [`Brightness::Light`], `TextTheme::body_medium` of `ThemeData::text_theme` will be
168    /// used with `Colors::BLACK`.
169    pub text_style: Option<TextStyle>,
170
171    /// How the message of the tooltip is aligned horizontally.
172    ///
173    /// If this property is null, then [`TooltipThemeData::text_align`] is used.
174    /// If [`TooltipThemeData::text_align`] is also null, the default value is
175    /// [`TextAlign::Start`].
176    pub text_align: Option<TextAlign>,
177
178    /// The length of time that a pointer must hover over a tooltip's widget
179    /// before the tooltip will be shown.
180    ///
181    /// Defaults to 0 milliseconds (the tooltip is shown immediately upon hover).
182    pub wait_duration: Option<Duration>,
183
184    /// The length of time that the tooltip will be shown after a long press is
185    /// released (if trigger_mode is [`TooltipTriggerMode::LongPress`]) or a tap is
186    /// released (if trigger_mode is [`TooltipTriggerMode::Tap`]).
187    ///
188    /// This property does not affect mouse pointer devices.
189    ///
190    /// Defaults to 1.5 seconds (the tooltip is shown 1.5 seconds after a tap or
191    /// long press is released).
192    ///
193    /// See also:
194    ///
195    ///  * [`exit_duration`](Self::exit_duration), which allows configuring the time until a
196    ///    pointer disappears when hovering.
197    pub show_duration: Option<Duration>,
198
199    /// The length of time that a pointer must have stopped hovering over a
200    /// tooltip's widget before the tooltip will be hidden.
201    ///
202    /// Defaults to 100 milliseconds.
203    ///
204    /// See also:
205    ///
206    ///  * [`show_duration`](Self::show_duration), which allows configuring the length of time
207    ///    that a tooltip will be visible after touch events are released.
208    pub exit_duration: Option<Duration>,
209
210    /// Whether the tooltip can be dismissed by tap.
211    ///
212    /// The default value is true.
213    pub enable_tap_to_dismiss: bool,
214
215    /// The [`TooltipTriggerMode`] that will show the tooltip.
216    ///
217    /// This property does not affect mouse devices. Setting
218    /// [`trigger_mode`](Self::trigger_mode) to [`TooltipTriggerMode::Manual`] will not prevent
219    /// the tooltip from showing when the mouse cursor hovers over it.
220    ///
221    /// If this property is null, then [`TooltipThemeData::trigger_mode`] is used.
222    /// If [`TooltipThemeData::trigger_mode`] is also null, the default mode is
223    /// [`TooltipTriggerMode::LongPress`].
224    pub trigger_mode: Option<TooltipTriggerMode>,
225
226    /// Whether the tooltip should provide acoustic and/or haptic feedback.
227    ///
228    /// For example, on Android a tap will produce a clicking sound and a
229    /// long-press will produce a short vibration, when feedback is enabled.
230    ///
231    /// When null, the default value is true.
232    ///
233    /// See also:
234    ///
235    ///  * `Feedback`, for providing platform-specific feedback to certain
236    ///    actions.
237    pub enable_feedback: Option<bool>,
238
239    /// Called when the [`Tooltip`] is triggered programmatically, on tap, or on
240    /// long press.
241    ///
242    /// The tooltip is triggered after a tap when [`trigger_mode`](Self::trigger_mode) is
243    /// [`TooltipTriggerMode::Tap`] or after a long press when
244    /// [`trigger_mode`](Self::trigger_mode) is [`TooltipTriggerMode::LongPress`].
245    ///
246    /// Hovering over the tooltip with a mouse pointer does not trigger this
247    /// callback.
248    pub on_triggered: Option<TooltipTriggeredCallback>,
249
250    /// The cursor for a mouse pointer when it enters or is hovering over the
251    /// widget.
252    ///
253    /// If this property is null, `MouseCursor::defer` will be used.
254    pub mouse_cursor: Option<MouseCursorRef>,
255
256    /// Whether this tooltip should be invisible to hit testing.
257    ///
258    /// If no value is passed, pointer events are ignored unless the tooltip has a
259    /// [`rich_message`](Self::rich_message) instead of a [`message`](Self::message).
260    ///
261    /// See also:
262    ///
263    /// * `IgnorePointer`, for more information about how pointer events are
264    ///   handled or ignored.
265    pub ignore_pointer: Option<bool>,
266
267    /// A custom position delegate function for computing where the tooltip should
268    /// be positioned.
269    ///
270    /// If provided, this function will be called with a [`TooltipPositionContext`]
271    /// containing all the necessary information for positioning the tooltip. The
272    /// function should return an [`Offset`](waft_embedder::Offset) indicating where to place the tooltip
273    /// in the closest `Overlay`.
274    ///
275    /// If null, defaults to positioning the tooltip center-aligned and below the
276    /// target using [`position_dependent_box`].
277    pub position_delegate: Option<TooltipPositionDelegate>,
278}
279
280#[allow(deprecated)]
281impl Default for Tooltip {
282    fn default() -> Tooltip {
283        Tooltip {
284            key: None,
285            message: None,
286            rich_message: None,
287            height: None,
288            constraints: None,
289            padding: None,
290            margin: None,
291            vertical_offset: None,
292            prefer_below: None,
293            exclude_from_semantics: None,
294            child: None,
295            decoration: None,
296            text_style: None,
297            text_align: None,
298            wait_duration: None,
299            show_duration: None,
300            exit_duration: None,
301            enable_tap_to_dismiss: true,
302            trigger_mode: None,
303            enable_feedback: None,
304            on_triggered: None,
305            mouse_cursor: None,
306            ignore_pointer: None,
307            position_delegate: None,
308        }
309    }
310}
311
312#[allow(deprecated)]
313impl Tooltip {
314    /// Creates a tooltip.
315    ///
316    /// By default, tooltips should adhere to the
317    /// [Material specification](https://material.io/design/components/tooltips.html#spec).
318    /// If the optional constructor parameters are not defined, the values
319    /// provided by [`TooltipTheme::of`] will be used if a [`TooltipTheme`] is present
320    /// or specified in `ThemeData`.
321    ///
322    /// All parameters that are defined in the constructor will
323    /// override the default values _and_ the values in [`TooltipTheme::of`].
324    ///
325    /// Exactly one of [`message`](Self::message) and [`rich_message`](Self::rich_message) must
326    /// be given; the tooltip's state checks it when it builds.
327    pub fn new() -> Tooltip {
328        Tooltip::default()
329    }
330
331    /// Dart `Tooltip(key:)`.
332    pub fn key(mut self, key: KeyRef) -> Tooltip {
333        self.key = Some(key);
334        self
335    }
336
337    /// Dart `Tooltip(message:)`.
338    pub fn message(mut self, message: impl Into<String>) -> Tooltip {
339        debug_assert!(
340            self.rich_message.is_none(),
341            "Either `message` or `richMessage` must be specified"
342        );
343        self.message = Some(message.into());
344        self
345    }
346
347    /// Dart `Tooltip(richMessage:)`.
348    pub fn rich_message(mut self, rich_message: InlineSpanRef) -> Tooltip {
349        debug_assert!(
350            self.message.is_none(),
351            "Either `message` or `richMessage` must be specified"
352        );
353        self.rich_message = Some(rich_message);
354        self
355    }
356
357    /// Dart `Tooltip(height:)`.
358    #[deprecated(
359        note = "Use Tooltip.constraints instead. This feature was deprecated after v3.30.0-0.1.pre."
360    )]
361    pub fn height(mut self, height: f64) -> Tooltip {
362        debug_assert!(
363            self.constraints.is_none(),
364            "Only one of `height` and `constraints` may be specified."
365        );
366        self.height = Some(height);
367        self
368    }
369
370    /// Dart `Tooltip(constraints:)`.
371    pub fn constraints(mut self, constraints: BoxConstraints) -> Tooltip {
372        debug_assert!(
373            self.height.is_none(),
374            "Only one of `height` and `constraints` may be specified."
375        );
376        self.constraints = Some(constraints);
377        self
378    }
379
380    /// Dart `Tooltip(padding:)`.
381    pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> Tooltip {
382        let padding = padding.into();
383        self.padding = Some(padding);
384        self
385    }
386
387    /// Dart `Tooltip(margin:)`.
388    pub fn margin(mut self, margin: impl Into<EdgeInsetsGeometry>) -> Tooltip {
389        let margin = margin.into();
390        self.margin = Some(margin);
391        self
392    }
393
394    /// Dart `Tooltip(verticalOffset:)`.
395    pub fn vertical_offset(mut self, vertical_offset: f64) -> Tooltip {
396        self.vertical_offset = Some(vertical_offset);
397        self
398    }
399
400    /// Dart `Tooltip(preferBelow:)`.
401    pub fn prefer_below(mut self, prefer_below: bool) -> Tooltip {
402        self.prefer_below = Some(prefer_below);
403        self
404    }
405
406    /// Dart `Tooltip(excludeFromSemantics:)`.
407    pub fn exclude_from_semantics(mut self, exclude_from_semantics: bool) -> Tooltip {
408        self.exclude_from_semantics = Some(exclude_from_semantics);
409        self
410    }
411
412    /// Dart `Tooltip(decoration:)`.
413    pub fn decoration(mut self, decoration: impl Into<DecorationRef>) -> Tooltip {
414        self.decoration = Some(decoration.into());
415        self
416    }
417
418    /// Dart `Tooltip(textStyle:)`.
419    pub fn text_style(mut self, text_style: TextStyle) -> Tooltip {
420        self.text_style = Some(text_style);
421        self
422    }
423
424    /// Dart `Tooltip(textAlign:)`.
425    pub fn text_align(mut self, text_align: TextAlign) -> Tooltip {
426        self.text_align = Some(text_align);
427        self
428    }
429
430    /// Dart `Tooltip(waitDuration:)`.
431    pub fn wait_duration(mut self, wait_duration: Duration) -> Tooltip {
432        self.wait_duration = Some(wait_duration);
433        self
434    }
435
436    /// Dart `Tooltip(showDuration:)`.
437    pub fn show_duration(mut self, show_duration: Duration) -> Tooltip {
438        self.show_duration = Some(show_duration);
439        self
440    }
441
442    /// Dart `Tooltip(exitDuration:)`.
443    pub fn exit_duration(mut self, exit_duration: Duration) -> Tooltip {
444        self.exit_duration = Some(exit_duration);
445        self
446    }
447
448    /// Dart `Tooltip(enableTapToDismiss:)`.
449    pub fn enable_tap_to_dismiss(mut self, enable_tap_to_dismiss: bool) -> Tooltip {
450        self.enable_tap_to_dismiss = enable_tap_to_dismiss;
451        self
452    }
453
454    /// Dart `Tooltip(triggerMode:)`.
455    pub fn trigger_mode(mut self, trigger_mode: TooltipTriggerMode) -> Tooltip {
456        self.trigger_mode = Some(trigger_mode);
457        self
458    }
459
460    /// Dart `Tooltip(enableFeedback:)`.
461    pub fn enable_feedback(mut self, enable_feedback: bool) -> Tooltip {
462        self.enable_feedback = Some(enable_feedback);
463        self
464    }
465
466    /// Dart `Tooltip(onTriggered:)`.
467    pub fn on_triggered(mut self, on_triggered: TooltipTriggeredCallback) -> Tooltip {
468        self.on_triggered = Some(on_triggered);
469        self
470    }
471
472    /// Dart `Tooltip(mouseCursor:)`.
473    pub fn mouse_cursor(mut self, mouse_cursor: MouseCursorRef) -> Tooltip {
474        self.mouse_cursor = Some(mouse_cursor);
475        self
476    }
477
478    /// Dart `Tooltip(ignorePointer:)`.
479    pub fn ignore_pointer(mut self, ignore_pointer: bool) -> Tooltip {
480        self.ignore_pointer = Some(ignore_pointer);
481        self
482    }
483
484    /// Dart `Tooltip(positionDelegate:)`.
485    pub fn position_delegate(mut self, position_delegate: TooltipPositionDelegate) -> Tooltip {
486        self.position_delegate = Some(position_delegate);
487        self
488    }
489
490    /// Dart `Tooltip(child:)`.
491    #[cfg_attr(debug_assertions, track_caller)]
492    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> Tooltip {
493        self.child = Some(child.into_widget());
494        self
495    }
496
497    /// Dismiss all of the tooltips that are currently shown on the screen,
498    /// including those with mouse cursors currently hovering over them.
499    ///
500    /// This method returns true if it successfully dismisses at least one tooltip
501    /// and returns false if there is no tooltip currently displayed.
502    pub fn dismiss_all_tool_tips(app: &mut App) -> bool {
503        RawTooltip::dismiss_all_tool_tips(app)
504    }
505}
506
507#[allow(deprecated)]
508impl fmt::Debug for Tooltip {
509    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
510        f.debug_struct("Tooltip")
511            .field("key", &self.key)
512            .field("message", &self.message)
513            .field(
514                "richMessage",
515                &self
516                    .rich_message
517                    .as_ref()
518                    .map(|rich_message| rich_message.to_plain_text(true, true)),
519            )
520            .field("height", &self.height)
521            .field("constraints", &self.constraints)
522            .field("padding", &self.padding)
523            .field("margin", &self.margin)
524            .field("vertical offset", &self.vertical_offset)
525            .field("position", &self.prefer_below)
526            .field("semantics", &self.exclude_from_semantics)
527            .field("wait duration", &self.wait_duration)
528            .field("show duration", &self.show_duration)
529            .field("exit duration", &self.exit_duration)
530            .field("triggerMode", &self.trigger_mode)
531            .field("enableFeedback", &self.enable_feedback)
532            .field("textAlign", &self.text_align)
533            .field("positionDelegate", &self.position_delegate.is_some())
534            .finish_non_exhaustive()
535    }
536}
537
538impl StatefulWidget for Tooltip {
539    type State = TooltipState;
540
541    fn key(&self) -> Option<&KeyRef> {
542        self.key.as_ref()
543    }
544
545    #[allow(deprecated)]
546    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
547        // Dart's `positionDelegate` line waits for that function type's `Display`.
548        properties.add({
549            let property = StringProperty::new("message", self.message.clone())
550                .with_show_name(self.message.is_none());
551            if self.message.is_none() {
552                property.default_value(None)
553            } else {
554                property
555            }
556        });
557        let rich_message = self
558            .rich_message
559            .as_ref()
560            .map(|span| span.to_plain_text(true, true));
561        properties.add({
562            let property = StringProperty::new("richMessage", rich_message)
563                .with_show_name(self.rich_message.is_none());
564            if self.rich_message.is_none() {
565                property.default_value(None)
566            } else {
567                property
568            }
569        });
570        properties.add(DoubleProperty::new("height", self.height).default_value(None));
571        properties.add(
572            DiagnosticsProperty::<BoxConstraints>::new("constraints", self.constraints)
573                .default_value(None),
574        );
575        properties.add(
576            DiagnosticsProperty::<EdgeInsetsGeometry>::new("padding", self.padding)
577                .default_value(None),
578        );
579        properties.add(
580            DiagnosticsProperty::<EdgeInsetsGeometry>::new("margin", self.margin)
581                .default_value(None),
582        );
583        properties
584            .add(DoubleProperty::new("vertical offset", self.vertical_offset).default_value(None));
585        properties.add(
586            FlagProperty::new("position", self.prefer_below)
587                .if_true("below")
588                .if_false("above")
589                .with_show_name(true)
590                .default_value(None),
591        );
592        properties.add(
593            FlagProperty::new("semantics", self.exclude_from_semantics)
594                .if_true("excluded")
595                .with_show_name(true)
596                .default_value(None),
597        );
598        properties.add(
599            DiagnosticsProperty::<SignedDuration>::new(
600                "wait duration",
601                self.wait_duration.map(SignedDuration::from),
602            )
603            .default_value(None),
604        );
605        properties.add(
606            DiagnosticsProperty::<SignedDuration>::new(
607                "show duration",
608                self.show_duration.map(SignedDuration::from),
609            )
610            .default_value(None),
611        );
612        properties.add(
613            DiagnosticsProperty::<SignedDuration>::new(
614                "exit duration",
615                self.exit_duration.map(SignedDuration::from),
616            )
617            .default_value(None),
618        );
619        properties.add(
620            DiagnosticsProperty::<waft_foundation::DartEnum<TooltipTriggerMode>>::new(
621                "triggerMode",
622                self.trigger_mode.map(waft_foundation::DartEnum),
623            )
624            .default_value(None),
625        );
626        properties.add(
627            FlagProperty::new("enableFeedback", self.enable_feedback)
628                .if_true("true")
629                .with_show_name(true)
630                .default_value(None),
631        );
632        properties.add(
633            DiagnosticsProperty::<waft_foundation::DartEnum<TextAlign>>::new(
634                "textAlign",
635                self.text_align.map(waft_foundation::DartEnum),
636            )
637            .default_value(None),
638        );
639    }
640
641    fn create_state(&self) -> TooltipState {
642        TooltipState {
643            state: StateData::new(),
644            single_ticker_provider: SingleTickerProviderStateMixinData::new(),
645            tooltip_key: GlobalKey::new(),
646            visible: true,
647            tooltip_theme: TooltipThemeData::new(),
648        }
649    }
650}
651
652/// Contains the state for a [`Tooltip`].
653///
654/// This class can be used to programmatically show the Tooltip, see the
655/// [`ensure_tooltip_visible`](Self::ensure_tooltip_visible) method.
656pub struct TooltipState {
657    state: StateData<Tooltip>,
658    single_ticker_provider: SingleTickerProviderStateMixinData,
659
660    /// Dart's `GlobalKey<RawTooltipState>`.
661    tooltip_key: GlobalKey,
662
663    // From InheritedWidgets; Dart's `late` fields, set by `did_change_dependencies` before the
664    // first build.
665    visible: bool,
666    tooltip_theme: TooltipThemeData,
667}
668
669impl TooltipState {
670    const DEFAULT_VERTICAL_OFFSET: f64 = 24.0;
671    const DEFAULT_PREFER_BELOW: bool = true;
672    const DEFAULT_MARGIN: EdgeInsetsGeometry = EdgeInsetsGeometry::ZERO;
673    const DEFAULT_SHOW_DURATION: Duration = Duration::from_millis(1500);
674    const DEFAULT_EXIT_DURATION: Duration = Duration::from_millis(100);
675    const DEFAULT_WAIT_DURATION: Duration = Duration::ZERO;
676    const DEFAULT_EXCLUDE_FROM_SEMANTICS: bool = false;
677    const DEFAULT_TRIGGER_MODE: TooltipTriggerMode = TooltipTriggerMode::LongPress;
678    const DEFAULT_ENABLE_FEEDBACK: bool = true;
679    const DEFAULT_TEXT_ALIGN: TextAlign = TextAlign::Start;
680
681    /// The plain text message for this tooltip.
682    ///
683    /// This value will either come from [`Tooltip::message`] or
684    /// [`Tooltip::rich_message`].
685    fn tooltip_message(self: Handle<Self>, app: &App) -> String {
686        let widget = self.widget(app);
687        match &widget.message {
688            Some(message) => message.clone(),
689            None => widget
690                .rich_message
691                .as_ref()
692                .expect("a tooltip has a message or a rich message")
693                .to_plain_text(true, true),
694        }
695    }
696
697    /// Shows the tooltip if it is not already visible.
698    ///
699    /// After made visible by this method, the tooltip does not automatically
700    /// dismiss after `wait_duration` until the user dismisses/re-triggers it, or
701    /// [`Tooltip::dismiss_all_tool_tips`] is called.
702    ///
703    /// Returns `false` when the tooltip shouldn't be shown or when the tooltip
704    /// was already visible.
705    pub fn ensure_tooltip_visible(self: Handle<Self>, app: &mut App) -> bool {
706        let tooltip_key = app.get(self).tooltip_key.clone();
707        tooltip_key
708            .current_state::<RawTooltipState>(app)
709            .is_some_and(|raw_tooltip| raw_tooltip.ensure_tooltip_visible(app))
710    }
711
712    // https://material.io/components/tooltips#specs
713    fn get_default_tooltip_height(self: Handle<Self>, app: &mut App, context: BuildContext) -> f64 {
714        match Theme::of(app, context).platform {
715            TargetPlatform::MacOS | TargetPlatform::Linux | TargetPlatform::Windows => 24.0,
716            TargetPlatform::Android | TargetPlatform::Fuchsia | TargetPlatform::IOS => 32.0,
717        }
718    }
719
720    fn get_default_padding(self: Handle<Self>, app: &mut App, context: BuildContext) -> EdgeInsets {
721        match Theme::of(app, context).platform {
722            TargetPlatform::MacOS | TargetPlatform::Linux | TargetPlatform::Windows => {
723                EdgeInsets::symmetric(4.0, 8.0)
724            }
725            TargetPlatform::Android | TargetPlatform::Fuchsia | TargetPlatform::IOS => {
726                EdgeInsets::symmetric(4.0, 16.0)
727            }
728        }
729    }
730
731    fn get_default_font_size(platform: TargetPlatform) -> f64 {
732        match platform {
733            TargetPlatform::MacOS | TargetPlatform::Linux | TargetPlatform::Windows => 12.0,
734            TargetPlatform::Android | TargetPlatform::Fuchsia | TargetPlatform::IOS => 14.0,
735        }
736    }
737
738    /// Dart's `_getDefaultPositionDelegate`, a tear-off that reads `widget` and
739    /// `_tooltipTheme` when it is called; here a closure holding what it reads, built anew on
740    /// every build, the only point either can change.
741    fn get_default_position_delegate(self: Handle<Self>, app: &App) -> TooltipPositionDelegate {
742        let widget = self.widget(app);
743        let tooltip_theme = &app.get(self).tooltip_theme;
744        let effective_vertical_offset = widget
745            .vertical_offset
746            .or(tooltip_theme.vertical_offset)
747            .unwrap_or(Self::DEFAULT_VERTICAL_OFFSET);
748        let effective_prefer_below = widget
749            .prefer_below
750            .or(tooltip_theme.prefer_below)
751            .unwrap_or(Self::DEFAULT_PREFER_BELOW);
752        let position_delegate = widget.position_delegate.clone();
753        Rc::new(move |context: TooltipPositionContext| {
754            let resolved_context = TooltipPositionContext::new(
755                context.target,
756                context.target_size,
757                context.tooltip_size,
758                effective_vertical_offset,
759            )
760            .overlay_size(context.overlay_size)
761            .prefer_below(effective_prefer_below);
762            match &position_delegate {
763                Some(position_delegate) => position_delegate(resolved_context),
764                None => position_dependent_box(
765                    context.overlay_size,
766                    context.tooltip_size,
767                    context.target,
768                    effective_prefer_below,
769                    effective_vertical_offset,
770                    10.0,
771                ),
772            }
773        })
774    }
775}
776
777impl SingleTickerProviderStateMixin for TooltipState {
778    fn single_ticker_provider_data(
779        self: Handle<Self>,
780        app: &App,
781    ) -> &SingleTickerProviderStateMixinData {
782        &app.get(self).single_ticker_provider
783    }
784
785    fn single_ticker_provider_data_mut(
786        self: Handle<Self>,
787        app: &mut App,
788    ) -> &mut SingleTickerProviderStateMixinData {
789        &mut app.get_mut(self).single_ticker_provider
790    }
791}
792
793/// Dart's `TooltipState with SingleTickerProviderStateMixin`.
794impl TickerProviderObject for TooltipState {
795    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
796        SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
797    }
798}
799
800impl State for TooltipState {
801    type Widget = Tooltip;
802    waft_widgets::state_accessors!();
803
804    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
805        let context = self.context(app);
806        let visible = TooltipVisibility::of(app, context);
807        let tooltip_theme = TooltipTheme::of(app, context);
808        let this = app.get_mut(self);
809        this.visible = visible;
810        this.tooltip_theme = tooltip_theme;
811    }
812
813    fn activate(self: Handle<Self>, app: &mut App) {
814        SingleTickerProviderStateMixin::activate(self, app);
815    }
816
817    fn dispose(self: Handle<Self>, app: &mut App) {
818        SingleTickerProviderStateMixin::dispose(self, app);
819    }
820
821    #[allow(deprecated)]
822    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
823        // If no message is provided, there is no need to create a tooltip overlay
824        // to show an empty container. In this case, just return the wrapped child
825        // as is, or SizedBox.shrink if a child is not provided.
826        if self.tooltip_message(app).is_empty() {
827            return self
828                .widget(app)
829                .child
830                .clone()
831                .unwrap_or_else(|| SizedBox::shrink().into_widget());
832        }
833        let theme = Theme::of(app, context);
834        let body_medium = theme
835            .text_theme
836            .body_medium
837            .as_ref()
838            .expect("a theme's text theme has a body medium style");
839        let font_size = Self::get_default_font_size(theme.platform);
840        let (default_text_style, default_decoration) = match theme.brightness() {
841            Brightness::Dark => (
842                body_medium
843                    .copy_with()
844                    .color(Colors::BLACK)
845                    .font_size(font_size),
846                BoxDecoration::new()
847                    .color(Colors::WHITE.with_opacity(0.9))
848                    .border_radius(BorderRadius::all(Radius::circular(4.0))),
849            ),
850            Brightness::Light => (
851                body_medium
852                    .copy_with()
853                    .color(Colors::WHITE)
854                    .font_size(font_size),
855                BoxDecoration::new()
856                    .color(
857                        Colors::GREY
858                            .get(&700)
859                            .expect("grey has a 700 shade")
860                            .with_opacity(0.9),
861                    )
862                    .border_radius(BorderRadius::all(Radius::circular(4.0))),
863            ),
864        };
865        let default_tooltip_height = self.get_default_tooltip_height(app, context);
866        let default_padding = self.get_default_padding(app, context);
867        let widget = self.widget(app);
868        let tooltip_theme = &app.get(self).tooltip_theme;
869        let default_constraints = BoxConstraints::new().min_height(
870            widget
871                .height
872                .or(tooltip_theme.height)
873                .unwrap_or(default_tooltip_height),
874        );
875
876        let tooltip_box = TooltipBox {
877            constraints: widget
878                .constraints
879                .or(tooltip_theme.constraints)
880                .unwrap_or(default_constraints),
881            text_style: widget
882                .text_style
883                .clone()
884                .or_else(|| tooltip_theme.text_style.clone())
885                .unwrap_or(default_text_style),
886            text_align: widget
887                .text_align
888                .or(tooltip_theme.text_align)
889                .unwrap_or(Self::DEFAULT_TEXT_ALIGN),
890            decoration: Some(
891                widget
892                    .decoration
893                    .as_ref()
894                    .or(tooltip_theme.decoration.as_ref())
895                    .cloned()
896                    .unwrap_or_else(|| DecorationRef::new(default_decoration)),
897            ),
898            padding: Some(
899                widget
900                    .padding
901                    .or(tooltip_theme.padding)
902                    .unwrap_or(EdgeInsetsGeometry::Insets(default_padding)),
903            ),
904            margin: Some(
905                widget
906                    .margin
907                    .or(tooltip_theme.margin)
908                    .unwrap_or(Self::DEFAULT_MARGIN),
909            ),
910            rich_message: widget.rich_message.clone().unwrap_or_else(|| {
911                let mut span = TextSpan::new();
912                span.text = widget.message.clone();
913                Rc::new(span)
914            }),
915        }
916        .into_widget();
917
918        let mut effective_child = MouseRegion::new()
919            .cursor(
920                widget
921                    .mouse_cursor
922                    .clone()
923                    .unwrap_or_else(<dyn MouseCursor>::defer),
924            )
925            .child(
926                widget
927                    .child
928                    .clone()
929                    .unwrap_or_else(|| SizedBox::shrink().into_widget()),
930            )
931            .into_widget();
932
933        let exclude_from_semantics = widget
934            .exclude_from_semantics
935            .or(tooltip_theme.exclude_from_semantics)
936            .unwrap_or(Self::DEFAULT_EXCLUDE_FROM_SEMANTICS);
937
938        if app.get(self).visible {
939            let widget = self.widget(app);
940            let tooltip_theme = &app.get(self).tooltip_theme;
941            let mut raw_tooltip = RawTooltip::new(
942                if exclude_from_semantics {
943                    None
944                } else {
945                    Some(self.tooltip_message(app))
946                },
947                move |_app, _context, animation| {
948                    FadeTransition::new(animation)
949                        .child(tooltip_box.clone())
950                        .into_widget()
951                },
952                effective_child,
953            )
954            .key(app.get(self).tooltip_key.clone().into())
955            .touch_delay(
956                widget
957                    .show_duration
958                    .or(tooltip_theme.show_duration)
959                    .unwrap_or(Self::DEFAULT_SHOW_DURATION),
960            )
961            .trigger_mode(
962                widget
963                    .trigger_mode
964                    .or(tooltip_theme.trigger_mode)
965                    .unwrap_or(Self::DEFAULT_TRIGGER_MODE),
966            )
967            .enable_feedback(
968                widget
969                    .enable_feedback
970                    .or(tooltip_theme.enable_feedback)
971                    .unwrap_or(Self::DEFAULT_ENABLE_FEEDBACK),
972            )
973            .hover_delay(
974                widget
975                    .wait_duration
976                    .or(tooltip_theme.wait_duration)
977                    .unwrap_or(Self::DEFAULT_WAIT_DURATION),
978            )
979            .enable_tap_to_dismiss(widget.enable_tap_to_dismiss);
980            if let Some(on_triggered) = widget.on_triggered.clone() {
981                raw_tooltip = raw_tooltip.on_triggered(on_triggered);
982            }
983            effective_child = raw_tooltip
984                .dismiss_delay(
985                    widget
986                        .exit_duration
987                        .or(tooltip_theme.exit_duration)
988                        .unwrap_or(Self::DEFAULT_EXIT_DURATION),
989                )
990                .position_delegate(self.get_default_position_delegate(app))
991                .ignore_pointer(
992                    widget
993                        .ignore_pointer
994                        .or(tooltip_theme.ignore_pointer)
995                        .unwrap_or(widget.message.is_some()),
996                )
997                .into_widget();
998        }
999
1000        effective_child
1001    }
1002}
1003
1004#[derive(Debug)]
1005struct TooltipBox {
1006    constraints: BoxConstraints,
1007    text_style: TextStyle,
1008    text_align: TextAlign,
1009    decoration: Option<DecorationRef>,
1010    padding: Option<EdgeInsetsGeometry>,
1011    margin: Option<EdgeInsetsGeometry>,
1012    rich_message: InlineSpanRef,
1013}
1014
1015impl StatelessWidget for TooltipBox {
1016    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
1017        let mut container = Container::new();
1018        container.decoration = self.decoration.clone();
1019        container.padding = self.padding;
1020        container.margin = self.margin;
1021        ConstrainedBox::new(self.constraints)
1022            .child(
1023                DefaultTextStyle::new(
1024                    self.text_style.clone(),
1025                    container.child(
1026                        Center::new().width_factor(1.0).height_factor(1.0).child(
1027                            Text::rich(Rc::clone(&self.rich_message))
1028                                .style(self.text_style.clone())
1029                                .text_align(self.text_align),
1030                        ),
1031                    ),
1032                )
1033                .text_align(self.text_align),
1034            )
1035            .into_widget()
1036    }
1037}
1038
1039#[cfg(test)]
1040#[allow(deprecated)]
1041pub(crate) mod tests {
1042    use std::cell::Cell;
1043
1044    use waft_embedder::{
1045        Color, FontWeight, Offset, PointerChange, RRect, Rect, Size, TextDecoration,
1046        TextDecorationStyle,
1047    };
1048    use waft_foundation::Listener;
1049    use waft_gestures::{GestureRecognizerLeaf, TapGestureRecognizer};
1050    use waft_painting::{AnyColor, BorderSide, ShapeDecoration, StadiumBorder, TextScaler};
1051    use waft_rendering::testing::{PaintCall, assert_paints};
1052    use waft_rendering::{AnyRenderBox, RenderParagraph, RendererBinding};
1053    use waft_services::SystemMouseCursors;
1054    use waft_widgets::{
1055        AnyElement, IgnorePointer, MediaQuery, MediaQueryData, Overlay, OverlayEntry, Padding,
1056        Positioned, RichText, Stack, WidgetSpan,
1057    };
1058
1059    use waft_widgets::testing::{
1060        TargetPlatformVariant, TestPointer, WidgetTester, expect, find, finds_nothing,
1061        finds_one_widget, test_widgets, test_widgets_variant,
1062    };
1063
1064    use super::*;
1065    use crate::test_support::{PaintInspection, material_app};
1066    use crate::theme_data::ThemeData;
1067
1068    pub(crate) const TOOLTIP_TEXT: &str = "TIP";
1069
1070    /// `tester.pumpWidget(MaterialApp(theme: theme(app), home: home(app)))`.
1071    pub(crate) fn pump_app(
1072        tester: &mut WidgetTester,
1073        theme: impl FnOnce(&App) -> ThemeData,
1074        home: impl FnOnce(&mut App) -> WidgetRef,
1075    ) {
1076        let root = {
1077            let mut app = tester.cell.borrow_mut();
1078            let theme = theme(&app);
1079            material_app(theme, home(&mut app))
1080        };
1081        tester.pump_widget(root);
1082    }
1083
1084    pub(crate) fn m3(app: &App) -> ThemeData {
1085        ThemeData::new(app)
1086    }
1087
1088    pub(crate) fn m2(app: &App) -> ThemeData {
1089        ThemeData::builder().use_material3(false).build(app)
1090    }
1091
1092    /// Dart's `Overlay(initialEntries: [OverlayEntry(builder: (_) => child)])`.
1093    pub(crate) fn overlay(app: &mut App, child: WidgetRef) -> WidgetRef {
1094        let entry = OverlayEntry::new(
1095            app,
1096            Rc::new(move |_app, _context| child.clone()),
1097            false,
1098            false,
1099            false,
1100        );
1101        Overlay::new().initial_entries([entry]).into_widget()
1102    }
1103
1104    /// Dart's `Stack(children: [Positioned(left:, top:, child:)])`.
1105    pub(crate) fn positioned_at(left: f64, top: f64, child: Tooltip) -> WidgetRef {
1106        Stack::new()
1107            .children([Positioned::new(child).left(left).top(top).into_widget()])
1108            .into_widget()
1109    }
1110
1111    /// Dart's `tooltipKey.currentState?.ensureTooltipVisible()`.
1112    pub(crate) fn ensure_tooltip_visible(tester: &WidgetTester, key: &GlobalKey) -> bool {
1113        let mut app = tester.cell.borrow_mut();
1114        key.current_state::<TooltipState>(&app)
1115            .is_some_and(|state| state.ensure_tooltip_visible(&mut app))
1116    }
1117
1118    /// Dart's `find.text(tooltipText)`, found once.
1119    pub(crate) fn tooltip_text(tester: &WidgetTester) -> AnyElement {
1120        let found = find::text(TOOLTIP_TEXT).evaluate(tester);
1121        assert_eq!(found.len(), 1, "one tooltip text");
1122        found[0]
1123    }
1124
1125    /// Dart's `tester.renderObject(_findTooltipContainer(tooltipText))`.
1126    pub(crate) fn tooltip_container(tester: &WidgetTester) -> AnyRenderBox {
1127        let container = tester.ancestor_of_type::<Container>(tooltip_text(tester));
1128        tester.render_box_of(container)
1129    }
1130
1131    /// The render box of the tooltip's text: Dart's `tester.renderObject(find.text(..))`.
1132    pub(crate) fn text_box(tester: &WidgetTester) -> AnyRenderBox {
1133        tester.render_box_of(tooltip_text(tester))
1134    }
1135
1136    /// Dart's `tester.widget<Text>(find.text(tooltipText)).style!`.
1137    pub(crate) fn text_style(tester: &WidgetTester) -> TextStyle {
1138        tester.widget(tooltip_text(tester), |text: &Text| {
1139            text.style
1140                .clone()
1141                .expect("the tooltip gives its text a style")
1142        })
1143    }
1144
1145    pub(crate) fn rect(tester: &WidgetTester, render: AnyRenderBox) -> Rect {
1146        tester.get_rect(render)
1147    }
1148
1149    pub(crate) fn size(tester: &WidgetTester, render: AnyRenderBox) -> Size {
1150        render.size(&tester.cell.borrow())
1151    }
1152
1153    /// The `Container` the tooltip builds around its text.
1154    fn container_widget<R>(tester: &WidgetTester, read: impl FnOnce(&Container) -> R) -> R {
1155        let container = tester.ancestor_of_type::<Container>(tooltip_text(tester));
1156        tester.widget(container, read)
1157    }
1158
1159    /// The size of the tooltip's paragraph: Dart's `tester.getSize(find.text(tooltipText))`.
1160    pub(crate) fn paragraph_size(tester: &WidgetTester) -> Size {
1161        size(tester, text_box(tester))
1162    }
1163
1164    pub(crate) fn found(tester: &WidgetTester, text: &str) -> bool {
1165        !find::text(text).evaluate(tester).is_empty()
1166    }
1167
1168    pub(crate) fn center(tester: &WidgetTester, element: AnyElement) -> Offset {
1169        rect(tester, tester.render_box_of(element)).center()
1170    }
1171
1172    pub(crate) fn tooltip_center(tester: &WidgetTester) -> Offset {
1173        center(tester, find::by_type::<Tooltip>().evaluate(tester)[0])
1174    }
1175
1176    pub(crate) fn ensure_visible_and_fade_in(tester: &mut WidgetTester, key: &GlobalKey) {
1177        ensure_tooltip_visible(tester, key);
1178        tester.pump_by(Duration::from_secs(2)); // faded in, show timer started (and at 0.0)
1179    }
1180
1181    /// The tooltip of the positioning cases: `height`, `padding`, `verticalOffset` and
1182    /// `preferBelow` given.
1183    fn positioned_tooltip(
1184        key: &GlobalKey,
1185        height: f64,
1186        padding: EdgeInsetsGeometry,
1187        vertical_offset: f64,
1188        prefer_below: bool,
1189    ) -> Tooltip {
1190        Tooltip::new()
1191            .key(key.clone().into())
1192            .message(TOOLTIP_TEXT)
1193            .height(height)
1194            .padding(padding)
1195            .vertical_offset(vertical_offset)
1196            .prefer_below(prefer_below)
1197            .child(SizedBox::shrink())
1198    }
1199
1200    pub(crate) fn green_box() -> Container {
1201        Container::new()
1202            .width(100.0)
1203            .height(100.0)
1204            .color(Colors::GREEN.get(&500).expect("a 500 shade"))
1205    }
1206
1207    #[test]
1208    fn does_tooltip_end_up_in_the_right_place_center() {
1209        test_widgets(|tester| {
1210            let key = GlobalKey::new();
1211            let tooltip = positioned_tooltip(&key, 20.0, EdgeInsetsGeometry::all(5.0), 20.0, false);
1212            pump_app(tester, m3, |app| {
1213                overlay(app, positioned_at(300.0, 0.0, tooltip))
1214            });
1215            ensure_visible_and_fade_in(tester, &key);
1216
1217            let tip_in_global = rect(tester, tooltip_container(tester)).top_center();
1218            assert_eq!(tip_in_global.dx(), 300.0);
1219            assert_eq!(tip_in_global.dy(), 20.0);
1220        });
1221    }
1222
1223    #[test]
1224    fn does_tooltip_end_up_in_the_right_place_center_with_padding_outside_overlay() {
1225        test_widgets(|tester| {
1226            let key = GlobalKey::new();
1227            let tooltip = positioned_tooltip(&key, 20.0, EdgeInsetsGeometry::all(5.0), 20.0, false);
1228            pump_app(tester, m3, |app| {
1229                let overlay = overlay(app, positioned_at(300.0, 0.0, tooltip));
1230                Padding::new(EdgeInsetsGeometry::all(20.0))
1231                    .child(overlay)
1232                    .into_widget()
1233            });
1234            ensure_visible_and_fade_in(tester, &key);
1235
1236            let tip_in_global = rect(tester, tooltip_container(tester)).top_center();
1237            assert_eq!(tip_in_global.dx(), 320.0);
1238            assert_eq!(tip_in_global.dy(), 40.0);
1239        });
1240    }
1241
1242    fn top_left_case(tester: &mut WidgetTester, theme: fn(&App) -> ThemeData) -> Rect {
1243        let key = GlobalKey::new();
1244        let tooltip = positioned_tooltip(&key, 20.0, EdgeInsetsGeometry::all(5.0), 20.0, false);
1245        pump_app(tester, theme, |app| {
1246            overlay(app, positioned_at(0.0, 0.0, tooltip))
1247        });
1248        ensure_visible_and_fade_in(tester, &key);
1249        rect(tester, tooltip_container(tester))
1250    }
1251
1252    #[test]
1253    fn material2_does_tooltip_end_up_in_the_right_place_top_left() {
1254        test_widgets(|tester| {
1255            let tip = top_left_case(tester, m2);
1256            assert_eq!(tip.height(), 24.0); // 14.0 height + 5.0 padding * 2 (top, bottom)
1257            assert_eq!(tip.top_left(), Offset::new(10.0, 20.0));
1258        });
1259    }
1260
1261    #[test]
1262    fn material3_does_tooltip_end_up_in_the_right_place_top_left() {
1263        test_widgets(|tester| {
1264            let tip = top_left_case(tester, m3);
1265            assert_eq!(tip.height(), 30.0); // 20.0 height + 5.0 padding * 2 (top, bottom)
1266            assert_eq!(tip.top_left(), Offset::new(10.0, 20.0));
1267        });
1268    }
1269
1270    fn center_case(tester: &mut WidgetTester, top: f64, height: f64, prefer_below: bool) -> Rect {
1271        let key = GlobalKey::new();
1272        let tooltip =
1273            positioned_tooltip(&key, height, EdgeInsetsGeometry::ZERO, 100.0, prefer_below);
1274        pump_app(tester, m3, |app| {
1275            overlay(app, positioned_at(400.0, top, tooltip))
1276        });
1277        ensure_visible_and_fade_in(tester, &key);
1278        rect(tester, tooltip_container(tester))
1279    }
1280
1281    #[test]
1282    fn does_tooltip_end_up_in_the_right_place_center_prefer_above_fits() {
1283        test_widgets(|tester| {
1284            let tip = center_case(tester, 300.0, 100.0, false);
1285            assert_eq!(tip.height(), 100.0);
1286            assert_eq!(tip.top, 100.0);
1287            assert_eq!(tip.bottom, 200.0);
1288        });
1289    }
1290
1291    #[test]
1292    fn does_tooltip_end_up_in_the_right_place_center_prefer_above_does_not_fit() {
1293        test_widgets(|tester| {
1294            let tip = center_case(tester, 299.0, 190.0, false);
1295            assert_eq!(tip.height(), 190.0);
1296            assert_eq!(tip.top, 399.0);
1297            assert_eq!(tip.bottom, 589.0);
1298        });
1299    }
1300
1301    #[test]
1302    fn does_tooltip_end_up_in_the_right_place_center_prefer_below_fits() {
1303        test_widgets(|tester| {
1304            let tip = center_case(tester, 300.0, 190.0, true);
1305            assert_eq!(tip.height(), 190.0);
1306            assert_eq!(tip.top, 400.0);
1307            assert_eq!(tip.bottom, 590.0);
1308        });
1309    }
1310
1311    fn right_edge_case(tester: &mut WidgetTester, theme: fn(&App) -> ThemeData, left: f64) -> Rect {
1312        let key = GlobalKey::new();
1313        let tooltip = positioned_tooltip(&key, 10.0, EdgeInsetsGeometry::ZERO, 10.0, true);
1314        pump_app(tester, theme, |app| {
1315            overlay(app, positioned_at(left, 300.0, tooltip))
1316        });
1317        ensure_visible_and_fade_in(tester, &key);
1318        rect(tester, tooltip_container(tester))
1319    }
1320
1321    #[test]
1322    fn material2_does_tooltip_end_up_in_the_right_place_way_off_to_the_right() {
1323        test_widgets(|tester| {
1324            let tip = right_edge_case(tester, m2, 1600.0);
1325            assert_eq!(tip.height(), 14.0);
1326            assert_eq!(tip.top, 310.0);
1327            assert_eq!(tip.right, 790.0);
1328            assert_eq!(tip.bottom, 324.0);
1329        });
1330    }
1331
1332    #[test]
1333    fn material3_does_tooltip_end_up_in_the_right_place_way_off_to_the_right() {
1334        test_widgets(|tester| {
1335            let tip = right_edge_case(tester, m3, 1600.0);
1336            assert_eq!(tip.height(), 20.0);
1337            assert_eq!(tip.top, 310.0);
1338            assert_eq!(tip.right, 790.0);
1339            assert_eq!(tip.bottom, 330.0);
1340        });
1341    }
1342
1343    #[test]
1344    fn material2_does_tooltip_end_up_in_the_right_place_near_the_edge() {
1345        test_widgets(|tester| {
1346            let tip = right_edge_case(tester, m2, 780.0);
1347            assert_eq!(tip.height(), 14.0);
1348            assert_eq!(tip.top, 310.0);
1349            assert_eq!(tip.right, 790.0);
1350            assert_eq!(tip.bottom, 324.0);
1351        });
1352    }
1353
1354    #[test]
1355    fn material3_does_tooltip_end_up_in_the_right_place_near_the_edge() {
1356        test_widgets(|tester| {
1357            let tip = right_edge_case(tester, m3, 780.0);
1358            assert_eq!(tip.height(), 20.0);
1359            assert_eq!(tip.top, 310.0);
1360            assert_eq!(tip.right, 790.0);
1361            assert_eq!(tip.bottom, 330.0);
1362        });
1363    }
1364
1365    #[test]
1366    fn custom_tooltip_margin() {
1367        test_widgets(|tester| {
1368            const CUSTOM_MARGIN_VALUE: f64 = 10.0;
1369            let key = GlobalKey::new();
1370            let tooltip = Tooltip::new()
1371                .key(key.clone().into())
1372                .message(TOOLTIP_TEXT)
1373                .padding(EdgeInsetsGeometry::ZERO)
1374                .margin(EdgeInsetsGeometry::all(CUSTOM_MARGIN_VALUE))
1375                .child(SizedBox::shrink())
1376                .into_widget();
1377            pump_app(tester, m3, |app| overlay(app, tooltip));
1378            ensure_visible_and_fade_in(tester, &key);
1379
1380            let tip = rect(tester, tooltip_container(tester));
1381            let content = rect(tester, text_box(tester));
1382            assert_eq!(content.left, tip.left + CUSTOM_MARGIN_VALUE);
1383            assert_eq!(content.top, tip.top + CUSTOM_MARGIN_VALUE);
1384            assert_eq!(content.right, tip.right - CUSTOM_MARGIN_VALUE);
1385            assert_eq!(content.bottom, tip.bottom - CUSTOM_MARGIN_VALUE);
1386        });
1387    }
1388
1389    fn default_text_style_case(
1390        tester: &mut WidgetTester,
1391        theme: impl FnOnce(&App) -> ThemeData,
1392    ) -> TextStyle {
1393        let key = GlobalKey::new();
1394        let tooltip = Tooltip::new()
1395            .key(key.clone().into())
1396            .message(TOOLTIP_TEXT)
1397            .child(green_box())
1398            .into_widget();
1399        pump_app(tester, theme, |_app| tooltip);
1400        ensure_visible_and_fade_in(tester, &key);
1401        text_style(tester)
1402    }
1403
1404    #[test]
1405    fn material2_default_tooltip_message_text_style_light() {
1406        test_widgets(|tester| {
1407            let text_style = default_text_style_case(tester, m2);
1408            assert_eq!(text_style.color, Some(AnyColor::new(Colors::WHITE)));
1409            assert_eq!(text_style.font_family.as_deref(), Some("Roboto"));
1410            assert_eq!(text_style.decoration, Some(TextDecoration::NONE));
1411            assert_eq!(
1412                text_style.debug_label.as_deref(),
1413                Some(
1414                    "((englishLike bodyMedium 2014).merge(blackMountainView bodyMedium)).copyWith"
1415                )
1416            );
1417        });
1418    }
1419
1420    #[test]
1421    fn material3_default_tooltip_message_text_style_light() {
1422        test_widgets(|tester| {
1423            let text_style = default_text_style_case(tester, m3);
1424            assert_eq!(text_style.color, Some(AnyColor::new(Colors::WHITE)));
1425            assert_eq!(text_style.font_family.as_deref(), Some("Roboto"));
1426            assert_eq!(text_style.decoration, Some(TextDecoration::NONE));
1427            assert_eq!(
1428                text_style.debug_label.as_deref(),
1429                Some(
1430                    "((englishLike bodyMedium 2021).merge((blackMountainView bodyMedium).apply)).copyWith"
1431                )
1432            );
1433        });
1434    }
1435
1436    #[test]
1437    fn material2_default_tooltip_message_text_style_dark() {
1438        test_widgets(|tester| {
1439            let text_style = default_text_style_case(tester, |app| {
1440                ThemeData::builder()
1441                    .use_material3(false)
1442                    .brightness(Brightness::Dark)
1443                    .build(app)
1444            });
1445            assert_eq!(text_style.color, Some(AnyColor::new(Colors::BLACK)));
1446            assert_eq!(text_style.font_family.as_deref(), Some("Roboto"));
1447            assert_eq!(text_style.decoration, Some(TextDecoration::NONE));
1448            assert_eq!(
1449                text_style.debug_label.as_deref(),
1450                Some(
1451                    "((englishLike bodyMedium 2014).merge(whiteMountainView bodyMedium)).copyWith"
1452                )
1453            );
1454        });
1455    }
1456
1457    #[test]
1458    fn material3_default_tooltip_message_text_style_dark() {
1459        test_widgets(|tester| {
1460            let text_style = default_text_style_case(tester, |app| {
1461                ThemeData::builder().brightness(Brightness::Dark).build(app)
1462            });
1463            assert_eq!(text_style.color, Some(AnyColor::new(Colors::BLACK)));
1464            assert_eq!(text_style.font_family.as_deref(), Some("Roboto"));
1465            assert_eq!(text_style.decoration, Some(TextDecoration::NONE));
1466            assert_eq!(
1467                text_style.debug_label.as_deref(),
1468                Some(
1469                    "((englishLike bodyMedium 2021).merge((whiteMountainView bodyMedium).apply)).copyWith"
1470                )
1471            );
1472        });
1473    }
1474
1475    #[test]
1476    fn custom_tooltip_message_text_style() {
1477        test_widgets(|tester| {
1478            let key = GlobalKey::new();
1479            let tooltip = Tooltip::new()
1480                .key(key.clone().into())
1481                .text_style(
1482                    TextStyle::new()
1483                        .color(Colors::ORANGE.primary())
1484                        .decoration(TextDecoration::UNDERLINE),
1485                )
1486                .message(TOOLTIP_TEXT)
1487                .child(green_box())
1488                .into_widget();
1489            pump_app(tester, m3, |_app| tooltip);
1490            ensure_visible_and_fade_in(tester, &key);
1491
1492            let text_style = text_style(tester);
1493            assert_eq!(
1494                text_style.color,
1495                Some(AnyColor::new(Colors::ORANGE.primary()))
1496            );
1497            assert_eq!(text_style.font_family, None);
1498            assert_eq!(text_style.decoration, Some(TextDecoration::UNDERLINE));
1499        });
1500    }
1501
1502    #[test]
1503    fn custom_tooltip_message_text_align() {
1504        test_widgets(|tester| {
1505            let mut pump_tooltip_with_text_align = |text_align: Option<TextAlign>| {
1506                let key = GlobalKey::new();
1507                let mut tooltip = Tooltip::new()
1508                    .key(key.clone().into())
1509                    .message(TOOLTIP_TEXT)
1510                    .child(green_box());
1511                if let Some(text_align) = text_align {
1512                    tooltip = tooltip.text_align(text_align);
1513                }
1514                let tooltip = tooltip.into_widget();
1515                pump_app(tester, m3, |_app| tooltip);
1516                ensure_visible_and_fade_in(tester, &key);
1517                tester.widget(tooltip_text(tester), |text: &Text| text.text_align)
1518            };
1519
1520            // Default value should be TextAlign.start
1521            assert_eq!(pump_tooltip_with_text_align(None), Some(TextAlign::Start));
1522            assert_eq!(
1523                pump_tooltip_with_text_align(Some(TextAlign::Center)),
1524                Some(TextAlign::Center)
1525            );
1526            assert_eq!(
1527                pump_tooltip_with_text_align(Some(TextAlign::End)),
1528                Some(TextAlign::End)
1529            );
1530        });
1531    }
1532
1533    #[test]
1534    fn tooltip_overlay_wrapped_with_a_non_fallback_default_text_style_widget() {
1535        test_widgets(|tester| {
1536            let key = GlobalKey::new();
1537            let tooltip = Tooltip::new()
1538                .key(key.clone().into())
1539                .message(TOOLTIP_TEXT)
1540                .child(green_box())
1541                .into_widget();
1542            pump_app(tester, m3, |_app| tooltip);
1543            ensure_visible_and_fade_in(tester, &key);
1544
1545            let default_text_style =
1546                tester.ancestor_of_type::<DefaultTextStyle>(tooltip_text(tester));
1547            let text_style = tester.widget(default_text_style, |widget: &DefaultTextStyle| {
1548                widget.style.clone()
1549            });
1550            // The default fallback text style results in a text with a
1551            // double underline of Color(0xffffff00).
1552            assert_ne!(text_style.decoration, Some(TextDecoration::UNDERLINE));
1553            assert_ne!(
1554                text_style.decoration_color,
1555                Some(AnyColor::new(Color::new(0xffffff00)))
1556            );
1557            assert_ne!(
1558                text_style.decoration_style,
1559                Some(TextDecorationStyle::Double)
1560            );
1561        });
1562    }
1563
1564    /// The tooltip of the size, shape and colour cases, made visible in an overlay.
1565    fn default_look_case(
1566        tester: &mut WidgetTester,
1567        theme: fn(&App) -> ThemeData,
1568        decoration: Option<ShapeDecoration>,
1569    ) {
1570        let key = GlobalKey::new();
1571        let mut tooltip = Tooltip::new()
1572            .key(key.clone().into())
1573            .message(TOOLTIP_TEXT)
1574            .child(SizedBox::shrink());
1575        if let Some(decoration) = decoration {
1576            tooltip = tooltip.decoration(decoration);
1577        }
1578        let tooltip = tooltip.into_widget();
1579        pump_app(tester, theme, |app| overlay(app, tooltip));
1580        ensure_visible_and_fade_in(tester, &key);
1581    }
1582
1583    fn default_decoration() -> BoxDecoration {
1584        BoxDecoration::new()
1585            .color(Color::new(0xe6616161))
1586            .border_radius(BorderRadius::all(Radius::circular(4.0)))
1587    }
1588
1589    fn assert_default_look(tester: &WidgetTester, padding: EdgeInsets) {
1590        let tip = tooltip_container(tester);
1591        assert_paints(
1592            &tester.painted_ops(tip.as_object()),
1593            &[PaintCall::rrect_at(
1594                RRect::from_rect_and_radius(
1595                    Rect::from_ltwh(
1596                        0.0,
1597                        0.0,
1598                        size(tester, tip).width(),
1599                        size(tester, tip).height(),
1600                    ),
1601                    Radius::circular(4.0),
1602                ),
1603                Some(Color::new(0xe6616161)),
1604            )],
1605        );
1606        container_widget(tester, |container| {
1607            assert!(
1608                container
1609                    .decoration
1610                    .as_deref()
1611                    .is_some_and(|decoration| decoration.eq_decoration(&default_decoration()))
1612            );
1613            assert_eq!(container.padding, Some(EdgeInsetsGeometry::Insets(padding)));
1614        });
1615    }
1616
1617    #[test]
1618    fn material2_does_tooltip_end_up_with_the_right_default_size_shape_and_color() {
1619        test_widgets(|tester| {
1620            default_look_case(tester, m2, None);
1621            let tip = size(tester, tooltip_container(tester));
1622            assert_eq!(tip.height(), 32.0);
1623            assert_eq!(tip.width(), 74.0);
1624            assert_default_look(tester, EdgeInsets::symmetric(4.0, 16.0));
1625        });
1626    }
1627
1628    #[test]
1629    fn material3_does_tooltip_end_up_with_the_right_default_size_shape_and_color() {
1630        test_widgets(|tester| {
1631            default_look_case(tester, m3, None);
1632            let tip = size(tester, tooltip_container(tester));
1633            assert_eq!(tip.height(), 32.0);
1634            assert_eq!(tip.width(), 74.75);
1635            assert_default_look(tester, EdgeInsets::symmetric(4.0, 16.0));
1636        });
1637    }
1638
1639    const DESKTOP: [TargetPlatform; 3] = [
1640        TargetPlatform::MacOS,
1641        TargetPlatform::Linux,
1642        TargetPlatform::Windows,
1643    ];
1644
1645    fn desktop_case(tester: &mut WidgetTester, theme: fn(&App) -> ThemeData) {
1646        let key = GlobalKey::new();
1647        let tooltip = Tooltip::new()
1648            .key(key.clone().into())
1649            .message(TOOLTIP_TEXT)
1650            .child(SizedBox::shrink())
1651            .into_widget();
1652        pump_app(tester, theme, |_app| tooltip);
1653        ensure_visible_and_fade_in(tester, &key);
1654    }
1655
1656    #[test]
1657    fn material2_tooltip_default_size_shape_and_color_test_for_desktop() {
1658        test_widgets(|_| {
1659            for platform in DESKTOP {
1660                test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
1661                    desktop_case(tester, m2);
1662                    let paragraph = tester.first::<RenderParagraph>();
1663                    let text_size = paragraph.text_size(&tester.cell.borrow());
1664                    assert_eq!(text_size.height(), 12.0);
1665                    let tip = size(tester, tooltip_container(tester));
1666                    assert_eq!(tip.height(), 24.0);
1667                    assert_default_look(tester, EdgeInsets::symmetric(4.0, 8.0));
1668                });
1669            }
1670        });
1671    }
1672
1673    #[test]
1674    fn material3_tooltip_default_size_shape_and_color_test_for_desktop() {
1675        test_widgets(|_| {
1676            for platform in DESKTOP {
1677                test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
1678                    desktop_case(tester, m3);
1679                    let paragraph = tester.first::<RenderParagraph>();
1680                    let text_size = paragraph.text_size(&tester.cell.borrow());
1681                    assert_eq!(text_size.height(), 17.0);
1682                    let tip = size(tester, tooltip_container(tester));
1683                    assert_eq!(tip.height(), 25.0);
1684                    assert_default_look(tester, EdgeInsets::symmetric(4.0, 8.0));
1685                });
1686            }
1687        });
1688    }
1689
1690    pub(crate) fn custom_decoration() -> ShapeDecoration {
1691        ShapeDecoration::new(StadiumBorder::new(BorderSide::NONE)).color(Color::new(0x80800000))
1692    }
1693
1694    #[test]
1695    fn material2_can_tooltip_decoration_be_customized() {
1696        test_widgets(|tester| {
1697            default_look_case(tester, m2, Some(custom_decoration()));
1698            let tip = tooltip_container(tester);
1699            assert_eq!(size(tester, tip).height(), 32.0);
1700            assert_eq!(size(tester, tip).width(), 74.0);
1701            assert_paints(
1702                &tester.painted_ops(tip.as_object()),
1703                &[PaintCall::rrect(Some(Color::new(0x80800000)))],
1704            );
1705        });
1706    }
1707
1708    #[test]
1709    fn material3_can_tooltip_decoration_be_customized() {
1710        test_widgets(|tester| {
1711            default_look_case(tester, m3, Some(custom_decoration()));
1712            let tip = tooltip_container(tester);
1713            assert_eq!(size(tester, tip).height(), 32.0);
1714            assert_eq!(size(tester, tip).width(), 74.75);
1715            assert_paints(
1716                &tester.painted_ops(tip.as_object()),
1717                &[PaintCall::rrect(Some(Color::new(0x80800000)))],
1718            );
1719        });
1720    }
1721
1722    /// Dart's text scaling cases, whose `Navigator` and `MaterialPageRoute` only put the
1723    /// tooltip under the `MediaQuery`: (paragraph, tip) sizes at no scaling and at 4x, pumped
1724    /// into one tester.
1725    fn text_scale_case(
1726        tester: &mut WidgetTester,
1727        theme: fn(&App) -> ThemeData,
1728    ) -> [(Size, f64); 2] {
1729        [TextScaler::NO_SCALING, TextScaler::linear(4.0)].map(|text_scaler| {
1730            pump_app(tester, theme, |_app| {
1731                let data = MediaQueryData::new().text_scaler(text_scaler);
1732                MediaQuery::new(
1733                    data,
1734                    Center::new().child(Tooltip::new().message(TOOLTIP_TEXT).child(green_box())),
1735                )
1736                .into_widget()
1737            });
1738            let at = tooltip_center(tester);
1739            tester.long_press_at(at, 1);
1740            assert!(found(tester, TOOLTIP_TEXT));
1741            (
1742                paragraph_size(tester),
1743                size(tester, tooltip_container(tester)).height(),
1744            )
1745        })
1746    }
1747
1748    #[test]
1749    fn material2_tooltip_text_scales_with_text_scaler() {
1750        test_widgets(|tester| {
1751            let [(text, tip), (scaled_text, scaled_tip)] = text_scale_case(tester, m2);
1752            assert_eq!(text, Size::new(42.0, 14.0));
1753            assert_eq!(tip, 32.0);
1754            assert_eq!(scaled_text, Size::new(168.0, 56.0));
1755            assert_eq!(scaled_tip, 64.0);
1756        });
1757    }
1758
1759    #[test]
1760    fn material3_tooltip_text_scales_with_text_scale_factor() {
1761        test_widgets(|tester| {
1762            let [(text, tip), (scaled_text, scaled_tip)] = text_scale_case(tester, m3);
1763            assert_eq!(text.width(), 42.75);
1764            assert_eq!(text.height(), 20.0);
1765            assert_eq!(tip, 32.0);
1766            assert_eq!(scaled_text.width(), 168.75);
1767            assert_eq!(scaled_text.height(), 80.0);
1768            assert_eq!(scaled_tip, 88.0);
1769        });
1770    }
1771
1772    #[test]
1773    fn tooltip_text_displays_with_rich_message() {
1774        test_widgets(|tester| {
1775            const TEXT_SPAN1_TEXT: &str = "I am a rich tooltip message. ";
1776            const TEXT_SPAN2_TEXT: &str = "I am another span of a rich tooltip message";
1777            let key = GlobalKey::new();
1778            let rich_message = TextSpan::new()
1779                .text(TEXT_SPAN1_TEXT)
1780                .children(vec![TextSpan::new().text(TEXT_SPAN2_TEXT).into_span()])
1781                .into_span();
1782            let tooltip = Tooltip::new()
1783                .key(key.clone().into())
1784                .rich_message(rich_message)
1785                .child(green_box())
1786                .into_widget();
1787            pump_app(tester, m3, |_app| tooltip);
1788            ensure_visible_and_fade_in(tester, &key);
1789
1790            let rich_texts = find::by_type::<RichText>().evaluate(tester);
1791            assert_eq!(rich_texts.len(), 1);
1792            let plain_text = tester.widget(rich_texts[0], |rich_text: &RichText| {
1793                rich_text.text.to_plain_text(true, true)
1794            });
1795            assert_eq!(plain_text, format!("{TEXT_SPAN1_TEXT}{TEXT_SPAN2_TEXT}"));
1796        });
1797    }
1798
1799    #[test]
1800    fn tooltip_does_not_crash_at_zero_area() {
1801        test_widgets(|tester| {
1802            tester.view().set_physical_size(Size::ZERO);
1803            let key = GlobalKey::new();
1804            let tooltip = Tooltip::new().key(key.clone().into()).message("X");
1805            pump_app(tester, m3, |_app| {
1806                Center::new().child(tooltip).into_widget()
1807            });
1808            let tooltip_size = |tester: &WidgetTester| {
1809                size(
1810                    tester,
1811                    tester.render_box_of(find::by_type::<Tooltip>().evaluate(tester)[0]),
1812                )
1813            };
1814            assert_eq!(tooltip_size(tester), Size::ZERO);
1815            ensure_tooltip_visible(tester, &key);
1816            tester.pump_and_settle();
1817            assert_eq!(tooltip_size(tester), Size::ZERO);
1818            expect(tester, &find::text("X"), finds_one_widget());
1819        });
1820    }
1821
1822    #[test]
1823    #[should_panic(expected = "Either `message` or `richMessage` must be specified")]
1824    fn tooltip_throws_assertion_error_when_both_message_and_rich_message_are_specified() {
1825        let _ = Tooltip::new()
1826            .message("I am a tooltip message.")
1827            .rich_message(
1828                TextSpan::new()
1829                    .text("I am a rich tooltip.")
1830                    .children(vec![
1831                        TextSpan::new()
1832                            .text("I am another span of a rich tooltip.")
1833                            .into_span(),
1834                    ])
1835                    .into_span(),
1836            )
1837            .child(green_box());
1838    }
1839
1840    #[test]
1841    fn tooltip_should_not_be_shown_with_empty_message_with_child() {
1842        test_widgets(|tester| {
1843            pump_app(tester, m3, |_app| {
1844                Tooltip::new()
1845                    .message("")
1846                    .child(Text::new(TOOLTIP_TEXT))
1847                    .into_widget()
1848            });
1849            expect(tester, &find::text(TOOLTIP_TEXT), finds_one_widget());
1850            expect(tester, &find::by_type::<Tooltip>(), finds_one_widget());
1851
1852            let at = center(tester, tooltip_text(tester));
1853            tester.long_press_at(at, 1);
1854            expect(tester, &find::by_type::<Tooltip>(), finds_one_widget());
1855            expect(tester, &find::by_type::<RawTooltip>(), finds_nothing());
1856        });
1857    }
1858
1859    #[test]
1860    fn tooltip_should_not_be_shown_with_empty_message_without_child() {
1861        test_widgets(|tester| {
1862            pump_app(tester, m3, |_app| Tooltip::new().message("").into_widget());
1863            expect(tester, &find::by_type::<Tooltip>(), finds_one_widget());
1864            expect(tester, &find::by_type::<SizedBox>(), finds_one_widget());
1865            expect(tester, &find::by_type::<RawTooltip>(), finds_nothing());
1866        });
1867    }
1868
1869    /// Dart's `_testGestureTap`.
1870    pub(crate) fn test_gesture_tap(tester: &mut WidgetTester, at: Offset) {
1871        tester.tap_at(at, 1);
1872        tester.pump_by(Duration::from_millis(10));
1873    }
1874
1875    #[test]
1876    fn tooltip_should_not_ignore_users_tap_on_rich_message() {
1877        test_widgets(|tester| {
1878            let is_tapped = Rc::new(Cell::new(false));
1879            let recognizer = {
1880                let mut app = tester.cell.borrow_mut();
1881                let recognizer = TapGestureRecognizer::new(&mut app);
1882                let tapped = Rc::clone(&is_tapped);
1883                recognizer.set_on_tap(&mut app, Some(Listener::new(move |_app| tapped.set(true))));
1884                recognizer
1885            };
1886            let rich_message = TextSpan::new()
1887                .text(TOOLTIP_TEXT)
1888                .recognizer(recognizer.erase())
1889                .into_span();
1890            pump_app(tester, m3, |_app| {
1891                Tooltip::new()
1892                    .rich_message(rich_message)
1893                    .show_duration(Duration::from_secs(5))
1894                    .trigger_mode(TooltipTriggerMode::Tap)
1895                    .child(SizedBox::new().width(24.0).height(24.0))
1896                    .into_widget()
1897            });
1898
1899            assert!(!found(tester, TOOLTIP_TEXT));
1900
1901            let at = tooltip_center(tester);
1902            test_gesture_tap(tester, at);
1903            expect(tester, &find::text(TOOLTIP_TEXT), finds_one_widget());
1904
1905            let at = center(tester, tooltip_text(tester));
1906            test_gesture_tap(tester, at);
1907            assert!(is_tapped.get());
1908            recognizer
1909                .as_recognizer()
1910                .dispose(&mut tester.cell.borrow_mut());
1911        });
1912    }
1913
1914    #[test]
1915    fn tooltip_does_not_rebuild_for_fade_in_fade_out_animation() {
1916        test_widgets(|tester| {
1917            pump_app(tester, m3, |_app| {
1918                Center::new()
1919                    .child(
1920                        SizedBox::square(Some(10.0)).child(
1921                            Tooltip::new()
1922                                .message(TOOLTIP_TEXT)
1923                                .wait_duration(Duration::from_secs(1))
1924                                .trigger_mode(TooltipTriggerMode::LongPress)
1925                                .child(SizedBox::expand()),
1926                        ),
1927                    )
1928                    .into_widget()
1929            });
1930            let element = find::by_type::<Tooltip>().evaluate(tester)[0];
1931            let state = element
1932                .state_handle::<TooltipState>(&tester.cell.borrow())
1933                .expect("a tooltip state");
1934            let dirty = |tester: &WidgetTester| element.dirty(&tester.cell.borrow());
1935            // The Tooltip widget itself is almost stateless thus doesn't need
1936            // rebuilding.
1937            assert!(!dirty(tester));
1938
1939            assert!(state.ensure_tooltip_visible(&mut tester.cell.borrow_mut()));
1940            assert!(!dirty(tester));
1941            tester.pump_by(Duration::from_secs(1));
1942            assert!(!dirty(tester));
1943
1944            assert!(Tooltip::dismiss_all_tool_tips(
1945                &mut tester.cell.borrow_mut()
1946            ));
1947            assert!(!dirty(tester));
1948            tester.pump_by(Duration::from_secs(1));
1949            assert!(!dirty(tester));
1950        });
1951    }
1952
1953    fn active_cursor(tester: &WidgetTester) -> MouseCursorRef {
1954        let mut app = tester.cell.borrow_mut();
1955        let tracker = RendererBinding::instance(&mut app).mouse_tracker(&app);
1956        tracker
1957            .debug_device_active_cursor(&app, 1)
1958            .expect("the mouse is over the view")
1959    }
1960
1961    #[test]
1962    fn tooltip_mouse_cursor_behavior() {
1963        test_widgets(|tester| {
1964            pump_app(tester, m3, |_app| {
1965                Center::new()
1966                    .child(
1967                        Tooltip::new()
1968                            .message(TOOLTIP_TEXT)
1969                            .mouse_cursor(SystemMouseCursors::GRAB.into())
1970                            .child(SizedBox::square(Some(50.0))),
1971                    )
1972                    .into_widget()
1973            });
1974
1975            let mut gesture = TestPointer::mouse(1, 0);
1976            tester.add_pointer(&mut gesture, Offset::new(10.0, 10.0));
1977            tester.pump();
1978            assert!(*active_cursor(tester) == *MouseCursorRef::from(SystemMouseCursors::BASIC));
1979
1980            let chip = tooltip_center(tester);
1981            tester.move_to(&mut gesture, chip, false);
1982            tester.pump();
1983            assert!(*active_cursor(tester) == *MouseCursorRef::from(SystemMouseCursors::GRAB));
1984        });
1985    }
1986
1987    /// The hover cases on whether the overlay ignores the pointer: `ignoring` of the last
1988    /// `IgnorePointer` once the mouse hovers the child. Dart's child is an `ElevatedButton`
1989    /// in a `Scaffold`, only a hover target here.
1990    fn overlay_ignores_pointer(
1991        tester: &mut WidgetTester,
1992        tooltip: Tooltip,
1993        tooltip_message: &str,
1994    ) -> bool {
1995        let tooltip = tooltip.child(Text::new("Hover me")).into_widget();
1996        pump_app(tester, m3, |_app| {
1997            Center::new().child(tooltip).into_widget()
1998        });
1999
2000        let button = find::text("Hover me").evaluate(tester);
2001        assert_eq!(button.len(), 1);
2002
2003        let mut gesture = TestPointer::mouse(1, 0);
2004        tester.add_pointer(&mut gesture, Offset::ZERO);
2005        let at = center(tester, button[0]);
2006        tester.move_to(&mut gesture, at, false);
2007        tester.pump_and_settle();
2008
2009        expect(tester, &find::text(tooltip_message), finds_one_widget());
2010
2011        let ignore_pointers = find::by_type::<IgnorePointer>().evaluate(tester);
2012        let ignoring = tester.widget(
2013            *ignore_pointers.last().expect("an IgnorePointer"),
2014            |ignore_pointer: &IgnorePointer| ignore_pointer.ignoring,
2015        );
2016        tester.send(&gesture, PointerChange::Remove);
2017        ignoring
2018    }
2019
2020    fn rich_tooltip_message() -> InlineSpanRef {
2021        TextSpan::new()
2022            .children(vec![
2023                TextSpan::new()
2024                    .text("Rich ")
2025                    .style(TextStyle::new().font_weight(FontWeight::BOLD))
2026                    .into_span(),
2027                TextSpan::new().text("Tooltip").into_span(),
2028            ])
2029            .into_span()
2030    }
2031
2032    #[test]
2033    fn tooltip_overlay_ignores_pointer_by_default_when_passing_simple_message() {
2034        test_widgets(|tester| {
2035            const TOOLTIP_MESSAGE: &str = "Tooltip message";
2036            assert!(overlay_ignores_pointer(
2037                tester,
2038                Tooltip::new().message(TOOLTIP_MESSAGE),
2039                TOOLTIP_MESSAGE
2040            ));
2041        });
2042    }
2043
2044    #[test]
2045    fn tooltip_overlay_with_simple_message_does_not_ignore_pointer_when_passing_ignore_pointer_false()
2046     {
2047        test_widgets(|tester| {
2048            const TOOLTIP_MESSAGE: &str = "Tooltip message";
2049            assert!(!overlay_ignores_pointer(
2050                tester,
2051                Tooltip::new()
2052                    .ignore_pointer(false)
2053                    .message(TOOLTIP_MESSAGE),
2054                TOOLTIP_MESSAGE
2055            ));
2056        });
2057    }
2058
2059    #[test]
2060    fn tooltip_overlay_does_not_ignore_pointer_by_default_when_passing_rich_message() {
2061        test_widgets(|tester| {
2062            assert!(!overlay_ignores_pointer(
2063                tester,
2064                Tooltip::new().rich_message(rich_tooltip_message()),
2065                "Rich Tooltip"
2066            ));
2067        });
2068    }
2069
2070    #[test]
2071    fn tooltip_overlay_with_rich_message_ignores_pointer_when_passing_ignore_pointer_true() {
2072        test_widgets(|tester| {
2073            assert!(overlay_ignores_pointer(
2074                tester,
2075                Tooltip::new()
2076                    .ignore_pointer(true)
2077                    .rich_message(rich_tooltip_message()),
2078                "Rich Tooltip"
2079            ));
2080        });
2081    }
2082
2083    #[test]
2084    fn tooltip_should_pass_its_default_text_style_down_to_widget_spans() {
2085        test_widgets(|tester| {
2086            let key = GlobalKey::new();
2087            let tooltip = Tooltip::new()
2088                .key(key.clone().into())
2089                .rich_message(Rc::new(WidgetSpan::new(Text::new(TOOLTIP_TEXT))))
2090                .child(green_box())
2091                .into_widget();
2092            pump_app(tester, m3, |_app| tooltip);
2093            ensure_visible_and_fade_in(tester, &key);
2094
2095            let default_text_style =
2096                tester.ancestor_of_type::<DefaultTextStyle>(tooltip_text(tester));
2097            let style = tester.widget(default_text_style, |widget: &DefaultTextStyle| {
2098                widget.style.clone()
2099            });
2100            assert_eq!(style.color, Some(AnyColor::new(Colors::WHITE)));
2101            assert_eq!(style.font_family.as_deref(), Some("Roboto"));
2102            assert_eq!(style.decoration, Some(TextDecoration::NONE));
2103            assert_eq!(
2104                style.debug_label.as_deref(),
2105                Some(
2106                    "((englishLike bodyMedium 2021).merge((blackMountainView bodyMedium).apply)).copyWith"
2107                )
2108            );
2109        });
2110    }
2111
2112    #[test]
2113    fn tooltip_should_apply_provided_text_style_to_rich_messages() {
2114        test_widgets(|tester| {
2115            let key = GlobalKey::new();
2116            let expected_text_style = TextStyle::new().color(Colors::ORANGE.primary());
2117            let tooltip = Tooltip::new()
2118                .key(key.clone().into())
2119                .rich_message(TextSpan::new().text(TOOLTIP_TEXT).into_span())
2120                .text_style(expected_text_style.clone())
2121                .child(green_box())
2122                .into_widget();
2123            pump_app(tester, m3, |_app| tooltip);
2124            ensure_visible_and_fade_in(tester, &key);
2125
2126            let text_style = text_style(tester);
2127            let default_text_style =
2128                tester.ancestor_of_type::<DefaultTextStyle>(tooltip_text(tester));
2129            let default_text_style = tester
2130                .widget(default_text_style, |widget: &DefaultTextStyle| {
2131                    widget.style.clone()
2132                });
2133            // Dart's `same`: a style here is a value, so equality stands for identity.
2134            assert_eq!(text_style, expected_text_style);
2135            assert_eq!(default_text_style, expected_text_style);
2136        });
2137    }
2138
2139    #[test]
2140    fn tooltip_respects_and_prefers_the_given_constraints_over_theme_constraints() {
2141        test_widgets(|tester| {
2142            let key = GlobalKey::new();
2143            let theme_constraints = BoxConstraints::tight_for(Some(300.0), Some(150.0));
2144            let tooltip_constraints = BoxConstraints::tight_for(Some(500.0), Some(250.0));
2145            let tooltip = Tooltip::new()
2146                .key(key.clone().into())
2147                .message(TOOLTIP_TEXT)
2148                .constraints(tooltip_constraints)
2149                .padding(EdgeInsetsGeometry::ZERO)
2150                .child(waft_widgets::ColoredBox::new(Colors::GREEN.primary()))
2151                .into_widget();
2152            pump_app(
2153                tester,
2154                |app| {
2155                    ThemeData::builder()
2156                        .tooltip_theme(TooltipThemeData::new().constraints(theme_constraints))
2157                        .build(app)
2158                },
2159                |_app| tooltip,
2160            );
2161            ensure_visible_and_fade_in(tester, &key);
2162
2163            let text_ancestor = tester.ancestors(tooltip_text(tester))[0];
2164            assert_eq!(
2165                text_ancestor.size(&tester.cell.borrow()),
2166                Some(tooltip_constraints.biggest())
2167            );
2168        });
2169    }
2170
2171    #[test]
2172    fn custom_tooltip_positioning_position_delegate_parameter() {
2173        test_widgets(|tester| {
2174            pump_app(tester, m3, |_app| {
2175                let position_delegate: TooltipPositionDelegate =
2176                    Rc::new(|context: TooltipPositionContext| {
2177                        // Align on top right of box with bottom left of tooltip.
2178                        Offset::new(
2179                            context.target.dx() + (context.target_size.width() / 2.0),
2180                            context.target.dy()
2181                                - (context.target_size.height() / 2.0)
2182                                - context.tooltip_size.height(),
2183                        )
2184                    });
2185                Center::new()
2186                    .child(
2187                        Tooltip::new()
2188                            .message(TOOLTIP_TEXT)
2189                            .position_delegate(position_delegate)
2190                            .child(SizedBox::new().width(50.0).height(50.0)),
2191                    )
2192                    .into_widget()
2193            });
2194
2195            let at = tooltip_center(tester);
2196            tester.long_press_at(at, 1);
2197            tester.pump_by(Duration::from_secs(1));
2198
2199            expect(tester, &find::text(TOOLTIP_TEXT), finds_one_widget());
2200
2201            let target_center = tooltip_center(tester);
2202            let tooltip_position = rect(tester, tooltip_container(tester)).top_left();
2203
2204            // The tooltip should be positioned at target + (25, -25-32).
2205            assert!((tooltip_position.dx() - (target_center.dx() + 25.0)).abs() <= 5.0);
2206            assert!((tooltip_position.dy() - (target_center.dy() - 25.0 - 32.0)).abs() <= 5.0);
2207        });
2208    }
2209
2210    #[test]
2211    fn tooltip_should_disappear_even_if_mouse_is_hovering_over_the_tooltip_overlay() {
2212        test_widgets(|tester| {
2213            pump_app(tester, m3, |_app| {
2214                Center::new()
2215                    .child(
2216                        Tooltip::new()
2217                            .message(TOOLTIP_TEXT)
2218                            .child(Text::new("Hover me")),
2219                    )
2220                    .into_widget()
2221            });
2222
2223            // Hover over the target widget.
2224            let mut gesture = TestPointer::mouse(1, 0);
2225            tester.add_pointer(&mut gesture, Offset::ZERO);
2226
2227            let target = find::text("Hover me").evaluate(tester)[0];
2228            let at = center(tester, target);
2229            tester.move_to(&mut gesture, at, false);
2230            tester.pump();
2231
2232            // Wait for the tooltip to actually appear.
2233            tester.pump_by(Duration::from_millis(100));
2234            expect(tester, &find::text(TOOLTIP_TEXT), finds_one_widget());
2235
2236            // Move the mouse to the tooltip overlay.
2237            let at = center(tester, tooltip_text(tester));
2238            tester.move_to(&mut gesture, at, false);
2239            tester.pump_and_settle();
2240
2241            // Verify the tooltip overlay is no longer displayed.
2242            assert!(!found(tester, TOOLTIP_TEXT));
2243            tester.send(&gesture, PointerChange::Remove);
2244        });
2245    }
2246    /// `tooltip_test.dart`, "default Tooltip debugFillProperties".
2247    #[test]
2248    fn a_default_tooltip_describes_its_message() {
2249        use waft_foundation::DiagnosticPropertiesBuilder;
2250
2251        let tooltip = Tooltip::new().message("message");
2252        let cell = waft_foundation::AppCell::new();
2253        let app = cell.borrow();
2254        let description: Vec<String> = waft_widgets::testing::describe_properties(
2255            |properties: &mut DiagnosticPropertiesBuilder| {
2256                tooltip.debug_fill_properties(&app, properties)
2257            },
2258        );
2259        assert_eq!(description, ["\"message\""]);
2260    }
2261
2262    /// `tooltip_test.dart`, "default Tooltip debugFillProperties with richMessage".
2263    #[test]
2264    fn a_tooltip_describes_its_rich_message() {
2265        use std::rc::Rc;
2266
2267        use waft_foundation::DiagnosticPropertiesBuilder;
2268
2269        let rich_message: InlineSpanRef = Rc::new(TextSpan::new().text("This is a ").children(
2270            vec![Rc::new(TextSpan::new().text("richMessage")) as InlineSpanRef],
2271        ));
2272        let tooltip = Tooltip::new().rich_message(rich_message);
2273        let cell = waft_foundation::AppCell::new();
2274        let app = cell.borrow();
2275        let description: Vec<String> = waft_widgets::testing::describe_properties(
2276            |properties: &mut DiagnosticPropertiesBuilder| {
2277                tooltip.debug_fill_properties(&app, properties)
2278            },
2279        );
2280        assert_eq!(description, ["\"This is a richMessage\""]);
2281    }
2282
2283    /// `tooltip_test.dart`, "Tooltip implements debugFillProperties". The `positionDelegate`
2284    /// line is left out until that function type has a `Display`.
2285    #[test]
2286    #[allow(deprecated)]
2287    fn a_tooltip_describes_its_properties() {
2288        use std::time::Duration;
2289
2290        use waft_foundation::DiagnosticPropertiesBuilder;
2291        use waft_painting::{BoxDecoration, EdgeInsets};
2292        use waft_widgets::TooltipTriggerMode;
2293
2294        let tooltip = Tooltip::new()
2295            .message("message")
2296            .decoration(BoxDecoration::new())
2297            .wait_duration(Duration::from_secs(1))
2298            .show_duration(Duration::from_secs(2))
2299            .padding(EdgeInsets::ZERO)
2300            .margin(EdgeInsets::all(5.0))
2301            .height(100.0)
2302            .exclude_from_semantics(true)
2303            .prefer_below(false)
2304            .vertical_offset(50.0)
2305            .trigger_mode(TooltipTriggerMode::Manual)
2306            .enable_feedback(true);
2307        let cell = waft_foundation::AppCell::new();
2308        let app = cell.borrow();
2309        let description: Vec<String> = waft_widgets::testing::describe_properties(
2310            |properties: &mut DiagnosticPropertiesBuilder| {
2311                tooltip.debug_fill_properties(&app, properties)
2312            },
2313        );
2314        assert_eq!(
2315            description,
2316            [
2317                "\"message\"".to_string(),
2318                "height: 100.0".to_string(),
2319                "padding: EdgeInsets.zero".to_string(),
2320                "margin: EdgeInsets.all(5.0)".to_string(),
2321                "vertical offset: 50.0".to_string(),
2322                "position: above".to_string(),
2323                "semantics: excluded".to_string(),
2324                "wait duration: 0:00:01.000000".to_string(),
2325                "show duration: 0:00:02.000000".to_string(),
2326                "triggerMode: TooltipTriggerMode.manual".to_string(),
2327                "enableFeedback: true".to_string(),
2328            ]
2329        );
2330    }
2331}