Skip to main content

waft_material/
text_selection_theme.rs

1//! Flutter counterpart: material_ui's `text_selection_theme.dart`.
2
3use waft_embedder::Color;
4use waft_foundation::App;
5use waft_widgets::{
6    BuildContext, DefaultSelectionStyle, InheritedTheme, InheritedWidget, IntoWidget, KeyRef,
7    WidgetRef,
8};
9
10use crate::theme::Theme;
11
12/// Defines the text selection visual properties for descendant `TextField` and
13/// `SelectableText` widgets.
14///
15/// Descendant widgets obtain the current [`TextSelectionThemeData`] object using
16/// [`TextSelectionTheme::of`]. Instances of [`TextSelectionThemeData`] can be customized
17/// with [`TextSelectionThemeData::copy_with`].
18///
19/// Typically a [`TextSelectionThemeData`] is specified as part of the overall `Theme`
20/// with `ThemeData::text_selection_theme`.
21///
22/// See also:
23///
24///  * [`TextSelectionTheme`], an `InheritedWidget` that propagates the theme down its
25///    subtree.
26///  * `InputDecorationThemeData`, which defines most other visual properties of
27///    text fields.
28#[derive(Clone, Debug, Default, PartialEq)]
29pub struct TextSelectionThemeData {
30    /// The color of the cursor in the text field.
31    ///
32    /// The cursor indicates the current location of text insertion point in
33    /// the field.
34    pub cursor_color: Option<Color>,
35
36    /// The background color of selected text.
37    pub selection_color: Option<Color>,
38
39    /// The color of the selection handles on the text field.
40    ///
41    /// Selection handles are used to indicate the bounds of the selected text,
42    /// or as a handle to drag the cursor to a new location in the text.
43    ///
44    /// On iOS `TextField` and `SelectableText` cannot access
45    /// [`selection_handle_color`](Self::selection_handle_color).
46    /// To set the [`selection_handle_color`](Self::selection_handle_color) on iOS, you can
47    /// change the `CupertinoThemeData::selection_handle_color` by wrapping the subtree
48    /// containing your `TextField` or `SelectableText` with a `CupertinoTheme`.
49    pub selection_handle_color: Option<Color>,
50}
51
52impl TextSelectionThemeData {
53    /// Creates the set of properties used to configure `TextField`s; Dart's optional named
54    /// arguments are the fluent setters.
55    pub fn new() -> TextSelectionThemeData {
56        TextSelectionThemeData::default()
57    }
58
59    /// Dart `TextSelectionThemeData(cursorColor:)`.
60    pub fn cursor_color(mut self, cursor_color: Color) -> TextSelectionThemeData {
61        self.cursor_color = Some(cursor_color);
62        self
63    }
64
65    /// Dart `TextSelectionThemeData(selectionColor:)`.
66    pub fn selection_color(mut self, selection_color: Color) -> TextSelectionThemeData {
67        self.selection_color = Some(selection_color);
68        self
69    }
70
71    /// Dart `TextSelectionThemeData(selectionHandleColor:)`.
72    pub fn selection_handle_color(
73        mut self,
74        selection_handle_color: Color,
75    ) -> TextSelectionThemeData {
76        self.selection_handle_color = Some(selection_handle_color);
77        self
78    }
79
80    /// Creates a copy of this object with the given fields replaced with the
81    /// specified values.
82    ///
83    /// Dart's named arguments are the fluent setters on the copy
84    /// (`data.copy_with().cursor_color(color)`).
85    pub fn copy_with(&self) -> TextSelectionThemeData {
86        self.clone()
87    }
88
89    /// Linearly interpolate between two text field themes.
90    ///
91    /// If both arguments are null, then null is returned.
92    ///
93    /// {@macro dart.ui.shadow.lerp}
94    pub fn lerp(
95        a: Option<&TextSelectionThemeData>,
96        b: Option<&TextSelectionThemeData>,
97        t: f64,
98    ) -> Option<TextSelectionThemeData> {
99        match (a, b) {
100            (None, None) => return None,
101            (Some(a), Some(b)) if std::ptr::eq(a, b) => return Some(a.clone()),
102            _ => {}
103        }
104        Some(TextSelectionThemeData {
105            cursor_color: Color::lerp(
106                a.and_then(|a| a.cursor_color),
107                b.and_then(|b| b.cursor_color),
108                t,
109            ),
110            selection_color: Color::lerp(
111                a.and_then(|a| a.selection_color),
112                b.and_then(|b| b.selection_color),
113                t,
114            ),
115            selection_handle_color: Color::lerp(
116                a.and_then(|a| a.selection_handle_color),
117                b.and_then(|b| b.selection_handle_color),
118                t,
119            ),
120        })
121    }
122}
123
124/// An inherited widget that defines the appearance of text selection in
125/// this widget's subtree.
126///
127/// Values specified here are used for `TextField` and `SelectableText`
128/// properties that are not given an explicit non-null value.
129///
130/// Here is an example of a text selection theme that applies a blue cursor
131/// color with light blue selection handles to the child text field.
132///
133/// ```text
134/// TextSelectionTheme::new(
135///     TextSelectionThemeData::new()
136///         .cursor_color(Colors::BLUE.primary())
137///         .selection_handle_color(Colors::LIGHT_BLUE.primary()),
138///     TextField::new(),
139/// )
140/// ```
141///
142/// This widget also creates a [`DefaultSelectionStyle`] for its subtree with
143/// [`data`](Self::data).
144#[derive(Debug)]
145pub struct TextSelectionTheme {
146    pub key: Option<KeyRef>,
147    /// The properties for descendant `TextField` and `SelectableText` widgets.
148    pub data: TextSelectionThemeData,
149    // Dart's `child` getter inserts the `DefaultSelectionStyle` into the subtree; here the
150    // inserted widget is built by the constructor and held, as `InheritedWidget::child`
151    // answers a reference.
152    child: WidgetRef,
153}
154
155impl TextSelectionTheme {
156    /// Creates a text selection theme widget that specifies the text
157    /// selection properties for all widgets below it in the widget tree.
158    #[cfg_attr(debug_assertions, track_caller)]
159    pub fn new<K>(data: TextSelectionThemeData, child: impl IntoWidget<K>) -> TextSelectionTheme {
160        let mut default_selection_style = DefaultSelectionStyle::new(child);
161        if let Some(selection_color) = data.selection_color {
162            default_selection_style = default_selection_style.selection_color(selection_color);
163        }
164        if let Some(cursor_color) = data.cursor_color {
165            default_selection_style = default_selection_style.cursor_color(cursor_color);
166        }
167        TextSelectionTheme {
168            key: None,
169            data,
170            child: default_selection_style.into_widget(),
171        }
172    }
173
174    /// Dart `TextSelectionTheme(key:)`.
175    pub fn key(mut self, key: KeyRef) -> TextSelectionTheme {
176        self.key = Some(key);
177        self
178    }
179
180    /// Returns the [`data`](Self::data) from the closest [`TextSelectionTheme`] ancestor. If
181    /// there is no ancestor, it returns `ThemeData::text_selection_theme`.
182    /// Applications can assume that the returned value will not be null.
183    ///
184    /// Typical usage is as follows:
185    ///
186    /// ```text
187    /// let theme = TextSelectionTheme::of(app, context);
188    /// ```
189    pub fn of(app: &mut App, context: BuildContext) -> TextSelectionThemeData {
190        match context.depend_on_inherited_widget_of_exact_type::<TextSelectionTheme>(app) {
191            Some(selection_theme) => selection_theme.data.clone(),
192            None => Theme::of(app, context).text_selection_theme.clone(),
193        }
194    }
195}
196
197impl InheritedTheme for TextSelectionTheme {
198    fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
199        TextSelectionTheme::new(self.data.clone(), child).into_widget()
200    }
201}
202
203impl InheritedWidget for TextSelectionTheme {
204    fn key(&self) -> Option<&KeyRef> {
205        self.key.as_ref()
206    }
207
208    fn child(&self) -> &WidgetRef {
209        &self.child
210    }
211
212    fn update_should_notify(&self, old_widget: &TextSelectionTheme) -> bool {
213        self.data != old_widget.data
214    }
215
216    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
217        Some(self)
218    }
219}
220
221impl waft_foundation::Diagnosticable for TextSelectionThemeData {
222    fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
223        properties.add(
224            waft_painting::ColorProperty::new("cursorColor", self.cursor_color).default_value(None),
225        );
226        properties.add(
227            waft_painting::ColorProperty::new("selectionColor", self.selection_color)
228                .default_value(None),
229        );
230        properties.add(
231            waft_painting::ColorProperty::new("selectionHandleColor", self.selection_handle_color)
232                .default_value(None),
233        );
234    }
235}
236
237impl std::fmt::Display for TextSelectionThemeData {
238    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
239        f.write_str(&waft_foundation::Diagnosticable::to_string(self))
240    }
241}
242
243#[cfg(test)]
244mod tests {
245    use std::cell::RefCell;
246    use std::rc::Rc;
247
248    use waft_painting::AnyColor;
249    use waft_widgets::{Builder, SizedBox};
250
251    use waft_widgets::testing::test_widgets;
252
253    use super::*;
254    use crate::colors::Colors;
255    use crate::test_support::probe;
256    use crate::theme_data::ThemeData;
257
258    fn any(color: Color) -> AnyColor {
259        AnyColor::new(color)
260    }
261
262    #[test]
263    fn text_selection_theme_data_copy_with_and_equality_basics() {
264        assert_eq!(
265            TextSelectionThemeData::new(),
266            TextSelectionThemeData::new().copy_with()
267        );
268    }
269
270    #[test]
271    fn text_selection_theme_data_lerp_special_cases() {
272        assert_eq!(TextSelectionThemeData::lerp(None, None, 0.0), None);
273        let data = TextSelectionThemeData::new();
274        assert_eq!(
275            TextSelectionThemeData::lerp(Some(&data), Some(&data), 0.5),
276            Some(data)
277        );
278    }
279
280    #[test]
281    fn text_selection_theme_data_lerps_each_color() {
282        let a = TextSelectionThemeData::new().cursor_color(Colors::BLACK);
283        let b = TextSelectionThemeData::new()
284            .cursor_color(Colors::WHITE)
285            .selection_color(Color::new(0x88888888));
286
287        let lerped = TextSelectionThemeData::lerp(Some(&a), Some(&b), 0.5).expect("both given");
288
289        assert_eq!(
290            lerped.cursor_color,
291            Color::lerp(Some(Colors::BLACK), Some(Colors::WHITE), 0.5)
292        );
293        assert_eq!(
294            lerped.selection_color,
295            Color::lerp(None, Some(Color::new(0x88888888)), 0.5)
296        );
297        assert_eq!(lerped.selection_handle_color, None);
298    }
299
300    #[test]
301    fn text_selection_theme_data_null_fields_by_default() {
302        let theme = TextSelectionThemeData::new();
303        assert_eq!(theme.cursor_color, None);
304        assert_eq!(theme.selection_color, None);
305        assert_eq!(theme.selection_handle_color, None);
306    }
307
308    #[test]
309    fn text_selection_theme_data_copy_with_replaces_given_fields() {
310        let theme = TextSelectionThemeData::new().cursor_color(Colors::RED.primary());
311
312        let copy = theme.copy_with().selection_color(Colors::BLUE.primary());
313
314        assert_eq!(copy.cursor_color, Some(Colors::RED.primary()));
315        assert_eq!(copy.selection_color, Some(Colors::BLUE.primary()));
316        assert_ne!(copy, theme);
317    }
318
319    #[test]
320    fn cursor_color() {
321        assert_eq!(
322            TextSelectionThemeData::new()
323                .cursor_color(Colors::RED.primary())
324                .cursor_color,
325            Some(Colors::RED.primary())
326        );
327    }
328
329    #[test]
330    fn text_selection_theme_overrides_default_selection_style() {
331        test_widgets(|tester| {
332            const THEME_SELECTION_COLOR: Color = Color::new(0xffaabbcc);
333            const THEME_CURSOR_COLOR: Color = Color::new(0x00ccbbaa);
334            const DEFAULT_SELECTION_COLOR: Color = Color::new(0xffaa1111);
335            const DEFAULT_CURSOR_COLOR: Color = Color::new(0x00cc2222);
336            type Seen = Rc<RefCell<Option<DefaultSelectionStyle>>>;
337            let outer: Seen = Rc::default();
338            let inner: Seen = Rc::default();
339            let recording = |seen: &Seen, child: Option<WidgetRef>| {
340                let seen = Rc::clone(seen);
341                Builder::new(move |app, context| {
342                    *seen.borrow_mut() = Some(DefaultSelectionStyle::of(app, context));
343                    child
344                        .clone()
345                        .unwrap_or_else(|| SizedBox::shrink().into_widget())
346                })
347                .into_widget()
348            };
349            let theme = TextSelectionTheme::new(
350                TextSelectionThemeData::new()
351                    .selection_color(THEME_SELECTION_COLOR)
352                    .cursor_color(THEME_CURSOR_COLOR),
353                recording(&inner, None),
354            );
355            let root = DefaultSelectionStyle::new(recording(&outer, Some(theme.into_widget())))
356                .selection_color(DEFAULT_SELECTION_COLOR)
357                .cursor_color(DEFAULT_CURSOR_COLOR)
358                .into_widget();
359
360            tester.pump_widget(root);
361
362            let style = outer.borrow_mut().take().expect("the outer probe built");
363            assert_eq!(style.selection_color, Some(any(DEFAULT_SELECTION_COLOR)));
364            assert_eq!(style.cursor_color, Some(any(DEFAULT_CURSOR_COLOR)));
365            let style = inner.borrow_mut().take().expect("the inner probe built");
366            assert_eq!(style.selection_color, Some(any(THEME_SELECTION_COLOR)));
367            assert_eq!(style.cursor_color, Some(any(THEME_CURSOR_COLOR)));
368        });
369    }
370
371    #[test]
372    fn of_returns_the_theme_data_text_selection_theme_without_an_ancestor() {
373        test_widgets(|tester| {
374            let theme_data_selection = TextSelectionThemeData::new()
375                .cursor_color(Color::new(0xffaabbcc))
376                .selection_handle_color(Color::new(0x00ccbbaa));
377            let expected = theme_data_selection.clone();
378
379            let seen = probe(
380                tester,
381                move |app, child| {
382                    let data = ThemeData::builder()
383                        .text_selection_theme(theme_data_selection.clone())
384                        .build(app);
385                    Theme::new(data, child).into_widget()
386                },
387                TextSelectionTheme::of,
388            );
389
390            assert_eq!(seen, expected);
391        });
392    }
393
394    #[test]
395    fn of_returns_the_closest_text_selection_theme_over_theme_data() {
396        test_widgets(|tester| {
397            let widget_selection = TextSelectionThemeData::new()
398                .cursor_color(Color::new(0xffddeeff))
399                .selection_color(Color::new(0x44444444))
400                .selection_handle_color(Color::new(0x00ffeedd));
401            let expected = widget_selection.clone();
402
403            let seen = probe(
404                tester,
405                move |app, child| {
406                    let data = ThemeData::builder()
407                        .text_selection_theme(
408                            TextSelectionThemeData::new().cursor_color(Color::new(0xffaabbcc)),
409                        )
410                        .build(app);
411                    Theme::new(
412                        data,
413                        TextSelectionTheme::new(widget_selection.clone(), child),
414                    )
415                    .into_widget()
416                },
417                TextSelectionTheme::of,
418            );
419
420            assert_eq!(seen, expected);
421        });
422    }
423    // Flutter's "Default TextSelectionThemeData debugFillProperties".
424    #[test]
425    fn a_text_selection_theme_data_describes_nothing_by_default() {
426        assert_eq!(
427            waft_widgets::testing::describe_properties(|properties| {
428                waft_foundation::Diagnosticable::debug_fill_properties(
429                    &TextSelectionThemeData::new(),
430                    properties,
431                )
432            }),
433            Vec::<String>::new()
434        );
435    }
436}