masonry 0.5.0

Traits and types of the Masonry toolkit.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
// Copyright 2018 the Xilem Authors and the Druid Authors
// SPDX-License-Identifier: Apache-2.0

use std::any::TypeId;

use accesskit::{Node, Role};
use tracing::{Span, trace_span};

use crate::TextAlign;
use crate::core::{
    AccessCtx, ArcStr, ChildrenIds, EventCtx, LayoutCtx, MeasureCtx, NewWidget, NoAction, PaintCtx,
    PointerButton, PointerButtonEvent, PointerEvent, PrePaintProps, PropertiesMut, PropertiesRef,
    RegisterCtx, TextEvent, Update, UpdateCtx, UsesProperty, Widget, WidgetId, WidgetMut,
    WidgetPod, paint_background, paint_border, paint_box_shadow,
};
use crate::imaging::Painter;
use crate::kurbo::{Axis, Point, Size};
use crate::layout::{LayoutSize, LenReq, Length};
use crate::properties::{CaretColor, ContentColor, LineBreaking, PlaceholderColor, SelectionColor};
use crate::widgets::{Label, TextArea};

/// The text input widget displays text which can be edited by the user,
/// inside a surrounding box.
///
/// This currently does not support newlines entered by the user,
/// although pre-existing newlines are handled correctly.
///
/// This widget itself does not emit any actions.
/// However, the child widget will do so, as it is user editable.
/// The ID of the child can be accessed using [`area_pod`](Self::area_pod).
///
/// At runtime, most properties of the text will be set using [`text_mut`](Self::text_mut).
/// This is because `TextInput` largely serves as a wrapper around a [`TextArea`].
///
/// # Classes
///
/// When the window is not focused, this widget will have the `#unfocused` [class].
///
/// [class]: masonry_core::doc::masonry_concepts#classes
pub struct TextInput {
    text: WidgetPod<TextArea<true>>,

    // TODO: We want placeholder to match wordwrap property of main text.
    // TODO: We want placeholder to clip even when wordwrap is enabled.
    placeholder: WidgetPod<Label>,
    placeholder_text: ArcStr,

    /// The text alignment for both the text area and placeholder.
    text_alignment: TextAlign,

    /// Whether to clip the contained text.
    clip: bool,
}

// --- MARK: BUILDERS
impl TextInput {
    /// Creates a new `TextInput` with the given text.
    ///
    /// To use non-default text properties, use [`from_text_area`](Self::from_text_area) instead.
    pub fn new(text: &str) -> Self {
        Self::from_text_area(TextArea::new_editable(text).prepare())
    }

    /// Creates a new `TextInput` from a styled text area.
    pub fn from_text_area(text: NewWidget<TextArea<true>>) -> Self {
        Self {
            text: text.to_pod(),
            placeholder: Label::new("")
                .accessibility_hidden(true)
                .prepare()
                .with_props(LineBreaking::Clip)
                .to_pod(),
            placeholder_text: "".into(),
            text_alignment: TextAlign::default(),
            clip: false,
        }
    }

    /// Sets the text alignment for both the input text and placeholder.
    pub fn with_text_alignment(mut self, text_alignment: TextAlign) -> Self {
        self.text_alignment = text_alignment;
        self
    }

    /// The text that will be displayed when this input is empty.
    ///
    /// To modify this on active text input, use [`set_placeholder`](Self::set_placeholder).
    pub fn with_placeholder(mut self, placeholder_text: impl Into<ArcStr>) -> Self {
        let placeholder_text = placeholder_text.into();
        let label = Label::new(placeholder_text.clone()).with_text_alignment(self.text_alignment);
        self.placeholder = label
            .accessibility_hidden(true)
            .prepare()
            .with_props(LineBreaking::Clip)
            .to_pod();
        self.placeholder_text = placeholder_text;
        self
    }

    /// Whether to clip the text to the drawn boundaries.
    ///
    /// If this is set to true, it is recommended, but not required, that this
    /// wraps a text area with [word wrapping](TextArea::with_word_wrap) enabled.
    ///
    /// To modify this on active text input, use [`set_clip`](Self::set_clip).
    pub fn with_clip(mut self, clip: bool) -> Self {
        self.clip = clip;
        self
    }
}

// --- MARK: METHODS
impl TextInput {
    /// Reads the underlying text area.
    ///
    /// Useful for getting its ID, as most actions from the text input will be sent by the child.
    pub fn area_pod(&self) -> &WidgetPod<TextArea<true>> {
        &self.text
    }
}

// --- MARK: WIDGETMUT
impl TextInput {
    /// Edits the underlying text area.
    ///
    /// Used to modify most properties of the text.
    pub fn text_mut<'t>(this: &'t mut WidgetMut<'_, Self>) -> WidgetMut<'t, TextArea<true>> {
        this.ctx.get_mut(&mut this.widget.text)
    }

    /// Edits the child label representing the placeholder text.
    pub fn placeholder_mut<'t>(this: &'t mut WidgetMut<'_, Self>) -> WidgetMut<'t, Label> {
        this.ctx.get_mut(&mut this.widget.placeholder)
    }

    /// The text that will be displayed when this input is empty.
    ///
    /// The runtime equivalent of [`with_placeholder`](Self::with_placeholder).
    pub fn set_placeholder(this: &mut WidgetMut<'_, Self>, placeholder_text: impl Into<ArcStr>) {
        let placeholder_text = placeholder_text.into();
        this.widget.placeholder_text = placeholder_text.clone();
        Label::set_text(&mut Self::placeholder_mut(this), placeholder_text.clone());
        TextArea::set_placeholder(&mut Self::text_mut(this), placeholder_text);
    }

    /// Whether to clip the text to the drawn boundaries.
    ///
    /// If this is set to true, it is recommended, but not required, that this
    /// wraps a text area with [word wrapping](TextArea::set_word_wrap) enabled.
    ///
    /// The runtime equivalent of [`with_clip`](Self::with_clip).
    pub fn set_clip(this: &mut WidgetMut<'_, Self>, clip: bool) {
        this.widget.clip = clip;
        this.ctx.request_layout();
    }

    /// Sets the text alignment for both the input text and placeholder.
    pub fn set_text_alignment(this: &mut WidgetMut<'_, Self>, text_alignment: TextAlign) {
        this.widget.text_alignment = text_alignment;
        TextArea::set_text_alignment(&mut Self::text_mut(this), text_alignment);
        Label::set_text_alignment(&mut Self::placeholder_mut(this), text_alignment);
    }
}

impl UsesProperty<CaretColor> for TextInput {}
impl UsesProperty<PlaceholderColor> for TextInput {}
impl UsesProperty<SelectionColor> for TextInput {}

// --- MARK: IMPL WIDGET
impl Widget for TextInput {
    type Action = NoAction;

    fn on_pointer_event(
        &mut self,
        ctx: &mut EventCtx<'_>,
        _props: &mut PropertiesMut<'_>,
        event: &PointerEvent,
    ) {
        match event {
            PointerEvent::Down(PointerButtonEvent {
                button: None | Some(PointerButton::Primary),
                ..
            }) => {
                // If the user clicks the padding area around the text,
                // we still want to focus the text area.
                ctx.set_focus(self.text.id());
            }
            _ => {}
        }
    }

    fn on_text_event(
        &mut self,
        ctx: &mut EventCtx<'_>,
        _props: &mut PropertiesMut<'_>,
        event: &TextEvent,
    ) {
        match event {
            TextEvent::WindowFocusChange(focused) => {
                if *focused {
                    ctx.remove_class("#unfocused");
                } else {
                    ctx.add_class("#unfocused");
                }
            }
            _ => {}
        }
    }

    fn register_children(&mut self, ctx: &mut RegisterCtx<'_>) {
        ctx.register_child(&mut self.text);
        ctx.register_child(&mut self.placeholder);
    }

    fn property_changed(&mut self, ctx: &mut UpdateCtx<'_>, property_type: TypeId) {
        // FIXME - Find more elegant way to propagate property to child.
        if property_type == TypeId::of::<CaretColor>() {
            ctx.mutate_self_later(|mut input| {
                let mut input = input.downcast::<Self>();
                let color = *input.get_prop::<CaretColor>();
                let mut text_area = Self::text_mut(&mut input);
                text_area.insert_prop(color);
            });
        } else if property_type == TypeId::of::<SelectionColor>() {
            ctx.mutate_self_later(|mut input| {
                let mut input = input.downcast::<Self>();
                let color = *input.get_prop::<SelectionColor>();
                let mut text_area = Self::text_mut(&mut input);
                text_area.insert_prop(color);
            });
        } else if property_type == TypeId::of::<PlaceholderColor>() {
            ctx.mutate_self_later(|mut input| {
                let mut input = input.downcast::<Self>();
                let color = input.get_prop::<PlaceholderColor>().color;
                let mut label = Self::placeholder_mut(&mut input);
                label.insert_prop(ContentColor::new(color));
            });
        }
    }

    fn update(&mut self, ctx: &mut UpdateCtx<'_>, _props: &mut PropertiesMut<'_>, event: &Update) {
        match event {
            Update::WidgetAdded => {
                // FIXME - Find more elegant way to propagate property to child.
                ctx.mutate_self_later(|mut input| {
                    let mut input = input.downcast::<Self>();
                    let color = *input.get_prop::<CaretColor>();
                    let mut text_area = Self::text_mut(&mut input);
                    text_area.insert_prop(color);
                });
                ctx.mutate_self_later(|mut input| {
                    let mut input = input.downcast::<Self>();
                    let color = *input.get_prop::<SelectionColor>();
                    let mut text_area = Self::text_mut(&mut input);
                    text_area.insert_prop(color);
                });
                ctx.mutate_self_later(|mut input| {
                    let mut input = input.downcast::<Self>();
                    let color = input.get_prop::<PlaceholderColor>().color;
                    let mut label = Self::placeholder_mut(&mut input);
                    label.insert_prop(ContentColor::new(color));
                });
                ctx.mutate_self_later(|mut input| {
                    let mut input = input.downcast::<Self>();
                    let placeholder_text = input.widget.placeholder_text.clone();
                    TextArea::set_placeholder(&mut Self::text_mut(&mut input), placeholder_text);
                });
            }
            // We check for `ChildFocusChanged` instead of `FocusChanged`
            // because the actual widget that receives focus is the child `TextArea`
            Update::ChildFocusChanged(_) => {
                ctx.request_pre_paint();
            }
            _ => {}
        }
    }

    fn measure(
        &mut self,
        ctx: &mut MeasureCtx<'_>,
        _props: &PropertiesRef<'_>,
        axis: Axis,
        len_req: LenReq,
        cross_length: Option<Length>,
    ) -> Length {
        match len_req {
            LenReq::MaxContent | LenReq::MinContent => {
                let auto_length = len_req.into();
                let context_size = LayoutSize::maybe(axis.cross(), cross_length);

                ctx.compute_length(
                    &mut self.text,
                    auto_length,
                    context_size,
                    axis,
                    cross_length,
                )
            }
            // We always want to use all the offered space,
            // even on the block axis as we have multi-line display.
            LenReq::FitContent(space) => space,
        }
    }

    fn layout(&mut self, ctx: &mut LayoutCtx<'_>, _props: &PropertiesRef<'_>, size: Size) {
        ctx.run_layout(&mut self.text, size);

        let child_origin = Point::ORIGIN;
        ctx.place_child(&mut self.text, child_origin);

        ctx.derive_baselines(&self.text);

        let text_is_empty = ctx.get_raw(&mut self.text).0.is_empty();
        ctx.set_stashed(&mut self.placeholder, !text_is_empty);
        if text_is_empty {
            ctx.run_layout(&mut self.placeholder, size);
            ctx.place_child(&mut self.placeholder, child_origin);
        }

        if self.clip {
            ctx.set_clip_path(size.to_rect());
        } else {
            ctx.clear_clip_path();
        }
    }

    fn pre_paint(
        &mut self,
        ctx: &mut PaintCtx<'_>,
        props: &PropertiesRef<'_>,
        painter: &mut Painter<'_>,
    ) {
        let bbox = ctx.border_box();
        let cache = ctx.property_cache();
        let p = PrePaintProps::fetch(props, cache);

        paint_box_shadow(painter, bbox, p.box_shadow, p.corner_radius);
        paint_background(painter, bbox, p.background, p.border_width, p.corner_radius);
        paint_border(
            painter,
            bbox,
            p.border_color,
            p.border_width,
            p.corner_radius,
        );
    }

    fn paint(
        &mut self,
        _ctx: &mut PaintCtx<'_>,
        _props: &PropertiesRef<'_>,
        _painter: &mut Painter<'_>,
    ) {
    }

    fn accessibility_role(&self) -> Role {
        Role::GenericContainer
    }

    fn accessibility(
        &mut self,
        _ctx: &mut AccessCtx<'_>,
        _props: &PropertiesRef<'_>,
        _node: &mut Node,
    ) {
    }

    fn children_ids(&self) -> ChildrenIds {
        ChildrenIds::from_slice(&[self.text.id(), self.placeholder.id()])
    }

    fn make_trace_span(&self, id: WidgetId) -> Span {
        trace_span!("TextInput", id = id.trace())
    }

    fn get_debug_text(&self) -> Option<String> {
        self.clip.then(|| "(clip)".into())
    }
}

// --- MARK: TESTS
// TODO - Add more tests
#[cfg(test)]
mod tests {
    use masonry_testing::TestHarnessParams;

    use super::*;
    use crate::core::{StyleProperty, TextEvent, WidgetTag};
    use crate::dpi::LogicalSize;
    use crate::testing::{TestHarness, assert_render_snapshot};
    use crate::theme::test_property_set;
    use crate::util::Duration;
    use crate::widgets::TextArea;

    const HARNESS_PARAMS: TestHarnessParams = {
        let mut params = TestHarnessParams::DEFAULT;
        params.window_size = LogicalSize::new(150, 40);
        params.root_padding = 15;
        params
    };

    #[test]
    fn text_input_outline() {
        let text_area_tag = WidgetTag::named("text_area");
        let text_input = NewWidget::new(TextInput::from_text_area(
            TextArea::new_editable("TextInput contents")
                .with_style(StyleProperty::FontSize(14.0))
                .prepare()
                .with_tag(text_area_tag),
        ));
        let mut harness = TestHarness::create_with(test_property_set(), text_input, HARNESS_PARAMS);

        assert_render_snapshot!(harness, "text_input_outline");

        harness.edit_root_widget(|mut text_input| {
            let mut text_area = TextInput::text_mut(&mut text_input);
            TextArea::select_text(&mut text_area, "contents");
        });
        harness.focus_on(text_area_tag);

        assert_render_snapshot!(harness, "text_input_selection");

        harness.process_text_event(TextEvent::WindowFocusChange(false));

        assert_render_snapshot!(harness, "text_input_selection_unfocused");

        harness.process_text_event(TextEvent::WindowFocusChange(true));
        harness.advance_time(Duration::from_millis(500));

        assert_render_snapshot!(harness, "text_input_cursor_blink");
    }

    #[test]
    fn placeholder() {
        let text_input = NewWidget::new(
            TextInput::from_text_area(
                TextArea::new_editable("")
                    .with_style(StyleProperty::FontSize(14.0))
                    .prepare(),
            )
            .with_placeholder("HELLO WORLD"),
        );

        let mut harness = TestHarness::create_with(test_property_set(), text_input, HARNESS_PARAMS);

        assert_render_snapshot!(harness, "text_input_placeholder");
    }

    #[test]
    fn placeholder_is_exposed_on_text_area_accessibility_node() {
        let text_input = NewWidget::new(TextInput::new("").with_placeholder("Search"));

        let text_area_id = text_input.widget.area_pod().id();
        let placeholder_id = text_input.widget.placeholder.id();

        let mut harness = TestHarness::create_with(test_property_set(), text_input, HARNESS_PARAMS);

        let text_area_tag = harness.make_dyn_tag_for_widget(text_area_id);
        let placeholder_tag = harness.make_dyn_tag_for_widget(placeholder_id);

        let text_input_node = harness.access_node(harness.root_tag()).unwrap();
        assert_eq!(text_input_node.data().placeholder(), None);
        assert_eq!(text_input_node.child_ids().count(), 2);

        let placeholder_node = harness.access_node(placeholder_tag).unwrap();
        assert!(placeholder_node.is_hidden());

        let text_area_node = harness.access_node(text_area_tag).unwrap();
        assert_eq!(text_area_node.data().placeholder(), Some("Search"));

        harness.edit_root_widget(|mut text_input| {
            TextInput::set_placeholder(&mut text_input, "Filter");
        });
        let _ = harness.redraw();

        let text_area_node = harness.access_node(text_area_tag).unwrap();
        assert_eq!(text_area_node.data().placeholder(), Some("Filter"));
    }

    #[test]
    fn text_input_clips() {
        let text_input = NewWidget::new(
            TextInput::from_text_area(
                TextArea::new_editable("TextInput contents which should be clipped")
                    .with_style(StyleProperty::FontSize(14.0))
                    .with_word_wrap(false)
                    .prepare(),
            )
            .with_clip(true),
        );
        let mut harness = TestHarness::create_with(test_property_set(), text_input, HARNESS_PARAMS);

        assert_render_snapshot!(harness, "text_input_clip");
    }
}