yew_styles/components/forms/
form_textarea.rs

1use super::error_message::get_error_message;
2use crate::styles::{get_palette, get_size, Palette, Size};
3use stylist::{css, StyleSource};
4use wasm_bindgen_test::*;
5use yew::prelude::*;
6use yew::{utils, App};
7
8/// # Form Textearea
9///
10/// ## Features required
11///
12/// forms
13///
14/// ## Example
15///
16/// ```rust
17/// use yew::prelude::*;
18/// use yew_styles::forms::form_textarea::FormTextArea;
19/// use yew_styles::styles::{Palette, Size};
20///
21/// pub struct FormTextAreaExample {
22///     pub link: ComponentLink<Self>,
23///     pub value: String,
24/// }
25///
26/// pub enum Msg {
27///     Input(String),
28/// }
29///
30/// impl Component for FormTextAreaExample {
31///     type Message = Msg;
32///     type Properties = ();
33///     fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self {
34///         FormTextAreaExample {
35///             link,
36///             value: "".to_string(),
37///         }
38///     }
39///     fn update(&mut self, msg: Self::Message) -> ShouldRender {
40///         match msg {
41///             Msg::Input(value) => {
42///                 self.value = value;
43///             }
44///         }
45///         true
46///     }
47///     fn change(&mut self, _props: Self::Properties) -> ShouldRender {
48///         false
49///     }
50///
51///     fn view(&self) -> Html {
52///         html!{
53///             <FormTextArea placeholder="write here"
54///                 textarea_size=Size::Small
55///                 textarea_style=Palette::Info
56///                 oninput_signal=form_page.link.callback(|e: InputData| Msg::Input(e.value))
57///             />
58///         }
59///     }
60/// ```
61pub struct FormTextArea {
62    link: ComponentLink<Self>,
63    props: Props,
64}
65
66/// Type of wraps. You can find more information [here](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea)
67#[derive(Clone, PartialEq)]
68pub enum WrapText {
69    Hard,
70    Soft,
71    Off,
72}
73
74#[derive(Clone, PartialEq, Properties)]
75pub struct Props {
76    /// General property to get the ref of the component
77    #[prop_or_default]
78    pub code_ref: NodeRef,
79    /// General property to add keys
80    #[prop_or_default]
81    pub key: String,
82    /// General property to add custom class styles
83    #[prop_or_default]
84    pub class_name: String,
85    /// General property to add custom id
86    #[prop_or_default]
87    pub id: String,
88    /// Content to be appear in the form control when the form control is empty
89    #[prop_or_default]
90    pub placeholder: String,
91    /// The input style according with the purpose. Default `Palette::Standard`
92    #[prop_or(Palette::Standard)]
93    pub textarea_style: Palette,
94    /// The size of the input. Default `Size::Medium`
95    #[prop_or(Size::Medium)]
96    pub textarea_size: Size,
97    /// Maximum length (number of characters) of value. Default `1000`
98    #[prop_or(1000)]
99    pub maxlength: u32,
100    /// Minimum length (number of characters) of value
101    #[prop_or_default]
102    pub minlength: u16,
103    /// Whether the form control is disabled. Default `false`
104    #[prop_or(false)]
105    pub disabled: bool,
106    /// The name of the textarea
107    #[prop_or_default]
108    pub name: String,
109    /// The value is not editable. Default `false`
110    #[prop_or(false)]
111    pub readonly: bool,
112    /// A value is required or must be check for the form to be submittable. Default `false`
113    #[prop_or(false)]
114    pub required: bool,
115    /// Automatically focus the form control when the page is loaded. Default `false`
116    #[prop_or(false)]
117    pub autofocus: bool,
118    /// Hint for form autofill feature. Default `false`
119    #[prop_or(false)]
120    pub autocomplete: bool,
121    /// The visible width of the text control
122    #[prop_or_default]
123    pub cols: u16,
124    /// The number of visible text lines for the control
125    #[prop_or_default]
126    pub rows: u16,
127    /// Specifies whether the "textarea"
128    /// is subject to spell checking by the underlying browser/OS. Default `false`
129    #[prop_or(false)]
130    pub spellcheck: bool,
131    /// Signal to emit the event input
132    #[prop_or(Callback::noop())]
133    pub oninput_signal: Callback<InputData>,
134    /// Signal to emit the event blur
135    #[prop_or(Callback::noop())]
136    pub onblur_signal: Callback<FocusEvent>,
137    /// Signal to emit the event keypress
138    #[prop_or(Callback::noop())]
139    pub onkeydown_signal: Callback<KeyboardEvent>,
140    /// Error state for validation. Default `false`
141    #[prop_or(false)]
142    pub error_state: bool,
143    /// Show error message when error_state is true
144    #[prop_or_default]
145    pub error_message: String,
146    /// Indicates how the control wraps text. Default `WrapText::Soft`
147    #[prop_or(WrapText::Soft)]
148    pub wrap: WrapText,
149    /// Set css styles directly in the component
150    #[prop_or(css!(""))]
151    pub styles: StyleSource<'static>,
152}
153
154#[derive(Debug)]
155pub enum Msg {
156    Input(InputData),
157    Blur(FocusEvent),
158    KeyPressed(KeyboardEvent),
159}
160
161impl Component for FormTextArea {
162    type Message = Msg;
163    type Properties = Props;
164
165    fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self {
166        Self { link, props }
167    }
168
169    fn update(&mut self, msg: Self::Message) -> ShouldRender {
170        match msg {
171            Msg::Input(input_data) => {
172                self.props.oninput_signal.emit(input_data);
173            }
174            Msg::Blur(focus_event) => {
175                self.props.onblur_signal.emit(focus_event);
176            }
177            Msg::KeyPressed(keyboard_event) => {
178                self.props.onkeydown_signal.emit(keyboard_event);
179            }
180        };
181
182        true
183    }
184
185    fn change(&mut self, props: Self::Properties) -> ShouldRender {
186        if self.props != props {
187            self.props = props;
188            true
189        } else {
190            false
191        }
192    }
193
194    fn view(&self) -> Html {
195        html! {
196            <>
197                <textarea
198                    id=self.props.id.clone()
199                    class=classes!("form-textarea",
200                        get_palette(self.props.textarea_style.clone()),
201                        get_size(self.props.textarea_size.clone()),
202                        self.props.class_name.clone(),
203                        self.props.styles.clone()
204                    )
205                    key=self.props.key.clone()
206                    ref=self.props.code_ref.clone()
207                    oninput=self.link.callback(Msg::Input)
208                    onblur=self.link.callback(Msg::Blur)
209                    onkeydown=self.link.callback(Msg::KeyPressed)
210                    name=self.props.name.clone()
211                    autocomplete=self.props.autocomplete.to_string()
212                    autofocus=self.props.autofocus
213                    required=self.props.required
214                    readonly=self.props.readonly
215                    disabled=self.props.disabled
216                    rows=self.props.rows.to_string()
217                    placeholder=self.props.placeholder.clone()
218                    cols=self.props.cols.to_string()
219                    spellcheck=self.props.spellcheck.to_string()
220                    minlength=self.props.minlength.to_string()
221                    maxlength=self.props.maxlength.to_string()
222                    warp=get_wrap(self.props.wrap.clone())
223                />
224                {get_error_message(self.props.error_state, self.props.error_message.clone())}
225            </>
226        }
227    }
228}
229
230fn get_wrap(wrap_text: WrapText) -> String {
231    match wrap_text {
232        WrapText::Hard => "hard".to_string(),
233        WrapText::Off => "soft".to_string(),
234        WrapText::Soft => "off".to_string(),
235    }
236}
237
238#[wasm_bindgen_test]
239fn should_create_form_textarea() {
240    let props = Props {
241        id: "form-input-id-test".to_string(),
242        key: "".to_string(),
243        code_ref: NodeRef::default(),
244        class_name: "form-input-class-test".to_string(),
245        styles: css!("background-color: #918d94;"),
246        oninput_signal: Callback::noop(),
247        onblur_signal: Callback::noop(),
248        onkeydown_signal: Callback::noop(),
249        error_message: "invalid input".to_string(),
250        error_state: false,
251        name: "input-test".to_string(),
252        textarea_style: Palette::Standard,
253        textarea_size: Size::Medium,
254        placeholder: "test input".to_string(),
255        required: false,
256        autocomplete: false,
257        autofocus: false,
258        maxlength: 100,
259        minlength: 0,
260        readonly: false,
261        disabled: false,
262        cols: 20,
263        rows: 10,
264        spellcheck: true,
265        wrap: WrapText::Hard,
266    };
267
268    let form_textarea: App<FormTextArea> = App::new();
269
270    form_textarea.mount_with_props(
271        utils::document().get_element_by_id("output").unwrap(),
272        props,
273    );
274
275    let form_textarea_element = utils::document()
276        .get_element_by_id("form-input-id-test")
277        .unwrap();
278
279    assert_eq!(form_textarea_element.tag_name(), "TEXTAREA");
280}