1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
use dioxus::prelude::*;
use freya_elements::elements as dioxus_elements;
use freya_elements::events::keyboard::Key;
use freya_elements::events::{KeyboardData, MouseEvent};
use freya_hooks::use_platform;
use freya_hooks::{
    use_applied_theme, use_editable, use_focus, EditableConfig, EditableEvent, EditableMode,
    FontTheme, InputTheme, InputThemeWith, TextEditor,
};

use winit::window::CursorIcon;

/// Enum to declare is [`Input`] hidden.
#[derive(Default, Clone, PartialEq)]
pub enum InputMode {
    /// The input text is shown
    #[default]
    Shown,
    /// The input text is obfuscated with a character
    Hidden(char),
}

impl InputMode {
    pub fn new_password() -> Self {
        Self::Hidden('*')
    }
}

/// Indicates the current status of the Input.
#[derive(Debug, Default, PartialEq, Clone, Copy)]
pub enum InputStatus {
    /// Default state.
    #[default]
    Idle,
    /// Mouse is hovering the input.
    Hovering,
}

/// [`Input`] component properties.
#[derive(Props, Clone, PartialEq)]
pub struct InputProps {
    /// Theme override.
    pub theme: Option<InputThemeWith>,
    /// Current value of the Input
    pub value: String,
    /// Handler for the `onchange` event.
    pub onchange: EventHandler<String>,
    /// Display mode for Input. By default, input text is shown as it is provided.
    #[props(default = InputMode::Shown, into)]
    pub mode: InputMode,
}

/// `Input` component.
///
/// # Props
/// See [`InputProps`].
///
/// # Styling
/// Inherits the [`InputTheme`](freya_hooks::InputTheme) theme.
///
/// # Example
///
/// ```rust,no_run
/// # use freya::prelude::*;
/// fn app() -> Element {
///     let mut value = use_signal(String::new);
///
///     rsx!(
///         label {
///             "Value: {value}"
///         }
///         Input {
///             value: value.read().clone(),
///             onchange: move |e| {
///                  value.set(e)
///             }
///         }
///     )
/// }
/// ```
#[allow(non_snake_case)]
pub fn Input(
    InputProps {
        theme,
        value,
        onchange,
        mode,
    }: InputProps,
) -> Element {
    let platform = use_platform();
    let status = use_signal(InputStatus::default);
    let mut editable = use_editable(
        || EditableConfig::new(value.to_string()),
        EditableMode::MultipleLinesSingleEditor,
    );
    let theme = use_applied_theme!(&theme, input);
    let focus = use_focus();

    if &value != editable.editor().read().rope() {
        editable.editor_mut().write().set(&value);
    }

    let text = match mode {
        InputMode::Hidden(ch) => ch.to_string().repeat(value.len()),
        InputMode::Shown => value.clone(),
    };

    use_drop({
        to_owned![status, platform];
        move || {
            if *status.peek() == InputStatus::Hovering {
                platform.set_cursor(CursorIcon::default());
            }
        }
    });

    let onkeydown = {
        to_owned![editable, focus];
        move |e: Event<KeyboardData>| {
            if focus.is_focused() && e.data.key != Key::Enter {
                editable.process_event(&EditableEvent::KeyDown(e.data));
                onchange.call(editable.editor().peek().to_string());
            }
        }
    };

    let onmousedown = {
        to_owned![editable, focus];
        move |e: MouseEvent| {
            editable.process_event(&EditableEvent::MouseDown(e.data, 0));
            focus.focus();
        }
    };

    let onmouseover = {
        to_owned![editable];
        move |e: MouseEvent| {
            editable.process_event(&EditableEvent::MouseOver(e.data, 0));
        }
    };

    let onmouseenter = {
        to_owned![platform, status];
        move |_| {
            platform.set_cursor(CursorIcon::Text);
            *status.write() = InputStatus::Hovering;
        }
    };

    let onmouseleave = {
        to_owned![platform, status];
        move |_| {
            platform.set_cursor(CursorIcon::default());
            *status.write() = InputStatus::default();
        }
    };

    let onglobalclick = {
        to_owned![editable, focus];
        move |_| match *status.read() {
            InputStatus::Idle if focus.is_focused() => {
                focus.unfocus();
            }
            InputStatus::Hovering => {
                editable.process_event(&EditableEvent::Click);
            }
            _ => {}
        }
    };

    let focus_id = focus.attribute();
    let cursor_reference = editable.cursor_attr();
    let highlights = editable.highlights_attr(0);

    let (background, cursor_char) = if focus.is_focused() {
        (
            theme.hover_background,
            editable.editor().read().cursor_pos().to_string(),
        )
    } else {
        (theme.background, "none".to_string())
    };
    let InputTheme {
        border_fill,
        width,
        margin,
        font_theme: FontTheme { color },
        ..
    } = theme;

    rsx!(
        rect {
            width: "{width}",
            direction: "vertical",
            color: "{color}",
            background: "{background}",
            border: "1 solid {border_fill}",
            shadow: "0 3 15 0 rgb(0, 0, 0, 0.3)",
            corner_radius: "10",
            margin: "{margin}",
            cursor_reference,
            focus_id,
            role: "textInput",
            main_align: "center",
            paragraph {
                margin: "8 12",
                onkeydown,
                onglobalclick,
                onmouseenter,
                onmouseleave,
                onmousedown,
                onmouseover,
                width: "100%",
                cursor_id: "0",
                cursor_index: "{cursor_char}",
                cursor_mode: "editable",
                cursor_color: "{color}",
                max_lines: "1",
                highlights,
                text {
                    "{text}"
                }
            }
        }
    )
}