Skip to main content

waft_widgets/widgets/
default_selection_style.rs

1//! Flutter counterpart: `widgets/default_selection_style.dart`.
2
3use waft_embedder::Color;
4use waft_foundation::App;
5use waft_painting::AnyColor;
6use waft_services::MouseCursorRef;
7
8use crate::framework::{
9    BuildContext, InheritedWidget, IntoWidget, KeyRef, StatelessWidget, WidgetRef,
10};
11use crate::widgets::basic::Builder;
12use crate::widgets::inherited_theme::InheritedTheme;
13
14/// The default cursor and selection color (semi-transparent grey) for the current platform.
15///
16/// The selection color is used by `Text` widgets in a `SelectionArea` and by editable text
17/// widgets that read this style.
18///
19/// See also:
20///
21///  * `DefaultTextStyle`, which provides the default text style.
22#[derive(Debug)]
23pub struct DefaultSelectionStyle {
24    /// See [`InheritedWidget::key`].
25    pub key: Option<KeyRef>,
26    /// The default cursor color.
27    pub cursor_color: Option<AnyColor>,
28    /// The default selection color.
29    pub selection_color: Option<AnyColor>,
30    /// The [`MouseCursor`](waft_services::MouseCursor) for mouse pointers hovering over
31    /// selectable Text widgets.
32    ///
33    /// If this property is `None`, `SystemMouseCursors::text` will be used.
34    pub mouse_cursor: Option<MouseCursorRef>,
35    /// The widget below this widget in the tree.
36    pub child: WidgetRef,
37}
38
39impl DefaultSelectionStyle {
40    /// The default color.
41    pub const DEFAULT_COLOR: Color = Color::new(0x80808080);
42
43    /// Creates a default selection style widget that specifies the selection properties for
44    /// all widgets below it in the widget tree; Dart's optional named arguments are the
45    /// setters.
46    #[cfg_attr(debug_assertions, track_caller)]
47    pub fn new<K>(child: impl IntoWidget<K>) -> DefaultSelectionStyle {
48        DefaultSelectionStyle {
49            key: None,
50            cursor_color: None,
51            selection_color: None,
52            mouse_cursor: None,
53            child: child.into_widget(),
54        }
55    }
56
57    /// A const-constructable default selection style that provides fallback values
58    /// (`None`).
59    ///
60    /// Returned from [`of`](Self::of) when the given [`BuildContext`] doesn't have an
61    /// enclosing default selection style.
62    ///
63    /// This constructor creates a [`DefaultSelectionStyle`] with an invalid `child`, which
64    /// means the constructed value cannot be incorporated into the tree.
65    pub fn fallback() -> DefaultSelectionStyle {
66        DefaultSelectionStyle::new(NullWidget)
67    }
68
69    /// Dart `DefaultSelectionStyle(key:)`.
70    pub fn key(mut self, key: KeyRef) -> DefaultSelectionStyle {
71        self.key = Some(key);
72        self
73    }
74
75    /// Dart `DefaultSelectionStyle(cursorColor:)`.
76    pub fn cursor_color(mut self, cursor_color: impl Into<AnyColor>) -> DefaultSelectionStyle {
77        self.cursor_color = Some(cursor_color.into());
78        self
79    }
80
81    /// Dart `DefaultSelectionStyle(selectionColor:)`.
82    pub fn selection_color(
83        mut self,
84        selection_color: impl Into<AnyColor>,
85    ) -> DefaultSelectionStyle {
86        self.selection_color = Some(selection_color.into());
87        self
88    }
89
90    /// Dart `DefaultSelectionStyle(mouseCursor:)`.
91    pub fn mouse_cursor(mut self, mouse_cursor: MouseCursorRef) -> DefaultSelectionStyle {
92        self.mouse_cursor = Some(mouse_cursor);
93        self
94    }
95
96    /// Creates a default selection style that overrides the selection styles in scope at
97    /// this point in the widget tree.
98    ///
99    /// Any arguments that are not `None` replace the corresponding properties on the
100    /// ambient default selection style. Dart's optional named arguments are the setters of
101    /// the [`DefaultSelectionStyleMerge`] this returns.
102    #[cfg_attr(debug_assertions, track_caller)]
103    pub fn merge<K>(child: impl IntoWidget<K>) -> DefaultSelectionStyleMerge {
104        DefaultSelectionStyleMerge {
105            key: None,
106            cursor_color: None,
107            selection_color: None,
108            mouse_cursor: None,
109            child: child.into_widget(),
110        }
111    }
112
113    /// The closest instance of this class that encloses the given context.
114    ///
115    /// If no such instance exists, this method will return
116    /// [`fallback`](Self::fallback).
117    pub fn of(app: &mut App, context: BuildContext) -> DefaultSelectionStyle {
118        match context.depend_on_inherited_widget_of_exact_type::<DefaultSelectionStyle>(app) {
119            Some(style) => DefaultSelectionStyle {
120                key: style.key.clone(),
121                cursor_color: style.cursor_color.clone(),
122                selection_color: style.selection_color.clone(),
123                mouse_cursor: style.mouse_cursor.clone(),
124                child: style.child.clone(),
125            },
126            None => DefaultSelectionStyle::fallback(),
127        }
128    }
129}
130
131/// Dart's `mouseCursor != oldWidget.mouseCursor` over two optional cursors.
132fn cursors_differ(a: &Option<MouseCursorRef>, b: &Option<MouseCursorRef>) -> bool {
133    match (a, b) {
134        (None, None) => false,
135        (Some(a), Some(b)) => **a != **b,
136        _ => true,
137    }
138}
139
140impl InheritedTheme for DefaultSelectionStyle {
141    fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
142        DefaultSelectionStyle {
143            key: None,
144            cursor_color: self.cursor_color.clone(),
145            selection_color: self.selection_color.clone(),
146            mouse_cursor: self.mouse_cursor.clone(),
147            child,
148        }
149        .into_widget()
150    }
151}
152
153impl InheritedWidget for DefaultSelectionStyle {
154    fn key(&self) -> Option<&KeyRef> {
155        self.key.as_ref()
156    }
157
158    fn child(&self) -> &WidgetRef {
159        &self.child
160    }
161
162    fn update_should_notify(&self, old_widget: &DefaultSelectionStyle) -> bool {
163        self.cursor_color != old_widget.cursor_color
164            || self.selection_color != old_widget.selection_color
165            || cursors_differ(&self.mouse_cursor, &old_widget.mouse_cursor)
166    }
167
168    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
169        Some(self)
170    }
171}
172
173/// Dart's `DefaultSelectionStyle.merge(..)` before its optional arguments are known: a
174/// `Builder` that merges them into the ambient [`DefaultSelectionStyle`].
175#[derive(Debug)]
176pub struct DefaultSelectionStyleMerge {
177    key: Option<KeyRef>,
178    cursor_color: Option<AnyColor>,
179    selection_color: Option<AnyColor>,
180    mouse_cursor: Option<MouseCursorRef>,
181    child: WidgetRef,
182}
183
184impl DefaultSelectionStyleMerge {
185    /// Dart `DefaultSelectionStyle.merge(key:)`.
186    pub fn key(mut self, key: KeyRef) -> DefaultSelectionStyleMerge {
187        self.key = Some(key);
188        self
189    }
190
191    /// Dart `DefaultSelectionStyle.merge(cursorColor:)`.
192    pub fn cursor_color(mut self, cursor_color: impl Into<AnyColor>) -> DefaultSelectionStyleMerge {
193        self.cursor_color = Some(cursor_color.into());
194        self
195    }
196
197    /// Dart `DefaultSelectionStyle.merge(selectionColor:)`.
198    pub fn selection_color(
199        mut self,
200        selection_color: impl Into<AnyColor>,
201    ) -> DefaultSelectionStyleMerge {
202        self.selection_color = Some(selection_color.into());
203        self
204    }
205
206    /// Dart `DefaultSelectionStyle.merge(mouseCursor:)`.
207    pub fn mouse_cursor(mut self, mouse_cursor: MouseCursorRef) -> DefaultSelectionStyleMerge {
208        self.mouse_cursor = Some(mouse_cursor);
209        self
210    }
211}
212
213/// The kind tag of [`IntoWidget`] for a [`DefaultSelectionStyleMerge`].
214pub struct DefaultSelectionStyleMergeKind;
215
216impl IntoWidget<DefaultSelectionStyleMergeKind> for DefaultSelectionStyleMerge {
217    #[cfg_attr(debug_assertions, track_caller)]
218    fn into_widget(self) -> WidgetRef {
219        Builder::new(move |app, context| {
220            let parent = DefaultSelectionStyle::of(app, context);
221            DefaultSelectionStyle {
222                key: self.key.clone(),
223                cursor_color: self.cursor_color.clone().or(parent.cursor_color),
224                selection_color: self.selection_color.clone().or(parent.selection_color),
225                mouse_cursor: self.mouse_cursor.clone().or(parent.mouse_cursor),
226                child: self.child.clone(),
227            }
228            .into_widget()
229        })
230        .into_widget()
231    }
232}
233
234/// Dart's `_NullWidget`: the child of [`DefaultSelectionStyle::fallback`], which must never
235/// build.
236#[derive(Debug)]
237struct NullWidget;
238
239impl StatelessWidget for NullWidget {
240    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
241        panic!(
242            "A DefaultSelectionStyle constructed with DefaultSelectionStyle.fallback cannot be \
243             incorporated into the widget tree, it is meant only to provide a fallback value \
244             returned by DefaultSelectionStyle.of() when no enclosing default selection style \
245             is present in a BuildContext."
246        );
247    }
248}
249
250#[cfg(test)]
251mod tests {
252    use std::cell::RefCell;
253    use std::rc::Rc;
254
255    use waft_foundation::AppCell;
256
257    use super::*;
258    use crate::test_harness::Harness;
259    use crate::widgets::basic::SizedBox;
260
261    fn reader(seen: &Rc<RefCell<Option<DefaultSelectionStyle>>>) -> WidgetRef {
262        let seen = Rc::clone(seen);
263        Builder::new(move |app, context| {
264            *seen.borrow_mut() = Some(DefaultSelectionStyle::of(app, context));
265            SizedBox::shrink().into_widget()
266        })
267        .into_widget()
268    }
269
270    /// Without an ancestor, `of` is the fallback; `merge` keeps what it leaves unset and
271    /// replaces what it sets.
272    #[test]
273    fn of_falls_back_and_merge_overrides_only_what_it_sets() {
274        let cell = AppCell::new();
275        let mut app = cell.borrow_mut();
276        let seen: Rc<RefCell<Option<DefaultSelectionStyle>>> = Rc::default();
277        let harness = Harness::mount(&mut app, reader(&seen));
278        harness.pump(&mut app);
279        let fallback = seen.borrow_mut().take().expect("built");
280        assert!(fallback.cursor_color.is_none() && fallback.selection_color.is_none());
281
282        let red = Color::new(0xFFFF0000);
283        let blue = Color::new(0xFF0000FF);
284        harness.set_child(
285            &mut app,
286            DefaultSelectionStyle::new(
287                DefaultSelectionStyle::merge(reader(&seen)).selection_color(blue),
288            )
289            .cursor_color(red)
290            .selection_color(red)
291            .into_widget(),
292        );
293        harness.pump(&mut app);
294        let merged = seen.borrow_mut().take().expect("built");
295        assert_eq!(merged.cursor_color, Some(AnyColor::new(red)));
296        assert_eq!(merged.selection_color, Some(AnyColor::new(blue)));
297    }
298
299    /// A [`DefaultSelectionStyle`] is an [`InheritedTheme`]: a capture carries it.
300    #[test]
301    fn a_capture_carries_the_selection_style() {
302        let cell = AppCell::new();
303        let mut app = cell.borrow_mut();
304        let context: Rc<RefCell<Option<BuildContext>>> = Rc::default();
305        let tree = {
306            let context = Rc::clone(&context);
307            DefaultSelectionStyle::new(Builder::new(move |_app, builder_context| {
308                *context.borrow_mut() = Some(builder_context);
309                SizedBox::shrink().into_widget()
310            }))
311            .cursor_color(Color::new(0xFF00FF00))
312        };
313        let harness = Harness::mount(&mut app, tree.into_widget());
314        harness.pump(&mut app);
315        let from = context.borrow().expect("built");
316        let seen: Rc<RefCell<Option<DefaultSelectionStyle>>> = Rc::default();
317        let child = <dyn InheritedTheme>::capture_all(&app, from, reader(&seen), None);
318        let route = Harness::mount(&mut app, child);
319        route.pump(&mut app);
320        assert_eq!(
321            seen.borrow().as_ref().expect("built").cursor_color,
322            Some(AnyColor::new(Color::new(0xFF00FF00)))
323        );
324    }
325}