iced_web/widget/
text_input.rs

1//! Display fields that can be filled with text.
2//!
3//! A [`TextInput`] has some local [`State`].
4use crate::{bumpalo, css, Bus, Css, Element, Length, Widget};
5
6pub use iced_style::text_input::{Style, StyleSheet};
7
8use std::{rc::Rc, u32};
9
10/// A field that can be filled with text.
11///
12/// # Example
13/// ```
14/// # use iced_web::{text_input, TextInput};
15/// #
16/// enum Message {
17///     TextInputChanged(String),
18/// }
19///
20/// let mut state = text_input::State::new();
21/// let value = "Some text";
22///
23/// let input = TextInput::new(
24///     &mut state,
25///     "This is the placeholder...",
26///     value,
27///     Message::TextInputChanged,
28/// );
29/// ```
30#[allow(missing_debug_implementations)]
31pub struct TextInput<'a, Message> {
32    _state: &'a mut State,
33    placeholder: String,
34    value: String,
35    is_secure: bool,
36    width: Length,
37    max_width: u32,
38    padding: u16,
39    size: Option<u16>,
40    on_change: Rc<Box<dyn Fn(String) -> Message>>,
41    on_submit: Option<Message>,
42    style_sheet: Box<dyn StyleSheet>,
43}
44
45impl<'a, Message> TextInput<'a, Message> {
46    /// Creates a new [`TextInput`].
47    ///
48    /// It expects:
49    /// - some [`State`]
50    /// - a placeholder
51    /// - the current value
52    /// - a function that produces a message when the [`TextInput`] changes
53    pub fn new<F>(
54        state: &'a mut State,
55        placeholder: &str,
56        value: &str,
57        on_change: F,
58    ) -> Self
59    where
60        F: 'static + Fn(String) -> Message,
61    {
62        Self {
63            _state: state,
64            placeholder: String::from(placeholder),
65            value: String::from(value),
66            is_secure: false,
67            width: Length::Fill,
68            max_width: u32::MAX,
69            padding: 0,
70            size: None,
71            on_change: Rc::new(Box::new(on_change)),
72            on_submit: None,
73            style_sheet: Default::default(),
74        }
75    }
76
77    /// Converts the [`TextInput`] into a secure password input.
78    pub fn password(mut self) -> Self {
79        self.is_secure = true;
80        self
81    }
82
83    /// Sets the width of the [`TextInput`].
84    pub fn width(mut self, width: Length) -> Self {
85        self.width = width;
86        self
87    }
88
89    /// Sets the maximum width of the [`TextInput`].
90    pub fn max_width(mut self, max_width: u32) -> Self {
91        self.max_width = max_width;
92        self
93    }
94
95    /// Sets the padding of the [`TextInput`].
96    pub fn padding(mut self, units: u16) -> Self {
97        self.padding = units;
98        self
99    }
100
101    /// Sets the text size of the [`TextInput`].
102    pub fn size(mut self, size: u16) -> Self {
103        self.size = Some(size);
104        self
105    }
106
107    /// Sets the message that should be produced when the [`TextInput`] is
108    /// focused and the enter key is pressed.
109    pub fn on_submit(mut self, message: Message) -> Self {
110        self.on_submit = Some(message);
111        self
112    }
113
114    /// Sets the style of the [`TextInput`].
115    pub fn style(mut self, style: impl Into<Box<dyn StyleSheet>>) -> Self {
116        self.style_sheet = style.into();
117        self
118    }
119}
120
121impl<'a, Message> Widget<Message> for TextInput<'a, Message>
122where
123    Message: 'static + Clone,
124{
125    fn node<'b>(
126        &self,
127        bump: &'b bumpalo::Bump,
128        bus: &Bus<Message>,
129        style_sheet: &mut Css<'b>,
130    ) -> dodrio::Node<'b> {
131        use dodrio::builder::*;
132        use wasm_bindgen::JsCast;
133
134        let class = {
135            use dodrio::bumpalo::collections::String;
136
137            let padding_class =
138                style_sheet.insert(bump, css::Rule::Padding(self.padding));
139
140            String::from_str_in(&padding_class, bump).into_bump_str()
141        };
142
143        let placeholder = {
144            use dodrio::bumpalo::collections::String;
145
146            String::from_str_in(&self.placeholder, bump).into_bump_str()
147        };
148
149        let value = {
150            use dodrio::bumpalo::collections::String;
151
152            String::from_str_in(&self.value, bump).into_bump_str()
153        };
154
155        let on_change = self.on_change.clone();
156        let on_submit = self.on_submit.clone();
157        let input_event_bus = bus.clone();
158        let submit_event_bus = bus.clone();
159        let style = self.style_sheet.active();
160
161        input(bump)
162            .attr("class", class)
163            .attr(
164                "style",
165                bumpalo::format!(
166                    in bump,
167                    "width: {}; max-width: {}; font-size: {}px; \
168                    background: {}; border-width: {}px; border-color: {}; \
169                    border-radius: {}px; color: {}",
170                    css::length(self.width),
171                    css::max_length(self.max_width),
172                    self.size.unwrap_or(20),
173                    css::background(style.background),
174                    style.border_width,
175                    css::color(style.border_color),
176                    style.border_radius,
177                    css::color(self.style_sheet.value_color())
178                )
179                .into_bump_str(),
180            )
181            .attr("placeholder", placeholder)
182            .attr("value", value)
183            .attr("type", if self.is_secure { "password" } else { "text" })
184            .on("input", move |_root, _vdom, event| {
185                let text_input = match event.target().and_then(|t| {
186                    t.dyn_into::<web_sys::HtmlInputElement>().ok()
187                }) {
188                    None => return,
189                    Some(text_input) => text_input,
190                };
191
192                input_event_bus.publish(on_change(text_input.value()));
193            })
194            .on("keypress", move |_root, _vdom, event| {
195                if let Some(on_submit) = on_submit.clone() {
196                    let event =
197                        event.unchecked_into::<web_sys::KeyboardEvent>();
198
199                    match event.key_code() {
200                        13 => {
201                            submit_event_bus.publish(on_submit);
202                        }
203                        _ => {}
204                    }
205                }
206            })
207            .finish()
208    }
209}
210
211impl<'a, Message> From<TextInput<'a, Message>> for Element<'a, Message>
212where
213    Message: 'static + Clone,
214{
215    fn from(text_input: TextInput<'a, Message>) -> Element<'a, Message> {
216        Element::new(text_input)
217    }
218}
219
220/// The state of a [`TextInput`].
221#[derive(Debug, Clone, Copy, Default)]
222pub struct State;
223
224impl State {
225    /// Creates a new [`State`], representing an unfocused [`TextInput`].
226    pub fn new() -> Self {
227        Self::default()
228    }
229
230    /// Creates a new [`State`], representing a focused [`TextInput`].
231    pub fn focused() -> Self {
232        // TODO
233        Self::default()
234    }
235}