Skip to main content

blit_gui_widget/
text_input.rs

1use blit::{KeyboardEvent, LogicalRect, Paint, Sides, StrSource, Widget};
2use blit_gui::{
3    Context,
4    color::Color,
5    rectangle::{self, Rectangle},
6    text::{self, FrameText, TextOptions, TextRequest, TextStyle, TextWrap, VerticalAlign},
7};
8pub use blit_widget::text_input::{Edit, Response as TextInputResponse, default_keymap};
9pub type TextInputState = blit_widget::text_input::State<f32>;
10
11blit::builder! {
12    /// single or multiline text editing with configurable keyboard bindings
13    ///
14    /// [`Self::keymap`] overrides [`default_keymap`] and receives [`Self::multiline`].
15    /// return `None` to let an event bubble.
16    /// the edited text lives in [`TextInputState`]
17    /// only the text, selection, and caret are painted so callers draw any frame behind it
18    pub struct TextInput<'a> {
19        new(state: &'a mut TextInputState),
20        multiline: bool = false,
21        keymap: fn(KeyboardEvent<'_>, bool) -> Option<Edit> = default_keymap,
22        style: TextStyle<'a> = TextStyle::new(),
23        padding: Sides<f32> = Sides::all(0.0),
24        #[into]
25        placeholder: StrSource<'a> = StrSource::default(),
26        placeholder_color: Color = Color::GRAY,
27        selection_background: Color = Color::rgba(64, 128, 255, 128),
28        cursor_background: Color = Color::BLACK,
29    }
30}
31
32impl<C> Widget<C> for TextInput<'_>
33where
34    C: Context + blit_widget::Context + blit_widget::Clipboard,
35    C: Paint<rectangle::FrameRectangle> + Paint<text::FrameText>,
36{
37    type Response = TextInputResponse;
38
39    fn build(self, mut ui: blit::Ui<'_, C>) -> Self::Response {
40        let Self {
41            state,
42            multiline,
43            keymap,
44            style,
45            padding,
46            placeholder,
47            placeholder_color,
48            selection_background,
49            cursor_background,
50        } = self;
51        let options = if multiline {
52            TextOptions::new().wrap(TextWrap::Word)
53        } else {
54            TextOptions::new().max_lines(1).vertical_align(VerticalAlign::Center)
55        };
56        let (response, text) = blit_widget::text_input::drive(
57            &mut ui,
58            state,
59            multiline,
60            keymap,
61            padding,
62            |cx, text| cx.text().text_run(text, style),
63            |cx, run, area, offset, position| {
64                let request = TextRequest::new(run).offset(offset).options(options);
65                cx.text().offset_at_position(area, &request, position)
66            },
67            |cx, run, area, offset, cursor, upstream| {
68                let request = TextRequest::new(run).offset(offset).options(options);
69                cx.text().caret_rect(area, &request, cursor, upstream)
70            },
71        );
72        let (display, color) = if state.value().is_empty() {
73            let placeholder = ui.scratch().str(placeholder);
74            if placeholder.is_empty() {
75                (text, style.color)
76            } else {
77                (ui.context_mut().text().text_run(&placeholder, style), placeholder_color)
78            }
79        } else {
80            (text, style.color)
81        };
82        let (cursor, anchor, upstream, offset) = (state.cursor, state.anchor, state.upstream, state.offset);
83        let pad = padding.size();
84        ui.measure(move |cx, constraints| {
85            let max_width = (multiline && constraints.max.width.is_finite())
86                .then_some((constraints.max.width - pad.width).max(0.0));
87            let mut fit = cx.text().measure(display, max_width, options);
88            fit.min.width = 0.0;
89            if multiline {
90                fit.min.height = 0.0;
91            }
92            blit::Fit::new(fit.min + pad, fit.natural + pad)
93        });
94        ui.paint(move |cx, area| {
95            let scratch = cx.scratch();
96            let context = cx.context_mut();
97            let area = area.inset(padding);
98            let request = TextRequest::new(text).offset(offset).options(options);
99            let (start, end) = (cursor.min(anchor), cursor.max(anchor));
100            if start != end {
101                let rects = context.text().range_rects(area, &request, start..end, scratch);
102                for rect in &*rects {
103                    if let Some(selection) = rect.intersection(area) {
104                        Rectangle::new()
105                            .background(selection_background)
106                            .paint(selection, context);
107                    }
108                }
109            }
110            if response.focused {
111                let caret = context.text().caret_rect(area, &request, cursor, upstream);
112                if let Some(caret) = LogicalRect::new(caret.x, caret.y, 1.0, caret.height).intersection(area) {
113                    Rectangle::new().background(cursor_background).paint(caret, context);
114                }
115            }
116            let colors = context.store_mut().slice_from(&[color]);
117            let text = FrameText::new(display, colors).offset(offset).options(options);
118            context.paint(area, &text);
119        });
120        response
121    }
122}