Skip to main content

freya_components/
input.rs

1use std::{
2    borrow::Cow,
3    cell::{
4        Ref,
5        RefCell,
6    },
7    rc::Rc,
8};
9
10use freya_core::prelude::*;
11use freya_edit::*;
12use torin::{
13    gaps::Gaps,
14    prelude::{
15        Alignment,
16        Area,
17        Content,
18        Direction,
19    },
20    size::Size,
21};
22
23use crate::{
24    cursor_blink::use_cursor_blink,
25    define_theme,
26    get_theme,
27    scrollviews::ScrollView,
28};
29
30define_theme! {
31    for = Input;
32    theme_field = theme_layout;
33
34    %[component]
35    pub InputLayout {
36        %[fields]
37        corner_radius: CornerRadius,
38        inner_margin: Gaps,
39    }
40}
41
42define_theme! {
43    for = Input;
44    theme_field = theme_colors;
45
46    %[component]
47    pub InputColors {
48        %[fields]
49        background: Color,
50        focus_background: Color,
51        border_fill: Color,
52        focus_border_fill: Color,
53        color: Color,
54        placeholder_color: Color,
55    }
56}
57
58#[derive(Clone, PartialEq)]
59pub enum InputStyleVariant {
60    Normal,
61    Filled,
62    Flat,
63}
64
65#[derive(Clone, PartialEq)]
66pub enum InputLayoutVariant {
67    Normal,
68    Compact,
69    Expanded,
70}
71
72#[derive(Default, Clone, PartialEq)]
73pub enum InputMode {
74    #[default]
75    Shown,
76    Hidden(char),
77}
78
79impl InputMode {
80    pub fn new_password() -> Self {
81        Self::Hidden('*')
82    }
83}
84
85#[derive(Debug, Default, PartialEq, Clone, Copy)]
86pub enum InputStatus {
87    /// Default state.
88    #[default]
89    Idle,
90    /// Pointer is hovering the input.
91    Hovering,
92}
93
94#[derive(Clone)]
95pub struct InputValidator {
96    valid: Rc<RefCell<bool>>,
97    text: Rc<RefCell<String>>,
98}
99
100impl InputValidator {
101    pub fn new(text: String) -> Self {
102        Self {
103            valid: Rc::new(RefCell::new(true)),
104            text: Rc::new(RefCell::new(text)),
105        }
106    }
107    pub fn text(&'_ self) -> Ref<'_, String> {
108        self.text.borrow()
109    }
110    pub fn set_valid(&self, is_valid: bool) {
111        *self.valid.borrow_mut() = is_valid;
112    }
113    pub fn is_valid(&self) -> bool {
114        *self.valid.borrow()
115    }
116}
117
118/// Small box to write some text.
119///
120/// ## **Normal**
121///
122/// ```rust
123/// # use freya::prelude::*;
124/// fn app() -> impl IntoElement {
125///     let value = use_state(String::new);
126///     Input::new(value).placeholder("Type here")
127/// }
128/// # use freya_testing::prelude::*;
129/// # launch_doc(|| {
130/// #   rect().center().expanded().child(app())
131/// # }, "./images/gallery_input.png").render();
132/// ```
133/// ## **Filled**
134///
135/// ```rust
136/// # use freya::prelude::*;
137/// fn app() -> impl IntoElement {
138///     let value = use_state(String::new);
139///     Input::new(value).placeholder("Type here").filled()
140/// }
141/// # use freya_testing::prelude::*;
142/// # launch_doc(|| {
143/// #   rect().center().expanded().child(app())
144/// # }, "./images/gallery_filled_input.png").render();
145/// ```
146/// ## **Flat**
147///
148/// ```rust
149/// # use freya::prelude::*;
150/// fn app() -> impl IntoElement {
151///     let value = use_state(String::new);
152///     Input::new(value).placeholder("Type here").flat()
153/// }
154/// # use freya_testing::prelude::*;
155/// # launch_doc(|| {
156/// #   rect().center().expanded().child(app())
157/// # }, "./images/gallery_flat_input.png").render();
158/// ```
159///
160/// # Preview
161/// ![Input Preview][input]
162/// ![Filled Input Preview][filled_input]
163/// ![Flat Input Preview][flat_input]
164#[cfg_attr(feature = "docs",
165    doc = embed_doc_image::embed_image!("input", "images/gallery_input.png"),
166    doc = embed_doc_image::embed_image!("filled_input", "images/gallery_filled_input.png"),
167    doc = embed_doc_image::embed_image!("flat_input", "images/gallery_flat_input.png"),
168)]
169#[derive(Clone, PartialEq)]
170pub struct Input {
171    pub(crate) theme_colors: Option<InputColorsThemePartial>,
172    pub(crate) theme_layout: Option<InputLayoutThemePartial>,
173    value: Writable<String>,
174    placeholder: Option<Cow<'static, str>>,
175    on_validate: Option<EventHandler<InputValidator>>,
176    on_submit: Option<EventHandler<String>>,
177    mode: InputMode,
178    auto_focus: bool,
179    width: Size,
180    enabled: bool,
181    key: DiffKey,
182    style_variant: InputStyleVariant,
183    layout_variant: InputLayoutVariant,
184    text_align: TextAlign,
185    a11y_id: Option<AccessibilityId>,
186    leading: Option<Element>,
187    trailing: Option<Element>,
188    on_pre_key_down: Callback<Event<KeyboardEventData>, bool>,
189}
190
191impl KeyExt for Input {
192    fn write_key(&mut self) -> &mut DiffKey {
193        &mut self.key
194    }
195}
196
197impl Input {
198    pub fn new(value: impl Into<Writable<String>>) -> Self {
199        Input {
200            theme_colors: None,
201            theme_layout: None,
202            value: value.into(),
203            placeholder: None,
204            on_validate: None,
205            on_submit: None,
206            mode: InputMode::default(),
207            auto_focus: false,
208            width: Size::px(150.),
209            enabled: true,
210            key: DiffKey::default(),
211            style_variant: InputStyleVariant::Normal,
212            layout_variant: InputLayoutVariant::Normal,
213            text_align: TextAlign::default(),
214            a11y_id: None,
215            leading: None,
216            trailing: None,
217            on_pre_key_down: Callback::new(|e: Event<KeyboardEventData>| match &e.key {
218                Key::Named(NamedKey::Enter)
219                | Key::Named(NamedKey::Escape)
220                | Key::Named(NamedKey::Shift) => true,
221                Key::Named(NamedKey::Tab) => false,
222                _ => {
223                    e.stop_propagation();
224                    e.prevent_default();
225                    true
226                }
227            }),
228        }
229    }
230
231    pub fn enabled(mut self, enabled: impl Into<bool>) -> Self {
232        self.enabled = enabled.into();
233        self
234    }
235
236    pub fn placeholder(mut self, placeholder: impl Into<Cow<'static, str>>) -> Self {
237        self.placeholder = Some(placeholder.into());
238        self
239    }
240
241    pub fn on_validate(mut self, on_validate: impl Into<EventHandler<InputValidator>>) -> Self {
242        self.on_validate = Some(on_validate.into());
243        self
244    }
245
246    pub fn on_submit(mut self, on_submit: impl Into<EventHandler<String>>) -> Self {
247        self.on_submit = Some(on_submit.into());
248        self
249    }
250
251    pub fn mode(mut self, mode: InputMode) -> Self {
252        self.mode = mode;
253        self
254    }
255
256    pub fn auto_focus(mut self, auto_focus: impl Into<bool>) -> Self {
257        self.auto_focus = auto_focus.into();
258        self
259    }
260
261    pub fn width(mut self, width: impl Into<Size>) -> Self {
262        self.width = width.into();
263        self
264    }
265
266    pub fn theme_colors(mut self, theme: InputColorsThemePartial) -> Self {
267        self.theme_colors = Some(theme);
268        self
269    }
270
271    pub fn theme_layout(mut self, theme: InputLayoutThemePartial) -> Self {
272        self.theme_layout = Some(theme);
273        self
274    }
275
276    pub fn text_align(mut self, text_align: impl Into<TextAlign>) -> Self {
277        self.text_align = text_align.into();
278        self
279    }
280
281    pub fn style_variant(mut self, style_variant: impl Into<InputStyleVariant>) -> Self {
282        self.style_variant = style_variant.into();
283        self
284    }
285
286    pub fn layout_variant(mut self, layout_variant: impl Into<InputLayoutVariant>) -> Self {
287        self.layout_variant = layout_variant.into();
288        self
289    }
290
291    /// Shortcut for [Self::style_variant] with [InputStyleVariant::Filled].
292    pub fn filled(self) -> Self {
293        self.style_variant(InputStyleVariant::Filled)
294    }
295
296    /// Shortcut for [Self::style_variant] with [InputStyleVariant::Flat].
297    pub fn flat(self) -> Self {
298        self.style_variant(InputStyleVariant::Flat)
299    }
300
301    /// Shortcut for [Self::layout_variant] with [InputLayoutVariant::Compact].
302    pub fn compact(self) -> Self {
303        self.layout_variant(InputLayoutVariant::Compact)
304    }
305
306    /// Shortcut for [Self::layout_variant] with [InputLayoutVariant::Expanded].
307    pub fn expanded(self) -> Self {
308        self.layout_variant(InputLayoutVariant::Expanded)
309    }
310
311    pub fn a11y_id(mut self, a11y_id: impl Into<AccessibilityId>) -> Self {
312        self.a11y_id = Some(a11y_id.into());
313        self
314    }
315
316    /// Optional element rendered before the text input.
317    pub fn leading(mut self, leading: impl Into<Element>) -> Self {
318        self.leading = Some(leading.into());
319        self
320    }
321
322    /// Optional element rendered after the text input.
323    pub fn trailing(mut self, trailing: impl Into<Element>) -> Self {
324        self.trailing = Some(trailing.into());
325        self
326    }
327
328    /// Sets a pre-handler called for each key event. Return `true` to let the input process it,
329    /// `false` to skip. The callback may call `stop_propagation()` / `prevent_default()` directly.
330    pub fn on_pre_key_down(
331        mut self,
332        on_pre_key_down: impl Into<Callback<Event<KeyboardEventData>, bool>>,
333    ) -> Self {
334        self.on_pre_key_down = on_pre_key_down.into();
335        self
336    }
337}
338
339impl CornerRadiusExt for Input {
340    fn with_corner_radius(self, corner_radius: f32) -> Self {
341        self.corner_radius(corner_radius)
342    }
343}
344
345impl Component for Input {
346    fn render(&self) -> impl IntoElement {
347        let a11y_id = use_hook(|| self.a11y_id.unwrap_or_else(AccessibilityId::new_unique));
348        let focus = use_focus(a11y_id);
349        let holder = use_state(ParagraphHolder::default);
350        let mut area = use_state(Area::default);
351        let mut status = use_state(InputStatus::default);
352        let allow_write_clipboard = !matches!(self.mode, InputMode::Hidden(_));
353        let mut editable = use_editable(
354            || self.value.read().to_string(),
355            move || EditableConfig::new().with_allow_write_clipboard(allow_write_clipboard),
356        );
357        let mut is_dragging = use_state(|| false);
358        let mut value = self.value.clone();
359
360        let theme_colors = match self.style_variant {
361            InputStyleVariant::Normal => {
362                get_theme!(&self.theme_colors, InputColorsThemePreference, "input")
363            }
364            InputStyleVariant::Filled => get_theme!(
365                &self.theme_colors,
366                InputColorsThemePreference,
367                "filled_input"
368            ),
369            InputStyleVariant::Flat => {
370                get_theme!(&self.theme_colors, InputColorsThemePreference, "flat_input")
371            }
372        };
373        let theme_layout = match self.layout_variant {
374            InputLayoutVariant::Normal => get_theme!(
375                &self.theme_layout,
376                InputLayoutThemePreference,
377                "input_layout"
378            ),
379            InputLayoutVariant::Compact => get_theme!(
380                &self.theme_layout,
381                InputLayoutThemePreference,
382                "compact_input_layout"
383            ),
384            InputLayoutVariant::Expanded => get_theme!(
385                &self.theme_layout,
386                InputLayoutThemePreference,
387                "expanded_input_layout"
388            ),
389        };
390
391        let (mut movement_timeout, cursor_color) =
392            use_cursor_blink(focus() != Focus::Not, theme_colors.color);
393
394        let enabled = use_reactive(&self.enabled);
395        use_drop(move || {
396            if status() == InputStatus::Hovering && enabled() {
397                Cursor::set(CursorIcon::default());
398            }
399        });
400
401        let display_placeholder = value.read().is_empty()
402            && self.placeholder.is_some()
403            && !editable.editor().read().has_preedit();
404        let on_validate = self.on_validate.clone();
405        let on_submit = self.on_submit.clone();
406
407        if *value.read() != editable.editor().read().committed_text() {
408            let mut editor = editable.editor_mut().write();
409            editor.clear_preedit();
410            editor.set(&value.read());
411            editor.editor_history().clear();
412            editor.clear_selection();
413        }
414
415        let on_ime_preedit = move |e: Event<ImePreeditEventData>| {
416            let mut editor = editable.editor_mut().write();
417            if e.data().text.is_empty() {
418                editor.clear_preedit();
419            } else {
420                editor.set_preedit(&e.data().text);
421            }
422        };
423
424        let on_pre_key_down = self.on_pre_key_down.clone();
425        let on_key_down = move |e: Event<KeyboardEventData>| {
426            let key = e.key.clone();
427            let modifiers = e.modifiers;
428
429            if !on_pre_key_down.call(e) {
430                return;
431            }
432
433            match &key {
434                // On submit
435                Key::Named(NamedKey::Enter) => {
436                    if let Some(on_submit) = &on_submit {
437                        let text = editable.editor().peek().committed_text();
438                        on_submit.call(text);
439                    }
440                }
441                // On unfocus
442                Key::Named(NamedKey::Escape) => {
443                    a11y_id.request_unfocus();
444                    Cursor::set(CursorIcon::default());
445                }
446                // On change
447                _ => {
448                    movement_timeout.reset();
449                    editable.process_event(EditableEvent::KeyDown {
450                        key: &key,
451                        modifiers,
452                    });
453                    let text = editable.editor().read().committed_text();
454
455                    let apply_change = match &on_validate {
456                        Some(on_validate) => {
457                            let mut editor = editable.editor_mut().write();
458                            let validator = InputValidator::new(text.clone());
459                            on_validate.call(validator.clone());
460                            if !validator.is_valid() {
461                                if let Some(selection) = editor.undo() {
462                                    *editor.selection_mut() = selection;
463                                }
464                                editor.editor_history().clear_redos();
465                            }
466                            validator.is_valid()
467                        }
468                        None => true,
469                    };
470
471                    if apply_change {
472                        *value.write() = text;
473                    }
474                }
475            }
476        };
477
478        let on_key_up = move |e: Event<KeyboardEventData>| {
479            e.stop_propagation();
480            editable.process_event(EditableEvent::KeyUp { key: &e.key });
481        };
482
483        let on_input_focus_press = move |e: Event<FocusPressEventData>| {
484            e.stop_propagation();
485            e.prevent_default();
486            if cfg!(target_os = "android") {
487                if a11y_id.is_focused() {
488                    // Require a second press to enabling dragging on Android
489                    is_dragging.set_if_modified(true);
490                }
491            } else {
492                is_dragging.set_if_modified(true);
493            }
494            movement_timeout.reset();
495            if !display_placeholder {
496                let area = area.read().to_f64();
497                let global_location = e.global_location().clamp(area.min(), area.max());
498                let location = (global_location - area.min()).to_point();
499                editable.process_event(EditableEvent::Down {
500                    location,
501                    editor_line: EditorLine::SingleParagraph,
502                    holder: &holder.read(),
503                });
504            }
505            a11y_id.request_focus();
506        };
507
508        let on_focus_press = move |e: Event<FocusPressEventData>| {
509            e.stop_propagation();
510            e.prevent_default();
511            if cfg!(target_os = "android") {
512                if a11y_id.is_focused() {
513                    // Require a second press to enabling dragging on Android
514                    is_dragging.set_if_modified(true);
515                }
516            } else {
517                is_dragging.set_if_modified(true);
518            }
519            movement_timeout.reset();
520            if !display_placeholder {
521                editable.process_event(EditableEvent::Down {
522                    location: e.element_location(),
523                    editor_line: EditorLine::SingleParagraph,
524                    holder: &holder.read(),
525                });
526            }
527            a11y_id.request_focus();
528        };
529
530        let on_global_pointer_move = move |e: Event<PointerEventData>| {
531            if a11y_id.is_focused() && *is_dragging.read() {
532                let mut location = e.global_location();
533                location.x -= area.read().min_x() as f64;
534                location.y -= area.read().min_y() as f64;
535                editable.process_event(EditableEvent::Move {
536                    location,
537                    editor_line: EditorLine::SingleParagraph,
538                    holder: &holder.read(),
539                });
540            }
541        };
542
543        let on_pointer_enter = move |_| {
544            *status.write() = InputStatus::Hovering;
545            if enabled() {
546                Cursor::set(CursorIcon::Text);
547            } else {
548                Cursor::set(CursorIcon::NotAllowed);
549            }
550        };
551
552        let on_pointer_leave = move |_| {
553            if status() == InputStatus::Hovering {
554                Cursor::set(CursorIcon::default());
555                *status.write() = InputStatus::default();
556            }
557        };
558
559        let on_global_pointer_press = move |_: Event<PointerEventData>| {
560            match *status.read() {
561                InputStatus::Idle if a11y_id.is_focused() => {
562                    editable.process_event(EditableEvent::Release);
563                }
564                InputStatus::Hovering => {
565                    editable.process_event(EditableEvent::Release);
566                }
567                _ => {}
568            };
569
570            if a11y_id.is_focused() {
571                if *is_dragging.read() {
572                    // The input is focused and dragging, but it just clicked so we assume the dragging can stop
573                    is_dragging.set(false);
574                } else {
575                    // The input is focused but not dragging, so the click means it was clicked outside, therefore we can unfocus this input
576                    a11y_id.request_unfocus();
577                }
578            }
579        };
580
581        let on_pointer_press = move |e: Event<PointerEventData>| {
582            e.stop_propagation();
583            e.prevent_default();
584            match *status.read() {
585                InputStatus::Idle if a11y_id.is_focused() => {
586                    editable.process_event(EditableEvent::Release);
587                }
588                InputStatus::Hovering => {
589                    editable.process_event(EditableEvent::Release);
590                }
591                _ => {}
592            };
593
594            if a11y_id.is_focused() {
595                is_dragging.set_if_modified(false);
596            }
597        };
598
599        let (background, cursor_index, text_selection) = if enabled() && focus() != Focus::Not {
600            (
601                theme_colors.focus_background,
602                Some(editable.editor().read().cursor_pos()),
603                editable
604                    .editor()
605                    .read()
606                    .get_visible_selection(EditorLine::SingleParagraph),
607            )
608        } else {
609            (theme_colors.background, None, None)
610        };
611
612        let border = if focus().is_focused() {
613            Border::new()
614                .fill(theme_colors.focus_border_fill)
615                .width(2.)
616                .alignment(BorderAlignment::Inner)
617        } else {
618            Border::new()
619                .fill(theme_colors.border_fill.mul_if(!self.enabled, 0.85))
620                .width(1.)
621                .alignment(BorderAlignment::Inner)
622        };
623
624        let color = if display_placeholder {
625            theme_colors.placeholder_color
626        } else {
627            theme_colors.color
628        };
629
630        let value = self.value.read();
631        let a11y_text: Cow<str> = match (self.mode.clone(), &self.placeholder) {
632            (_, Some(ph)) if display_placeholder => Cow::Borrowed(ph.as_ref()),
633            (InputMode::Hidden(ch), _) => Cow::Owned(ch.to_string().repeat(value.len())),
634            (InputMode::Shown, _) => Cow::Borrowed(value.as_ref()),
635        };
636
637        let a11_role = match self.mode {
638            InputMode::Hidden(_) => AccessibilityRole::PasswordInput,
639            _ => AccessibilityRole::TextInput,
640        };
641
642        rect()
643            .a11y_id(a11y_id)
644            .a11y_focusable(self.enabled)
645            .a11y_auto_focus(self.auto_focus)
646            .a11y_alt(a11y_text)
647            .a11y_role(a11_role)
648            .maybe(self.enabled, |el| {
649                el.on_key_up(on_key_up)
650                    .on_key_down(on_key_down)
651                    .on_focus_press(on_input_focus_press)
652                    .on_ime_preedit(on_ime_preedit)
653                    .on_pointer_press(on_pointer_press)
654                    .on_global_pointer_press(on_global_pointer_press)
655                    .on_global_pointer_move(on_global_pointer_move)
656            })
657            .on_pointer_enter(on_pointer_enter)
658            .on_pointer_leave(on_pointer_leave)
659            .width(self.width.clone())
660            .background(background.mul_if(!self.enabled, 0.85))
661            .border(border)
662            .corner_radius(theme_layout.corner_radius)
663            .content(Content::Flex)
664            .direction(Direction::Horizontal)
665            .cross_align(Alignment::center())
666            .maybe_child(
667                self.leading
668                    .clone()
669                    .map(|leading| rect().padding(Gaps::new(0., 0., 0., 8.)).child(leading)),
670            )
671            .child(
672                ScrollView::new()
673                    .width(Size::flex(1.))
674                    .height(Size::Inner)
675                    .direction(Direction::Horizontal)
676                    .show_scrollbar(false)
677                    .child(
678                        paragraph()
679                            .holder(holder.read().clone())
680                            .on_sized(move |e: Event<SizedEventData>| area.set(e.visible_area))
681                            .min_width(Size::func(move |context| {
682                                Some(context.parent - theme_layout.inner_margin.horizontal())
683                            }))
684                            .maybe(self.enabled, |el| el.on_focus_press(on_focus_press))
685                            .margin(theme_layout.inner_margin)
686                            .cursor_index(cursor_index)
687                            .cursor_color(cursor_color)
688                            .color(color)
689                            .text_align(self.text_align)
690                            .max_lines(1)
691                            .highlights(text_selection.map(|h| vec![h]))
692                            .maybe(display_placeholder, |el| {
693                                el.span(self.placeholder.as_ref().unwrap().to_string())
694                            })
695                            .maybe(!display_placeholder, |el| {
696                                let editor = editable.editor().read();
697                                if editor.has_preedit() {
698                                    let (b, p, a) = editor.preedit_text_segments();
699                                    let (b, p, a) = match self.mode.clone() {
700                                        InputMode::Hidden(ch) => {
701                                            let ch = ch.to_string();
702                                            (
703                                                ch.repeat(b.chars().count()),
704                                                ch.repeat(p.chars().count()),
705                                                ch.repeat(a.chars().count()),
706                                            )
707                                        }
708                                        InputMode::Shown => (b, p, a),
709                                    };
710                                    el.span(b)
711                                        .span(
712                                            Span::new(p).text_decoration(TextDecoration::Underline),
713                                        )
714                                        .span(a)
715                                } else {
716                                    let text = match self.mode.clone() {
717                                        InputMode::Hidden(ch) => {
718                                            ch.to_string().repeat(editor.rope().len_chars())
719                                        }
720                                        InputMode::Shown => editor.rope().to_string(),
721                                    };
722                                    el.span(text)
723                                }
724                            }),
725                    ),
726            )
727            .maybe_child(
728                self.trailing
729                    .clone()
730                    .map(|trailing| rect().padding(Gaps::new(0., 8., 0., 0.)).child(trailing)),
731            )
732    }
733
734    fn render_key(&self) -> DiffKey {
735        self.key.clone().or(self.default_key())
736    }
737}