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) | Key::Named(NamedKey::Escape) => true,
219                Key::Named(NamedKey::Tab) => false,
220                _ => {
221                    e.stop_propagation();
222                    e.prevent_default();
223                    true
224                }
225            }),
226        }
227    }
228
229    pub fn enabled(mut self, enabled: impl Into<bool>) -> Self {
230        self.enabled = enabled.into();
231        self
232    }
233
234    pub fn placeholder(mut self, placeholder: impl Into<Cow<'static, str>>) -> Self {
235        self.placeholder = Some(placeholder.into());
236        self
237    }
238
239    pub fn on_validate(mut self, on_validate: impl Into<EventHandler<InputValidator>>) -> Self {
240        self.on_validate = Some(on_validate.into());
241        self
242    }
243
244    pub fn on_submit(mut self, on_submit: impl Into<EventHandler<String>>) -> Self {
245        self.on_submit = Some(on_submit.into());
246        self
247    }
248
249    pub fn mode(mut self, mode: InputMode) -> Self {
250        self.mode = mode;
251        self
252    }
253
254    pub fn auto_focus(mut self, auto_focus: impl Into<bool>) -> Self {
255        self.auto_focus = auto_focus.into();
256        self
257    }
258
259    pub fn width(mut self, width: impl Into<Size>) -> Self {
260        self.width = width.into();
261        self
262    }
263
264    pub fn theme_colors(mut self, theme: InputColorsThemePartial) -> Self {
265        self.theme_colors = Some(theme);
266        self
267    }
268
269    pub fn theme_layout(mut self, theme: InputLayoutThemePartial) -> Self {
270        self.theme_layout = Some(theme);
271        self
272    }
273
274    pub fn text_align(mut self, text_align: impl Into<TextAlign>) -> Self {
275        self.text_align = text_align.into();
276        self
277    }
278
279    pub fn style_variant(mut self, style_variant: impl Into<InputStyleVariant>) -> Self {
280        self.style_variant = style_variant.into();
281        self
282    }
283
284    pub fn layout_variant(mut self, layout_variant: impl Into<InputLayoutVariant>) -> Self {
285        self.layout_variant = layout_variant.into();
286        self
287    }
288
289    /// Shortcut for [Self::style_variant] with [InputStyleVariant::Filled].
290    pub fn filled(self) -> Self {
291        self.style_variant(InputStyleVariant::Filled)
292    }
293
294    /// Shortcut for [Self::style_variant] with [InputStyleVariant::Flat].
295    pub fn flat(self) -> Self {
296        self.style_variant(InputStyleVariant::Flat)
297    }
298
299    /// Shortcut for [Self::layout_variant] with [InputLayoutVariant::Compact].
300    pub fn compact(self) -> Self {
301        self.layout_variant(InputLayoutVariant::Compact)
302    }
303
304    /// Shortcut for [Self::layout_variant] with [InputLayoutVariant::Expanded].
305    pub fn expanded(self) -> Self {
306        self.layout_variant(InputLayoutVariant::Expanded)
307    }
308
309    pub fn a11y_id(mut self, a11y_id: impl Into<AccessibilityId>) -> Self {
310        self.a11y_id = Some(a11y_id.into());
311        self
312    }
313
314    /// Optional element rendered before the text input.
315    pub fn leading(mut self, leading: impl Into<Element>) -> Self {
316        self.leading = Some(leading.into());
317        self
318    }
319
320    /// Optional element rendered after the text input.
321    pub fn trailing(mut self, trailing: impl Into<Element>) -> Self {
322        self.trailing = Some(trailing.into());
323        self
324    }
325
326    /// Sets a pre-handler called for each key event. Return `true` to let the input process it,
327    /// `false` to skip. The callback may call `stop_propagation()` / `prevent_default()` directly.
328    pub fn on_pre_key_down(
329        mut self,
330        on_pre_key_down: impl Into<Callback<Event<KeyboardEventData>, bool>>,
331    ) -> Self {
332        self.on_pre_key_down = on_pre_key_down.into();
333        self
334    }
335}
336
337impl CornerRadiusExt for Input {
338    fn with_corner_radius(self, corner_radius: f32) -> Self {
339        self.corner_radius(corner_radius)
340    }
341}
342
343impl Component for Input {
344    fn render(&self) -> impl IntoElement {
345        let a11y_id = use_hook(|| self.a11y_id.unwrap_or_else(AccessibilityId::new_unique));
346        let focus = use_focus(a11y_id);
347        let holder = use_state(ParagraphHolder::default);
348        let mut area = use_state(Area::default);
349        let mut status = use_state(InputStatus::default);
350        let is_masked = matches!(self.mode, InputMode::Hidden(_));
351        let mut editable = use_editable(
352            || self.value.read().to_string(),
353            move || {
354                EditableConfig::new()
355                    .with_allow_write_clipboard(!is_masked)
356                    .with_select_all_on_double_click(is_masked)
357            },
358        );
359        let mut is_dragging = use_state(|| false);
360        let mut value = self.value.clone();
361
362        let theme_colors = match self.style_variant {
363            InputStyleVariant::Normal => {
364                get_theme!(&self.theme_colors, InputColorsThemePreference, "input")
365            }
366            InputStyleVariant::Filled => get_theme!(
367                &self.theme_colors,
368                InputColorsThemePreference,
369                "filled_input"
370            ),
371            InputStyleVariant::Flat => {
372                get_theme!(&self.theme_colors, InputColorsThemePreference, "flat_input")
373            }
374        };
375        let theme_layout = match self.layout_variant {
376            InputLayoutVariant::Normal => get_theme!(
377                &self.theme_layout,
378                InputLayoutThemePreference,
379                "input_layout"
380            ),
381            InputLayoutVariant::Compact => get_theme!(
382                &self.theme_layout,
383                InputLayoutThemePreference,
384                "compact_input_layout"
385            ),
386            InputLayoutVariant::Expanded => get_theme!(
387                &self.theme_layout,
388                InputLayoutThemePreference,
389                "expanded_input_layout"
390            ),
391        };
392
393        let (mut movement_timeout, cursor_color) =
394            use_cursor_blink(focus() != Focus::Not, theme_colors.color);
395
396        let enabled = use_reactive(&self.enabled);
397        use_drop(move || {
398            if status() == InputStatus::Hovering && enabled() {
399                Cursor::set(CursorIcon::default());
400            }
401        });
402
403        let display_placeholder = value.read().is_empty()
404            && self.placeholder.is_some()
405            && !editable.editor().read().has_preedit();
406        let on_validate = self.on_validate.clone();
407        let on_submit = self.on_submit.clone();
408
409        if *value.read() != editable.editor().read().committed_text() {
410            let mut editor = editable.editor_mut().write();
411            editor.clear_preedit();
412            editor.set(&value.read());
413            editor.editor_history().clear();
414            editor.clear_selection();
415        }
416
417        let on_ime_preedit = move |e: Event<ImePreeditEventData>| {
418            let mut editor = editable.editor_mut().write();
419            if e.data().text.is_empty() {
420                editor.clear_preedit();
421            } else {
422                editor.set_preedit(&e.data().text);
423            }
424        };
425
426        let on_pre_key_down = self.on_pre_key_down.clone();
427        let on_key_down = move |e: Event<KeyboardEventData>| {
428            let key = e.key.clone();
429            let modifiers = e.modifiers;
430
431            if !on_pre_key_down.call(e) {
432                return;
433            }
434
435            match &key {
436                // On submit
437                Key::Named(NamedKey::Enter) => {
438                    if let Some(on_submit) = &on_submit {
439                        let text = editable.editor().peek().committed_text();
440                        on_submit.call(text);
441                    }
442                }
443                // On unfocus
444                Key::Named(NamedKey::Escape) => {
445                    a11y_id.request_unfocus();
446                    Cursor::set(CursorIcon::default());
447                }
448                // On change
449                _ => {
450                    movement_timeout.reset();
451                    editable.process_event(EditableEvent::KeyDown {
452                        key: &key,
453                        modifiers,
454                    });
455                    let text = editable.editor().read().committed_text();
456
457                    let apply_change = match &on_validate {
458                        Some(on_validate) => {
459                            let mut editor = editable.editor_mut().write();
460                            let validator = InputValidator::new(text.clone());
461                            on_validate.call(validator.clone());
462                            if !validator.is_valid() {
463                                if let Some(selection) = editor.undo() {
464                                    *editor.selection_mut() = selection;
465                                }
466                                editor.editor_history().clear_redos();
467                            }
468                            validator.is_valid()
469                        }
470                        None => true,
471                    };
472
473                    if apply_change {
474                        *value.write() = text;
475                    }
476                }
477            }
478        };
479
480        let on_key_up = move |e: Event<KeyboardEventData>| {
481            e.stop_propagation();
482            editable.process_event(EditableEvent::KeyUp { key: &e.key });
483        };
484
485        let on_input_focus_press = move |e: Event<FocusPressEventData>| {
486            e.stop_propagation();
487            e.prevent_default();
488            if cfg!(target_os = "android") {
489                if a11y_id.is_focused() {
490                    // Require a second press to enabling dragging on Android
491                    is_dragging.set_if_modified(true);
492                }
493            } else {
494                is_dragging.set_if_modified(true);
495            }
496            movement_timeout.reset();
497            if !display_placeholder {
498                let area = area.read().to_f64();
499                let global_location = e.global_location().clamp(area.min(), area.max());
500                let location = (global_location - area.min()).to_point();
501                editable.process_event(EditableEvent::Down {
502                    location,
503                    editor_line: EditorLine::SingleParagraph,
504                    holder: &holder.read(),
505                });
506            }
507            a11y_id.request_focus();
508        };
509
510        let on_focus_press = move |e: Event<FocusPressEventData>| {
511            e.stop_propagation();
512            e.prevent_default();
513            if cfg!(target_os = "android") {
514                if a11y_id.is_focused() {
515                    // Require a second press to enabling dragging on Android
516                    is_dragging.set_if_modified(true);
517                }
518            } else {
519                is_dragging.set_if_modified(true);
520            }
521            movement_timeout.reset();
522            if !display_placeholder {
523                editable.process_event(EditableEvent::Down {
524                    location: e.element_location(),
525                    editor_line: EditorLine::SingleParagraph,
526                    holder: &holder.read(),
527                });
528            }
529            a11y_id.request_focus();
530        };
531
532        let on_global_pointer_move = move |e: Event<PointerEventData>| {
533            if a11y_id.is_focused() && *is_dragging.read() {
534                let mut location = e.global_location();
535                location.x -= area.read().min_x() as f64;
536                location.y -= area.read().min_y() as f64;
537                editable.process_event(EditableEvent::Move {
538                    location,
539                    editor_line: EditorLine::SingleParagraph,
540                    holder: &holder.read(),
541                });
542            }
543        };
544
545        let on_pointer_enter = move |_| {
546            *status.write() = InputStatus::Hovering;
547            if enabled() {
548                Cursor::set(CursorIcon::Text);
549            } else {
550                Cursor::set(CursorIcon::NotAllowed);
551            }
552        };
553
554        let on_pointer_leave = move |_| {
555            if status() == InputStatus::Hovering {
556                Cursor::set(CursorIcon::default());
557                *status.write() = InputStatus::default();
558            }
559        };
560
561        let on_global_pointer_press = move |_: Event<PointerEventData>| {
562            match *status.read() {
563                InputStatus::Idle if a11y_id.is_focused() => {
564                    editable.process_event(EditableEvent::Release);
565                }
566                InputStatus::Hovering => {
567                    editable.process_event(EditableEvent::Release);
568                }
569                _ => {}
570            };
571
572            if a11y_id.is_focused() {
573                if *is_dragging.read() {
574                    // The input is focused and dragging, but it just clicked so we assume the dragging can stop
575                    is_dragging.set(false);
576                } else {
577                    // The input is focused but not dragging, so the click means it was clicked outside, therefore we can unfocus this input
578                    a11y_id.request_unfocus();
579                }
580            }
581        };
582
583        let on_pointer_press = move |e: Event<PointerEventData>| {
584            e.stop_propagation();
585            e.prevent_default();
586            match *status.read() {
587                InputStatus::Idle if a11y_id.is_focused() => {
588                    editable.process_event(EditableEvent::Release);
589                }
590                InputStatus::Hovering => {
591                    editable.process_event(EditableEvent::Release);
592                }
593                _ => {}
594            };
595
596            if a11y_id.is_focused() {
597                is_dragging.set_if_modified(false);
598            }
599        };
600
601        let (background, cursor_index, text_selection) = if enabled() && focus() != Focus::Not {
602            (
603                theme_colors.focus_background,
604                Some(editable.editor().read().cursor_pos()),
605                editable
606                    .editor()
607                    .read()
608                    .get_visible_selection(EditorLine::SingleParagraph),
609            )
610        } else {
611            (theme_colors.background, None, None)
612        };
613
614        let border = if focus().is_focused() {
615            Border::new()
616                .fill(theme_colors.focus_border_fill)
617                .width(2.)
618                .alignment(BorderAlignment::Inner)
619        } else {
620            Border::new()
621                .fill(theme_colors.border_fill.mul_if(!self.enabled, 0.85))
622                .width(1.)
623                .alignment(BorderAlignment::Inner)
624        };
625
626        let color = if display_placeholder {
627            theme_colors.placeholder_color
628        } else {
629            theme_colors.color
630        };
631
632        let value = self.value.read();
633        let a11y_text: Cow<str> = match (self.mode.clone(), &self.placeholder) {
634            (_, Some(ph)) if display_placeholder => Cow::Borrowed(ph.as_ref()),
635            (InputMode::Hidden(ch), _) => Cow::Owned(ch.to_string().repeat(value.len())),
636            (InputMode::Shown, _) => Cow::Borrowed(value.as_ref()),
637        };
638
639        let a11_role = match self.mode {
640            InputMode::Hidden(_) => AccessibilityRole::PasswordInput,
641            _ => AccessibilityRole::TextInput,
642        };
643
644        rect()
645            .a11y_id(a11y_id)
646            .a11y_focusable(self.enabled)
647            .a11y_auto_focus(self.auto_focus)
648            .a11y_alt(a11y_text)
649            .a11y_role(a11_role)
650            .maybe(self.enabled, |el| {
651                el.on_key_up(on_key_up)
652                    .on_key_down(on_key_down)
653                    .on_focus_press(on_input_focus_press)
654                    .on_ime_preedit(on_ime_preedit)
655                    .on_pointer_press(on_pointer_press)
656                    .on_global_pointer_press(on_global_pointer_press)
657                    .on_global_pointer_move(on_global_pointer_move)
658            })
659            .on_pointer_enter(on_pointer_enter)
660            .on_pointer_leave(on_pointer_leave)
661            .width(self.width.clone())
662            .background(background.mul_if(!self.enabled, 0.85))
663            .border(border)
664            .corner_radius(theme_layout.corner_radius)
665            .content(Content::Flex)
666            .direction(Direction::Horizontal)
667            .cross_align(Alignment::center())
668            .maybe_child(
669                self.leading
670                    .clone()
671                    .map(|leading| rect().padding(Gaps::new(0., 0., 0., 8.)).child(leading)),
672            )
673            .child(
674                ScrollView::new()
675                    .width(Size::flex(1.))
676                    .height(Size::Inner)
677                    .direction(Direction::Horizontal)
678                    .show_scrollbar(false)
679                    .child(
680                        paragraph()
681                            .holder(holder.read().clone())
682                            .on_sized(move |e: Event<SizedEventData>| area.set(e.visible_area))
683                            .min_width(Size::func(move |context| {
684                                Some(context.parent - theme_layout.inner_margin.horizontal())
685                            }))
686                            .maybe(self.enabled, |el| el.on_focus_press(on_focus_press))
687                            .margin(theme_layout.inner_margin)
688                            .cursor_index(cursor_index)
689                            .cursor_color(cursor_color)
690                            .color(color)
691                            .text_align(self.text_align)
692                            .max_lines(1)
693                            .highlights(text_selection.map(|h| vec![h]))
694                            .maybe(display_placeholder, |el| {
695                                el.span(self.placeholder.as_ref().unwrap().to_string())
696                            })
697                            .maybe(!display_placeholder, |el| {
698                                let editor = editable.editor().read();
699                                if editor.has_preedit() {
700                                    let (b, p, a) = editor.preedit_text_segments();
701                                    let (b, p, a) = match self.mode.clone() {
702                                        InputMode::Hidden(ch) => {
703                                            let ch = ch.to_string();
704                                            (
705                                                ch.repeat(b.chars().count()),
706                                                ch.repeat(p.chars().count()),
707                                                ch.repeat(a.chars().count()),
708                                            )
709                                        }
710                                        InputMode::Shown => (b, p, a),
711                                    };
712                                    el.span(b)
713                                        .span(
714                                            Span::new(p).text_decoration(TextDecoration::Underline),
715                                        )
716                                        .span(a)
717                                } else {
718                                    let text = match self.mode.clone() {
719                                        InputMode::Hidden(ch) => {
720                                            ch.to_string().repeat(editor.rope().len_chars())
721                                        }
722                                        InputMode::Shown => editor.rope().to_string(),
723                                    };
724                                    el.span(text)
725                                }
726                            }),
727                    ),
728            )
729            .maybe_child(
730                self.trailing
731                    .clone()
732                    .map(|trailing| rect().padding(Gaps::new(0., 8., 0., 0.)).child(trailing)),
733            )
734    }
735
736    fn render_key(&self) -> DiffKey {
737        self.key.clone().or(self.default_key())
738    }
739}